Thanks to visit codestin.com
Credit goes to clang.llvm.org

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 && UT->getOriginalDecl()
3584 ->getMostRecentDecl()
3585 ->hasAttr<TransparentUnionAttr>()) {
3586 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
3587 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
3588 Expr = ILE->getInit(0);
3589 }
3590
3591 bool Result;
3592 return (!Expr->isValueDependent() &&
3594 !Result);
3595}
3596
3598 const Expr *ArgExpr,
3599 SourceLocation CallSiteLoc) {
3600 if (CheckNonNullExpr(S, ArgExpr))
3601 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
3602 S.PDiag(diag::warn_null_arg)
3603 << ArgExpr->getSourceRange());
3604}
3605
3606/// Determine whether the given type has a non-null nullability annotation.
3608 if (auto nullability = type->getNullability())
3609 return *nullability == NullabilityKind::NonNull;
3610
3611 return false;
3612}
3613
3615 const NamedDecl *FDecl,
3616 const FunctionProtoType *Proto,
3618 SourceLocation CallSiteLoc) {
3619 assert((FDecl || Proto) && "Need a function declaration or prototype");
3620
3621 // Already checked by constant evaluator.
3623 return;
3624 // Check the attributes attached to the method/function itself.
3625 llvm::SmallBitVector NonNullArgs;
3626 if (FDecl) {
3627 // Handle the nonnull attribute on the function/method declaration itself.
3628 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3629 if (!NonNull->args_size()) {
3630 // Easy case: all pointer arguments are nonnull.
3631 for (const auto *Arg : Args)
3632 if (S.isValidPointerAttrType(Arg->getType()))
3633 CheckNonNullArgument(S, Arg, CallSiteLoc);
3634 return;
3635 }
3636
3637 for (const ParamIdx &Idx : NonNull->args()) {
3638 unsigned IdxAST = Idx.getASTIndex();
3639 if (IdxAST >= Args.size())
3640 continue;
3641 if (NonNullArgs.empty())
3642 NonNullArgs.resize(Args.size());
3643 NonNullArgs.set(IdxAST);
3644 }
3645 }
3646 }
3647
3648 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
3649 // Handle the nonnull attribute on the parameters of the
3650 // function/method.
3652 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
3653 parms = FD->parameters();
3654 else
3655 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
3656
3657 unsigned ParamIndex = 0;
3658 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3659 I != E; ++I, ++ParamIndex) {
3660 const ParmVarDecl *PVD = *I;
3661 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
3662 if (NonNullArgs.empty())
3663 NonNullArgs.resize(Args.size());
3664
3665 NonNullArgs.set(ParamIndex);
3666 }
3667 }
3668 } else {
3669 // If we have a non-function, non-method declaration but no
3670 // function prototype, try to dig out the function prototype.
3671 if (!Proto) {
3672 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
3673 QualType type = VD->getType().getNonReferenceType();
3674 if (auto pointerType = type->getAs<PointerType>())
3675 type = pointerType->getPointeeType();
3676 else if (auto blockType = type->getAs<BlockPointerType>())
3677 type = blockType->getPointeeType();
3678 // FIXME: data member pointers?
3679
3680 // Dig out the function prototype, if there is one.
3681 Proto = type->getAs<FunctionProtoType>();
3682 }
3683 }
3684
3685 // Fill in non-null argument information from the nullability
3686 // information on the parameter types (if we have them).
3687 if (Proto) {
3688 unsigned Index = 0;
3689 for (auto paramType : Proto->getParamTypes()) {
3690 if (isNonNullType(paramType)) {
3691 if (NonNullArgs.empty())
3692 NonNullArgs.resize(Args.size());
3693
3694 NonNullArgs.set(Index);
3695 }
3696
3697 ++Index;
3698 }
3699 }
3700 }
3701
3702 // Check for non-null arguments.
3703 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
3704 ArgIndex != ArgIndexEnd; ++ArgIndex) {
3705 if (NonNullArgs[ArgIndex])
3706 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
3707 }
3708}
3709
3710void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
3711 StringRef ParamName, QualType ArgTy,
3712 QualType ParamTy) {
3713
3714 // If a function accepts a pointer or reference type
3715 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
3716 return;
3717
3718 // If the parameter is a pointer type, get the pointee type for the
3719 // argument too. If the parameter is a reference type, don't try to get
3720 // the pointee type for the argument.
3721 if (ParamTy->isPointerType())
3722 ArgTy = ArgTy->getPointeeType();
3723
3724 // Remove reference or pointer
3725 ParamTy = ParamTy->getPointeeType();
3726
3727 // Find expected alignment, and the actual alignment of the passed object.
3728 // getTypeAlignInChars requires complete types
3729 if (ArgTy.isNull() || ParamTy->isDependentType() ||
3730 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
3731 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
3732 return;
3733
3734 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
3735 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
3736
3737 // If the argument is less aligned than the parameter, there is a
3738 // potential alignment issue.
3739 if (ArgAlign < ParamAlign)
3740 Diag(Loc, diag::warn_param_mismatched_alignment)
3741 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
3742 << ParamName << (FDecl != nullptr) << FDecl;
3743}
3744
3745void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
3746 const Expr *ThisArg,
3748 if (!FD || Args.empty())
3749 return;
3750 auto GetArgAt = [&](int Idx) -> const Expr * {
3751 if (Idx == LifetimeCaptureByAttr::Global ||
3752 Idx == LifetimeCaptureByAttr::Unknown)
3753 return nullptr;
3754 if (IsMemberFunction && Idx == 0)
3755 return ThisArg;
3756 return Args[Idx - IsMemberFunction];
3757 };
3758 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
3759 unsigned ArgIdx) {
3760 if (!Attr)
3761 return;
3762
3763 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
3764 for (int CapturingParamIdx : Attr->params()) {
3765 // lifetime_capture_by(this) case is handled in the lifetimebound expr
3766 // initialization codepath.
3767 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
3769 continue;
3770 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
3771 CapturingEntity CE{Capturing};
3772 // Ensure that 'Captured' outlives the 'Capturing' entity.
3773 checkCaptureByLifetime(*this, CE, Captured);
3774 }
3775 };
3776 for (unsigned I = 0; I < FD->getNumParams(); ++I)
3777 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(),
3778 I + IsMemberFunction);
3779 // Check when the implicit object param is captured.
3780 if (IsMemberFunction) {
3781 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
3782 if (!TSI)
3783 return;
3785 for (TypeLoc TL = TSI->getTypeLoc();
3786 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
3787 TL = ATL.getModifiedLoc())
3788 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
3789 }
3790}
3791
3793 const Expr *ThisArg, ArrayRef<const Expr *> Args,
3794 bool IsMemberFunction, SourceLocation Loc,
3795 SourceRange Range, VariadicCallType CallType) {
3796 // FIXME: We should check as much as we can in the template definition.
3797 if (CurContext->isDependentContext())
3798 return;
3799
3800 // Printf and scanf checking.
3801 llvm::SmallBitVector CheckedVarArgs;
3802 if (FDecl) {
3803 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
3804 // Only create vector if there are format attributes.
3805 CheckedVarArgs.resize(Args.size());
3806 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
3807 CheckedVarArgs);
3808 }
3809
3810 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
3811 CheckedVarArgs.resize(Args.size());
3812 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
3813 CheckedVarArgs);
3814 }
3815 }
3816
3817 // Refuse POD arguments that weren't caught by the format string
3818 // checks above.
3819 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
3820 if (CallType != VariadicCallType::DoesNotApply &&
3821 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
3822 unsigned NumParams = Proto ? Proto->getNumParams()
3823 : isa_and_nonnull<FunctionDecl>(FDecl)
3824 ? cast<FunctionDecl>(FDecl)->getNumParams()
3825 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
3826 ? cast<ObjCMethodDecl>(FDecl)->param_size()
3827 : 0;
3828
3829 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
3830 // Args[ArgIdx] can be null in malformed code.
3831 if (const Expr *Arg = Args[ArgIdx]) {
3832 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
3833 checkVariadicArgument(Arg, CallType);
3834 }
3835 }
3836 }
3837 if (FD)
3838 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
3839 if (FDecl || Proto) {
3840 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
3841
3842 // Type safety checking.
3843 if (FDecl) {
3844 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
3845 CheckArgumentWithTypeTag(I, Args, Loc);
3846 }
3847 }
3848
3849 // Check that passed arguments match the alignment of original arguments.
3850 // Try to get the missing prototype from the declaration.
3851 if (!Proto && FDecl) {
3852 const auto *FT = FDecl->getFunctionType();
3853 if (isa_and_nonnull<FunctionProtoType>(FT))
3854 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
3855 }
3856 if (Proto) {
3857 // For variadic functions, we may have more args than parameters.
3858 // For some K&R functions, we may have less args than parameters.
3859 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
3860 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
3861 bool IsScalableArg = false;
3862 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
3863 // Args[ArgIdx] can be null in malformed code.
3864 if (const Expr *Arg = Args[ArgIdx]) {
3865 if (Arg->containsErrors())
3866 continue;
3867
3868 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
3869 FDecl->hasLinkage() &&
3870 FDecl->getFormalLinkage() != Linkage::Internal &&
3872 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
3873
3874 QualType ParamTy = Proto->getParamType(ArgIdx);
3875 if (ParamTy->isSizelessVectorType())
3876 IsScalableArg = true;
3877 QualType ArgTy = Arg->getType();
3878 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
3879 ArgTy, ParamTy);
3880 }
3881 }
3882
3883 // If the callee has an AArch64 SME attribute to indicate that it is an
3884 // __arm_streaming function, then the caller requires SME to be available.
3887 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
3888 llvm::StringMap<bool> CallerFeatureMap;
3889 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
3890 if (!CallerFeatureMap.contains("sme"))
3891 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3892 } else if (!Context.getTargetInfo().hasFeature("sme")) {
3893 Diag(Loc, diag::err_sme_call_in_non_sme_target);
3894 }
3895 }
3896
3897 // If the call requires a streaming-mode change and has scalable vector
3898 // arguments or return values, then warn the user that the streaming and
3899 // non-streaming vector lengths may be different.
3900 // When both streaming and non-streaming vector lengths are defined and
3901 // mismatched, produce an error.
3902 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
3903 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
3904 (IsScalableArg || IsScalableRet)) {
3905 bool IsCalleeStreaming =
3907 bool IsCalleeStreamingCompatible =
3908 ExtInfo.AArch64SMEAttributes &
3910 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
3911 if (!IsCalleeStreamingCompatible &&
3912 (CallerFnType == SemaARM::ArmStreamingCompatible ||
3913 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
3914 const LangOptions &LO = getLangOpts();
3915 unsigned VL = LO.VScaleMin * 128;
3916 unsigned SVL = LO.VScaleStreamingMin * 128;
3917 bool IsVLMismatch = VL && SVL && VL != SVL;
3918
3919 auto EmitDiag = [&](bool IsArg) {
3920 if (IsVLMismatch) {
3921 if (CallerFnType == SemaARM::ArmStreamingCompatible)
3922 // Emit warning for streaming-compatible callers
3923 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
3924 << IsArg << IsCalleeStreaming << SVL << VL;
3925 else
3926 // Emit error otherwise
3927 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
3928 << IsArg << SVL << VL;
3929 } else
3930 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
3931 << IsArg;
3932 };
3933
3934 if (IsScalableArg)
3935 EmitDiag(true);
3936 if (IsScalableRet)
3937 EmitDiag(false);
3938 }
3939 }
3940
3941 FunctionType::ArmStateValue CalleeArmZAState =
3943 FunctionType::ArmStateValue CalleeArmZT0State =
3945 if (CalleeArmZAState != FunctionType::ARM_None ||
3946 CalleeArmZT0State != FunctionType::ARM_None) {
3947 bool CallerHasZAState = false;
3948 bool CallerHasZT0State = false;
3949 if (CallerFD) {
3950 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
3951 if (Attr && Attr->isNewZA())
3952 CallerHasZAState = true;
3953 if (Attr && Attr->isNewZT0())
3954 CallerHasZT0State = true;
3955 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
3956 CallerHasZAState |=
3958 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3960 CallerHasZT0State |=
3962 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
3964 }
3965 }
3966
3967 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
3968 Diag(Loc, diag::err_sme_za_call_no_za_state);
3969
3970 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
3971 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
3972
3973 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
3974 CalleeArmZT0State != FunctionType::ARM_None) {
3975 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
3976 Diag(Loc, diag::note_sme_use_preserves_za);
3977 }
3978 }
3979 }
3980
3981 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
3982 auto *AA = FDecl->getAttr<AllocAlignAttr>();
3983 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
3984 if (!Arg->isValueDependent()) {
3985 Expr::EvalResult Align;
3986 if (Arg->EvaluateAsInt(Align, Context)) {
3987 const llvm::APSInt &I = Align.Val.getInt();
3988 if (!I.isPowerOf2())
3989 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
3990 << Arg->getSourceRange();
3991
3992 if (I > Sema::MaximumAlignment)
3993 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
3994 << Arg->getSourceRange() << Sema::MaximumAlignment;
3995 }
3996 }
3997 }
3998
3999 if (FD)
4000 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4001}
4002
4003void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4004 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4005 DiagnoseUseOfDecl(Decl, Loc);
4006 }
4007}
4008
4009void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4011 const FunctionProtoType *Proto,
4012 SourceLocation Loc) {
4013 VariadicCallType CallType = Proto->isVariadic()
4016
4017 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4018 CheckArgAlignment(
4019 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4020 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4021
4022 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4023 Loc, SourceRange(), CallType);
4024}
4025
4027 const FunctionProtoType *Proto) {
4028 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4029 isa<CXXMethodDecl>(FDecl);
4030 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4031 IsMemberOperatorCall;
4032 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4033 TheCall->getCallee());
4034 Expr** Args = TheCall->getArgs();
4035 unsigned NumArgs = TheCall->getNumArgs();
4036
4037 Expr *ImplicitThis = nullptr;
4038 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4039 // If this is a call to a member operator, hide the first
4040 // argument from checkCall.
4041 // FIXME: Our choice of AST representation here is less than ideal.
4042 ImplicitThis = Args[0];
4043 ++Args;
4044 --NumArgs;
4045 } else if (IsMemberFunction && !FDecl->isStatic() &&
4047 ImplicitThis =
4048 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4049
4050 if (ImplicitThis) {
4051 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4052 // used.
4053 QualType ThisType = ImplicitThis->getType();
4054 if (!ThisType->isPointerType()) {
4055 assert(!ThisType->isReferenceType());
4056 ThisType = Context.getPointerType(ThisType);
4057 }
4058
4059 QualType ThisTypeFromDecl = Context.getPointerType(
4060 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4061
4062 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4063 ThisTypeFromDecl);
4064 }
4065
4066 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4067 IsMemberFunction, TheCall->getRParenLoc(),
4068 TheCall->getCallee()->getSourceRange(), CallType);
4069
4070 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4071 // None of the checks below are needed for functions that don't have
4072 // simple names (e.g., C++ conversion functions).
4073 if (!FnInfo)
4074 return false;
4075
4076 // Enforce TCB except for builtin calls, which are always allowed.
4077 if (FDecl->getBuiltinID() == 0)
4078 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4079
4080 CheckAbsoluteValueFunction(TheCall, FDecl);
4081 CheckMaxUnsignedZero(TheCall, FDecl);
4082 CheckInfNaNFunction(TheCall, FDecl);
4083
4084 if (getLangOpts().ObjC)
4085 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4086
4087 unsigned CMId = FDecl->getMemoryFunctionKind();
4088
4089 // Handle memory setting and copying functions.
4090 switch (CMId) {
4091 case 0:
4092 return false;
4093 case Builtin::BIstrlcpy: // fallthrough
4094 case Builtin::BIstrlcat:
4095 CheckStrlcpycatArguments(TheCall, FnInfo);
4096 break;
4097 case Builtin::BIstrncat:
4098 CheckStrncatArguments(TheCall, FnInfo);
4099 break;
4100 case Builtin::BIfree:
4101 CheckFreeArguments(TheCall);
4102 break;
4103 default:
4104 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4105 }
4106
4107 return false;
4108}
4109
4110bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4111 const FunctionProtoType *Proto) {
4112 QualType Ty;
4113 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4114 Ty = V->getType().getNonReferenceType();
4115 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4116 Ty = F->getType().getNonReferenceType();
4117 else
4118 return false;
4119
4120 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4121 !Ty->isFunctionProtoType())
4122 return false;
4123
4124 VariadicCallType CallType;
4125 if (!Proto || !Proto->isVariadic()) {
4127 } else if (Ty->isBlockPointerType()) {
4128 CallType = VariadicCallType::Block;
4129 } else { // Ty->isFunctionPointerType()
4130 CallType = VariadicCallType::Function;
4131 }
4132
4133 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4134 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4135 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4136 TheCall->getCallee()->getSourceRange(), CallType);
4137
4138 return false;
4139}
4140
4141bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4142 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4143 TheCall->getCallee());
4144 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4145 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4146 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4147 TheCall->getCallee()->getSourceRange(), CallType);
4148
4149 return false;
4150}
4151
4152static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4153 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4154 return false;
4155
4156 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4157 switch (Op) {
4158 case AtomicExpr::AO__c11_atomic_init:
4159 case AtomicExpr::AO__opencl_atomic_init:
4160 llvm_unreachable("There is no ordering argument for an init");
4161
4162 case AtomicExpr::AO__c11_atomic_load:
4163 case AtomicExpr::AO__opencl_atomic_load:
4164 case AtomicExpr::AO__hip_atomic_load:
4165 case AtomicExpr::AO__atomic_load_n:
4166 case AtomicExpr::AO__atomic_load:
4167 case AtomicExpr::AO__scoped_atomic_load_n:
4168 case AtomicExpr::AO__scoped_atomic_load:
4169 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4170 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4171
4172 case AtomicExpr::AO__c11_atomic_store:
4173 case AtomicExpr::AO__opencl_atomic_store:
4174 case AtomicExpr::AO__hip_atomic_store:
4175 case AtomicExpr::AO__atomic_store:
4176 case AtomicExpr::AO__atomic_store_n:
4177 case AtomicExpr::AO__scoped_atomic_store:
4178 case AtomicExpr::AO__scoped_atomic_store_n:
4179 case AtomicExpr::AO__atomic_clear:
4180 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4181 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4182 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4183
4184 default:
4185 return true;
4186 }
4187}
4188
4189ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4191 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4192 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4193 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4194 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4195 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4196 Op);
4197}
4198
4200 SourceLocation RParenLoc, MultiExprArg Args,
4202 AtomicArgumentOrder ArgOrder) {
4203 // All the non-OpenCL operations take one of the following forms.
4204 // The OpenCL operations take the __c11 forms with one extra argument for
4205 // synchronization scope.
4206 enum {
4207 // C __c11_atomic_init(A *, C)
4208 Init,
4209
4210 // C __c11_atomic_load(A *, int)
4211 Load,
4212
4213 // void __atomic_load(A *, CP, int)
4214 LoadCopy,
4215
4216 // void __atomic_store(A *, CP, int)
4217 Copy,
4218
4219 // C __c11_atomic_add(A *, M, int)
4220 Arithmetic,
4221
4222 // C __atomic_exchange_n(A *, CP, int)
4223 Xchg,
4224
4225 // void __atomic_exchange(A *, C *, CP, int)
4226 GNUXchg,
4227
4228 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4229 C11CmpXchg,
4230
4231 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4232 GNUCmpXchg,
4233
4234 // bool __atomic_test_and_set(A *, int)
4235 TestAndSetByte,
4236
4237 // void __atomic_clear(A *, int)
4238 ClearByte,
4239 } Form = Init;
4240
4241 const unsigned NumForm = ClearByte + 1;
4242 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4243 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4244 // where:
4245 // C is an appropriate type,
4246 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4247 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4248 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4249 // the int parameters are for orderings.
4250
4251 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4252 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4253 "need to update code for modified forms");
4254 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4255 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4256 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4257 "need to update code for modified C11 atomics");
4258 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4259 Op <= AtomicExpr::AO__opencl_atomic_store;
4260 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4261 Op <= AtomicExpr::AO__hip_atomic_store;
4262 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4263 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4264 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4265 Op <= AtomicExpr::AO__c11_atomic_store) ||
4266 IsOpenCL;
4267 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4268 Op == AtomicExpr::AO__atomic_store_n ||
4269 Op == AtomicExpr::AO__atomic_exchange_n ||
4270 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4271 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4272 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4273 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4274 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4275 // Bit mask for extra allowed value types other than integers for atomic
4276 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4277 // allow floating point.
4278 enum ArithOpExtraValueType {
4279 AOEVT_None = 0,
4280 AOEVT_Pointer = 1,
4281 AOEVT_FP = 2,
4282 };
4283 unsigned ArithAllows = AOEVT_None;
4284
4285 switch (Op) {
4286 case AtomicExpr::AO__c11_atomic_init:
4287 case AtomicExpr::AO__opencl_atomic_init:
4288 Form = Init;
4289 break;
4290
4291 case AtomicExpr::AO__c11_atomic_load:
4292 case AtomicExpr::AO__opencl_atomic_load:
4293 case AtomicExpr::AO__hip_atomic_load:
4294 case AtomicExpr::AO__atomic_load_n:
4295 case AtomicExpr::AO__scoped_atomic_load_n:
4296 Form = Load;
4297 break;
4298
4299 case AtomicExpr::AO__atomic_load:
4300 case AtomicExpr::AO__scoped_atomic_load:
4301 Form = LoadCopy;
4302 break;
4303
4304 case AtomicExpr::AO__c11_atomic_store:
4305 case AtomicExpr::AO__opencl_atomic_store:
4306 case AtomicExpr::AO__hip_atomic_store:
4307 case AtomicExpr::AO__atomic_store:
4308 case AtomicExpr::AO__atomic_store_n:
4309 case AtomicExpr::AO__scoped_atomic_store:
4310 case AtomicExpr::AO__scoped_atomic_store_n:
4311 Form = Copy;
4312 break;
4313 case AtomicExpr::AO__atomic_fetch_add:
4314 case AtomicExpr::AO__atomic_fetch_sub:
4315 case AtomicExpr::AO__atomic_add_fetch:
4316 case AtomicExpr::AO__atomic_sub_fetch:
4317 case AtomicExpr::AO__scoped_atomic_fetch_add:
4318 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4319 case AtomicExpr::AO__scoped_atomic_add_fetch:
4320 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4321 case AtomicExpr::AO__c11_atomic_fetch_add:
4322 case AtomicExpr::AO__c11_atomic_fetch_sub:
4323 case AtomicExpr::AO__opencl_atomic_fetch_add:
4324 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4325 case AtomicExpr::AO__hip_atomic_fetch_add:
4326 case AtomicExpr::AO__hip_atomic_fetch_sub:
4327 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4328 Form = Arithmetic;
4329 break;
4330 case AtomicExpr::AO__atomic_fetch_max:
4331 case AtomicExpr::AO__atomic_fetch_min:
4332 case AtomicExpr::AO__atomic_max_fetch:
4333 case AtomicExpr::AO__atomic_min_fetch:
4334 case AtomicExpr::AO__scoped_atomic_fetch_max:
4335 case AtomicExpr::AO__scoped_atomic_fetch_min:
4336 case AtomicExpr::AO__scoped_atomic_max_fetch:
4337 case AtomicExpr::AO__scoped_atomic_min_fetch:
4338 case AtomicExpr::AO__c11_atomic_fetch_max:
4339 case AtomicExpr::AO__c11_atomic_fetch_min:
4340 case AtomicExpr::AO__opencl_atomic_fetch_max:
4341 case AtomicExpr::AO__opencl_atomic_fetch_min:
4342 case AtomicExpr::AO__hip_atomic_fetch_max:
4343 case AtomicExpr::AO__hip_atomic_fetch_min:
4344 ArithAllows = AOEVT_FP;
4345 Form = Arithmetic;
4346 break;
4347 case AtomicExpr::AO__c11_atomic_fetch_and:
4348 case AtomicExpr::AO__c11_atomic_fetch_or:
4349 case AtomicExpr::AO__c11_atomic_fetch_xor:
4350 case AtomicExpr::AO__hip_atomic_fetch_and:
4351 case AtomicExpr::AO__hip_atomic_fetch_or:
4352 case AtomicExpr::AO__hip_atomic_fetch_xor:
4353 case AtomicExpr::AO__c11_atomic_fetch_nand:
4354 case AtomicExpr::AO__opencl_atomic_fetch_and:
4355 case AtomicExpr::AO__opencl_atomic_fetch_or:
4356 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4357 case AtomicExpr::AO__atomic_fetch_and:
4358 case AtomicExpr::AO__atomic_fetch_or:
4359 case AtomicExpr::AO__atomic_fetch_xor:
4360 case AtomicExpr::AO__atomic_fetch_nand:
4361 case AtomicExpr::AO__atomic_and_fetch:
4362 case AtomicExpr::AO__atomic_or_fetch:
4363 case AtomicExpr::AO__atomic_xor_fetch:
4364 case AtomicExpr::AO__atomic_nand_fetch:
4365 case AtomicExpr::AO__scoped_atomic_fetch_and:
4366 case AtomicExpr::AO__scoped_atomic_fetch_or:
4367 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4368 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4369 case AtomicExpr::AO__scoped_atomic_and_fetch:
4370 case AtomicExpr::AO__scoped_atomic_or_fetch:
4371 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4372 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4373 Form = Arithmetic;
4374 break;
4375
4376 case AtomicExpr::AO__c11_atomic_exchange:
4377 case AtomicExpr::AO__hip_atomic_exchange:
4378 case AtomicExpr::AO__opencl_atomic_exchange:
4379 case AtomicExpr::AO__atomic_exchange_n:
4380 case AtomicExpr::AO__scoped_atomic_exchange_n:
4381 Form = Xchg;
4382 break;
4383
4384 case AtomicExpr::AO__atomic_exchange:
4385 case AtomicExpr::AO__scoped_atomic_exchange:
4386 Form = GNUXchg;
4387 break;
4388
4389 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4390 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4391 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4392 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4393 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4394 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4395 Form = C11CmpXchg;
4396 break;
4397
4398 case AtomicExpr::AO__atomic_compare_exchange:
4399 case AtomicExpr::AO__atomic_compare_exchange_n:
4400 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4401 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4402 Form = GNUCmpXchg;
4403 break;
4404
4405 case AtomicExpr::AO__atomic_test_and_set:
4406 Form = TestAndSetByte;
4407 break;
4408
4409 case AtomicExpr::AO__atomic_clear:
4410 Form = ClearByte;
4411 break;
4412 }
4413
4414 unsigned AdjustedNumArgs = NumArgs[Form];
4415 if ((IsOpenCL || IsHIP || IsScoped) &&
4416 Op != AtomicExpr::AO__opencl_atomic_init)
4417 ++AdjustedNumArgs;
4418 // Check we have the right number of arguments.
4419 if (Args.size() < AdjustedNumArgs) {
4420 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4421 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4422 << /*is non object*/ 0 << ExprRange;
4423 return ExprError();
4424 } else if (Args.size() > AdjustedNumArgs) {
4425 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4426 diag::err_typecheck_call_too_many_args)
4427 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4428 << /*is non object*/ 0 << ExprRange;
4429 return ExprError();
4430 }
4431
4432 // Inspect the first argument of the atomic operation.
4433 Expr *Ptr = Args[0];
4435 if (ConvertedPtr.isInvalid())
4436 return ExprError();
4437
4438 Ptr = ConvertedPtr.get();
4439 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4440 if (!pointerType) {
4441 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4442 << Ptr->getType() << 0 << Ptr->getSourceRange();
4443 return ExprError();
4444 }
4445
4446 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4447 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4448 QualType ValType = AtomTy; // 'C'
4449 if (IsC11) {
4450 if (!AtomTy->isAtomicType()) {
4451 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4452 << Ptr->getType() << Ptr->getSourceRange();
4453 return ExprError();
4454 }
4455 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4457 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4458 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4459 << Ptr->getSourceRange();
4460 return ExprError();
4461 }
4462 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4463 } else if (Form != Load && Form != LoadCopy) {
4464 if (ValType.isConstQualified()) {
4465 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4466 << Ptr->getType() << Ptr->getSourceRange();
4467 return ExprError();
4468 }
4469 }
4470
4471 if (Form != TestAndSetByte && Form != ClearByte) {
4472 // Pointer to object of size zero is not allowed.
4473 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
4474 diag::err_incomplete_type))
4475 return ExprError();
4476
4477 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
4478 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4479 << Ptr->getType() << 1 << Ptr->getSourceRange();
4480 return ExprError();
4481 }
4482 } else {
4483 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4484 // non-const pointer type, including void* and pointers to incomplete
4485 // structs, but only access the first byte.
4486 AtomTy = Context.CharTy;
4487 AtomTy = AtomTy.withCVRQualifiers(
4488 pointerType->getPointeeType().getCVRQualifiers());
4489 QualType PointerQT = Context.getPointerType(AtomTy);
4490 pointerType = PointerQT->getAs<PointerType>();
4491 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
4492 ValType = AtomTy;
4493 }
4494
4495 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4496 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4497 Diag(ExprRange.getBegin(),
4498 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4499 << 0 << Ptr->getType() << Ptr->getSourceRange();
4500 return ExprError();
4501 }
4502
4503 // For an arithmetic operation, the implied arithmetic must be well-formed.
4504 if (Form == Arithmetic) {
4505 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4506 // trivial type errors.
4507 auto IsAllowedValueType = [&](QualType ValType,
4508 unsigned AllowedType) -> bool {
4509 if (ValType->isIntegerType())
4510 return true;
4511 if (ValType->isPointerType())
4512 return AllowedType & AOEVT_Pointer;
4513 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4514 return false;
4515 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4516 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
4517 &Context.getTargetInfo().getLongDoubleFormat() ==
4518 &llvm::APFloat::x87DoubleExtended())
4519 return false;
4520 return true;
4521 };
4522 if (!IsAllowedValueType(ValType, ArithAllows)) {
4523 auto DID = ArithAllows & AOEVT_FP
4524 ? (ArithAllows & AOEVT_Pointer
4525 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4526 : diag::err_atomic_op_needs_atomic_int_or_fp)
4527 : diag::err_atomic_op_needs_atomic_int;
4528 Diag(ExprRange.getBegin(), DID)
4529 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4530 return ExprError();
4531 }
4532 if (IsC11 && ValType->isPointerType() &&
4534 diag::err_incomplete_type)) {
4535 return ExprError();
4536 }
4537 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4538 // For __atomic_*_n operations, the value type must be a scalar integral or
4539 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4540 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4541 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4542 return ExprError();
4543 }
4544
4545 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4546 !AtomTy->isScalarType()) {
4547 // For GNU atomics, require a trivially-copyable type. This is not part of
4548 // the GNU atomics specification but we enforce it for consistency with
4549 // other atomics which generally all require a trivially-copyable type. This
4550 // is because atomics just copy bits.
4551 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4552 << Ptr->getType() << Ptr->getSourceRange();
4553 return ExprError();
4554 }
4555
4556 switch (ValType.getObjCLifetime()) {
4559 // okay
4560 break;
4561
4565 // FIXME: Can this happen? By this point, ValType should be known
4566 // to be trivially copyable.
4567 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4568 << ValType << Ptr->getSourceRange();
4569 return ExprError();
4570 }
4571
4572 // All atomic operations have an overload which takes a pointer to a volatile
4573 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4574 // into the result or the other operands. Similarly atomic_load takes a
4575 // pointer to a const 'A'.
4576 ValType.removeLocalVolatile();
4577 ValType.removeLocalConst();
4578 QualType ResultType = ValType;
4579 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4580 Form == ClearByte)
4581 ResultType = Context.VoidTy;
4582 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4583 ResultType = Context.BoolTy;
4584
4585 // The type of a parameter passed 'by value'. In the GNU atomics, such
4586 // arguments are actually passed as pointers.
4587 QualType ByValType = ValType; // 'CP'
4588 bool IsPassedByAddress = false;
4589 if (!IsC11 && !IsHIP && !IsN) {
4590 ByValType = Ptr->getType();
4591 IsPassedByAddress = true;
4592 }
4593
4594 SmallVector<Expr *, 5> APIOrderedArgs;
4595 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4596 APIOrderedArgs.push_back(Args[0]);
4597 switch (Form) {
4598 case Init:
4599 case Load:
4600 APIOrderedArgs.push_back(Args[1]); // Val1/Order
4601 break;
4602 case LoadCopy:
4603 case Copy:
4604 case Arithmetic:
4605 case Xchg:
4606 APIOrderedArgs.push_back(Args[2]); // Val1
4607 APIOrderedArgs.push_back(Args[1]); // Order
4608 break;
4609 case GNUXchg:
4610 APIOrderedArgs.push_back(Args[2]); // Val1
4611 APIOrderedArgs.push_back(Args[3]); // Val2
4612 APIOrderedArgs.push_back(Args[1]); // Order
4613 break;
4614 case C11CmpXchg:
4615 APIOrderedArgs.push_back(Args[2]); // Val1
4616 APIOrderedArgs.push_back(Args[4]); // Val2
4617 APIOrderedArgs.push_back(Args[1]); // Order
4618 APIOrderedArgs.push_back(Args[3]); // OrderFail
4619 break;
4620 case GNUCmpXchg:
4621 APIOrderedArgs.push_back(Args[2]); // Val1
4622 APIOrderedArgs.push_back(Args[4]); // Val2
4623 APIOrderedArgs.push_back(Args[5]); // Weak
4624 APIOrderedArgs.push_back(Args[1]); // Order
4625 APIOrderedArgs.push_back(Args[3]); // OrderFail
4626 break;
4627 case TestAndSetByte:
4628 case ClearByte:
4629 APIOrderedArgs.push_back(Args[1]); // Order
4630 break;
4631 }
4632 } else
4633 APIOrderedArgs.append(Args.begin(), Args.end());
4634
4635 // The first argument's non-CV pointer type is used to deduce the type of
4636 // subsequent arguments, except for:
4637 // - weak flag (always converted to bool)
4638 // - memory order (always converted to int)
4639 // - scope (always converted to int)
4640 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4641 QualType Ty;
4642 if (i < NumVals[Form] + 1) {
4643 switch (i) {
4644 case 0:
4645 // The first argument is always a pointer. It has a fixed type.
4646 // It is always dereferenced, a nullptr is undefined.
4647 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4648 // Nothing else to do: we already know all we want about this pointer.
4649 continue;
4650 case 1:
4651 // The second argument is the non-atomic operand. For arithmetic, this
4652 // is always passed by value, and for a compare_exchange it is always
4653 // passed by address. For the rest, GNU uses by-address and C11 uses
4654 // by-value.
4655 assert(Form != Load);
4656 if (Form == Arithmetic && ValType->isPointerType())
4657 Ty = Context.getPointerDiffType();
4658 else if (Form == Init || Form == Arithmetic)
4659 Ty = ValType;
4660 else if (Form == Copy || Form == Xchg) {
4661 if (IsPassedByAddress) {
4662 // The value pointer is always dereferenced, a nullptr is undefined.
4663 CheckNonNullArgument(*this, APIOrderedArgs[i],
4664 ExprRange.getBegin());
4665 }
4666 Ty = ByValType;
4667 } else {
4668 Expr *ValArg = APIOrderedArgs[i];
4669 // The value pointer is always dereferenced, a nullptr is undefined.
4670 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
4672 // Keep address space of non-atomic pointer type.
4673 if (const PointerType *PtrTy =
4674 ValArg->getType()->getAs<PointerType>()) {
4675 AS = PtrTy->getPointeeType().getAddressSpace();
4676 }
4677 Ty = Context.getPointerType(
4678 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4679 }
4680 break;
4681 case 2:
4682 // The third argument to compare_exchange / GNU exchange is the desired
4683 // value, either by-value (for the C11 and *_n variant) or as a pointer.
4684 if (IsPassedByAddress)
4685 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
4686 Ty = ByValType;
4687 break;
4688 case 3:
4689 // The fourth argument to GNU compare_exchange is a 'weak' flag.
4690 Ty = Context.BoolTy;
4691 break;
4692 }
4693 } else {
4694 // The order(s) and scope are always converted to int.
4695 Ty = Context.IntTy;
4696 }
4697
4698 InitializedEntity Entity =
4700 ExprResult Arg = APIOrderedArgs[i];
4701 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4702 if (Arg.isInvalid())
4703 return true;
4704 APIOrderedArgs[i] = Arg.get();
4705 }
4706
4707 // Permute the arguments into a 'consistent' order.
4708 SmallVector<Expr*, 5> SubExprs;
4709 SubExprs.push_back(Ptr);
4710 switch (Form) {
4711 case Init:
4712 // Note, AtomicExpr::getVal1() has a special case for this atomic.
4713 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4714 break;
4715 case Load:
4716 case TestAndSetByte:
4717 case ClearByte:
4718 SubExprs.push_back(APIOrderedArgs[1]); // Order
4719 break;
4720 case LoadCopy:
4721 case Copy:
4722 case Arithmetic:
4723 case Xchg:
4724 SubExprs.push_back(APIOrderedArgs[2]); // Order
4725 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4726 break;
4727 case GNUXchg:
4728 // Note, AtomicExpr::getVal2() has a special case for this atomic.
4729 SubExprs.push_back(APIOrderedArgs[3]); // Order
4730 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4731 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4732 break;
4733 case C11CmpXchg:
4734 SubExprs.push_back(APIOrderedArgs[3]); // Order
4735 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4736 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
4737 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4738 break;
4739 case GNUCmpXchg:
4740 SubExprs.push_back(APIOrderedArgs[4]); // Order
4741 SubExprs.push_back(APIOrderedArgs[1]); // Val1
4742 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
4743 SubExprs.push_back(APIOrderedArgs[2]); // Val2
4744 SubExprs.push_back(APIOrderedArgs[3]); // Weak
4745 break;
4746 }
4747
4748 // If the memory orders are constants, check they are valid.
4749 if (SubExprs.size() >= 2 && Form != Init) {
4750 std::optional<llvm::APSInt> Success =
4751 SubExprs[1]->getIntegerConstantExpr(Context);
4752 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
4753 Diag(SubExprs[1]->getBeginLoc(),
4754 diag::warn_atomic_op_has_invalid_memory_order)
4755 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
4756 << SubExprs[1]->getSourceRange();
4757 }
4758 if (SubExprs.size() >= 5) {
4759 if (std::optional<llvm::APSInt> Failure =
4760 SubExprs[3]->getIntegerConstantExpr(Context)) {
4761 if (!llvm::is_contained(
4762 {llvm::AtomicOrderingCABI::relaxed,
4763 llvm::AtomicOrderingCABI::consume,
4764 llvm::AtomicOrderingCABI::acquire,
4765 llvm::AtomicOrderingCABI::seq_cst},
4766 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
4767 Diag(SubExprs[3]->getBeginLoc(),
4768 diag::warn_atomic_op_has_invalid_memory_order)
4769 << /*failure=*/2 << SubExprs[3]->getSourceRange();
4770 }
4771 }
4772 }
4773 }
4774
4775 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4776 auto *Scope = Args[Args.size() - 1];
4777 if (std::optional<llvm::APSInt> Result =
4778 Scope->getIntegerConstantExpr(Context)) {
4779 if (!ScopeModel->isValid(Result->getZExtValue()))
4780 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
4781 << Scope->getSourceRange();
4782 }
4783 SubExprs.push_back(Scope);
4784 }
4785
4786 AtomicExpr *AE = new (Context)
4787 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
4788
4789 if ((Op == AtomicExpr::AO__c11_atomic_load ||
4790 Op == AtomicExpr::AO__c11_atomic_store ||
4791 Op == AtomicExpr::AO__opencl_atomic_load ||
4792 Op == AtomicExpr::AO__hip_atomic_load ||
4793 Op == AtomicExpr::AO__opencl_atomic_store ||
4794 Op == AtomicExpr::AO__hip_atomic_store) &&
4795 Context.AtomicUsesUnsupportedLibcall(AE))
4796 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4797 << ((Op == AtomicExpr::AO__c11_atomic_load ||
4798 Op == AtomicExpr::AO__opencl_atomic_load ||
4799 Op == AtomicExpr::AO__hip_atomic_load)
4800 ? 0
4801 : 1);
4802
4803 if (ValType->isBitIntType()) {
4804 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
4805 return ExprError();
4806 }
4807
4808 return AE;
4809}
4810
4811/// checkBuiltinArgument - Given a call to a builtin function, perform
4812/// normal type-checking on the given argument, updating the call in
4813/// place. This is useful when a builtin function requires custom
4814/// type-checking for some of its arguments but not necessarily all of
4815/// them.
4816///
4817/// Returns true on error.
4818static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4819 FunctionDecl *Fn = E->getDirectCallee();
4820 assert(Fn && "builtin call without direct callee!");
4821
4822 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4823 InitializedEntity Entity =
4825
4826 ExprResult Arg = E->getArg(ArgIndex);
4827 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4828 if (Arg.isInvalid())
4829 return true;
4830
4831 E->setArg(ArgIndex, Arg.get());
4832 return false;
4833}
4834
4835ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
4836 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4837 Expr *Callee = TheCall->getCallee();
4838 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4839 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4840
4841 // Ensure that we have at least one argument to do type inference from.
4842 if (TheCall->getNumArgs() < 1) {
4843 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4844 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
4845 << Callee->getSourceRange();
4846 return ExprError();
4847 }
4848
4849 // Inspect the first argument of the atomic builtin. This should always be
4850 // a pointer type, whose element is an integral scalar or pointer type.
4851 // Because it is a pointer type, we don't have to worry about any implicit
4852 // casts here.
4853 // FIXME: We don't allow floating point scalars as input.
4854 Expr *FirstArg = TheCall->getArg(0);
4855 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4856 if (FirstArgResult.isInvalid())
4857 return ExprError();
4858 FirstArg = FirstArgResult.get();
4859 TheCall->setArg(0, FirstArg);
4860
4861 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4862 if (!pointerType) {
4863 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4864 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4865 return ExprError();
4866 }
4867
4868 QualType ValType = pointerType->getPointeeType();
4869 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4870 !ValType->isBlockPointerType()) {
4871 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4872 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
4873 return ExprError();
4874 }
4875 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
4876 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4877 Diag(FirstArg->getBeginLoc(),
4878 diag::err_atomic_op_needs_non_address_discriminated_pointer)
4879 << 1 << ValType << FirstArg->getSourceRange();
4880 return ExprError();
4881 }
4882
4883 if (ValType.isConstQualified()) {
4884 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4885 << FirstArg->getType() << FirstArg->getSourceRange();
4886 return ExprError();
4887 }
4888
4889 switch (ValType.getObjCLifetime()) {
4892 // okay
4893 break;
4894
4898 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4899 << ValType << FirstArg->getSourceRange();
4900 return ExprError();
4901 }
4902
4903 // Strip any qualifiers off ValType.
4904 ValType = ValType.getUnqualifiedType();
4905
4906 // The majority of builtins return a value, but a few have special return
4907 // types, so allow them to override appropriately below.
4908 QualType ResultType = ValType;
4909
4910 // We need to figure out which concrete builtin this maps onto. For example,
4911 // __sync_fetch_and_add with a 2 byte object turns into
4912 // __sync_fetch_and_add_2.
4913#define BUILTIN_ROW(x) \
4914 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4915 Builtin::BI##x##_8, Builtin::BI##x##_16 }
4916
4917 static const unsigned BuiltinIndices[][5] = {
4918 BUILTIN_ROW(__sync_fetch_and_add),
4919 BUILTIN_ROW(__sync_fetch_and_sub),
4920 BUILTIN_ROW(__sync_fetch_and_or),
4921 BUILTIN_ROW(__sync_fetch_and_and),
4922 BUILTIN_ROW(__sync_fetch_and_xor),
4923 BUILTIN_ROW(__sync_fetch_and_nand),
4924
4925 BUILTIN_ROW(__sync_add_and_fetch),
4926 BUILTIN_ROW(__sync_sub_and_fetch),
4927 BUILTIN_ROW(__sync_and_and_fetch),
4928 BUILTIN_ROW(__sync_or_and_fetch),
4929 BUILTIN_ROW(__sync_xor_and_fetch),
4930 BUILTIN_ROW(__sync_nand_and_fetch),
4931
4932 BUILTIN_ROW(__sync_val_compare_and_swap),
4933 BUILTIN_ROW(__sync_bool_compare_and_swap),
4934 BUILTIN_ROW(__sync_lock_test_and_set),
4935 BUILTIN_ROW(__sync_lock_release),
4936 BUILTIN_ROW(__sync_swap)
4937 };
4938#undef BUILTIN_ROW
4939
4940 // Determine the index of the size.
4941 unsigned SizeIndex;
4942 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4943 case 1: SizeIndex = 0; break;
4944 case 2: SizeIndex = 1; break;
4945 case 4: SizeIndex = 2; break;
4946 case 8: SizeIndex = 3; break;
4947 case 16: SizeIndex = 4; break;
4948 default:
4949 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4950 << FirstArg->getType() << FirstArg->getSourceRange();
4951 return ExprError();
4952 }
4953
4954 // Each of these builtins has one pointer argument, followed by some number of
4955 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4956 // that we ignore. Find out which row of BuiltinIndices to read from as well
4957 // as the number of fixed args.
4958 unsigned BuiltinID = FDecl->getBuiltinID();
4959 unsigned BuiltinIndex, NumFixed = 1;
4960 bool WarnAboutSemanticsChange = false;
4961 switch (BuiltinID) {
4962 default: llvm_unreachable("Unknown overloaded atomic builtin!");
4963 case Builtin::BI__sync_fetch_and_add:
4964 case Builtin::BI__sync_fetch_and_add_1:
4965 case Builtin::BI__sync_fetch_and_add_2:
4966 case Builtin::BI__sync_fetch_and_add_4:
4967 case Builtin::BI__sync_fetch_and_add_8:
4968 case Builtin::BI__sync_fetch_and_add_16:
4969 BuiltinIndex = 0;
4970 break;
4971
4972 case Builtin::BI__sync_fetch_and_sub:
4973 case Builtin::BI__sync_fetch_and_sub_1:
4974 case Builtin::BI__sync_fetch_and_sub_2:
4975 case Builtin::BI__sync_fetch_and_sub_4:
4976 case Builtin::BI__sync_fetch_and_sub_8:
4977 case Builtin::BI__sync_fetch_and_sub_16:
4978 BuiltinIndex = 1;
4979 break;
4980
4981 case Builtin::BI__sync_fetch_and_or:
4982 case Builtin::BI__sync_fetch_and_or_1:
4983 case Builtin::BI__sync_fetch_and_or_2:
4984 case Builtin::BI__sync_fetch_and_or_4:
4985 case Builtin::BI__sync_fetch_and_or_8:
4986 case Builtin::BI__sync_fetch_and_or_16:
4987 BuiltinIndex = 2;
4988 break;
4989
4990 case Builtin::BI__sync_fetch_and_and:
4991 case Builtin::BI__sync_fetch_and_and_1:
4992 case Builtin::BI__sync_fetch_and_and_2:
4993 case Builtin::BI__sync_fetch_and_and_4:
4994 case Builtin::BI__sync_fetch_and_and_8:
4995 case Builtin::BI__sync_fetch_and_and_16:
4996 BuiltinIndex = 3;
4997 break;
4998
4999 case Builtin::BI__sync_fetch_and_xor:
5000 case Builtin::BI__sync_fetch_and_xor_1:
5001 case Builtin::BI__sync_fetch_and_xor_2:
5002 case Builtin::BI__sync_fetch_and_xor_4:
5003 case Builtin::BI__sync_fetch_and_xor_8:
5004 case Builtin::BI__sync_fetch_and_xor_16:
5005 BuiltinIndex = 4;
5006 break;
5007
5008 case Builtin::BI__sync_fetch_and_nand:
5009 case Builtin::BI__sync_fetch_and_nand_1:
5010 case Builtin::BI__sync_fetch_and_nand_2:
5011 case Builtin::BI__sync_fetch_and_nand_4:
5012 case Builtin::BI__sync_fetch_and_nand_8:
5013 case Builtin::BI__sync_fetch_and_nand_16:
5014 BuiltinIndex = 5;
5015 WarnAboutSemanticsChange = true;
5016 break;
5017
5018 case Builtin::BI__sync_add_and_fetch:
5019 case Builtin::BI__sync_add_and_fetch_1:
5020 case Builtin::BI__sync_add_and_fetch_2:
5021 case Builtin::BI__sync_add_and_fetch_4:
5022 case Builtin::BI__sync_add_and_fetch_8:
5023 case Builtin::BI__sync_add_and_fetch_16:
5024 BuiltinIndex = 6;
5025 break;
5026
5027 case Builtin::BI__sync_sub_and_fetch:
5028 case Builtin::BI__sync_sub_and_fetch_1:
5029 case Builtin::BI__sync_sub_and_fetch_2:
5030 case Builtin::BI__sync_sub_and_fetch_4:
5031 case Builtin::BI__sync_sub_and_fetch_8:
5032 case Builtin::BI__sync_sub_and_fetch_16:
5033 BuiltinIndex = 7;
5034 break;
5035
5036 case Builtin::BI__sync_and_and_fetch:
5037 case Builtin::BI__sync_and_and_fetch_1:
5038 case Builtin::BI__sync_and_and_fetch_2:
5039 case Builtin::BI__sync_and_and_fetch_4:
5040 case Builtin::BI__sync_and_and_fetch_8:
5041 case Builtin::BI__sync_and_and_fetch_16:
5042 BuiltinIndex = 8;
5043 break;
5044
5045 case Builtin::BI__sync_or_and_fetch:
5046 case Builtin::BI__sync_or_and_fetch_1:
5047 case Builtin::BI__sync_or_and_fetch_2:
5048 case Builtin::BI__sync_or_and_fetch_4:
5049 case Builtin::BI__sync_or_and_fetch_8:
5050 case Builtin::BI__sync_or_and_fetch_16:
5051 BuiltinIndex = 9;
5052 break;
5053
5054 case Builtin::BI__sync_xor_and_fetch:
5055 case Builtin::BI__sync_xor_and_fetch_1:
5056 case Builtin::BI__sync_xor_and_fetch_2:
5057 case Builtin::BI__sync_xor_and_fetch_4:
5058 case Builtin::BI__sync_xor_and_fetch_8:
5059 case Builtin::BI__sync_xor_and_fetch_16:
5060 BuiltinIndex = 10;
5061 break;
5062
5063 case Builtin::BI__sync_nand_and_fetch:
5064 case Builtin::BI__sync_nand_and_fetch_1:
5065 case Builtin::BI__sync_nand_and_fetch_2:
5066 case Builtin::BI__sync_nand_and_fetch_4:
5067 case Builtin::BI__sync_nand_and_fetch_8:
5068 case Builtin::BI__sync_nand_and_fetch_16:
5069 BuiltinIndex = 11;
5070 WarnAboutSemanticsChange = true;
5071 break;
5072
5073 case Builtin::BI__sync_val_compare_and_swap:
5074 case Builtin::BI__sync_val_compare_and_swap_1:
5075 case Builtin::BI__sync_val_compare_and_swap_2:
5076 case Builtin::BI__sync_val_compare_and_swap_4:
5077 case Builtin::BI__sync_val_compare_and_swap_8:
5078 case Builtin::BI__sync_val_compare_and_swap_16:
5079 BuiltinIndex = 12;
5080 NumFixed = 2;
5081 break;
5082
5083 case Builtin::BI__sync_bool_compare_and_swap:
5084 case Builtin::BI__sync_bool_compare_and_swap_1:
5085 case Builtin::BI__sync_bool_compare_and_swap_2:
5086 case Builtin::BI__sync_bool_compare_and_swap_4:
5087 case Builtin::BI__sync_bool_compare_and_swap_8:
5088 case Builtin::BI__sync_bool_compare_and_swap_16:
5089 BuiltinIndex = 13;
5090 NumFixed = 2;
5091 ResultType = Context.BoolTy;
5092 break;
5093
5094 case Builtin::BI__sync_lock_test_and_set:
5095 case Builtin::BI__sync_lock_test_and_set_1:
5096 case Builtin::BI__sync_lock_test_and_set_2:
5097 case Builtin::BI__sync_lock_test_and_set_4:
5098 case Builtin::BI__sync_lock_test_and_set_8:
5099 case Builtin::BI__sync_lock_test_and_set_16:
5100 BuiltinIndex = 14;
5101 break;
5102
5103 case Builtin::BI__sync_lock_release:
5104 case Builtin::BI__sync_lock_release_1:
5105 case Builtin::BI__sync_lock_release_2:
5106 case Builtin::BI__sync_lock_release_4:
5107 case Builtin::BI__sync_lock_release_8:
5108 case Builtin::BI__sync_lock_release_16:
5109 BuiltinIndex = 15;
5110 NumFixed = 0;
5111 ResultType = Context.VoidTy;
5112 break;
5113
5114 case Builtin::BI__sync_swap:
5115 case Builtin::BI__sync_swap_1:
5116 case Builtin::BI__sync_swap_2:
5117 case Builtin::BI__sync_swap_4:
5118 case Builtin::BI__sync_swap_8:
5119 case Builtin::BI__sync_swap_16:
5120 BuiltinIndex = 16;
5121 break;
5122 }
5123
5124 // Now that we know how many fixed arguments we expect, first check that we
5125 // have at least that many.
5126 if (TheCall->getNumArgs() < 1+NumFixed) {
5127 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5128 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5129 << Callee->getSourceRange();
5130 return ExprError();
5131 }
5132
5133 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5134 << Callee->getSourceRange();
5135
5136 if (WarnAboutSemanticsChange) {
5137 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5138 << Callee->getSourceRange();
5139 }
5140
5141 // Get the decl for the concrete builtin from this, we can tell what the
5142 // concrete integer type we should convert to is.
5143 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5144 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5145 FunctionDecl *NewBuiltinDecl;
5146 if (NewBuiltinID == BuiltinID)
5147 NewBuiltinDecl = FDecl;
5148 else {
5149 // Perform builtin lookup to avoid redeclaring it.
5150 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5151 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5152 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5153 assert(Res.getFoundDecl());
5154 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5155 if (!NewBuiltinDecl)
5156 return ExprError();
5157 }
5158
5159 // The first argument --- the pointer --- has a fixed type; we
5160 // deduce the types of the rest of the arguments accordingly. Walk
5161 // the remaining arguments, converting them to the deduced value type.
5162 for (unsigned i = 0; i != NumFixed; ++i) {
5163 ExprResult Arg = TheCall->getArg(i+1);
5164
5165 // GCC does an implicit conversion to the pointer or integer ValType. This
5166 // can fail in some cases (1i -> int**), check for this error case now.
5167 // Initialize the argument.
5168 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5169 ValType, /*consume*/ false);
5170 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5171 if (Arg.isInvalid())
5172 return ExprError();
5173
5174 // Okay, we have something that *can* be converted to the right type. Check
5175 // to see if there is a potentially weird extension going on here. This can
5176 // happen when you do an atomic operation on something like an char* and
5177 // pass in 42. The 42 gets converted to char. This is even more strange
5178 // for things like 45.123 -> char, etc.
5179 // FIXME: Do this check.
5180 TheCall->setArg(i+1, Arg.get());
5181 }
5182
5183 // Create a new DeclRefExpr to refer to the new decl.
5184 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5185 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5186 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5187 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5188
5189 // Set the callee in the CallExpr.
5190 // FIXME: This loses syntactic information.
5191 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5192 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5193 CK_BuiltinFnToFnPtr);
5194 TheCall->setCallee(PromotedCall.get());
5195
5196 // Change the result type of the call to match the original value type. This
5197 // is arbitrary, but the codegen for these builtins ins design to handle it
5198 // gracefully.
5199 TheCall->setType(ResultType);
5200
5201 // Prohibit problematic uses of bit-precise integer types with atomic
5202 // builtins. The arguments would have already been converted to the first
5203 // argument's type, so only need to check the first argument.
5204 const auto *BitIntValType = ValType->getAs<BitIntType>();
5205 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
5206 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5207 return ExprError();
5208 }
5209
5210 return TheCallResult;
5211}
5212
5213ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5214 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5215 DeclRefExpr *DRE =
5217 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5218 unsigned BuiltinID = FDecl->getBuiltinID();
5219 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5220 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5221 "Unexpected nontemporal load/store builtin!");
5222 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5223 unsigned numArgs = isStore ? 2 : 1;
5224
5225 // Ensure that we have the proper number of arguments.
5226 if (checkArgCount(TheCall, numArgs))
5227 return ExprError();
5228
5229 // Inspect the last argument of the nontemporal builtin. This should always
5230 // be a pointer type, from which we imply the type of the memory access.
5231 // Because it is a pointer type, we don't have to worry about any implicit
5232 // casts here.
5233 Expr *PointerArg = TheCall->getArg(numArgs - 1);
5234 ExprResult PointerArgResult =
5236
5237 if (PointerArgResult.isInvalid())
5238 return ExprError();
5239 PointerArg = PointerArgResult.get();
5240 TheCall->setArg(numArgs - 1, PointerArg);
5241
5242 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5243 if (!pointerType) {
5244 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5245 << PointerArg->getType() << PointerArg->getSourceRange();
5246 return ExprError();
5247 }
5248
5249 QualType ValType = pointerType->getPointeeType();
5250
5251 // Strip any qualifiers off ValType.
5252 ValType = ValType.getUnqualifiedType();
5253 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5254 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5255 !ValType->isVectorType()) {
5256 Diag(DRE->getBeginLoc(),
5257 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5258 << PointerArg->getType() << PointerArg->getSourceRange();
5259 return ExprError();
5260 }
5261
5262 if (!isStore) {
5263 TheCall->setType(ValType);
5264 return TheCallResult;
5265 }
5266
5267 ExprResult ValArg = TheCall->getArg(0);
5268 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5269 Context, ValType, /*consume*/ false);
5270 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5271 if (ValArg.isInvalid())
5272 return ExprError();
5273
5274 TheCall->setArg(0, ValArg.get());
5275 TheCall->setType(Context.VoidTy);
5276 return TheCallResult;
5277}
5278
5279/// CheckObjCString - Checks that the format string argument to the os_log()
5280/// and os_trace() functions is correct, and converts it to const char *.
5281ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5282 Arg = Arg->IgnoreParenCasts();
5283 auto *Literal = dyn_cast<StringLiteral>(Arg);
5284 if (!Literal) {
5285 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5286 Literal = ObjcLiteral->getString();
5287 }
5288 }
5289
5290 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5291 return ExprError(
5292 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5293 << Arg->getSourceRange());
5294 }
5295
5296 ExprResult Result(Literal);
5297 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5298 InitializedEntity Entity =
5300 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5301 return Result;
5302}
5303
5304/// Check that the user is calling the appropriate va_start builtin for the
5305/// target and calling convention.
5306static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5307 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5308 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5309 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5310 TT.getArch() == llvm::Triple::aarch64_32);
5311 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5312 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5313 if (IsX64 || IsAArch64) {
5314 CallingConv CC = CC_C;
5315 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5316 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5317 if (IsMSVAStart) {
5318 // Don't allow this in System V ABI functions.
5319 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5320 return S.Diag(Fn->getBeginLoc(),
5321 diag::err_ms_va_start_used_in_sysv_function);
5322 } else {
5323 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5324 // On x64 Windows, don't allow this in System V ABI functions.
5325 // (Yes, that means there's no corresponding way to support variadic
5326 // System V ABI functions on Windows.)
5327 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5328 (!IsWindowsOrUEFI && CC == CC_Win64))
5329 return S.Diag(Fn->getBeginLoc(),
5330 diag::err_va_start_used_in_wrong_abi_function)
5331 << !IsWindowsOrUEFI;
5332 }
5333 return false;
5334 }
5335
5336 if (IsMSVAStart)
5337 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5338 return false;
5339}
5340
5342 ParmVarDecl **LastParam = nullptr) {
5343 // Determine whether the current function, block, or obj-c method is variadic
5344 // and get its parameter list.
5345 bool IsVariadic = false;
5347 DeclContext *Caller = S.CurContext;
5348 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5349 IsVariadic = Block->isVariadic();
5350 Params = Block->parameters();
5351 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5352 IsVariadic = FD->isVariadic();
5353 Params = FD->parameters();
5354 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5355 IsVariadic = MD->isVariadic();
5356 // FIXME: This isn't correct for methods (results in bogus warning).
5357 Params = MD->parameters();
5358 } else if (isa<CapturedDecl>(Caller)) {
5359 // We don't support va_start in a CapturedDecl.
5360 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5361 return true;
5362 } else {
5363 // This must be some other declcontext that parses exprs.
5364 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5365 return true;
5366 }
5367
5368 if (!IsVariadic) {
5369 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5370 return true;
5371 }
5372
5373 if (LastParam)
5374 *LastParam = Params.empty() ? nullptr : Params.back();
5375
5376 return false;
5377}
5378
5379bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5380 Expr *Fn = TheCall->getCallee();
5381 if (checkVAStartABI(*this, BuiltinID, Fn))
5382 return true;
5383
5384 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5385 // This builtin requires one argument (the va_list), allows two arguments,
5386 // but diagnoses more than two arguments. e.g.,
5387 // __builtin_c23_va_start(); // error
5388 // __builtin_c23_va_start(list); // ok
5389 // __builtin_c23_va_start(list, param); // ok
5390 // __builtin_c23_va_start(list, anything, anything); // error
5391 // This differs from the GCC behavior in that they accept the last case
5392 // with a warning, but it doesn't seem like a useful behavior to allow.
5393 if (checkArgCountRange(TheCall, 1, 2))
5394 return true;
5395 } else {
5396 // In C23 mode, va_start only needs one argument. However, the builtin still
5397 // requires two arguments (which matches the behavior of the GCC builtin),
5398 // <stdarg.h> passes `0` as the second argument in C23 mode.
5399 if (checkArgCount(TheCall, 2))
5400 return true;
5401 }
5402
5403 // Type-check the first argument normally.
5404 if (checkBuiltinArgument(*this, TheCall, 0))
5405 return true;
5406
5407 // Check that the current function is variadic, and get its last parameter.
5408 ParmVarDecl *LastParam;
5409 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5410 return true;
5411
5412 // Verify that the second argument to the builtin is the last non-variadic
5413 // argument of the current function or method. In C23 mode, if the call is
5414 // not to __builtin_c23_va_start, and the second argument is an integer
5415 // constant expression with value 0, then we don't bother with this check.
5416 // For __builtin_c23_va_start, we only perform the check for the second
5417 // argument being the last argument to the current function if there is a
5418 // second argument present.
5419 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5420 TheCall->getNumArgs() < 2) {
5421 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5422 return false;
5423 }
5424
5425 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5426 if (std::optional<llvm::APSInt> Val =
5428 Val && LangOpts.C23 && *Val == 0 &&
5429 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5430 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
5431 return false;
5432 }
5433
5434 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5435 // next block.
5436 QualType Type;
5437 SourceLocation ParamLoc;
5438 bool IsCRegister = false;
5439 bool SecondArgIsLastNonVariadicArgument = false;
5440 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5441 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5442 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5443
5444 Type = PV->getType();
5445 ParamLoc = PV->getLocation();
5446 IsCRegister =
5447 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5448 }
5449 }
5450
5451 if (!SecondArgIsLastNonVariadicArgument)
5452 Diag(TheCall->getArg(1)->getBeginLoc(),
5453 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5454 else if (IsCRegister || Type->isReferenceType() ||
5455 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5456 // Promotable integers are UB, but enumerations need a bit of
5457 // extra checking to see what their promotable type actually is.
5458 if (!Context.isPromotableIntegerType(Type))
5459 return false;
5460 const auto *ED = Type->getAsEnumDecl();
5461 if (!ED)
5462 return true;
5463 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
5464 }()) {
5465 unsigned Reason = 0;
5466 if (Type->isReferenceType()) Reason = 1;
5467 else if (IsCRegister) Reason = 2;
5468 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5469 Diag(ParamLoc, diag::note_parameter_type) << Type;
5470 }
5471
5472 return false;
5473}
5474
5475bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5476 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5477 const LangOptions &LO = getLangOpts();
5478
5479 if (LO.CPlusPlus)
5480 return Arg->getType()
5482 .getTypePtr()
5483 ->getPointeeType()
5485
5486 // In C, allow aliasing through `char *`, this is required for AArch64 at
5487 // least.
5488 return true;
5489 };
5490
5491 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5492 // const char *named_addr);
5493
5494 Expr *Func = Call->getCallee();
5495
5496 if (Call->getNumArgs() < 3)
5497 return Diag(Call->getEndLoc(),
5498 diag::err_typecheck_call_too_few_args_at_least)
5499 << 0 /*function call*/ << 3 << Call->getNumArgs()
5500 << /*is non object*/ 0;
5501
5502 // Type-check the first argument normally.
5503 if (checkBuiltinArgument(*this, Call, 0))
5504 return true;
5505
5506 // Check that the current function is variadic.
5508 return true;
5509
5510 // __va_start on Windows does not validate the parameter qualifiers
5511
5512 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5513 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5514
5515 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5516 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5517
5518 const QualType &ConstCharPtrTy =
5519 Context.getPointerType(Context.CharTy.withConst());
5520 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5521 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5522 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5523 << 0 /* qualifier difference */
5524 << 3 /* parameter mismatch */
5525 << 2 << Arg1->getType() << ConstCharPtrTy;
5526
5527 const QualType SizeTy = Context.getSizeType();
5528 if (!Context.hasSameType(
5530 SizeTy))
5531 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5532 << Arg2->getType() << SizeTy << 1 /* different class */
5533 << 0 /* qualifier difference */
5534 << 3 /* parameter mismatch */
5535 << 3 << Arg2->getType() << SizeTy;
5536
5537 return false;
5538}
5539
5540bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5541 if (checkArgCount(TheCall, 2))
5542 return true;
5543
5544 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5545 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
5546 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5547 << 1 << 0 << TheCall->getSourceRange();
5548
5549 ExprResult OrigArg0 = TheCall->getArg(0);
5550 ExprResult OrigArg1 = TheCall->getArg(1);
5551
5552 // Do standard promotions between the two arguments, returning their common
5553 // type.
5554 QualType Res = UsualArithmeticConversions(
5555 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
5556 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5557 return true;
5558
5559 // Make sure any conversions are pushed back into the call; this is
5560 // type safe since unordered compare builtins are declared as "_Bool
5561 // foo(...)".
5562 TheCall->setArg(0, OrigArg0.get());
5563 TheCall->setArg(1, OrigArg1.get());
5564
5565 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5566 return false;
5567
5568 // If the common type isn't a real floating type, then the arguments were
5569 // invalid for this operation.
5570 if (Res.isNull() || !Res->isRealFloatingType())
5571 return Diag(OrigArg0.get()->getBeginLoc(),
5572 diag::err_typecheck_call_invalid_ordered_compare)
5573 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5574 << SourceRange(OrigArg0.get()->getBeginLoc(),
5575 OrigArg1.get()->getEndLoc());
5576
5577 return false;
5578}
5579
5580bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5581 unsigned BuiltinID) {
5582 if (checkArgCount(TheCall, NumArgs))
5583 return true;
5584
5585 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
5586 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5587 BuiltinID == Builtin::BI__builtin_isinf ||
5588 BuiltinID == Builtin::BI__builtin_isinf_sign))
5589 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5590 << 0 << 0 << TheCall->getSourceRange();
5591
5592 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5593 BuiltinID == Builtin::BI__builtin_isunordered))
5594 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
5595 << 1 << 0 << TheCall->getSourceRange();
5596
5597 bool IsFPClass = NumArgs == 2;
5598
5599 // Find out position of floating-point argument.
5600 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5601
5602 // We can count on all parameters preceding the floating-point just being int.
5603 // Try all of those.
5604 for (unsigned i = 0; i < FPArgNo; ++i) {
5605 Expr *Arg = TheCall->getArg(i);
5606
5607 if (Arg->isTypeDependent())
5608 return false;
5609
5612
5613 if (Res.isInvalid())
5614 return true;
5615 TheCall->setArg(i, Res.get());
5616 }
5617
5618 Expr *OrigArg = TheCall->getArg(FPArgNo);
5619
5620 if (OrigArg->isTypeDependent())
5621 return false;
5622
5623 // Usual Unary Conversions will convert half to float, which we want for
5624 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5625 // type how it is, but do normal L->Rvalue conversions.
5626 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
5627 ExprResult Res = UsualUnaryConversions(OrigArg);
5628
5629 if (!Res.isUsable())
5630 return true;
5631 OrigArg = Res.get();
5632 } else {
5634
5635 if (!Res.isUsable())
5636 return true;
5637 OrigArg = Res.get();
5638 }
5639 TheCall->setArg(FPArgNo, OrigArg);
5640
5641 QualType VectorResultTy;
5642 QualType ElementTy = OrigArg->getType();
5643 // TODO: When all classification function are implemented with is_fpclass,
5644 // vector argument can be supported in all of them.
5645 if (ElementTy->isVectorType() && IsFPClass) {
5646 VectorResultTy = GetSignedVectorType(ElementTy);
5647 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
5648 }
5649
5650 // This operation requires a non-_Complex floating-point number.
5651 if (!ElementTy->isRealFloatingType())
5652 return Diag(OrigArg->getBeginLoc(),
5653 diag::err_typecheck_call_invalid_unary_fp)
5654 << OrigArg->getType() << OrigArg->getSourceRange();
5655
5656 // __builtin_isfpclass has integer parameter that specify test mask. It is
5657 // passed in (...), so it should be analyzed completely here.
5658 if (IsFPClass)
5659 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
5660 return true;
5661
5662 // TODO: enable this code to all classification functions.
5663 if (IsFPClass) {
5664 QualType ResultTy;
5665 if (!VectorResultTy.isNull())
5666 ResultTy = VectorResultTy;
5667 else
5668 ResultTy = Context.IntTy;
5669 TheCall->setType(ResultTy);
5670 }
5671
5672 return false;
5673}
5674
5675bool Sema::BuiltinComplex(CallExpr *TheCall) {
5676 if (checkArgCount(TheCall, 2))
5677 return true;
5678
5679 bool Dependent = false;
5680 for (unsigned I = 0; I != 2; ++I) {
5681 Expr *Arg = TheCall->getArg(I);
5682 QualType T = Arg->getType();
5683 if (T->isDependentType()) {
5684 Dependent = true;
5685 continue;
5686 }
5687
5688 // Despite supporting _Complex int, GCC requires a real floating point type
5689 // for the operands of __builtin_complex.
5690 if (!T->isRealFloatingType()) {
5691 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5692 << Arg->getType() << Arg->getSourceRange();
5693 }
5694
5695 ExprResult Converted = DefaultLvalueConversion(Arg);
5696 if (Converted.isInvalid())
5697 return true;
5698 TheCall->setArg(I, Converted.get());
5699 }
5700
5701 if (Dependent) {
5702 TheCall->setType(Context.DependentTy);
5703 return false;
5704 }
5705
5706 Expr *Real = TheCall->getArg(0);
5707 Expr *Imag = TheCall->getArg(1);
5708 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
5709 return Diag(Real->getBeginLoc(),
5710 diag::err_typecheck_call_different_arg_types)
5711 << Real->getType() << Imag->getType()
5712 << Real->getSourceRange() << Imag->getSourceRange();
5713 }
5714
5715 TheCall->setType(Context.getComplexType(Real->getType()));
5716 return false;
5717}
5718
5719/// BuiltinShuffleVector - Handle __builtin_shufflevector.
5720// This is declared to take (...), so we have to check everything.
5722 unsigned NumArgs = TheCall->getNumArgs();
5723 if (NumArgs < 2)
5724 return ExprError(Diag(TheCall->getEndLoc(),
5725 diag::err_typecheck_call_too_few_args_at_least)
5726 << 0 /*function call*/ << 2 << NumArgs
5727 << /*is non object*/ 0 << TheCall->getSourceRange());
5728
5729 // Determine which of the following types of shufflevector we're checking:
5730 // 1) unary, vector mask: (lhs, mask)
5731 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5732 QualType ResType = TheCall->getArg(0)->getType();
5733 unsigned NumElements = 0;
5734
5735 if (!TheCall->getArg(0)->isTypeDependent() &&
5736 !TheCall->getArg(1)->isTypeDependent()) {
5737 QualType LHSType = TheCall->getArg(0)->getType();
5738 QualType RHSType = TheCall->getArg(1)->getType();
5739
5740 if (!LHSType->isVectorType() || !RHSType->isVectorType())
5741 return ExprError(
5742 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5743 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
5744 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5745 TheCall->getArg(1)->getEndLoc()));
5746
5747 NumElements = LHSType->castAs<VectorType>()->getNumElements();
5748 unsigned NumResElements = NumArgs - 2;
5749
5750 // Check to see if we have a call with 2 vector arguments, the unary shuffle
5751 // with mask. If so, verify that RHS is an integer vector type with the
5752 // same number of elts as lhs.
5753 if (NumArgs == 2) {
5754 if (!RHSType->hasIntegerRepresentation() ||
5755 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
5756 return ExprError(Diag(TheCall->getBeginLoc(),
5757 diag::err_vec_builtin_incompatible_vector)
5758 << TheCall->getDirectCallee()
5759 << /*isMoreThanTwoArgs*/ false
5760 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5761 TheCall->getArg(1)->getEndLoc()));
5762 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5763 return ExprError(Diag(TheCall->getBeginLoc(),
5764 diag::err_vec_builtin_incompatible_vector)
5765 << TheCall->getDirectCallee()
5766 << /*isMoreThanTwoArgs*/ false
5767 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5768 TheCall->getArg(1)->getEndLoc()));
5769 } else if (NumElements != NumResElements) {
5770 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
5771 ResType = ResType->isExtVectorType()
5772 ? Context.getExtVectorType(EltType, NumResElements)
5773 : Context.getVectorType(EltType, NumResElements,
5775 }
5776 }
5777
5778 for (unsigned I = 2; I != NumArgs; ++I) {
5779 Expr *Arg = TheCall->getArg(I);
5780 if (Arg->isTypeDependent() || Arg->isValueDependent())
5781 continue;
5782
5783 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
5784 if (!Result)
5785 return ExprError(Diag(TheCall->getBeginLoc(),
5786 diag::err_shufflevector_nonconstant_argument)
5787 << Arg->getSourceRange());
5788
5789 // Allow -1 which will be translated to undef in the IR.
5790 if (Result->isSigned() && Result->isAllOnes())
5791 ;
5792 else if (Result->getActiveBits() > 64 ||
5793 Result->getZExtValue() >= NumElements * 2)
5794 return ExprError(Diag(TheCall->getBeginLoc(),
5795 diag::err_shufflevector_argument_too_large)
5796 << Arg->getSourceRange());
5797
5798 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
5799 }
5800
5801 auto *Result = new (Context) ShuffleVectorExpr(
5802 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
5803 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
5804
5805 // All moved to Result.
5806 TheCall->shrinkNumArgs(0);
5807 return Result;
5808}
5809
5811 SourceLocation BuiltinLoc,
5812 SourceLocation RParenLoc) {
5815 QualType DstTy = TInfo->getType();
5816 QualType SrcTy = E->getType();
5817
5818 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5819 return ExprError(Diag(BuiltinLoc,
5820 diag::err_convertvector_non_vector)
5821 << E->getSourceRange());
5822 if (!DstTy->isVectorType() && !DstTy->isDependentType())
5823 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
5824 << "second"
5825 << "__builtin_convertvector");
5826
5827 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5828 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
5829 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
5830 if (SrcElts != DstElts)
5831 return ExprError(Diag(BuiltinLoc,
5832 diag::err_convertvector_incompatible_vector)
5833 << E->getSourceRange());
5834 }
5835
5836 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
5837 RParenLoc, CurFPFeatureOverrides());
5838}
5839
5840bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
5841 unsigned NumArgs = TheCall->getNumArgs();
5842
5843 if (NumArgs > 3)
5844 return Diag(TheCall->getEndLoc(),
5845 diag::err_typecheck_call_too_many_args_at_most)
5846 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
5847 << TheCall->getSourceRange();
5848
5849 // Argument 0 is checked for us and the remaining arguments must be
5850 // constant integers.
5851 for (unsigned i = 1; i != NumArgs; ++i)
5852 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5853 return true;
5854
5855 return false;
5856}
5857
5858bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
5859 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
5860 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
5861 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
5862 if (checkArgCount(TheCall, 1))
5863 return true;
5864 Expr *Arg = TheCall->getArg(0);
5865 if (Arg->isInstantiationDependent())
5866 return false;
5867
5868 QualType ArgTy = Arg->getType();
5869 if (!ArgTy->hasFloatingRepresentation())
5870 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
5871 << ArgTy;
5872 if (Arg->isLValue()) {
5873 ExprResult FirstArg = DefaultLvalueConversion(Arg);
5874 TheCall->setArg(0, FirstArg.get());
5875 }
5876 TheCall->setType(TheCall->getArg(0)->getType());
5877 return false;
5878}
5879
5880bool Sema::BuiltinAssume(CallExpr *TheCall) {
5881 Expr *Arg = TheCall->getArg(0);
5882 if (Arg->isInstantiationDependent()) return false;
5883
5884 if (Arg->HasSideEffects(Context))
5885 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5886 << Arg->getSourceRange()
5887 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5888
5889 return false;
5890}
5891
5892bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
5893 // The alignment must be a constant integer.
5894 Expr *Arg = TheCall->getArg(1);
5895
5896 // We can't check the value of a dependent argument.
5897 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5898 if (const auto *UE =
5899 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5900 if (UE->getKind() == UETT_AlignOf ||
5901 UE->getKind() == UETT_PreferredAlignOf)
5902 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5903 << Arg->getSourceRange();
5904
5905 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5906
5907 if (!Result.isPowerOf2())
5908 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5909 << Arg->getSourceRange();
5910
5911 if (Result < Context.getCharWidth())
5912 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5913 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5914
5915 if (Result > std::numeric_limits<int32_t>::max())
5916 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5917 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5918 }
5919
5920 return false;
5921}
5922
5923bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
5924 if (checkArgCountRange(TheCall, 2, 3))
5925 return true;
5926
5927 unsigned NumArgs = TheCall->getNumArgs();
5928 Expr *FirstArg = TheCall->getArg(0);
5929
5930 {
5931 ExprResult FirstArgResult =
5933 if (!FirstArgResult.get()->getType()->isPointerType()) {
5934 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
5935 << TheCall->getSourceRange();
5936 return true;
5937 }
5938 TheCall->setArg(0, FirstArgResult.get());
5939 }
5940
5941 // The alignment must be a constant integer.
5942 Expr *SecondArg = TheCall->getArg(1);
5943
5944 // We can't check the value of a dependent argument.
5945 if (!SecondArg->isValueDependent()) {
5946 llvm::APSInt Result;
5947 if (BuiltinConstantArg(TheCall, 1, Result))
5948 return true;
5949
5950 if (!Result.isPowerOf2())
5951 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5952 << SecondArg->getSourceRange();
5953
5955 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
5956 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
5957 }
5958
5959 if (NumArgs > 2) {
5960 Expr *ThirdArg = TheCall->getArg(2);
5961 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
5962 return true;
5963 TheCall->setArg(2, ThirdArg);
5964 }
5965
5966 return false;
5967}
5968
5969bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
5970 unsigned BuiltinID =
5971 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5972 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5973
5974 unsigned NumArgs = TheCall->getNumArgs();
5975 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5976 if (NumArgs < NumRequiredArgs) {
5977 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5978 << 0 /* function call */ << NumRequiredArgs << NumArgs
5979 << /*is non object*/ 0 << TheCall->getSourceRange();
5980 }
5981 if (NumArgs >= NumRequiredArgs + 0x100) {
5982 return Diag(TheCall->getEndLoc(),
5983 diag::err_typecheck_call_too_many_args_at_most)
5984 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5985 << /*is non object*/ 0 << TheCall->getSourceRange();
5986 }
5987 unsigned i = 0;
5988
5989 // For formatting call, check buffer arg.
5990 if (!IsSizeCall) {
5991 ExprResult Arg(TheCall->getArg(i));
5992 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5993 Context, Context.VoidPtrTy, false);
5994 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5995 if (Arg.isInvalid())
5996 return true;
5997 TheCall->setArg(i, Arg.get());
5998 i++;
5999 }
6000
6001 // Check string literal arg.
6002 unsigned FormatIdx = i;
6003 {
6004 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6005 if (Arg.isInvalid())
6006 return true;
6007 TheCall->setArg(i, Arg.get());
6008 i++;
6009 }
6010
6011 // Make sure variadic args are scalar.
6012 unsigned FirstDataArg = i;
6013 while (i < NumArgs) {
6015 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6016 if (Arg.isInvalid())
6017 return true;
6018 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6019 if (ArgSize.getQuantity() >= 0x100) {
6020 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6021 << i << (int)ArgSize.getQuantity() << 0xff
6022 << TheCall->getSourceRange();
6023 }
6024 TheCall->setArg(i, Arg.get());
6025 i++;
6026 }
6027
6028 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6029 // call to avoid duplicate diagnostics.
6030 if (!IsSizeCall) {
6031 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6032 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6033 bool Success = CheckFormatArguments(
6034 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6036 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6037 if (!Success)
6038 return true;
6039 }
6040
6041 if (IsSizeCall) {
6042 TheCall->setType(Context.getSizeType());
6043 } else {
6044 TheCall->setType(Context.VoidPtrTy);
6045 }
6046 return false;
6047}
6048
6049bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6050 llvm::APSInt &Result) {
6051 Expr *Arg = TheCall->getArg(ArgNum);
6052
6053 if (Arg->isTypeDependent() || Arg->isValueDependent())
6054 return false;
6055
6056 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6057 if (!R) {
6058 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6059 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6060 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6061 << FDecl->getDeclName() << Arg->getSourceRange();
6062 }
6063 Result = *R;
6064
6065 return false;
6066}
6067
6068bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6069 int High, bool RangeIsError) {
6071 return false;
6072 llvm::APSInt Result;
6073
6074 // We can't check the value of a dependent argument.
6075 Expr *Arg = TheCall->getArg(ArgNum);
6076 if (Arg->isTypeDependent() || Arg->isValueDependent())
6077 return false;
6078
6079 // Check constant-ness first.
6080 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6081 return true;
6082
6083 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6084 if (RangeIsError)
6085 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6086 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6087 else
6088 // Defer the warning until we know if the code will be emitted so that
6089 // dead code can ignore this.
6090 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6091 PDiag(diag::warn_argument_invalid_range)
6092 << toString(Result, 10) << Low << High
6093 << Arg->getSourceRange());
6094 }
6095
6096 return false;
6097}
6098
6099bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6100 unsigned Num) {
6101 llvm::APSInt Result;
6102
6103 // We can't check the value of a dependent argument.
6104 Expr *Arg = TheCall->getArg(ArgNum);
6105 if (Arg->isTypeDependent() || Arg->isValueDependent())
6106 return false;
6107
6108 // Check constant-ness first.
6109 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6110 return true;
6111
6112 if (Result.getSExtValue() % Num != 0)
6113 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6114 << Num << Arg->getSourceRange();
6115
6116 return false;
6117}
6118
6119bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6120 llvm::APSInt Result;
6121
6122 // We can't check the value of a dependent argument.
6123 Expr *Arg = TheCall->getArg(ArgNum);
6124 if (Arg->isTypeDependent() || Arg->isValueDependent())
6125 return false;
6126
6127 // Check constant-ness first.
6128 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6129 return true;
6130
6131 if (Result.isPowerOf2())
6132 return false;
6133
6134 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6135 << Arg->getSourceRange();
6136}
6137
6138static bool IsShiftedByte(llvm::APSInt Value) {
6139 if (Value.isNegative())
6140 return false;
6141
6142 // Check if it's a shifted byte, by shifting it down
6143 while (true) {
6144 // If the value fits in the bottom byte, the check passes.
6145 if (Value < 0x100)
6146 return true;
6147
6148 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6149 // fails.
6150 if ((Value & 0xFF) != 0)
6151 return false;
6152
6153 // If the bottom 8 bits are all 0, but something above that is nonzero,
6154 // then shifting the value right by 8 bits won't affect whether it's a
6155 // shifted byte or not. So do that, and go round again.
6156 Value >>= 8;
6157 }
6158}
6159
6160bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6161 unsigned ArgBits) {
6162 llvm::APSInt Result;
6163
6164 // We can't check the value of a dependent argument.
6165 Expr *Arg = TheCall->getArg(ArgNum);
6166 if (Arg->isTypeDependent() || Arg->isValueDependent())
6167 return false;
6168
6169 // Check constant-ness first.
6170 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6171 return true;
6172
6173 // Truncate to the given size.
6174 Result = Result.getLoBits(ArgBits);
6175 Result.setIsUnsigned(true);
6176
6177 if (IsShiftedByte(Result))
6178 return false;
6179
6180 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6181 << Arg->getSourceRange();
6182}
6183
6185 unsigned ArgNum,
6186 unsigned ArgBits) {
6187 llvm::APSInt Result;
6188
6189 // We can't check the value of a dependent argument.
6190 Expr *Arg = TheCall->getArg(ArgNum);
6191 if (Arg->isTypeDependent() || Arg->isValueDependent())
6192 return false;
6193
6194 // Check constant-ness first.
6195 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6196 return true;
6197
6198 // Truncate to the given size.
6199 Result = Result.getLoBits(ArgBits);
6200 Result.setIsUnsigned(true);
6201
6202 // Check to see if it's in either of the required forms.
6203 if (IsShiftedByte(Result) ||
6204 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6205 return false;
6206
6207 return Diag(TheCall->getBeginLoc(),
6208 diag::err_argument_not_shifted_byte_or_xxff)
6209 << Arg->getSourceRange();
6210}
6211
6212bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6213 if (!Context.getTargetInfo().hasSjLjLowering())
6214 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6215 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6216
6217 Expr *Arg = TheCall->getArg(1);
6218 llvm::APSInt Result;
6219
6220 // TODO: This is less than ideal. Overload this to take a value.
6221 if (BuiltinConstantArg(TheCall, 1, Result))
6222 return true;
6223
6224 if (Result != 1)
6225 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6226 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6227
6228 return false;
6229}
6230
6231bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6232 if (!Context.getTargetInfo().hasSjLjLowering())
6233 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6234 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6235 return false;
6236}
6237
6238bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6239 if (checkArgCount(TheCall, 1))
6240 return true;
6241
6242 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
6243 if (ArgRes.isInvalid())
6244 return true;
6245
6246 // For simplicity, we support only limited expressions for the argument.
6247 // Specifically a pointer to a flexible array member:'ptr->array'. This
6248 // allows us to reject arguments with complex casting, which really shouldn't
6249 // be a huge problem.
6250 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6251 if (!isa<PointerType>(Arg->getType()) && !Arg->getType()->isArrayType())
6252 return Diag(Arg->getBeginLoc(),
6253 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6254 << Arg->getSourceRange();
6255
6256 if (Arg->HasSideEffects(Context))
6257 return Diag(Arg->getBeginLoc(),
6258 diag::err_builtin_counted_by_ref_has_side_effects)
6259 << Arg->getSourceRange();
6260
6261 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
6262 if (!ME->isFlexibleArrayMemberLike(
6263 Context, getLangOpts().getStrictFlexArraysLevel()))
6264 return Diag(Arg->getBeginLoc(),
6265 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6266 << Arg->getSourceRange();
6267
6268 if (auto *CATy =
6269 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6270 CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6271 const auto *FAMDecl = cast<FieldDecl>(ME->getMemberDecl());
6272 if (const FieldDecl *CountFD = FAMDecl->findCountedByField()) {
6273 TheCall->setType(Context.getPointerType(CountFD->getType()));
6274 return false;
6275 }
6276 }
6277 } else {
6278 return Diag(Arg->getBeginLoc(),
6279 diag::err_builtin_counted_by_ref_must_be_flex_array_member)
6280 << Arg->getSourceRange();
6281 }
6282
6283 TheCall->setType(Context.getPointerType(Context.VoidTy));
6284 return false;
6285}
6286
6287/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6288/// It allows leaking and modification of bounds safety information.
6289bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6291 const CallExpr *CE =
6292 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
6293 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6294 return false;
6295
6296 switch (K) {
6299 Diag(E->getExprLoc(),
6300 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6301 << 0 << E->getSourceRange();
6302 break;
6304 Diag(E->getExprLoc(),
6305 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6306 << 1 << E->getSourceRange();
6307 break;
6309 Diag(E->getExprLoc(),
6310 diag::err_builtin_counted_by_ref_cannot_leak_reference)
6311 << 2 << E->getSourceRange();
6312 break;
6314 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6315 << 0 << E->getSourceRange();
6316 break;
6318 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
6319 << 1 << E->getSourceRange();
6320 break;
6321 }
6322
6323 return true;
6324}
6325
6326namespace {
6327
6328class UncoveredArgHandler {
6329 enum { Unknown = -1, AllCovered = -2 };
6330
6331 signed FirstUncoveredArg = Unknown;
6332 SmallVector<const Expr *, 4> DiagnosticExprs;
6333
6334public:
6335 UncoveredArgHandler() = default;
6336
6337 bool hasUncoveredArg() const {
6338 return (FirstUncoveredArg >= 0);
6339 }
6340
6341 unsigned getUncoveredArg() const {
6342 assert(hasUncoveredArg() && "no uncovered argument");
6343 return FirstUncoveredArg;
6344 }
6345
6346 void setAllCovered() {
6347 // A string has been found with all arguments covered, so clear out
6348 // the diagnostics.
6349 DiagnosticExprs.clear();
6350 FirstUncoveredArg = AllCovered;
6351 }
6352
6353 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6354 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6355
6356 // Don't update if a previous string covers all arguments.
6357 if (FirstUncoveredArg == AllCovered)
6358 return;
6359
6360 // UncoveredArgHandler tracks the highest uncovered argument index
6361 // and with it all the strings that match this index.
6362 if (NewFirstUncoveredArg == FirstUncoveredArg)
6363 DiagnosticExprs.push_back(StrExpr);
6364 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6365 DiagnosticExprs.clear();
6366 DiagnosticExprs.push_back(StrExpr);
6367 FirstUncoveredArg = NewFirstUncoveredArg;
6368 }
6369 }
6370
6371 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6372};
6373
6374enum StringLiteralCheckType {
6375 SLCT_NotALiteral,
6376 SLCT_UncheckedLiteral,
6377 SLCT_CheckedLiteral
6378};
6379
6380} // namespace
6381
6382static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6383 BinaryOperatorKind BinOpKind,
6384 bool AddendIsRight) {
6385 unsigned BitWidth = Offset.getBitWidth();
6386 unsigned AddendBitWidth = Addend.getBitWidth();
6387 // There might be negative interim results.
6388 if (Addend.isUnsigned()) {
6389 Addend = Addend.zext(++AddendBitWidth);
6390 Addend.setIsSigned(true);
6391 }
6392 // Adjust the bit width of the APSInts.
6393 if (AddendBitWidth > BitWidth) {
6394 Offset = Offset.sext(AddendBitWidth);
6395 BitWidth = AddendBitWidth;
6396 } else if (BitWidth > AddendBitWidth) {
6397 Addend = Addend.sext(BitWidth);
6398 }
6399
6400 bool Ov = false;
6401 llvm::APSInt ResOffset = Offset;
6402 if (BinOpKind == BO_Add)
6403 ResOffset = Offset.sadd_ov(Addend, Ov);
6404 else {
6405 assert(AddendIsRight && BinOpKind == BO_Sub &&
6406 "operator must be add or sub with addend on the right");
6407 ResOffset = Offset.ssub_ov(Addend, Ov);
6408 }
6409
6410 // We add an offset to a pointer here so we should support an offset as big as
6411 // possible.
6412 if (Ov) {
6413 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6414 "index (intermediate) result too big");
6415 Offset = Offset.sext(2 * BitWidth);
6416 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6417 return;
6418 }
6419
6420 Offset = ResOffset;
6421}
6422
6423namespace {
6424
6425// This is a wrapper class around StringLiteral to support offsetted string
6426// literals as format strings. It takes the offset into account when returning
6427// the string and its length or the source locations to display notes correctly.
6428class FormatStringLiteral {
6429 const StringLiteral *FExpr;
6430 int64_t Offset;
6431
6432public:
6433 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6434 : FExpr(fexpr), Offset(Offset) {}
6435
6436 const StringLiteral *getFormatString() const { return FExpr; }
6437
6438 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
6439
6440 unsigned getByteLength() const {
6441 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6442 }
6443
6444 unsigned getLength() const { return FExpr->getLength() - Offset; }
6445 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6446
6447 StringLiteralKind getKind() const { return FExpr->getKind(); }
6448
6449 QualType getType() const { return FExpr->getType(); }
6450
6451 bool isAscii() const { return FExpr->isOrdinary(); }
6452 bool isWide() const { return FExpr->isWide(); }
6453 bool isUTF8() const { return FExpr->isUTF8(); }
6454 bool isUTF16() const { return FExpr->isUTF16(); }
6455 bool isUTF32() const { return FExpr->isUTF32(); }
6456 bool isPascal() const { return FExpr->isPascal(); }
6457
6458 SourceLocation getLocationOfByte(
6459 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6460 const TargetInfo &Target, unsigned *StartToken = nullptr,
6461 unsigned *StartTokenByteOffset = nullptr) const {
6462 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6463 StartToken, StartTokenByteOffset);
6464 }
6465
6466 SourceLocation getBeginLoc() const LLVM_READONLY {
6467 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6468 }
6469
6470 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6471};
6472
6473} // namespace
6474
6475static void CheckFormatString(
6476 Sema &S, const FormatStringLiteral *FExpr,
6477 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6479 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6480 bool inFunctionCall, VariadicCallType CallType,
6481 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6482 bool IgnoreStringsWithoutSpecifiers);
6483
6484static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6485 const Expr *E);
6486
6487// Determine if an expression is a string literal or constant string.
6488// If this function returns false on the arguments to a function expecting a
6489// format string, we will usually need to emit a warning.
6490// True string literals are then checked by CheckFormatString.
6491static StringLiteralCheckType checkFormatStringExpr(
6492 Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E,
6494 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6495 VariadicCallType CallType, bool InFunctionCall,
6496 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6497 llvm::APSInt Offset, bool IgnoreStringsWithoutSpecifiers = false) {
6499 return SLCT_NotALiteral;
6500tryAgain:
6501 assert(Offset.isSigned() && "invalid offset");
6502
6503 if (E->isTypeDependent() || E->isValueDependent())
6504 return SLCT_NotALiteral;
6505
6506 E = E->IgnoreParenCasts();
6507
6509 // Technically -Wformat-nonliteral does not warn about this case.
6510 // The behavior of printf and friends in this case is implementation
6511 // dependent. Ideally if the format string cannot be null then
6512 // it should have a 'nonnull' attribute in the function prototype.
6513 return SLCT_UncheckedLiteral;
6514
6515 switch (E->getStmtClass()) {
6516 case Stmt::InitListExprClass:
6517 // Handle expressions like {"foobar"}.
6518 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
6519 return checkFormatStringExpr(
6520 S, ReferenceFormatString, SLE, Args, APK, format_idx, firstDataArg,
6521 Type, CallType, /*InFunctionCall*/ false, CheckedVarArgs,
6522 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6523 }
6524 return SLCT_NotALiteral;
6525 case Stmt::BinaryConditionalOperatorClass:
6526 case Stmt::ConditionalOperatorClass: {
6527 // The expression is a literal if both sub-expressions were, and it was
6528 // completely checked only if both sub-expressions were checked.
6531
6532 // Determine whether it is necessary to check both sub-expressions, for
6533 // example, because the condition expression is a constant that can be
6534 // evaluated at compile time.
6535 bool CheckLeft = true, CheckRight = true;
6536
6537 bool Cond;
6538 if (C->getCond()->EvaluateAsBooleanCondition(
6540 if (Cond)
6541 CheckRight = false;
6542 else
6543 CheckLeft = false;
6544 }
6545
6546 // We need to maintain the offsets for the right and the left hand side
6547 // separately to check if every possible indexed expression is a valid
6548 // string literal. They might have different offsets for different string
6549 // literals in the end.
6550 StringLiteralCheckType Left;
6551 if (!CheckLeft)
6552 Left = SLCT_UncheckedLiteral;
6553 else {
6554 Left = checkFormatStringExpr(
6555 S, ReferenceFormatString, C->getTrueExpr(), Args, APK, format_idx,
6556 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6557 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6558 if (Left == SLCT_NotALiteral || !CheckRight) {
6559 return Left;
6560 }
6561 }
6562
6563 StringLiteralCheckType Right = checkFormatStringExpr(
6564 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
6565 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6566 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6567
6568 return (CheckLeft && Left < Right) ? Left : Right;
6569 }
6570
6571 case Stmt::ImplicitCastExprClass:
6572 E = cast<ImplicitCastExpr>(E)->getSubExpr();
6573 goto tryAgain;
6574
6575 case Stmt::OpaqueValueExprClass:
6576 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6577 E = src;
6578 goto tryAgain;
6579 }
6580 return SLCT_NotALiteral;
6581
6582 case Stmt::PredefinedExprClass:
6583 // While __func__, etc., are technically not string literals, they
6584 // cannot contain format specifiers and thus are not a security
6585 // liability.
6586 return SLCT_UncheckedLiteral;
6587
6588 case Stmt::DeclRefExprClass: {
6589 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6590
6591 // As an exception, do not flag errors for variables binding to
6592 // const string literals.
6593 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6594 bool isConstant = false;
6595 QualType T = DR->getType();
6596
6597 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6598 isConstant = AT->getElementType().isConstant(S.Context);
6599 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6600 isConstant = T.isConstant(S.Context) &&
6601 PT->getPointeeType().isConstant(S.Context);
6602 } else if (T->isObjCObjectPointerType()) {
6603 // In ObjC, there is usually no "const ObjectPointer" type,
6604 // so don't check if the pointee type is constant.
6605 isConstant = T.isConstant(S.Context);
6606 }
6607
6608 if (isConstant) {
6609 if (const Expr *Init = VD->getAnyInitializer()) {
6610 // Look through initializers like const char c[] = { "foo" }
6611 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6612 if (InitList->isStringLiteralInit())
6613 Init = InitList->getInit(0)->IgnoreParenImpCasts();
6614 }
6615 return checkFormatStringExpr(
6616 S, ReferenceFormatString, Init, Args, APK, format_idx,
6617 firstDataArg, Type, CallType,
6618 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset);
6619 }
6620 }
6621
6622 // When the format argument is an argument of this function, and this
6623 // function also has the format attribute, there are several interactions
6624 // for which there shouldn't be a warning. For instance, when calling
6625 // v*printf from a function that has the printf format attribute, we
6626 // should not emit a warning about using `fmt`, even though it's not
6627 // constant, because the arguments have already been checked for the
6628 // caller of `logmessage`:
6629 //
6630 // __attribute__((format(printf, 1, 2)))
6631 // void logmessage(char const *fmt, ...) {
6632 // va_list ap;
6633 // va_start(ap, fmt);
6634 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
6635 // ...
6636 // }
6637 //
6638 // Another interaction that we need to support is using a format string
6639 // specified by the format_matches attribute:
6640 //
6641 // __attribute__((format_matches(printf, 1, "%s %d")))
6642 // void logmessage(char const *fmt, const char *a, int b) {
6643 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
6644 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
6645 // ...
6646 // }
6647 //
6648 // Yet another interaction that we need to support is calling a variadic
6649 // format function from a format function that has fixed arguments. For
6650 // instance:
6651 //
6652 // __attribute__((format(printf, 1, 2)))
6653 // void logstring(char const *fmt, char const *str) {
6654 // printf(fmt, str); /* do not emit a warning about "fmt" */
6655 // }
6656 //
6657 // Same (and perhaps more relatably) for the variadic template case:
6658 //
6659 // template<typename... Args>
6660 // __attribute__((format(printf, 1, 2)))
6661 // void log(const char *fmt, Args&&... args) {
6662 // printf(fmt, forward<Args>(args)...);
6663 // /* do not emit a warning about "fmt" */
6664 // }
6665 //
6666 // Due to implementation difficulty, we only check the format, not the
6667 // format arguments, in all cases.
6668 //
6669 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
6670 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
6671 for (const auto *PVFormatMatches :
6672 D->specific_attrs<FormatMatchesAttr>()) {
6673 Sema::FormatStringInfo CalleeFSI;
6674 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
6675 0, &CalleeFSI))
6676 continue;
6677 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
6678 // If using the wrong type of format string, emit a diagnostic
6679 // here and stop checking to avoid irrelevant diagnostics.
6680 if (Type != S.GetFormatStringType(PVFormatMatches)) {
6681 S.Diag(Args[format_idx]->getBeginLoc(),
6682 diag::warn_format_string_type_incompatible)
6683 << PVFormatMatches->getType()->getName()
6685 if (!InFunctionCall) {
6686 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
6687 diag::note_format_string_defined);
6688 }
6689 return SLCT_UncheckedLiteral;
6690 }
6691 return checkFormatStringExpr(
6692 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
6693 Args, APK, format_idx, firstDataArg, Type, CallType,
6694 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
6695 Offset, IgnoreStringsWithoutSpecifiers);
6696 }
6697 }
6698
6699 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
6700 Sema::FormatStringInfo CallerFSI;
6701 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
6702 PVFormat->getFirstArg(), &CallerFSI))
6703 continue;
6704 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
6705 // We also check if the formats are compatible.
6706 // We can't pass a 'scanf' string to a 'printf' function.
6707 if (Type != S.GetFormatStringType(PVFormat)) {
6708 S.Diag(Args[format_idx]->getBeginLoc(),
6709 diag::warn_format_string_type_incompatible)
6710 << PVFormat->getType()->getName()
6712 if (!InFunctionCall) {
6713 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
6714 }
6715 return SLCT_UncheckedLiteral;
6716 }
6717 // Lastly, check that argument passing kinds transition in a
6718 // way that makes sense:
6719 // from a caller with FAPK_VAList, allow FAPK_VAList
6720 // from a caller with FAPK_Fixed, allow FAPK_Fixed
6721 // from a caller with FAPK_Fixed, allow FAPK_Variadic
6722 // from a caller with FAPK_Variadic, allow FAPK_VAList
6723 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
6728 return SLCT_UncheckedLiteral;
6729 }
6730 }
6731 }
6732 }
6733 }
6734 }
6735
6736 return SLCT_NotALiteral;
6737 }
6738
6739 case Stmt::CallExprClass:
6740 case Stmt::CXXMemberCallExprClass: {
6741 const CallExpr *CE = cast<CallExpr>(E);
6742 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6743 bool IsFirst = true;
6744 StringLiteralCheckType CommonResult;
6745 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6746 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6747 StringLiteralCheckType Result = checkFormatStringExpr(
6748 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6749 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6750 Offset, IgnoreStringsWithoutSpecifiers);
6751 if (IsFirst) {
6752 CommonResult = Result;
6753 IsFirst = false;
6754 }
6755 }
6756 if (!IsFirst)
6757 return CommonResult;
6758
6759 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6760 unsigned BuiltinID = FD->getBuiltinID();
6761 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6762 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6763 const Expr *Arg = CE->getArg(0);
6764 return checkFormatStringExpr(
6765 S, ReferenceFormatString, Arg, Args, APK, format_idx,
6766 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6767 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6768 }
6769 }
6770 }
6771 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
6772 return checkFormatStringExpr(
6773 S, ReferenceFormatString, SLE, Args, APK, format_idx, firstDataArg,
6774 Type, CallType, /*InFunctionCall*/ false, CheckedVarArgs,
6775 UncoveredArg, Offset, IgnoreStringsWithoutSpecifiers);
6776 return SLCT_NotALiteral;
6777 }
6778 case Stmt::ObjCMessageExprClass: {
6779 const auto *ME = cast<ObjCMessageExpr>(E);
6780 if (const auto *MD = ME->getMethodDecl()) {
6781 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
6782 // As a special case heuristic, if we're using the method -[NSBundle
6783 // localizedStringForKey:value:table:], ignore any key strings that lack
6784 // format specifiers. The idea is that if the key doesn't have any
6785 // format specifiers then its probably just a key to map to the
6786 // localized strings. If it does have format specifiers though, then its
6787 // likely that the text of the key is the format string in the
6788 // programmer's language, and should be checked.
6789 const ObjCInterfaceDecl *IFace;
6790 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
6791 IFace->getIdentifier()->isStr("NSBundle") &&
6792 MD->getSelector().isKeywordSelector(
6793 {"localizedStringForKey", "value", "table"})) {
6794 IgnoreStringsWithoutSpecifiers = true;
6795 }
6796
6797 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6798 return checkFormatStringExpr(
6799 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
6800 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
6801 Offset, IgnoreStringsWithoutSpecifiers);
6802 }
6803 }
6804
6805 return SLCT_NotALiteral;
6806 }
6807 case Stmt::ObjCStringLiteralClass:
6808 case Stmt::StringLiteralClass: {
6809 const StringLiteral *StrE = nullptr;
6810
6811 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6812 StrE = ObjCFExpr->getString();
6813 else
6814 StrE = cast<StringLiteral>(E);
6815
6816 if (StrE) {
6817 if (Offset.isNegative() || Offset > StrE->getLength()) {
6818 // TODO: It would be better to have an explicit warning for out of
6819 // bounds literals.
6820 return SLCT_NotALiteral;
6821 }
6822 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6823 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
6824 format_idx, firstDataArg, Type, InFunctionCall,
6825 CallType, CheckedVarArgs, UncoveredArg,
6826 IgnoreStringsWithoutSpecifiers);
6827 return SLCT_CheckedLiteral;
6828 }
6829
6830 return SLCT_NotALiteral;
6831 }
6832 case Stmt::BinaryOperatorClass: {
6833 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6834
6835 // A string literal + an int offset is still a string literal.
6836 if (BinOp->isAdditiveOp()) {
6837 Expr::EvalResult LResult, RResult;
6838
6839 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
6840 LResult, S.Context, Expr::SE_NoSideEffects,
6842 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
6843 RResult, S.Context, Expr::SE_NoSideEffects,
6845
6846 if (LIsInt != RIsInt) {
6847 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6848
6849 if (LIsInt) {
6850 if (BinOpKind == BO_Add) {
6851 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6852 E = BinOp->getRHS();
6853 goto tryAgain;
6854 }
6855 } else {
6856 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6857 E = BinOp->getLHS();
6858 goto tryAgain;
6859 }
6860 }
6861 }
6862
6863 return SLCT_NotALiteral;
6864 }
6865 case Stmt::UnaryOperatorClass: {
6866 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6867 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6868 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6869 Expr::EvalResult IndexResult;
6870 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
6873 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6874 /*RHS is int*/ true);
6875 E = ASE->getBase();
6876 goto tryAgain;
6877 }
6878 }
6879
6880 return SLCT_NotALiteral;
6881 }
6882
6883 default:
6884 return SLCT_NotALiteral;
6885 }
6886}
6887
6888// If this expression can be evaluated at compile-time,
6889// check if the result is a StringLiteral and return it
6890// otherwise return nullptr
6892 const Expr *E) {
6893 Expr::EvalResult Result;
6894 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
6895 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
6896 if (isa_and_nonnull<StringLiteral>(LVE))
6897 return LVE;
6898 }
6899 return nullptr;
6900}
6901
6903 switch (FST) {
6905 return "scanf";
6907 return "printf";
6909 return "NSString";
6911 return "strftime";
6913 return "strfmon";
6915 return "kprintf";
6917 return "freebsd_kprintf";
6919 return "os_log";
6920 default:
6921 return "<unknown>";
6922 }
6923}
6924
6926 return llvm::StringSwitch<FormatStringType>(Flavor)
6927 .Cases("gnu_scanf", "scanf", FormatStringType::Scanf)
6928 .Cases("gnu_printf", "printf", "printf0", "syslog",
6930 .Cases("NSString", "CFString", FormatStringType::NSString)
6931 .Cases("gnu_strftime", "strftime", FormatStringType::Strftime)
6932 .Cases("gnu_strfmon", "strfmon", FormatStringType::Strfmon)
6933 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err",
6935 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
6936 .Case("os_trace", FormatStringType::OSLog)
6937 .Case("os_log", FormatStringType::OSLog)
6938 .Default(FormatStringType::Unknown);
6939}
6940
6942 return GetFormatStringType(Format->getType()->getName());
6943}
6944
6945FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
6946 return GetFormatStringType(Format->getType()->getName());
6947}
6948
6949bool Sema::CheckFormatArguments(const FormatAttr *Format,
6950 ArrayRef<const Expr *> Args, bool IsCXXMember,
6951 VariadicCallType CallType, SourceLocation Loc,
6952 SourceRange Range,
6953 llvm::SmallBitVector &CheckedVarArgs) {
6954 FormatStringInfo FSI;
6955 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
6956 IsCXXMember,
6957 CallType != VariadicCallType::DoesNotApply, &FSI))
6958 return CheckFormatArguments(
6959 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
6960 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
6961 return false;
6962}
6963
6964bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
6965 ArrayRef<const Expr *> Args, bool IsCXXMember,
6966 VariadicCallType CallType, SourceLocation Loc,
6967 SourceRange Range,
6968 llvm::SmallBitVector &CheckedVarArgs) {
6969 FormatStringInfo FSI;
6970 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
6971 &FSI)) {
6972 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
6973 return CheckFormatArguments(Args, FSI.ArgPassingKind,
6974 Format->getFormatString(), FSI.FormatIdx,
6975 FSI.FirstDataArg, GetFormatStringType(Format),
6976 CallType, Loc, Range, CheckedVarArgs);
6977 }
6978 return false;
6979}
6980
6981bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6983 const StringLiteral *ReferenceFormatString,
6984 unsigned format_idx, unsigned firstDataArg,
6986 VariadicCallType CallType, SourceLocation Loc,
6987 SourceRange Range,
6988 llvm::SmallBitVector &CheckedVarArgs) {
6989 // CHECK: printf/scanf-like function is called with no format string.
6990 if (format_idx >= Args.size()) {
6991 Diag(Loc, diag::warn_missing_format_string) << Range;
6992 return false;
6993 }
6994
6995 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6996
6997 // CHECK: format string is not a string literal.
6998 //
6999 // Dynamically generated format strings are difficult to
7000 // automatically vet at compile time. Requiring that format strings
7001 // are string literals: (1) permits the checking of format strings by
7002 // the compiler and thereby (2) can practically remove the source of
7003 // many format string exploits.
7004
7005 // Format string can be either ObjC string (e.g. @"%d") or
7006 // C string (e.g. "%d")
7007 // ObjC string uses the same format specifiers as C string, so we can use
7008 // the same format string checking logic for both ObjC and C strings.
7009 UncoveredArgHandler UncoveredArg;
7010 StringLiteralCheckType CT = checkFormatStringExpr(
7011 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7012 firstDataArg, Type, CallType,
7013 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
7014 /*no string offset*/ llvm::APSInt(64, false) = 0);
7015
7016 // Generate a diagnostic where an uncovered argument is detected.
7017 if (UncoveredArg.hasUncoveredArg()) {
7018 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7019 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7020 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7021 }
7022
7023 if (CT != SLCT_NotALiteral)
7024 // Literal format string found, check done!
7025 return CT == SLCT_CheckedLiteral;
7026
7027 // Strftime is particular as it always uses a single 'time' argument,
7028 // so it is safe to pass a non-literal string.
7030 return false;
7031
7032 // Do not emit diag when the string param is a macro expansion and the
7033 // format is either NSString or CFString. This is a hack to prevent
7034 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7035 // which are usually used in place of NS and CF string literals.
7036 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7038 SourceMgr.isInSystemMacro(FormatLoc))
7039 return false;
7040
7041 // If there are no arguments specified, warn with -Wformat-security, otherwise
7042 // warn only with -Wformat-nonliteral.
7043 if (Args.size() == firstDataArg) {
7044 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7045 << OrigFormatExpr->getSourceRange();
7046 switch (Type) {
7047 default:
7048 break;
7052 Diag(FormatLoc, diag::note_format_security_fixit)
7053 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7054 break;
7056 Diag(FormatLoc, diag::note_format_security_fixit)
7057 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7058 break;
7059 }
7060 } else {
7061 Diag(FormatLoc, diag::warn_format_nonliteral)
7062 << OrigFormatExpr->getSourceRange();
7063 }
7064 return false;
7065}
7066
7067namespace {
7068
7069class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7070protected:
7071 Sema &S;
7072 const FormatStringLiteral *FExpr;
7073 const Expr *OrigFormatExpr;
7074 const FormatStringType FSType;
7075 const unsigned FirstDataArg;
7076 const unsigned NumDataArgs;
7077 const char *Beg; // Start of format string.
7078 const Sema::FormatArgumentPassingKind ArgPassingKind;
7079 ArrayRef<const Expr *> Args;
7080 unsigned FormatIdx;
7081 llvm::SmallBitVector CoveredArgs;
7082 bool usesPositionalArgs = false;
7083 bool atFirstArg = true;
7084 bool inFunctionCall;
7085 VariadicCallType CallType;
7086 llvm::SmallBitVector &CheckedVarArgs;
7087 UncoveredArgHandler &UncoveredArg;
7088
7089public:
7090 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7091 const Expr *origFormatExpr, const FormatStringType type,
7092 unsigned firstDataArg, unsigned numDataArgs,
7093 const char *beg, Sema::FormatArgumentPassingKind APK,
7094 ArrayRef<const Expr *> Args, unsigned formatIdx,
7095 bool inFunctionCall, VariadicCallType callType,
7096 llvm::SmallBitVector &CheckedVarArgs,
7097 UncoveredArgHandler &UncoveredArg)
7098 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7099 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7100 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7101 inFunctionCall(inFunctionCall), CallType(callType),
7102 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7103 CoveredArgs.resize(numDataArgs);
7104 CoveredArgs.reset();
7105 }
7106
7107 bool HasFormatArguments() const {
7108 return ArgPassingKind == Sema::FAPK_Fixed ||
7109 ArgPassingKind == Sema::FAPK_Variadic;
7110 }
7111
7112 void DoneProcessing();
7113
7114 void HandleIncompleteSpecifier(const char *startSpecifier,
7115 unsigned specifierLen) override;
7116
7117 void HandleInvalidLengthModifier(
7118 const analyze_format_string::FormatSpecifier &FS,
7119 const analyze_format_string::ConversionSpecifier &CS,
7120 const char *startSpecifier, unsigned specifierLen,
7121 unsigned DiagID);
7122
7123 void HandleNonStandardLengthModifier(
7124 const analyze_format_string::FormatSpecifier &FS,
7125 const char *startSpecifier, unsigned specifierLen);
7126
7127 void HandleNonStandardConversionSpecifier(
7128 const analyze_format_string::ConversionSpecifier &CS,
7129 const char *startSpecifier, unsigned specifierLen);
7130
7131 void HandlePosition(const char *startPos, unsigned posLen) override;
7132
7133 void HandleInvalidPosition(const char *startSpecifier,
7134 unsigned specifierLen,
7136
7137 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7138
7139 void HandleNullChar(const char *nullCharacter) override;
7140
7141 template <typename Range>
7142 static void
7143 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7144 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7145 bool IsStringLocation, Range StringRange,
7146 ArrayRef<FixItHint> Fixit = {});
7147
7148protected:
7149 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7150 const char *startSpec,
7151 unsigned specifierLen,
7152 const char *csStart, unsigned csLen);
7153
7154 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7155 const char *startSpec,
7156 unsigned specifierLen);
7157
7158 SourceRange getFormatStringRange();
7159 CharSourceRange getSpecifierRange(const char *startSpecifier,
7160 unsigned specifierLen);
7161 SourceLocation getLocationOfByte(const char *x);
7162
7163 const Expr *getDataArg(unsigned i) const;
7164
7165 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7166 const analyze_format_string::ConversionSpecifier &CS,
7167 const char *startSpecifier, unsigned specifierLen,
7168 unsigned argIndex);
7169
7170 template <typename Range>
7171 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7172 bool IsStringLocation, Range StringRange,
7173 ArrayRef<FixItHint> Fixit = {});
7174};
7175
7176} // namespace
7177
7178SourceRange CheckFormatHandler::getFormatStringRange() {
7179 return OrigFormatExpr->getSourceRange();
7180}
7181
7182CharSourceRange CheckFormatHandler::
7183getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7184 SourceLocation Start = getLocationOfByte(startSpecifier);
7185 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
7186
7187 // Advance the end SourceLocation by one due to half-open ranges.
7188 End = End.getLocWithOffset(1);
7189
7190 return CharSourceRange::getCharRange(Start, End);
7191}
7192
7193SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7194 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7196}
7197
7198void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7199 unsigned specifierLen){
7200 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7201 getLocationOfByte(startSpecifier),
7202 /*IsStringLocation*/true,
7203 getSpecifierRange(startSpecifier, specifierLen));
7204}
7205
7206void CheckFormatHandler::HandleInvalidLengthModifier(
7209 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7210 using namespace analyze_format_string;
7211
7212 const LengthModifier &LM = FS.getLengthModifier();
7213 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7214
7215 // See if we know how to fix this length modifier.
7216 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7217 if (FixedLM) {
7218 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7219 getLocationOfByte(LM.getStart()),
7220 /*IsStringLocation*/true,
7221 getSpecifierRange(startSpecifier, specifierLen));
7222
7223 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7224 << FixedLM->toString()
7225 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7226
7227 } else {
7228 FixItHint Hint;
7229 if (DiagID == diag::warn_format_nonsensical_length)
7230 Hint = FixItHint::CreateRemoval(LMRange);
7231
7232 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7233 getLocationOfByte(LM.getStart()),
7234 /*IsStringLocation*/true,
7235 getSpecifierRange(startSpecifier, specifierLen),
7236 Hint);
7237 }
7238}
7239
7240void CheckFormatHandler::HandleNonStandardLengthModifier(
7242 const char *startSpecifier, unsigned specifierLen) {
7243 using namespace analyze_format_string;
7244
7245 const LengthModifier &LM = FS.getLengthModifier();
7246 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7247
7248 // See if we know how to fix this length modifier.
7249 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7250 if (FixedLM) {
7251 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7252 << LM.toString() << 0,
7253 getLocationOfByte(LM.getStart()),
7254 /*IsStringLocation*/true,
7255 getSpecifierRange(startSpecifier, specifierLen));
7256
7257 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7258 << FixedLM->toString()
7259 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7260
7261 } else {
7262 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7263 << LM.toString() << 0,
7264 getLocationOfByte(LM.getStart()),
7265 /*IsStringLocation*/true,
7266 getSpecifierRange(startSpecifier, specifierLen));
7267 }
7268}
7269
7270void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7272 const char *startSpecifier, unsigned specifierLen) {
7273 using namespace analyze_format_string;
7274
7275 // See if we know how to fix this conversion specifier.
7276 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7277 if (FixedCS) {
7278 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7279 << CS.toString() << /*conversion specifier*/1,
7280 getLocationOfByte(CS.getStart()),
7281 /*IsStringLocation*/true,
7282 getSpecifierRange(startSpecifier, specifierLen));
7283
7284 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7285 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7286 << FixedCS->toString()
7287 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7288 } else {
7289 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7290 << CS.toString() << /*conversion specifier*/1,
7291 getLocationOfByte(CS.getStart()),
7292 /*IsStringLocation*/true,
7293 getSpecifierRange(startSpecifier, specifierLen));
7294 }
7295}
7296
7297void CheckFormatHandler::HandlePosition(const char *startPos,
7298 unsigned posLen) {
7299 if (!S.getDiagnostics().isIgnored(
7300 diag::warn_format_non_standard_positional_arg, SourceLocation()))
7301 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7302 getLocationOfByte(startPos),
7303 /*IsStringLocation*/ true,
7304 getSpecifierRange(startPos, posLen));
7305}
7306
7307void CheckFormatHandler::HandleInvalidPosition(
7308 const char *startSpecifier, unsigned specifierLen,
7310 if (!S.getDiagnostics().isIgnored(
7311 diag::warn_format_invalid_positional_specifier, SourceLocation()))
7312 EmitFormatDiagnostic(
7313 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7314 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
7315 getSpecifierRange(startSpecifier, specifierLen));
7316}
7317
7318void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7319 unsigned posLen) {
7320 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
7321 SourceLocation()))
7322 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7323 getLocationOfByte(startPos),
7324 /*IsStringLocation*/ true,
7325 getSpecifierRange(startPos, posLen));
7326}
7327
7328void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7329 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7330 // The presence of a null character is likely an error.
7331 EmitFormatDiagnostic(
7332 S.PDiag(diag::warn_printf_format_string_contains_null_char),
7333 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7334 getFormatStringRange());
7335 }
7336}
7337
7338// Note that this may return NULL if there was an error parsing or building
7339// one of the argument expressions.
7340const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7341 return Args[FirstDataArg + i];
7342}
7343
7344void CheckFormatHandler::DoneProcessing() {
7345 // Does the number of data arguments exceed the number of
7346 // format conversions in the format string?
7347 if (HasFormatArguments()) {
7348 // Find any arguments that weren't covered.
7349 CoveredArgs.flip();
7350 signed notCoveredArg = CoveredArgs.find_first();
7351 if (notCoveredArg >= 0) {
7352 assert((unsigned)notCoveredArg < NumDataArgs);
7353 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7354 } else {
7355 UncoveredArg.setAllCovered();
7356 }
7357 }
7358}
7359
7360void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7361 const Expr *ArgExpr) {
7362 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7363 "Invalid state");
7364
7365 if (!ArgExpr)
7366 return;
7367
7368 SourceLocation Loc = ArgExpr->getBeginLoc();
7369
7370 if (S.getSourceManager().isInSystemMacro(Loc))
7371 return;
7372
7373 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7374 for (auto E : DiagnosticExprs)
7375 PDiag << E->getSourceRange();
7376
7377 CheckFormatHandler::EmitFormatDiagnostic(
7378 S, IsFunctionCall, DiagnosticExprs[0],
7379 PDiag, Loc, /*IsStringLocation*/false,
7380 DiagnosticExprs[0]->getSourceRange());
7381}
7382
7383bool
7384CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7385 SourceLocation Loc,
7386 const char *startSpec,
7387 unsigned specifierLen,
7388 const char *csStart,
7389 unsigned csLen) {
7390 bool keepGoing = true;
7391 if (argIndex < NumDataArgs) {
7392 // Consider the argument coverered, even though the specifier doesn't
7393 // make sense.
7394 CoveredArgs.set(argIndex);
7395 }
7396 else {
7397 // If argIndex exceeds the number of data arguments we
7398 // don't issue a warning because that is just a cascade of warnings (and
7399 // they may have intended '%%' anyway). We don't want to continue processing
7400 // the format string after this point, however, as we will like just get
7401 // gibberish when trying to match arguments.
7402 keepGoing = false;
7403 }
7404
7405 StringRef Specifier(csStart, csLen);
7406
7407 // If the specifier in non-printable, it could be the first byte of a UTF-8
7408 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7409 // hex value.
7410 std::string CodePointStr;
7411 if (!llvm::sys::locale::isPrint(*csStart)) {
7412 llvm::UTF32 CodePoint;
7413 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7414 const llvm::UTF8 *E =
7415 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7416 llvm::ConversionResult Result =
7417 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7418
7419 if (Result != llvm::conversionOK) {
7420 unsigned char FirstChar = *csStart;
7421 CodePoint = (llvm::UTF32)FirstChar;
7422 }
7423
7424 llvm::raw_string_ostream OS(CodePointStr);
7425 if (CodePoint < 256)
7426 OS << "\\x" << llvm::format("%02x", CodePoint);
7427 else if (CodePoint <= 0xFFFF)
7428 OS << "\\u" << llvm::format("%04x", CodePoint);
7429 else
7430 OS << "\\U" << llvm::format("%08x", CodePoint);
7431 Specifier = CodePointStr;
7432 }
7433
7434 EmitFormatDiagnostic(
7435 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7436 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7437
7438 return keepGoing;
7439}
7440
7441void
7442CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7443 const char *startSpec,
7444 unsigned specifierLen) {
7445 EmitFormatDiagnostic(
7446 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7447 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7448}
7449
7450bool
7451CheckFormatHandler::CheckNumArgs(
7454 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7455
7456 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7458 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7459 << (argIndex+1) << NumDataArgs)
7460 : S.PDiag(diag::warn_printf_insufficient_data_args);
7461 EmitFormatDiagnostic(
7462 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7463 getSpecifierRange(startSpecifier, specifierLen));
7464
7465 // Since more arguments than conversion tokens are given, by extension
7466 // all arguments are covered, so mark this as so.
7467 UncoveredArg.setAllCovered();
7468 return false;
7469 }
7470 return true;
7471}
7472
7473template<typename Range>
7474void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7475 SourceLocation Loc,
7476 bool IsStringLocation,
7477 Range StringRange,
7478 ArrayRef<FixItHint> FixIt) {
7479 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7480 Loc, IsStringLocation, StringRange, FixIt);
7481}
7482
7483/// If the format string is not within the function call, emit a note
7484/// so that the function call and string are in diagnostic messages.
7485///
7486/// \param InFunctionCall if true, the format string is within the function
7487/// call and only one diagnostic message will be produced. Otherwise, an
7488/// extra note will be emitted pointing to location of the format string.
7489///
7490/// \param ArgumentExpr the expression that is passed as the format string
7491/// argument in the function call. Used for getting locations when two
7492/// diagnostics are emitted.
7493///
7494/// \param PDiag the callee should already have provided any strings for the
7495/// diagnostic message. This function only adds locations and fixits
7496/// to diagnostics.
7497///
7498/// \param Loc primary location for diagnostic. If two diagnostics are
7499/// required, one will be at Loc and a new SourceLocation will be created for
7500/// the other one.
7501///
7502/// \param IsStringLocation if true, Loc points to the format string should be
7503/// used for the note. Otherwise, Loc points to the argument list and will
7504/// be used with PDiag.
7505///
7506/// \param StringRange some or all of the string to highlight. This is
7507/// templated so it can accept either a CharSourceRange or a SourceRange.
7508///
7509/// \param FixIt optional fix it hint for the format string.
7510template <typename Range>
7511void CheckFormatHandler::EmitFormatDiagnostic(
7512 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7513 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7514 Range StringRange, ArrayRef<FixItHint> FixIt) {
7515 if (InFunctionCall) {
7516 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7517 D << StringRange;
7518 D << FixIt;
7519 } else {
7520 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7521 << ArgumentExpr->getSourceRange();
7522
7524 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7525 diag::note_format_string_defined);
7526
7527 Note << StringRange;
7528 Note << FixIt;
7529 }
7530}
7531
7532//===--- CHECK: Printf format string checking -----------------------------===//
7533
7534namespace {
7535
7536class CheckPrintfHandler : public CheckFormatHandler {
7537public:
7538 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7539 const Expr *origFormatExpr, const FormatStringType type,
7540 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
7541 const char *beg, Sema::FormatArgumentPassingKind APK,
7542 ArrayRef<const Expr *> Args, unsigned formatIdx,
7543 bool inFunctionCall, VariadicCallType CallType,
7544 llvm::SmallBitVector &CheckedVarArgs,
7545 UncoveredArgHandler &UncoveredArg)
7546 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7547 numDataArgs, beg, APK, Args, formatIdx,
7548 inFunctionCall, CallType, CheckedVarArgs,
7549 UncoveredArg) {}
7550
7551 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
7552
7553 /// Returns true if '%@' specifiers are allowed in the format string.
7554 bool allowsObjCArg() const {
7555 return FSType == FormatStringType::NSString ||
7556 FSType == FormatStringType::OSLog ||
7557 FSType == FormatStringType::OSTrace;
7558 }
7559
7560 bool HandleInvalidPrintfConversionSpecifier(
7561 const analyze_printf::PrintfSpecifier &FS,
7562 const char *startSpecifier,
7563 unsigned specifierLen) override;
7564
7565 void handleInvalidMaskType(StringRef MaskType) override;
7566
7567 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7568 const char *startSpecifier, unsigned specifierLen,
7569 const TargetInfo &Target) override;
7570 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7571 const char *StartSpecifier,
7572 unsigned SpecifierLen,
7573 const Expr *E);
7574
7575 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7576 const char *startSpecifier, unsigned specifierLen);
7577 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7578 const analyze_printf::OptionalAmount &Amt,
7579 unsigned type,
7580 const char *startSpecifier, unsigned specifierLen);
7581 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7582 const analyze_printf::OptionalFlag &flag,
7583 const char *startSpecifier, unsigned specifierLen);
7584 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7585 const analyze_printf::OptionalFlag &ignoredFlag,
7586 const analyze_printf::OptionalFlag &flag,
7587 const char *startSpecifier, unsigned specifierLen);
7588 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7589 const Expr *E);
7590
7591 void HandleEmptyObjCModifierFlag(const char *startFlag,
7592 unsigned flagLen) override;
7593
7594 void HandleInvalidObjCModifierFlag(const char *startFlag,
7595 unsigned flagLen) override;
7596
7597 void
7598 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7599 const char *flagsEnd,
7600 const char *conversionPosition) override;
7601};
7602
7603/// Keeps around the information needed to verify that two specifiers are
7604/// compatible.
7605class EquatableFormatArgument {
7606public:
7607 enum SpecifierSensitivity : unsigned {
7608 SS_None,
7609 SS_Private,
7610 SS_Public,
7611 SS_Sensitive
7612 };
7613
7614 enum FormatArgumentRole : unsigned {
7615 FAR_Data,
7616 FAR_FieldWidth,
7617 FAR_Precision,
7618 FAR_Auxiliary, // FreeBSD kernel %b and %D
7619 };
7620
7621private:
7622 analyze_format_string::ArgType ArgType;
7624 StringRef SpecifierLetter;
7625 CharSourceRange Range;
7626 SourceLocation ElementLoc;
7627 FormatArgumentRole Role : 2;
7628 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
7629 unsigned Position : 14;
7630 unsigned ModifierFor : 14; // not set for FAR_Data
7631
7632 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
7633 bool InFunctionCall) const;
7634
7635public:
7636 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
7638 StringRef SpecifierLetter,
7639 analyze_format_string::ArgType ArgType,
7640 FormatArgumentRole Role,
7641 SpecifierSensitivity Sensitivity, unsigned Position,
7642 unsigned ModifierFor)
7643 : ArgType(ArgType), LengthMod(LengthMod),
7644 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
7645 Role(Role), Sensitivity(Sensitivity), Position(Position),
7646 ModifierFor(ModifierFor) {}
7647
7648 unsigned getPosition() const { return Position; }
7649 SourceLocation getSourceLocation() const { return ElementLoc; }
7650 CharSourceRange getSourceRange() const { return Range; }
7651 analyze_format_string::LengthModifier getLengthModifier() const {
7652 return analyze_format_string::LengthModifier(nullptr, LengthMod);
7653 }
7654 void setModifierFor(unsigned V) { ModifierFor = V; }
7655
7656 std::string buildFormatSpecifier() const {
7657 std::string result;
7658 llvm::raw_string_ostream(result)
7659 << getLengthModifier().toString() << SpecifierLetter;
7660 return result;
7661 }
7662
7663 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
7664 const Expr *FmtExpr, bool InFunctionCall) const;
7665};
7666
7667/// Turns format strings into lists of EquatableSpecifier objects.
7668class DecomposePrintfHandler : public CheckPrintfHandler {
7669 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
7670 bool HadError;
7671
7672 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7673 const Expr *origFormatExpr,
7674 const FormatStringType type, unsigned firstDataArg,
7675 unsigned numDataArgs, bool isObjC, const char *beg,
7677 ArrayRef<const Expr *> Args, unsigned formatIdx,
7678 bool inFunctionCall, VariadicCallType CallType,
7679 llvm::SmallBitVector &CheckedVarArgs,
7680 UncoveredArgHandler &UncoveredArg,
7681 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
7682 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7683 numDataArgs, isObjC, beg, APK, Args, formatIdx,
7684 inFunctionCall, CallType, CheckedVarArgs,
7685 UncoveredArg),
7686 Specs(Specs), HadError(false) {}
7687
7688public:
7689 static bool
7690 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7691 FormatStringType type, bool IsObjC, bool InFunctionCall,
7692 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
7693
7694 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7695 const char *startSpecifier,
7696 unsigned specifierLen,
7697 const TargetInfo &Target) override;
7698};
7699
7700} // namespace
7701
7702bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7703 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7704 unsigned specifierLen) {
7707
7708 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7709 getLocationOfByte(CS.getStart()),
7710 startSpecifier, specifierLen,
7711 CS.getStart(), CS.getLength());
7712}
7713
7714void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7715 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7716}
7717
7718// Error out if struct or complex type argments are passed to os_log.
7720 QualType T) {
7721 if (FSType != FormatStringType::OSLog)
7722 return false;
7723 return T->isRecordType() || T->isComplexType();
7724}
7725
7726bool CheckPrintfHandler::HandleAmount(
7727 const analyze_format_string::OptionalAmount &Amt, unsigned k,
7728 const char *startSpecifier, unsigned specifierLen) {
7729 if (Amt.hasDataArgument()) {
7730 if (HasFormatArguments()) {
7731 unsigned argIndex = Amt.getArgIndex();
7732 if (argIndex >= NumDataArgs) {
7733 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7734 << k,
7735 getLocationOfByte(Amt.getStart()),
7736 /*IsStringLocation*/ true,
7737 getSpecifierRange(startSpecifier, specifierLen));
7738 // Don't do any more checking. We will just emit
7739 // spurious errors.
7740 return false;
7741 }
7742
7743 // Type check the data argument. It should be an 'int'.
7744 // Although not in conformance with C99, we also allow the argument to be
7745 // an 'unsigned int' as that is a reasonably safe case. GCC also
7746 // doesn't emit a warning for that case.
7747 CoveredArgs.set(argIndex);
7748 const Expr *Arg = getDataArg(argIndex);
7749 if (!Arg)
7750 return false;
7751
7752 QualType T = Arg->getType();
7753
7754 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7755 assert(AT.isValid());
7756
7757 if (!AT.matchesType(S.Context, T)) {
7758 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
7759 ? diag::err_printf_asterisk_wrong_type
7760 : diag::warn_printf_asterisk_wrong_type;
7761 EmitFormatDiagnostic(S.PDiag(DiagID)
7763 << T << Arg->getSourceRange(),
7764 getLocationOfByte(Amt.getStart()),
7765 /*IsStringLocation*/ true,
7766 getSpecifierRange(startSpecifier, specifierLen));
7767 // Don't do any more checking. We will just emit
7768 // spurious errors.
7769 return false;
7770 }
7771 }
7772 }
7773 return true;
7774}
7775
7776void CheckPrintfHandler::HandleInvalidAmount(
7779 unsigned type,
7780 const char *startSpecifier,
7781 unsigned specifierLen) {
7784
7785 FixItHint fixit =
7787 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7788 Amt.getConstantLength()))
7789 : FixItHint();
7790
7791 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7792 << type << CS.toString(),
7793 getLocationOfByte(Amt.getStart()),
7794 /*IsStringLocation*/true,
7795 getSpecifierRange(startSpecifier, specifierLen),
7796 fixit);
7797}
7798
7799void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7800 const analyze_printf::OptionalFlag &flag,
7801 const char *startSpecifier,
7802 unsigned specifierLen) {
7803 // Warn about pointless flag with a fixit removal.
7806 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7807 << flag.toString() << CS.toString(),
7808 getLocationOfByte(flag.getPosition()),
7809 /*IsStringLocation*/true,
7810 getSpecifierRange(startSpecifier, specifierLen),
7812 getSpecifierRange(flag.getPosition(), 1)));
7813}
7814
7815void CheckPrintfHandler::HandleIgnoredFlag(
7817 const analyze_printf::OptionalFlag &ignoredFlag,
7818 const analyze_printf::OptionalFlag &flag,
7819 const char *startSpecifier,
7820 unsigned specifierLen) {
7821 // Warn about ignored flag with a fixit removal.
7822 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7823 << ignoredFlag.toString() << flag.toString(),
7824 getLocationOfByte(ignoredFlag.getPosition()),
7825 /*IsStringLocation*/true,
7826 getSpecifierRange(startSpecifier, specifierLen),
7828 getSpecifierRange(ignoredFlag.getPosition(), 1)));
7829}
7830
7831void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7832 unsigned flagLen) {
7833 // Warn about an empty flag.
7834 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7835 getLocationOfByte(startFlag),
7836 /*IsStringLocation*/true,
7837 getSpecifierRange(startFlag, flagLen));
7838}
7839
7840void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7841 unsigned flagLen) {
7842 // Warn about an invalid flag.
7843 auto Range = getSpecifierRange(startFlag, flagLen);
7844 StringRef flag(startFlag, flagLen);
7845 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7846 getLocationOfByte(startFlag),
7847 /*IsStringLocation*/true,
7848 Range, FixItHint::CreateRemoval(Range));
7849}
7850
7851void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7852 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7853 // Warn about using '[...]' without a '@' conversion.
7854 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7855 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7856 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7857 getLocationOfByte(conversionPosition),
7858 /*IsStringLocation*/ true, Range,
7860}
7861
7862void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
7863 const Expr *FmtExpr,
7864 bool InFunctionCall) const {
7865 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
7866 ElementLoc, true, Range);
7867}
7868
7869bool EquatableFormatArgument::VerifyCompatible(
7870 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
7871 bool InFunctionCall) const {
7873 if (Role != Other.Role) {
7874 // diagnose and stop
7875 EmitDiagnostic(
7876 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
7877 FmtExpr, InFunctionCall);
7878 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
7879 return false;
7880 }
7881
7882 if (Role != FAR_Data) {
7883 if (ModifierFor != Other.ModifierFor) {
7884 // diagnose and stop
7885 EmitDiagnostic(S,
7886 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
7887 << (ModifierFor + 1) << (Other.ModifierFor + 1),
7888 FmtExpr, InFunctionCall);
7889 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
7890 return false;
7891 }
7892 return true;
7893 }
7894
7895 bool HadError = false;
7896 if (Sensitivity != Other.Sensitivity) {
7897 // diagnose and continue
7898 EmitDiagnostic(S,
7899 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
7900 << Sensitivity << Other.Sensitivity,
7901 FmtExpr, InFunctionCall);
7902 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7903 << 0 << Other.Range;
7904 }
7905
7906 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
7907 case MK::Match:
7908 break;
7909
7910 case MK::MatchPromotion:
7911 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
7912 // MatchPromotion is treated as a failure by format_matches.
7913 case MK::NoMatch:
7914 case MK::NoMatchTypeConfusion:
7915 case MK::NoMatchPromotionTypeConfusion:
7916 EmitDiagnostic(S,
7917 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
7918 << buildFormatSpecifier()
7919 << Other.buildFormatSpecifier(),
7920 FmtExpr, InFunctionCall);
7921 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7922 << 0 << Other.Range;
7923 break;
7924
7925 case MK::NoMatchPedantic:
7926 EmitDiagnostic(S,
7927 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
7928 << buildFormatSpecifier()
7929 << Other.buildFormatSpecifier(),
7930 FmtExpr, InFunctionCall);
7931 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7932 << 0 << Other.Range;
7933 break;
7934
7935 case MK::NoMatchSignedness:
7936 EmitDiagnostic(S,
7937 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
7938 << buildFormatSpecifier()
7939 << Other.buildFormatSpecifier(),
7940 FmtExpr, InFunctionCall);
7941 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
7942 << 0 << Other.Range;
7943 break;
7944 }
7945 return !HadError;
7946}
7947
7948bool DecomposePrintfHandler::GetSpecifiers(
7949 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
7950 FormatStringType Type, bool IsObjC, bool InFunctionCall,
7952 StringRef Data = FSL->getString();
7953 const char *Str = Data.data();
7954 llvm::SmallBitVector BV;
7955 UncoveredArgHandler UA;
7956 const Expr *PrintfArgs[] = {FSL->getFormatString()};
7957 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
7958 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
7959 InFunctionCall, VariadicCallType::DoesNotApply, BV,
7960 UA, Args);
7961
7963 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
7965 H.DoneProcessing();
7966 if (H.HadError)
7967 return false;
7968
7969 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
7970 const EquatableFormatArgument &B) {
7971 return A.getPosition() < B.getPosition();
7972 });
7973 return true;
7974}
7975
7976bool DecomposePrintfHandler::HandlePrintfSpecifier(
7977 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
7978 unsigned specifierLen, const TargetInfo &Target) {
7979 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
7980 specifierLen, Target)) {
7981 HadError = true;
7982 return false;
7983 }
7984
7985 // Do not add any specifiers to the list for %%. This is possibly incorrect
7986 // if using a precision/width with a data argument, but that combination is
7987 // meaningless and we wouldn't know which format to attach the
7988 // precision/width to.
7989 const auto &CS = FS.getConversionSpecifier();
7991 return true;
7992
7993 // have to patch these to have the right ModifierFor if they are used
7994 const unsigned Unset = ~0;
7995 unsigned FieldWidthIndex = Unset;
7996 unsigned PrecisionIndex = Unset;
7997
7998 // field width?
7999 const auto &FieldWidth = FS.getFieldWidth();
8000 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8001 FieldWidthIndex = Specs.size();
8002 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8003 getLocationOfByte(FieldWidth.getStart()),
8005 FieldWidth.getArgType(S.Context),
8006 EquatableFormatArgument::FAR_FieldWidth,
8007 EquatableFormatArgument::SS_None,
8008 FieldWidth.usesPositionalArg()
8009 ? FieldWidth.getPositionalArgIndex() - 1
8010 : FieldWidthIndex,
8011 0);
8012 }
8013 // precision?
8014 const auto &Precision = FS.getPrecision();
8015 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8016 PrecisionIndex = Specs.size();
8017 Specs.emplace_back(
8018 getSpecifierRange(startSpecifier, specifierLen),
8019 getLocationOfByte(Precision.getStart()),
8021 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
8022 EquatableFormatArgument::SS_None,
8023 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8024 : PrecisionIndex,
8025 0);
8026 }
8027
8028 // this specifier
8029 unsigned SpecIndex =
8030 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8031 if (FieldWidthIndex != Unset)
8032 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8033 if (PrecisionIndex != Unset)
8034 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8035
8036 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8037 if (FS.isPrivate())
8038 Sensitivity = EquatableFormatArgument::SS_Private;
8039 else if (FS.isPublic())
8040 Sensitivity = EquatableFormatArgument::SS_Public;
8041 else if (FS.isSensitive())
8042 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8043 else
8044 Sensitivity = EquatableFormatArgument::SS_None;
8045
8046 Specs.emplace_back(
8047 getSpecifierRange(startSpecifier, specifierLen),
8048 getLocationOfByte(CS.getStart()), FS.getLengthModifier().getKind(),
8049 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
8050 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
8051
8052 // auxiliary argument?
8055 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
8056 getLocationOfByte(CS.getStart()),
8058 CS.getCharacters(),
8060 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
8061 SpecIndex + 1, SpecIndex);
8062 }
8063 return true;
8064}
8065
8066// Determines if the specified is a C++ class or struct containing
8067// a member with the specified name and kind (e.g. a CXXMethodDecl named
8068// "c_str()").
8069template<typename MemberKind>
8071CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8072 auto *RD = Ty->getAsCXXRecordDecl();
8074
8075 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8076 return Results;
8077
8078 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8081
8082 // We just need to include all members of the right kind turned up by the
8083 // filter, at this point.
8084 if (S.LookupQualifiedName(R, RD))
8085 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8086 NamedDecl *decl = (*I)->getUnderlyingDecl();
8087 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8088 Results.insert(FK);
8089 }
8090 return Results;
8091}
8092
8093/// Check if we could call '.c_str()' on an object.
8094///
8095/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8096/// allow the call, or if it would be ambiguous).
8098 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8099
8100 MethodSet Results =
8101 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8102 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8103 MI != ME; ++MI)
8104 if ((*MI)->getMinRequiredArguments() == 0)
8105 return true;
8106 return false;
8107}
8108
8109// Check if a (w)string was passed when a (w)char* was needed, and offer a
8110// better diagnostic if so. AT is assumed to be valid.
8111// Returns true when a c_str() conversion method is found.
8112bool CheckPrintfHandler::checkForCStrMembers(
8113 const analyze_printf::ArgType &AT, const Expr *E) {
8114 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8115
8116 MethodSet Results =
8118
8119 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8120 MI != ME; ++MI) {
8121 const CXXMethodDecl *Method = *MI;
8122 if (Method->getMinRequiredArguments() == 0 &&
8123 AT.matchesType(S.Context, Method->getReturnType())) {
8124 // FIXME: Suggest parens if the expression needs them.
8126 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8127 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8128 return true;
8129 }
8130 }
8131
8132 return false;
8133}
8134
8135bool CheckPrintfHandler::HandlePrintfSpecifier(
8136 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8137 unsigned specifierLen, const TargetInfo &Target) {
8138 using namespace analyze_format_string;
8139 using namespace analyze_printf;
8140
8141 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8142
8143 if (FS.consumesDataArgument()) {
8144 if (atFirstArg) {
8145 atFirstArg = false;
8146 usesPositionalArgs = FS.usesPositionalArg();
8147 }
8148 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8149 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8150 startSpecifier, specifierLen);
8151 return false;
8152 }
8153 }
8154
8155 // First check if the field width, precision, and conversion specifier
8156 // have matching data arguments.
8157 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8158 startSpecifier, specifierLen)) {
8159 return false;
8160 }
8161
8162 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8163 startSpecifier, specifierLen)) {
8164 return false;
8165 }
8166
8167 if (!CS.consumesDataArgument()) {
8168 // FIXME: Technically specifying a precision or field width here
8169 // makes no sense. Worth issuing a warning at some point.
8170 return true;
8171 }
8172
8173 // Consume the argument.
8174 unsigned argIndex = FS.getArgIndex();
8175 if (argIndex < NumDataArgs) {
8176 // The check to see if the argIndex is valid will come later.
8177 // We set the bit here because we may exit early from this
8178 // function if we encounter some other error.
8179 CoveredArgs.set(argIndex);
8180 }
8181
8182 // FreeBSD kernel extensions.
8183 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8184 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8185 // We need at least two arguments.
8186 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8187 return false;
8188
8189 if (HasFormatArguments()) {
8190 // Claim the second argument.
8191 CoveredArgs.set(argIndex + 1);
8192
8193 // Type check the first argument (int for %b, pointer for %D)
8194 const Expr *Ex = getDataArg(argIndex);
8195 const analyze_printf::ArgType &AT =
8196 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8197 ? ArgType(S.Context.IntTy)
8198 : ArgType::CPointerTy;
8199 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8200 EmitFormatDiagnostic(
8201 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8202 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8203 << false << Ex->getSourceRange(),
8204 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8205 getSpecifierRange(startSpecifier, specifierLen));
8206
8207 // Type check the second argument (char * for both %b and %D)
8208 Ex = getDataArg(argIndex + 1);
8210 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8211 EmitFormatDiagnostic(
8212 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8213 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8214 << false << Ex->getSourceRange(),
8215 Ex->getBeginLoc(), /*IsStringLocation*/ false,
8216 getSpecifierRange(startSpecifier, specifierLen));
8217 }
8218 return true;
8219 }
8220
8221 // Check for using an Objective-C specific conversion specifier
8222 // in a non-ObjC literal.
8223 if (!allowsObjCArg() && CS.isObjCArg()) {
8224 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8225 specifierLen);
8226 }
8227
8228 // %P can only be used with os_log.
8229 if (FSType != FormatStringType::OSLog &&
8230 CS.getKind() == ConversionSpecifier::PArg) {
8231 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8232 specifierLen);
8233 }
8234
8235 // %n is not allowed with os_log.
8236 if (FSType == FormatStringType::OSLog &&
8237 CS.getKind() == ConversionSpecifier::nArg) {
8238 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8239 getLocationOfByte(CS.getStart()),
8240 /*IsStringLocation*/ false,
8241 getSpecifierRange(startSpecifier, specifierLen));
8242
8243 return true;
8244 }
8245
8246 // Only scalars are allowed for os_trace.
8247 if (FSType == FormatStringType::OSTrace &&
8248 (CS.getKind() == ConversionSpecifier::PArg ||
8249 CS.getKind() == ConversionSpecifier::sArg ||
8250 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8251 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8252 specifierLen);
8253 }
8254
8255 // Check for use of public/private annotation outside of os_log().
8256 if (FSType != FormatStringType::OSLog) {
8257 if (FS.isPublic().isSet()) {
8258 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8259 << "public",
8260 getLocationOfByte(FS.isPublic().getPosition()),
8261 /*IsStringLocation*/ false,
8262 getSpecifierRange(startSpecifier, specifierLen));
8263 }
8264 if (FS.isPrivate().isSet()) {
8265 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8266 << "private",
8267 getLocationOfByte(FS.isPrivate().getPosition()),
8268 /*IsStringLocation*/ false,
8269 getSpecifierRange(startSpecifier, specifierLen));
8270 }
8271 }
8272
8273 const llvm::Triple &Triple = Target.getTriple();
8274 if (CS.getKind() == ConversionSpecifier::nArg &&
8275 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8276 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
8277 getLocationOfByte(CS.getStart()),
8278 /*IsStringLocation*/ false,
8279 getSpecifierRange(startSpecifier, specifierLen));
8280 }
8281
8282 // Check for invalid use of field width
8283 if (!FS.hasValidFieldWidth()) {
8284 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8285 startSpecifier, specifierLen);
8286 }
8287
8288 // Check for invalid use of precision
8289 if (!FS.hasValidPrecision()) {
8290 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8291 startSpecifier, specifierLen);
8292 }
8293
8294 // Precision is mandatory for %P specifier.
8295 if (CS.getKind() == ConversionSpecifier::PArg &&
8297 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8298 getLocationOfByte(startSpecifier),
8299 /*IsStringLocation*/ false,
8300 getSpecifierRange(startSpecifier, specifierLen));
8301 }
8302
8303 // Check each flag does not conflict with any other component.
8305 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8306 if (!FS.hasValidLeadingZeros())
8307 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8308 if (!FS.hasValidPlusPrefix())
8309 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8310 if (!FS.hasValidSpacePrefix())
8311 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8312 if (!FS.hasValidAlternativeForm())
8313 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8314 if (!FS.hasValidLeftJustified())
8315 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8316
8317 // Check that flags are not ignored by another flag
8318 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8319 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8320 startSpecifier, specifierLen);
8321 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8322 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8323 startSpecifier, specifierLen);
8324
8325 // Check the length modifier is valid with the given conversion specifier.
8327 S.getLangOpts()))
8328 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8329 diag::warn_format_nonsensical_length);
8330 else if (!FS.hasStandardLengthModifier())
8331 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8333 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8334 diag::warn_format_non_standard_conversion_spec);
8335
8337 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8338
8339 // The remaining checks depend on the data arguments.
8340 if (!HasFormatArguments())
8341 return true;
8342
8343 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8344 return false;
8345
8346 const Expr *Arg = getDataArg(argIndex);
8347 if (!Arg)
8348 return true;
8349
8350 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8351}
8352
8353static bool requiresParensToAddCast(const Expr *E) {
8354 // FIXME: We should have a general way to reason about operator
8355 // precedence and whether parens are actually needed here.
8356 // Take care of a few common cases where they aren't.
8357 const Expr *Inside = E->IgnoreImpCasts();
8358 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8359 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8360
8361 switch (Inside->getStmtClass()) {
8362 case Stmt::ArraySubscriptExprClass:
8363 case Stmt::CallExprClass:
8364 case Stmt::CharacterLiteralClass:
8365 case Stmt::CXXBoolLiteralExprClass:
8366 case Stmt::DeclRefExprClass:
8367 case Stmt::FloatingLiteralClass:
8368 case Stmt::IntegerLiteralClass:
8369 case Stmt::MemberExprClass:
8370 case Stmt::ObjCArrayLiteralClass:
8371 case Stmt::ObjCBoolLiteralExprClass:
8372 case Stmt::ObjCBoxedExprClass:
8373 case Stmt::ObjCDictionaryLiteralClass:
8374 case Stmt::ObjCEncodeExprClass:
8375 case Stmt::ObjCIvarRefExprClass:
8376 case Stmt::ObjCMessageExprClass:
8377 case Stmt::ObjCPropertyRefExprClass:
8378 case Stmt::ObjCStringLiteralClass:
8379 case Stmt::ObjCSubscriptRefExprClass:
8380 case Stmt::ParenExprClass:
8381 case Stmt::StringLiteralClass:
8382 case Stmt::UnaryOperatorClass:
8383 return false;
8384 default:
8385 return true;
8386 }
8387}
8388
8389static std::pair<QualType, StringRef>
8391 QualType IntendedTy,
8392 const Expr *E) {
8393 // Use a 'while' to peel off layers of typedefs.
8394 QualType TyTy = IntendedTy;
8395 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8396 StringRef Name = UserTy->getDecl()->getName();
8397 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8398 .Case("CFIndex", Context.getNSIntegerType())
8399 .Case("NSInteger", Context.getNSIntegerType())
8400 .Case("NSUInteger", Context.getNSUIntegerType())
8401 .Case("SInt32", Context.IntTy)
8402 .Case("UInt32", Context.UnsignedIntTy)
8403 .Default(QualType());
8404
8405 if (!CastTy.isNull())
8406 return std::make_pair(CastTy, Name);
8407
8408 TyTy = UserTy->desugar();
8409 }
8410
8411 // Strip parens if necessary.
8412 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8413 return shouldNotPrintDirectly(Context,
8414 PE->getSubExpr()->getType(),
8415 PE->getSubExpr());
8416
8417 // If this is a conditional expression, then its result type is constructed
8418 // via usual arithmetic conversions and thus there might be no necessary
8419 // typedef sugar there. Recurse to operands to check for NSInteger &
8420 // Co. usage condition.
8421 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8422 QualType TrueTy, FalseTy;
8423 StringRef TrueName, FalseName;
8424
8425 std::tie(TrueTy, TrueName) =
8426 shouldNotPrintDirectly(Context,
8427 CO->getTrueExpr()->getType(),
8428 CO->getTrueExpr());
8429 std::tie(FalseTy, FalseName) =
8430 shouldNotPrintDirectly(Context,
8431 CO->getFalseExpr()->getType(),
8432 CO->getFalseExpr());
8433
8434 if (TrueTy == FalseTy)
8435 return std::make_pair(TrueTy, TrueName);
8436 else if (TrueTy.isNull())
8437 return std::make_pair(FalseTy, FalseName);
8438 else if (FalseTy.isNull())
8439 return std::make_pair(TrueTy, TrueName);
8440 }
8441
8442 return std::make_pair(QualType(), StringRef());
8443}
8444
8445/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8446/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8447/// type do not count.
8448static bool
8450 QualType From = ICE->getSubExpr()->getType();
8451 QualType To = ICE->getType();
8452 // It's an integer promotion if the destination type is the promoted
8453 // source type.
8454 if (ICE->getCastKind() == CK_IntegralCast &&
8456 S.Context.getPromotedIntegerType(From) == To)
8457 return true;
8458 // Look through vector types, since we do default argument promotion for
8459 // those in OpenCL.
8460 if (const auto *VecTy = From->getAs<ExtVectorType>())
8461 From = VecTy->getElementType();
8462 if (const auto *VecTy = To->getAs<ExtVectorType>())
8463 To = VecTy->getElementType();
8464 // It's a floating promotion if the source type is a lower rank.
8465 return ICE->getCastKind() == CK_FloatingCast &&
8466 S.Context.getFloatingTypeOrder(From, To) < 0;
8467}
8468
8471 DiagnosticsEngine &Diags, SourceLocation Loc) {
8473 if (Diags.isIgnored(
8474 diag::warn_format_conversion_argument_type_mismatch_signedness,
8475 Loc) ||
8476 Diags.isIgnored(
8477 // Arbitrary -Wformat diagnostic to detect -Wno-format:
8478 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
8480 }
8481 }
8482 return Match;
8483}
8484
8485bool
8486CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8487 const char *StartSpecifier,
8488 unsigned SpecifierLen,
8489 const Expr *E) {
8490 using namespace analyze_format_string;
8491 using namespace analyze_printf;
8492
8493 // Now type check the data expression that matches the
8494 // format specifier.
8495 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8496 if (!AT.isValid())
8497 return true;
8498
8499 QualType ExprTy = E->getType();
8500 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8501 ExprTy = TET->getUnderlyingExpr()->getType();
8502 }
8503
8504 // When using the format attribute in C++, you can receive a function or an
8505 // array that will necessarily decay to a pointer when passed to the final
8506 // format consumer. Apply decay before type comparison.
8507 if (ExprTy->canDecayToPointerType())
8508 ExprTy = S.Context.getDecayedType(ExprTy);
8509
8510 // Diagnose attempts to print a boolean value as a character. Unlike other
8511 // -Wformat diagnostics, this is fine from a type perspective, but it still
8512 // doesn't make sense.
8515 const CharSourceRange &CSR =
8516 getSpecifierRange(StartSpecifier, SpecifierLen);
8517 SmallString<4> FSString;
8518 llvm::raw_svector_ostream os(FSString);
8519 FS.toString(os);
8520 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8521 << FSString,
8522 E->getExprLoc(), false, CSR);
8523 return true;
8524 }
8525
8526 // Diagnose attempts to use '%P' with ObjC object types, which will result in
8527 // dumping raw class data (like is-a pointer), not actual data.
8529 ExprTy->isObjCObjectPointerType()) {
8530 const CharSourceRange &CSR =
8531 getSpecifierRange(StartSpecifier, SpecifierLen);
8532 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
8533 E->getExprLoc(), false, CSR);
8534 return true;
8535 }
8536
8537 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
8539 ArgType::MatchKind OrigMatch = Match;
8540
8542 if (Match == ArgType::Match)
8543 return true;
8544
8545 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
8546 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
8547
8548 // Look through argument promotions for our error message's reported type.
8549 // This includes the integral and floating promotions, but excludes array
8550 // and function pointer decay (seeing that an argument intended to be a
8551 // string has type 'char [6]' is probably more confusing than 'char *') and
8552 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8553 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8554 if (isArithmeticArgumentPromotion(S, ICE)) {
8555 E = ICE->getSubExpr();
8556 ExprTy = E->getType();
8557
8558 // Check if we didn't match because of an implicit cast from a 'char'
8559 // or 'short' to an 'int'. This is done because printf is a varargs
8560 // function.
8561 if (ICE->getType() == S.Context.IntTy ||
8562 ICE->getType() == S.Context.UnsignedIntTy) {
8563 // All further checking is done on the subexpression
8564 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
8565 if (OrigMatch == ArgType::NoMatchSignedness &&
8566 ImplicitMatch != ArgType::NoMatchSignedness)
8567 // If the original match was a signedness match this match on the
8568 // implicit cast type also need to be signedness match otherwise we
8569 // might introduce new unexpected warnings from -Wformat-signedness.
8570 return true;
8571 ImplicitMatch = handleFormatSignedness(
8572 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
8573 if (ImplicitMatch == ArgType::Match)
8574 return true;
8575 }
8576 }
8577 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8578 // Special case for 'a', which has type 'int' in C.
8579 // Note, however, that we do /not/ want to treat multibyte constants like
8580 // 'MooV' as characters! This form is deprecated but still exists. In
8581 // addition, don't treat expressions as of type 'char' if one byte length
8582 // modifier is provided.
8583 if (ExprTy == S.Context.IntTy &&
8585 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
8586 ExprTy = S.Context.CharTy;
8587 // To improve check results, we consider a character literal in C
8588 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
8589 // more likely a type confusion situation, so we will suggest to
8590 // use '%hhd' instead by discarding the MatchPromotion.
8591 if (Match == ArgType::MatchPromotion)
8593 }
8594 }
8595 if (Match == ArgType::MatchPromotion) {
8596 // WG14 N2562 only clarified promotions in *printf
8597 // For NSLog in ObjC, just preserve -Wformat behavior
8598 if (!S.getLangOpts().ObjC &&
8599 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
8600 ImplicitMatch != ArgType::NoMatchTypeConfusion)
8601 return true;
8603 }
8604 if (ImplicitMatch == ArgType::NoMatchPedantic ||
8605 ImplicitMatch == ArgType::NoMatchTypeConfusion)
8606 Match = ImplicitMatch;
8607 assert(Match != ArgType::MatchPromotion);
8608
8609 // Look through unscoped enums to their underlying type.
8610 bool IsEnum = false;
8611 bool IsScopedEnum = false;
8612 QualType IntendedTy = ExprTy;
8613 if (const auto *ED = ExprTy->getAsEnumDecl()) {
8614 IntendedTy = ED->getIntegerType();
8615 if (!ED->isScoped()) {
8616 ExprTy = IntendedTy;
8617 // This controls whether we're talking about the underlying type or not,
8618 // which we only want to do when it's an unscoped enum.
8619 IsEnum = true;
8620 } else {
8621 IsScopedEnum = true;
8622 }
8623 }
8624
8625 // %C in an Objective-C context prints a unichar, not a wchar_t.
8626 // If the argument is an integer of some kind, believe the %C and suggest
8627 // a cast instead of changing the conversion specifier.
8628 if (isObjCContext() &&
8631 !ExprTy->isCharType()) {
8632 // 'unichar' is defined as a typedef of unsigned short, but we should
8633 // prefer using the typedef if it is visible.
8634 IntendedTy = S.Context.UnsignedShortTy;
8635
8636 // While we are here, check if the value is an IntegerLiteral that happens
8637 // to be within the valid range.
8638 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8639 const llvm::APInt &V = IL->getValue();
8640 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8641 return true;
8642 }
8643
8644 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8646 if (S.LookupName(Result, S.getCurScope())) {
8647 NamedDecl *ND = Result.getFoundDecl();
8648 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8649 if (TD->getUnderlyingType() == IntendedTy)
8650 IntendedTy =
8652 /*Qualifier=*/std::nullopt, TD);
8653 }
8654 }
8655 }
8656
8657 // Special-case some of Darwin's platform-independence types by suggesting
8658 // casts to primitive types that are known to be large enough.
8659 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8660 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8661 QualType CastTy;
8662 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8663 if (!CastTy.isNull()) {
8664 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8665 // (long in ASTContext). Only complain to pedants or when they're the
8666 // underlying type of a scoped enum (which always needs a cast).
8667 if (!IsScopedEnum &&
8668 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8669 (AT.isSizeT() || AT.isPtrdiffT()) &&
8670 AT.matchesType(S.Context, CastTy))
8672 IntendedTy = CastTy;
8673 ShouldNotPrintDirectly = true;
8674 }
8675 }
8676
8677 // We may be able to offer a FixItHint if it is a supported type.
8678 PrintfSpecifier fixedFS = FS;
8679 bool Success =
8680 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8681
8682 if (Success) {
8683 // Get the fix string from the fixed format specifier
8684 SmallString<16> buf;
8685 llvm::raw_svector_ostream os(buf);
8686 fixedFS.toString(os);
8687
8688 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8689
8690 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
8691 unsigned Diag;
8692 switch (Match) {
8693 case ArgType::Match:
8696 llvm_unreachable("expected non-matching");
8698 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
8699 break;
8701 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8702 break;
8704 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8705 break;
8706 case ArgType::NoMatch:
8707 Diag = diag::warn_format_conversion_argument_type_mismatch;
8708 break;
8709 }
8710
8711 // In this case, the specifier is wrong and should be changed to match
8712 // the argument.
8713 EmitFormatDiagnostic(S.PDiag(Diag)
8715 << IntendedTy << IsEnum << E->getSourceRange(),
8716 E->getBeginLoc(),
8717 /*IsStringLocation*/ false, SpecRange,
8718 FixItHint::CreateReplacement(SpecRange, os.str()));
8719 } else {
8720 // The canonical type for formatting this value is different from the
8721 // actual type of the expression. (This occurs, for example, with Darwin's
8722 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8723 // should be printed as 'long' for 64-bit compatibility.)
8724 // Rather than emitting a normal format/argument mismatch, we want to
8725 // add a cast to the recommended type (and correct the format string
8726 // if necessary). We should also do so for scoped enumerations.
8727 SmallString<16> CastBuf;
8728 llvm::raw_svector_ostream CastFix(CastBuf);
8729 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
8730 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8731 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
8732
8734 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
8735 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
8736 E->getExprLoc());
8737 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
8738 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8739
8740 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8741 // If there's already a cast present, just replace it.
8742 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8743 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8744
8745 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
8746 // If the expression has high enough precedence,
8747 // just write the C-style cast.
8748 Hints.push_back(
8749 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8750 } else {
8751 // Otherwise, add parens around the expression as well as the cast.
8752 CastFix << "(";
8753 Hints.push_back(
8754 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8755
8756 // We don't use getLocForEndOfToken because it returns invalid source
8757 // locations for macro expansions (by design).
8761 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8762 }
8763
8764 if (ShouldNotPrintDirectly && !IsScopedEnum) {
8765 // The expression has a type that should not be printed directly.
8766 // We extract the name from the typedef because we don't want to show
8767 // the underlying type in the diagnostic.
8768 StringRef Name;
8769 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
8770 Name = TypedefTy->getDecl()->getName();
8771 else
8772 Name = CastTyName;
8773 unsigned Diag = Match == ArgType::NoMatchPedantic
8774 ? diag::warn_format_argument_needs_cast_pedantic
8775 : diag::warn_format_argument_needs_cast;
8776 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8777 << E->getSourceRange(),
8778 E->getBeginLoc(), /*IsStringLocation=*/false,
8779 SpecRange, Hints);
8780 } else {
8781 // In this case, the expression could be printed using a different
8782 // specifier, but we've decided that the specifier is probably correct
8783 // and we should cast instead. Just use the normal warning message.
8784
8785 unsigned Diag =
8786 IsScopedEnum
8787 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8788 : diag::warn_format_conversion_argument_type_mismatch;
8789
8790 EmitFormatDiagnostic(
8791 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8792 << IsEnum << E->getSourceRange(),
8793 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8794 }
8795 }
8796 } else {
8797 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8798 SpecifierLen);
8799 // Since the warning for passing non-POD types to variadic functions
8800 // was deferred until now, we emit a warning for non-POD
8801 // arguments here.
8802 bool EmitTypeMismatch = false;
8803 switch (S.isValidVarArgType(ExprTy)) {
8804 case VarArgKind::Valid:
8806 unsigned Diag;
8807 switch (Match) {
8808 case ArgType::Match:
8812 llvm_unreachable("expected non-matching");
8814 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8815 break;
8817 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8818 break;
8819 case ArgType::NoMatch:
8820 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)
8821 ? diag::err_format_conversion_argument_type_mismatch
8822 : diag::warn_format_conversion_argument_type_mismatch;
8823 break;
8824 }
8825
8826 EmitFormatDiagnostic(
8827 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8828 << IsEnum << CSR << E->getSourceRange(),
8829 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8830 break;
8831 }
8834 if (CallType == VariadicCallType::DoesNotApply) {
8835 EmitTypeMismatch = true;
8836 } else {
8837 EmitFormatDiagnostic(
8838 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8839 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8840 << AT.getRepresentativeTypeName(S.Context) << CSR
8841 << E->getSourceRange(),
8842 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8843 checkForCStrMembers(AT, E);
8844 }
8845 break;
8846
8848 if (CallType == VariadicCallType::DoesNotApply)
8849 EmitTypeMismatch = true;
8850 else if (ExprTy->isObjCObjectType())
8851 EmitFormatDiagnostic(
8852 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8853 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8854 << AT.getRepresentativeTypeName(S.Context) << CSR
8855 << E->getSourceRange(),
8856 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8857 else
8858 // FIXME: If this is an initializer list, suggest removing the braces
8859 // or inserting a cast to the target type.
8860 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8861 << isa<InitListExpr>(E) << ExprTy << CallType
8863 break;
8864 }
8865
8866 if (EmitTypeMismatch) {
8867 // The function is not variadic, so we do not generate warnings about
8868 // being allowed to pass that object as a variadic argument. Instead,
8869 // since there are inherently no printf specifiers for types which cannot
8870 // be passed as variadic arguments, emit a plain old specifier mismatch
8871 // argument.
8872 EmitFormatDiagnostic(
8873 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8874 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
8875 << E->getSourceRange(),
8876 E->getBeginLoc(), false, CSR);
8877 }
8878
8879 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8880 "format string specifier index out of range");
8881 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8882 }
8883
8884 return true;
8885}
8886
8887//===--- CHECK: Scanf format string checking ------------------------------===//
8888
8889namespace {
8890
8891class CheckScanfHandler : public CheckFormatHandler {
8892public:
8893 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8894 const Expr *origFormatExpr, FormatStringType type,
8895 unsigned firstDataArg, unsigned numDataArgs,
8896 const char *beg, Sema::FormatArgumentPassingKind APK,
8897 ArrayRef<const Expr *> Args, unsigned formatIdx,
8898 bool inFunctionCall, VariadicCallType CallType,
8899 llvm::SmallBitVector &CheckedVarArgs,
8900 UncoveredArgHandler &UncoveredArg)
8901 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8902 numDataArgs, beg, APK, Args, formatIdx,
8903 inFunctionCall, CallType, CheckedVarArgs,
8904 UncoveredArg) {}
8905
8906 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8907 const char *startSpecifier,
8908 unsigned specifierLen) override;
8909
8910 bool HandleInvalidScanfConversionSpecifier(
8911 const analyze_scanf::ScanfSpecifier &FS,
8912 const char *startSpecifier,
8913 unsigned specifierLen) override;
8914
8915 void HandleIncompleteScanList(const char *start, const char *end) override;
8916};
8917
8918} // namespace
8919
8920void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8921 const char *end) {
8922 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8923 getLocationOfByte(end), /*IsStringLocation*/true,
8924 getSpecifierRange(start, end - start));
8925}
8926
8927bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8929 const char *startSpecifier,
8930 unsigned specifierLen) {
8933
8934 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8935 getLocationOfByte(CS.getStart()),
8936 startSpecifier, specifierLen,
8937 CS.getStart(), CS.getLength());
8938}
8939
8940bool CheckScanfHandler::HandleScanfSpecifier(
8942 const char *startSpecifier,
8943 unsigned specifierLen) {
8944 using namespace analyze_scanf;
8945 using namespace analyze_format_string;
8946
8947 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8948
8949 // Handle case where '%' and '*' don't consume an argument. These shouldn't
8950 // be used to decide if we are using positional arguments consistently.
8951 if (FS.consumesDataArgument()) {
8952 if (atFirstArg) {
8953 atFirstArg = false;
8954 usesPositionalArgs = FS.usesPositionalArg();
8955 }
8956 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8957 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8958 startSpecifier, specifierLen);
8959 return false;
8960 }
8961 }
8962
8963 // Check if the field with is non-zero.
8964 const OptionalAmount &Amt = FS.getFieldWidth();
8966 if (Amt.getConstantAmount() == 0) {
8967 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8968 Amt.getConstantLength());
8969 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8970 getLocationOfByte(Amt.getStart()),
8971 /*IsStringLocation*/true, R,
8973 }
8974 }
8975
8976 if (!FS.consumesDataArgument()) {
8977 // FIXME: Technically specifying a precision or field width here
8978 // makes no sense. Worth issuing a warning at some point.
8979 return true;
8980 }
8981
8982 // Consume the argument.
8983 unsigned argIndex = FS.getArgIndex();
8984 if (argIndex < NumDataArgs) {
8985 // The check to see if the argIndex is valid will come later.
8986 // We set the bit here because we may exit early from this
8987 // function if we encounter some other error.
8988 CoveredArgs.set(argIndex);
8989 }
8990
8991 // Check the length modifier is valid with the given conversion specifier.
8993 S.getLangOpts()))
8994 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8995 diag::warn_format_nonsensical_length);
8996 else if (!FS.hasStandardLengthModifier())
8997 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8999 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9000 diag::warn_format_non_standard_conversion_spec);
9001
9003 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9004
9005 // The remaining checks depend on the data arguments.
9006 if (!HasFormatArguments())
9007 return true;
9008
9009 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9010 return false;
9011
9012 // Check that the argument type matches the format specifier.
9013 const Expr *Ex = getDataArg(argIndex);
9014 if (!Ex)
9015 return true;
9016
9018
9019 if (!AT.isValid()) {
9020 return true;
9021 }
9022
9024 AT.matchesType(S.Context, Ex->getType());
9027 return true;
9030
9031 ScanfSpecifier fixedFS = FS;
9032 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9033 S.getLangOpts(), S.Context);
9034
9035 unsigned Diag =
9036 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9037 : Signedness
9038 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9039 : diag::warn_format_conversion_argument_type_mismatch;
9040
9041 if (Success) {
9042 // Get the fix string from the fixed format specifier.
9043 SmallString<128> buf;
9044 llvm::raw_svector_ostream os(buf);
9045 fixedFS.toString(os);
9046
9047 EmitFormatDiagnostic(
9049 << Ex->getType() << false << Ex->getSourceRange(),
9050 Ex->getBeginLoc(),
9051 /*IsStringLocation*/ false,
9052 getSpecifierRange(startSpecifier, specifierLen),
9054 getSpecifierRange(startSpecifier, specifierLen), os.str()));
9055 } else {
9056 EmitFormatDiagnostic(S.PDiag(Diag)
9058 << Ex->getType() << false << Ex->getSourceRange(),
9059 Ex->getBeginLoc(),
9060 /*IsStringLocation*/ false,
9061 getSpecifierRange(startSpecifier, specifierLen));
9062 }
9063
9064 return true;
9065}
9066
9067static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9069 const StringLiteral *Fmt,
9071 const Expr *FmtExpr, bool InFunctionCall) {
9072 bool HadError = false;
9073 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9074 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9075 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9076 // In positional-style format strings, the same specifier can appear
9077 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9078 // are sorted by getPosition(), and we process each range of equal
9079 // getPosition() values as one group.
9080 // RefArgs are taken from a string literal that was given to
9081 // attribute(format_matches), and if we got this far, we have already
9082 // verified that if it has positional specifiers that appear in multiple
9083 // locations, then they are all mutually compatible. What's left for us to
9084 // do is verify that all specifiers with the same position in FmtArgs are
9085 // compatible with the RefArgs specifiers. We check each specifier from
9086 // FmtArgs against the first member of the RefArgs group.
9087 for (; FmtIter < FmtEnd; ++FmtIter) {
9088 // Clang does not diagnose missing format specifiers in positional-style
9089 // strings (TODO: which it probably should do, as it is UB to skip over a
9090 // format argument). Skip specifiers if needed.
9091 if (FmtIter->getPosition() < RefIter->getPosition())
9092 continue;
9093
9094 // Delimits a new getPosition() value.
9095 if (FmtIter->getPosition() > RefIter->getPosition())
9096 break;
9097
9098 HadError |=
9099 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
9100 }
9101
9102 // Jump RefIter to the start of the next group.
9103 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
9104 return Arg.getPosition() != RefIter->getPosition();
9105 });
9106 }
9107
9108 if (FmtIter < FmtEnd) {
9109 CheckFormatHandler::EmitFormatDiagnostic(
9110 S, InFunctionCall, FmtExpr,
9111 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
9112 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
9113 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
9114 } else if (RefIter < RefEnd) {
9115 CheckFormatHandler::EmitFormatDiagnostic(
9116 S, InFunctionCall, FmtExpr,
9117 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
9118 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
9119 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
9120 << 1 << RefIter->getSourceRange();
9121 }
9122 return !HadError;
9123}
9124
9126 Sema &S, const FormatStringLiteral *FExpr,
9127 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9129 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9130 bool inFunctionCall, VariadicCallType CallType,
9131 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9132 bool IgnoreStringsWithoutSpecifiers) {
9133 // CHECK: is the format string a wide literal?
9134 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9135 CheckFormatHandler::EmitFormatDiagnostic(
9136 S, inFunctionCall, Args[format_idx],
9137 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9138 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9139 return;
9140 }
9141
9142 // Str - The format string. NOTE: this is NOT null-terminated!
9143 StringRef StrRef = FExpr->getString();
9144 const char *Str = StrRef.data();
9145 // Account for cases where the string literal is truncated in a declaration.
9146 const ConstantArrayType *T =
9147 S.Context.getAsConstantArrayType(FExpr->getType());
9148 assert(T && "String literal not of constant array type!");
9149 size_t TypeSize = T->getZExtSize();
9150 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9151 const unsigned numDataArgs = Args.size() - firstDataArg;
9152
9153 if (IgnoreStringsWithoutSpecifiers &&
9155 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9156 return;
9157
9158 // Emit a warning if the string literal is truncated and does not contain an
9159 // embedded null character.
9160 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9161 CheckFormatHandler::EmitFormatDiagnostic(
9162 S, inFunctionCall, Args[format_idx],
9163 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9164 FExpr->getBeginLoc(),
9165 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9166 return;
9167 }
9168
9169 // CHECK: empty format string?
9170 if (StrLen == 0 && numDataArgs > 0) {
9171 CheckFormatHandler::EmitFormatDiagnostic(
9172 S, inFunctionCall, Args[format_idx],
9173 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9174 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9175 return;
9176 }
9177
9182 bool IsObjC =
9184 if (ReferenceFormatString == nullptr) {
9185 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9186 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9187 inFunctionCall, CallType, CheckedVarArgs,
9188 UncoveredArg);
9189
9191 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
9194 H.DoneProcessing();
9195 } else {
9197 Type, ReferenceFormatString, FExpr->getFormatString(),
9198 inFunctionCall ? nullptr : Args[format_idx]);
9199 }
9200 } else if (Type == FormatStringType::Scanf) {
9201 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9202 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9203 CallType, CheckedVarArgs, UncoveredArg);
9204
9206 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9207 H.DoneProcessing();
9208 } // TODO: handle other formats
9209}
9210
9212 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9213 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9218 return true;
9219
9220 bool IsObjC =
9223 FormatStringLiteral RefLit = AuthoritativeFormatString;
9224 FormatStringLiteral TestLit = TestedFormatString;
9225 const Expr *Arg;
9226 bool DiagAtStringLiteral;
9227 if (FunctionCallArg) {
9228 Arg = FunctionCallArg;
9229 DiagAtStringLiteral = false;
9230 } else {
9231 Arg = TestedFormatString;
9232 DiagAtStringLiteral = true;
9233 }
9234 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
9235 AuthoritativeFormatString, Type,
9236 IsObjC, true, RefArgs) &&
9237 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
9238 DiagAtStringLiteral, FmtArgs)) {
9239 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
9240 TestedFormatString, FmtArgs, Arg,
9241 DiagAtStringLiteral);
9242 }
9243 return false;
9244}
9245
9247 const StringLiteral *Str) {
9252 return true;
9253
9254 FormatStringLiteral RefLit = Str;
9256 bool IsObjC =
9258 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
9259 true, Args))
9260 return false;
9261
9262 // Group arguments by getPosition() value, and check that each member of the
9263 // group is compatible with the first member. This verifies that when
9264 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9265 // are mutually compatible. As an optimization, don't test the first member
9266 // against itself.
9267 bool HadError = false;
9268 auto Iter = Args.begin();
9269 auto End = Args.end();
9270 while (Iter != End) {
9271 const auto &FirstInGroup = *Iter;
9272 for (++Iter;
9273 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9274 ++Iter) {
9275 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
9276 }
9277 }
9278 return !HadError;
9279}
9280
9282 // Str - The format string. NOTE: this is NOT null-terminated!
9283 StringRef StrRef = FExpr->getString();
9284 const char *Str = StrRef.data();
9285 // Account for cases where the string literal is truncated in a declaration.
9286 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9287 assert(T && "String literal not of constant array type!");
9288 size_t TypeSize = T->getZExtSize();
9289 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9290 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9291 getLangOpts(),
9292 Context.getTargetInfo());
9293}
9294
9295//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9296
9297// Returns the related absolute value function that is larger, of 0 if one
9298// does not exist.
9299static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9300 switch (AbsFunction) {
9301 default:
9302 return 0;
9303
9304 case Builtin::BI__builtin_abs:
9305 return Builtin::BI__builtin_labs;
9306 case Builtin::BI__builtin_labs:
9307 return Builtin::BI__builtin_llabs;
9308 case Builtin::BI__builtin_llabs:
9309 return 0;
9310
9311 case Builtin::BI__builtin_fabsf:
9312 return Builtin::BI__builtin_fabs;
9313 case Builtin::BI__builtin_fabs:
9314 return Builtin::BI__builtin_fabsl;
9315 case Builtin::BI__builtin_fabsl:
9316 return 0;
9317
9318 case Builtin::BI__builtin_cabsf:
9319 return Builtin::BI__builtin_cabs;
9320 case Builtin::BI__builtin_cabs:
9321 return Builtin::BI__builtin_cabsl;
9322 case Builtin::BI__builtin_cabsl:
9323 return 0;
9324
9325 case Builtin::BIabs:
9326 return Builtin::BIlabs;
9327 case Builtin::BIlabs:
9328 return Builtin::BIllabs;
9329 case Builtin::BIllabs:
9330 return 0;
9331
9332 case Builtin::BIfabsf:
9333 return Builtin::BIfabs;
9334 case Builtin::BIfabs:
9335 return Builtin::BIfabsl;
9336 case Builtin::BIfabsl:
9337 return 0;
9338
9339 case Builtin::BIcabsf:
9340 return Builtin::BIcabs;
9341 case Builtin::BIcabs:
9342 return Builtin::BIcabsl;
9343 case Builtin::BIcabsl:
9344 return 0;
9345 }
9346}
9347
9348// Returns the argument type of the absolute value function.
9350 unsigned AbsType) {
9351 if (AbsType == 0)
9352 return QualType();
9353
9355 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9357 return QualType();
9358
9360 if (!FT)
9361 return QualType();
9362
9363 if (FT->getNumParams() != 1)
9364 return QualType();
9365
9366 return FT->getParamType(0);
9367}
9368
9369// Returns the best absolute value function, or zero, based on type and
9370// current absolute value function.
9371static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9372 unsigned AbsFunctionKind) {
9373 unsigned BestKind = 0;
9374 uint64_t ArgSize = Context.getTypeSize(ArgType);
9375 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9376 Kind = getLargerAbsoluteValueFunction(Kind)) {
9377 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9378 if (Context.getTypeSize(ParamType) >= ArgSize) {
9379 if (BestKind == 0)
9380 BestKind = Kind;
9381 else if (Context.hasSameType(ParamType, ArgType)) {
9382 BestKind = Kind;
9383 break;
9384 }
9385 }
9386 }
9387 return BestKind;
9388}
9389
9395
9397 if (T->isIntegralOrEnumerationType())
9398 return AVK_Integer;
9399 if (T->isRealFloatingType())
9400 return AVK_Floating;
9401 if (T->isAnyComplexType())
9402 return AVK_Complex;
9403
9404 llvm_unreachable("Type not integer, floating, or complex");
9405}
9406
9407// Changes the absolute value function to a different type. Preserves whether
9408// the function is a builtin.
9409static unsigned changeAbsFunction(unsigned AbsKind,
9410 AbsoluteValueKind ValueKind) {
9411 switch (ValueKind) {
9412 case AVK_Integer:
9413 switch (AbsKind) {
9414 default:
9415 return 0;
9416 case Builtin::BI__builtin_fabsf:
9417 case Builtin::BI__builtin_fabs:
9418 case Builtin::BI__builtin_fabsl:
9419 case Builtin::BI__builtin_cabsf:
9420 case Builtin::BI__builtin_cabs:
9421 case Builtin::BI__builtin_cabsl:
9422 return Builtin::BI__builtin_abs;
9423 case Builtin::BIfabsf:
9424 case Builtin::BIfabs:
9425 case Builtin::BIfabsl:
9426 case Builtin::BIcabsf:
9427 case Builtin::BIcabs:
9428 case Builtin::BIcabsl:
9429 return Builtin::BIabs;
9430 }
9431 case AVK_Floating:
9432 switch (AbsKind) {
9433 default:
9434 return 0;
9435 case Builtin::BI__builtin_abs:
9436 case Builtin::BI__builtin_labs:
9437 case Builtin::BI__builtin_llabs:
9438 case Builtin::BI__builtin_cabsf:
9439 case Builtin::BI__builtin_cabs:
9440 case Builtin::BI__builtin_cabsl:
9441 return Builtin::BI__builtin_fabsf;
9442 case Builtin::BIabs:
9443 case Builtin::BIlabs:
9444 case Builtin::BIllabs:
9445 case Builtin::BIcabsf:
9446 case Builtin::BIcabs:
9447 case Builtin::BIcabsl:
9448 return Builtin::BIfabsf;
9449 }
9450 case AVK_Complex:
9451 switch (AbsKind) {
9452 default:
9453 return 0;
9454 case Builtin::BI__builtin_abs:
9455 case Builtin::BI__builtin_labs:
9456 case Builtin::BI__builtin_llabs:
9457 case Builtin::BI__builtin_fabsf:
9458 case Builtin::BI__builtin_fabs:
9459 case Builtin::BI__builtin_fabsl:
9460 return Builtin::BI__builtin_cabsf;
9461 case Builtin::BIabs:
9462 case Builtin::BIlabs:
9463 case Builtin::BIllabs:
9464 case Builtin::BIfabsf:
9465 case Builtin::BIfabs:
9466 case Builtin::BIfabsl:
9467 return Builtin::BIcabsf;
9468 }
9469 }
9470 llvm_unreachable("Unable to convert function");
9471}
9472
9473static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9474 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9475 if (!FnInfo)
9476 return 0;
9477
9478 switch (FDecl->getBuiltinID()) {
9479 default:
9480 return 0;
9481 case Builtin::BI__builtin_abs:
9482 case Builtin::BI__builtin_fabs:
9483 case Builtin::BI__builtin_fabsf:
9484 case Builtin::BI__builtin_fabsl:
9485 case Builtin::BI__builtin_labs:
9486 case Builtin::BI__builtin_llabs:
9487 case Builtin::BI__builtin_cabs:
9488 case Builtin::BI__builtin_cabsf:
9489 case Builtin::BI__builtin_cabsl:
9490 case Builtin::BIabs:
9491 case Builtin::BIlabs:
9492 case Builtin::BIllabs:
9493 case Builtin::BIfabs:
9494 case Builtin::BIfabsf:
9495 case Builtin::BIfabsl:
9496 case Builtin::BIcabs:
9497 case Builtin::BIcabsf:
9498 case Builtin::BIcabsl:
9499 return FDecl->getBuiltinID();
9500 }
9501 llvm_unreachable("Unknown Builtin type");
9502}
9503
9504// If the replacement is valid, emit a note with replacement function.
9505// Additionally, suggest including the proper header if not already included.
9507 unsigned AbsKind, QualType ArgType) {
9508 bool EmitHeaderHint = true;
9509 const char *HeaderName = nullptr;
9510 std::string FunctionName;
9511 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9512 FunctionName = "std::abs";
9513 if (ArgType->isIntegralOrEnumerationType()) {
9514 HeaderName = "cstdlib";
9515 } else if (ArgType->isRealFloatingType()) {
9516 HeaderName = "cmath";
9517 } else {
9518 llvm_unreachable("Invalid Type");
9519 }
9520
9521 // Lookup all std::abs
9522 if (NamespaceDecl *Std = S.getStdNamespace()) {
9523 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9525 S.LookupQualifiedName(R, Std);
9526
9527 for (const auto *I : R) {
9528 const FunctionDecl *FDecl = nullptr;
9529 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9530 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9531 } else {
9532 FDecl = dyn_cast<FunctionDecl>(I);
9533 }
9534 if (!FDecl)
9535 continue;
9536
9537 // Found std::abs(), check that they are the right ones.
9538 if (FDecl->getNumParams() != 1)
9539 continue;
9540
9541 // Check that the parameter type can handle the argument.
9542 QualType ParamType = FDecl->getParamDecl(0)->getType();
9543 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9544 S.Context.getTypeSize(ArgType) <=
9545 S.Context.getTypeSize(ParamType)) {
9546 // Found a function, don't need the header hint.
9547 EmitHeaderHint = false;
9548 break;
9549 }
9550 }
9551 }
9552 } else {
9553 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9554 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9555
9556 if (HeaderName) {
9557 DeclarationName DN(&S.Context.Idents.get(FunctionName));
9558 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9560 S.LookupName(R, S.getCurScope());
9561
9562 if (R.isSingleResult()) {
9563 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9564 if (FD && FD->getBuiltinID() == AbsKind) {
9565 EmitHeaderHint = false;
9566 } else {
9567 return;
9568 }
9569 } else if (!R.empty()) {
9570 return;
9571 }
9572 }
9573 }
9574
9575 S.Diag(Loc, diag::note_replace_abs_function)
9576 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9577
9578 if (!HeaderName)
9579 return;
9580
9581 if (!EmitHeaderHint)
9582 return;
9583
9584 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9585 << FunctionName;
9586}
9587
9588template <std::size_t StrLen>
9589static bool IsStdFunction(const FunctionDecl *FDecl,
9590 const char (&Str)[StrLen]) {
9591 if (!FDecl)
9592 return false;
9593 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9594 return false;
9595 if (!FDecl->isInStdNamespace())
9596 return false;
9597
9598 return true;
9599}
9600
9601enum class MathCheck { NaN, Inf };
9602static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
9603 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
9604 return llvm::is_contained(names, calleeName);
9605 };
9606
9607 switch (Check) {
9608 case MathCheck::NaN:
9609 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
9610 "__builtin_nanf16", "__builtin_nanf128"});
9611 case MathCheck::Inf:
9612 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
9613 "__builtin_inff16", "__builtin_inff128"});
9614 }
9615 llvm_unreachable("unknown MathCheck");
9616}
9617
9618static bool IsInfinityFunction(const FunctionDecl *FDecl) {
9619 if (FDecl->getName() != "infinity")
9620 return false;
9621
9622 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
9623 const CXXRecordDecl *RDecl = MDecl->getParent();
9624 if (RDecl->getName() != "numeric_limits")
9625 return false;
9626
9627 if (const NamespaceDecl *NSDecl =
9628 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
9629 return NSDecl->isStdNamespace();
9630 }
9631
9632 return false;
9633}
9634
9635void Sema::CheckInfNaNFunction(const CallExpr *Call,
9636 const FunctionDecl *FDecl) {
9637 if (!FDecl->getIdentifier())
9638 return;
9639
9640 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
9641 if (FPO.getNoHonorNaNs() &&
9642 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
9644 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9645 << 1 << 0 << Call->getSourceRange();
9646 return;
9647 }
9648
9649 if (FPO.getNoHonorInfs() &&
9650 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
9651 IsInfinityFunction(FDecl) ||
9653 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
9654 << 0 << 0 << Call->getSourceRange();
9655 }
9656}
9657
9658void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9659 const FunctionDecl *FDecl) {
9660 if (Call->getNumArgs() != 1)
9661 return;
9662
9663 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9664 bool IsStdAbs = IsStdFunction(FDecl, "abs");
9665 if (AbsKind == 0 && !IsStdAbs)
9666 return;
9667
9668 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9669 QualType ParamType = Call->getArg(0)->getType();
9670
9671 // Unsigned types cannot be negative. Suggest removing the absolute value
9672 // function call.
9673 if (ArgType->isUnsignedIntegerType()) {
9674 std::string FunctionName =
9675 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9676 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9677 Diag(Call->getExprLoc(), diag::note_remove_abs)
9678 << FunctionName
9679 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9680 return;
9681 }
9682
9683 // Taking the absolute value of a pointer is very suspicious, they probably
9684 // wanted to index into an array, dereference a pointer, call a function, etc.
9685 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9686 unsigned DiagType = 0;
9687 if (ArgType->isFunctionType())
9688 DiagType = 1;
9689 else if (ArgType->isArrayType())
9690 DiagType = 2;
9691
9692 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9693 return;
9694 }
9695
9696 // std::abs has overloads which prevent most of the absolute value problems
9697 // from occurring.
9698 if (IsStdAbs)
9699 return;
9700
9701 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9702 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9703
9704 // The argument and parameter are the same kind. Check if they are the right
9705 // size.
9706 if (ArgValueKind == ParamValueKind) {
9707 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9708 return;
9709
9710 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9711 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9712 << FDecl << ArgType << ParamType;
9713
9714 if (NewAbsKind == 0)
9715 return;
9716
9717 emitReplacement(*this, Call->getExprLoc(),
9718 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9719 return;
9720 }
9721
9722 // ArgValueKind != ParamValueKind
9723 // The wrong type of absolute value function was used. Attempt to find the
9724 // proper one.
9725 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9726 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9727 if (NewAbsKind == 0)
9728 return;
9729
9730 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9731 << FDecl << ParamValueKind << ArgValueKind;
9732
9733 emitReplacement(*this, Call->getExprLoc(),
9734 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9735}
9736
9737//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9738void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9739 const FunctionDecl *FDecl) {
9740 if (!Call || !FDecl) return;
9741
9742 // Ignore template specializations and macros.
9743 if (inTemplateInstantiation()) return;
9744 if (Call->getExprLoc().isMacroID()) return;
9745
9746 // Only care about the one template argument, two function parameter std::max
9747 if (Call->getNumArgs() != 2) return;
9748 if (!IsStdFunction(FDecl, "max")) return;
9749 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9750 if (!ArgList) return;
9751 if (ArgList->size() != 1) return;
9752
9753 // Check that template type argument is unsigned integer.
9754 const auto& TA = ArgList->get(0);
9755 if (TA.getKind() != TemplateArgument::Type) return;
9756 QualType ArgType = TA.getAsType();
9757 if (!ArgType->isUnsignedIntegerType()) return;
9758
9759 // See if either argument is a literal zero.
9760 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9761 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9762 if (!MTE) return false;
9763 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9764 if (!Num) return false;
9765 if (Num->getValue() != 0) return false;
9766 return true;
9767 };
9768
9769 const Expr *FirstArg = Call->getArg(0);
9770 const Expr *SecondArg = Call->getArg(1);
9771 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9772 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9773
9774 // Only warn when exactly one argument is zero.
9775 if (IsFirstArgZero == IsSecondArgZero) return;
9776
9777 SourceRange FirstRange = FirstArg->getSourceRange();
9778 SourceRange SecondRange = SecondArg->getSourceRange();
9779
9780 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9781
9782 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9783 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9784
9785 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9786 SourceRange RemovalRange;
9787 if (IsFirstArgZero) {
9788 RemovalRange = SourceRange(FirstRange.getBegin(),
9789 SecondRange.getBegin().getLocWithOffset(-1));
9790 } else {
9791 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9792 SecondRange.getEnd());
9793 }
9794
9795 Diag(Call->getExprLoc(), diag::note_remove_max_call)
9796 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9797 << FixItHint::CreateRemoval(RemovalRange);
9798}
9799
9800//===--- CHECK: Standard memory functions ---------------------------------===//
9801
9802/// Takes the expression passed to the size_t parameter of functions
9803/// such as memcmp, strncat, etc and warns if it's a comparison.
9804///
9805/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9807 const IdentifierInfo *FnName,
9808 SourceLocation FnLoc,
9809 SourceLocation RParenLoc) {
9810 const auto *Size = dyn_cast<BinaryOperator>(E);
9811 if (!Size)
9812 return false;
9813
9814 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9815 if (!Size->isComparisonOp() && !Size->isLogicalOp())
9816 return false;
9817
9818 SourceRange SizeRange = Size->getSourceRange();
9819 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9820 << SizeRange << FnName;
9821 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9822 << FnName
9824 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9825 << FixItHint::CreateRemoval(RParenLoc);
9826 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9827 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9829 ")");
9830
9831 return true;
9832}
9833
9834/// Determine whether the given type is or contains a dynamic class type
9835/// (e.g., whether it has a vtable).
9837 bool &IsContained) {
9838 // Look through array types while ignoring qualifiers.
9839 const Type *Ty = T->getBaseElementTypeUnsafe();
9840 IsContained = false;
9841
9842 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9843 RD = RD ? RD->getDefinition() : nullptr;
9844 if (!RD || RD->isInvalidDecl())
9845 return nullptr;
9846
9847 if (RD->isDynamicClass())
9848 return RD;
9849
9850 // Check all the fields. If any bases were dynamic, the class is dynamic.
9851 // It's impossible for a class to transitively contain itself by value, so
9852 // infinite recursion is impossible.
9853 for (auto *FD : RD->fields()) {
9854 bool SubContained;
9855 if (const CXXRecordDecl *ContainedRD =
9856 getContainedDynamicClass(FD->getType(), SubContained)) {
9857 IsContained = true;
9858 return ContainedRD;
9859 }
9860 }
9861
9862 return nullptr;
9863}
9864
9866 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9867 if (Unary->getKind() == UETT_SizeOf)
9868 return Unary;
9869 return nullptr;
9870}
9871
9872/// If E is a sizeof expression, returns its argument expression,
9873/// otherwise returns NULL.
9874static const Expr *getSizeOfExprArg(const Expr *E) {
9876 if (!SizeOf->isArgumentType())
9877 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9878 return nullptr;
9879}
9880
9881/// If E is a sizeof expression, returns its argument type.
9884 return SizeOf->getTypeOfArgument();
9885 return QualType();
9886}
9887
9888namespace {
9889
9890struct SearchNonTrivialToInitializeField
9891 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9892 using Super =
9893 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9894
9895 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9896
9897 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9898 SourceLocation SL) {
9899 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9900 asDerived().visitArray(PDIK, AT, SL);
9901 return;
9902 }
9903
9904 Super::visitWithKind(PDIK, FT, SL);
9905 }
9906
9907 void visitARCStrong(QualType FT, SourceLocation SL) {
9908 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9909 }
9910 void visitARCWeak(QualType FT, SourceLocation SL) {
9911 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9912 }
9913 void visitStruct(QualType FT, SourceLocation SL) {
9914 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
9915 visit(FD->getType(), FD->getLocation());
9916 }
9917 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9918 const ArrayType *AT, SourceLocation SL) {
9919 visit(getContext().getBaseElementType(AT), SL);
9920 }
9921 void visitTrivial(QualType FT, SourceLocation SL) {}
9922
9923 static void diag(QualType RT, const Expr *E, Sema &S) {
9924 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9925 }
9926
9927 ASTContext &getContext() { return S.getASTContext(); }
9928
9929 const Expr *E;
9930 Sema &S;
9931};
9932
9933struct SearchNonTrivialToCopyField
9934 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9935 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9936
9937 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9938
9939 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9940 SourceLocation SL) {
9941 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9942 asDerived().visitArray(PCK, AT, SL);
9943 return;
9944 }
9945
9946 Super::visitWithKind(PCK, FT, SL);
9947 }
9948
9949 void visitARCStrong(QualType FT, SourceLocation SL) {
9950 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9951 }
9952 void visitARCWeak(QualType FT, SourceLocation SL) {
9953 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9954 }
9955 void visitPtrAuth(QualType FT, SourceLocation SL) {
9956 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9957 }
9958 void visitStruct(QualType FT, SourceLocation SL) {
9959 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
9960 visit(FD->getType(), FD->getLocation());
9961 }
9962 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9963 SourceLocation SL) {
9964 visit(getContext().getBaseElementType(AT), SL);
9965 }
9966 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9967 SourceLocation SL) {}
9968 void visitTrivial(QualType FT, SourceLocation SL) {}
9969 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9970
9971 static void diag(QualType RT, const Expr *E, Sema &S) {
9972 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9973 }
9974
9975 ASTContext &getContext() { return S.getASTContext(); }
9976
9977 const Expr *E;
9978 Sema &S;
9979};
9980
9981}
9982
9983/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9984static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9985 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9986
9987 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9988 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9989 return false;
9990
9991 return doesExprLikelyComputeSize(BO->getLHS()) ||
9992 doesExprLikelyComputeSize(BO->getRHS());
9993 }
9994
9995 return getAsSizeOfExpr(SizeofExpr) != nullptr;
9996}
9997
9998/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9999///
10000/// \code
10001/// #define MACRO 0
10002/// foo(MACRO);
10003/// foo(0);
10004/// \endcode
10005///
10006/// This should return true for the first call to foo, but not for the second
10007/// (regardless of whether foo is a macro or function).
10009 SourceLocation CallLoc,
10010 SourceLocation ArgLoc) {
10011 if (!CallLoc.isMacroID())
10012 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10013
10014 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10015 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10016}
10017
10018/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10019/// last two arguments transposed.
10020static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10021 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10022 return;
10023
10024 const Expr *SizeArg =
10025 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10026
10027 auto isLiteralZero = [](const Expr *E) {
10028 return (isa<IntegerLiteral>(E) &&
10029 cast<IntegerLiteral>(E)->getValue() == 0) ||
10031 cast<CharacterLiteral>(E)->getValue() == 0);
10032 };
10033
10034 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10035 SourceLocation CallLoc = Call->getRParenLoc();
10037 if (isLiteralZero(SizeArg) &&
10038 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10039
10040 SourceLocation DiagLoc = SizeArg->getExprLoc();
10041
10042 // Some platforms #define bzero to __builtin_memset. See if this is the
10043 // case, and if so, emit a better diagnostic.
10044 if (BId == Builtin::BIbzero ||
10046 CallLoc, SM, S.getLangOpts()) == "bzero")) {
10047 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10048 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10049 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10050 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10051 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10052 }
10053 return;
10054 }
10055
10056 // If the second argument to a memset is a sizeof expression and the third
10057 // isn't, this is also likely an error. This should catch
10058 // 'memset(buf, sizeof(buf), 0xff)'.
10059 if (BId == Builtin::BImemset &&
10060 doesExprLikelyComputeSize(Call->getArg(1)) &&
10061 !doesExprLikelyComputeSize(Call->getArg(2))) {
10062 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10063 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10064 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10065 return;
10066 }
10067}
10068
10069void Sema::CheckMemaccessArguments(const CallExpr *Call,
10070 unsigned BId,
10071 IdentifierInfo *FnName) {
10072 assert(BId != 0);
10073
10074 // It is possible to have a non-standard definition of memset. Validate
10075 // we have enough arguments, and if not, abort further checking.
10076 unsigned ExpectedNumArgs =
10077 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10078 if (Call->getNumArgs() < ExpectedNumArgs)
10079 return;
10080
10081 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10082 BId == Builtin::BIstrndup ? 1 : 2);
10083 unsigned LenArg =
10084 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10085 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10086
10087 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10088 Call->getBeginLoc(), Call->getRParenLoc()))
10089 return;
10090
10091 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10092 CheckMemaccessSize(*this, BId, Call);
10093
10094 // We have special checking when the length is a sizeof expression.
10095 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10096 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10097 llvm::FoldingSetNodeID SizeOfArgID;
10098
10099 // Although widely used, 'bzero' is not a standard function. Be more strict
10100 // with the argument types before allowing diagnostics and only allow the
10101 // form bzero(ptr, sizeof(...)).
10102 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10103 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10104 return;
10105
10106 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10107 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10108 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10109
10110 QualType DestTy = Dest->getType();
10111 QualType PointeeTy;
10112 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10113 PointeeTy = DestPtrTy->getPointeeType();
10114
10115 // Never warn about void type pointers. This can be used to suppress
10116 // false positives.
10117 if (PointeeTy->isVoidType())
10118 continue;
10119
10120 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10121 // actually comparing the expressions for equality. Because computing the
10122 // expression IDs can be expensive, we only do this if the diagnostic is
10123 // enabled.
10124 if (SizeOfArg &&
10125 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10126 SizeOfArg->getExprLoc())) {
10127 // We only compute IDs for expressions if the warning is enabled, and
10128 // cache the sizeof arg's ID.
10129 if (SizeOfArgID == llvm::FoldingSetNodeID())
10130 SizeOfArg->Profile(SizeOfArgID, Context, true);
10131 llvm::FoldingSetNodeID DestID;
10132 Dest->Profile(DestID, Context, true);
10133 if (DestID == SizeOfArgID) {
10134 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10135 // over sizeof(src) as well.
10136 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10137 StringRef ReadableName = FnName->getName();
10138
10139 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10140 if (UnaryOp->getOpcode() == UO_AddrOf)
10141 ActionIdx = 1; // If its an address-of operator, just remove it.
10142 if (!PointeeTy->isIncompleteType() &&
10143 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10144 ActionIdx = 2; // If the pointee's size is sizeof(char),
10145 // suggest an explicit length.
10146
10147 // If the function is defined as a builtin macro, do not show macro
10148 // expansion.
10149 SourceLocation SL = SizeOfArg->getExprLoc();
10150 SourceRange DSR = Dest->getSourceRange();
10151 SourceRange SSR = SizeOfArg->getSourceRange();
10152 SourceManager &SM = getSourceManager();
10153
10154 if (SM.isMacroArgExpansion(SL)) {
10155 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10156 SL = SM.getSpellingLoc(SL);
10157 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10158 SM.getSpellingLoc(DSR.getEnd()));
10159 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10160 SM.getSpellingLoc(SSR.getEnd()));
10161 }
10162
10163 DiagRuntimeBehavior(SL, SizeOfArg,
10164 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10165 << ReadableName
10166 << PointeeTy
10167 << DestTy
10168 << DSR
10169 << SSR);
10170 DiagRuntimeBehavior(SL, SizeOfArg,
10171 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10172 << ActionIdx
10173 << SSR);
10174
10175 break;
10176 }
10177 }
10178
10179 // Also check for cases where the sizeof argument is the exact same
10180 // type as the memory argument, and where it points to a user-defined
10181 // record type.
10182 if (SizeOfArgTy != QualType()) {
10183 if (PointeeTy->isRecordType() &&
10184 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10185 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10186 PDiag(diag::warn_sizeof_pointer_type_memaccess)
10187 << FnName << SizeOfArgTy << ArgIdx
10188 << PointeeTy << Dest->getSourceRange()
10189 << LenExpr->getSourceRange());
10190 break;
10191 }
10192 }
10193 } else if (DestTy->isArrayType()) {
10194 PointeeTy = DestTy;
10195 }
10196
10197 if (PointeeTy == QualType())
10198 continue;
10199
10200 // Always complain about dynamic classes.
10201 bool IsContained;
10202 if (const CXXRecordDecl *ContainedRD =
10203 getContainedDynamicClass(PointeeTy, IsContained)) {
10204
10205 unsigned OperationType = 0;
10206 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10207 // "overwritten" if we're warning about the destination for any call
10208 // but memcmp; otherwise a verb appropriate to the call.
10209 if (ArgIdx != 0 || IsCmp) {
10210 if (BId == Builtin::BImemcpy)
10211 OperationType = 1;
10212 else if(BId == Builtin::BImemmove)
10213 OperationType = 2;
10214 else if (IsCmp)
10215 OperationType = 3;
10216 }
10217
10218 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10219 PDiag(diag::warn_dyn_class_memaccess)
10220 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10221 << IsContained << ContainedRD << OperationType
10222 << Call->getCallee()->getSourceRange());
10223 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10224 BId != Builtin::BImemset)
10226 Dest->getExprLoc(), Dest,
10227 PDiag(diag::warn_arc_object_memaccess)
10228 << ArgIdx << FnName << PointeeTy
10229 << Call->getCallee()->getSourceRange());
10230 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10231
10232 // FIXME: Do not consider incomplete types even though they may be
10233 // completed later. GCC does not diagnose such code, but we may want to
10234 // consider diagnosing it in the future, perhaps under a different, but
10235 // related, diagnostic group.
10236 bool NonTriviallyCopyableCXXRecord =
10237 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10238 !PointeeTy.isTriviallyCopyableType(Context);
10239
10240 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10242 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10243 PDiag(diag::warn_cstruct_memaccess)
10244 << ArgIdx << FnName << PointeeTy << 0);
10245 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10246 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10247 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10248 // FIXME: Limiting this warning to dest argument until we decide
10249 // whether it's valid for source argument too.
10250 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10251 PDiag(diag::warn_cxxstruct_memaccess)
10252 << FnName << PointeeTy);
10253 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10255 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10256 PDiag(diag::warn_cstruct_memaccess)
10257 << ArgIdx << FnName << PointeeTy << 1);
10258 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10259 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10260 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10261 // FIXME: Limiting this warning to dest argument until we decide
10262 // whether it's valid for source argument too.
10263 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10264 PDiag(diag::warn_cxxstruct_memaccess)
10265 << FnName << PointeeTy);
10266 } else {
10267 continue;
10268 }
10269 } else
10270 continue;
10271
10273 Dest->getExprLoc(), Dest,
10274 PDiag(diag::note_bad_memaccess_silence)
10275 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10276 break;
10277 }
10278}
10279
10280// A little helper routine: ignore addition and subtraction of integer literals.
10281// This intentionally does not ignore all integer constant expressions because
10282// we don't want to remove sizeof().
10283static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10284 Ex = Ex->IgnoreParenCasts();
10285
10286 while (true) {
10287 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10288 if (!BO || !BO->isAdditiveOp())
10289 break;
10290
10291 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10292 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10293
10294 if (isa<IntegerLiteral>(RHS))
10295 Ex = LHS;
10296 else if (isa<IntegerLiteral>(LHS))
10297 Ex = RHS;
10298 else
10299 break;
10300 }
10301
10302 return Ex;
10303}
10304
10306 ASTContext &Context) {
10307 // Only handle constant-sized or VLAs, but not flexible members.
10308 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10309 // Only issue the FIXIT for arrays of size > 1.
10310 if (CAT->getZExtSize() <= 1)
10311 return false;
10312 } else if (!Ty->isVariableArrayType()) {
10313 return false;
10314 }
10315 return true;
10316}
10317
10318void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10319 IdentifierInfo *FnName) {
10320
10321 // Don't crash if the user has the wrong number of arguments
10322 unsigned NumArgs = Call->getNumArgs();
10323 if ((NumArgs != 3) && (NumArgs != 4))
10324 return;
10325
10326 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10327 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10328 const Expr *CompareWithSrc = nullptr;
10329
10330 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10331 Call->getBeginLoc(), Call->getRParenLoc()))
10332 return;
10333
10334 // Look for 'strlcpy(dst, x, sizeof(x))'
10335 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10336 CompareWithSrc = Ex;
10337 else {
10338 // Look for 'strlcpy(dst, x, strlen(x))'
10339 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10340 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10341 SizeCall->getNumArgs() == 1)
10342 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10343 }
10344 }
10345
10346 if (!CompareWithSrc)
10347 return;
10348
10349 // Determine if the argument to sizeof/strlen is equal to the source
10350 // argument. In principle there's all kinds of things you could do
10351 // here, for instance creating an == expression and evaluating it with
10352 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10353 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10354 if (!SrcArgDRE)
10355 return;
10356
10357 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10358 if (!CompareWithSrcDRE ||
10359 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10360 return;
10361
10362 const Expr *OriginalSizeArg = Call->getArg(2);
10363 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10364 << OriginalSizeArg->getSourceRange() << FnName;
10365
10366 // Output a FIXIT hint if the destination is an array (rather than a
10367 // pointer to an array). This could be enhanced to handle some
10368 // pointers if we know the actual size, like if DstArg is 'array+2'
10369 // we could say 'sizeof(array)-2'.
10370 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10372 return;
10373
10374 SmallString<128> sizeString;
10375 llvm::raw_svector_ostream OS(sizeString);
10376 OS << "sizeof(";
10377 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10378 OS << ")";
10379
10380 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10381 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10382 OS.str());
10383}
10384
10385/// Check if two expressions refer to the same declaration.
10386static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10387 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10388 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10389 return D1->getDecl() == D2->getDecl();
10390 return false;
10391}
10392
10393static const Expr *getStrlenExprArg(const Expr *E) {
10394 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10395 const FunctionDecl *FD = CE->getDirectCallee();
10396 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10397 return nullptr;
10398 return CE->getArg(0)->IgnoreParenCasts();
10399 }
10400 return nullptr;
10401}
10402
10403void Sema::CheckStrncatArguments(const CallExpr *CE,
10404 const IdentifierInfo *FnName) {
10405 // Don't crash if the user has the wrong number of arguments.
10406 if (CE->getNumArgs() < 3)
10407 return;
10408 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10409 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10410 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10411
10412 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10413 CE->getRParenLoc()))
10414 return;
10415
10416 // Identify common expressions, which are wrongly used as the size argument
10417 // to strncat and may lead to buffer overflows.
10418 unsigned PatternType = 0;
10419 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10420 // - sizeof(dst)
10421 if (referToTheSameDecl(SizeOfArg, DstArg))
10422 PatternType = 1;
10423 // - sizeof(src)
10424 else if (referToTheSameDecl(SizeOfArg, SrcArg))
10425 PatternType = 2;
10426 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10427 if (BE->getOpcode() == BO_Sub) {
10428 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10429 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10430 // - sizeof(dst) - strlen(dst)
10431 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10433 PatternType = 1;
10434 // - sizeof(src) - (anything)
10435 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10436 PatternType = 2;
10437 }
10438 }
10439
10440 if (PatternType == 0)
10441 return;
10442
10443 // Generate the diagnostic.
10444 SourceLocation SL = LenArg->getBeginLoc();
10445 SourceRange SR = LenArg->getSourceRange();
10446 SourceManager &SM = getSourceManager();
10447
10448 // If the function is defined as a builtin macro, do not show macro expansion.
10449 if (SM.isMacroArgExpansion(SL)) {
10450 SL = SM.getSpellingLoc(SL);
10451 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10452 SM.getSpellingLoc(SR.getEnd()));
10453 }
10454
10455 // Check if the destination is an array (rather than a pointer to an array).
10456 QualType DstTy = DstArg->getType();
10457 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10458 Context);
10459 if (!isKnownSizeArray) {
10460 if (PatternType == 1)
10461 Diag(SL, diag::warn_strncat_wrong_size) << SR;
10462 else
10463 Diag(SL, diag::warn_strncat_src_size) << SR;
10464 return;
10465 }
10466
10467 if (PatternType == 1)
10468 Diag(SL, diag::warn_strncat_large_size) << SR;
10469 else
10470 Diag(SL, diag::warn_strncat_src_size) << SR;
10471
10472 SmallString<128> sizeString;
10473 llvm::raw_svector_ostream OS(sizeString);
10474 OS << "sizeof(";
10475 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10476 OS << ") - ";
10477 OS << "strlen(";
10478 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10479 OS << ") - 1";
10480
10481 Diag(SL, diag::note_strncat_wrong_size)
10482 << FixItHint::CreateReplacement(SR, OS.str());
10483}
10484
10485namespace {
10486void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10487 const UnaryOperator *UnaryExpr, const Decl *D) {
10489 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10490 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10491 return;
10492 }
10493}
10494
10495void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10496 const UnaryOperator *UnaryExpr) {
10497 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10498 const Decl *D = Lvalue->getDecl();
10499 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
10500 if (!DD->getType()->isReferenceType())
10501 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10502 }
10503 }
10504
10505 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10506 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10507 Lvalue->getMemberDecl());
10508}
10509
10510void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10511 const UnaryOperator *UnaryExpr) {
10512 const auto *Lambda = dyn_cast<LambdaExpr>(
10514 if (!Lambda)
10515 return;
10516
10517 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10518 << CalleeName << 2 /*object: lambda expression*/;
10519}
10520
10521void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10522 const DeclRefExpr *Lvalue) {
10523 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10524 if (Var == nullptr)
10525 return;
10526
10527 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10528 << CalleeName << 0 /*object: */ << Var;
10529}
10530
10531void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10532 const CastExpr *Cast) {
10533 SmallString<128> SizeString;
10534 llvm::raw_svector_ostream OS(SizeString);
10535
10536 clang::CastKind Kind = Cast->getCastKind();
10537 if (Kind == clang::CK_BitCast &&
10538 !Cast->getSubExpr()->getType()->isFunctionPointerType())
10539 return;
10540 if (Kind == clang::CK_IntegralToPointer &&
10542 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10543 return;
10544
10545 switch (Cast->getCastKind()) {
10546 case clang::CK_BitCast:
10547 case clang::CK_IntegralToPointer:
10548 case clang::CK_FunctionToPointerDecay:
10549 OS << '\'';
10550 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10551 OS << '\'';
10552 break;
10553 default:
10554 return;
10555 }
10556
10557 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10558 << CalleeName << 0 /*object: */ << OS.str();
10559}
10560} // namespace
10561
10562void Sema::CheckFreeArguments(const CallExpr *E) {
10563 const std::string CalleeName =
10564 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10565
10566 { // Prefer something that doesn't involve a cast to make things simpler.
10567 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10568 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10569 switch (UnaryExpr->getOpcode()) {
10570 case UnaryOperator::Opcode::UO_AddrOf:
10571 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10572 case UnaryOperator::Opcode::UO_Plus:
10573 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10574 default:
10575 break;
10576 }
10577
10578 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10579 if (Lvalue->getType()->isArrayType())
10580 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10581
10582 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10583 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10584 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10585 return;
10586 }
10587
10588 if (isa<BlockExpr>(Arg)) {
10589 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10590 << CalleeName << 1 /*object: block*/;
10591 return;
10592 }
10593 }
10594 // Maybe the cast was important, check after the other cases.
10595 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10596 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10597}
10598
10599void
10600Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10601 SourceLocation ReturnLoc,
10602 bool isObjCMethod,
10603 const AttrVec *Attrs,
10604 const FunctionDecl *FD) {
10605 // Check if the return value is null but should not be.
10606 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10607 (!isObjCMethod && isNonNullType(lhsType))) &&
10608 CheckNonNullExpr(*this, RetValExp))
10609 Diag(ReturnLoc, diag::warn_null_ret)
10610 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10611
10612 // C++11 [basic.stc.dynamic.allocation]p4:
10613 // If an allocation function declared with a non-throwing
10614 // exception-specification fails to allocate storage, it shall return
10615 // a null pointer. Any other allocation function that fails to allocate
10616 // storage shall indicate failure only by throwing an exception [...]
10617 if (FD) {
10619 if (Op == OO_New || Op == OO_Array_New) {
10620 const FunctionProtoType *Proto
10621 = FD->getType()->castAs<FunctionProtoType>();
10622 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10623 CheckNonNullExpr(*this, RetValExp))
10624 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10625 << FD << getLangOpts().CPlusPlus11;
10626 }
10627 }
10628
10629 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
10630 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
10631 }
10632
10633 // PPC MMA non-pointer types are not allowed as return type. Checking the type
10634 // here prevent the user from using a PPC MMA type as trailing return type.
10635 if (Context.getTargetInfo().getTriple().isPPC64())
10636 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10637}
10638
10640 const Expr *RHS, BinaryOperatorKind Opcode) {
10641 if (!BinaryOperator::isEqualityOp(Opcode))
10642 return;
10643
10644 // Match and capture subexpressions such as "(float) X == 0.1".
10645 const FloatingLiteral *FPLiteral;
10646 const CastExpr *FPCast;
10647 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
10648 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
10649 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
10650 return FPLiteral && FPCast;
10651 };
10652
10653 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
10654 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
10655 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
10656 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
10657 TargetTy->isFloatingPoint()) {
10658 bool Lossy;
10659 llvm::APFloat TargetC = FPLiteral->getValue();
10660 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
10661 llvm::APFloat::rmNearestTiesToEven, &Lossy);
10662 if (Lossy) {
10663 // If the literal cannot be represented in the source type, then a
10664 // check for == is always false and check for != is always true.
10665 Diag(Loc, diag::warn_float_compare_literal)
10666 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
10667 << LHS->getSourceRange() << RHS->getSourceRange();
10668 return;
10669 }
10670 }
10671 }
10672
10673 // Match a more general floating-point equality comparison (-Wfloat-equal).
10674 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
10675 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
10676
10677 // Special case: check for x == x (which is OK).
10678 // Do not emit warnings for such cases.
10679 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10680 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10681 if (DRL->getDecl() == DRR->getDecl())
10682 return;
10683
10684 // Special case: check for comparisons against literals that can be exactly
10685 // represented by APFloat. In such cases, do not emit a warning. This
10686 // is a heuristic: often comparison against such literals are used to
10687 // detect if a value in a variable has not changed. This clearly can
10688 // lead to false negatives.
10689 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10690 if (FLL->isExact())
10691 return;
10692 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10693 if (FLR->isExact())
10694 return;
10695
10696 // Check for comparisons with builtin types.
10697 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
10698 CL && CL->getBuiltinCallee())
10699 return;
10700
10701 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
10702 CR && CR->getBuiltinCallee())
10703 return;
10704
10705 // Emit the diagnostic.
10706 Diag(Loc, diag::warn_floatingpoint_eq)
10707 << LHS->getSourceRange() << RHS->getSourceRange();
10708}
10709
10710//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10711//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10712
10713namespace {
10714
10715/// Structure recording the 'active' range of an integer-valued
10716/// expression.
10717struct IntRange {
10718 /// The number of bits active in the int. Note that this includes exactly one
10719 /// sign bit if !NonNegative.
10720 unsigned Width;
10721
10722 /// True if the int is known not to have negative values. If so, all leading
10723 /// bits before Width are known zero, otherwise they are known to be the
10724 /// same as the MSB within Width.
10725 bool NonNegative;
10726
10727 IntRange(unsigned Width, bool NonNegative)
10728 : Width(Width), NonNegative(NonNegative) {}
10729
10730 /// Number of bits excluding the sign bit.
10731 unsigned valueBits() const {
10732 return NonNegative ? Width : Width - 1;
10733 }
10734
10735 /// Returns the range of the bool type.
10736 static IntRange forBoolType() {
10737 return IntRange(1, true);
10738 }
10739
10740 /// Returns the range of an opaque value of the given integral type.
10741 static IntRange forValueOfType(ASTContext &C, QualType T) {
10742 return forValueOfCanonicalType(C,
10744 }
10745
10746 /// Returns the range of an opaque value of a canonical integral type.
10747 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10748 assert(T->isCanonicalUnqualified());
10749
10750 if (const auto *VT = dyn_cast<VectorType>(T))
10751 T = VT->getElementType().getTypePtr();
10752 if (const auto *CT = dyn_cast<ComplexType>(T))
10753 T = CT->getElementType().getTypePtr();
10754 if (const auto *AT = dyn_cast<AtomicType>(T))
10755 T = AT->getValueType().getTypePtr();
10756
10757 if (!C.getLangOpts().CPlusPlus) {
10758 // For enum types in C code, use the underlying datatype.
10759 if (const auto *ED = T->getAsEnumDecl())
10760 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
10761 } else if (auto *Enum = T->getAsEnumDecl()) {
10762 // For enum types in C++, use the known bit width of the enumerators.
10763 // In C++11, enums can have a fixed underlying type. Use this type to
10764 // compute the range.
10765 if (Enum->isFixed()) {
10766 return IntRange(C.getIntWidth(QualType(T, 0)),
10767 !Enum->getIntegerType()->isSignedIntegerType());
10768 }
10769
10770 unsigned NumPositive = Enum->getNumPositiveBits();
10771 unsigned NumNegative = Enum->getNumNegativeBits();
10772
10773 if (NumNegative == 0)
10774 return IntRange(NumPositive, true/*NonNegative*/);
10775 else
10776 return IntRange(std::max(NumPositive + 1, NumNegative),
10777 false/*NonNegative*/);
10778 }
10779
10780 if (const auto *EIT = dyn_cast<BitIntType>(T))
10781 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10782
10783 const BuiltinType *BT = cast<BuiltinType>(T);
10784 assert(BT->isInteger());
10785
10786 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10787 }
10788
10789 /// Returns the "target" range of a canonical integral type, i.e.
10790 /// the range of values expressible in the type.
10791 ///
10792 /// This matches forValueOfCanonicalType except that enums have the
10793 /// full range of their type, not the range of their enumerators.
10794 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10795 assert(T->isCanonicalUnqualified());
10796
10797 if (const VectorType *VT = dyn_cast<VectorType>(T))
10798 T = VT->getElementType().getTypePtr();
10799 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10800 T = CT->getElementType().getTypePtr();
10801 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10802 T = AT->getValueType().getTypePtr();
10803 if (const auto *ED = T->getAsEnumDecl())
10804 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
10805
10806 if (const auto *EIT = dyn_cast<BitIntType>(T))
10807 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10808
10809 const BuiltinType *BT = cast<BuiltinType>(T);
10810 assert(BT->isInteger());
10811
10812 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10813 }
10814
10815 /// Returns the supremum of two ranges: i.e. their conservative merge.
10816 static IntRange join(IntRange L, IntRange R) {
10817 bool Unsigned = L.NonNegative && R.NonNegative;
10818 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10819 L.NonNegative && R.NonNegative);
10820 }
10821
10822 /// Return the range of a bitwise-AND of the two ranges.
10823 static IntRange bit_and(IntRange L, IntRange R) {
10824 unsigned Bits = std::max(L.Width, R.Width);
10825 bool NonNegative = false;
10826 if (L.NonNegative) {
10827 Bits = std::min(Bits, L.Width);
10828 NonNegative = true;
10829 }
10830 if (R.NonNegative) {
10831 Bits = std::min(Bits, R.Width);
10832 NonNegative = true;
10833 }
10834 return IntRange(Bits, NonNegative);
10835 }
10836
10837 /// Return the range of a sum of the two ranges.
10838 static IntRange sum(IntRange L, IntRange R) {
10839 bool Unsigned = L.NonNegative && R.NonNegative;
10840 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10841 Unsigned);
10842 }
10843
10844 /// Return the range of a difference of the two ranges.
10845 static IntRange difference(IntRange L, IntRange R) {
10846 // We need a 1-bit-wider range if:
10847 // 1) LHS can be negative: least value can be reduced.
10848 // 2) RHS can be negative: greatest value can be increased.
10849 bool CanWiden = !L.NonNegative || !R.NonNegative;
10850 bool Unsigned = L.NonNegative && R.Width == 0;
10851 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10852 !Unsigned,
10853 Unsigned);
10854 }
10855
10856 /// Return the range of a product of the two ranges.
10857 static IntRange product(IntRange L, IntRange R) {
10858 // If both LHS and RHS can be negative, we can form
10859 // -2^L * -2^R = 2^(L + R)
10860 // which requires L + R + 1 value bits to represent.
10861 bool CanWiden = !L.NonNegative && !R.NonNegative;
10862 bool Unsigned = L.NonNegative && R.NonNegative;
10863 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10864 Unsigned);
10865 }
10866
10867 /// Return the range of a remainder operation between the two ranges.
10868 static IntRange rem(IntRange L, IntRange R) {
10869 // The result of a remainder can't be larger than the result of
10870 // either side. The sign of the result is the sign of the LHS.
10871 bool Unsigned = L.NonNegative;
10872 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10873 Unsigned);
10874 }
10875};
10876
10877} // namespace
10878
10879static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
10880 if (value.isSigned() && value.isNegative())
10881 return IntRange(value.getSignificantBits(), false);
10882
10883 if (value.getBitWidth() > MaxWidth)
10884 value = value.trunc(MaxWidth);
10885
10886 // isNonNegative() just checks the sign bit without considering
10887 // signedness.
10888 return IntRange(value.getActiveBits(), true);
10889}
10890
10891static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
10892 if (result.isInt())
10893 return GetValueRange(result.getInt(), MaxWidth);
10894
10895 if (result.isVector()) {
10896 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
10897 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10898 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
10899 R = IntRange::join(R, El);
10900 }
10901 return R;
10902 }
10903
10904 if (result.isComplexInt()) {
10905 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
10906 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
10907 return IntRange::join(R, I);
10908 }
10909
10910 // This can happen with lossless casts to intptr_t of "based" lvalues.
10911 // Assume it might use arbitrary bits.
10912 // FIXME: The only reason we need to pass the type in here is to get
10913 // the sign right on this one case. It would be nice if APValue
10914 // preserved this.
10915 assert(result.isLValue() || result.isAddrLabelDiff());
10916 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10917}
10918
10919static QualType GetExprType(const Expr *E) {
10920 QualType Ty = E->getType();
10921 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
10922 Ty = AtomicRHS->getValueType();
10923 return Ty;
10924}
10925
10926/// Attempts to estimate an approximate range for the given integer expression.
10927/// Returns a range if successful, otherwise it returns \c std::nullopt if a
10928/// reliable estimation cannot be determined.
10929///
10930/// \param MaxWidth The width to which the value will be truncated.
10931/// \param InConstantContext If \c true, interpret the expression within a
10932/// constant context.
10933/// \param Approximate If \c true, provide a likely range of values by assuming
10934/// that arithmetic on narrower types remains within those types.
10935/// If \c false, return a range that includes all possible values
10936/// resulting from the expression.
10937/// \returns A range of values that the expression might take, or
10938/// std::nullopt if a reliable estimation cannot be determined.
10939static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
10940 unsigned MaxWidth,
10941 bool InConstantContext,
10942 bool Approximate) {
10943 E = E->IgnoreParens();
10944
10945 // Try a full evaluation first.
10946 Expr::EvalResult result;
10947 if (E->EvaluateAsRValue(result, C, InConstantContext))
10948 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
10949
10950 // I think we only want to look through implicit casts here; if the
10951 // user has an explicit widening cast, we should treat the value as
10952 // being of the new, wider type.
10953 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10954 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10955 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10956 Approximate);
10957
10958 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10959
10960 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10961 CE->getCastKind() == CK_BooleanToSignedIntegral;
10962
10963 // Assume that non-integer casts can span the full range of the type.
10964 if (!isIntegerCast)
10965 return OutputTypeRange;
10966
10967 std::optional<IntRange> SubRange = TryGetExprRange(
10968 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
10969 InConstantContext, Approximate);
10970 if (!SubRange)
10971 return std::nullopt;
10972
10973 // Bail out if the subexpr's range is as wide as the cast type.
10974 if (SubRange->Width >= OutputTypeRange.Width)
10975 return OutputTypeRange;
10976
10977 // Otherwise, we take the smaller width, and we're non-negative if
10978 // either the output type or the subexpr is.
10979 return IntRange(SubRange->Width,
10980 SubRange->NonNegative || OutputTypeRange.NonNegative);
10981 }
10982
10983 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10984 // If we can fold the condition, just take that operand.
10985 bool CondResult;
10986 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10987 return TryGetExprRange(
10988 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
10989 InConstantContext, Approximate);
10990
10991 // Otherwise, conservatively merge.
10992 // TryGetExprRange requires an integer expression, but a throw expression
10993 // results in a void type.
10994 Expr *TrueExpr = CO->getTrueExpr();
10995 if (TrueExpr->getType()->isVoidType())
10996 return std::nullopt;
10997
10998 std::optional<IntRange> L =
10999 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
11000 if (!L)
11001 return std::nullopt;
11002
11003 Expr *FalseExpr = CO->getFalseExpr();
11004 if (FalseExpr->getType()->isVoidType())
11005 return std::nullopt;
11006
11007 std::optional<IntRange> R =
11008 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
11009 if (!R)
11010 return std::nullopt;
11011
11012 return IntRange::join(*L, *R);
11013 }
11014
11015 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11016 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11017
11018 switch (BO->getOpcode()) {
11019 case BO_Cmp:
11020 llvm_unreachable("builtin <=> should have class type");
11021
11022 // Boolean-valued operations are single-bit and positive.
11023 case BO_LAnd:
11024 case BO_LOr:
11025 case BO_LT:
11026 case BO_GT:
11027 case BO_LE:
11028 case BO_GE:
11029 case BO_EQ:
11030 case BO_NE:
11031 return IntRange::forBoolType();
11032
11033 // The type of the assignments is the type of the LHS, so the RHS
11034 // is not necessarily the same type.
11035 case BO_MulAssign:
11036 case BO_DivAssign:
11037 case BO_RemAssign:
11038 case BO_AddAssign:
11039 case BO_SubAssign:
11040 case BO_XorAssign:
11041 case BO_OrAssign:
11042 // TODO: bitfields?
11043 return IntRange::forValueOfType(C, GetExprType(E));
11044
11045 // Simple assignments just pass through the RHS, which will have
11046 // been coerced to the LHS type.
11047 case BO_Assign:
11048 // TODO: bitfields?
11049 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11050 Approximate);
11051
11052 // Operations with opaque sources are black-listed.
11053 case BO_PtrMemD:
11054 case BO_PtrMemI:
11055 return IntRange::forValueOfType(C, GetExprType(E));
11056
11057 // Bitwise-and uses the *infinum* of the two source ranges.
11058 case BO_And:
11059 case BO_AndAssign:
11060 Combine = IntRange::bit_and;
11061 break;
11062
11063 // Left shift gets black-listed based on a judgement call.
11064 case BO_Shl:
11065 // ...except that we want to treat '1 << (blah)' as logically
11066 // positive. It's an important idiom.
11067 if (IntegerLiteral *I
11068 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11069 if (I->getValue() == 1) {
11070 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11071 return IntRange(R.Width, /*NonNegative*/ true);
11072 }
11073 }
11074 [[fallthrough]];
11075
11076 case BO_ShlAssign:
11077 return IntRange::forValueOfType(C, GetExprType(E));
11078
11079 // Right shift by a constant can narrow its left argument.
11080 case BO_Shr:
11081 case BO_ShrAssign: {
11082 std::optional<IntRange> L = TryGetExprRange(
11083 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11084 if (!L)
11085 return std::nullopt;
11086
11087 // If the shift amount is a positive constant, drop the width by
11088 // that much.
11089 if (std::optional<llvm::APSInt> shift =
11090 BO->getRHS()->getIntegerConstantExpr(C)) {
11091 if (shift->isNonNegative()) {
11092 if (shift->uge(L->Width))
11093 L->Width = (L->NonNegative ? 0 : 1);
11094 else
11095 L->Width -= shift->getZExtValue();
11096 }
11097 }
11098
11099 return L;
11100 }
11101
11102 // Comma acts as its right operand.
11103 case BO_Comma:
11104 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11105 Approximate);
11106
11107 case BO_Add:
11108 if (!Approximate)
11109 Combine = IntRange::sum;
11110 break;
11111
11112 case BO_Sub:
11113 if (BO->getLHS()->getType()->isPointerType())
11114 return IntRange::forValueOfType(C, GetExprType(E));
11115 if (!Approximate)
11116 Combine = IntRange::difference;
11117 break;
11118
11119 case BO_Mul:
11120 if (!Approximate)
11121 Combine = IntRange::product;
11122 break;
11123
11124 // The width of a division result is mostly determined by the size
11125 // of the LHS.
11126 case BO_Div: {
11127 // Don't 'pre-truncate' the operands.
11128 unsigned opWidth = C.getIntWidth(GetExprType(E));
11129 std::optional<IntRange> L = TryGetExprRange(
11130 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11131 if (!L)
11132 return std::nullopt;
11133
11134 // If the divisor is constant, use that.
11135 if (std::optional<llvm::APSInt> divisor =
11136 BO->getRHS()->getIntegerConstantExpr(C)) {
11137 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11138 if (log2 >= L->Width)
11139 L->Width = (L->NonNegative ? 0 : 1);
11140 else
11141 L->Width = std::min(L->Width - log2, MaxWidth);
11142 return L;
11143 }
11144
11145 // Otherwise, just use the LHS's width.
11146 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11147 // could be -1.
11148 std::optional<IntRange> R = TryGetExprRange(
11149 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11150 if (!R)
11151 return std::nullopt;
11152
11153 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11154 }
11155
11156 case BO_Rem:
11157 Combine = IntRange::rem;
11158 break;
11159
11160 // The default behavior is okay for these.
11161 case BO_Xor:
11162 case BO_Or:
11163 break;
11164 }
11165
11166 // Combine the two ranges, but limit the result to the type in which we
11167 // performed the computation.
11168 QualType T = GetExprType(E);
11169 unsigned opWidth = C.getIntWidth(T);
11170 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
11171 InConstantContext, Approximate);
11172 if (!L)
11173 return std::nullopt;
11174
11175 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
11176 InConstantContext, Approximate);
11177 if (!R)
11178 return std::nullopt;
11179
11180 IntRange C = Combine(*L, *R);
11181 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11182 C.Width = std::min(C.Width, MaxWidth);
11183 return C;
11184 }
11185
11186 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11187 switch (UO->getOpcode()) {
11188 // Boolean-valued operations are white-listed.
11189 case UO_LNot:
11190 return IntRange::forBoolType();
11191
11192 // Operations with opaque sources are black-listed.
11193 case UO_Deref:
11194 case UO_AddrOf: // should be impossible
11195 return IntRange::forValueOfType(C, GetExprType(E));
11196
11197 case UO_Minus: {
11198 if (E->getType()->isUnsignedIntegerType()) {
11199 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11200 Approximate);
11201 }
11202
11203 std::optional<IntRange> SubRange = TryGetExprRange(
11204 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11205
11206 if (!SubRange)
11207 return std::nullopt;
11208
11209 // If the range was previously non-negative, we need an extra bit for the
11210 // sign bit. Otherwise, we need an extra bit because the negation of the
11211 // most-negative value is one bit wider than that value.
11212 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
11213 }
11214
11215 case UO_Not: {
11216 if (E->getType()->isUnsignedIntegerType()) {
11217 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11218 Approximate);
11219 }
11220
11221 std::optional<IntRange> SubRange = TryGetExprRange(
11222 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11223
11224 if (!SubRange)
11225 return std::nullopt;
11226
11227 // The width increments by 1 if the sub-expression cannot be negative
11228 // since it now can be.
11229 return IntRange(
11230 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
11231 false);
11232 }
11233
11234 default:
11235 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11236 Approximate);
11237 }
11238 }
11239
11240 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11241 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11242 Approximate);
11243
11244 if (const auto *BitField = E->getSourceBitField())
11245 return IntRange(BitField->getBitWidthValue(),
11246 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11247
11248 if (GetExprType(E)->isVoidType())
11249 return std::nullopt;
11250
11251 return IntRange::forValueOfType(C, GetExprType(E));
11252}
11253
11254static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11255 bool InConstantContext,
11256 bool Approximate) {
11257 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11258 Approximate);
11259}
11260
11261/// Checks whether the given value, which currently has the given
11262/// source semantics, has the same value when coerced through the
11263/// target semantics.
11264static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11265 const llvm::fltSemantics &Src,
11266 const llvm::fltSemantics &Tgt) {
11267 llvm::APFloat truncated = value;
11268
11269 bool ignored;
11270 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11271 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11272
11273 return truncated.bitwiseIsEqual(value);
11274}
11275
11276/// Checks whether the given value, which currently has the given
11277/// source semantics, has the same value when coerced through the
11278/// target semantics.
11279///
11280/// The value might be a vector of floats (or a complex number).
11281static bool IsSameFloatAfterCast(const APValue &value,
11282 const llvm::fltSemantics &Src,
11283 const llvm::fltSemantics &Tgt) {
11284 if (value.isFloat())
11285 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11286
11287 if (value.isVector()) {
11288 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11289 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11290 return false;
11291 return true;
11292 }
11293
11294 assert(value.isComplexFloat());
11295 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11296 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11297}
11298
11299static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11300 bool IsListInit = false);
11301
11302static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11303 // Suppress cases where we are comparing against an enum constant.
11304 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11305 if (isa<EnumConstantDecl>(DR->getDecl()))
11306 return true;
11307
11308 // Suppress cases where the value is expanded from a macro, unless that macro
11309 // is how a language represents a boolean literal. This is the case in both C
11310 // and Objective-C.
11311 SourceLocation BeginLoc = E->getBeginLoc();
11312 if (BeginLoc.isMacroID()) {
11313 StringRef MacroName = Lexer::getImmediateMacroName(
11314 BeginLoc, S.getSourceManager(), S.getLangOpts());
11315 return MacroName != "YES" && MacroName != "NO" &&
11316 MacroName != "true" && MacroName != "false";
11317 }
11318
11319 return false;
11320}
11321
11322static bool isKnownToHaveUnsignedValue(const Expr *E) {
11323 return E->getType()->isIntegerType() &&
11324 (!E->getType()->isSignedIntegerType() ||
11326}
11327
11328namespace {
11329/// The promoted range of values of a type. In general this has the
11330/// following structure:
11331///
11332/// |-----------| . . . |-----------|
11333/// ^ ^ ^ ^
11334/// Min HoleMin HoleMax Max
11335///
11336/// ... where there is only a hole if a signed type is promoted to unsigned
11337/// (in which case Min and Max are the smallest and largest representable
11338/// values).
11339struct PromotedRange {
11340 // Min, or HoleMax if there is a hole.
11341 llvm::APSInt PromotedMin;
11342 // Max, or HoleMin if there is a hole.
11343 llvm::APSInt PromotedMax;
11344
11345 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11346 if (R.Width == 0)
11347 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11348 else if (R.Width >= BitWidth && !Unsigned) {
11349 // Promotion made the type *narrower*. This happens when promoting
11350 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11351 // Treat all values of 'signed int' as being in range for now.
11352 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11353 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11354 } else {
11355 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11356 .extOrTrunc(BitWidth);
11357 PromotedMin.setIsUnsigned(Unsigned);
11358
11359 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11360 .extOrTrunc(BitWidth);
11361 PromotedMax.setIsUnsigned(Unsigned);
11362 }
11363 }
11364
11365 // Determine whether this range is contiguous (has no hole).
11366 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11367
11368 // Where a constant value is within the range.
11369 enum ComparisonResult {
11370 LT = 0x1,
11371 LE = 0x2,
11372 GT = 0x4,
11373 GE = 0x8,
11374 EQ = 0x10,
11375 NE = 0x20,
11376 InRangeFlag = 0x40,
11377
11378 Less = LE | LT | NE,
11379 Min = LE | InRangeFlag,
11380 InRange = InRangeFlag,
11381 Max = GE | InRangeFlag,
11382 Greater = GE | GT | NE,
11383
11384 OnlyValue = LE | GE | EQ | InRangeFlag,
11385 InHole = NE
11386 };
11387
11388 ComparisonResult compare(const llvm::APSInt &Value) const {
11389 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11390 Value.isUnsigned() == PromotedMin.isUnsigned());
11391 if (!isContiguous()) {
11392 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11393 if (Value.isMinValue()) return Min;
11394 if (Value.isMaxValue()) return Max;
11395 if (Value >= PromotedMin) return InRange;
11396 if (Value <= PromotedMax) return InRange;
11397 return InHole;
11398 }
11399
11400 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11401 case -1: return Less;
11402 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11403 case 1:
11404 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11405 case -1: return InRange;
11406 case 0: return Max;
11407 case 1: return Greater;
11408 }
11409 }
11410
11411 llvm_unreachable("impossible compare result");
11412 }
11413
11414 static std::optional<StringRef>
11415 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11416 if (Op == BO_Cmp) {
11417 ComparisonResult LTFlag = LT, GTFlag = GT;
11418 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11419
11420 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11421 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11422 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11423 return std::nullopt;
11424 }
11425
11426 ComparisonResult TrueFlag, FalseFlag;
11427 if (Op == BO_EQ) {
11428 TrueFlag = EQ;
11429 FalseFlag = NE;
11430 } else if (Op == BO_NE) {
11431 TrueFlag = NE;
11432 FalseFlag = EQ;
11433 } else {
11434 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11435 TrueFlag = LT;
11436 FalseFlag = GE;
11437 } else {
11438 TrueFlag = GT;
11439 FalseFlag = LE;
11440 }
11441 if (Op == BO_GE || Op == BO_LE)
11442 std::swap(TrueFlag, FalseFlag);
11443 }
11444 if (R & TrueFlag)
11445 return StringRef("true");
11446 if (R & FalseFlag)
11447 return StringRef("false");
11448 return std::nullopt;
11449 }
11450};
11451}
11452
11453static bool HasEnumType(const Expr *E) {
11454 // Strip off implicit integral promotions.
11455 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11456 if (ICE->getCastKind() != CK_IntegralCast &&
11457 ICE->getCastKind() != CK_NoOp)
11458 break;
11459 E = ICE->getSubExpr();
11460 }
11461
11462 return E->getType()->isEnumeralType();
11463}
11464
11465static int classifyConstantValue(Expr *Constant) {
11466 // The values of this enumeration are used in the diagnostics
11467 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11468 enum ConstantValueKind {
11469 Miscellaneous = 0,
11470 LiteralTrue,
11471 LiteralFalse
11472 };
11473 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11474 return BL->getValue() ? ConstantValueKind::LiteralTrue
11475 : ConstantValueKind::LiteralFalse;
11476 return ConstantValueKind::Miscellaneous;
11477}
11478
11480 Expr *Constant, Expr *Other,
11481 const llvm::APSInt &Value,
11482 bool RhsConstant) {
11484 return false;
11485
11486 Expr *OriginalOther = Other;
11487
11488 Constant = Constant->IgnoreParenImpCasts();
11489 Other = Other->IgnoreParenImpCasts();
11490
11491 // Suppress warnings on tautological comparisons between values of the same
11492 // enumeration type. There are only two ways we could warn on this:
11493 // - If the constant is outside the range of representable values of
11494 // the enumeration. In such a case, we should warn about the cast
11495 // to enumeration type, not about the comparison.
11496 // - If the constant is the maximum / minimum in-range value. For an
11497 // enumeratin type, such comparisons can be meaningful and useful.
11498 if (Constant->getType()->isEnumeralType() &&
11499 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11500 return false;
11501
11502 std::optional<IntRange> OtherValueRange = TryGetExprRange(
11503 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
11504 if (!OtherValueRange)
11505 return false;
11506
11507 QualType OtherT = Other->getType();
11508 if (const auto *AT = OtherT->getAs<AtomicType>())
11509 OtherT = AT->getValueType();
11510 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11511
11512 // Special case for ObjC BOOL on targets where its a typedef for a signed char
11513 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11514 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11515 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
11516 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11517
11518 // Whether we're treating Other as being a bool because of the form of
11519 // expression despite it having another type (typically 'int' in C).
11520 bool OtherIsBooleanDespiteType =
11521 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11522 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11523 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
11524
11525 // Check if all values in the range of possible values of this expression
11526 // lead to the same comparison outcome.
11527 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
11528 Value.isUnsigned());
11529 auto Cmp = OtherPromotedValueRange.compare(Value);
11530 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11531 if (!Result)
11532 return false;
11533
11534 // Also consider the range determined by the type alone. This allows us to
11535 // classify the warning under the proper diagnostic group.
11536 bool TautologicalTypeCompare = false;
11537 {
11538 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11539 Value.isUnsigned());
11540 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11541 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11542 RhsConstant)) {
11543 TautologicalTypeCompare = true;
11544 Cmp = TypeCmp;
11545 Result = TypeResult;
11546 }
11547 }
11548
11549 // Don't warn if the non-constant operand actually always evaluates to the
11550 // same value.
11551 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
11552 return false;
11553
11554 // Suppress the diagnostic for an in-range comparison if the constant comes
11555 // from a macro or enumerator. We don't want to diagnose
11556 //
11557 // some_long_value <= INT_MAX
11558 //
11559 // when sizeof(int) == sizeof(long).
11560 bool InRange = Cmp & PromotedRange::InRangeFlag;
11561 if (InRange && IsEnumConstOrFromMacro(S, Constant))
11562 return false;
11563
11564 // A comparison of an unsigned bit-field against 0 is really a type problem,
11565 // even though at the type level the bit-field might promote to 'signed int'.
11566 if (Other->refersToBitField() && InRange && Value == 0 &&
11567 Other->getType()->isUnsignedIntegerOrEnumerationType())
11568 TautologicalTypeCompare = true;
11569
11570 // If this is a comparison to an enum constant, include that
11571 // constant in the diagnostic.
11572 const EnumConstantDecl *ED = nullptr;
11573 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
11574 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11575
11576 // Should be enough for uint128 (39 decimal digits)
11577 SmallString<64> PrettySourceValue;
11578 llvm::raw_svector_ostream OS(PrettySourceValue);
11579 if (ED) {
11580 OS << '\'' << *ED << "' (" << Value << ")";
11581 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11582 Constant->IgnoreParenImpCasts())) {
11583 OS << (BL->getValue() ? "YES" : "NO");
11584 } else {
11585 OS << Value;
11586 }
11587
11588 if (!TautologicalTypeCompare) {
11589 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11590 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
11591 << E->getOpcodeStr() << OS.str() << *Result
11592 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11593 return true;
11594 }
11595
11596 if (IsObjCSignedCharBool) {
11598 S.PDiag(diag::warn_tautological_compare_objc_bool)
11599 << OS.str() << *Result);
11600 return true;
11601 }
11602
11603 // FIXME: We use a somewhat different formatting for the in-range cases and
11604 // cases involving boolean values for historical reasons. We should pick a
11605 // consistent way of presenting these diagnostics.
11606 if (!InRange || Other->isKnownToHaveBooleanValue()) {
11607
11609 E->getOperatorLoc(), E,
11610 S.PDiag(!InRange ? diag::warn_out_of_range_compare
11611 : diag::warn_tautological_bool_compare)
11612 << OS.str() << classifyConstantValue(Constant) << OtherT
11613 << OtherIsBooleanDespiteType << *Result
11614 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11615 } else {
11616 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11617 unsigned Diag =
11618 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11619 ? (HasEnumType(OriginalOther)
11620 ? diag::warn_unsigned_enum_always_true_comparison
11621 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11622 : diag::warn_unsigned_always_true_comparison)
11623 : diag::warn_tautological_constant_compare;
11624
11625 S.Diag(E->getOperatorLoc(), Diag)
11626 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11627 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11628 }
11629
11630 return true;
11631}
11632
11633/// Analyze the operands of the given comparison. Implements the
11634/// fallback case from AnalyzeComparison.
11639
11640/// Implements -Wsign-compare.
11641///
11642/// \param E the binary operator to check for warnings
11644 // The type the comparison is being performed in.
11645 QualType T = E->getLHS()->getType();
11646
11647 // Only analyze comparison operators where both sides have been converted to
11648 // the same type.
11650 return AnalyzeImpConvsInComparison(S, E);
11651
11652 // Don't analyze value-dependent comparisons directly.
11653 if (E->isValueDependent())
11654 return AnalyzeImpConvsInComparison(S, E);
11655
11656 Expr *LHS = E->getLHS();
11657 Expr *RHS = E->getRHS();
11658
11659 if (T->isIntegralType(S.Context)) {
11660 std::optional<llvm::APSInt> RHSValue =
11662 std::optional<llvm::APSInt> LHSValue =
11664
11665 // We don't care about expressions whose result is a constant.
11666 if (RHSValue && LHSValue)
11667 return AnalyzeImpConvsInComparison(S, E);
11668
11669 // We only care about expressions where just one side is literal
11670 if ((bool)RHSValue ^ (bool)LHSValue) {
11671 // Is the constant on the RHS or LHS?
11672 const bool RhsConstant = (bool)RHSValue;
11673 Expr *Const = RhsConstant ? RHS : LHS;
11674 Expr *Other = RhsConstant ? LHS : RHS;
11675 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11676
11677 // Check whether an integer constant comparison results in a value
11678 // of 'true' or 'false'.
11679 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11680 return AnalyzeImpConvsInComparison(S, E);
11681 }
11682 }
11683
11684 if (!T->hasUnsignedIntegerRepresentation()) {
11685 // We don't do anything special if this isn't an unsigned integral
11686 // comparison: we're only interested in integral comparisons, and
11687 // signed comparisons only happen in cases we don't care to warn about.
11688 return AnalyzeImpConvsInComparison(S, E);
11689 }
11690
11691 LHS = LHS->IgnoreParenImpCasts();
11692 RHS = RHS->IgnoreParenImpCasts();
11693
11694 if (!S.getLangOpts().CPlusPlus) {
11695 // Avoid warning about comparison of integers with different signs when
11696 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11697 // the type of `E`.
11698 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11699 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11700 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11701 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11702 }
11703
11704 // Check to see if one of the (unmodified) operands is of different
11705 // signedness.
11706 Expr *signedOperand, *unsignedOperand;
11708 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11709 "unsigned comparison between two signed integer expressions?");
11710 signedOperand = LHS;
11711 unsignedOperand = RHS;
11712 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11713 signedOperand = RHS;
11714 unsignedOperand = LHS;
11715 } else {
11716 return AnalyzeImpConvsInComparison(S, E);
11717 }
11718
11719 // Otherwise, calculate the effective range of the signed operand.
11720 std::optional<IntRange> signedRange =
11722 /*Approximate=*/true);
11723 if (!signedRange)
11724 return;
11725
11726 // Go ahead and analyze implicit conversions in the operands. Note
11727 // that we skip the implicit conversions on both sides.
11730
11731 // If the signed range is non-negative, -Wsign-compare won't fire.
11732 if (signedRange->NonNegative)
11733 return;
11734
11735 // For (in)equality comparisons, if the unsigned operand is a
11736 // constant which cannot collide with a overflowed signed operand,
11737 // then reinterpreting the signed operand as unsigned will not
11738 // change the result of the comparison.
11739 if (E->isEqualityOp()) {
11740 unsigned comparisonWidth = S.Context.getIntWidth(T);
11741 std::optional<IntRange> unsignedRange = TryGetExprRange(
11742 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
11743 /*Approximate=*/true);
11744 if (!unsignedRange)
11745 return;
11746
11747 // We should never be unable to prove that the unsigned operand is
11748 // non-negative.
11749 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
11750
11751 if (unsignedRange->Width < comparisonWidth)
11752 return;
11753 }
11754
11756 S.PDiag(diag::warn_mixed_sign_comparison)
11757 << LHS->getType() << RHS->getType()
11758 << LHS->getSourceRange() << RHS->getSourceRange());
11759}
11760
11761/// Analyzes an attempt to assign the given value to a bitfield.
11762///
11763/// Returns true if there was something fishy about the attempt.
11765 SourceLocation InitLoc) {
11766 assert(Bitfield->isBitField());
11767 if (Bitfield->isInvalidDecl())
11768 return false;
11769
11770 // White-list bool bitfields.
11771 QualType BitfieldType = Bitfield->getType();
11772 if (BitfieldType->isBooleanType())
11773 return false;
11774
11775 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
11776 // If the underlying enum type was not explicitly specified as an unsigned
11777 // type and the enum contain only positive values, MSVC++ will cause an
11778 // inconsistency by storing this as a signed type.
11779 if (S.getLangOpts().CPlusPlus11 &&
11780 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11781 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11782 BitfieldEnumDecl->getNumNegativeBits() == 0) {
11783 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11784 << BitfieldEnumDecl;
11785 }
11786 }
11787
11788 // Ignore value- or type-dependent expressions.
11789 if (Bitfield->getBitWidth()->isValueDependent() ||
11790 Bitfield->getBitWidth()->isTypeDependent() ||
11791 Init->isValueDependent() ||
11792 Init->isTypeDependent())
11793 return false;
11794
11795 Expr *OriginalInit = Init->IgnoreParenImpCasts();
11796 unsigned FieldWidth = Bitfield->getBitWidthValue();
11797
11798 Expr::EvalResult Result;
11799 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11801 // The RHS is not constant. If the RHS has an enum type, make sure the
11802 // bitfield is wide enough to hold all the values of the enum without
11803 // truncation.
11804 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
11805 const PreferredTypeAttr *PTAttr = nullptr;
11806 if (!ED) {
11807 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
11808 if (PTAttr)
11809 ED = PTAttr->getType()->getAsEnumDecl();
11810 }
11811 if (ED) {
11812 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
11813
11814 // Enum types are implicitly signed on Windows, so check if there are any
11815 // negative enumerators to see if the enum was intended to be signed or
11816 // not.
11817 bool SignedEnum = ED->getNumNegativeBits() > 0;
11818
11819 // Check for surprising sign changes when assigning enum values to a
11820 // bitfield of different signedness. If the bitfield is signed and we
11821 // have exactly the right number of bits to store this unsigned enum,
11822 // suggest changing the enum to an unsigned type. This typically happens
11823 // on Windows where unfixed enums always use an underlying type of 'int'.
11824 unsigned DiagID = 0;
11825 if (SignedEnum && !SignedBitfield) {
11826 DiagID =
11827 PTAttr == nullptr
11828 ? diag::warn_unsigned_bitfield_assigned_signed_enum
11829 : diag::
11830 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
11831 } else if (SignedBitfield && !SignedEnum &&
11832 ED->getNumPositiveBits() == FieldWidth) {
11833 DiagID =
11834 PTAttr == nullptr
11835 ? diag::warn_signed_bitfield_enum_conversion
11836 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
11837 }
11838 if (DiagID) {
11839 S.Diag(InitLoc, DiagID) << Bitfield << ED;
11840 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11841 SourceRange TypeRange =
11842 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11843 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11844 << SignedEnum << TypeRange;
11845 if (PTAttr)
11846 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
11847 << ED;
11848 }
11849
11850 // Compute the required bitwidth. If the enum has negative values, we need
11851 // one more bit than the normal number of positive bits to represent the
11852 // sign bit.
11853 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11854 ED->getNumNegativeBits())
11855 : ED->getNumPositiveBits();
11856
11857 // Check the bitwidth.
11858 if (BitsNeeded > FieldWidth) {
11859 Expr *WidthExpr = Bitfield->getBitWidth();
11860 auto DiagID =
11861 PTAttr == nullptr
11862 ? diag::warn_bitfield_too_small_for_enum
11863 : diag::warn_preferred_type_bitfield_too_small_for_enum;
11864 S.Diag(InitLoc, DiagID) << Bitfield << ED;
11865 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11866 << BitsNeeded << ED << WidthExpr->getSourceRange();
11867 if (PTAttr)
11868 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
11869 << ED;
11870 }
11871 }
11872
11873 return false;
11874 }
11875
11876 llvm::APSInt Value = Result.Val.getInt();
11877
11878 unsigned OriginalWidth = Value.getBitWidth();
11879
11880 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
11881 // false positives where the user is demonstrating they intend to use the
11882 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
11883 // to a one-bit bit-field to see if the value came from a macro named 'true'.
11884 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
11885 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
11886 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
11887 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
11888 S.findMacroSpelling(MaybeMacroLoc, "true"))
11889 return false;
11890 }
11891
11892 if (!Value.isSigned() || Value.isNegative())
11893 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11894 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11895 OriginalWidth = Value.getSignificantBits();
11896
11897 if (OriginalWidth <= FieldWidth)
11898 return false;
11899
11900 // Compute the value which the bitfield will contain.
11901 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11902 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11903
11904 // Check whether the stored value is equal to the original value.
11905 TruncatedValue = TruncatedValue.extend(OriginalWidth);
11906 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11907 return false;
11908
11909 std::string PrettyValue = toString(Value, 10);
11910 std::string PrettyTrunc = toString(TruncatedValue, 10);
11911
11912 S.Diag(InitLoc, OneAssignedToOneBitBitfield
11913 ? diag::warn_impcast_single_bit_bitield_precision_constant
11914 : diag::warn_impcast_bitfield_precision_constant)
11915 << PrettyValue << PrettyTrunc << OriginalInit->getType()
11916 << Init->getSourceRange();
11917
11918 return true;
11919}
11920
11921/// Analyze the given simple or compound assignment for warning-worthy
11922/// operations.
11924 // Just recurse on the LHS.
11926
11927 // We want to recurse on the RHS as normal unless we're assigning to
11928 // a bitfield.
11929 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11930 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11931 E->getOperatorLoc())) {
11932 // Recurse, ignoring any implicit conversions on the RHS.
11934 E->getOperatorLoc());
11935 }
11936 }
11937
11939
11940 // Diagnose implicitly sequentially-consistent atomic assignment.
11941 if (E->getLHS()->getType()->isAtomicType())
11942 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11943}
11944
11945/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
11946static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
11947 QualType T, SourceLocation CContext, unsigned diag,
11948 bool PruneControlFlow = false) {
11949 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
11950 // address space annotations isn't really useful. The warnings aren't because
11951 // you're converting a `private int` to `unsigned int`, it is because you're
11952 // conerting `int` to `unsigned int`.
11953 if (SourceType.hasAddressSpace())
11954 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
11955 if (T.hasAddressSpace())
11957 if (PruneControlFlow) {
11959 S.PDiag(diag)
11960 << SourceType << T << E->getSourceRange()
11961 << SourceRange(CContext));
11962 return;
11963 }
11964 S.Diag(E->getExprLoc(), diag)
11965 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11966}
11967
11968/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
11969static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
11970 SourceLocation CContext, unsigned diag,
11971 bool PruneControlFlow = false) {
11972 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
11973}
11974
11975/// Diagnose an implicit cast from a floating point value to an integer value.
11976static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
11977 SourceLocation CContext) {
11978 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11979 bool PruneWarnings = S.inTemplateInstantiation();
11980
11981 const Expr *InnerE = E->IgnoreParenImpCasts();
11982 // We also want to warn on, e.g., "int i = -1.234"
11983 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
11984 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11985 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11986
11987 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11988
11989 llvm::APFloat Value(0.0);
11990 bool IsConstant =
11992 if (!IsConstant) {
11993 if (S.ObjC().isSignedCharBool(T)) {
11995 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11996 << E->getType());
11997 }
11998
11999 return DiagnoseImpCast(S, E, T, CContext,
12000 diag::warn_impcast_float_integer, PruneWarnings);
12001 }
12002
12003 bool isExact = false;
12004
12005 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12006 T->hasUnsignedIntegerRepresentation());
12007 llvm::APFloat::opStatus Result = Value.convertToInteger(
12008 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12009
12010 // FIXME: Force the precision of the source value down so we don't print
12011 // digits which are usually useless (we don't really care here if we
12012 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12013 // would automatically print the shortest representation, but it's a bit
12014 // tricky to implement.
12015 SmallString<16> PrettySourceValue;
12016 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12017 precision = (precision * 59 + 195) / 196;
12018 Value.toString(PrettySourceValue, precision);
12019
12020 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
12022 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12023 << PrettySourceValue);
12024 }
12025
12026 if (Result == llvm::APFloat::opOK && isExact) {
12027 if (IsLiteral) return;
12028 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12029 PruneWarnings);
12030 }
12031
12032 // Conversion of a floating-point value to a non-bool integer where the
12033 // integral part cannot be represented by the integer type is undefined.
12034 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12035 return DiagnoseImpCast(
12036 S, E, T, CContext,
12037 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12038 : diag::warn_impcast_float_to_integer_out_of_range,
12039 PruneWarnings);
12040
12041 unsigned DiagID = 0;
12042 if (IsLiteral) {
12043 // Warn on floating point literal to integer.
12044 DiagID = diag::warn_impcast_literal_float_to_integer;
12045 } else if (IntegerValue == 0) {
12046 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12047 return DiagnoseImpCast(S, E, T, CContext,
12048 diag::warn_impcast_float_integer, PruneWarnings);
12049 }
12050 // Warn on non-zero to zero conversion.
12051 DiagID = diag::warn_impcast_float_to_integer_zero;
12052 } else {
12053 if (IntegerValue.isUnsigned()) {
12054 if (!IntegerValue.isMaxValue()) {
12055 return DiagnoseImpCast(S, E, T, CContext,
12056 diag::warn_impcast_float_integer, PruneWarnings);
12057 }
12058 } else { // IntegerValue.isSigned()
12059 if (!IntegerValue.isMaxSignedValue() &&
12060 !IntegerValue.isMinSignedValue()) {
12061 return DiagnoseImpCast(S, E, T, CContext,
12062 diag::warn_impcast_float_integer, PruneWarnings);
12063 }
12064 }
12065 // Warn on evaluatable floating point expression to integer conversion.
12066 DiagID = diag::warn_impcast_float_to_integer;
12067 }
12068
12069 SmallString<16> PrettyTargetValue;
12070 if (IsBool)
12071 PrettyTargetValue = Value.isZero() ? "false" : "true";
12072 else
12073 IntegerValue.toString(PrettyTargetValue);
12074
12075 if (PruneWarnings) {
12077 S.PDiag(DiagID)
12078 << E->getType() << T.getUnqualifiedType()
12079 << PrettySourceValue << PrettyTargetValue
12080 << E->getSourceRange() << SourceRange(CContext));
12081 } else {
12082 S.Diag(E->getExprLoc(), DiagID)
12083 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12084 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12085 }
12086}
12087
12088/// Analyze the given compound assignment for the possible losing of
12089/// floating-point precision.
12091 assert(isa<CompoundAssignOperator>(E) &&
12092 "Must be compound assignment operation");
12093 // Recurse on the LHS and RHS in here
12096
12097 if (E->getLHS()->getType()->isAtomicType())
12098 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12099
12100 // Now check the outermost expression
12101 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12102 const auto *RBT = cast<CompoundAssignOperator>(E)
12103 ->getComputationResultType()
12104 ->getAs<BuiltinType>();
12105
12106 // The below checks assume source is floating point.
12107 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12108
12109 // If source is floating point but target is an integer.
12110 if (ResultBT->isInteger())
12111 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12112 E->getExprLoc(), diag::warn_impcast_float_integer);
12113
12114 if (!ResultBT->isFloatingPoint())
12115 return;
12116
12117 // If both source and target are floating points, warn about losing precision.
12119 QualType(ResultBT, 0), QualType(RBT, 0));
12120 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12121 // warn about dropping FP rank.
12122 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12123 diag::warn_impcast_float_result_precision);
12124}
12125
12126static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12127 IntRange Range) {
12128 if (!Range.Width) return "0";
12129
12130 llvm::APSInt ValueInRange = Value;
12131 ValueInRange.setIsSigned(!Range.NonNegative);
12132 ValueInRange = ValueInRange.trunc(Range.Width);
12133 return toString(ValueInRange, 10);
12134}
12135
12136static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12137 bool ToBool) {
12138 if (!isa<ImplicitCastExpr>(Ex))
12139 return false;
12140
12141 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12143 const Type *Source =
12145 if (Target->isDependentType())
12146 return false;
12147
12148 const auto *FloatCandidateBT =
12149 dyn_cast<BuiltinType>(ToBool ? Source : Target);
12150 const Type *BoolCandidateType = ToBool ? Target : Source;
12151
12152 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12153 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12154}
12155
12156static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12157 SourceLocation CC) {
12158 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12159 const Expr *CurrA = TheCall->getArg(I);
12160 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12161 continue;
12162
12163 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12164 S, TheCall->getArg(I - 1), false));
12165 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12166 S, TheCall->getArg(I + 1), false));
12167 if (IsSwapped) {
12168 // Warn on this floating-point to bool conversion.
12170 CurrA->getType(), CC,
12171 diag::warn_impcast_floating_point_to_bool);
12172 }
12173 }
12174}
12175
12177 SourceLocation CC) {
12178 // Don't warn on functions which have return type nullptr_t.
12179 if (isa<CallExpr>(E))
12180 return;
12181
12182 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12183 const Expr *NewE = E->IgnoreParenImpCasts();
12184 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
12185 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12186 if (!IsGNUNullExpr && !HasNullPtrType)
12187 return;
12188
12189 // Return if target type is a safe conversion.
12190 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12191 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12192 return;
12193
12194 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12195 E->getExprLoc()))
12196 return;
12197
12199
12200 // Venture through the macro stacks to get to the source of macro arguments.
12201 // The new location is a better location than the complete location that was
12202 // passed in.
12203 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12205
12206 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12207 if (IsGNUNullExpr && Loc.isMacroID()) {
12208 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12209 Loc, S.SourceMgr, S.getLangOpts());
12210 if (MacroName == "NULL")
12212 }
12213
12214 // Only warn if the null and context location are in the same macro expansion.
12215 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12216 return;
12217
12218 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12219 << HasNullPtrType << T << SourceRange(CC)
12222}
12223
12224// Helper function to filter out cases for constant width constant conversion.
12225// Don't warn on char array initialization or for non-decimal values.
12227 SourceLocation CC) {
12228 // If initializing from a constant, and the constant starts with '0',
12229 // then it is a binary, octal, or hexadecimal. Allow these constants
12230 // to fill all the bits, even if there is a sign change.
12231 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12232 const char FirstLiteralCharacter =
12233 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12234 if (FirstLiteralCharacter == '0')
12235 return false;
12236 }
12237
12238 // If the CC location points to a '{', and the type is char, then assume
12239 // assume it is an array initialization.
12240 if (CC.isValid() && T->isCharType()) {
12241 const char FirstContextCharacter =
12243 if (FirstContextCharacter == '{')
12244 return false;
12245 }
12246
12247 return true;
12248}
12249
12251 const auto *IL = dyn_cast<IntegerLiteral>(E);
12252 if (!IL) {
12253 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12254 if (UO->getOpcode() == UO_Minus)
12255 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12256 }
12257 }
12258
12259 return IL;
12260}
12261
12263 E = E->IgnoreParenImpCasts();
12264 SourceLocation ExprLoc = E->getExprLoc();
12265
12266 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12267 BinaryOperator::Opcode Opc = BO->getOpcode();
12268 Expr::EvalResult Result;
12269 // Do not diagnose unsigned shifts.
12270 if (Opc == BO_Shl) {
12271 const auto *LHS = getIntegerLiteral(BO->getLHS());
12272 const auto *RHS = getIntegerLiteral(BO->getRHS());
12273 if (LHS && LHS->getValue() == 0)
12274 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12275 else if (!E->isValueDependent() && LHS && RHS &&
12276 RHS->getValue().isNonNegative() &&
12278 S.Diag(ExprLoc, diag::warn_left_shift_always)
12279 << (Result.Val.getInt() != 0);
12280 else if (E->getType()->isSignedIntegerType())
12281 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
12284 ") != 0");
12285 }
12286 }
12287
12288 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12289 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12290 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12291 if (!LHS || !RHS)
12292 return;
12293 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12294 (RHS->getValue() == 0 || RHS->getValue() == 1))
12295 // Do not diagnose common idioms.
12296 return;
12297 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12298 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12299 }
12300}
12301
12303 const Type *Target, Expr *E,
12304 QualType T,
12305 SourceLocation CC) {
12306 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12307 Source != Target);
12308 Expr::EvalResult Result;
12311 llvm::APSInt Value(32);
12312 Value = Result.Val.getInt();
12313 bool IsASCII = Value <= 0x7F;
12314 bool IsBMP = Value <= 0xD7FF || (Value >= 0xE000 && Value <= 0xFFFF);
12315 bool ConversionPreservesSemantics =
12316 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12317
12318 if (!ConversionPreservesSemantics) {
12319 auto IsSingleCodeUnitCP = [](const QualType &T,
12320 const llvm::APSInt &Value) {
12321 if (T->isChar8Type())
12322 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12323 if (T->isChar16Type())
12324 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12325 assert(T->isChar32Type());
12326 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12327 };
12328
12329 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
12330 << E->getType() << T
12331 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12332 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
12333 }
12334 } else {
12335 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
12337 DiagnoseImpCast(S, E, T, CC,
12338 LosesPrecision ? diag::warn_impcast_unicode_precision
12339 : diag::warn_impcast_unicode_char_type);
12340 }
12341}
12342
12348
12350 QualType To) {
12351 QualType MaybePointee = From->getPointeeType();
12352 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12353 From = MaybePointee;
12354 MaybePointee = To->getPointeeType();
12355 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12356 To = MaybePointee;
12357
12358 if (const auto *FromFn = From->getAs<FunctionType>()) {
12359 if (const auto *ToFn = To->getAs<FunctionType>()) {
12360 if (FromFn->getCFIUncheckedCalleeAttr() &&
12361 !ToFn->getCFIUncheckedCalleeAttr())
12362 return Discarding;
12363 if (!FromFn->getCFIUncheckedCalleeAttr() &&
12364 ToFn->getCFIUncheckedCalleeAttr())
12365 return Adding;
12366 }
12367 }
12368 return None;
12369}
12370
12372 From = Context.getCanonicalType(From);
12373 To = Context.getCanonicalType(To);
12374 return ::AdjustingCFIUncheckedCallee(From, To) == Discarding;
12375}
12376
12378 From = Context.getCanonicalType(From);
12379 To = Context.getCanonicalType(To);
12380 return ::AdjustingCFIUncheckedCallee(From, To) == Adding;
12381}
12382
12384 bool *ICContext, bool IsListInit) {
12385 if (E->isTypeDependent() || E->isValueDependent()) return;
12386
12387 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
12388 const Type *Target = Context.getCanonicalType(T).getTypePtr();
12389 if (Source == Target) return;
12390 if (Target->isDependentType()) return;
12391
12392 // If the conversion context location is invalid don't complain. We also
12393 // don't want to emit a warning if the issue occurs from the expansion of
12394 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12395 // delay this check as long as possible. Once we detect we are in that
12396 // scenario, we just return.
12397 if (CC.isInvalid())
12398 return;
12399
12400 if (Source->isAtomicType())
12401 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12402
12403 // Diagnose implicit casts to bool.
12404 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12405 if (isa<StringLiteral>(E))
12406 // Warn on string literal to bool. Checks for string literals in logical
12407 // and expressions, for instance, assert(0 && "error here"), are
12408 // prevented by a check in AnalyzeImplicitConversions().
12409 return DiagnoseImpCast(*this, E, T, CC,
12410 diag::warn_impcast_string_literal_to_bool);
12413 // This covers the literal expressions that evaluate to Objective-C
12414 // objects.
12415 return DiagnoseImpCast(*this, E, T, CC,
12416 diag::warn_impcast_objective_c_literal_to_bool);
12417 }
12418 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12419 // Warn on pointer to bool conversion that is always true.
12421 SourceRange(CC));
12422 }
12423 }
12424
12425 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12426 // is a typedef for signed char (macOS), then that constant value has to be 1
12427 // or 0.
12428 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
12431 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12433 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12434 << toString(Result.Val.getInt(), 10));
12435 }
12436 return;
12437 }
12438 }
12439
12440 // Check implicit casts from Objective-C collection literals to specialized
12441 // collection types, e.g., NSArray<NSString *> *.
12442 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12443 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
12444 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12445 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
12446
12447 // Strip vector types.
12448 if (isa<VectorType>(Source)) {
12449 if (Target->isSveVLSBuiltinType() &&
12450 (ARM().areCompatibleSveTypes(QualType(Target, 0),
12451 QualType(Source, 0)) ||
12452 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
12453 QualType(Source, 0))))
12454 return;
12455
12456 if (Target->isRVVVLSBuiltinType() &&
12457 (Context.areCompatibleRVVTypes(QualType(Target, 0),
12458 QualType(Source, 0)) ||
12459 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
12460 QualType(Source, 0))))
12461 return;
12462
12463 if (!isa<VectorType>(Target)) {
12464 if (SourceMgr.isInSystemMacro(CC))
12465 return;
12466 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
12467 } else if (getLangOpts().HLSL &&
12468 Target->castAs<VectorType>()->getNumElements() <
12469 Source->castAs<VectorType>()->getNumElements()) {
12470 // Diagnose vector truncation but don't return. We may also want to
12471 // diagnose an element conversion.
12472 DiagnoseImpCast(*this, E, T, CC,
12473 diag::warn_hlsl_impcast_vector_truncation);
12474 }
12475
12476 // If the vector cast is cast between two vectors of the same size, it is
12477 // a bitcast, not a conversion, except under HLSL where it is a conversion.
12478 if (!getLangOpts().HLSL &&
12479 Context.getTypeSize(Source) == Context.getTypeSize(Target))
12480 return;
12481
12482 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12483 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12484 }
12485 if (auto VecTy = dyn_cast<VectorType>(Target))
12486 Target = VecTy->getElementType().getTypePtr();
12487
12488 // Strip complex types.
12489 if (isa<ComplexType>(Source)) {
12490 if (!isa<ComplexType>(Target)) {
12491 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12492 return;
12493
12494 return DiagnoseImpCast(*this, E, T, CC,
12496 ? diag::err_impcast_complex_scalar
12497 : diag::warn_impcast_complex_scalar);
12498 }
12499
12500 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12501 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12502 }
12503
12504 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12505 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12506
12507 // Strip SVE vector types
12508 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
12509 // Need the original target type for vector type checks
12510 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
12511 // Handle conversion from scalable to fixed when msve-vector-bits is
12512 // specified
12513 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
12514 QualType(Source, 0)) ||
12515 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
12516 QualType(Source, 0)))
12517 return;
12518
12519 // If the vector cast is cast between two vectors of the same size, it is
12520 // a bitcast, not a conversion.
12521 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
12522 return;
12523
12524 Source = SourceBT->getSveEltType(Context).getTypePtr();
12525 }
12526
12527 if (TargetBT && TargetBT->isSveVLSBuiltinType())
12528 Target = TargetBT->getSveEltType(Context).getTypePtr();
12529
12530 // If the source is floating point...
12531 if (SourceBT && SourceBT->isFloatingPoint()) {
12532 // ...and the target is floating point...
12533 if (TargetBT && TargetBT->isFloatingPoint()) {
12534 // ...then warn if we're dropping FP rank.
12535
12537 QualType(SourceBT, 0), QualType(TargetBT, 0));
12538 if (Order > 0) {
12539 // Don't warn about float constants that are precisely
12540 // representable in the target type.
12541 Expr::EvalResult result;
12542 if (E->EvaluateAsRValue(result, Context)) {
12543 // Value might be a float, a float vector, or a float complex.
12545 result.Val,
12546 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12547 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12548 return;
12549 }
12550
12551 if (SourceMgr.isInSystemMacro(CC))
12552 return;
12553
12554 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
12555 }
12556 // ... or possibly if we're increasing rank, too
12557 else if (Order < 0) {
12558 if (SourceMgr.isInSystemMacro(CC))
12559 return;
12560
12561 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
12562 }
12563 return;
12564 }
12565
12566 // If the target is integral, always warn.
12567 if (TargetBT && TargetBT->isInteger()) {
12568 if (SourceMgr.isInSystemMacro(CC))
12569 return;
12570
12571 DiagnoseFloatingImpCast(*this, E, T, CC);
12572 }
12573
12574 // Detect the case where a call result is converted from floating-point to
12575 // to bool, and the final argument to the call is converted from bool, to
12576 // discover this typo:
12577 //
12578 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
12579 //
12580 // FIXME: This is an incredibly special case; is there some more general
12581 // way to detect this class of misplaced-parentheses bug?
12582 if (Target->isBooleanType() && isa<CallExpr>(E)) {
12583 // Check last argument of function call to see if it is an
12584 // implicit cast from a type matching the type the result
12585 // is being cast to.
12586 CallExpr *CEx = cast<CallExpr>(E);
12587 if (unsigned NumArgs = CEx->getNumArgs()) {
12588 Expr *LastA = CEx->getArg(NumArgs - 1);
12589 Expr *InnerE = LastA->IgnoreParenImpCasts();
12590 if (isa<ImplicitCastExpr>(LastA) &&
12591 InnerE->getType()->isBooleanType()) {
12592 // Warn on this floating-point to bool conversion
12593 DiagnoseImpCast(*this, E, T, CC,
12594 diag::warn_impcast_floating_point_to_bool);
12595 }
12596 }
12597 }
12598 return;
12599 }
12600
12601 // Valid casts involving fixed point types should be accounted for here.
12602 if (Source->isFixedPointType()) {
12603 if (Target->isUnsaturatedFixedPointType()) {
12607 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12608 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
12609 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
12610 if (Value > MaxVal || Value < MinVal) {
12612 PDiag(diag::warn_impcast_fixed_point_range)
12613 << Value.toString() << T
12614 << E->getSourceRange()
12615 << clang::SourceRange(CC));
12616 return;
12617 }
12618 }
12619 } else if (Target->isIntegerType()) {
12623 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12624
12625 bool Overflowed;
12626 llvm::APSInt IntResult = FXResult.convertToInt(
12627 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
12628 &Overflowed);
12629
12630 if (Overflowed) {
12632 PDiag(diag::warn_impcast_fixed_point_range)
12633 << FXResult.toString() << T
12634 << E->getSourceRange()
12635 << clang::SourceRange(CC));
12636 return;
12637 }
12638 }
12639 }
12640 } else if (Target->isUnsaturatedFixedPointType()) {
12641 if (Source->isIntegerType()) {
12645 llvm::APSInt Value = Result.Val.getInt();
12646
12647 bool Overflowed;
12648 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12649 Value, Context.getFixedPointSemantics(T), &Overflowed);
12650
12651 if (Overflowed) {
12653 PDiag(diag::warn_impcast_fixed_point_range)
12654 << toString(Value, /*Radix=*/10) << T
12655 << E->getSourceRange()
12656 << clang::SourceRange(CC));
12657 return;
12658 }
12659 }
12660 }
12661 }
12662
12663 // If we are casting an integer type to a floating point type without
12664 // initialization-list syntax, we might lose accuracy if the floating
12665 // point type has a narrower significand than the integer type.
12666 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12667 TargetBT->isFloatingType() && !IsListInit) {
12668 // Determine the number of precision bits in the source integer type.
12669 std::optional<IntRange> SourceRange =
12671 /*Approximate=*/true);
12672 if (!SourceRange)
12673 return;
12674 unsigned int SourcePrecision = SourceRange->Width;
12675
12676 // Determine the number of precision bits in the
12677 // target floating point type.
12678 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12679 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12680
12681 if (SourcePrecision > 0 && TargetPrecision > 0 &&
12682 SourcePrecision > TargetPrecision) {
12683
12684 if (std::optional<llvm::APSInt> SourceInt =
12686 // If the source integer is a constant, convert it to the target
12687 // floating point type. Issue a warning if the value changes
12688 // during the whole conversion.
12689 llvm::APFloat TargetFloatValue(
12690 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12691 llvm::APFloat::opStatus ConversionStatus =
12692 TargetFloatValue.convertFromAPInt(
12693 *SourceInt, SourceBT->isSignedInteger(),
12694 llvm::APFloat::rmNearestTiesToEven);
12695
12696 if (ConversionStatus != llvm::APFloat::opOK) {
12697 SmallString<32> PrettySourceValue;
12698 SourceInt->toString(PrettySourceValue, 10);
12699 SmallString<32> PrettyTargetValue;
12700 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12701
12703 E->getExprLoc(), E,
12704 PDiag(diag::warn_impcast_integer_float_precision_constant)
12705 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12706 << E->getSourceRange() << clang::SourceRange(CC));
12707 }
12708 } else {
12709 // Otherwise, the implicit conversion may lose precision.
12710 DiagnoseImpCast(*this, E, T, CC,
12711 diag::warn_impcast_integer_float_precision);
12712 }
12713 }
12714 }
12715
12716 DiagnoseNullConversion(*this, E, T, CC);
12717
12719
12720 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
12721 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
12722 return;
12723 }
12724
12725 if (Target->isBooleanType())
12726 DiagnoseIntInBoolContext(*this, E);
12727
12729 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
12730 << QualType(Source, 0) << QualType(Target, 0);
12731 }
12732
12733 if (!Source->isIntegerType() || !Target->isIntegerType())
12734 return;
12735
12736 // TODO: remove this early return once the false positives for constant->bool
12737 // in templates, macros, etc, are reduced or removed.
12738 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12739 return;
12740
12741 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
12742 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12744 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12745 << E->getType());
12746 }
12747 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
12748 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
12749 if (!LikelySourceRange)
12750 return;
12751
12752 IntRange SourceTypeRange =
12753 IntRange::forTargetOfCanonicalType(Context, Source);
12754 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
12755
12756 if (LikelySourceRange->Width > TargetRange.Width) {
12757 // If the source is a constant, use a default-on diagnostic.
12758 // TODO: this should happen for bitfield stores, too.
12762 llvm::APSInt Value(32);
12763 Value = Result.Val.getInt();
12764
12765 if (SourceMgr.isInSystemMacro(CC))
12766 return;
12767
12768 std::string PrettySourceValue = toString(Value, 10);
12769 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12770
12772 PDiag(diag::warn_impcast_integer_precision_constant)
12773 << PrettySourceValue << PrettyTargetValue
12774 << E->getType() << T << E->getSourceRange()
12775 << SourceRange(CC));
12776 return;
12777 }
12778
12779 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12780 if (SourceMgr.isInSystemMacro(CC))
12781 return;
12782
12783 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12784 if (UO->getOpcode() == UO_Minus)
12785 return DiagnoseImpCast(
12786 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
12787 }
12788
12789 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
12790 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
12791 /* pruneControlFlow */ true);
12792 return DiagnoseImpCast(*this, E, T, CC,
12793 diag::warn_impcast_integer_precision);
12794 }
12795
12796 if (TargetRange.Width > SourceTypeRange.Width) {
12797 if (auto *UO = dyn_cast<UnaryOperator>(E))
12798 if (UO->getOpcode() == UO_Minus)
12799 if (Source->isUnsignedIntegerType()) {
12800 if (Target->isUnsignedIntegerType())
12801 return DiagnoseImpCast(*this, E, T, CC,
12802 diag::warn_impcast_high_order_zero_bits);
12803 if (Target->isSignedIntegerType())
12804 return DiagnoseImpCast(*this, E, T, CC,
12805 diag::warn_impcast_nonnegative_result);
12806 }
12807 }
12808
12809 if (TargetRange.Width == LikelySourceRange->Width &&
12810 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
12811 Source->isSignedIntegerType()) {
12812 // Warn when doing a signed to signed conversion, warn if the positive
12813 // source value is exactly the width of the target type, which will
12814 // cause a negative value to be stored.
12815
12818 !SourceMgr.isInSystemMacro(CC)) {
12819 llvm::APSInt Value = Result.Val.getInt();
12820 if (isSameWidthConstantConversion(*this, E, T, CC)) {
12821 std::string PrettySourceValue = toString(Value, 10);
12822 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12823
12824 Diag(E->getExprLoc(),
12825 PDiag(diag::warn_impcast_integer_precision_constant)
12826 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12827 << E->getSourceRange() << SourceRange(CC));
12828 return;
12829 }
12830 }
12831
12832 // Fall through for non-constants to give a sign conversion warning.
12833 }
12834
12835 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
12836 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
12837 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
12838 LikelySourceRange->Width == TargetRange.Width))) {
12839 if (SourceMgr.isInSystemMacro(CC))
12840 return;
12841
12842 if (SourceBT && SourceBT->isInteger() && TargetBT &&
12843 TargetBT->isInteger() &&
12844 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
12845 return;
12846 }
12847
12848 unsigned DiagID = diag::warn_impcast_integer_sign;
12849
12850 // Traditionally, gcc has warned about this under -Wsign-compare.
12851 // We also want to warn about it in -Wconversion.
12852 // So if -Wconversion is off, use a completely identical diagnostic
12853 // in the sign-compare group.
12854 // The conditional-checking code will
12855 if (ICContext) {
12856 DiagID = diag::warn_impcast_integer_sign_conditional;
12857 *ICContext = true;
12858 }
12859
12860 DiagnoseImpCast(*this, E, T, CC, DiagID);
12861 }
12862
12863 // If we're implicitly converting from an integer into an enumeration, that
12864 // is valid in C but invalid in C++.
12865 QualType SourceType = E->getEnumCoercedType(Context);
12866 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
12867 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
12868 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
12869
12870 // Diagnose conversions between different enumeration types.
12871 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12872 // type, to give us better diagnostics.
12873 Source = Context.getCanonicalType(SourceType).getTypePtr();
12874
12875 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
12876 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
12877 if (SourceEnum->getOriginalDecl()->hasNameForLinkage() &&
12878 TargetEnum->getOriginalDecl()->hasNameForLinkage() &&
12879 SourceEnum != TargetEnum) {
12880 if (SourceMgr.isInSystemMacro(CC))
12881 return;
12882
12883 return DiagnoseImpCast(*this, E, SourceType, T, CC,
12884 diag::warn_impcast_different_enum_types);
12885 }
12886}
12887
12890
12892 SourceLocation CC, bool &ICContext) {
12893 E = E->IgnoreParenImpCasts();
12894 // Diagnose incomplete type for second or third operand in C.
12895 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
12896 S.RequireCompleteExprType(E, diag::err_incomplete_type);
12897
12898 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12899 return CheckConditionalOperator(S, CO, CC, T);
12900
12902 if (E->getType() != T)
12903 return S.CheckImplicitConversion(E, T, CC, &ICContext);
12904}
12905
12909
12910 Expr *TrueExpr = E->getTrueExpr();
12911 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12912 TrueExpr = BCO->getCommon();
12913
12914 bool Suspicious = false;
12915 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12916 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12917
12918 if (T->isBooleanType())
12920
12921 // If -Wconversion would have warned about either of the candidates
12922 // for a signedness conversion to the context type...
12923 if (!Suspicious) return;
12924
12925 // ...but it's currently ignored...
12926 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12927 return;
12928
12929 // ...then check whether it would have warned about either of the
12930 // candidates for a signedness conversion to the condition type.
12931 if (E->getType() == T) return;
12932
12933 Suspicious = false;
12934 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
12935 &Suspicious);
12936 if (!Suspicious)
12938 E->getType(), CC, &Suspicious);
12939}
12940
12941/// Check conversion of given expression to boolean.
12942/// Input argument E is a logical expression.
12944 // Run the bool-like conversion checks only for C since there bools are
12945 // still not used as the return type from "boolean" operators or as the input
12946 // type for conditional operators.
12947 if (S.getLangOpts().CPlusPlus)
12948 return;
12950 return;
12952}
12953
12954namespace {
12955struct AnalyzeImplicitConversionsWorkItem {
12956 Expr *E;
12957 SourceLocation CC;
12958 bool IsListInit;
12959};
12960}
12961
12963 Sema &S, Expr *E, QualType T, SourceLocation CC,
12964 bool ExtraCheckForImplicitConversion,
12966 E = E->IgnoreParenImpCasts();
12967 WorkList.push_back({E, CC, false});
12968
12969 if (ExtraCheckForImplicitConversion && E->getType() != T)
12970 S.CheckImplicitConversion(E, T, CC);
12971}
12972
12973/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12974/// that should be visited are added to WorkList.
12976 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12978 Expr *OrigE = Item.E;
12979 SourceLocation CC = Item.CC;
12980
12981 QualType T = OrigE->getType();
12982 Expr *E = OrigE->IgnoreParenImpCasts();
12983
12984 // Propagate whether we are in a C++ list initialization expression.
12985 // If so, we do not issue warnings for implicit int-float conversion
12986 // precision loss, because C++11 narrowing already handles it.
12987 //
12988 // HLSL's initialization lists are special, so they shouldn't observe the C++
12989 // behavior here.
12990 bool IsListInit =
12991 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
12992 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
12993
12994 if (E->isTypeDependent() || E->isValueDependent())
12995 return;
12996
12997 Expr *SourceExpr = E;
12998 // Examine, but don't traverse into the source expression of an
12999 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13000 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13001 // evaluate it in the context of checking the specific conversion to T though.
13002 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13003 if (auto *Src = OVE->getSourceExpr())
13004 SourceExpr = Src;
13005
13006 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13007 if (UO->getOpcode() == UO_Not &&
13008 UO->getSubExpr()->isKnownToHaveBooleanValue())
13009 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13010 << OrigE->getSourceRange() << T->isBooleanType()
13011 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13012
13013 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
13014 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13015 BO->getLHS()->isKnownToHaveBooleanValue() &&
13016 BO->getRHS()->isKnownToHaveBooleanValue() &&
13017 BO->getLHS()->HasSideEffects(S.Context) &&
13018 BO->getRHS()->HasSideEffects(S.Context)) {
13020 const LangOptions &LO = S.getLangOpts();
13021 SourceLocation BLoc = BO->getOperatorLoc();
13022 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
13023 StringRef SR = clang::Lexer::getSourceText(
13024 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
13025 // To reduce false positives, only issue the diagnostic if the operator
13026 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13027 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13028 // in C, along with other macro spellings the user might invent.
13029 if (SR.str() == "&" || SR.str() == "|") {
13030
13031 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13032 << (BO->getOpcode() == BO_And ? "&" : "|")
13033 << OrigE->getSourceRange()
13035 BO->getOperatorLoc(),
13036 (BO->getOpcode() == BO_And ? "&&" : "||"));
13037 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13038 }
13039 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13040 /// Analyze the given comma operator. The basic idea behind the analysis
13041 /// is to analyze the left and right operands slightly differently. The
13042 /// left operand needs to check whether the operand itself has an implicit
13043 /// conversion, but not whether the left operand induces an implicit
13044 /// conversion for the entire comma expression itself. This is similar to
13045 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13046 /// were directly used for the implicit conversion check.
13047 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
13048 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13049 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
13050 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13051 return;
13052 }
13053 }
13054
13055 // For conditional operators, we analyze the arguments as if they
13056 // were being fed directly into the output.
13057 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13058 CheckConditionalOperator(S, CO, CC, T);
13059 return;
13060 }
13061
13062 // Check implicit argument conversions for function calls.
13063 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
13065
13066 // Go ahead and check any implicit conversions we might have skipped.
13067 // The non-canonical typecheck is just an optimization;
13068 // CheckImplicitConversion will filter out dead implicit conversions.
13069 if (SourceExpr->getType() != T)
13070 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
13071
13072 // Now continue drilling into this expression.
13073
13074 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13075 // The bound subexpressions in a PseudoObjectExpr are not reachable
13076 // as transitive children.
13077 // FIXME: Use a more uniform representation for this.
13078 for (auto *SE : POE->semantics())
13079 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13080 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13081 }
13082
13083 // Skip past explicit casts.
13084 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13085 E = CE->getSubExpr();
13086 // In the special case of a C++ function-style cast with braces,
13087 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13088 // initializer. This InitListExpr basically belongs to the cast itself, so
13089 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13091 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
13092 if (InitListE->getNumInits() == 1) {
13093 E = InitListE->getInit(0);
13094 }
13095 }
13096 }
13097 E = E->IgnoreParenImpCasts();
13098 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13099 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13100 WorkList.push_back({E, CC, IsListInit});
13101 return;
13102 }
13103
13104 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
13105 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
13106 // The base expression is only used to initialize the parameter for
13107 // arguments to `inout` parameters, so we only traverse down the base
13108 // expression for `inout` cases.
13109 if (OutArgE->isInOut())
13110 WorkList.push_back(
13111 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
13112 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
13113 return;
13114 }
13115
13116 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13117 // Do a somewhat different check with comparison operators.
13118 if (BO->isComparisonOp())
13119 return AnalyzeComparison(S, BO);
13120
13121 // And with simple assignments.
13122 if (BO->getOpcode() == BO_Assign)
13123 return AnalyzeAssignment(S, BO);
13124 // And with compound assignments.
13125 if (BO->isAssignmentOp())
13126 return AnalyzeCompoundAssignment(S, BO);
13127 }
13128
13129 // These break the otherwise-useful invariant below. Fortunately,
13130 // we don't really need to recurse into them, because any internal
13131 // expressions should have been analyzed already when they were
13132 // built into statements.
13133 if (isa<StmtExpr>(E)) return;
13134
13135 // Don't descend into unevaluated contexts.
13136 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13137
13138 // Now just recurse over the expression's children.
13139 CC = E->getExprLoc();
13140 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13141 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13142 for (Stmt *SubStmt : E->children()) {
13143 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13144 if (!ChildExpr)
13145 continue;
13146
13147 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
13148 if (ChildExpr == CSE->getOperand())
13149 // Do not recurse over a CoroutineSuspendExpr's operand.
13150 // The operand is also a subexpression of getCommonExpr(), and
13151 // recursing into it directly would produce duplicate diagnostics.
13152 continue;
13153
13154 if (IsLogicalAndOperator &&
13156 // Ignore checking string literals that are in logical and operators.
13157 // This is a common pattern for asserts.
13158 continue;
13159 WorkList.push_back({ChildExpr, CC, IsListInit});
13160 }
13161
13162 if (BO && BO->isLogicalOp()) {
13163 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13164 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13165 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13166
13167 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13168 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13169 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13170 }
13171
13172 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13173 if (U->getOpcode() == UO_LNot) {
13174 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13175 } else if (U->getOpcode() != UO_AddrOf) {
13176 if (U->getSubExpr()->getType()->isAtomicType())
13177 S.Diag(U->getSubExpr()->getBeginLoc(),
13178 diag::warn_atomic_implicit_seq_cst);
13179 }
13180 }
13181}
13182
13183/// AnalyzeImplicitConversions - Find and report any interesting
13184/// implicit conversions in the given expression. There are a couple
13185/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13187 bool IsListInit/*= false*/) {
13189 WorkList.push_back({OrigE, CC, IsListInit});
13190 while (!WorkList.empty())
13191 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13192}
13193
13194// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13195// Returns true when emitting a warning about taking the address of a reference.
13196static bool CheckForReference(Sema &SemaRef, const Expr *E,
13197 const PartialDiagnostic &PD) {
13198 E = E->IgnoreParenImpCasts();
13199
13200 const FunctionDecl *FD = nullptr;
13201
13202 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13203 if (!DRE->getDecl()->getType()->isReferenceType())
13204 return false;
13205 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13206 if (!M->getMemberDecl()->getType()->isReferenceType())
13207 return false;
13208 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13209 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13210 return false;
13211 FD = Call->getDirectCallee();
13212 } else {
13213 return false;
13214 }
13215
13216 SemaRef.Diag(E->getExprLoc(), PD);
13217
13218 // If possible, point to location of function.
13219 if (FD) {
13220 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13221 }
13222
13223 return true;
13224}
13225
13226// Returns true if the SourceLocation is expanded from any macro body.
13227// Returns false if the SourceLocation is invalid, is from not in a macro
13228// expansion, or is from expanded from a top-level macro argument.
13230 if (Loc.isInvalid())
13231 return false;
13232
13233 while (Loc.isMacroID()) {
13234 if (SM.isMacroBodyExpansion(Loc))
13235 return true;
13236 Loc = SM.getImmediateMacroCallerLoc(Loc);
13237 }
13238
13239 return false;
13240}
13241
13244 bool IsEqual, SourceRange Range) {
13245 if (!E)
13246 return;
13247
13248 // Don't warn inside macros.
13249 if (E->getExprLoc().isMacroID()) {
13251 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13252 IsInAnyMacroBody(SM, Range.getBegin()))
13253 return;
13254 }
13255 E = E->IgnoreImpCasts();
13256
13257 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13258
13259 if (isa<CXXThisExpr>(E)) {
13260 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13261 : diag::warn_this_bool_conversion;
13262 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13263 return;
13264 }
13265
13266 bool IsAddressOf = false;
13267
13268 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
13269 if (UO->getOpcode() != UO_AddrOf)
13270 return;
13271 IsAddressOf = true;
13272 E = UO->getSubExpr();
13273 }
13274
13275 if (IsAddressOf) {
13276 unsigned DiagID = IsCompare
13277 ? diag::warn_address_of_reference_null_compare
13278 : diag::warn_address_of_reference_bool_conversion;
13279 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13280 << IsEqual;
13281 if (CheckForReference(*this, E, PD)) {
13282 return;
13283 }
13284 }
13285
13286 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13287 bool IsParam = isa<NonNullAttr>(NonnullAttr);
13288 std::string Str;
13289 llvm::raw_string_ostream S(Str);
13290 E->printPretty(S, nullptr, getPrintingPolicy());
13291 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13292 : diag::warn_cast_nonnull_to_bool;
13293 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13294 << E->getSourceRange() << Range << IsEqual;
13295 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13296 };
13297
13298 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13299 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13300 if (auto *Callee = Call->getDirectCallee()) {
13301 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13302 ComplainAboutNonnullParamOrCall(A);
13303 return;
13304 }
13305 }
13306 }
13307
13308 // Complain if we are converting a lambda expression to a boolean value
13309 // outside of instantiation.
13310 if (!inTemplateInstantiation()) {
13311 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
13312 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13313 MRecordDecl && MRecordDecl->isLambda()) {
13314 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
13315 << /*LambdaPointerConversionOperatorType=*/3
13316 << MRecordDecl->getSourceRange() << Range << IsEqual;
13317 return;
13318 }
13319 }
13320 }
13321
13322 // Expect to find a single Decl. Skip anything more complicated.
13323 ValueDecl *D = nullptr;
13324 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13325 D = R->getDecl();
13326 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13327 D = M->getMemberDecl();
13328 }
13329
13330 // Weak Decls can be null.
13331 if (!D || D->isWeak())
13332 return;
13333
13334 // Check for parameter decl with nonnull attribute
13335 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13336 if (getCurFunction() &&
13337 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13338 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13339 ComplainAboutNonnullParamOrCall(A);
13340 return;
13341 }
13342
13343 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13344 // Skip function template not specialized yet.
13346 return;
13347 auto ParamIter = llvm::find(FD->parameters(), PV);
13348 assert(ParamIter != FD->param_end());
13349 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13350
13351 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13352 if (!NonNull->args_size()) {
13353 ComplainAboutNonnullParamOrCall(NonNull);
13354 return;
13355 }
13356
13357 for (const ParamIdx &ArgNo : NonNull->args()) {
13358 if (ArgNo.getASTIndex() == ParamNo) {
13359 ComplainAboutNonnullParamOrCall(NonNull);
13360 return;
13361 }
13362 }
13363 }
13364 }
13365 }
13366 }
13367
13368 QualType T = D->getType();
13369 const bool IsArray = T->isArrayType();
13370 const bool IsFunction = T->isFunctionType();
13371
13372 // Address of function is used to silence the function warning.
13373 if (IsAddressOf && IsFunction) {
13374 return;
13375 }
13376
13377 // Found nothing.
13378 if (!IsAddressOf && !IsFunction && !IsArray)
13379 return;
13380
13381 // Pretty print the expression for the diagnostic.
13382 std::string Str;
13383 llvm::raw_string_ostream S(Str);
13384 E->printPretty(S, nullptr, getPrintingPolicy());
13385
13386 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13387 : diag::warn_impcast_pointer_to_bool;
13388 enum {
13389 AddressOf,
13390 FunctionPointer,
13391 ArrayPointer
13392 } DiagType;
13393 if (IsAddressOf)
13394 DiagType = AddressOf;
13395 else if (IsFunction)
13396 DiagType = FunctionPointer;
13397 else if (IsArray)
13398 DiagType = ArrayPointer;
13399 else
13400 llvm_unreachable("Could not determine diagnostic.");
13401 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13402 << Range << IsEqual;
13403
13404 if (!IsFunction)
13405 return;
13406
13407 // Suggest '&' to silence the function warning.
13408 Diag(E->getExprLoc(), diag::note_function_warning_silence)
13410
13411 // Check to see if '()' fixit should be emitted.
13412 QualType ReturnType;
13413 UnresolvedSet<4> NonTemplateOverloads;
13414 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13415 if (ReturnType.isNull())
13416 return;
13417
13418 if (IsCompare) {
13419 // There are two cases here. If there is null constant, the only suggest
13420 // for a pointer return type. If the null is 0, then suggest if the return
13421 // type is a pointer or an integer type.
13422 if (!ReturnType->isPointerType()) {
13423 if (NullKind == Expr::NPCK_ZeroExpression ||
13424 NullKind == Expr::NPCK_ZeroLiteral) {
13425 if (!ReturnType->isIntegerType())
13426 return;
13427 } else {
13428 return;
13429 }
13430 }
13431 } else { // !IsCompare
13432 // For function to bool, only suggest if the function pointer has bool
13433 // return type.
13434 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13435 return;
13436 }
13437 Diag(E->getExprLoc(), diag::note_function_to_function_call)
13439}
13440
13441void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13442 // Don't diagnose in unevaluated contexts.
13444 return;
13445
13446 // Don't diagnose for value- or type-dependent expressions.
13447 if (E->isTypeDependent() || E->isValueDependent())
13448 return;
13449
13450 // Check for array bounds violations in cases where the check isn't triggered
13451 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13452 // ArraySubscriptExpr is on the RHS of a variable initialization.
13453 CheckArrayAccess(E);
13454
13455 // This is not the right CC for (e.g.) a variable initialization.
13456 AnalyzeImplicitConversions(*this, E, CC);
13457}
13458
13459void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13460 ::CheckBoolLikeConversion(*this, E, CC);
13461}
13462
13463void Sema::CheckForIntOverflow (const Expr *E) {
13464 // Use a work list to deal with nested struct initializers.
13465 SmallVector<const Expr *, 2> Exprs(1, E);
13466
13467 do {
13468 const Expr *OriginalE = Exprs.pop_back_val();
13469 const Expr *E = OriginalE->IgnoreParenCasts();
13470
13473 continue;
13474 }
13475
13476 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
13477 Exprs.append(InitList->inits().begin(), InitList->inits().end());
13478 else if (isa<ObjCBoxedExpr>(OriginalE))
13480 else if (const auto *Call = dyn_cast<CallExpr>(E))
13481 Exprs.append(Call->arg_begin(), Call->arg_end());
13482 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
13483 Exprs.append(Message->arg_begin(), Message->arg_end());
13484 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
13485 Exprs.append(Construct->arg_begin(), Construct->arg_end());
13486 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
13487 Exprs.push_back(Temporary->getSubExpr());
13488 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
13489 Exprs.push_back(Array->getIdx());
13490 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
13491 Exprs.push_back(Compound->getInitializer());
13492 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
13493 New && New->isArray()) {
13494 if (auto ArraySize = New->getArraySize())
13495 Exprs.push_back(*ArraySize);
13496 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
13497 Exprs.push_back(MTE->getSubExpr());
13498 } while (!Exprs.empty());
13499}
13500
13501namespace {
13502
13503/// Visitor for expressions which looks for unsequenced operations on the
13504/// same object.
13505class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13506 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13507
13508 /// A tree of sequenced regions within an expression. Two regions are
13509 /// unsequenced if one is an ancestor or a descendent of the other. When we
13510 /// finish processing an expression with sequencing, such as a comma
13511 /// expression, we fold its tree nodes into its parent, since they are
13512 /// unsequenced with respect to nodes we will visit later.
13513 class SequenceTree {
13514 struct Value {
13515 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13516 unsigned Parent : 31;
13517 LLVM_PREFERRED_TYPE(bool)
13518 unsigned Merged : 1;
13519 };
13520 SmallVector<Value, 8> Values;
13521
13522 public:
13523 /// A region within an expression which may be sequenced with respect
13524 /// to some other region.
13525 class Seq {
13526 friend class SequenceTree;
13527
13528 unsigned Index;
13529
13530 explicit Seq(unsigned N) : Index(N) {}
13531
13532 public:
13533 Seq() : Index(0) {}
13534 };
13535
13536 SequenceTree() { Values.push_back(Value(0)); }
13537 Seq root() const { return Seq(0); }
13538
13539 /// Create a new sequence of operations, which is an unsequenced
13540 /// subset of \p Parent. This sequence of operations is sequenced with
13541 /// respect to other children of \p Parent.
13542 Seq allocate(Seq Parent) {
13543 Values.push_back(Value(Parent.Index));
13544 return Seq(Values.size() - 1);
13545 }
13546
13547 /// Merge a sequence of operations into its parent.
13548 void merge(Seq S) {
13549 Values[S.Index].Merged = true;
13550 }
13551
13552 /// Determine whether two operations are unsequenced. This operation
13553 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13554 /// should have been merged into its parent as appropriate.
13555 bool isUnsequenced(Seq Cur, Seq Old) {
13556 unsigned C = representative(Cur.Index);
13557 unsigned Target = representative(Old.Index);
13558 while (C >= Target) {
13559 if (C == Target)
13560 return true;
13561 C = Values[C].Parent;
13562 }
13563 return false;
13564 }
13565
13566 private:
13567 /// Pick a representative for a sequence.
13568 unsigned representative(unsigned K) {
13569 if (Values[K].Merged)
13570 // Perform path compression as we go.
13571 return Values[K].Parent = representative(Values[K].Parent);
13572 return K;
13573 }
13574 };
13575
13576 /// An object for which we can track unsequenced uses.
13577 using Object = const NamedDecl *;
13578
13579 /// Different flavors of object usage which we track. We only track the
13580 /// least-sequenced usage of each kind.
13581 enum UsageKind {
13582 /// A read of an object. Multiple unsequenced reads are OK.
13583 UK_Use,
13584
13585 /// A modification of an object which is sequenced before the value
13586 /// computation of the expression, such as ++n in C++.
13587 UK_ModAsValue,
13588
13589 /// A modification of an object which is not sequenced before the value
13590 /// computation of the expression, such as n++.
13591 UK_ModAsSideEffect,
13592
13593 UK_Count = UK_ModAsSideEffect + 1
13594 };
13595
13596 /// Bundle together a sequencing region and the expression corresponding
13597 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13598 struct Usage {
13599 const Expr *UsageExpr = nullptr;
13600 SequenceTree::Seq Seq;
13601
13602 Usage() = default;
13603 };
13604
13605 struct UsageInfo {
13606 Usage Uses[UK_Count];
13607
13608 /// Have we issued a diagnostic for this object already?
13609 bool Diagnosed = false;
13610
13611 UsageInfo();
13612 };
13613 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13614
13615 Sema &SemaRef;
13616
13617 /// Sequenced regions within the expression.
13618 SequenceTree Tree;
13619
13620 /// Declaration modifications and references which we have seen.
13621 UsageInfoMap UsageMap;
13622
13623 /// The region we are currently within.
13624 SequenceTree::Seq Region;
13625
13626 /// Filled in with declarations which were modified as a side-effect
13627 /// (that is, post-increment operations).
13628 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13629
13630 /// Expressions to check later. We defer checking these to reduce
13631 /// stack usage.
13632 SmallVectorImpl<const Expr *> &WorkList;
13633
13634 /// RAII object wrapping the visitation of a sequenced subexpression of an
13635 /// expression. At the end of this process, the side-effects of the evaluation
13636 /// become sequenced with respect to the value computation of the result, so
13637 /// we downgrade any UK_ModAsSideEffect within the evaluation to
13638 /// UK_ModAsValue.
13639 struct SequencedSubexpression {
13640 SequencedSubexpression(SequenceChecker &Self)
13641 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13642 Self.ModAsSideEffect = &ModAsSideEffect;
13643 }
13644
13645 ~SequencedSubexpression() {
13646 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13647 // Add a new usage with usage kind UK_ModAsValue, and then restore
13648 // the previous usage with UK_ModAsSideEffect (thus clearing it if
13649 // the previous one was empty).
13650 UsageInfo &UI = Self.UsageMap[M.first];
13651 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13652 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13653 SideEffectUsage = M.second;
13654 }
13655 Self.ModAsSideEffect = OldModAsSideEffect;
13656 }
13657
13658 SequenceChecker &Self;
13659 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13660 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13661 };
13662
13663 /// RAII object wrapping the visitation of a subexpression which we might
13664 /// choose to evaluate as a constant. If any subexpression is evaluated and
13665 /// found to be non-constant, this allows us to suppress the evaluation of
13666 /// the outer expression.
13667 class EvaluationTracker {
13668 public:
13669 EvaluationTracker(SequenceChecker &Self)
13670 : Self(Self), Prev(Self.EvalTracker) {
13671 Self.EvalTracker = this;
13672 }
13673
13674 ~EvaluationTracker() {
13675 Self.EvalTracker = Prev;
13676 if (Prev)
13677 Prev->EvalOK &= EvalOK;
13678 }
13679
13680 bool evaluate(const Expr *E, bool &Result) {
13681 if (!EvalOK || E->isValueDependent())
13682 return false;
13683 EvalOK = E->EvaluateAsBooleanCondition(
13684 Result, Self.SemaRef.Context,
13685 Self.SemaRef.isConstantEvaluatedContext());
13686 return EvalOK;
13687 }
13688
13689 private:
13690 SequenceChecker &Self;
13691 EvaluationTracker *Prev;
13692 bool EvalOK = true;
13693 } *EvalTracker = nullptr;
13694
13695 /// Find the object which is produced by the specified expression,
13696 /// if any.
13697 Object getObject(const Expr *E, bool Mod) const {
13698 E = E->IgnoreParenCasts();
13699 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13700 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13701 return getObject(UO->getSubExpr(), Mod);
13702 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13703 if (BO->getOpcode() == BO_Comma)
13704 return getObject(BO->getRHS(), Mod);
13705 if (Mod && BO->isAssignmentOp())
13706 return getObject(BO->getLHS(), Mod);
13707 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13708 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13709 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13710 return ME->getMemberDecl();
13711 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13712 // FIXME: If this is a reference, map through to its value.
13713 return DRE->getDecl();
13714 return nullptr;
13715 }
13716
13717 /// Note that an object \p O was modified or used by an expression
13718 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13719 /// the object \p O as obtained via the \p UsageMap.
13720 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13721 // Get the old usage for the given object and usage kind.
13722 Usage &U = UI.Uses[UK];
13723 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13724 // If we have a modification as side effect and are in a sequenced
13725 // subexpression, save the old Usage so that we can restore it later
13726 // in SequencedSubexpression::~SequencedSubexpression.
13727 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13728 ModAsSideEffect->push_back(std::make_pair(O, U));
13729 // Then record the new usage with the current sequencing region.
13730 U.UsageExpr = UsageExpr;
13731 U.Seq = Region;
13732 }
13733 }
13734
13735 /// Check whether a modification or use of an object \p O in an expression
13736 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13737 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13738 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13739 /// usage and false we are checking for a mod-use unsequenced usage.
13740 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13741 UsageKind OtherKind, bool IsModMod) {
13742 if (UI.Diagnosed)
13743 return;
13744
13745 const Usage &U = UI.Uses[OtherKind];
13746 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13747 return;
13748
13749 const Expr *Mod = U.UsageExpr;
13750 const Expr *ModOrUse = UsageExpr;
13751 if (OtherKind == UK_Use)
13752 std::swap(Mod, ModOrUse);
13753
13754 SemaRef.DiagRuntimeBehavior(
13755 Mod->getExprLoc(), {Mod, ModOrUse},
13756 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13757 : diag::warn_unsequenced_mod_use)
13758 << O << SourceRange(ModOrUse->getExprLoc()));
13759 UI.Diagnosed = true;
13760 }
13761
13762 // A note on note{Pre, Post}{Use, Mod}:
13763 //
13764 // (It helps to follow the algorithm with an expression such as
13765 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13766 // operations before C++17 and both are well-defined in C++17).
13767 //
13768 // When visiting a node which uses/modify an object we first call notePreUse
13769 // or notePreMod before visiting its sub-expression(s). At this point the
13770 // children of the current node have not yet been visited and so the eventual
13771 // uses/modifications resulting from the children of the current node have not
13772 // been recorded yet.
13773 //
13774 // We then visit the children of the current node. After that notePostUse or
13775 // notePostMod is called. These will 1) detect an unsequenced modification
13776 // as side effect (as in "k++ + k") and 2) add a new usage with the
13777 // appropriate usage kind.
13778 //
13779 // We also have to be careful that some operation sequences modification as
13780 // side effect as well (for example: || or ,). To account for this we wrap
13781 // the visitation of such a sub-expression (for example: the LHS of || or ,)
13782 // with SequencedSubexpression. SequencedSubexpression is an RAII object
13783 // which record usages which are modifications as side effect, and then
13784 // downgrade them (or more accurately restore the previous usage which was a
13785 // modification as side effect) when exiting the scope of the sequenced
13786 // subexpression.
13787
13788 void notePreUse(Object O, const Expr *UseExpr) {
13789 UsageInfo &UI = UsageMap[O];
13790 // Uses conflict with other modifications.
13791 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13792 }
13793
13794 void notePostUse(Object O, const Expr *UseExpr) {
13795 UsageInfo &UI = UsageMap[O];
13796 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13797 /*IsModMod=*/false);
13798 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13799 }
13800
13801 void notePreMod(Object O, const Expr *ModExpr) {
13802 UsageInfo &UI = UsageMap[O];
13803 // Modifications conflict with other modifications and with uses.
13804 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13805 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13806 }
13807
13808 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13809 UsageInfo &UI = UsageMap[O];
13810 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13811 /*IsModMod=*/true);
13812 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13813 }
13814
13815public:
13816 SequenceChecker(Sema &S, const Expr *E,
13817 SmallVectorImpl<const Expr *> &WorkList)
13818 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13819 Visit(E);
13820 // Silence a -Wunused-private-field since WorkList is now unused.
13821 // TODO: Evaluate if it can be used, and if not remove it.
13822 (void)this->WorkList;
13823 }
13824
13825 void VisitStmt(const Stmt *S) {
13826 // Skip all statements which aren't expressions for now.
13827 }
13828
13829 void VisitExpr(const Expr *E) {
13830 // By default, just recurse to evaluated subexpressions.
13831 Base::VisitStmt(E);
13832 }
13833
13834 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
13835 for (auto *Sub : CSE->children()) {
13836 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
13837 if (!ChildExpr)
13838 continue;
13839
13840 if (ChildExpr == CSE->getOperand())
13841 // Do not recurse over a CoroutineSuspendExpr's operand.
13842 // The operand is also a subexpression of getCommonExpr(), and
13843 // recursing into it directly could confuse object management
13844 // for the sake of sequence tracking.
13845 continue;
13846
13847 Visit(Sub);
13848 }
13849 }
13850
13851 void VisitCastExpr(const CastExpr *E) {
13852 Object O = Object();
13853 if (E->getCastKind() == CK_LValueToRValue)
13854 O = getObject(E->getSubExpr(), false);
13855
13856 if (O)
13857 notePreUse(O, E);
13858 VisitExpr(E);
13859 if (O)
13860 notePostUse(O, E);
13861 }
13862
13863 void VisitSequencedExpressions(const Expr *SequencedBefore,
13864 const Expr *SequencedAfter) {
13865 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13866 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13867 SequenceTree::Seq OldRegion = Region;
13868
13869 {
13870 SequencedSubexpression SeqBefore(*this);
13871 Region = BeforeRegion;
13872 Visit(SequencedBefore);
13873 }
13874
13875 Region = AfterRegion;
13876 Visit(SequencedAfter);
13877
13878 Region = OldRegion;
13879
13880 Tree.merge(BeforeRegion);
13881 Tree.merge(AfterRegion);
13882 }
13883
13884 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13885 // C++17 [expr.sub]p1:
13886 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13887 // expression E1 is sequenced before the expression E2.
13888 if (SemaRef.getLangOpts().CPlusPlus17)
13889 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13890 else {
13891 Visit(ASE->getLHS());
13892 Visit(ASE->getRHS());
13893 }
13894 }
13895
13896 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13897 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13898 void VisitBinPtrMem(const BinaryOperator *BO) {
13899 // C++17 [expr.mptr.oper]p4:
13900 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13901 // the expression E1 is sequenced before the expression E2.
13902 if (SemaRef.getLangOpts().CPlusPlus17)
13903 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13904 else {
13905 Visit(BO->getLHS());
13906 Visit(BO->getRHS());
13907 }
13908 }
13909
13910 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13911 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13912 void VisitBinShlShr(const BinaryOperator *BO) {
13913 // C++17 [expr.shift]p4:
13914 // The expression E1 is sequenced before the expression E2.
13915 if (SemaRef.getLangOpts().CPlusPlus17)
13916 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13917 else {
13918 Visit(BO->getLHS());
13919 Visit(BO->getRHS());
13920 }
13921 }
13922
13923 void VisitBinComma(const BinaryOperator *BO) {
13924 // C++11 [expr.comma]p1:
13925 // Every value computation and side effect associated with the left
13926 // expression is sequenced before every value computation and side
13927 // effect associated with the right expression.
13928 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13929 }
13930
13931 void VisitBinAssign(const BinaryOperator *BO) {
13932 SequenceTree::Seq RHSRegion;
13933 SequenceTree::Seq LHSRegion;
13934 if (SemaRef.getLangOpts().CPlusPlus17) {
13935 RHSRegion = Tree.allocate(Region);
13936 LHSRegion = Tree.allocate(Region);
13937 } else {
13938 RHSRegion = Region;
13939 LHSRegion = Region;
13940 }
13941 SequenceTree::Seq OldRegion = Region;
13942
13943 // C++11 [expr.ass]p1:
13944 // [...] the assignment is sequenced after the value computation
13945 // of the right and left operands, [...]
13946 //
13947 // so check it before inspecting the operands and update the
13948 // map afterwards.
13949 Object O = getObject(BO->getLHS(), /*Mod=*/true);
13950 if (O)
13951 notePreMod(O, BO);
13952
13953 if (SemaRef.getLangOpts().CPlusPlus17) {
13954 // C++17 [expr.ass]p1:
13955 // [...] The right operand is sequenced before the left operand. [...]
13956 {
13957 SequencedSubexpression SeqBefore(*this);
13958 Region = RHSRegion;
13959 Visit(BO->getRHS());
13960 }
13961
13962 Region = LHSRegion;
13963 Visit(BO->getLHS());
13964
13965 if (O && isa<CompoundAssignOperator>(BO))
13966 notePostUse(O, BO);
13967
13968 } else {
13969 // C++11 does not specify any sequencing between the LHS and RHS.
13970 Region = LHSRegion;
13971 Visit(BO->getLHS());
13972
13973 if (O && isa<CompoundAssignOperator>(BO))
13974 notePostUse(O, BO);
13975
13976 Region = RHSRegion;
13977 Visit(BO->getRHS());
13978 }
13979
13980 // C++11 [expr.ass]p1:
13981 // the assignment is sequenced [...] before the value computation of the
13982 // assignment expression.
13983 // C11 6.5.16/3 has no such rule.
13984 Region = OldRegion;
13985 if (O)
13986 notePostMod(O, BO,
13987 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13988 : UK_ModAsSideEffect);
13989 if (SemaRef.getLangOpts().CPlusPlus17) {
13990 Tree.merge(RHSRegion);
13991 Tree.merge(LHSRegion);
13992 }
13993 }
13994
13995 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13996 VisitBinAssign(CAO);
13997 }
13998
13999 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14000 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14001 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14002 Object O = getObject(UO->getSubExpr(), true);
14003 if (!O)
14004 return VisitExpr(UO);
14005
14006 notePreMod(O, UO);
14007 Visit(UO->getSubExpr());
14008 // C++11 [expr.pre.incr]p1:
14009 // the expression ++x is equivalent to x+=1
14010 notePostMod(O, UO,
14011 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14012 : UK_ModAsSideEffect);
14013 }
14014
14015 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14016 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14017 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14018 Object O = getObject(UO->getSubExpr(), true);
14019 if (!O)
14020 return VisitExpr(UO);
14021
14022 notePreMod(O, UO);
14023 Visit(UO->getSubExpr());
14024 notePostMod(O, UO, UK_ModAsSideEffect);
14025 }
14026
14027 void VisitBinLOr(const BinaryOperator *BO) {
14028 // C++11 [expr.log.or]p2:
14029 // If the second expression is evaluated, every value computation and
14030 // side effect associated with the first expression is sequenced before
14031 // every value computation and side effect associated with the
14032 // second expression.
14033 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14034 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14035 SequenceTree::Seq OldRegion = Region;
14036
14037 EvaluationTracker Eval(*this);
14038 {
14039 SequencedSubexpression Sequenced(*this);
14040 Region = LHSRegion;
14041 Visit(BO->getLHS());
14042 }
14043
14044 // C++11 [expr.log.or]p1:
14045 // [...] the second operand is not evaluated if the first operand
14046 // evaluates to true.
14047 bool EvalResult = false;
14048 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14049 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14050 if (ShouldVisitRHS) {
14051 Region = RHSRegion;
14052 Visit(BO->getRHS());
14053 }
14054
14055 Region = OldRegion;
14056 Tree.merge(LHSRegion);
14057 Tree.merge(RHSRegion);
14058 }
14059
14060 void VisitBinLAnd(const BinaryOperator *BO) {
14061 // C++11 [expr.log.and]p2:
14062 // If the second expression is evaluated, every value computation and
14063 // side effect associated with the first expression is sequenced before
14064 // every value computation and side effect associated with the
14065 // second expression.
14066 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14067 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14068 SequenceTree::Seq OldRegion = Region;
14069
14070 EvaluationTracker Eval(*this);
14071 {
14072 SequencedSubexpression Sequenced(*this);
14073 Region = LHSRegion;
14074 Visit(BO->getLHS());
14075 }
14076
14077 // C++11 [expr.log.and]p1:
14078 // [...] the second operand is not evaluated if the first operand is false.
14079 bool EvalResult = false;
14080 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14081 bool ShouldVisitRHS = !EvalOK || EvalResult;
14082 if (ShouldVisitRHS) {
14083 Region = RHSRegion;
14084 Visit(BO->getRHS());
14085 }
14086
14087 Region = OldRegion;
14088 Tree.merge(LHSRegion);
14089 Tree.merge(RHSRegion);
14090 }
14091
14092 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14093 // C++11 [expr.cond]p1:
14094 // [...] Every value computation and side effect associated with the first
14095 // expression is sequenced before every value computation and side effect
14096 // associated with the second or third expression.
14097 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14098
14099 // No sequencing is specified between the true and false expression.
14100 // However since exactly one of both is going to be evaluated we can
14101 // consider them to be sequenced. This is needed to avoid warning on
14102 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14103 // both the true and false expressions because we can't evaluate x.
14104 // This will still allow us to detect an expression like (pre C++17)
14105 // "(x ? y += 1 : y += 2) = y".
14106 //
14107 // We don't wrap the visitation of the true and false expression with
14108 // SequencedSubexpression because we don't want to downgrade modifications
14109 // as side effect in the true and false expressions after the visition
14110 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14111 // not warn between the two "y++", but we should warn between the "y++"
14112 // and the "y".
14113 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14114 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14115 SequenceTree::Seq OldRegion = Region;
14116
14117 EvaluationTracker Eval(*this);
14118 {
14119 SequencedSubexpression Sequenced(*this);
14120 Region = ConditionRegion;
14121 Visit(CO->getCond());
14122 }
14123
14124 // C++11 [expr.cond]p1:
14125 // [...] The first expression is contextually converted to bool (Clause 4).
14126 // It is evaluated and if it is true, the result of the conditional
14127 // expression is the value of the second expression, otherwise that of the
14128 // third expression. Only one of the second and third expressions is
14129 // evaluated. [...]
14130 bool EvalResult = false;
14131 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14132 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14133 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14134 if (ShouldVisitTrueExpr) {
14135 Region = TrueRegion;
14136 Visit(CO->getTrueExpr());
14137 }
14138 if (ShouldVisitFalseExpr) {
14139 Region = FalseRegion;
14140 Visit(CO->getFalseExpr());
14141 }
14142
14143 Region = OldRegion;
14144 Tree.merge(ConditionRegion);
14145 Tree.merge(TrueRegion);
14146 Tree.merge(FalseRegion);
14147 }
14148
14149 void VisitCallExpr(const CallExpr *CE) {
14150 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14151
14152 if (CE->isUnevaluatedBuiltinCall(Context))
14153 return;
14154
14155 // C++11 [intro.execution]p15:
14156 // When calling a function [...], every value computation and side effect
14157 // associated with any argument expression, or with the postfix expression
14158 // designating the called function, is sequenced before execution of every
14159 // expression or statement in the body of the function [and thus before
14160 // the value computation of its result].
14161 SequencedSubexpression Sequenced(*this);
14162 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14163 // C++17 [expr.call]p5
14164 // The postfix-expression is sequenced before each expression in the
14165 // expression-list and any default argument. [...]
14166 SequenceTree::Seq CalleeRegion;
14167 SequenceTree::Seq OtherRegion;
14168 if (SemaRef.getLangOpts().CPlusPlus17) {
14169 CalleeRegion = Tree.allocate(Region);
14170 OtherRegion = Tree.allocate(Region);
14171 } else {
14172 CalleeRegion = Region;
14173 OtherRegion = Region;
14174 }
14175 SequenceTree::Seq OldRegion = Region;
14176
14177 // Visit the callee expression first.
14178 Region = CalleeRegion;
14179 if (SemaRef.getLangOpts().CPlusPlus17) {
14180 SequencedSubexpression Sequenced(*this);
14181 Visit(CE->getCallee());
14182 } else {
14183 Visit(CE->getCallee());
14184 }
14185
14186 // Then visit the argument expressions.
14187 Region = OtherRegion;
14188 for (const Expr *Argument : CE->arguments())
14189 Visit(Argument);
14190
14191 Region = OldRegion;
14192 if (SemaRef.getLangOpts().CPlusPlus17) {
14193 Tree.merge(CalleeRegion);
14194 Tree.merge(OtherRegion);
14195 }
14196 });
14197 }
14198
14199 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14200 // C++17 [over.match.oper]p2:
14201 // [...] the operator notation is first transformed to the equivalent
14202 // function-call notation as summarized in Table 12 (where @ denotes one
14203 // of the operators covered in the specified subclause). However, the
14204 // operands are sequenced in the order prescribed for the built-in
14205 // operator (Clause 8).
14206 //
14207 // From the above only overloaded binary operators and overloaded call
14208 // operators have sequencing rules in C++17 that we need to handle
14209 // separately.
14210 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14211 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14212 return VisitCallExpr(CXXOCE);
14213
14214 enum {
14215 NoSequencing,
14216 LHSBeforeRHS,
14217 RHSBeforeLHS,
14218 LHSBeforeRest
14219 } SequencingKind;
14220 switch (CXXOCE->getOperator()) {
14221 case OO_Equal:
14222 case OO_PlusEqual:
14223 case OO_MinusEqual:
14224 case OO_StarEqual:
14225 case OO_SlashEqual:
14226 case OO_PercentEqual:
14227 case OO_CaretEqual:
14228 case OO_AmpEqual:
14229 case OO_PipeEqual:
14230 case OO_LessLessEqual:
14231 case OO_GreaterGreaterEqual:
14232 SequencingKind = RHSBeforeLHS;
14233 break;
14234
14235 case OO_LessLess:
14236 case OO_GreaterGreater:
14237 case OO_AmpAmp:
14238 case OO_PipePipe:
14239 case OO_Comma:
14240 case OO_ArrowStar:
14241 case OO_Subscript:
14242 SequencingKind = LHSBeforeRHS;
14243 break;
14244
14245 case OO_Call:
14246 SequencingKind = LHSBeforeRest;
14247 break;
14248
14249 default:
14250 SequencingKind = NoSequencing;
14251 break;
14252 }
14253
14254 if (SequencingKind == NoSequencing)
14255 return VisitCallExpr(CXXOCE);
14256
14257 // This is a call, so all subexpressions are sequenced before the result.
14258 SequencedSubexpression Sequenced(*this);
14259
14260 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14261 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14262 "Should only get there with C++17 and above!");
14263 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14264 "Should only get there with an overloaded binary operator"
14265 " or an overloaded call operator!");
14266
14267 if (SequencingKind == LHSBeforeRest) {
14268 assert(CXXOCE->getOperator() == OO_Call &&
14269 "We should only have an overloaded call operator here!");
14270
14271 // This is very similar to VisitCallExpr, except that we only have the
14272 // C++17 case. The postfix-expression is the first argument of the
14273 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14274 // are in the following arguments.
14275 //
14276 // Note that we intentionally do not visit the callee expression since
14277 // it is just a decayed reference to a function.
14278 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14279 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14280 SequenceTree::Seq OldRegion = Region;
14281
14282 assert(CXXOCE->getNumArgs() >= 1 &&
14283 "An overloaded call operator must have at least one argument"
14284 " for the postfix-expression!");
14285 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14286 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14287 CXXOCE->getNumArgs() - 1);
14288
14289 // Visit the postfix-expression first.
14290 {
14291 Region = PostfixExprRegion;
14292 SequencedSubexpression Sequenced(*this);
14293 Visit(PostfixExpr);
14294 }
14295
14296 // Then visit the argument expressions.
14297 Region = ArgsRegion;
14298 for (const Expr *Arg : Args)
14299 Visit(Arg);
14300
14301 Region = OldRegion;
14302 Tree.merge(PostfixExprRegion);
14303 Tree.merge(ArgsRegion);
14304 } else {
14305 assert(CXXOCE->getNumArgs() == 2 &&
14306 "Should only have two arguments here!");
14307 assert((SequencingKind == LHSBeforeRHS ||
14308 SequencingKind == RHSBeforeLHS) &&
14309 "Unexpected sequencing kind!");
14310
14311 // We do not visit the callee expression since it is just a decayed
14312 // reference to a function.
14313 const Expr *E1 = CXXOCE->getArg(0);
14314 const Expr *E2 = CXXOCE->getArg(1);
14315 if (SequencingKind == RHSBeforeLHS)
14316 std::swap(E1, E2);
14317
14318 return VisitSequencedExpressions(E1, E2);
14319 }
14320 });
14321 }
14322
14323 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14324 // This is a call, so all subexpressions are sequenced before the result.
14325 SequencedSubexpression Sequenced(*this);
14326
14327 if (!CCE->isListInitialization())
14328 return VisitExpr(CCE);
14329
14330 // In C++11, list initializations are sequenced.
14331 SequenceExpressionsInOrder(
14332 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14333 }
14334
14335 void VisitInitListExpr(const InitListExpr *ILE) {
14336 if (!SemaRef.getLangOpts().CPlusPlus11)
14337 return VisitExpr(ILE);
14338
14339 // In C++11, list initializations are sequenced.
14340 SequenceExpressionsInOrder(ILE->inits());
14341 }
14342
14343 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14344 // C++20 parenthesized list initializations are sequenced. See C++20
14345 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14346 SequenceExpressionsInOrder(PLIE->getInitExprs());
14347 }
14348
14349private:
14350 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14352 SequenceTree::Seq Parent = Region;
14353 for (const Expr *E : ExpressionList) {
14354 if (!E)
14355 continue;
14356 Region = Tree.allocate(Parent);
14357 Elts.push_back(Region);
14358 Visit(E);
14359 }
14360
14361 // Forget that the initializers are sequenced.
14362 Region = Parent;
14363 for (unsigned I = 0; I < Elts.size(); ++I)
14364 Tree.merge(Elts[I]);
14365 }
14366};
14367
14368SequenceChecker::UsageInfo::UsageInfo() = default;
14369
14370} // namespace
14371
14372void Sema::CheckUnsequencedOperations(const Expr *E) {
14373 SmallVector<const Expr *, 8> WorkList;
14374 WorkList.push_back(E);
14375 while (!WorkList.empty()) {
14376 const Expr *Item = WorkList.pop_back_val();
14377 SequenceChecker(*this, Item, WorkList);
14378 }
14379}
14380
14381void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14382 bool IsConstexpr) {
14383 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
14384 IsConstexpr || isa<ConstantExpr>(E));
14385 CheckImplicitConversions(E, CheckLoc);
14386 if (!E->isInstantiationDependent())
14387 CheckUnsequencedOperations(E);
14388 if (!IsConstexpr && !E->isValueDependent())
14389 CheckForIntOverflow(E);
14390}
14391
14392void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14393 FieldDecl *BitField,
14394 Expr *Init) {
14395 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14396}
14397
14399 SourceLocation Loc) {
14400 if (!PType->isVariablyModifiedType())
14401 return;
14402 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14403 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14404 return;
14405 }
14406 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14407 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14408 return;
14409 }
14410 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14411 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14412 return;
14413 }
14414
14415 const ArrayType *AT = S.Context.getAsArrayType(PType);
14416 if (!AT)
14417 return;
14418
14421 return;
14422 }
14423
14424 S.Diag(Loc, diag::err_array_star_in_function_definition);
14425}
14426
14428 bool CheckParameterNames) {
14429 bool HasInvalidParm = false;
14430 for (ParmVarDecl *Param : Parameters) {
14431 assert(Param && "null in a parameter list");
14432 // C99 6.7.5.3p4: the parameters in a parameter type list in a
14433 // function declarator that is part of a function definition of
14434 // that function shall not have incomplete type.
14435 //
14436 // C++23 [dcl.fct.def.general]/p2
14437 // The type of a parameter [...] for a function definition
14438 // shall not be a (possibly cv-qualified) class type that is incomplete
14439 // or abstract within the function body unless the function is deleted.
14440 if (!Param->isInvalidDecl() &&
14441 (RequireCompleteType(Param->getLocation(), Param->getType(),
14442 diag::err_typecheck_decl_incomplete_type) ||
14443 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
14444 diag::err_abstract_type_in_decl,
14446 Param->setInvalidDecl();
14447 HasInvalidParm = true;
14448 }
14449
14450 // C99 6.9.1p5: If the declarator includes a parameter type list, the
14451 // declaration of each parameter shall include an identifier.
14452 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14453 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14454 // Diagnose this as an extension in C17 and earlier.
14455 if (!getLangOpts().C23)
14456 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
14457 }
14458
14459 // C99 6.7.5.3p12:
14460 // If the function declarator is not part of a definition of that
14461 // function, parameters may have incomplete type and may use the [*]
14462 // notation in their sequences of declarator specifiers to specify
14463 // variable length array types.
14464 QualType PType = Param->getOriginalType();
14465 // FIXME: This diagnostic should point the '[*]' if source-location
14466 // information is added for it.
14467 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14468
14469 // If the parameter is a c++ class type and it has to be destructed in the
14470 // callee function, declare the destructor so that it can be called by the
14471 // callee function. Do not perform any direct access check on the dtor here.
14472 if (!Param->isInvalidDecl()) {
14473 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14474 if (!ClassDecl->isInvalidDecl() &&
14475 !ClassDecl->hasIrrelevantDestructor() &&
14476 !ClassDecl->isDependentContext() &&
14477 ClassDecl->isParamDestroyedInCallee()) {
14479 MarkFunctionReferenced(Param->getLocation(), Destructor);
14480 DiagnoseUseOfDecl(Destructor, Param->getLocation());
14481 }
14482 }
14483 }
14484
14485 // Parameters with the pass_object_size attribute only need to be marked
14486 // constant at function definitions. Because we lack information about
14487 // whether we're on a declaration or definition when we're instantiating the
14488 // attribute, we need to check for constness here.
14489 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14490 if (!Param->getType().isConstQualified())
14491 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14492 << Attr->getSpelling() << 1;
14493
14494 // Check for parameter names shadowing fields from the class.
14495 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14496 // The owning context for the parameter should be the function, but we
14497 // want to see if this function's declaration context is a record.
14498 DeclContext *DC = Param->getDeclContext();
14499 if (DC && DC->isFunctionOrMethod()) {
14500 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14501 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14502 RD, /*DeclIsField*/ false);
14503 }
14504 }
14505
14506 if (!Param->isInvalidDecl() &&
14507 Param->getOriginalType()->isWebAssemblyTableType()) {
14508 Param->setInvalidDecl();
14509 HasInvalidParm = true;
14510 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
14511 }
14512 }
14513
14514 return HasInvalidParm;
14515}
14516
14517std::optional<std::pair<
14519 *E,
14521 &Ctx);
14522
14523/// Compute the alignment and offset of the base class object given the
14524/// derived-to-base cast expression and the alignment and offset of the derived
14525/// class object.
14526static std::pair<CharUnits, CharUnits>
14528 CharUnits BaseAlignment, CharUnits Offset,
14529 ASTContext &Ctx) {
14530 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14531 ++PathI) {
14532 const CXXBaseSpecifier *Base = *PathI;
14533 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14534 if (Base->isVirtual()) {
14535 // The complete object may have a lower alignment than the non-virtual
14536 // alignment of the base, in which case the base may be misaligned. Choose
14537 // the smaller of the non-virtual alignment and BaseAlignment, which is a
14538 // conservative lower bound of the complete object alignment.
14539 CharUnits NonVirtualAlignment =
14541 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14542 Offset = CharUnits::Zero();
14543 } else {
14544 const ASTRecordLayout &RL =
14545 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14546 Offset += RL.getBaseClassOffset(BaseDecl);
14547 }
14548 DerivedType = Base->getType();
14549 }
14550
14551 return std::make_pair(BaseAlignment, Offset);
14552}
14553
14554/// Compute the alignment and offset of a binary additive operator.
14555static std::optional<std::pair<CharUnits, CharUnits>>
14557 bool IsSub, ASTContext &Ctx) {
14558 QualType PointeeType = PtrE->getType()->getPointeeType();
14559
14560 if (!PointeeType->isConstantSizeType())
14561 return std::nullopt;
14562
14563 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14564
14565 if (!P)
14566 return std::nullopt;
14567
14568 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14569 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14570 CharUnits Offset = EltSize * IdxRes->getExtValue();
14571 if (IsSub)
14572 Offset = -Offset;
14573 return std::make_pair(P->first, P->second + Offset);
14574 }
14575
14576 // If the integer expression isn't a constant expression, compute the lower
14577 // bound of the alignment using the alignment and offset of the pointer
14578 // expression and the element size.
14579 return std::make_pair(
14580 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14581 CharUnits::Zero());
14582}
14583
14584/// This helper function takes an lvalue expression and returns the alignment of
14585/// a VarDecl and a constant offset from the VarDecl.
14586std::optional<std::pair<
14587 CharUnits,
14589 ASTContext &Ctx) {
14590 E = E->IgnoreParens();
14591 switch (E->getStmtClass()) {
14592 default:
14593 break;
14594 case Stmt::CStyleCastExprClass:
14595 case Stmt::CXXStaticCastExprClass:
14596 case Stmt::ImplicitCastExprClass: {
14597 auto *CE = cast<CastExpr>(E);
14598 const Expr *From = CE->getSubExpr();
14599 switch (CE->getCastKind()) {
14600 default:
14601 break;
14602 case CK_NoOp:
14603 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14604 case CK_UncheckedDerivedToBase:
14605 case CK_DerivedToBase: {
14606 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14607 if (!P)
14608 break;
14609 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14610 P->second, Ctx);
14611 }
14612 }
14613 break;
14614 }
14615 case Stmt::ArraySubscriptExprClass: {
14616 auto *ASE = cast<ArraySubscriptExpr>(E);
14618 false, Ctx);
14619 }
14620 case Stmt::DeclRefExprClass: {
14621 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14622 // FIXME: If VD is captured by copy or is an escaping __block variable,
14623 // use the alignment of VD's type.
14624 if (!VD->getType()->isReferenceType()) {
14625 // Dependent alignment cannot be resolved -> bail out.
14626 if (VD->hasDependentAlignment())
14627 break;
14628 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14629 }
14630 if (VD->hasInit())
14631 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14632 }
14633 break;
14634 }
14635 case Stmt::MemberExprClass: {
14636 auto *ME = cast<MemberExpr>(E);
14637 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14638 if (!FD || FD->getType()->isReferenceType() ||
14639 FD->getParent()->isInvalidDecl())
14640 break;
14641 std::optional<std::pair<CharUnits, CharUnits>> P;
14642 if (ME->isArrow())
14643 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14644 else
14645 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14646 if (!P)
14647 break;
14648 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14649 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14650 return std::make_pair(P->first,
14651 P->second + CharUnits::fromQuantity(Offset));
14652 }
14653 case Stmt::UnaryOperatorClass: {
14654 auto *UO = cast<UnaryOperator>(E);
14655 switch (UO->getOpcode()) {
14656 default:
14657 break;
14658 case UO_Deref:
14660 }
14661 break;
14662 }
14663 case Stmt::BinaryOperatorClass: {
14664 auto *BO = cast<BinaryOperator>(E);
14665 auto Opcode = BO->getOpcode();
14666 switch (Opcode) {
14667 default:
14668 break;
14669 case BO_Comma:
14671 }
14672 break;
14673 }
14674 }
14675 return std::nullopt;
14676}
14677
14678/// This helper function takes a pointer expression and returns the alignment of
14679/// a VarDecl and a constant offset from the VarDecl.
14680std::optional<std::pair<
14682 *E,
14684 &Ctx) {
14685 E = E->IgnoreParens();
14686 switch (E->getStmtClass()) {
14687 default:
14688 break;
14689 case Stmt::CStyleCastExprClass:
14690 case Stmt::CXXStaticCastExprClass:
14691 case Stmt::ImplicitCastExprClass: {
14692 auto *CE = cast<CastExpr>(E);
14693 const Expr *From = CE->getSubExpr();
14694 switch (CE->getCastKind()) {
14695 default:
14696 break;
14697 case CK_NoOp:
14698 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14699 case CK_ArrayToPointerDecay:
14700 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14701 case CK_UncheckedDerivedToBase:
14702 case CK_DerivedToBase: {
14703 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14704 if (!P)
14705 break;
14707 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14708 }
14709 }
14710 break;
14711 }
14712 case Stmt::CXXThisExprClass: {
14713 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14715 return std::make_pair(Alignment, CharUnits::Zero());
14716 }
14717 case Stmt::UnaryOperatorClass: {
14718 auto *UO = cast<UnaryOperator>(E);
14719 if (UO->getOpcode() == UO_AddrOf)
14721 break;
14722 }
14723 case Stmt::BinaryOperatorClass: {
14724 auto *BO = cast<BinaryOperator>(E);
14725 auto Opcode = BO->getOpcode();
14726 switch (Opcode) {
14727 default:
14728 break;
14729 case BO_Add:
14730 case BO_Sub: {
14731 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14732 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14733 std::swap(LHS, RHS);
14734 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14735 Ctx);
14736 }
14737 case BO_Comma:
14738 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14739 }
14740 break;
14741 }
14742 }
14743 return std::nullopt;
14744}
14745
14747 // See if we can compute the alignment of a VarDecl and an offset from it.
14748 std::optional<std::pair<CharUnits, CharUnits>> P =
14750
14751 if (P)
14752 return P->first.alignmentAtOffset(P->second);
14753
14754 // If that failed, return the type's alignment.
14756}
14757
14759 // This is actually a lot of work to potentially be doing on every
14760 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14761 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14762 return;
14763
14764 // Ignore dependent types.
14765 if (T->isDependentType() || Op->getType()->isDependentType())
14766 return;
14767
14768 // Require that the destination be a pointer type.
14769 const PointerType *DestPtr = T->getAs<PointerType>();
14770 if (!DestPtr) return;
14771
14772 // If the destination has alignment 1, we're done.
14773 QualType DestPointee = DestPtr->getPointeeType();
14774 if (DestPointee->isIncompleteType()) return;
14775 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14776 if (DestAlign.isOne()) return;
14777
14778 // Require that the source be a pointer type.
14779 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14780 if (!SrcPtr) return;
14781 QualType SrcPointee = SrcPtr->getPointeeType();
14782
14783 // Explicitly allow casts from cv void*. We already implicitly
14784 // allowed casts to cv void*, since they have alignment 1.
14785 // Also allow casts involving incomplete types, which implicitly
14786 // includes 'void'.
14787 if (SrcPointee->isIncompleteType()) return;
14788
14789 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14790
14791 if (SrcAlign >= DestAlign) return;
14792
14793 Diag(TRange.getBegin(), diag::warn_cast_align)
14794 << Op->getType() << T
14795 << static_cast<unsigned>(SrcAlign.getQuantity())
14796 << static_cast<unsigned>(DestAlign.getQuantity())
14797 << TRange << Op->getSourceRange();
14798}
14799
14800void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14801 const ArraySubscriptExpr *ASE,
14802 bool AllowOnePastEnd, bool IndexNegated) {
14803 // Already diagnosed by the constant evaluator.
14805 return;
14806
14807 IndexExpr = IndexExpr->IgnoreParenImpCasts();
14808 if (IndexExpr->isValueDependent())
14809 return;
14810
14811 const Type *EffectiveType =
14813 BaseExpr = BaseExpr->IgnoreParenCasts();
14814 const ConstantArrayType *ArrayTy =
14815 Context.getAsConstantArrayType(BaseExpr->getType());
14816
14818 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
14819
14820 const Type *BaseType =
14821 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14822 bool IsUnboundedArray =
14823 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
14824 Context, StrictFlexArraysLevel,
14825 /*IgnoreTemplateOrMacroSubstitution=*/true);
14826 if (EffectiveType->isDependentType() ||
14827 (!IsUnboundedArray && BaseType->isDependentType()))
14828 return;
14829
14831 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14832 return;
14833
14834 llvm::APSInt index = Result.Val.getInt();
14835 if (IndexNegated) {
14836 index.setIsUnsigned(false);
14837 index = -index;
14838 }
14839
14840 if (IsUnboundedArray) {
14841 if (EffectiveType->isFunctionType())
14842 return;
14843 if (index.isUnsigned() || !index.isNegative()) {
14844 const auto &ASTC = getASTContext();
14845 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
14846 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
14847 if (index.getBitWidth() < AddrBits)
14848 index = index.zext(AddrBits);
14849 std::optional<CharUnits> ElemCharUnits =
14850 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14851 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14852 // pointer) bounds-checking isn't meaningful.
14853 if (!ElemCharUnits || ElemCharUnits->isZero())
14854 return;
14855 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14856 // If index has more active bits than address space, we already know
14857 // we have a bounds violation to warn about. Otherwise, compute
14858 // address of (index + 1)th element, and warn about bounds violation
14859 // only if that address exceeds address space.
14860 if (index.getActiveBits() <= AddrBits) {
14861 bool Overflow;
14862 llvm::APInt Product(index);
14863 Product += 1;
14864 Product = Product.umul_ov(ElemBytes, Overflow);
14865 if (!Overflow && Product.getActiveBits() <= AddrBits)
14866 return;
14867 }
14868
14869 // Need to compute max possible elements in address space, since that
14870 // is included in diag message.
14871 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14872 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14873 MaxElems += 1;
14874 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14875 MaxElems = MaxElems.udiv(ElemBytes);
14876
14877 unsigned DiagID =
14878 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14879 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14880
14881 // Diag message shows element size in bits and in "bytes" (platform-
14882 // dependent CharUnits)
14883 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14884 PDiag(DiagID)
14885 << toString(index, 10, true) << AddrBits
14886 << (unsigned)ASTC.toBits(*ElemCharUnits)
14887 << toString(ElemBytes, 10, false)
14888 << toString(MaxElems, 10, false)
14889 << (unsigned)MaxElems.getLimitedValue(~0U)
14890 << IndexExpr->getSourceRange());
14891
14892 const NamedDecl *ND = nullptr;
14893 // Try harder to find a NamedDecl to point at in the note.
14894 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14895 BaseExpr = ASE->getBase()->IgnoreParenCasts();
14896 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14897 ND = DRE->getDecl();
14898 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14899 ND = ME->getMemberDecl();
14900
14901 if (ND)
14902 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14903 PDiag(diag::note_array_declared_here) << ND);
14904 }
14905 return;
14906 }
14907
14908 if (index.isUnsigned() || !index.isNegative()) {
14909 // It is possible that the type of the base expression after
14910 // IgnoreParenCasts is incomplete, even though the type of the base
14911 // expression before IgnoreParenCasts is complete (see PR39746 for an
14912 // example). In this case we have no information about whether the array
14913 // access exceeds the array bounds. However we can still diagnose an array
14914 // access which precedes the array bounds.
14915 if (BaseType->isIncompleteType())
14916 return;
14917
14918 llvm::APInt size = ArrayTy->getSize();
14919
14920 if (BaseType != EffectiveType) {
14921 // Make sure we're comparing apples to apples when comparing index to
14922 // size.
14923 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14924 uint64_t array_typesize = Context.getTypeSize(BaseType);
14925
14926 // Handle ptrarith_typesize being zero, such as when casting to void*.
14927 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
14928 if (!ptrarith_typesize)
14929 ptrarith_typesize = Context.getCharWidth();
14930
14931 if (ptrarith_typesize != array_typesize) {
14932 // There's a cast to a different size type involved.
14933 uint64_t ratio = array_typesize / ptrarith_typesize;
14934
14935 // TODO: Be smarter about handling cases where array_typesize is not a
14936 // multiple of ptrarith_typesize.
14937 if (ptrarith_typesize * ratio == array_typesize)
14938 size *= llvm::APInt(size.getBitWidth(), ratio);
14939 }
14940 }
14941
14942 if (size.getBitWidth() > index.getBitWidth())
14943 index = index.zext(size.getBitWidth());
14944 else if (size.getBitWidth() < index.getBitWidth())
14945 size = size.zext(index.getBitWidth());
14946
14947 // For array subscripting the index must be less than size, but for pointer
14948 // arithmetic also allow the index (offset) to be equal to size since
14949 // computing the next address after the end of the array is legal and
14950 // commonly done e.g. in C++ iterators and range-based for loops.
14951 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14952 return;
14953
14954 // Suppress the warning if the subscript expression (as identified by the
14955 // ']' location) and the index expression are both from macro expansions
14956 // within a system header.
14957 if (ASE) {
14958 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14959 ASE->getRBracketLoc());
14960 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14961 SourceLocation IndexLoc =
14962 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14963 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14964 return;
14965 }
14966 }
14967
14968 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
14969 : diag::warn_ptr_arith_exceeds_bounds;
14970 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
14971 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
14972
14974 BaseExpr->getBeginLoc(), BaseExpr,
14975 PDiag(DiagID) << toString(index, 10, true) << ArrayTy->desugar()
14976 << CastMsg << CastMsgTy << IndexExpr->getSourceRange());
14977 } else {
14978 unsigned DiagID = diag::warn_array_index_precedes_bounds;
14979 if (!ASE) {
14980 DiagID = diag::warn_ptr_arith_precedes_bounds;
14981 if (index.isNegative()) index = -index;
14982 }
14983
14984 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14985 PDiag(DiagID) << toString(index, 10, true)
14986 << IndexExpr->getSourceRange());
14987 }
14988
14989 const NamedDecl *ND = nullptr;
14990 // Try harder to find a NamedDecl to point at in the note.
14991 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14992 BaseExpr = ASE->getBase()->IgnoreParenCasts();
14993 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14994 ND = DRE->getDecl();
14995 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14996 ND = ME->getMemberDecl();
14997
14998 if (ND)
14999 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15000 PDiag(diag::note_array_declared_here) << ND);
15001}
15002
15003void Sema::CheckArrayAccess(const Expr *expr) {
15004 int AllowOnePastEnd = 0;
15005 while (expr) {
15006 expr = expr->IgnoreParenImpCasts();
15007 switch (expr->getStmtClass()) {
15008 case Stmt::ArraySubscriptExprClass: {
15009 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15010 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15011 AllowOnePastEnd > 0);
15012 expr = ASE->getBase();
15013 break;
15014 }
15015 case Stmt::MemberExprClass: {
15016 expr = cast<MemberExpr>(expr)->getBase();
15017 break;
15018 }
15019 case Stmt::ArraySectionExprClass: {
15020 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
15021 // FIXME: We should probably be checking all of the elements to the
15022 // 'length' here as well.
15023 if (ASE->getLowerBound())
15024 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15025 /*ASE=*/nullptr, AllowOnePastEnd > 0);
15026 return;
15027 }
15028 case Stmt::UnaryOperatorClass: {
15029 // Only unwrap the * and & unary operators
15030 const UnaryOperator *UO = cast<UnaryOperator>(expr);
15031 expr = UO->getSubExpr();
15032 switch (UO->getOpcode()) {
15033 case UO_AddrOf:
15034 AllowOnePastEnd++;
15035 break;
15036 case UO_Deref:
15037 AllowOnePastEnd--;
15038 break;
15039 default:
15040 return;
15041 }
15042 break;
15043 }
15044 case Stmt::ConditionalOperatorClass: {
15045 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15046 if (const Expr *lhs = cond->getLHS())
15047 CheckArrayAccess(lhs);
15048 if (const Expr *rhs = cond->getRHS())
15049 CheckArrayAccess(rhs);
15050 return;
15051 }
15052 case Stmt::CXXOperatorCallExprClass: {
15053 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15054 for (const auto *Arg : OCE->arguments())
15055 CheckArrayAccess(Arg);
15056 return;
15057 }
15058 default:
15059 return;
15060 }
15061 }
15062}
15063
15065 Expr *RHS, bool isProperty) {
15066 // Check if RHS is an Objective-C object literal, which also can get
15067 // immediately zapped in a weak reference. Note that we explicitly
15068 // allow ObjCStringLiterals, since those are designed to never really die.
15069 RHS = RHS->IgnoreParenImpCasts();
15070
15071 // This enum needs to match with the 'select' in
15072 // warn_objc_arc_literal_assign (off-by-1).
15074 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15075 return false;
15076
15077 S.Diag(Loc, diag::warn_arc_literal_assign)
15078 << (unsigned) Kind
15079 << (isProperty ? 0 : 1)
15080 << RHS->getSourceRange();
15081
15082 return true;
15083}
15084
15087 Expr *RHS, bool isProperty) {
15088 // Strip off any implicit cast added to get to the one ARC-specific.
15089 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15090 if (cast->getCastKind() == CK_ARCConsumeObject) {
15091 S.Diag(Loc, diag::warn_arc_retained_assign)
15093 << (isProperty ? 0 : 1)
15094 << RHS->getSourceRange();
15095 return true;
15096 }
15097 RHS = cast->getSubExpr();
15098 }
15099
15100 if (LT == Qualifiers::OCL_Weak &&
15101 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15102 return true;
15103
15104 return false;
15105}
15106
15108 QualType LHS, Expr *RHS) {
15110
15112 return false;
15113
15114 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15115 return true;
15116
15117 return false;
15118}
15119
15121 Expr *LHS, Expr *RHS) {
15122 QualType LHSType;
15123 // PropertyRef on LHS type need be directly obtained from
15124 // its declaration as it has a PseudoType.
15126 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15127 if (PRE && !PRE->isImplicitProperty()) {
15128 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15129 if (PD)
15130 LHSType = PD->getType();
15131 }
15132
15133 if (LHSType.isNull())
15134 LHSType = LHS->getType();
15135
15137
15138 if (LT == Qualifiers::OCL_Weak) {
15139 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15141 }
15142
15143 if (checkUnsafeAssigns(Loc, LHSType, RHS))
15144 return;
15145
15146 // FIXME. Check for other life times.
15147 if (LT != Qualifiers::OCL_None)
15148 return;
15149
15150 if (PRE) {
15151 if (PRE->isImplicitProperty())
15152 return;
15153 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15154 if (!PD)
15155 return;
15156
15157 unsigned Attributes = PD->getPropertyAttributes();
15158 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15159 // when 'assign' attribute was not explicitly specified
15160 // by user, ignore it and rely on property type itself
15161 // for lifetime info.
15162 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15163 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15164 LHSType->isObjCRetainableType())
15165 return;
15166
15167 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15168 if (cast->getCastKind() == CK_ARCConsumeObject) {
15169 Diag(Loc, diag::warn_arc_retained_property_assign)
15170 << RHS->getSourceRange();
15171 return;
15172 }
15173 RHS = cast->getSubExpr();
15174 }
15175 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15176 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15177 return;
15178 }
15179 }
15180}
15181
15182//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15183
15184static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15185 SourceLocation StmtLoc,
15186 const NullStmt *Body) {
15187 // Do not warn if the body is a macro that expands to nothing, e.g:
15188 //
15189 // #define CALL(x)
15190 // if (condition)
15191 // CALL(0);
15192 if (Body->hasLeadingEmptyMacro())
15193 return false;
15194
15195 // Get line numbers of statement and body.
15196 bool StmtLineInvalid;
15197 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15198 &StmtLineInvalid);
15199 if (StmtLineInvalid)
15200 return false;
15201
15202 bool BodyLineInvalid;
15203 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15204 &BodyLineInvalid);
15205 if (BodyLineInvalid)
15206 return false;
15207
15208 // Warn if null statement and body are on the same line.
15209 if (StmtLine != BodyLine)
15210 return false;
15211
15212 return true;
15213}
15214
15216 const Stmt *Body,
15217 unsigned DiagID) {
15218 // Since this is a syntactic check, don't emit diagnostic for template
15219 // instantiations, this just adds noise.
15221 return;
15222
15223 // The body should be a null statement.
15224 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15225 if (!NBody)
15226 return;
15227
15228 // Do the usual checks.
15229 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15230 return;
15231
15232 Diag(NBody->getSemiLoc(), DiagID);
15233 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15234}
15235
15237 const Stmt *PossibleBody) {
15238 assert(!CurrentInstantiationScope); // Ensured by caller
15239
15240 SourceLocation StmtLoc;
15241 const Stmt *Body;
15242 unsigned DiagID;
15243 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15244 StmtLoc = FS->getRParenLoc();
15245 Body = FS->getBody();
15246 DiagID = diag::warn_empty_for_body;
15247 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15248 StmtLoc = WS->getRParenLoc();
15249 Body = WS->getBody();
15250 DiagID = diag::warn_empty_while_body;
15251 } else
15252 return; // Neither `for' nor `while'.
15253
15254 // The body should be a null statement.
15255 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15256 if (!NBody)
15257 return;
15258
15259 // Skip expensive checks if diagnostic is disabled.
15260 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15261 return;
15262
15263 // Do the usual checks.
15264 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15265 return;
15266
15267 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15268 // noise level low, emit diagnostics only if for/while is followed by a
15269 // CompoundStmt, e.g.:
15270 // for (int i = 0; i < n; i++);
15271 // {
15272 // a(i);
15273 // }
15274 // or if for/while is followed by a statement with more indentation
15275 // than for/while itself:
15276 // for (int i = 0; i < n; i++);
15277 // a(i);
15278 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15279 if (!ProbableTypo) {
15280 bool BodyColInvalid;
15281 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15282 PossibleBody->getBeginLoc(), &BodyColInvalid);
15283 if (BodyColInvalid)
15284 return;
15285
15286 bool StmtColInvalid;
15287 unsigned StmtCol =
15288 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15289 if (StmtColInvalid)
15290 return;
15291
15292 if (BodyCol > StmtCol)
15293 ProbableTypo = true;
15294 }
15295
15296 if (ProbableTypo) {
15297 Diag(NBody->getSemiLoc(), DiagID);
15298 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15299 }
15300}
15301
15302//===--- CHECK: Warn on self move with std::move. -------------------------===//
15303
15304void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15305 SourceLocation OpLoc) {
15306 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15307 return;
15308
15310 return;
15311
15312 // Strip parens and casts away.
15313 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15314 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15315
15316 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15317 // which we can treat as an inlined std::move
15318 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
15319 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15320 RHSExpr = CE->getArg(0);
15321 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
15322 CXXSCE && CXXSCE->isXValue())
15323 RHSExpr = CXXSCE->getSubExpr();
15324 else
15325 return;
15326
15327 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15328 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15329
15330 // Two DeclRefExpr's, check that the decls are the same.
15331 if (LHSDeclRef && RHSDeclRef) {
15332 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15333 return;
15334 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15335 RHSDeclRef->getDecl()->getCanonicalDecl())
15336 return;
15337
15338 auto D = Diag(OpLoc, diag::warn_self_move)
15339 << LHSExpr->getType() << LHSExpr->getSourceRange()
15340 << RHSExpr->getSourceRange();
15341 if (const FieldDecl *F =
15343 D << 1 << F
15344 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15345 else
15346 D << 0;
15347 return;
15348 }
15349
15350 // Member variables require a different approach to check for self moves.
15351 // MemberExpr's are the same if every nested MemberExpr refers to the same
15352 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15353 // the base Expr's are CXXThisExpr's.
15354 const Expr *LHSBase = LHSExpr;
15355 const Expr *RHSBase = RHSExpr;
15356 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15357 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15358 if (!LHSME || !RHSME)
15359 return;
15360
15361 while (LHSME && RHSME) {
15362 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15363 RHSME->getMemberDecl()->getCanonicalDecl())
15364 return;
15365
15366 LHSBase = LHSME->getBase();
15367 RHSBase = RHSME->getBase();
15368 LHSME = dyn_cast<MemberExpr>(LHSBase);
15369 RHSME = dyn_cast<MemberExpr>(RHSBase);
15370 }
15371
15372 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15373 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15374 if (LHSDeclRef && RHSDeclRef) {
15375 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15376 return;
15377 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15378 RHSDeclRef->getDecl()->getCanonicalDecl())
15379 return;
15380
15381 Diag(OpLoc, diag::warn_self_move)
15382 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15383 << RHSExpr->getSourceRange();
15384 return;
15385 }
15386
15387 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15388 Diag(OpLoc, diag::warn_self_move)
15389 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15390 << RHSExpr->getSourceRange();
15391}
15392
15393//===--- Layout compatibility ----------------------------------------------//
15394
15395static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
15396
15397/// Check if two enumeration types are layout-compatible.
15398static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
15399 const EnumDecl *ED2) {
15400 // C++11 [dcl.enum] p8:
15401 // Two enumeration types are layout-compatible if they have the same
15402 // underlying type.
15403 return ED1->isComplete() && ED2->isComplete() &&
15404 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15405}
15406
15407/// Check if two fields are layout-compatible.
15408/// Can be used on union members, which are exempt from alignment requirement
15409/// of common initial sequence.
15410static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
15411 const FieldDecl *Field2,
15412 bool AreUnionMembers = false) {
15413#ifndef NDEBUG
15414 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
15415 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
15416 assert(((Field1Parent->isStructureOrClassType() &&
15417 Field2Parent->isStructureOrClassType()) ||
15418 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
15419 "Can't evaluate layout compatibility between a struct field and a "
15420 "union field.");
15421 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
15422 (AreUnionMembers && Field1Parent->isUnionType())) &&
15423 "AreUnionMembers should be 'true' for union fields (only).");
15424#endif
15425
15426 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15427 return false;
15428
15429 if (Field1->isBitField() != Field2->isBitField())
15430 return false;
15431
15432 if (Field1->isBitField()) {
15433 // Make sure that the bit-fields are the same length.
15434 unsigned Bits1 = Field1->getBitWidthValue();
15435 unsigned Bits2 = Field2->getBitWidthValue();
15436
15437 if (Bits1 != Bits2)
15438 return false;
15439 }
15440
15441 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
15442 Field2->hasAttr<clang::NoUniqueAddressAttr>())
15443 return false;
15444
15445 if (!AreUnionMembers &&
15446 Field1->getMaxAlignment() != Field2->getMaxAlignment())
15447 return false;
15448
15449 return true;
15450}
15451
15452/// Check if two standard-layout structs are layout-compatible.
15453/// (C++11 [class.mem] p17)
15454static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
15455 const RecordDecl *RD2) {
15456 // Get to the class where the fields are declared
15457 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
15458 RD1 = D1CXX->getStandardLayoutBaseWithFields();
15459
15460 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
15461 RD2 = D2CXX->getStandardLayoutBaseWithFields();
15462
15463 // Check the fields.
15464 return llvm::equal(RD1->fields(), RD2->fields(),
15465 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
15466 return isLayoutCompatible(C, F1, F2);
15467 });
15468}
15469
15470/// Check if two standard-layout unions are layout-compatible.
15471/// (C++11 [class.mem] p18)
15472static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
15473 const RecordDecl *RD2) {
15474 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
15475 RD2->fields());
15476
15477 for (auto *Field1 : RD1->fields()) {
15478 auto I = UnmatchedFields.begin();
15479 auto E = UnmatchedFields.end();
15480
15481 for ( ; I != E; ++I) {
15482 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) {
15483 bool Result = UnmatchedFields.erase(*I);
15484 (void) Result;
15485 assert(Result);
15486 break;
15487 }
15488 }
15489 if (I == E)
15490 return false;
15491 }
15492
15493 return UnmatchedFields.empty();
15494}
15495
15496static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
15497 const RecordDecl *RD2) {
15498 if (RD1->isUnion() != RD2->isUnion())
15499 return false;
15500
15501 if (RD1->isUnion())
15502 return isLayoutCompatibleUnion(C, RD1, RD2);
15503 else
15504 return isLayoutCompatibleStruct(C, RD1, RD2);
15505}
15506
15507/// Check if two types are layout-compatible in C++11 sense.
15508static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
15509 if (T1.isNull() || T2.isNull())
15510 return false;
15511
15512 // C++20 [basic.types] p11:
15513 // Two types cv1 T1 and cv2 T2 are layout-compatible types
15514 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
15515 // or layout-compatible standard-layout class types (11.4).
15518
15519 if (C.hasSameType(T1, T2))
15520 return true;
15521
15522 const Type::TypeClass TC1 = T1->getTypeClass();
15523 const Type::TypeClass TC2 = T2->getTypeClass();
15524
15525 if (TC1 != TC2)
15526 return false;
15527
15528 if (TC1 == Type::Enum)
15529 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
15530 if (TC1 == Type::Record) {
15531 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15532 return false;
15533
15535 T2->castAsRecordDecl());
15536 }
15537
15538 return false;
15539}
15540
15542 return isLayoutCompatible(getASTContext(), T1, T2);
15543}
15544
15545//===-------------- Pointer interconvertibility ----------------------------//
15546
15548 const TypeSourceInfo *Derived) {
15549 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
15550 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
15551
15552 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
15553 getASTContext().hasSameType(BaseT, DerivedT))
15554 return true;
15555
15556 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
15557 return false;
15558
15559 // Per [basic.compound]/4.3, containing object has to be standard-layout.
15560 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
15561 return true;
15562
15563 return false;
15564}
15565
15566//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15567
15568/// Given a type tag expression find the type tag itself.
15569///
15570/// \param TypeExpr Type tag expression, as it appears in user's code.
15571///
15572/// \param VD Declaration of an identifier that appears in a type tag.
15573///
15574/// \param MagicValue Type tag magic value.
15575///
15576/// \param isConstantEvaluated whether the evalaution should be performed in
15577
15578/// constant context.
15579static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15580 const ValueDecl **VD, uint64_t *MagicValue,
15581 bool isConstantEvaluated) {
15582 while(true) {
15583 if (!TypeExpr)
15584 return false;
15585
15586 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15587
15588 switch (TypeExpr->getStmtClass()) {
15589 case Stmt::UnaryOperatorClass: {
15590 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15591 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15592 TypeExpr = UO->getSubExpr();
15593 continue;
15594 }
15595 return false;
15596 }
15597
15598 case Stmt::DeclRefExprClass: {
15599 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15600 *VD = DRE->getDecl();
15601 return true;
15602 }
15603
15604 case Stmt::IntegerLiteralClass: {
15605 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15606 llvm::APInt MagicValueAPInt = IL->getValue();
15607 if (MagicValueAPInt.getActiveBits() <= 64) {
15608 *MagicValue = MagicValueAPInt.getZExtValue();
15609 return true;
15610 } else
15611 return false;
15612 }
15613
15614 case Stmt::BinaryConditionalOperatorClass:
15615 case Stmt::ConditionalOperatorClass: {
15616 const AbstractConditionalOperator *ACO =
15618 bool Result;
15619 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15620 isConstantEvaluated)) {
15621 if (Result)
15622 TypeExpr = ACO->getTrueExpr();
15623 else
15624 TypeExpr = ACO->getFalseExpr();
15625 continue;
15626 }
15627 return false;
15628 }
15629
15630 case Stmt::BinaryOperatorClass: {
15631 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15632 if (BO->getOpcode() == BO_Comma) {
15633 TypeExpr = BO->getRHS();
15634 continue;
15635 }
15636 return false;
15637 }
15638
15639 default:
15640 return false;
15641 }
15642 }
15643}
15644
15645/// Retrieve the C type corresponding to type tag TypeExpr.
15646///
15647/// \param TypeExpr Expression that specifies a type tag.
15648///
15649/// \param MagicValues Registered magic values.
15650///
15651/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15652/// kind.
15653///
15654/// \param TypeInfo Information about the corresponding C type.
15655///
15656/// \param isConstantEvaluated whether the evalaution should be performed in
15657/// constant context.
15658///
15659/// \returns true if the corresponding C type was found.
15661 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15662 const ASTContext &Ctx,
15663 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15664 *MagicValues,
15665 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15666 bool isConstantEvaluated) {
15667 FoundWrongKind = false;
15668
15669 // Variable declaration that has type_tag_for_datatype attribute.
15670 const ValueDecl *VD = nullptr;
15671
15672 uint64_t MagicValue;
15673
15674 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15675 return false;
15676
15677 if (VD) {
15678 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15679 if (I->getArgumentKind() != ArgumentKind) {
15680 FoundWrongKind = true;
15681 return false;
15682 }
15683 TypeInfo.Type = I->getMatchingCType();
15684 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15685 TypeInfo.MustBeNull = I->getMustBeNull();
15686 return true;
15687 }
15688 return false;
15689 }
15690
15691 if (!MagicValues)
15692 return false;
15693
15694 llvm::DenseMap<Sema::TypeTagMagicValue,
15696 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15697 if (I == MagicValues->end())
15698 return false;
15699
15700 TypeInfo = I->second;
15701 return true;
15702}
15703
15705 uint64_t MagicValue, QualType Type,
15706 bool LayoutCompatible,
15707 bool MustBeNull) {
15708 if (!TypeTagForDatatypeMagicValues)
15709 TypeTagForDatatypeMagicValues.reset(
15710 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15711
15712 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15713 (*TypeTagForDatatypeMagicValues)[Magic] =
15714 TypeTagData(Type, LayoutCompatible, MustBeNull);
15715}
15716
15717static bool IsSameCharType(QualType T1, QualType T2) {
15718 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15719 if (!BT1)
15720 return false;
15721
15722 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15723 if (!BT2)
15724 return false;
15725
15726 BuiltinType::Kind T1Kind = BT1->getKind();
15727 BuiltinType::Kind T2Kind = BT2->getKind();
15728
15729 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
15730 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
15731 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15732 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15733}
15734
15735void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15736 const ArrayRef<const Expr *> ExprArgs,
15737 SourceLocation CallSiteLoc) {
15738 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15739 bool IsPointerAttr = Attr->getIsPointer();
15740
15741 // Retrieve the argument representing the 'type_tag'.
15742 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15743 if (TypeTagIdxAST >= ExprArgs.size()) {
15744 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15745 << 0 << Attr->getTypeTagIdx().getSourceIndex();
15746 return;
15747 }
15748 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15749 bool FoundWrongKind;
15750 TypeTagData TypeInfo;
15751 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15752 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15753 TypeInfo, isConstantEvaluatedContext())) {
15754 if (FoundWrongKind)
15755 Diag(TypeTagExpr->getExprLoc(),
15756 diag::warn_type_tag_for_datatype_wrong_kind)
15757 << TypeTagExpr->getSourceRange();
15758 return;
15759 }
15760
15761 // Retrieve the argument representing the 'arg_idx'.
15762 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15763 if (ArgumentIdxAST >= ExprArgs.size()) {
15764 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15765 << 1 << Attr->getArgumentIdx().getSourceIndex();
15766 return;
15767 }
15768 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15769 if (IsPointerAttr) {
15770 // Skip implicit cast of pointer to `void *' (as a function argument).
15771 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15772 if (ICE->getType()->isVoidPointerType() &&
15773 ICE->getCastKind() == CK_BitCast)
15774 ArgumentExpr = ICE->getSubExpr();
15775 }
15776 QualType ArgumentType = ArgumentExpr->getType();
15777
15778 // Passing a `void*' pointer shouldn't trigger a warning.
15779 if (IsPointerAttr && ArgumentType->isVoidPointerType())
15780 return;
15781
15782 if (TypeInfo.MustBeNull) {
15783 // Type tag with matching void type requires a null pointer.
15784 if (!ArgumentExpr->isNullPointerConstant(Context,
15786 Diag(ArgumentExpr->getExprLoc(),
15787 diag::warn_type_safety_null_pointer_required)
15788 << ArgumentKind->getName()
15789 << ArgumentExpr->getSourceRange()
15790 << TypeTagExpr->getSourceRange();
15791 }
15792 return;
15793 }
15794
15795 QualType RequiredType = TypeInfo.Type;
15796 if (IsPointerAttr)
15797 RequiredType = Context.getPointerType(RequiredType);
15798
15799 bool mismatch = false;
15800 if (!TypeInfo.LayoutCompatible) {
15801 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15802
15803 // C++11 [basic.fundamental] p1:
15804 // Plain char, signed char, and unsigned char are three distinct types.
15805 //
15806 // But we treat plain `char' as equivalent to `signed char' or `unsigned
15807 // char' depending on the current char signedness mode.
15808 if (mismatch)
15809 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15810 RequiredType->getPointeeType())) ||
15811 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15812 mismatch = false;
15813 } else
15814 if (IsPointerAttr)
15815 mismatch = !isLayoutCompatible(Context,
15816 ArgumentType->getPointeeType(),
15817 RequiredType->getPointeeType());
15818 else
15819 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15820
15821 if (mismatch)
15822 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15823 << ArgumentType << ArgumentKind
15824 << TypeInfo.LayoutCompatible << RequiredType
15825 << ArgumentExpr->getSourceRange()
15826 << TypeTagExpr->getSourceRange();
15827}
15828
15829void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15830 CharUnits Alignment) {
15831 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
15832 Alignment);
15833}
15834
15836 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
15837 const NamedDecl *ND = m.RD;
15838 if (ND->getName().empty()) {
15839 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15840 ND = TD;
15841 }
15842 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15843 << m.MD << ND << m.E->getSourceRange();
15844 }
15846}
15847
15849 E = E->IgnoreParens();
15850 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
15851 return;
15852 if (isa<UnaryOperator>(E) &&
15853 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15854 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15855 if (isa<MemberExpr>(Op)) {
15856 auto &MisalignedMembersForExpr =
15858 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
15859 if (MA != MisalignedMembersForExpr.end() &&
15860 (T->isDependentType() || T->isIntegerType() ||
15861 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15862 Context.getTypeAlignInChars(
15863 T->getPointeeType()) <= MA->Alignment))))
15864 MisalignedMembersForExpr.erase(MA);
15865 }
15866 }
15867}
15868
15870 Expr *E,
15871 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15872 Action) {
15873 const auto *ME = dyn_cast<MemberExpr>(E);
15874 if (!ME)
15875 return;
15876
15877 // No need to check expressions with an __unaligned-qualified type.
15878 if (E->getType().getQualifiers().hasUnaligned())
15879 return;
15880
15881 // For a chain of MemberExpr like "a.b.c.d" this list
15882 // will keep FieldDecl's like [d, c, b].
15883 SmallVector<FieldDecl *, 4> ReverseMemberChain;
15884 const MemberExpr *TopME = nullptr;
15885 bool AnyIsPacked = false;
15886 do {
15887 QualType BaseType = ME->getBase()->getType();
15888 if (BaseType->isDependentType())
15889 return;
15890 if (ME->isArrow())
15891 BaseType = BaseType->getPointeeType();
15892 auto *RD = BaseType->castAsRecordDecl();
15893 if (RD->isInvalidDecl())
15894 return;
15895
15896 ValueDecl *MD = ME->getMemberDecl();
15897 auto *FD = dyn_cast<FieldDecl>(MD);
15898 // We do not care about non-data members.
15899 if (!FD || FD->isInvalidDecl())
15900 return;
15901
15902 AnyIsPacked =
15903 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15904 ReverseMemberChain.push_back(FD);
15905
15906 TopME = ME;
15907 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15908 } while (ME);
15909 assert(TopME && "We did not compute a topmost MemberExpr!");
15910
15911 // Not the scope of this diagnostic.
15912 if (!AnyIsPacked)
15913 return;
15914
15915 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15916 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15917 // TODO: The innermost base of the member expression may be too complicated.
15918 // For now, just disregard these cases. This is left for future
15919 // improvement.
15920 if (!DRE && !isa<CXXThisExpr>(TopBase))
15921 return;
15922
15923 // Alignment expected by the whole expression.
15924 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15925
15926 // No need to do anything else with this case.
15927 if (ExpectedAlignment.isOne())
15928 return;
15929
15930 // Synthesize offset of the whole access.
15931 CharUnits Offset;
15932 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
15933 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
15934
15935 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15936 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15937 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
15938
15939 // The base expression of the innermost MemberExpr may give
15940 // stronger guarantees than the class containing the member.
15941 if (DRE && !TopME->isArrow()) {
15942 const ValueDecl *VD = DRE->getDecl();
15943 if (!VD->getType()->isReferenceType())
15944 CompleteObjectAlignment =
15945 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15946 }
15947
15948 // Check if the synthesized offset fulfills the alignment.
15949 if (Offset % ExpectedAlignment != 0 ||
15950 // It may fulfill the offset it but the effective alignment may still be
15951 // lower than the expected expression alignment.
15952 CompleteObjectAlignment < ExpectedAlignment) {
15953 // If this happens, we want to determine a sensible culprit of this.
15954 // Intuitively, watching the chain of member expressions from right to
15955 // left, we start with the required alignment (as required by the field
15956 // type) but some packed attribute in that chain has reduced the alignment.
15957 // It may happen that another packed structure increases it again. But if
15958 // we are here such increase has not been enough. So pointing the first
15959 // FieldDecl that either is packed or else its RecordDecl is,
15960 // seems reasonable.
15961 FieldDecl *FD = nullptr;
15962 CharUnits Alignment;
15963 for (FieldDecl *FDI : ReverseMemberChain) {
15964 if (FDI->hasAttr<PackedAttr>() ||
15965 FDI->getParent()->hasAttr<PackedAttr>()) {
15966 FD = FDI;
15967 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
15968 Context.getTypeAlignInChars(
15969 Context.getCanonicalTagType(FD->getParent())));
15970 break;
15971 }
15972 }
15973 assert(FD && "We did not find a packed FieldDecl!");
15974 Action(E, FD->getParent(), FD, Alignment);
15975 }
15976}
15977
15978void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15979 using namespace std::placeholders;
15980
15982 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15983 _2, _3, _4));
15984}
15985
15986// Performs a similar job to Sema::UsualUnaryConversions, but without any
15987// implicit promotion of integral/enumeration types.
15989 // First, convert to an r-value.
15991 if (Res.isInvalid())
15992 return ExprError();
15993
15994 // Promote floating-point types.
15995 return S.UsualUnaryFPConversions(Res.get());
15996}
15997
15999 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16000 if (checkArgCount(TheCall, 1))
16001 return true;
16002
16003 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
16004 if (A.isInvalid())
16005 return true;
16006
16007 TheCall->setArg(0, A.get());
16008 QualType TyA = A.get()->getType();
16009
16010 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
16011 ArgTyRestr, 1))
16012 return true;
16013
16014 TheCall->setType(TyA);
16015 return false;
16016}
16017
16018bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16019 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16020 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16021 TheCall->setType(*Res);
16022 return false;
16023 }
16024 return true;
16025}
16026
16028 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16029 if (!Res)
16030 return true;
16031
16032 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16033 TheCall->setType(VecTy0->getElementType());
16034 else
16035 TheCall->setType(*Res);
16036
16037 return false;
16038}
16039
16041 SourceLocation Loc) {
16043 R = RHS->getEnumCoercedType(S.Context);
16044 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16046 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
16047 << LHS->getSourceRange() << RHS->getSourceRange()
16048 << /*Arithmetic Between*/ 0 << L << R;
16049 }
16050 return false;
16051}
16052
16053/// Check if all arguments have the same type. If the types don't match, emit an
16054/// error message and return true. Otherwise return false.
16055///
16056/// For scalars we directly compare their unqualified types. But even if we
16057/// compare unqualified vector types, a difference in qualifiers in the element
16058/// types can make the vector types be considered not equal. For example,
16059/// vector of 4 'const float' values vs vector of 4 'float' values.
16060/// So we compare unqualified types of their elements and number of elements.
16062 ArrayRef<Expr *> Args) {
16063 assert(!Args.empty() && "Should have at least one argument.");
16064
16065 Expr *Arg0 = Args.front();
16066 QualType Ty0 = Arg0->getType();
16067
16068 auto EmitError = [&](Expr *ArgI) {
16069 SemaRef.Diag(Arg0->getBeginLoc(),
16070 diag::err_typecheck_call_different_arg_types)
16071 << Arg0->getType() << ArgI->getType();
16072 };
16073
16074 // Compare scalar types.
16075 if (!Ty0->isVectorType()) {
16076 for (Expr *ArgI : Args.drop_front())
16077 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
16078 EmitError(ArgI);
16079 return true;
16080 }
16081
16082 return false;
16083 }
16084
16085 // Compare vector types.
16086 const auto *Vec0 = Ty0->castAs<VectorType>();
16087 for (Expr *ArgI : Args.drop_front()) {
16088 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16089 if (!VecI ||
16090 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
16091 VecI->getElementType()) ||
16092 Vec0->getNumElements() != VecI->getNumElements()) {
16093 EmitError(ArgI);
16094 return true;
16095 }
16096 }
16097
16098 return false;
16099}
16100
16101std::optional<QualType>
16103 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16104 if (checkArgCount(TheCall, 2))
16105 return std::nullopt;
16106
16108 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
16109 return std::nullopt;
16110
16111 Expr *Args[2];
16112 for (int I = 0; I < 2; ++I) {
16113 ExprResult Converted =
16114 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16115 if (Converted.isInvalid())
16116 return std::nullopt;
16117 Args[I] = Converted.get();
16118 }
16119
16120 SourceLocation LocA = Args[0]->getBeginLoc();
16121 QualType TyA = Args[0]->getType();
16122
16123 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
16124 return std::nullopt;
16125
16126 if (checkBuiltinVectorMathArgTypes(*this, Args))
16127 return std::nullopt;
16128
16129 TheCall->setArg(0, Args[0]);
16130 TheCall->setArg(1, Args[1]);
16131 return TyA;
16132}
16133
16135 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16136 if (checkArgCount(TheCall, 3))
16137 return true;
16138
16139 SourceLocation Loc = TheCall->getExprLoc();
16140 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
16141 TheCall->getArg(1), Loc) ||
16142 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
16143 TheCall->getArg(2), Loc))
16144 return true;
16145
16146 Expr *Args[3];
16147 for (int I = 0; I < 3; ++I) {
16148 ExprResult Converted =
16149 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
16150 if (Converted.isInvalid())
16151 return true;
16152 Args[I] = Converted.get();
16153 }
16154
16155 int ArgOrdinal = 1;
16156 for (Expr *Arg : Args) {
16157 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
16158 ArgTyRestr, ArgOrdinal++))
16159 return true;
16160 }
16161
16162 if (checkBuiltinVectorMathArgTypes(*this, Args))
16163 return true;
16164
16165 for (int I = 0; I < 3; ++I)
16166 TheCall->setArg(I, Args[I]);
16167
16168 TheCall->setType(Args[0]->getType());
16169 return false;
16170}
16171
16172bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16173 if (checkArgCount(TheCall, 1))
16174 return true;
16175
16176 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16177 if (A.isInvalid())
16178 return true;
16179
16180 TheCall->setArg(0, A.get());
16181 return false;
16182}
16183
16184bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16185 if (checkArgCount(TheCall, 1))
16186 return true;
16187
16188 ExprResult Arg = TheCall->getArg(0);
16189 QualType TyArg = Arg.get()->getType();
16190
16191 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16192 return Diag(TheCall->getArg(0)->getBeginLoc(),
16193 diag::err_builtin_invalid_arg_type)
16194 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16195
16196 TheCall->setType(TyArg);
16197 return false;
16198}
16199
16200ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16201 ExprResult CallResult) {
16202 if (checkArgCount(TheCall, 1))
16203 return ExprError();
16204
16205 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16206 if (MatrixArg.isInvalid())
16207 return MatrixArg;
16208 Expr *Matrix = MatrixArg.get();
16209
16210 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16211 if (!MType) {
16212 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16213 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16214 << Matrix->getType();
16215 return ExprError();
16216 }
16217
16218 // Create returned matrix type by swapping rows and columns of the argument
16219 // matrix type.
16220 QualType ResultType = Context.getConstantMatrixType(
16221 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16222
16223 // Change the return type to the type of the returned matrix.
16224 TheCall->setType(ResultType);
16225
16226 // Update call argument to use the possibly converted matrix argument.
16227 TheCall->setArg(0, Matrix);
16228 return CallResult;
16229}
16230
16231// Get and verify the matrix dimensions.
16232static std::optional<unsigned>
16234 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
16235 if (!Value) {
16236 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16237 << Name;
16238 return {};
16239 }
16240 uint64_t Dim = Value->getZExtValue();
16242 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16244 return {};
16245 }
16246 return Dim;
16247}
16248
16249ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16250 ExprResult CallResult) {
16251 if (!getLangOpts().MatrixTypes) {
16252 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16253 return ExprError();
16254 }
16255
16256 if (checkArgCount(TheCall, 4))
16257 return ExprError();
16258
16259 unsigned PtrArgIdx = 0;
16260 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16261 Expr *RowsExpr = TheCall->getArg(1);
16262 Expr *ColumnsExpr = TheCall->getArg(2);
16263 Expr *StrideExpr = TheCall->getArg(3);
16264
16265 bool ArgError = false;
16266
16267 // Check pointer argument.
16268 {
16270 if (PtrConv.isInvalid())
16271 return PtrConv;
16272 PtrExpr = PtrConv.get();
16273 TheCall->setArg(0, PtrExpr);
16274 if (PtrExpr->isTypeDependent()) {
16275 TheCall->setType(Context.DependentTy);
16276 return TheCall;
16277 }
16278 }
16279
16280 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16281 QualType ElementTy;
16282 if (!PtrTy) {
16283 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16284 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16285 << PtrExpr->getType();
16286 ArgError = true;
16287 } else {
16288 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16289
16291 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16292 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16293 << /* no fp */ 0 << PtrExpr->getType();
16294 ArgError = true;
16295 }
16296 }
16297
16298 // Apply default Lvalue conversions and convert the expression to size_t.
16299 auto ApplyArgumentConversions = [this](Expr *E) {
16301 if (Conv.isInvalid())
16302 return Conv;
16303
16304 return tryConvertExprToType(Conv.get(), Context.getSizeType());
16305 };
16306
16307 // Apply conversion to row and column expressions.
16308 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16309 if (!RowsConv.isInvalid()) {
16310 RowsExpr = RowsConv.get();
16311 TheCall->setArg(1, RowsExpr);
16312 } else
16313 RowsExpr = nullptr;
16314
16315 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16316 if (!ColumnsConv.isInvalid()) {
16317 ColumnsExpr = ColumnsConv.get();
16318 TheCall->setArg(2, ColumnsExpr);
16319 } else
16320 ColumnsExpr = nullptr;
16321
16322 // If any part of the result matrix type is still pending, just use
16323 // Context.DependentTy, until all parts are resolved.
16324 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16325 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16326 TheCall->setType(Context.DependentTy);
16327 return CallResult;
16328 }
16329
16330 // Check row and column dimensions.
16331 std::optional<unsigned> MaybeRows;
16332 if (RowsExpr)
16333 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16334
16335 std::optional<unsigned> MaybeColumns;
16336 if (ColumnsExpr)
16337 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16338
16339 // Check stride argument.
16340 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16341 if (StrideConv.isInvalid())
16342 return ExprError();
16343 StrideExpr = StrideConv.get();
16344 TheCall->setArg(3, StrideExpr);
16345
16346 if (MaybeRows) {
16347 if (std::optional<llvm::APSInt> Value =
16348 StrideExpr->getIntegerConstantExpr(Context)) {
16349 uint64_t Stride = Value->getZExtValue();
16350 if (Stride < *MaybeRows) {
16351 Diag(StrideExpr->getBeginLoc(),
16352 diag::err_builtin_matrix_stride_too_small);
16353 ArgError = true;
16354 }
16355 }
16356 }
16357
16358 if (ArgError || !MaybeRows || !MaybeColumns)
16359 return ExprError();
16360
16361 TheCall->setType(
16362 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16363 return CallResult;
16364}
16365
16366ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16367 ExprResult CallResult) {
16368 if (checkArgCount(TheCall, 3))
16369 return ExprError();
16370
16371 unsigned PtrArgIdx = 1;
16372 Expr *MatrixExpr = TheCall->getArg(0);
16373 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16374 Expr *StrideExpr = TheCall->getArg(2);
16375
16376 bool ArgError = false;
16377
16378 {
16379 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16380 if (MatrixConv.isInvalid())
16381 return MatrixConv;
16382 MatrixExpr = MatrixConv.get();
16383 TheCall->setArg(0, MatrixExpr);
16384 }
16385 if (MatrixExpr->isTypeDependent()) {
16386 TheCall->setType(Context.DependentTy);
16387 return TheCall;
16388 }
16389
16390 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16391 if (!MatrixTy) {
16392 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16393 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
16394 ArgError = true;
16395 }
16396
16397 {
16399 if (PtrConv.isInvalid())
16400 return PtrConv;
16401 PtrExpr = PtrConv.get();
16402 TheCall->setArg(1, PtrExpr);
16403 if (PtrExpr->isTypeDependent()) {
16404 TheCall->setType(Context.DependentTy);
16405 return TheCall;
16406 }
16407 }
16408
16409 // Check pointer argument.
16410 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16411 if (!PtrTy) {
16412 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16413 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
16414 << PtrExpr->getType();
16415 ArgError = true;
16416 } else {
16417 QualType ElementTy = PtrTy->getPointeeType();
16418 if (ElementTy.isConstQualified()) {
16419 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16420 ArgError = true;
16421 }
16422 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16423 if (MatrixTy &&
16424 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16425 Diag(PtrExpr->getBeginLoc(),
16426 diag::err_builtin_matrix_pointer_arg_mismatch)
16427 << ElementTy << MatrixTy->getElementType();
16428 ArgError = true;
16429 }
16430 }
16431
16432 // Apply default Lvalue conversions and convert the stride expression to
16433 // size_t.
16434 {
16435 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16436 if (StrideConv.isInvalid())
16437 return StrideConv;
16438
16439 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16440 if (StrideConv.isInvalid())
16441 return StrideConv;
16442 StrideExpr = StrideConv.get();
16443 TheCall->setArg(2, StrideExpr);
16444 }
16445
16446 // Check stride argument.
16447 if (MatrixTy) {
16448 if (std::optional<llvm::APSInt> Value =
16449 StrideExpr->getIntegerConstantExpr(Context)) {
16450 uint64_t Stride = Value->getZExtValue();
16451 if (Stride < MatrixTy->getNumRows()) {
16452 Diag(StrideExpr->getBeginLoc(),
16453 diag::err_builtin_matrix_stride_too_small);
16454 ArgError = true;
16455 }
16456 }
16457 }
16458
16459 if (ArgError)
16460 return ExprError();
16461
16462 return CallResult;
16463}
16464
16466 const NamedDecl *Callee) {
16467 // This warning does not make sense in code that has no runtime behavior.
16469 return;
16470
16471 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
16472
16473 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
16474 return;
16475
16476 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16477 // all TCBs the callee is a part of.
16478 llvm::StringSet<> CalleeTCBs;
16479 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
16480 CalleeTCBs.insert(A->getTCBName());
16481 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
16482 CalleeTCBs.insert(A->getTCBName());
16483
16484 // Go through the TCBs the caller is a part of and emit warnings if Caller
16485 // is in a TCB that the Callee is not.
16486 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
16487 StringRef CallerTCB = A->getTCBName();
16488 if (CalleeTCBs.count(CallerTCB) == 0) {
16489 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
16490 << Callee << CallerTCB;
16491 }
16492 }
16493}
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
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
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
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
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
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.
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.
@ 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:7171
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7175
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:3720
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3734
QualType getElementType() const
Definition TypeBase.h:3732
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:1017
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1031
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:3540
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:5135
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5175
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1225
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
bool isDynamicClass() const
Definition DeclCXX.h:574
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h: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:3758
QualType desugar() const
Definition TypeBase.h:3859
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3814
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
static constexpr unsigned getMaxElementsPerDimension()
Returns the maximum number of elements per dimension.
Definition TypeBase.h:4405
static constexpr bool isDimensionValid(size_t NumElements)
Returns true if NumElements is a valid matrix dimension.
Definition TypeBase.h:4400
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:5527
Expr * getOperand() const
Definition ExprCXX.h:5318
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:427
T * getAttr() const
Definition DeclBase.h:573
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:538
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:427
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:1988
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:808
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:231
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:950
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3420
Represents an enum.
Definition Decl.h:4004
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4227
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4168
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:4205
@ 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:4265
Represents a member of a struct/union/class.
Definition Decl.h:3157
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3260
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4693
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3273
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:78
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:139
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:128
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:102
llvm::APFloat getValue() const
Definition Expr.h:1666
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2888
Represents a function declaration or definition.
Definition Decl.h:1999
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4494
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2794
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3703
param_iterator param_end()
Definition Decl.h:2784
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3806
QualType getReturnType() const
Definition Decl.h:2842
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2771
param_iterator param_begin()
Definition Decl.h:2783
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3125
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4270
bool isStatic() const
Definition Decl.h:2926
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4085
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4071
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3767
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5264
unsigned getNumParams() const
Definition TypeBase.h:5542
QualType getParamType(unsigned i) const
Definition TypeBase.h:5544
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5668
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5553
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5663
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5549
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4460
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4769
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4765
QualType getReturnType() const
Definition TypeBase.h:4800
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:4356
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:3651
This represents a decl that may have a name.
Definition Decl.h:273
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1930
Represent a C++ namespace.
Definition Decl.h:591
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1683
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1697
SourceLocation getSemiLoc() const
Definition Stmt.h:1694
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
QualType getType() const
Definition DeclObjC.h:804
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition DeclObjC.h:827
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:815
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition ExprObjC.h:616
ObjCPropertyDecl * getExplicitProperty() const
Definition ExprObjC.h:705
bool isImplicitProperty() const
Definition ExprObjC.h:702
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:52
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:1789
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:5073
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8369
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2867
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:8285
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8411
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8325
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:8337
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8379
void removeLocalVolatile()
Definition TypeBase.h:8401
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1179
void removeLocalConst()
Definition TypeBase.h:8393
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8358
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8406
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:8331
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1442
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
bool hasUnaligned() const
Definition TypeBase.h:511
Represents a struct/union/class.
Definition Decl.h:4309
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4395
field_range fields() const
Definition Decl.h:4512
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4387
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:853
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:1419
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:12943
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1119
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:9290
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9298
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9335
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:6889
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:2048
SemaHexagon & Hexagon()
Definition Sema.h:1459
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1647
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:827
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1549
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:1282
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:921
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:1489
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:748
ASTContext & getASTContext() const
Definition Sema.h:924
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:2588
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:1190
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:2700
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:917
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:1434
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:1449
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:1280
static const uint64_t MaximumAlignment
Definition Sema.h:1213
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:946
SemaHLSL & HLSL()
Definition Sema.h:1454
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1474
SemaRISCV & RISCV()
Definition Sema.h:1519
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:2766
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:6922
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:1313
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition Sema.h:2668
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15245
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2294
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl)
The main callback when the parser finds something like expression .
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body,...
void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody)
Warn if a for/while loop statement S, which is followed by PossibleBody, has a suspicious null statem...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:633
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
void CheckTCBEnforcement(const SourceLocation CallExprLoc, const NamedDecl *Callee)
Enforce the bounds of a TCB CheckTCBEnforcement - Enforces that every function in a named TCB only di...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1417
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:1499
FormatArgumentPassingKind
Definition Sema.h:2598
@ FAPK_Elsewhere
Definition Sema.h:2602
@ FAPK_Fixed
Definition Sema.h:2599
@ FAPK_Variadic
Definition Sema.h:2600
@ FAPK_VAList
Definition Sema.h:2601
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:8129
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:13798
SourceManager & getSourceManager() const
Definition Sema.h:922
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:218
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
bool isConstantEvaluatedContext() const
Definition Sema.h:2590
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:1509
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:1245
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:1539
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:1285
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:777
DiagnosticsEngine & Diags
Definition Sema.h:1284
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:1484
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:6194
SemaSPIRV & SPIRV()
Definition Sema.h:1524
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:1464
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6382
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:1544
SemaARM & ARM()
Definition Sema.h:1424
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:358
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
child_range children()
Definition Stmt.cpp:295
StmtClass getStmtClass() const
Definition Stmt.h:1472
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:334
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h: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:3829
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3809
bool isUnion() const
Definition Decl.h:3919
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool 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:2715
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:6175
A container of type source information.
Definition TypeBase.h:8256
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8267
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isBlockPointerType() const
Definition TypeBase.h:8542
bool isVoidType() const
Definition TypeBase.h:8878
bool isBooleanType() const
Definition TypeBase.h:9008
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:9058
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:9038
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:2426
bool isArrayType() const
Definition TypeBase.h:8621
bool isCharType() const
Definition Type.cpp:2132
bool isFunctionPointerType() const
Definition TypeBase.h:8589
bool isPointerType() const
Definition TypeBase.h:8522
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8922
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9165
bool isReferenceType() const
Definition TypeBase.h:8546
bool isEnumeralType() const
Definition TypeBase.h:8653
bool isScalarType() const
Definition TypeBase.h:8980
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:8633
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2608
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:8665
bool isExtVectorBoolType() const
Definition TypeBase.h:8669
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2647
bool isBitIntType() const
Definition TypeBase.h:8787
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8847
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8645
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:2558
bool isAtomicType() const
Definition TypeBase.h:8704
bool isFunctionProtoType() const
Definition TypeBase.h:2601
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3075
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:8695
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9151
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9014
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:2436
bool isFunctionType() const
Definition TypeBase.h:8518
bool isObjCObjectPointerType() const
Definition TypeBase.h:8691
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:8661
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:8530
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:9098
bool isNullPtrType() const
Definition TypeBase.h:8915
bool isRecordType() const
Definition TypeBase.h:8649
bool isObjCRetainableType() const
Definition Type.cpp:5291
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5022
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2570
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2635
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3559
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h: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:711
QualType getType() const
Definition Decl.h:722
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5453
Represents a variable declaration or definition.
Definition Decl.h:925
Represents a GCC generic vector type.
Definition TypeBase.h:4173
unsigned getNumElements() const
Definition TypeBase.h:4188
QualType getElementType() const
Definition TypeBase.h:4187
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:2502
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:815
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:510
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:660
@ Comparison
A comparison.
Definition Sema.h:664
@ 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:591
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:561
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:496
CastKind
CastKind - The kind of operation required for a conversion.
BuiltinCountedByRefKind
Definition Sema.h:518
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:4134
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5884
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5877
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1745
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:5349
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:13083
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13109
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13099
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13058
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6783
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2610
#define log2(__x)
Definition tgmath.h:970