clang 24.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/TypeBase.h"
41#include "clang/AST/TypeLoc.h"
48#include "clang/Basic/LLVM.h"
58#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
60#include "clang/Sema/Lookup.h"
62#include "clang/Sema/Scope.h"
64#include "clang/Sema/Sema.h"
66#include "clang/Sema/SemaARM.h"
67#include "clang/Sema/SemaBPF.h"
69#include "clang/Sema/SemaHLSL.h"
72#include "clang/Sema/SemaMIPS.h"
74#include "clang/Sema/SemaObjC.h"
76#include "clang/Sema/SemaPPC.h"
79#include "clang/Sema/SemaSYCL.h"
81#include "clang/Sema/SemaWasm.h"
82#include "clang/Sema/SemaX86.h"
83#include "llvm/ADT/APFloat.h"
84#include "llvm/ADT/APInt.h"
85#include "llvm/ADT/APSInt.h"
86#include "llvm/ADT/ArrayRef.h"
87#include "llvm/ADT/DenseMap.h"
88#include "llvm/ADT/FoldingSet.h"
89#include "llvm/ADT/STLExtras.h"
90#include "llvm/ADT/STLForwardCompat.h"
91#include "llvm/ADT/SmallBitVector.h"
92#include "llvm/ADT/SmallPtrSet.h"
93#include "llvm/ADT/SmallString.h"
94#include "llvm/ADT/SmallVector.h"
95#include "llvm/ADT/StringExtras.h"
96#include "llvm/ADT/StringRef.h"
97#include "llvm/ADT/StringSet.h"
98#include "llvm/ADT/StringSwitch.h"
99#include "llvm/Support/AtomicOrdering.h"
100#include "llvm/Support/Compiler.h"
101#include "llvm/Support/ConvertUTF.h"
102#include "llvm/Support/ErrorHandling.h"
103#include "llvm/Support/Format.h"
104#include "llvm/Support/Locale.h"
105#include "llvm/Support/MathExtras.h"
106#include "llvm/Support/SaveAndRestore.h"
107#include "llvm/Support/raw_ostream.h"
108#include "llvm/TargetParser/RISCVTargetParser.h"
109#include "llvm/TargetParser/Triple.h"
110#include <algorithm>
111#include <cassert>
112#include <cctype>
113#include <cstddef>
114#include <cstdint>
115#include <functional>
116#include <limits>
117#include <optional>
118#include <string>
119#include <tuple>
120#include <utility>
121
122using namespace clang;
123using namespace sema;
124
126 unsigned ByteNo) const {
127 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
128 Context.getTargetInfo());
129}
130
131static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
133 return (A << 8) | B;
134}
135
136bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
137 unsigned ArgCount = Call->getNumArgs();
138 if (ArgCount >= MinArgCount)
139 return false;
140
141 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
142 << 0 /*function call*/ << MinArgCount << ArgCount
143 << /*is non object*/ 0 << Call->getSourceRange();
144}
145
146bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
147 unsigned ArgCount = Call->getNumArgs();
148 if (ArgCount <= MaxArgCount)
149 return false;
150 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
151 << 0 /*function call*/ << MaxArgCount << ArgCount
152 << /*is non object*/ 0 << Call->getSourceRange();
153}
154
155bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
156 unsigned MaxArgCount) {
157 return checkArgCountAtLeast(Call, MinArgCount) ||
158 checkArgCountAtMost(Call, MaxArgCount);
159}
160
161bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
162 unsigned ArgCount = Call->getNumArgs();
163 if (ArgCount == DesiredArgCount)
164 return false;
165
166 if (checkArgCountAtLeast(Call, DesiredArgCount))
167 return true;
168 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
169
170 // Highlight all the excess arguments.
171 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(),
172 Call->getArg(ArgCount - 1)->getEndLoc());
173
174 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
175 << 0 /*function call*/ << DesiredArgCount << ArgCount
176 << /*is non object*/ 0 << Range;
177}
178
180 bool HasError = false;
181
182 for (const Expr *Arg : Call->arguments()) {
183 if (Arg->isValueDependent())
184 continue;
185
186 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context);
187 int DiagMsgKind = -1;
188 // Arguments must be pointers to constant strings and cannot use '$'.
189 if (!ArgString.has_value())
190 DiagMsgKind = 0;
191 else if (ArgString->find('$') != std::string::npos)
192 DiagMsgKind = 1;
193
194 if (DiagMsgKind >= 0) {
195 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
196 << DiagMsgKind << Arg->getSourceRange();
197 HasError = true;
198 }
199 }
200
201 return !HasError;
202}
203
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
212 if (Result.isInvalid())
213 return true;
214 Value = Result.get();
215 return false;
216}
217
218/// Check that the first argument to __builtin_annotation is an integer
219/// and the second argument is a non-wide string literal.
220static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
221 if (S.checkArgCount(TheCall, 2))
222 return true;
223
224 // First argument should be an integer.
225 Expr *ValArg = TheCall->getArg(0);
226 QualType Ty = ValArg->getType();
227 if (!Ty->isIntegerType()) {
228 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
229 << ValArg->getSourceRange();
230 return true;
231 }
232
233 // Second argument should be a constant string.
234 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
235 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
236 if (!Literal || !Literal->isOrdinary()) {
237 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
238 << StrArg->getSourceRange();
239 return true;
240 }
241
242 TheCall->setType(Ty);
243 return false;
244}
245
246static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
247 // We need at least one argument.
248 if (TheCall->getNumArgs() < 1) {
249 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
250 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
251 << TheCall->getCallee()->getSourceRange();
252 return true;
253 }
254
255 // All arguments should be wide string literals.
256 for (Expr *Arg : TheCall->arguments()) {
257 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
258 if (!Literal || !Literal->isWide()) {
259 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
260 << Arg->getSourceRange();
261 return true;
262 }
263 }
264
265 return false;
266}
267
268/// Check that the argument to __builtin_addressof is a glvalue, and set the
269/// result type to the corresponding pointer type.
270static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
271 if (S.checkArgCount(TheCall, 1))
272 return true;
273
274 ExprResult Arg(TheCall->getArg(0));
275 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
276 if (ResultType.isNull())
277 return true;
278
279 TheCall->setArg(0, Arg.get());
280 TheCall->setType(ResultType);
281 return false;
282}
283
284/// Check that the argument to __builtin_function_start is a function.
285static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
286 if (S.checkArgCount(TheCall, 1))
287 return true;
288
289 if (TheCall->getArg(0)->containsErrors())
290 return true;
291
293 if (Arg.isInvalid())
294 return true;
295
296 TheCall->setArg(0, Arg.get());
297 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
299
300 if (!FD) {
301 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
302 << TheCall->getSourceRange();
303 return true;
304 }
305
306 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
307 TheCall->getBeginLoc());
308}
309
310/// Check the number of arguments and set the result type to
311/// the argument type.
312static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
313 if (S.checkArgCount(TheCall, 1))
314 return true;
315
316 TheCall->setType(TheCall->getArg(0)->getType());
317 return false;
318}
319
320/// Check that the value argument for __builtin_is_aligned(value, alignment) and
321/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
322/// type (but not a function pointer) and that the alignment is a power-of-two.
323static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
324 if (S.checkArgCount(TheCall, 2))
325 return true;
326
327 clang::Expr *Source = TheCall->getArg(0);
328 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
329
330 auto IsValidIntegerType = [](QualType Ty) {
331 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
332 };
333 QualType SrcTy = Source->getType();
334 // We should also be able to use it with arrays (but not functions!).
335 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
336 SrcTy = S.Context.getDecayedType(SrcTy);
337 }
338 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
339 SrcTy->isFunctionPointerType()) {
340 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
341 << SrcTy;
342 if (SrcTy->isFloatingType())
343 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_type);
344 else if (SrcTy->isMemberPointerType())
345 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_member_pointer);
346 else if (SrcTy->isFunctionPointerType())
347 S.Diag(Source->getExprLoc(),
348 diag::note_alignment_invalid_function_pointer);
349 return true;
350 }
351
352 clang::Expr *AlignOp = TheCall->getArg(1);
353 if (!IsValidIntegerType(AlignOp->getType())) {
354 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
355 << AlignOp->getType();
356 return true;
357 }
358 Expr::EvalResult AlignResult;
359 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
360 // We can't check validity of alignment if it is value dependent.
361 if (!AlignOp->isValueDependent() &&
362 AlignOp->EvaluateAsInt(AlignResult, S.Context,
364 llvm::APSInt AlignValue = AlignResult.Val.getInt();
365 llvm::APSInt MaxValue(
366 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
367 if (AlignValue < 1) {
368 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
369 return true;
370 }
371 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
372 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
373 << toString(MaxValue, 10);
374 return true;
375 }
376 if (!AlignValue.isPowerOf2()) {
377 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
378 return true;
379 }
380 if (AlignValue == 1) {
381 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
382 << IsBooleanAlignBuiltin;
383 }
384 }
385
388 SourceLocation(), Source);
389 if (SrcArg.isInvalid())
390 return true;
391 TheCall->setArg(0, SrcArg.get());
392 ExprResult AlignArg =
394 S.Context, AlignOp->getType(), false),
395 SourceLocation(), AlignOp);
396 if (AlignArg.isInvalid())
397 return true;
398 TheCall->setArg(1, AlignArg.get());
399 // For align_up/align_down, the return type is the same as the (potentially
400 // decayed) argument type including qualifiers. For is_aligned(), the result
401 // is always bool.
402 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
403 return false;
404}
405
406static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
407 if (S.checkArgCount(TheCall, 3))
408 return true;
409
410 std::pair<unsigned, const char *> Builtins[] = {
411 { Builtin::BI__builtin_add_overflow, "ckd_add" },
412 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
413 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
414 };
415
416 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
417 const char *> &P) {
418 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
420 S.getSourceManager(), S.getLangOpts()) == P.second;
421 });
422
423 auto ValidCkdIntType = [](QualType QT) {
424 // A valid checked integer type is an integer type other than a plain char,
425 // bool, a bit-precise type, or an enumeration type.
426 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
427 return (BT->getKind() >= BuiltinType::Short &&
428 BT->getKind() <= BuiltinType::Int128) || (
429 BT->getKind() >= BuiltinType::UShort &&
430 BT->getKind() <= BuiltinType::UInt128) ||
431 BT->getKind() == BuiltinType::UChar ||
432 BT->getKind() == BuiltinType::SChar;
433 return false;
434 };
435
436 // First two arguments should be integers.
437 for (unsigned I = 0; I < 2; ++I) {
439 if (Arg.isInvalid()) return true;
440 TheCall->setArg(I, Arg.get());
441
442 QualType Ty = Arg.get()->getType();
443 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
444 if (!IsValid) {
445 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
446 << CkdOperation << Ty << Arg.get()->getSourceRange();
447 return true;
448 }
449 }
450
451 // Third argument should be a pointer to a non-const integer.
452 // IRGen correctly handles volatile, restrict, and address spaces, and
453 // the other qualifiers aren't possible.
454 {
456 if (Arg.isInvalid()) return true;
457 TheCall->setArg(2, Arg.get());
458
459 QualType Ty = Arg.get()->getType();
460 const auto *PtrTy = Ty->getAs<PointerType>();
461 if (!PtrTy ||
462 !PtrTy->getPointeeType()->isIntegerType() ||
463 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
464 PtrTy->getPointeeType().isConstQualified()) {
465 S.Diag(Arg.get()->getBeginLoc(),
466 diag::err_overflow_builtin_must_be_ptr_int)
467 << CkdOperation << Ty << Arg.get()->getSourceRange();
468 return true;
469 }
470 }
471
472 // Disallow signed bit-precise integer args larger than 128 bits to mul
473 // function until we improve backend support.
474 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
475 for (unsigned I = 0; I < 3; ++I) {
476 const auto Arg = TheCall->getArg(I);
477 // Third argument will be a pointer.
478 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
479 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
480 S.getASTContext().getIntWidth(Ty) > 128)
481 return S.Diag(Arg->getBeginLoc(),
482 diag::err_overflow_builtin_bit_int_max_size)
483 << 128;
484 }
485 }
486
487 return false;
488}
489
490namespace {
491struct BuiltinDumpStructGenerator {
492 Sema &S;
493 CallExpr *TheCall;
494 SourceLocation Loc = TheCall->getBeginLoc();
495 SmallVector<Expr *, 32> Actions;
496 DiagnosticErrorTrap ErrorTracker;
497 PrintingPolicy Policy;
498
499 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
500 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
501 Policy(S.Context.getPrintingPolicy()) {
502 Policy.AnonymousTagNameStyle =
503 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
504 }
505
506 Expr *makeOpaqueValueExpr(Expr *Inner) {
507 auto *OVE = new (S.Context)
508 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
509 Inner->getObjectKind(), Inner);
510 Actions.push_back(OVE);
511 return OVE;
512 }
513
514 Expr *getStringLiteral(llvm::StringRef Str) {
516 // Wrap the literal in parentheses to attach a source location.
517 return new (S.Context) ParenExpr(Loc, Loc, Lit);
518 }
519
520 bool callPrintFunction(llvm::StringRef Format,
521 llvm::ArrayRef<Expr *> Exprs = {}) {
522 SmallVector<Expr *, 8> Args;
523 assert(TheCall->getNumArgs() >= 2);
524 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
525 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
526 Args.push_back(getStringLiteral(Format));
527 llvm::append_range(Args, Exprs);
528
529 // Register a note to explain why we're performing the call.
530 Sema::CodeSynthesisContext Ctx;
532 Ctx.PointOfInstantiation = Loc;
533 Ctx.CallArgs = Args.data();
534 Ctx.NumCallArgs = Args.size();
536
537 ExprResult RealCall =
538 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
539 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
540
542 if (!RealCall.isInvalid())
543 Actions.push_back(RealCall.get());
544 // Bail out if we've hit any unrecoverable errors, even if we managed
545 // to build the call.
546 return RealCall.isInvalid() || ErrorTracker.hasUnrecoverableErrorOccurred();
547 }
548
549 Expr *getIndentString(unsigned Depth) {
550 if (!Depth)
551 return nullptr;
552
553 llvm::SmallString<32> Indent;
554 Indent.resize(Depth * Policy.Indentation, ' ');
555 return getStringLiteral(Indent);
556 }
557
558 Expr *getTypeString(QualType T) {
559 return getStringLiteral(T.getAsString(Policy));
560 }
561
562 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
563 llvm::raw_svector_ostream OS(Str);
564
565 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
566 // than trying to print a single character.
567 if (auto *BT = T->getAs<BuiltinType>()) {
568 switch (BT->getKind()) {
569 case BuiltinType::Bool:
570 OS << "%d";
571 return true;
572 case BuiltinType::Char_U:
573 case BuiltinType::UChar:
574 OS << "%hhu";
575 return true;
576 case BuiltinType::Char_S:
577 case BuiltinType::SChar:
578 OS << "%hhd";
579 return true;
580 default:
581 break;
582 }
583 }
584
585 analyze_printf::PrintfSpecifier Specifier;
586 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
587 // We were able to guess how to format this.
588 if (Specifier.getConversionSpecifier().getKind() ==
589 analyze_printf::PrintfConversionSpecifier::sArg) {
590 // Wrap double-quotes around a '%s' specifier and limit its maximum
591 // length. Ideally we'd also somehow escape special characters in the
592 // contents but printf doesn't support that.
593 // FIXME: '%s' formatting is not safe in general.
594 OS << '"';
595 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
596 Specifier.toString(OS);
597 OS << '"';
598 // FIXME: It would be nice to include a '...' if the string doesn't fit
599 // in the length limit.
600 } else {
601 Specifier.toString(OS);
602 }
603 return true;
604 }
605
606 if (T->isPointerType()) {
607 // Format all pointers with '%p'.
608 OS << "%p";
609 return true;
610 }
611
612 return false;
613 }
614
615 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
616 Expr *IndentLit = getIndentString(Depth);
617 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
618 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
619 : callPrintFunction("%s", {TypeLit}))
620 return true;
621
622 return dumpRecordValue(RD, E, IndentLit, Depth);
623 }
624
625 // Dump a record value. E should be a pointer or lvalue referring to an RD.
626 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
627 unsigned Depth) {
628 // FIXME: Decide what to do if RD is a union. At least we should probably
629 // turn off printing `const char*` members with `%s`, because that is very
630 // likely to crash if that's not the active member. Whatever we decide, we
631 // should document it.
632
633 // Build an OpaqueValueExpr so we can refer to E more than once without
634 // triggering re-evaluation.
635 Expr *RecordArg = makeOpaqueValueExpr(E);
636 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
637
638 if (callPrintFunction(" {\n"))
639 return true;
640
641 // Dump each base class, regardless of whether they're aggregates.
642 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
643 for (const auto &Base : CXXRD->bases()) {
644 QualType BaseType =
645 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
646 : S.Context.getLValueReferenceType(Base.getType());
648 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
649 RecordArg);
650 if (BasePtr.isInvalid() ||
651 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
652 Depth + 1))
653 return true;
654 }
655 }
656
657 Expr *FieldIndentArg = getIndentString(Depth + 1);
658
659 // Dump each field.
660 for (auto *D : RD->decls()) {
661 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
662 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
663 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
664 continue;
665
666 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
667 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
668 getTypeString(FD->getType()),
669 getStringLiteral(FD->getName())};
670
671 if (FD->isBitField()) {
672 Format += ": %zu ";
673 QualType SizeT = S.Context.getSizeType();
674 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
675 FD->getBitWidthValue());
676 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
677 }
678
679 Format += "=";
680
683 CXXScopeSpec(), Loc, IFD,
684 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
686 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
688 DeclarationNameInfo(FD->getDeclName(), Loc));
689 if (Field.isInvalid())
690 return true;
691
692 auto *InnerRD = FD->getType()->getAsRecordDecl();
693 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
694 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
695 // Recursively print the values of members of aggregate record type.
696 if (callPrintFunction(Format, Args) ||
697 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
698 return true;
699 } else {
700 Format += " ";
701 if (appendFormatSpecifier(FD->getType(), Format)) {
702 // We know how to print this field.
703 Args.push_back(Field.get());
704 } else {
705 // We don't know how to print this field. Print out its address
706 // with a format specifier that a smart tool will be able to
707 // recognize and treat specially.
708 Format += "*%p";
709 ExprResult FieldAddr =
710 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
711 if (FieldAddr.isInvalid())
712 return true;
713 Args.push_back(FieldAddr.get());
714 }
715 Format += "\n";
716 if (callPrintFunction(Format, Args))
717 return true;
718 }
719 }
720
721 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
722 : callPrintFunction("}\n");
723 }
724
725 Expr *buildWrapper() {
726 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
728 TheCall->setType(Wrapper->getType());
729 TheCall->setValueKind(Wrapper->getValueKind());
730 return Wrapper;
731 }
732};
733} // namespace
734
736 if (S.checkArgCountAtLeast(TheCall, 2))
737 return ExprError();
738
739 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
740 if (PtrArgResult.isInvalid())
741 return ExprError();
742 TheCall->setArg(0, PtrArgResult.get());
743
744 // First argument should be a pointer to a struct.
745 QualType PtrArgType = PtrArgResult.get()->getType();
746 if (!PtrArgType->isPointerType() ||
747 !PtrArgType->getPointeeType()->isRecordType()) {
748 S.Diag(PtrArgResult.get()->getBeginLoc(),
749 diag::err_expected_struct_pointer_argument)
750 << 1 << TheCall->getDirectCallee() << PtrArgType;
751 return ExprError();
752 }
753 QualType Pointee = PtrArgType->getPointeeType();
754 const RecordDecl *RD = Pointee->getAsRecordDecl();
755 // Try to instantiate the class template as appropriate; otherwise, access to
756 // its data() may lead to a crash.
757 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
758 diag::err_incomplete_type))
759 return ExprError();
760 // Second argument is a callable, but we can't fully validate it until we try
761 // calling it.
762 QualType FnArgType = TheCall->getArg(1)->getType();
763 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
764 !FnArgType->isBlockPointerType() &&
765 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
766 auto *BT = FnArgType->getAs<BuiltinType>();
767 switch (BT ? BT->getKind() : BuiltinType::Void) {
768 case BuiltinType::Dependent:
769 case BuiltinType::Overload:
770 case BuiltinType::BoundMember:
771 case BuiltinType::PseudoObject:
772 case BuiltinType::UnknownAny:
773 case BuiltinType::BuiltinFn:
774 // This might be a callable.
775 break;
776
777 default:
778 S.Diag(TheCall->getArg(1)->getBeginLoc(),
779 diag::err_expected_callable_argument)
780 << 2 << TheCall->getDirectCallee() << FnArgType;
781 return ExprError();
782 }
783 }
784
785 BuiltinDumpStructGenerator Generator(S, TheCall);
786
787 // Wrap parentheses around the given pointer. This is not necessary for
788 // correct code generation, but it means that when we pretty-print the call
789 // arguments in our diagnostics we will produce '(&s)->n' instead of the
790 // incorrect '&s->n'.
791 Expr *PtrArg = PtrArgResult.get();
792 PtrArg = new (S.Context)
793 ParenExpr(PtrArg->getBeginLoc(),
794 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
795 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
796 return ExprError();
797
798 return Generator.buildWrapper();
799}
800
801static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
802 if (S.checkArgCount(BuiltinCall, 2))
803 return true;
804
805 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
806 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
807 Expr *Call = BuiltinCall->getArg(0);
808 Expr *Chain = BuiltinCall->getArg(1);
809
810 if (Call->getStmtClass() != Stmt::CallExprClass) {
811 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
812 << Call->getSourceRange();
813 return true;
814 }
815
816 auto CE = cast<CallExpr>(Call);
817 if (CE->getCallee()->getType()->isBlockPointerType()) {
818 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
819 << Call->getSourceRange();
820 return true;
821 }
822
823 const Decl *TargetDecl = CE->getCalleeDecl();
824 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
825 if (FD->getBuiltinID()) {
826 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
827 << Call->getSourceRange();
828 return true;
829 }
830
831 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
832 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
833 << Call->getSourceRange();
834 return true;
835 }
836
837 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
838 if (ChainResult.isInvalid())
839 return true;
840 if (!ChainResult.get()->getType()->isPointerType()) {
841 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
842 << Chain->getSourceRange();
843 return true;
844 }
845
846 QualType ReturnTy = CE->getCallReturnType(S.Context);
847 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
848 QualType BuiltinTy = S.Context.getFunctionType(
849 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
850 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
851
852 Builtin =
853 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
854
855 BuiltinCall->setType(CE->getType());
856 BuiltinCall->setValueKind(CE->getValueKind());
857 BuiltinCall->setObjectKind(CE->getObjectKind());
858 BuiltinCall->setCallee(Builtin);
859 BuiltinCall->setArg(1, ChainResult.get());
860
861 return false;
862}
863
864namespace {
865
866class ScanfDiagnosticFormatHandler
868 // Accepts the argument index (relative to the first destination index) of the
869 // argument whose size we want.
870 using ComputeSizeFunction =
871 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
872
873 // Accepts the argument index (relative to the first destination index), the
874 // destination size, and the source size).
875 using DiagnoseFunction =
876 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
877
878 ComputeSizeFunction ComputeSizeArgument;
879 DiagnoseFunction Diagnose;
880
881public:
882 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
883 DiagnoseFunction Diagnose)
884 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
885
886 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
887 const char *StartSpecifier,
888 unsigned specifierLen) override {
889 if (!FS.consumesDataArgument())
890 return true;
891
892 unsigned NulByte = 0;
893 switch ((FS.getConversionSpecifier().getKind())) {
894 default:
895 return true;
898 NulByte = 1;
899 break;
901 break;
902 }
903
904 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
905 if (FW.getHowSpecified() !=
906 analyze_format_string::OptionalAmount::HowSpecified::Constant)
907 return true;
908
909 unsigned SourceSize = FW.getConstantAmount() + NulByte;
910
911 std::optional<llvm::APSInt> DestSizeAPS =
912 ComputeSizeArgument(FS.getArgIndex());
913 if (!DestSizeAPS)
914 return true;
915
916 unsigned DestSize = DestSizeAPS->getZExtValue();
917
918 if (DestSize < SourceSize)
919 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
920
921 return true;
922 }
923};
924
925class EstimateSizeFormatHandler
927 size_t Size;
928 /// Whether the format string contains Linux kernel's format specifier
929 /// extension.
930 bool IsKernelCompatible = true;
931
932public:
933 EstimateSizeFormatHandler(StringRef Format)
934 : Size(std::min(Format.find(0), Format.size()) +
935 1 /* null byte always written by sprintf */) {}
936
937 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
938 const char *, unsigned SpecifierLen,
939 const TargetInfo &) override {
940
941 const size_t FieldWidth = computeFieldWidth(FS);
942 const size_t Precision = computePrecision(FS);
943
944 // The actual format.
945 switch (FS.getConversionSpecifier().getKind()) {
946 // Just a char.
949 Size += std::max(FieldWidth, (size_t)1);
950 break;
951 // Just an integer.
961 Size += std::max(FieldWidth, Precision);
962 break;
963
964 // %g style conversion switches between %f or %e style dynamically.
965 // %g removes trailing zeros, and does not print decimal point if there are
966 // no digits that follow it. Thus %g can print a single digit.
967 // FIXME: If it is alternative form:
968 // For g and G conversions, trailing zeros are not removed from the result.
971 Size += 1;
972 break;
973
974 // Floating point number in the form '[+]ddd.ddd'.
977 Size += std::max(FieldWidth, 1 /* integer part */ +
978 (Precision ? 1 + Precision
979 : 0) /* period + decimal */);
980 break;
981
982 // Floating point number in the form '[-]d.ddde[+-]dd'.
985 Size +=
986 std::max(FieldWidth,
987 1 /* integer part */ +
988 (Precision ? 1 + Precision : 0) /* period + decimal */ +
989 1 /* e or E letter */ + 2 /* exponent */);
990 break;
991
992 // Floating point number in the form '[-]0xh.hhhhp±dd'.
995 Size +=
996 std::max(FieldWidth,
997 2 /* 0x */ + 1 /* integer part */ +
998 (Precision ? 1 + Precision : 0) /* period + decimal */ +
999 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
1000 break;
1001
1002 // Just a string.
1005 Size += FieldWidth;
1006 break;
1007
1008 // Just a pointer in the form '0xddd'.
1010 // Linux kernel has its own extesion for `%p` specifier.
1011 // Kernel Document:
1012 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1013 IsKernelCompatible = false;
1014 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1015 break;
1016
1017 // A plain percent.
1019 Size += 1;
1020 break;
1021
1022 default:
1023 break;
1024 }
1025
1026 // If field width is specified, the sign/space is already accounted for
1027 // within the field width, so no additional size is needed.
1028 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1029 Size += 1;
1030
1031 if (FS.hasAlternativeForm()) {
1032 switch (FS.getConversionSpecifier().getKind()) {
1033 // For o conversion, it increases the precision, if and only if necessary,
1034 // to force the first digit of the result to be a zero
1035 // (if the value and precision are both 0, a single 0 is printed)
1037 // For b conversion, a nonzero result has 0b prefixed to it.
1039 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1040 // it.
1043 // Note: even when the prefix is added, if
1044 // (prefix_width <= FieldWidth - formatted_length) holds,
1045 // the prefix does not increase the format
1046 // size. e.g.(("%#3x", 0xf) is "0xf")
1047
1048 // If the result is zero, o, b, x, X adds nothing.
1049 break;
1050 // For a, A, e, E, f, F, g, and G conversions,
1051 // the result of converting a floating-point number always contains a
1052 // decimal-point
1061 Size += (Precision ? 0 : 1);
1062 break;
1063 // For other conversions, the behavior is undefined.
1064 default:
1065 break;
1066 }
1067 }
1068 assert(SpecifierLen <= Size && "no underflow");
1069 Size -= SpecifierLen;
1070 return true;
1071 }
1072
1073 size_t getSizeLowerBound() const { return Size; }
1074 bool isKernelCompatible() const { return IsKernelCompatible; }
1075
1076private:
1077 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1078 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1079 size_t FieldWidth = 0;
1081 FieldWidth = FW.getConstantAmount();
1082 return FieldWidth;
1083 }
1084
1085 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1086 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1087 size_t Precision = 0;
1088
1089 // See man 3 printf for default precision value based on the specifier.
1090 switch (FW.getHowSpecified()) {
1092 switch (FS.getConversionSpecifier().getKind()) {
1093 default:
1094 break;
1098 Precision = 1;
1099 break;
1106 Precision = 1;
1107 break;
1114 Precision = 6;
1115 break;
1117 Precision = 1;
1118 break;
1119 }
1120 break;
1122 Precision = FW.getConstantAmount();
1123 break;
1124 default:
1125 break;
1126 }
1127 return Precision;
1128 }
1129};
1130
1131} // namespace
1132
1133static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1134 StringRef &FormatStrRef, size_t &StrLen,
1135 ASTContext &Context) {
1136 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1137 Format && (Format->isOrdinary() || Format->isUTF8())) {
1138 FormatStrRef = Format->getString();
1139 const ConstantArrayType *T =
1140 Context.getAsConstantArrayType(Format->getType());
1141 assert(T && "String literal not of constant array type!");
1142 size_t TypeSize = T->getZExtSize();
1143 // In case there's a null byte somewhere.
1144 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1145 return true;
1146 }
1147 return false;
1148}
1149
1150namespace {
1151/// Helper class for buffer overflow/overread checking in fortified functions.
1152class FortifiedBufferChecker {
1153public:
1154 FortifiedBufferChecker(Sema &S, FunctionDecl *FD, CallExpr *TheCall)
1155 : S(S), TheCall(TheCall), FD(FD),
1156 DABAttr(FD ? FD->getAttr<DiagnoseAsBuiltinAttr>() : nullptr) {
1157 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1158 SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1159 }
1160
1161 std::optional<unsigned> TranslateIndex(unsigned Index) {
1162 // If we refer to a diagnose_as_builtin attribute, we need to change the
1163 // argument index to refer to the arguments of the called function. Unless
1164 // the index is out of bounds, which presumably means it's a variadic
1165 // function.
1166 if (!DABAttr)
1167 return Index;
1168 unsigned DABIndices = DABAttr->argIndices_size();
1169 unsigned NewIndex = Index < DABIndices
1170 ? DABAttr->argIndices_begin()[Index]
1171 : Index - DABIndices + FD->getNumParams();
1172 if (NewIndex >= TheCall->getNumArgs())
1173 return std::nullopt;
1174 return NewIndex;
1175 }
1176
1177 std::optional<llvm::APSInt>
1178 ComputeExplicitObjectSizeArgument(unsigned Index) {
1179 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1180 if (!IndexOptional)
1181 return std::nullopt;
1182 unsigned NewIndex = *IndexOptional;
1183 Expr::EvalResult Result;
1184 Expr *SizeArg = TheCall->getArg(NewIndex);
1185 if (!SizeArg->EvaluateAsInt(Result, S.getASTContext()))
1186 return std::nullopt;
1187 llvm::APSInt Integer = Result.Val.getInt();
1188 assert(Integer.isUnsigned() &&
1189 "size arg should be unsigned after implicit conversion to size_t");
1190 return Integer;
1191 }
1192
1193 std::optional<llvm::APSInt> ComputeSizeArgument(unsigned Index) {
1194 // If the parameter has a pass_object_size attribute, then we should use its
1195 // (potentially) more strict checking mode. Otherwise, conservatively assume
1196 // type 0.
1197 int BOSType = 0;
1198 // This check can fail for variadic functions.
1199 if (Index < FD->getNumParams()) {
1200 if (const auto *POS =
1201 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1202 BOSType = POS->getType();
1203 }
1204
1205 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1206 if (!IndexOptional)
1207 return std::nullopt;
1208 unsigned NewIndex = *IndexOptional;
1209
1210 if (NewIndex >= TheCall->getNumArgs())
1211 return std::nullopt;
1212
1213 const Expr *ObjArg = TheCall->getArg(NewIndex);
1214 if (std::optional<uint64_t> ObjSize =
1215 ObjArg->tryEvaluateObjectSize(S.getASTContext(), BOSType)) {
1216 // Get the object size in the target's size_t width.
1217 return llvm::APSInt::getUnsigned(*ObjSize).extOrTrunc(SizeTypeWidth);
1218 }
1219 return std::nullopt;
1220 }
1221
1222 std::optional<llvm::APSInt> ComputeStrLenArgument(unsigned Index) {
1223 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1224 if (!IndexOptional)
1225 return std::nullopt;
1226 unsigned NewIndex = *IndexOptional;
1227
1228 const Expr *ObjArg = TheCall->getArg(NewIndex);
1229
1230 if (std::optional<uint64_t> Result =
1231 ObjArg->tryEvaluateStrLen(S.getASTContext())) {
1232 // Add 1 for null byte.
1233 return llvm::APSInt::getUnsigned(*Result + 1).extOrTrunc(SizeTypeWidth);
1234 }
1235 return std::nullopt;
1236 }
1237
1238 unsigned getSizeTypeWidth() const { return SizeTypeWidth; }
1239
1240 unsigned getBuiltinID() const {
1241 const FunctionDecl *UseDecl = FD;
1242 if (DABAttr) {
1243 UseDecl = DABAttr->getFunction();
1244 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1245 }
1246 return UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1247 }
1248
1249 /// Return function name after stripping __builtin_ and _chk affixes.
1250 std::string getFunctionName() const {
1251 unsigned ID = getBuiltinID();
1252 if (!ID) {
1253 // Use callee name directly if not a builtin.
1254 const FunctionDecl *Callee = TheCall->getDirectCallee();
1255 assert(Callee && "expected callee");
1256 return Callee->getName().str();
1257 }
1258 std::string Name = S.getASTContext().BuiltinInfo.getName(ID);
1259 StringRef Ref = Name;
1260 // Strip __builtin___*_chk or __builtin_ prefix.
1261 if (!(Ref.consume_front("__builtin___") && Ref.consume_back("_chk")))
1262 Ref.consume_front("__builtin_");
1263 assert(!Ref.empty() && "expected non-empty function name");
1264 return Ref.str();
1265 }
1266
1267 /// Check for source buffer overread in memory functions.
1268 void checkSourceOverread(unsigned SrcArgIdx, unsigned SizeArgIdx) {
1270 return;
1271
1272 const Expr *SrcArg = TheCall->getArg(SrcArgIdx);
1273 const Expr *SizeArg = TheCall->getArg(SizeArgIdx);
1274 if (SrcArg->isInstantiationDependent() ||
1275 SizeArg->isInstantiationDependent())
1276 return;
1277
1278 std::optional<llvm::APSInt> CopyLen =
1279 ComputeExplicitObjectSizeArgument(SizeArgIdx);
1280 std::optional<llvm::APSInt> SrcBufSize = ComputeSizeArgument(SrcArgIdx);
1281
1282 if (!CopyLen || !SrcBufSize)
1283 return;
1284
1285 // Warn only if copy length exceeds source buffer size.
1286 if (llvm::APSInt::compareValues(*CopyLen, *SrcBufSize) <= 0)
1287 return;
1288
1289 S.DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1290 S.PDiag(diag::warn_stringop_overread)
1291 << getFunctionName() << CopyLen->getZExtValue()
1292 << SrcBufSize->getZExtValue());
1293 }
1294
1295private:
1296 Sema &S;
1297 CallExpr *TheCall;
1298 FunctionDecl *FD;
1299 const DiagnoseAsBuiltinAttr *DABAttr;
1300 unsigned SizeTypeWidth;
1301};
1302} // anonymous namespace
1303
1304void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1305 CallExpr *TheCall) {
1307 return;
1308
1309 FortifiedBufferChecker Checker(*this, FD, TheCall);
1310
1311 unsigned BuiltinID = Checker.getBuiltinID();
1312 if (!BuiltinID)
1313 return;
1314
1315 unsigned SizeTypeWidth = Checker.getSizeTypeWidth();
1316
1317 std::optional<llvm::APSInt> SourceSize;
1318 std::optional<llvm::APSInt> DestinationSize;
1319 unsigned DiagID = 0;
1320
1321 switch (BuiltinID) {
1322 default:
1323 return;
1324 case Builtin::BI__builtin_strcat:
1325 case Builtin::BIstrcat:
1326 case Builtin::BI__builtin_stpcpy:
1327 case Builtin::BIstpcpy:
1328 case Builtin::BI__builtin_strcpy:
1329 case Builtin::BIstrcpy: {
1330 DiagID = diag::warn_fortify_strlen_overflow;
1331 SourceSize = Checker.ComputeStrLenArgument(1);
1332 DestinationSize = Checker.ComputeSizeArgument(0);
1333 break;
1334 }
1335
1336 case Builtin::BI__builtin___strcat_chk:
1337 case Builtin::BI__builtin___stpcpy_chk:
1338 case Builtin::BI__builtin___strcpy_chk: {
1339 DiagID = diag::warn_fortify_strlen_overflow;
1340 SourceSize = Checker.ComputeStrLenArgument(1);
1341 DestinationSize = Checker.ComputeExplicitObjectSizeArgument(2);
1342 break;
1343 }
1344
1345 case Builtin::BIscanf:
1346 case Builtin::BIfscanf:
1347 case Builtin::BIsscanf: {
1348 unsigned FormatIndex = 1;
1349 unsigned DataIndex = 2;
1350 if (BuiltinID == Builtin::BIscanf) {
1351 FormatIndex = 0;
1352 DataIndex = 1;
1353 }
1354
1355 const auto *FormatExpr =
1356 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1357
1358 StringRef FormatStrRef;
1359 size_t StrLen;
1360 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1361 return;
1362
1363 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1364 unsigned SourceSize) {
1365 DiagID = diag::warn_fortify_scanf_overflow;
1366 unsigned Index = ArgIndex + DataIndex;
1367 std::string FunctionName = Checker.getFunctionName();
1368 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1369 PDiag(DiagID) << FunctionName << (Index + 1)
1370 << DestSize << SourceSize);
1371 };
1372
1373 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1374 return Checker.ComputeSizeArgument(Index + DataIndex);
1375 };
1376 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1377 const char *FormatBytes = FormatStrRef.data();
1379 FormatBytes + StrLen, getLangOpts(),
1380 Context.getTargetInfo());
1381
1382 // Unlike the other cases, in this one we have already issued the diagnostic
1383 // here, so no need to continue (because unlike the other cases, here the
1384 // diagnostic refers to the argument number).
1385 return;
1386 }
1387
1388 case Builtin::BIsprintf:
1389 case Builtin::BI__builtin___sprintf_chk: {
1390 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1391 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1392
1393 StringRef FormatStrRef;
1394 size_t StrLen;
1395 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1396 EstimateSizeFormatHandler H(FormatStrRef);
1397 const char *FormatBytes = FormatStrRef.data();
1399 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1400 Context.getTargetInfo(), false)) {
1401 DiagID = H.isKernelCompatible()
1402 ? diag::warn_format_overflow
1403 : diag::warn_format_overflow_non_kprintf;
1404 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1405 .extOrTrunc(SizeTypeWidth);
1406 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1407 DestinationSize = Checker.ComputeExplicitObjectSizeArgument(2);
1408 } else {
1409 DestinationSize = Checker.ComputeSizeArgument(0);
1410 }
1411 break;
1412 }
1413 }
1414 return;
1415 }
1416 case Builtin::BI__builtin___memcpy_chk:
1417 case Builtin::BI__builtin___memmove_chk:
1418 case Builtin::BI__builtin___memset_chk:
1419 case Builtin::BI__builtin___strlcat_chk:
1420 case Builtin::BI__builtin___strlcpy_chk:
1421 case Builtin::BI__builtin___strncat_chk:
1422 case Builtin::BI__builtin___strncpy_chk:
1423 case Builtin::BI__builtin___stpncpy_chk:
1424 case Builtin::BI__builtin___memccpy_chk:
1425 case Builtin::BI__builtin___mempcpy_chk: {
1426 DiagID = diag::warn_builtin_chk_overflow;
1427 SourceSize =
1428 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1429 DestinationSize =
1430 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1431
1432 if (BuiltinID == Builtin::BI__builtin___memcpy_chk ||
1433 BuiltinID == Builtin::BI__builtin___memmove_chk ||
1434 BuiltinID == Builtin::BI__builtin___mempcpy_chk) {
1435 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1436 }
1437 break;
1438 }
1439
1440 case Builtin::BI__builtin___snprintf_chk:
1441 case Builtin::BI__builtin___vsnprintf_chk: {
1442 DiagID = diag::warn_builtin_chk_overflow;
1443 SourceSize = Checker.ComputeExplicitObjectSizeArgument(1);
1444 DestinationSize = Checker.ComputeExplicitObjectSizeArgument(3);
1445 break;
1446 }
1447
1448 case Builtin::BIstrncat:
1449 case Builtin::BI__builtin_strncat:
1450 case Builtin::BIstrncpy:
1451 case Builtin::BI__builtin_strncpy:
1452 case Builtin::BIstpncpy:
1453 case Builtin::BI__builtin_stpncpy:
1454 case Builtin::BIstrlcat:
1455 case Builtin::BI__builtin_strlcat: {
1456 // Whether these functions overflow depends on the runtime strlen of the
1457 // string, not just the buffer size, so emitting the "always overflow"
1458 // diagnostic isn't quite right. We should still diagnose passing a buffer
1459 // size larger than the destination buffer though; this is a runtime abort
1460 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1461 DiagID = diag::warn_fortify_source_size_mismatch;
1462 SourceSize =
1463 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1464 DestinationSize = Checker.ComputeSizeArgument(0);
1465 break;
1466 }
1467
1468 case Builtin::BIbzero:
1469 case Builtin::BI__builtin_bzero:
1470 case Builtin::BImemcpy:
1471 case Builtin::BI__builtin_memcpy:
1472 case Builtin::BImemmove:
1473 case Builtin::BI__builtin_memmove:
1474 case Builtin::BImemset:
1475 case Builtin::BI__builtin_memset:
1476 case Builtin::BImempcpy:
1477 case Builtin::BI__builtin_mempcpy: {
1478 DiagID = diag::warn_fortify_source_overflow;
1479 SourceSize =
1480 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1481 DestinationSize = Checker.ComputeSizeArgument(0);
1482
1483 // Buffer overread doesn't make sense for memset/bzero.
1484 if (BuiltinID != Builtin::BImemset &&
1485 BuiltinID != Builtin::BI__builtin_memset &&
1486 BuiltinID != Builtin::BIbzero &&
1487 BuiltinID != Builtin::BI__builtin_bzero) {
1488 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1489 }
1490 break;
1491 }
1492 case Builtin::BIbcopy:
1493 case Builtin::BI__builtin_bcopy: {
1494 DiagID = diag::warn_fortify_source_overflow;
1495 SourceSize =
1496 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1497 DestinationSize = Checker.ComputeSizeArgument(1);
1498 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1499 break;
1500 }
1501
1502 // memchr(buf, val, size)
1503 case Builtin::BImemchr:
1504 case Builtin::BI__builtin_memchr: {
1505 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1506 return;
1507 }
1508
1509 // memcmp/bcmp(buf0, buf1, size)
1510 // Two checks since each buffer is read
1511 case Builtin::BImemcmp:
1512 case Builtin::BI__builtin_memcmp:
1513 case Builtin::BIbcmp:
1514 case Builtin::BI__builtin_bcmp: {
1515 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1516 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1517 return;
1518 }
1519 case Builtin::BIsnprintf:
1520 case Builtin::BI__builtin_snprintf:
1521 case Builtin::BIvsnprintf:
1522 case Builtin::BI__builtin_vsnprintf: {
1523 DiagID = diag::warn_fortify_source_size_mismatch;
1524 SourceSize = Checker.ComputeExplicitObjectSizeArgument(1);
1525 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1526 StringRef FormatStrRef;
1527 size_t StrLen;
1528 if (SourceSize &&
1529 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1530 EstimateSizeFormatHandler H(FormatStrRef);
1531 const char *FormatBytes = FormatStrRef.data();
1533 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1534 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1535 llvm::APSInt FormatSize =
1536 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1537 .extOrTrunc(SizeTypeWidth);
1538 if (FormatSize > *SourceSize && *SourceSize != 0) {
1539 unsigned TruncationDiagID =
1540 H.isKernelCompatible() ? diag::warn_format_truncation
1541 : diag::warn_format_truncation_non_kprintf;
1542 SmallString<16> SpecifiedSizeStr;
1543 SmallString<16> FormatSizeStr;
1544 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1545 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1546 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1547 PDiag(TruncationDiagID)
1548 << Checker.getFunctionName()
1549 << SpecifiedSizeStr << FormatSizeStr);
1550 }
1551 }
1552 }
1553 DestinationSize = Checker.ComputeSizeArgument(0);
1554 const Expr *LenArg = TheCall->getArg(1)->IgnoreCasts();
1555 const Expr *Dest = TheCall->getArg(0)->IgnoreCasts();
1556 IdentifierInfo *FnInfo = FD->getIdentifier();
1557 CheckSizeofMemaccessArgument(LenArg, Dest, FnInfo);
1558 }
1559 }
1560
1561 if (!SourceSize || !DestinationSize ||
1562 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0)
1563 return;
1564
1565 std::string FunctionName = Checker.getFunctionName();
1566
1567 SmallString<16> DestinationStr;
1568 SmallString<16> SourceStr;
1569 DestinationSize->toString(DestinationStr, /*Radix=*/10);
1570 SourceSize->toString(SourceStr, /*Radix=*/10);
1571 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1572 PDiag(DiagID)
1573 << FunctionName << DestinationStr << SourceStr);
1574}
1575
1576void Sema::checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall) {
1577 if (TheCall->isValueDependent() || TheCall->isTypeDependent())
1578 return;
1579
1580 // Recognize the libc function by builtin identity rather than by name and
1581 // system-header origin. umask is a LibBuiltin marked IgnoreSignature, so the
1582 // builtin id is attached to any file-scope, C-linkage declaration of umask
1583 // regardless of the libc's mode_t spelling -- including a hand-written
1584 // forward declaration without <sys/stat.h>. A static/local lookalike or a
1585 // C++ (non-extern-"C") declaration keeps a zero builtin id and is ignored.
1586 if (FD->getBuiltinID() != Builtin::BIumask)
1587 return;
1588
1589 // umask(mode_t): warn when the constant-evaluated argument has bits set
1590 // outside the file-permission mask (0777). Those bits are ignored.
1591 if (TheCall->getNumArgs() != 1)
1592 return;
1593 Expr *Arg = TheCall->getArg(0);
1594 if (!Arg->getType()->isIntegerType())
1595 return;
1596 Expr::EvalResult R;
1597 if (!Arg->EvaluateAsInt(R, getASTContext()))
1598 return;
1599 // Operate on the raw two's-complement bit pattern so that negative literals
1600 // (which convert to large unsigned mode_t values) are caught.
1601 llvm::APInt RawValue = R.Val.getInt();
1602 llvm::APInt Mask(RawValue.getBitWidth(), 0777);
1603 llvm::APInt Extra = RawValue & ~Mask;
1604 if (Extra == 0)
1605 return;
1606 SmallString<16> ExtraStr;
1607 Extra.toString(ExtraStr, /*Radix=*/8, /*Signed=*/false);
1608 Diag(TheCall->getBeginLoc(), diag::warn_fortify_umask_unused_bits)
1609 << ExtraStr;
1610}
1611
1612static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1613 Scope::ScopeFlags NeededScopeFlags,
1614 unsigned DiagID) {
1615 // Scopes aren't available during instantiation. Fortunately, builtin
1616 // functions cannot be template args so they cannot be formed through template
1617 // instantiation. Therefore checking once during the parse is sufficient.
1618 if (SemaRef.inTemplateInstantiation())
1619 return false;
1620
1621 Scope *S = SemaRef.getCurScope();
1622 while (S && !S->isSEHExceptScope())
1623 S = S->getParent();
1624 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1625 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1626 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1627 << DRE->getDecl()->getIdentifier();
1628 return true;
1629 }
1630
1631 return false;
1632}
1633
1634// In OpenCL, __builtin_alloca_* should return a pointer to address space
1635// that corresponds to the stack address space i.e private address space.
1636static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1637 QualType RT = TheCall->getType();
1638 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1639 "__builtin_alloca has invalid address space");
1640
1641 RT = RT->getPointeeType();
1643 TheCall->setType(S.Context.getPointerType(RT));
1644}
1645
1646static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1647 if (S.checkArgCountAtLeast(TheCall, 1))
1648 return true;
1649
1650 for (Expr *Arg : TheCall->arguments()) {
1651 // If argument is dependent on a template parameter, we can't resolve now.
1652 if (Arg->isTypeDependent() || Arg->isValueDependent())
1653 continue;
1654 // Reject void types.
1655 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1656 if (ArgTy->isVoidType())
1657 return S.Diag(Arg->getBeginLoc(), diag::err_param_with_void_type);
1658 }
1659
1660 TheCall->setType(S.Context.getSizeType());
1661 return false;
1662}
1663
1664namespace {
1665enum PointerAuthOpKind {
1666 PAO_Strip,
1667 PAO_Sign,
1668 PAO_Auth,
1669 PAO_SignGeneric,
1670 PAO_Discriminator,
1671 PAO_BlendPointer,
1672 PAO_BlendInteger,
1673 PAO_BlendPC
1674};
1675}
1676
1678 if (getLangOpts().PointerAuthIntrinsics)
1679 return false;
1680
1681 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1682 return true;
1683}
1684
1685static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1687}
1688
1689static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1690 // Convert it to type 'int'.
1691 if (convertArgumentToType(S, Arg, S.Context.IntTy))
1692 return true;
1693
1694 // Value-dependent expressions are okay; wait for template instantiation.
1695 if (Arg->isValueDependent())
1696 return false;
1697
1698 unsigned KeyValue;
1699 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1700}
1701
1703 // Attempt to constant-evaluate the expression.
1704 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1705 if (!KeyValue) {
1706 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1707 << 0 << Arg->getSourceRange();
1708 return true;
1709 }
1710
1711 // Ask the target to validate the key parameter.
1712 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1714 {
1715 llvm::raw_svector_ostream Str(Value);
1716 Str << *KeyValue;
1717 }
1718
1719 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1720 << Value << Arg->getSourceRange();
1721 return true;
1722 }
1723
1724 Result = KeyValue->getZExtValue();
1725 return false;
1726}
1727
1730 unsigned &IntVal) {
1731 if (!Arg) {
1732 IntVal = 0;
1733 return true;
1734 }
1735
1736 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1737 if (!Result) {
1738 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1739 return false;
1740 }
1741
1742 unsigned Max;
1743 bool IsAddrDiscArg = false;
1744
1745 switch (Kind) {
1747 Max = 1;
1748 IsAddrDiscArg = true;
1749 break;
1752 break;
1753 };
1754
1756 if (IsAddrDiscArg)
1757 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1758 << Result->getExtValue();
1759 else
1760 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1761 << Result->getExtValue() << Max;
1762
1763 return false;
1764 };
1765
1766 IntVal = Result->getZExtValue();
1767 return true;
1768}
1769
1770static std::pair<const ValueDecl *, CharUnits>
1772 // Must evaluate as a pointer.
1774 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1775 return {nullptr, CharUnits()};
1776
1777 const auto *BaseDecl =
1778 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1779 if (!BaseDecl)
1780 return {nullptr, CharUnits()};
1781
1782 return {BaseDecl, Result.Val.getLValueOffset()};
1783}
1784
1785static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1786 bool RequireConstant = false) {
1787 if (Arg->hasPlaceholderType()) {
1789 if (R.isInvalid())
1790 return true;
1791 Arg = R.get();
1792 }
1793
1794 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1795 return OpKind != PAO_BlendInteger;
1796 };
1797 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1798 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1799 OpKind == PAO_SignGeneric || OpKind == PAO_BlendPC;
1800 };
1801
1802 // Require the value to have the right range of type.
1803 QualType ExpectedTy;
1804 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1805 ExpectedTy = Arg->getType().getUnqualifiedType();
1806 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1807 ExpectedTy = S.Context.VoidPtrTy;
1808 } else if (AllowsInteger(OpKind) &&
1810 ExpectedTy = S.Context.getUIntPtrType();
1811
1812 } else {
1813 // Diagnose the failures.
1814 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1815 << unsigned(OpKind == PAO_Discriminator ? 1
1816 : OpKind == PAO_BlendPointer ? 2
1817 : OpKind == PAO_BlendInteger ? 3
1818 : OpKind == PAO_BlendPC ? 4
1819 : 0)
1820 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1821 << Arg->getType() << Arg->getSourceRange();
1822 return true;
1823 }
1824
1825 // Convert to that type. This should just be an lvalue-to-rvalue
1826 // conversion.
1827 if (convertArgumentToType(S, Arg, ExpectedTy))
1828 return true;
1829
1830 if (!RequireConstant) {
1831 // Warn about null pointers for non-generic sign and auth operations.
1832 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1834 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1835 ? diag::warn_ptrauth_sign_null_pointer
1836 : diag::warn_ptrauth_auth_null_pointer)
1837 << Arg->getSourceRange();
1838 }
1839
1840 return false;
1841 }
1842
1843 // Perform special checking on the arguments to ptrauth_sign_constant.
1844
1845 // The main argument.
1846 if (OpKind == PAO_Sign) {
1847 // Require the value we're signing to have a special form.
1848 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1849 bool Invalid;
1850
1851 // Must be rooted in a declaration reference.
1852 if (!BaseDecl)
1853 Invalid = true;
1854
1855 // If it's a function declaration, we can't have an offset.
1856 else if (isa<FunctionDecl>(BaseDecl))
1857 Invalid = !Offset.isZero();
1858
1859 // Otherwise we're fine.
1860 else
1861 Invalid = false;
1862
1863 if (Invalid)
1864 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1865 return Invalid;
1866 }
1867
1868 // The discriminator argument.
1869 assert(OpKind == PAO_Discriminator);
1870
1871 // Must be a pointer or integer or blend thereof.
1872 Expr *Pointer = nullptr;
1873 Expr *Integer = nullptr;
1874 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1875 if (Call->getBuiltinCallee() ==
1876 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1877 Pointer = Call->getArg(0);
1878 Integer = Call->getArg(1);
1879 }
1880 }
1881 if (!Pointer && !Integer) {
1882 if (Arg->getType()->isPointerType())
1883 Pointer = Arg;
1884 else
1885 Integer = Arg;
1886 }
1887
1888 // Check the pointer.
1889 bool Invalid = false;
1890 if (Pointer) {
1891 assert(Pointer->getType()->isPointerType());
1892
1893 // TODO: if we're initializing a global, check that the address is
1894 // somehow related to what we're initializing. This probably will
1895 // never really be feasible and we'll have to catch it at link-time.
1896 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
1897 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
1898 Invalid = true;
1899 }
1900
1901 // Check the integer.
1902 if (Integer) {
1903 assert(Integer->getType()->isIntegerType());
1904 if (!Integer->isEvaluatable(S.Context))
1905 Invalid = true;
1906 }
1907
1908 if (Invalid)
1909 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
1910 return Invalid;
1911}
1912
1914 if (S.checkArgCount(Call, 2))
1915 return ExprError();
1917 return ExprError();
1918 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
1919 checkPointerAuthKey(S, Call->getArgs()[1]))
1920 return ExprError();
1921
1922 Call->setType(Call->getArgs()[0]->getType());
1923 return Call;
1924}
1925
1927 if (S.checkArgCount(Call, 2))
1928 return ExprError();
1930 return ExprError();
1931 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
1932 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
1933 return ExprError();
1934
1935 Call->setType(S.Context.getUIntPtrType());
1936 return Call;
1937}
1938
1940 if (S.checkArgCount(Call, 2))
1941 return ExprError();
1943 return ExprError();
1944 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
1945 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
1946 return ExprError();
1947
1948 Call->setType(S.Context.getUIntPtrType());
1949 return Call;
1950}
1951
1953 PointerAuthOpKind OpKind,
1954 bool RequireConstant) {
1955 if (S.checkArgCount(Call, 3))
1956 return ExprError();
1958 return ExprError();
1959 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
1960 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1961 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
1962 RequireConstant))
1963 return ExprError();
1964
1965 Call->setType(Call->getArgs()[0]->getType());
1966 return Call;
1967}
1968
1970 if (S.checkArgCount(Call, 5))
1971 return ExprError();
1973 return ExprError();
1974 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1975 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1976 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1977 checkPointerAuthKey(S, Call->getArgs()[3]) ||
1978 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
1979 return ExprError();
1980
1981 Call->setType(Call->getArgs()[0]->getType());
1982 return Call;
1983}
1984
1986 if (S.checkArgCount(Call, 6))
1987 return ExprError();
1989 return ExprError();
1990 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
1991 checkPointerAuthKey(S, Call->getArgs()[1]) ||
1992 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
1993 checkPointerAuthValue(S, Call->getArgs()[3], PAO_BlendPC) ||
1994 checkPointerAuthKey(S, Call->getArgs()[4]) ||
1995 checkPointerAuthValue(S, Call->getArgs()[5], PAO_Discriminator))
1996 return ExprError();
1997
1998 // Validate that the oldKey is IA or IB, not DA or DB.
1999 // This enforces the constraint that auth_with_pc_and_resign only supports
2000 // IA/IB keys for authentication, as only those keys support the PC-based
2001 // signing instructions (paciasppc/pacibsppc).
2002 unsigned OldKey = 0;
2003 if (!S.checkConstantPointerAuthKey(Call->getArgs()[1], OldKey)) {
2005 if (OldKey != static_cast<unsigned>(AK::ASIA) &&
2006 OldKey != static_cast<unsigned>(AK::ASIB)) {
2007 S.Diag(Call->getArgs()[1]->getExprLoc(),
2008 diag::err_ptrauth_auth_with_pc_and_resign_invalid_key)
2009 << OldKey << Call->getArgs()[1]->getSourceRange();
2010 return ExprError();
2011 }
2012 }
2013
2014 Call->setType(Call->getArgs()[0]->getType());
2015 return Call;
2016}
2017
2019 if (S.checkArgCount(Call, 6))
2020 return ExprError();
2022 return ExprError();
2023 const Expr *AddendExpr = Call->getArg(5);
2024 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(S.Context);
2025 if (!AddendIsConstInt) {
2026 const Expr *Arg = Call->getArg(5)->IgnoreParenImpCasts();
2027 DeclRefExpr *DRE = cast<DeclRefExpr>(Call->getCallee()->IgnoreParenCasts());
2028 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2029 S.Diag(Arg->getBeginLoc(), diag::err_constant_integer_last_arg_type)
2030 << FDecl->getDeclName() << Arg->getSourceRange();
2031 }
2032 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2033 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2034 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2035 checkPointerAuthKey(S, Call->getArgs()[3]) ||
2036 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator) ||
2037 !AddendIsConstInt)
2038 return ExprError();
2039
2040 Call->setType(Call->getArgs()[0]->getType());
2041 return Call;
2042}
2043
2046 return ExprError();
2047
2048 // We've already performed normal call type-checking.
2049 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
2050
2051 // Operand must be an ordinary or UTF-8 string literal.
2052 const auto *Literal = dyn_cast<StringLiteral>(Arg);
2053 if (!Literal || Literal->getCharByteWidth() != 1) {
2054 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
2055 << (Literal ? 1 : 0) << Arg->getSourceRange();
2056 return ExprError();
2057 }
2058
2059 return Call;
2060}
2061
2063 if (S.checkArgCount(Call, 1))
2064 return ExprError();
2065 Expr *FirstArg = Call->getArg(0);
2066 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
2067 if (FirstValue.isInvalid())
2068 return ExprError();
2069 Call->setArg(0, FirstValue.get());
2070 QualType FirstArgType = FirstArg->getType();
2071 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
2072 FirstArgType = S.Context.getDecayedType(FirstArgType);
2073
2074 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
2075 if (!FirstArgRecord) {
2076 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
2077 << /*isPolymorphic=*/0 << FirstArgType;
2078 return ExprError();
2079 }
2080 if (S.RequireCompleteType(
2081 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
2082 diag::err_get_vtable_pointer_requires_complete_type)) {
2083 return ExprError();
2084 }
2085
2086 if (!FirstArgRecord->isPolymorphic()) {
2087 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
2088 << /*isPolymorphic=*/1 << FirstArgRecord;
2089 return ExprError();
2090 }
2092 Call->setType(ReturnType);
2093 return Call;
2094}
2095
2097 if (S.checkArgCount(TheCall, 1))
2098 return ExprError();
2099
2100 // Compute __builtin_launder's parameter type from the argument.
2101 // The parameter type is:
2102 // * The type of the argument if it's not an array or function type,
2103 // Otherwise,
2104 // * The decayed argument type.
2105 QualType ParamTy = [&]() {
2106 QualType ArgTy = TheCall->getArg(0)->getType();
2107 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
2108 return S.Context.getPointerType(Ty->getElementType());
2109 if (ArgTy->isFunctionType()) {
2110 return S.Context.getPointerType(ArgTy);
2111 }
2112 return ArgTy;
2113 }();
2114
2115 TheCall->setType(ParamTy);
2116
2117 auto DiagSelect = [&]() -> std::optional<unsigned> {
2118 if (!ParamTy->isPointerType())
2119 return 0;
2120 if (ParamTy->isFunctionPointerType())
2121 return 1;
2122 if (ParamTy->isVoidPointerType())
2123 return 2;
2124 return std::optional<unsigned>{};
2125 }();
2126 if (DiagSelect) {
2127 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
2128 << *DiagSelect << TheCall->getSourceRange();
2129 return ExprError();
2130 }
2131
2132 // We either have an incomplete class type, or we have a class template
2133 // whose instantiation has not been forced. Example:
2134 //
2135 // template <class T> struct Foo { T value; };
2136 // Foo<int> *p = nullptr;
2137 // auto *d = __builtin_launder(p);
2138 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
2139 diag::err_incomplete_type))
2140 return ExprError();
2141
2142 assert(ParamTy->getPointeeType()->isObjectType() &&
2143 "Unhandled non-object pointer case");
2144
2145 InitializedEntity Entity =
2147 ExprResult Arg =
2148 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
2149 if (Arg.isInvalid())
2150 return ExprError();
2151 TheCall->setArg(0, Arg.get());
2152
2153 return TheCall;
2154}
2155
2157 if (S.checkArgCount(TheCall, 1))
2158 return ExprError();
2159
2161 if (Arg.isInvalid())
2162 return ExprError();
2163 QualType ParamTy = Arg.get()->getType();
2164 TheCall->setArg(0, Arg.get());
2165 TheCall->setType(S.Context.BoolTy);
2166
2167 // Only accept pointers to objects as arguments, which should have object
2168 // pointer or void pointer types.
2169 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2170 // LWG4138: Function pointer types not allowed
2171 if (PT->getPointeeType()->isFunctionType()) {
2172 S.Diag(TheCall->getArg(0)->getExprLoc(),
2173 diag::err_builtin_is_within_lifetime_invalid_arg)
2174 << 1;
2175 return ExprError();
2176 }
2177 // Disallow VLAs too since those shouldn't be able to
2178 // be a template parameter for `std::is_within_lifetime`
2179 if (PT->getPointeeType()->isVariableArrayType()) {
2180 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
2181 << 1 << "__builtin_is_within_lifetime";
2182 return ExprError();
2183 }
2184 } else {
2185 S.Diag(TheCall->getArg(0)->getExprLoc(),
2186 diag::err_builtin_is_within_lifetime_invalid_arg)
2187 << 0;
2188 return ExprError();
2189 }
2190 return TheCall;
2191}
2192
2194 if (S.checkArgCount(TheCall, 3))
2195 return ExprError();
2196
2197 QualType Dest = TheCall->getArg(0)->getType();
2198 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2199 S.Diag(TheCall->getArg(0)->getExprLoc(),
2200 diag::err_builtin_trivially_relocate_invalid_arg_type)
2201 << /*a pointer*/ 0;
2202 return ExprError();
2203 }
2204
2205 QualType T = Dest->getPointeeType();
2206 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
2207 diag::err_incomplete_type))
2208 return ExprError();
2209
2210 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2211 T->isIncompleteArrayType()) {
2212 S.Diag(TheCall->getArg(0)->getExprLoc(),
2213 diag::err_builtin_trivially_relocate_invalid_arg_type)
2214 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2215 return ExprError();
2216 }
2217
2218 TheCall->setType(Dest);
2219
2220 QualType Src = TheCall->getArg(1)->getType();
2221 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2222 S.Diag(TheCall->getArg(1)->getExprLoc(),
2223 diag::err_builtin_trivially_relocate_invalid_arg_type)
2224 << /*the same*/ 3;
2225 return ExprError();
2226 }
2227
2228 Expr *SizeExpr = TheCall->getArg(2);
2229 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2230 if (Size.isInvalid())
2231 return ExprError();
2232
2233 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2234 if (Size.isInvalid())
2235 return ExprError();
2236 SizeExpr = Size.get();
2237 TheCall->setArg(2, SizeExpr);
2238
2239 return TheCall;
2240}
2241
2242// Emit an error and return true if the current object format type is in the
2243// list of unsupported types.
2245 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2246 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2247 llvm::Triple::ObjectFormatType CurObjFormat =
2248 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2249 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2250 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2251 << TheCall->getSourceRange();
2252 return true;
2253 }
2254 return false;
2255}
2256
2257// Emit an error and return true if the current architecture is not in the list
2258// of supported architectures.
2259static bool
2261 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2262 llvm::Triple::ArchType CurArch =
2263 S.getASTContext().getTargetInfo().getTriple().getArch();
2264 if (llvm::is_contained(SupportedArchs, CurArch))
2265 return false;
2266 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2267 << TheCall->getSourceRange();
2268 return true;
2269}
2270
2271static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2272 SourceLocation CallSiteLoc);
2273
2274bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2275 CallExpr *TheCall) {
2276 switch (TI.getTriple().getArch()) {
2277 default:
2278 // Some builtins don't require additional checking, so just consider these
2279 // acceptable.
2280 return false;
2281 case llvm::Triple::arm:
2282 case llvm::Triple::armeb:
2283 case llvm::Triple::thumb:
2284 case llvm::Triple::thumbeb:
2285 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2286 case llvm::Triple::aarch64:
2287 case llvm::Triple::aarch64_32:
2288 case llvm::Triple::aarch64_be:
2289 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2290 case llvm::Triple::bpfeb:
2291 case llvm::Triple::bpfel:
2292 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2293 case llvm::Triple::dxil:
2294 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2295 case llvm::Triple::hexagon:
2296 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2297 case llvm::Triple::mips:
2298 case llvm::Triple::mipsel:
2299 case llvm::Triple::mips64:
2300 case llvm::Triple::mips64el:
2301 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2302 case llvm::Triple::spirv:
2303 case llvm::Triple::spirv32:
2304 case llvm::Triple::spirv64:
2305 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2306 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2307 return false;
2308 case llvm::Triple::systemz:
2309 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2310 case llvm::Triple::x86:
2311 case llvm::Triple::x86_64:
2312 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2313 case llvm::Triple::ppc:
2314 case llvm::Triple::ppcle:
2315 case llvm::Triple::ppc64:
2316 case llvm::Triple::ppc64le:
2317 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2318 case llvm::Triple::amdgpu:
2319 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(TI, BuiltinID, TheCall);
2320 case llvm::Triple::riscv32:
2321 case llvm::Triple::riscv64:
2322 case llvm::Triple::riscv32be:
2323 case llvm::Triple::riscv64be:
2324 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2325 case llvm::Triple::loongarch32:
2326 case llvm::Triple::loongarch64:
2327 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2328 TheCall);
2329 case llvm::Triple::wasm32:
2330 case llvm::Triple::wasm64:
2331 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2332 case llvm::Triple::nvptx:
2333 case llvm::Triple::nvptx64:
2334 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2335 }
2336}
2337
2339 return T->isDependentType() ||
2340 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2341}
2342
2343// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2344// not a valid type, emit an error message and return true. Otherwise return
2345// false.
2346static bool
2349 int ArgOrdinal) {
2350 clang::QualType EltTy =
2351 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2352 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2353 : ArgTy;
2354
2355 switch (ArgTyRestr) {
2357 if (!ArgTy->getAs<VectorType>() && !ArgTy->getAs<MatrixType>() &&
2358 !isValidMathElementType(ArgTy)) {
2359 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2360 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2361 << ArgTy;
2362 }
2363 break;
2365 if (!EltTy->isRealFloatingType()) {
2366 // FIXME: make diagnostic's wording correct for matrices
2367 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2368 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2369 << /* floating-point */ 1 << ArgTy;
2370 }
2371 break;
2373 if (!EltTy->isIntegerType()) {
2374 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2375 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2376 << /* no fp */ 0 << ArgTy;
2377 }
2378 break;
2380 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2381 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2382 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2383 << /* or fp */ 1 << ArgTy;
2384 }
2385 break;
2386 }
2387
2388 return false;
2389}
2390
2391/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2392/// This checks that the target supports the builtin and that the string
2393/// argument is constant and valid.
2394static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2395 const TargetInfo *AuxTI, unsigned BuiltinID) {
2396 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2397 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2398 "Expecting __builtin_cpu_...");
2399
2400 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2401 const TargetInfo *TheTI = &TI;
2402 auto SupportsBI = [=](const TargetInfo *TInfo) {
2403 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2404 (!IsCPUSupports && TInfo->supportsCpuIs()));
2405 };
2406 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2407 TheTI = AuxTI;
2408
2409 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2410 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2411 return S.Diag(TheCall->getBeginLoc(),
2412 TI.getTriple().isOSAIX()
2413 ? diag::err_builtin_aix_os_unsupported
2414 : diag::err_builtin_target_unsupported)
2415 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2416
2417 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2418 // Check if the argument is a string literal.
2419 if (!isa<StringLiteral>(Arg))
2420 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2421 << Arg->getSourceRange();
2422
2423 // Check the contents of the string.
2424 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2425 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2426 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2427 << Arg->getSourceRange();
2428 return false;
2429 }
2430 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2431 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2432 << Arg->getSourceRange();
2433 return false;
2434}
2435
2436/// Checks that __builtin_bswapg was called with a single argument, which is an
2437/// unsigned integer, and overrides the return value type to the integer type.
2438static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2439 if (S.checkArgCount(TheCall, 1))
2440 return true;
2441 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2442 if (ArgRes.isInvalid())
2443 return true;
2444
2445 Expr *Arg = ArgRes.get();
2446 TheCall->setArg(0, Arg);
2447 if (Arg->isTypeDependent())
2448 return false;
2449
2450 QualType ArgTy = Arg->getType();
2451
2452 if (!ArgTy->isIntegerType()) {
2453 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2454 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2455 << ArgTy;
2456 return true;
2457 }
2458 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2459 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2460 BT->getNumBits() != 1) {
2461 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2462 << ArgTy << BT->getNumBits();
2463 return true;
2464 }
2465 }
2466 TheCall->setType(ArgTy);
2467 return false;
2468}
2469
2470/// Checks that __builtin_bitreverseg was called with a single argument, which
2471/// is an integer
2472static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2473 if (S.checkArgCount(TheCall, 1))
2474 return true;
2475 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2476 if (ArgRes.isInvalid())
2477 return true;
2478
2479 Expr *Arg = ArgRes.get();
2480 TheCall->setArg(0, Arg);
2481 if (Arg->isTypeDependent())
2482 return false;
2483
2484 QualType ArgTy = Arg->getType();
2485
2486 if (!ArgTy->isIntegerType()) {
2487 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2488 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2489 << ArgTy;
2490 return true;
2491 }
2492 TheCall->setType(ArgTy);
2493 return false;
2494}
2495
2496/// Checks that __builtin_popcountg was called with a single argument, which is
2497/// an unsigned integer.
2498static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2499 if (S.checkArgCount(TheCall, 1))
2500 return true;
2501
2502 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2503 if (ArgRes.isInvalid())
2504 return true;
2505
2506 Expr *Arg = ArgRes.get();
2507 TheCall->setArg(0, Arg);
2508
2509 QualType ArgTy = Arg->getType();
2510
2511 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2512 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2513 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2514 << ArgTy;
2515 return true;
2516 }
2517 return false;
2518}
2519
2520/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2521/// argument and return either int, bool, or the argument type.
2522static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2523 QualType ReturnType) {
2524 if (S.checkArgCount(TheCall, 1))
2525 return true;
2526
2527 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2528 if (ArgRes.isInvalid())
2529 return true;
2530
2531 Expr *Arg = ArgRes.get();
2532 TheCall->setArg(0, Arg);
2533
2534 QualType ArgTy = Arg->getType();
2535 // C23 stdbit.h functions do not permit bool or enumeration types.
2536 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2537 return S.Diag(Arg->getBeginLoc(),
2538 diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2539 << 1 /*1st argument*/ << ArgTy;
2540 if (!ArgTy->isUnsignedIntegerType())
2541 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_invalid_arg_type)
2542 << 1 /*1st argument*/ << ArgTy;
2543
2544 // For builtins returning unsigned int, verify the argument's bit width fits.
2545 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2546 // produce a count that overflows the return type.
2547 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2548 uint64_t ArgWidth = S.Context.getIntWidth(ArgTy);
2549 uint64_t ReturnTypeWidth = S.Context.getIntWidth(S.Context.UnsignedIntTy);
2550 if (!llvm::isUIntN(ReturnTypeWidth, ArgWidth))
2551 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_result_overflow)
2552 << ArgTy;
2553 }
2554
2555 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2556 return false;
2557}
2558
2559/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2560/// an unsigned integer, and an optional second argument, which is promoted to
2561/// an 'int'.
2562static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2563 if (S.checkArgCountRange(TheCall, 1, 2))
2564 return true;
2565
2566 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2567 if (Arg0Res.isInvalid())
2568 return true;
2569
2570 Expr *Arg0 = Arg0Res.get();
2571 TheCall->setArg(0, Arg0);
2572
2573 QualType Arg0Ty = Arg0->getType();
2574
2575 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2576 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2577 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2578 << Arg0Ty;
2579 return true;
2580 }
2581
2582 if (TheCall->getNumArgs() > 1) {
2583 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2584 if (Arg1Res.isInvalid())
2585 return true;
2586
2587 Expr *Arg1 = Arg1Res.get();
2588 TheCall->setArg(1, Arg1);
2589
2590 QualType Arg1Ty = Arg1->getType();
2591
2592 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2593 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2594 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2595 return true;
2596 }
2597 }
2598
2599 return false;
2600}
2601
2603 unsigned ArgIndex;
2604 bool OnlyUnsigned;
2605
2607 QualType T) {
2608 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2609 << ArgIndex << /*scalar*/ 1
2610 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2611 << /*no fp*/ 0 << T;
2612 }
2613
2614public:
2615 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2616 : ContextualImplicitConverter(/*Suppress=*/false,
2617 /*SuppressConversion=*/true),
2618 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2619
2620 bool match(QualType T) override {
2621 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2622 }
2623
2625 QualType T) override {
2626 return emitError(S, Loc, T);
2627 }
2628
2630 QualType T) override {
2631 return emitError(S, Loc, T);
2632 }
2633
2635 QualType T,
2636 QualType ConvTy) override {
2637 return emitError(S, Loc, T);
2638 }
2639
2641 QualType ConvTy) override {
2642 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2643 }
2644
2646 QualType T) override {
2647 return emitError(S, Loc, T);
2648 }
2649
2651 QualType ConvTy) override {
2652 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2653 }
2654
2656 QualType T,
2657 QualType ConvTy) override {
2658 llvm_unreachable("conversion functions are permitted");
2659 }
2660};
2661
2662/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2663/// arguments, that the first argument is an unsigned integer type, and that
2664/// the second argument is an integer type.
2665static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2666 if (S.checkArgCount(TheCall, 2))
2667 return true;
2668
2669 // First argument (value to rotate) must be unsigned integer type.
2670 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2672 TheCall->getArg(0)->getBeginLoc(), TheCall->getArg(0), Arg0Converter);
2673 if (Arg0Res.isInvalid())
2674 return true;
2675
2676 Expr *Arg0 = Arg0Res.get();
2677 TheCall->setArg(0, Arg0);
2678
2679 QualType Arg0Ty = Arg0->getType();
2680 if (!Arg0Ty->isUnsignedIntegerType())
2681 return true;
2682
2683 // Second argument (rotation count) must be integer type.
2684 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2686 TheCall->getArg(1)->getBeginLoc(), TheCall->getArg(1), Arg1Converter);
2687 if (Arg1Res.isInvalid())
2688 return true;
2689
2690 Expr *Arg1 = Arg1Res.get();
2691 TheCall->setArg(1, Arg1);
2692
2693 QualType Arg1Ty = Arg1->getType();
2694 if (!Arg1Ty->isIntegerType())
2695 return true;
2696
2697 TheCall->setType(Arg0Ty);
2698 return false;
2699}
2700
2701static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2702 unsigned Pos, bool AllowConst,
2703 bool AllowAS) {
2704 QualType MaskTy = MaskArg->getType();
2705 if (!MaskTy->isExtVectorBoolType())
2706 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2707 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2708 << MaskTy;
2709
2710 QualType PtrTy = PtrArg->getType();
2711 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2712 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2713 << Pos << "scalar pointer";
2714
2715 QualType PointeeTy = PtrTy->getPointeeType();
2716 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2717 (!AllowConst && PointeeTy.isConstQualified()) ||
2718 (!AllowAS && PointeeTy.hasAddressSpace())) {
2721 return S.Diag(PtrArg->getExprLoc(),
2722 diag::err_typecheck_convert_incompatible)
2723 << PtrTy << Target << /*different qualifiers=*/5
2724 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2725 << PtrTy << Target;
2726 }
2727 return false;
2728}
2729
2730static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2731 bool TypeDependent = false;
2732 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2733 ExprResult Converted =
2735 if (Converted.isInvalid())
2736 return true;
2737 TheCall->setArg(Arg, Converted.get());
2738 TypeDependent |= Converted.get()->isTypeDependent();
2739 }
2740
2741 if (TypeDependent)
2742 TheCall->setType(S.Context.DependentTy);
2743 return false;
2744}
2745
2747 if (S.checkArgCountRange(TheCall, 2, 3))
2748 return ExprError();
2749
2750 if (ConvertMaskedBuiltinArgs(S, TheCall))
2751 return ExprError();
2752
2753 Expr *MaskArg = TheCall->getArg(0);
2754 Expr *PtrArg = TheCall->getArg(1);
2755 if (TheCall->isTypeDependent())
2756 return TheCall;
2757
2758 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2759 TheCall->getBuiltinCallee() ==
2760 Builtin::BI__builtin_masked_load))
2761 return ExprError();
2762
2763 QualType MaskTy = MaskArg->getType();
2764 QualType PtrTy = PtrArg->getType();
2765 QualType PointeeTy = PtrTy->getPointeeType();
2766 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2767
2769 MaskVecTy->getNumElements());
2770 if (TheCall->getNumArgs() == 3) {
2771 Expr *PassThruArg = TheCall->getArg(2);
2772 QualType PassThruTy = PassThruArg->getType();
2773 if (!S.Context.hasSameType(PassThruTy, RetTy))
2774 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2775 << /* third argument */ 3 << RetTy;
2776 }
2777
2778 TheCall->setType(RetTy);
2779 return TheCall;
2780}
2781
2783 if (S.checkArgCount(TheCall, 3))
2784 return ExprError();
2785
2786 if (ConvertMaskedBuiltinArgs(S, TheCall))
2787 return ExprError();
2788
2789 Expr *MaskArg = TheCall->getArg(0);
2790 Expr *ValArg = TheCall->getArg(1);
2791 Expr *PtrArg = TheCall->getArg(2);
2792 if (TheCall->isTypeDependent())
2793 return TheCall;
2794
2795 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2796 TheCall->getBuiltinCallee() ==
2797 Builtin::BI__builtin_masked_store))
2798 return ExprError();
2799
2800 QualType MaskTy = MaskArg->getType();
2801 QualType PtrTy = PtrArg->getType();
2802 QualType ValTy = ValArg->getType();
2803 if (!ValTy->isVectorType())
2804 return ExprError(
2805 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2806 << 2 << "vector");
2807
2808 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2809 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2810
2811 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2812 return ExprError(
2813 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2815 TheCall->getBuiltinCallee())
2816 << MaskTy << ValTy);
2817 }
2818
2819 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2820 PtrTy->getPointeeType().getUnqualifiedType()))
2821 return ExprError(S.Diag(TheCall->getBeginLoc(),
2822 diag::err_vec_builtin_incompatible_vector)
2823 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2824 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2825 TheCall->getArg(1)->getEndLoc()));
2826
2827 TheCall->setType(S.Context.VoidTy);
2828 return TheCall;
2829}
2830
2832 if (S.checkArgCountRange(TheCall, 3, 4))
2833 return ExprError();
2834
2835 if (ConvertMaskedBuiltinArgs(S, TheCall))
2836 return ExprError();
2837
2838 Expr *MaskArg = TheCall->getArg(0);
2839 Expr *IdxArg = TheCall->getArg(1);
2840 Expr *PtrArg = TheCall->getArg(2);
2841 if (TheCall->isTypeDependent())
2842 return TheCall;
2843
2844 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2845 /*AllowAS=*/true))
2846 return ExprError();
2847
2848 QualType IdxTy = IdxArg->getType();
2849 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2850 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2851 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2852 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2853 << IdxTy;
2854
2855 QualType MaskTy = MaskArg->getType();
2856 QualType PtrTy = PtrArg->getType();
2857 QualType PointeeTy = PtrTy->getPointeeType();
2858 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2859 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2860 return ExprError(
2861 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2863 TheCall->getBuiltinCallee())
2864 << MaskTy << IdxTy);
2865
2867 MaskVecTy->getNumElements());
2868 if (TheCall->getNumArgs() == 4) {
2869 Expr *PassThruArg = TheCall->getArg(3);
2870 QualType PassThruTy = PassThruArg->getType();
2871 if (!S.Context.hasSameType(PassThruTy, RetTy))
2872 return S.Diag(PassThruArg->getExprLoc(),
2873 diag::err_vec_masked_load_store_ptr)
2874 << /* fourth argument */ 4 << RetTy;
2875 }
2876
2877 TheCall->setType(RetTy);
2878 return TheCall;
2879}
2880
2882 if (S.checkArgCount(TheCall, 4))
2883 return ExprError();
2884
2885 if (ConvertMaskedBuiltinArgs(S, TheCall))
2886 return ExprError();
2887
2888 Expr *MaskArg = TheCall->getArg(0);
2889 Expr *IdxArg = TheCall->getArg(1);
2890 Expr *ValArg = TheCall->getArg(2);
2891 Expr *PtrArg = TheCall->getArg(3);
2892 if (TheCall->isTypeDependent())
2893 return TheCall;
2894
2895 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
2896 /*AllowAS=*/true))
2897 return ExprError();
2898
2899 QualType IdxTy = IdxArg->getType();
2900 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2901 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2902 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2903 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2904 << IdxTy;
2905
2906 QualType ValTy = ValArg->getType();
2907 QualType MaskTy = MaskArg->getType();
2908 QualType PtrTy = PtrArg->getType();
2909
2910 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2911 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2912 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2913 return ExprError(
2914 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2916 TheCall->getBuiltinCallee())
2917 << MaskTy << IdxTy);
2918 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2919 return ExprError(
2920 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2922 TheCall->getBuiltinCallee())
2923 << MaskTy << ValTy);
2924
2925 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2926 PtrTy->getPointeeType().getUnqualifiedType()))
2927 return ExprError(S.Diag(TheCall->getBeginLoc(),
2928 diag::err_vec_builtin_incompatible_vector)
2929 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2930 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2931 TheCall->getArg(1)->getEndLoc()));
2932
2933 TheCall->setType(S.Context.VoidTy);
2934 return TheCall;
2935}
2936
2938 SourceLocation Loc = TheCall->getBeginLoc();
2939 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2940 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2941
2942 if (Args.size() == 0) {
2943 S.Diag(TheCall->getBeginLoc(),
2944 diag::err_typecheck_call_too_few_args_at_least)
2945 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2946 << /*is_non_object=*/0 << TheCall->getSourceRange();
2947 return ExprError();
2948 }
2949
2950 QualType FuncT = Args[0]->getType();
2951
2952 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2953 if (Args.size() < 2) {
2954 S.Diag(TheCall->getBeginLoc(),
2955 diag::err_typecheck_call_too_few_args_at_least)
2956 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2957 << /*is_non_object=*/0 << TheCall->getSourceRange();
2958 return ExprError();
2959 }
2960
2961 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2962 QualType ObjectT = Args[1]->getType();
2963
2964 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
2965 return ExprError();
2966
2967 ExprResult ObjectArg = [&]() -> ExprResult {
2968 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2969 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2970 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2971 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2972 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2973 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2974 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
2975 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
2976 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
2977 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
2978 return Args[1];
2979 }
2980
2981 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2982 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2983 // reference_wrapper;
2984 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2985 if (RD->isInStdNamespace() &&
2986 RD->getDeclName().getAsString() == "reference_wrapper") {
2987 CXXScopeSpec SS;
2988 IdentifierInfo *GetName = &S.Context.Idents.get("get");
2989 UnqualifiedId GetID;
2990 GetID.setIdentifier(GetName, Loc);
2991
2993 S.getCurScope(), Args[1], Loc, tok::period, SS,
2994 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
2995
2996 if (MemExpr.isInvalid())
2997 return ExprError();
2998
2999 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
3000 }
3001 }
3002
3003 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
3004 // class T and t1 does not satisfy the previous two items;
3005
3006 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
3007 }();
3008
3009 if (ObjectArg.isInvalid())
3010 return ExprError();
3011
3012 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
3013 tok::periodstar, ObjectArg.get(), Args[0]);
3014 if (BinOp.isInvalid())
3015 return ExprError();
3016
3017 if (MPT->isMemberDataPointer())
3018 return BinOp;
3019
3020 // Give the synthesized expression a valid source range for diagnostics.
3021 auto *MemCall = new (S.Context)
3022 ParenExpr(TheCall->getBeginLoc(), TheCall->getRParenLoc(), BinOp.get());
3023
3024 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
3025 Args.drop_front(2), TheCall->getRParenLoc());
3026 }
3027 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
3028 Args.drop_front(), TheCall->getRParenLoc());
3029}
3030
3031// Performs a similar job to Sema::UsualUnaryConversions, but without any
3032// implicit promotion of integral/enumeration types.
3034 // First, convert to an r-value.
3036 if (Res.isInvalid())
3037 return ExprError();
3038
3039 // Promote floating-point types.
3040 return S.UsualUnaryFPConversions(Res.get());
3041}
3042
3044 if (const auto *TyA = VecTy->getAs<VectorType>())
3045 return TyA->getElementType();
3046 if (VecTy->isSizelessVectorType())
3047 return VecTy->getSizelessVectorEltType(Context);
3048 return QualType();
3049}
3050
3052Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3053 CallExpr *TheCall) {
3054 ExprResult TheCallResult(TheCall);
3055
3056 // Find out if any arguments are required to be integer constant expressions.
3057 unsigned ICEArguments = 0;
3059 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
3061 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
3062
3063 // If any arguments are required to be ICE's, check and diagnose.
3064 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
3065 // Skip arguments not required to be ICE's.
3066 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
3067
3068 llvm::APSInt Result;
3069 // If we don't have enough arguments, continue so we can issue better
3070 // diagnostic in checkArgCount(...)
3071 if (ArgNo < TheCall->getNumArgs() &&
3072 BuiltinConstantArg(TheCall, ArgNo, Result))
3073 return true;
3074 ICEArguments &= ~(1 << ArgNo);
3075 }
3076
3077 FPOptions FPO;
3078 switch (BuiltinID) {
3079 case Builtin::BI__builtin___get_unsafe_stack_start:
3080 case Builtin::BI__builtin___get_unsafe_stack_bottom:
3081 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3082 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3083 << "__safestack_get_unsafe_stack_bottom";
3084 break;
3085 case Builtin::BI__builtin___get_unsafe_stack_top:
3086 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3087 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3088 << "__safestack_get_unsafe_stack_top";
3089 break;
3090 case Builtin::BI__builtin___get_unsafe_stack_ptr:
3091 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3092 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3093 << "__safestack_get_unsafe_stack_ptr";
3094 break;
3095 case Builtin::BI__builtin_cpu_supports:
3096 case Builtin::BI__builtin_cpu_is:
3097 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
3098 Context.getAuxTargetInfo(), BuiltinID))
3099 return ExprError();
3100 break;
3101 case Builtin::BI__builtin_cpu_init:
3102 if (!Context.getTargetInfo().supportsCpuInit()) {
3103 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3104 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
3105 return ExprError();
3106 }
3107 break;
3108 case Builtin::BI__builtin___CFStringMakeConstantString:
3109 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
3110 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
3112 *this, BuiltinID, TheCall,
3113 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
3114 return ExprError();
3115 assert(TheCall->getNumArgs() == 1 &&
3116 "Wrong # arguments to builtin CFStringMakeConstantString");
3117 if (ObjC().CheckObjCString(TheCall->getArg(0)))
3118 return ExprError();
3119 break;
3120 case Builtin::BI__builtin_ms_va_start:
3121 case Builtin::BI__builtin_zos_va_start:
3122 case Builtin::BI__builtin_stdarg_start:
3123 case Builtin::BI__builtin_va_start:
3124 case Builtin::BI__builtin_c23_va_start:
3125 if (BuiltinVAStart(BuiltinID, TheCall))
3126 return ExprError();
3127 break;
3128 case Builtin::BI__va_start: {
3129 switch (Context.getTargetInfo().getTriple().getArch()) {
3130 case llvm::Triple::aarch64:
3131 case llvm::Triple::arm:
3132 case llvm::Triple::thumb:
3133 if (BuiltinVAStartARMMicrosoft(TheCall))
3134 return ExprError();
3135 break;
3136 default:
3137 if (BuiltinVAStart(BuiltinID, TheCall))
3138 return ExprError();
3139 break;
3140 }
3141 break;
3142 }
3143
3144 // The acquire, release, and no fence variants are ARM and AArch64 only.
3145 case Builtin::BI_interlockedbittestandset_acq:
3146 case Builtin::BI_interlockedbittestandset_rel:
3147 case Builtin::BI_interlockedbittestandset_nf:
3148 case Builtin::BI_interlockedbittestandreset_acq:
3149 case Builtin::BI_interlockedbittestandreset_rel:
3150 case Builtin::BI_interlockedbittestandreset_nf:
3152 *this, TheCall,
3153 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
3154 return ExprError();
3155 break;
3156
3157 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
3158 case Builtin::BI_bittest64:
3159 case Builtin::BI_bittestandcomplement64:
3160 case Builtin::BI_bittestandreset64:
3161 case Builtin::BI_bittestandset64:
3162 case Builtin::BI_interlockedbittestandreset64:
3163 case Builtin::BI_interlockedbittestandset64:
3165 *this, TheCall,
3166 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3167 llvm::Triple::aarch64, llvm::Triple::amdgpu}))
3168 return ExprError();
3169 break;
3170
3171 // The 64-bit acquire, release, and no fence variants are AArch64 only.
3172 case Builtin::BI_interlockedbittestandreset64_acq:
3173 case Builtin::BI_interlockedbittestandreset64_rel:
3174 case Builtin::BI_interlockedbittestandreset64_nf:
3175 case Builtin::BI_interlockedbittestandset64_acq:
3176 case Builtin::BI_interlockedbittestandset64_rel:
3177 case Builtin::BI_interlockedbittestandset64_nf:
3178 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
3179 return ExprError();
3180 break;
3181
3182 case Builtin::BI__builtin_set_flt_rounds:
3184 *this, TheCall,
3185 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3186 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgpu,
3187 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3188 llvm::Triple::ppc64le}))
3189 return ExprError();
3190 break;
3191
3192 case Builtin::BI__builtin_isgreater:
3193 case Builtin::BI__builtin_isgreaterequal:
3194 case Builtin::BI__builtin_isless:
3195 case Builtin::BI__builtin_islessequal:
3196 case Builtin::BI__builtin_islessgreater:
3197 case Builtin::BI__builtin_isunordered:
3198 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3199 return ExprError();
3200 break;
3201 case Builtin::BI__builtin_fpclassify:
3202 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
3203 return ExprError();
3204 break;
3205 case Builtin::BI__builtin_isfpclass:
3206 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
3207 return ExprError();
3208 break;
3209 case Builtin::BI__builtin_isfinite:
3210 case Builtin::BI__builtin_isinf:
3211 case Builtin::BI__builtin_isinf_sign:
3212 case Builtin::BI__builtin_isnan:
3213 case Builtin::BI__builtin_issignaling:
3214 case Builtin::BI__builtin_isnormal:
3215 case Builtin::BI__builtin_issubnormal:
3216 case Builtin::BI__builtin_iszero:
3217 case Builtin::BI__builtin_signbit:
3218 case Builtin::BI__builtin_signbitf:
3219 case Builtin::BI__builtin_signbitl:
3220 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
3221 return ExprError();
3222 break;
3223 case Builtin::BI__builtin_shufflevector:
3224 return BuiltinShuffleVector(TheCall);
3225 // TheCall will be freed by the smart pointer here, but that's fine, since
3226 // BuiltinShuffleVector guts it, but then doesn't release it.
3227 case Builtin::BI__builtin_masked_load:
3228 case Builtin::BI__builtin_masked_expand_load:
3229 return BuiltinMaskedLoad(*this, TheCall);
3230 case Builtin::BI__builtin_masked_store:
3231 case Builtin::BI__builtin_masked_compress_store:
3232 return BuiltinMaskedStore(*this, TheCall);
3233 case Builtin::BI__builtin_masked_gather:
3234 return BuiltinMaskedGather(*this, TheCall);
3235 case Builtin::BI__builtin_masked_scatter:
3236 return BuiltinMaskedScatter(*this, TheCall);
3237 case Builtin::BI__builtin_invoke:
3238 return BuiltinInvoke(*this, TheCall);
3239 case Builtin::BI__builtin_prefetch:
3240 if (BuiltinPrefetch(TheCall))
3241 return ExprError();
3242 break;
3243 case Builtin::BI__builtin_alloca_with_align:
3244 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3245 if (BuiltinAllocaWithAlign(TheCall))
3246 return ExprError();
3247 [[fallthrough]];
3248 case Builtin::BI__builtin_alloca:
3249 case Builtin::BI__builtin_alloca_uninitialized:
3250 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
3251 << TheCall->getDirectCallee();
3252 if (getLangOpts().OpenCL) {
3253 builtinAllocaAddrSpace(*this, TheCall);
3254 }
3255 break;
3256 case Builtin::BI__builtin_infer_alloc_token:
3257 if (checkBuiltinInferAllocToken(*this, TheCall))
3258 return ExprError();
3259 break;
3260 case Builtin::BI__arithmetic_fence:
3261 if (BuiltinArithmeticFence(TheCall))
3262 return ExprError();
3263 break;
3264 case Builtin::BI__assume:
3265 case Builtin::BI__builtin_assume:
3266 if (BuiltinAssume(TheCall))
3267 return ExprError();
3268 break;
3269 case Builtin::BI__builtin_assume_aligned:
3270 if (BuiltinAssumeAligned(TheCall))
3271 return ExprError();
3272 break;
3273 case Builtin::BI__builtin_dynamic_object_size:
3274 case Builtin::BI__builtin_object_size:
3275 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
3276 return ExprError();
3277 break;
3278 case Builtin::BI__builtin_longjmp:
3279 if (BuiltinLongjmp(TheCall))
3280 return ExprError();
3281 break;
3282 case Builtin::BI__builtin_setjmp:
3283 if (BuiltinSetjmp(TheCall))
3284 return ExprError();
3285 break;
3286 case Builtin::BI__builtin_complex:
3287 if (BuiltinComplex(TheCall))
3288 return ExprError();
3289 break;
3290 case Builtin::BI__builtin_classify_type:
3291 case Builtin::BI__builtin_constant_p: {
3292 if (checkArgCount(TheCall, 1))
3293 return true;
3295 if (Arg.isInvalid()) return true;
3296 TheCall->setArg(0, Arg.get());
3297 TheCall->setType(Context.IntTy);
3298 break;
3299 }
3300 case Builtin::BI__builtin_launder:
3301 return BuiltinLaunder(*this, TheCall);
3302 case Builtin::BI__builtin_is_within_lifetime:
3303 return BuiltinIsWithinLifetime(*this, TheCall);
3304 case Builtin::BI__builtin_trivially_relocate:
3305 return BuiltinTriviallyRelocate(*this, TheCall);
3306 case Builtin::BI__builtin_clear_padding: {
3307 if (checkArgCount(TheCall, 1))
3308 return ExprError();
3309
3310 const Expr *PtrArg = TheCall->getArg(0);
3311 const QualType PtrArgType = PtrArg->getType();
3312 if (!PtrArgType->isPointerType()) {
3313 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
3314 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3315 << "pointer";
3316 return ExprError();
3317 }
3318 QualType PointeeType = PtrArgType->getPointeeType();
3319 if (PointeeType.isConstQualified()) {
3320 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_assign_const)
3321 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3322 return ExprError();
3323 }
3324 if (RequireCompleteType(PtrArg->getBeginLoc(), PointeeType,
3325 diag::err_typecheck_decl_incomplete_type))
3326 return ExprError();
3327
3328 // For non trivially copyable types, we try to match gcc's behaviour.
3329 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3330 // object, either a local variable or a function parameter passed by value
3331 auto IsAddrOfDeclExpr = [&]() {
3332 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Context);
3333 const auto *UnaryOp = dyn_cast<UnaryOperator>(Inner);
3334 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3335 return false;
3336
3337 const Expr *Operand =
3338 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Context);
3339 const auto *DeclRef = dyn_cast<DeclRefExpr>(Operand);
3340 if (!DeclRef)
3341 return false;
3342
3343 const auto *VarDecl = dyn_cast<::clang::VarDecl>(DeclRef->getDecl());
3344 if (!VarDecl || VarDecl->getType()->isReferenceType())
3345 return false;
3346
3347 // matching GCC behaviour
3348 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3349 QualType VarQType = VarDecl->getType();
3350 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3351 Context.hasSameUnqualifiedType(PointeeType, VarQType);
3352 };
3353
3354 if (!PointeeType.isTriviallyCopyableType(Context) &&
3355 !PointeeType->isAtomicType() // _Atomic is not copyable
3356 && !IsAddrOfDeclExpr()) {
3357 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_needs_trivial_copy)
3358 << PtrArg->getType() << PtrArg->getSourceRange();
3359 return ExprError();
3360 }
3361
3362 if (auto *Record = PointeeType->getAsRecordDecl();
3364 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_no_flexible_array)
3365 << PointeeType << PtrArg->getSourceRange();
3366 return ExprError();
3367 }
3368
3369 break;
3370 }
3371 case Builtin::BI__sync_fetch_and_add:
3372 case Builtin::BI__sync_fetch_and_add_1:
3373 case Builtin::BI__sync_fetch_and_add_2:
3374 case Builtin::BI__sync_fetch_and_add_4:
3375 case Builtin::BI__sync_fetch_and_add_8:
3376 case Builtin::BI__sync_fetch_and_add_16:
3377 case Builtin::BI__sync_fetch_and_sub:
3378 case Builtin::BI__sync_fetch_and_sub_1:
3379 case Builtin::BI__sync_fetch_and_sub_2:
3380 case Builtin::BI__sync_fetch_and_sub_4:
3381 case Builtin::BI__sync_fetch_and_sub_8:
3382 case Builtin::BI__sync_fetch_and_sub_16:
3383 case Builtin::BI__sync_fetch_and_or:
3384 case Builtin::BI__sync_fetch_and_or_1:
3385 case Builtin::BI__sync_fetch_and_or_2:
3386 case Builtin::BI__sync_fetch_and_or_4:
3387 case Builtin::BI__sync_fetch_and_or_8:
3388 case Builtin::BI__sync_fetch_and_or_16:
3389 case Builtin::BI__sync_fetch_and_and:
3390 case Builtin::BI__sync_fetch_and_and_1:
3391 case Builtin::BI__sync_fetch_and_and_2:
3392 case Builtin::BI__sync_fetch_and_and_4:
3393 case Builtin::BI__sync_fetch_and_and_8:
3394 case Builtin::BI__sync_fetch_and_and_16:
3395 case Builtin::BI__sync_fetch_and_xor:
3396 case Builtin::BI__sync_fetch_and_xor_1:
3397 case Builtin::BI__sync_fetch_and_xor_2:
3398 case Builtin::BI__sync_fetch_and_xor_4:
3399 case Builtin::BI__sync_fetch_and_xor_8:
3400 case Builtin::BI__sync_fetch_and_xor_16:
3401 case Builtin::BI__sync_fetch_and_nand:
3402 case Builtin::BI__sync_fetch_and_nand_1:
3403 case Builtin::BI__sync_fetch_and_nand_2:
3404 case Builtin::BI__sync_fetch_and_nand_4:
3405 case Builtin::BI__sync_fetch_and_nand_8:
3406 case Builtin::BI__sync_fetch_and_nand_16:
3407 case Builtin::BI__sync_add_and_fetch:
3408 case Builtin::BI__sync_add_and_fetch_1:
3409 case Builtin::BI__sync_add_and_fetch_2:
3410 case Builtin::BI__sync_add_and_fetch_4:
3411 case Builtin::BI__sync_add_and_fetch_8:
3412 case Builtin::BI__sync_add_and_fetch_16:
3413 case Builtin::BI__sync_sub_and_fetch:
3414 case Builtin::BI__sync_sub_and_fetch_1:
3415 case Builtin::BI__sync_sub_and_fetch_2:
3416 case Builtin::BI__sync_sub_and_fetch_4:
3417 case Builtin::BI__sync_sub_and_fetch_8:
3418 case Builtin::BI__sync_sub_and_fetch_16:
3419 case Builtin::BI__sync_and_and_fetch:
3420 case Builtin::BI__sync_and_and_fetch_1:
3421 case Builtin::BI__sync_and_and_fetch_2:
3422 case Builtin::BI__sync_and_and_fetch_4:
3423 case Builtin::BI__sync_and_and_fetch_8:
3424 case Builtin::BI__sync_and_and_fetch_16:
3425 case Builtin::BI__sync_or_and_fetch:
3426 case Builtin::BI__sync_or_and_fetch_1:
3427 case Builtin::BI__sync_or_and_fetch_2:
3428 case Builtin::BI__sync_or_and_fetch_4:
3429 case Builtin::BI__sync_or_and_fetch_8:
3430 case Builtin::BI__sync_or_and_fetch_16:
3431 case Builtin::BI__sync_xor_and_fetch:
3432 case Builtin::BI__sync_xor_and_fetch_1:
3433 case Builtin::BI__sync_xor_and_fetch_2:
3434 case Builtin::BI__sync_xor_and_fetch_4:
3435 case Builtin::BI__sync_xor_and_fetch_8:
3436 case Builtin::BI__sync_xor_and_fetch_16:
3437 case Builtin::BI__sync_nand_and_fetch:
3438 case Builtin::BI__sync_nand_and_fetch_1:
3439 case Builtin::BI__sync_nand_and_fetch_2:
3440 case Builtin::BI__sync_nand_and_fetch_4:
3441 case Builtin::BI__sync_nand_and_fetch_8:
3442 case Builtin::BI__sync_nand_and_fetch_16:
3443 case Builtin::BI__sync_val_compare_and_swap:
3444 case Builtin::BI__sync_val_compare_and_swap_1:
3445 case Builtin::BI__sync_val_compare_and_swap_2:
3446 case Builtin::BI__sync_val_compare_and_swap_4:
3447 case Builtin::BI__sync_val_compare_and_swap_8:
3448 case Builtin::BI__sync_val_compare_and_swap_16:
3449 case Builtin::BI__sync_bool_compare_and_swap:
3450 case Builtin::BI__sync_bool_compare_and_swap_1:
3451 case Builtin::BI__sync_bool_compare_and_swap_2:
3452 case Builtin::BI__sync_bool_compare_and_swap_4:
3453 case Builtin::BI__sync_bool_compare_and_swap_8:
3454 case Builtin::BI__sync_bool_compare_and_swap_16:
3455 case Builtin::BI__sync_lock_test_and_set:
3456 case Builtin::BI__sync_lock_test_and_set_1:
3457 case Builtin::BI__sync_lock_test_and_set_2:
3458 case Builtin::BI__sync_lock_test_and_set_4:
3459 case Builtin::BI__sync_lock_test_and_set_8:
3460 case Builtin::BI__sync_lock_test_and_set_16:
3461 case Builtin::BI__sync_lock_release:
3462 case Builtin::BI__sync_lock_release_1:
3463 case Builtin::BI__sync_lock_release_2:
3464 case Builtin::BI__sync_lock_release_4:
3465 case Builtin::BI__sync_lock_release_8:
3466 case Builtin::BI__sync_lock_release_16:
3467 case Builtin::BI__sync_swap:
3468 case Builtin::BI__sync_swap_1:
3469 case Builtin::BI__sync_swap_2:
3470 case Builtin::BI__sync_swap_4:
3471 case Builtin::BI__sync_swap_8:
3472 case Builtin::BI__sync_swap_16:
3473 return BuiltinAtomicOverloaded(TheCallResult);
3474 case Builtin::BI__sync_synchronize:
3475 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3476 << TheCall->getCallee()->getSourceRange();
3477 break;
3478 case Builtin::BI__builtin_nontemporal_load:
3479 case Builtin::BI__builtin_nontemporal_store:
3480 return BuiltinNontemporalOverloaded(TheCallResult);
3481 case Builtin::BI__builtin_memcpy_inline: {
3482 clang::Expr *SizeOp = TheCall->getArg(2);
3483 // We warn about copying to or from `nullptr` pointers when `size` is
3484 // greater than 0. When `size` is value dependent we cannot evaluate its
3485 // value so we bail out.
3486 if (SizeOp->isValueDependent())
3487 break;
3488 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3489 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3490 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3491 }
3492 break;
3493 }
3494 case Builtin::BI__builtin_memset_inline: {
3495 clang::Expr *SizeOp = TheCall->getArg(2);
3496 // We warn about filling to `nullptr` pointers when `size` is greater than
3497 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3498 // out.
3499 if (SizeOp->isValueDependent())
3500 break;
3501 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3502 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3503 break;
3504 }
3505#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3506 case Builtin::BI##ID: \
3507 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3508#include "clang/Basic/Builtins.inc"
3509 case Builtin::BI__annotation: {
3510 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3511 if (!TT.isOSWindows() && !TT.isUEFI()) {
3512 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3513 << TheCall->getSourceRange();
3514 return ExprError();
3515 }
3516 if (BuiltinMSVCAnnotation(*this, TheCall))
3517 return ExprError();
3518 break;
3519 }
3520 case Builtin::BI__builtin_annotation:
3521 if (BuiltinAnnotation(*this, TheCall))
3522 return ExprError();
3523 break;
3524 case Builtin::BI__builtin_addressof:
3525 if (BuiltinAddressof(*this, TheCall))
3526 return ExprError();
3527 break;
3528 case Builtin::BI__builtin_function_start:
3529 if (BuiltinFunctionStart(*this, TheCall))
3530 return ExprError();
3531 break;
3532 case Builtin::BI__builtin_is_aligned:
3533 case Builtin::BI__builtin_align_up:
3534 case Builtin::BI__builtin_align_down:
3535 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3536 return ExprError();
3537 break;
3538 case Builtin::BI__builtin_add_overflow:
3539 case Builtin::BI__builtin_sub_overflow:
3540 case Builtin::BI__builtin_mul_overflow:
3541 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3542 return ExprError();
3543 break;
3544 case Builtin::BI__builtin_operator_new:
3545 case Builtin::BI__builtin_operator_delete: {
3546 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3547 ExprResult Res =
3548 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3549 return Res;
3550 }
3551 case Builtin::BI__builtin_dump_struct:
3552 return BuiltinDumpStruct(*this, TheCall);
3553 case Builtin::BI__builtin_expect_with_probability: {
3554 // We first want to ensure we are called with 3 arguments
3555 if (checkArgCount(TheCall, 3))
3556 return ExprError();
3557 // then check probability is constant float in range [0.0, 1.0]
3558 const Expr *ProbArg = TheCall->getArg(2);
3559 SmallVector<PartialDiagnosticAt, 8> Notes;
3560 Expr::EvalResult Eval;
3561 Eval.Diag = &Notes;
3562 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3563 !Eval.Val.isFloat()) {
3564 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3565 << ProbArg->getSourceRange();
3566 for (const PartialDiagnosticAt &PDiag : Notes)
3567 Diag(PDiag.first, PDiag.second);
3568 return ExprError();
3569 }
3570 llvm::APFloat Probability = Eval.Val.getFloat();
3571 bool LoseInfo = false;
3572 Probability.convert(llvm::APFloat::IEEEdouble(),
3573 llvm::RoundingMode::Dynamic, &LoseInfo);
3574 if (!(Probability >= llvm::APFloat(0.0) &&
3575 Probability <= llvm::APFloat(1.0))) {
3576 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3577 << ProbArg->getSourceRange();
3578 return ExprError();
3579 }
3580 break;
3581 }
3582 case Builtin::BI__builtin_preserve_access_index:
3583 if (BuiltinPreserveAI(*this, TheCall))
3584 return ExprError();
3585 break;
3586 case Builtin::BI__builtin_call_with_static_chain:
3587 if (BuiltinCallWithStaticChain(*this, TheCall))
3588 return ExprError();
3589 break;
3590 case Builtin::BI__exception_code:
3591 case Builtin::BI_exception_code:
3592 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3593 diag::err_seh___except_block))
3594 return ExprError();
3595 break;
3596 case Builtin::BI__exception_info:
3597 case Builtin::BI_exception_info:
3598 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3599 diag::err_seh___except_filter))
3600 return ExprError();
3601 break;
3602 case Builtin::BI__GetExceptionInfo:
3603 if (checkArgCount(TheCall, 1))
3604 return ExprError();
3605
3607 TheCall->getBeginLoc(),
3608 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3609 TheCall))
3610 return ExprError();
3611
3612 TheCall->setType(Context.VoidPtrTy);
3613 break;
3614 case Builtin::BIaddressof:
3615 case Builtin::BI__addressof:
3616 case Builtin::BIforward:
3617 case Builtin::BIforward_like:
3618 case Builtin::BImove:
3619 case Builtin::BImove_if_noexcept:
3620 case Builtin::BIas_const: {
3621 // These are all expected to be of the form
3622 // T &/&&/* f(U &/&&)
3623 // where T and U only differ in qualification.
3624 if (checkArgCount(TheCall, 1))
3625 return ExprError();
3626 QualType Param = FDecl->getParamDecl(0)->getType();
3627 QualType Result = FDecl->getReturnType();
3628 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3629 BuiltinID == Builtin::BI__addressof;
3630 if (!(Param->isReferenceType() &&
3631 (ReturnsPointer ? Result->isAnyPointerType()
3632 : Result->isReferenceType()) &&
3633 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3634 Result->getPointeeType()))) {
3635 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3636 << FDecl;
3637 return ExprError();
3638 }
3639 break;
3640 }
3641 case Builtin::BI__builtin_ptrauth_strip:
3642 return PointerAuthStrip(*this, TheCall);
3643 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3644 return PointerAuthBlendDiscriminator(*this, TheCall);
3645 case Builtin::BI__builtin_ptrauth_sign_constant:
3646 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3647 /*RequireConstant=*/true);
3648 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3649 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3650 /*RequireConstant=*/false);
3651 case Builtin::BI__builtin_ptrauth_auth:
3652 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3653 /*RequireConstant=*/false);
3654 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3655 return PointerAuthSignGenericData(*this, TheCall);
3656 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3657 return PointerAuthAuthAndResign(*this, TheCall);
3658 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
3659 return PointerAuthAuthWithPCAndResign(*this, TheCall);
3660 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3661 return PointerAuthAuthLoadRelativeAndSign(*this, TheCall);
3662 case Builtin::BI__builtin_ptrauth_string_discriminator:
3663 return PointerAuthStringDiscriminator(*this, TheCall);
3664
3665 case Builtin::BI__builtin_get_vtable_pointer:
3666 return GetVTablePointer(*this, TheCall);
3667
3668 // OpenCL v2.0, s6.13.16 - Pipe functions
3669 case Builtin::BIread_pipe:
3670 case Builtin::BIwrite_pipe:
3671 // Since those two functions are declared with var args, we need a semantic
3672 // check for the argument.
3673 if (OpenCL().checkBuiltinRWPipe(TheCall))
3674 return ExprError();
3675 break;
3676 case Builtin::BIreserve_read_pipe:
3677 case Builtin::BIreserve_write_pipe:
3678 case Builtin::BIwork_group_reserve_read_pipe:
3679 case Builtin::BIwork_group_reserve_write_pipe:
3680 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3681 return ExprError();
3682 break;
3683 case Builtin::BIsub_group_reserve_read_pipe:
3684 case Builtin::BIsub_group_reserve_write_pipe:
3685 if (OpenCL().checkSubgroupExt(TheCall) ||
3686 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3687 return ExprError();
3688 break;
3689 case Builtin::BIcommit_read_pipe:
3690 case Builtin::BIcommit_write_pipe:
3691 case Builtin::BIwork_group_commit_read_pipe:
3692 case Builtin::BIwork_group_commit_write_pipe:
3693 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3694 return ExprError();
3695 break;
3696 case Builtin::BIsub_group_commit_read_pipe:
3697 case Builtin::BIsub_group_commit_write_pipe:
3698 if (OpenCL().checkSubgroupExt(TheCall) ||
3699 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3700 return ExprError();
3701 break;
3702 case Builtin::BIget_pipe_num_packets:
3703 case Builtin::BIget_pipe_max_packets:
3704 if (OpenCL().checkBuiltinPipePackets(TheCall))
3705 return ExprError();
3706 break;
3707 case Builtin::BIto_global:
3708 case Builtin::BIto_local:
3709 case Builtin::BIto_private:
3710 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3711 return ExprError();
3712 break;
3713 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3714 case Builtin::BIenqueue_kernel:
3715 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3716 return ExprError();
3717 break;
3718 case Builtin::BIget_kernel_work_group_size:
3719 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3720 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3721 return ExprError();
3722 break;
3723 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3724 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3725 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3726 return ExprError();
3727 break;
3728 case Builtin::BI__builtin_os_log_format:
3729 Cleanup.setExprNeedsCleanups(true);
3730 [[fallthrough]];
3731 case Builtin::BI__builtin_os_log_format_buffer_size:
3732 if (BuiltinOSLogFormat(TheCall))
3733 return ExprError();
3734 break;
3735 case Builtin::BI__builtin_frame_address:
3736 case Builtin::BI__builtin_return_address: {
3737 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3738 return ExprError();
3739
3740 // -Wframe-address warning if non-zero passed to builtin
3741 // return/frame address.
3742 Expr::EvalResult Result;
3743 if (!TheCall->getArg(0)->isValueDependent() &&
3744 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3745 Result.Val.getInt() != 0)
3746 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3747 << ((BuiltinID == Builtin::BI__builtin_return_address)
3748 ? "__builtin_return_address"
3749 : "__builtin_frame_address")
3750 << TheCall->getSourceRange();
3751 break;
3752 }
3753
3754 case Builtin::BI__builtin_nondeterministic_value: {
3755 if (BuiltinNonDeterministicValue(TheCall))
3756 return ExprError();
3757 break;
3758 }
3759
3760 // __builtin_elementwise_abs restricts the element type to signed integers or
3761 // floating point types only.
3762 case Builtin::BI__builtin_elementwise_abs:
3765 return ExprError();
3766 break;
3767
3768 // These builtins restrict the element type to floating point
3769 // types only.
3770 case Builtin::BI__builtin_elementwise_acos:
3771 case Builtin::BI__builtin_elementwise_asin:
3772 case Builtin::BI__builtin_elementwise_atan:
3773 case Builtin::BI__builtin_elementwise_ceil:
3774 case Builtin::BI__builtin_elementwise_cos:
3775 case Builtin::BI__builtin_elementwise_cosh:
3776 case Builtin::BI__builtin_elementwise_exp:
3777 case Builtin::BI__builtin_elementwise_exp2:
3778 case Builtin::BI__builtin_elementwise_exp10:
3779 case Builtin::BI__builtin_elementwise_floor:
3780 case Builtin::BI__builtin_elementwise_log:
3781 case Builtin::BI__builtin_elementwise_log2:
3782 case Builtin::BI__builtin_elementwise_log10:
3783 case Builtin::BI__builtin_elementwise_roundeven:
3784 case Builtin::BI__builtin_elementwise_round:
3785 case Builtin::BI__builtin_elementwise_rint:
3786 case Builtin::BI__builtin_elementwise_nearbyint:
3787 case Builtin::BI__builtin_elementwise_sin:
3788 case Builtin::BI__builtin_elementwise_sinh:
3789 case Builtin::BI__builtin_elementwise_sqrt:
3790 case Builtin::BI__builtin_elementwise_tan:
3791 case Builtin::BI__builtin_elementwise_tanh:
3792 case Builtin::BI__builtin_elementwise_trunc:
3793 case Builtin::BI__builtin_elementwise_canonicalize:
3796 return ExprError();
3797 break;
3798 case Builtin::BI__builtin_elementwise_fma:
3799 if (BuiltinElementwiseTernaryMath(TheCall))
3800 return ExprError();
3801 break;
3802
3803 case Builtin::BI__builtin_elementwise_ldexp: {
3804 if (checkArgCount(TheCall, 2))
3805 return ExprError();
3806
3807 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3808 if (A.isInvalid())
3809 return ExprError();
3810 QualType TyA = A.get()->getType();
3811 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3813 return ExprError();
3814
3815 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3816 if (Exp.isInvalid())
3817 return ExprError();
3818 QualType TyExp = Exp.get()->getType();
3819 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3821 2))
3822 return ExprError();
3823
3824 // Check the two arguments are either scalars or vectors of equal length.
3825 const auto *Vec0 = TyA->getAs<VectorType>();
3826 const auto *Vec1 = TyExp->getAs<VectorType>();
3827 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3828 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3829 if (Arg0Length != Arg1Length) {
3830 Diag(Exp.get()->getBeginLoc(),
3831 diag::err_typecheck_vector_lengths_not_equal)
3832 << TyA << TyExp << A.get()->getSourceRange()
3833 << Exp.get()->getSourceRange();
3834 return ExprError();
3835 }
3836
3837 TheCall->setArg(0, A.get());
3838 TheCall->setArg(1, Exp.get());
3839 TheCall->setType(TyA);
3840 break;
3841 }
3842
3843 // These builtins restrict the element type to floating point
3844 // types only, and take in two arguments.
3845 case Builtin::BI__builtin_elementwise_minnum:
3846 case Builtin::BI__builtin_elementwise_maxnum:
3847 case Builtin::BI__builtin_elementwise_minimum:
3848 case Builtin::BI__builtin_elementwise_maximum:
3849 case Builtin::BI__builtin_elementwise_minimumnum:
3850 case Builtin::BI__builtin_elementwise_maximumnum:
3851 case Builtin::BI__builtin_elementwise_atan2:
3852 case Builtin::BI__builtin_elementwise_fmod:
3853 case Builtin::BI__builtin_elementwise_pow:
3854 if (BuiltinElementwiseMath(TheCall,
3856 return ExprError();
3857 break;
3858 // These builtins restrict the element type to integer
3859 // types only.
3860 case Builtin::BI__builtin_elementwise_add_sat:
3861 case Builtin::BI__builtin_elementwise_sub_sat:
3862 case Builtin::BI__builtin_elementwise_clmul:
3863 case Builtin::BI__builtin_elementwise_pext:
3864 case Builtin::BI__builtin_elementwise_pdep:
3865 if (BuiltinElementwiseMath(TheCall,
3867 return ExprError();
3868 break;
3869 case Builtin::BI__builtin_elementwise_fshl:
3870 case Builtin::BI__builtin_elementwise_fshr:
3873 return ExprError();
3874 break;
3875 case Builtin::BI__builtin_elementwise_min:
3876 case Builtin::BI__builtin_elementwise_max: {
3877 if (BuiltinElementwiseMath(TheCall))
3878 return ExprError();
3879 Expr *Arg0 = TheCall->getArg(0);
3880 Expr *Arg1 = TheCall->getArg(1);
3881 QualType Ty0 = Arg0->getType();
3882 QualType Ty1 = Arg1->getType();
3883 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3884 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3885 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3886 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3887 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3888 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin_no_suggestion)
3889 << Context.BuiltinInfo.getQuotedName(BuiltinID);
3890 break;
3891 }
3892 case Builtin::BI__builtin_elementwise_popcount:
3893 case Builtin::BI__builtin_elementwise_bitreverse:
3896 return ExprError();
3897 break;
3898 case Builtin::BI__builtin_elementwise_copysign: {
3899 if (checkArgCount(TheCall, 2))
3900 return ExprError();
3901
3902 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
3903 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
3904 if (Magnitude.isInvalid() || Sign.isInvalid())
3905 return ExprError();
3906
3907 QualType MagnitudeTy = Magnitude.get()->getType();
3908 QualType SignTy = Sign.get()->getType();
3910 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
3913 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
3915 return ExprError();
3916 }
3917
3918 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3919 return Diag(Sign.get()->getBeginLoc(),
3920 diag::err_typecheck_call_different_arg_types)
3921 << MagnitudeTy << SignTy;
3922 }
3923
3924 TheCall->setArg(0, Magnitude.get());
3925 TheCall->setArg(1, Sign.get());
3926 TheCall->setType(Magnitude.get()->getType());
3927 break;
3928 }
3929 case Builtin::BI__builtin_elementwise_clzg:
3930 case Builtin::BI__builtin_elementwise_ctzg:
3931 // These builtins can be unary or binary. Note for empty calls we call the
3932 // unary checker in order to not emit an error that says the function
3933 // expects 2 arguments, which would be misleading.
3934 if (TheCall->getNumArgs() <= 1) {
3937 return ExprError();
3938 } else if (BuiltinElementwiseMath(
3940 return ExprError();
3941 break;
3942 case Builtin::BI__builtin_reduce_max:
3943 case Builtin::BI__builtin_reduce_min: {
3944 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3945 return ExprError();
3946
3947 const Expr *Arg = TheCall->getArg(0);
3948 const auto *TyA = Arg->getType()->getAs<VectorType>();
3949
3950 QualType ElTy;
3951 if (TyA)
3952 ElTy = TyA->getElementType();
3953 else if (Arg->getType()->isSizelessVectorType())
3955
3956 if (ElTy.isNull()) {
3957 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3958 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3959 << Arg->getType();
3960 return ExprError();
3961 }
3962
3963 TheCall->setType(ElTy);
3964 break;
3965 }
3966 case Builtin::BI__builtin_reduce_maximum:
3967 case Builtin::BI__builtin_reduce_minimum: {
3968 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3969 return ExprError();
3970
3971 const Expr *Arg = TheCall->getArg(0);
3972 const auto *TyA = Arg->getType()->getAs<VectorType>();
3973
3974 QualType ElTy;
3975 if (TyA)
3976 ElTy = TyA->getElementType();
3977 else if (Arg->getType()->isSizelessVectorType())
3979
3980 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3981 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3982 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3983 << Arg->getType();
3984 return ExprError();
3985 }
3986
3987 TheCall->setType(ElTy);
3988 break;
3989 }
3990
3991 // These builtins support vectors of integers only.
3992 // TODO: ADD/MUL should support floating-point types.
3993 case Builtin::BI__builtin_reduce_add:
3994 case Builtin::BI__builtin_reduce_mul:
3995 case Builtin::BI__builtin_reduce_xor:
3996 case Builtin::BI__builtin_reduce_or:
3997 case Builtin::BI__builtin_reduce_and: {
3998 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3999 return ExprError();
4000
4001 const Expr *Arg = TheCall->getArg(0);
4002
4003 QualType ElTy = getVectorElementType(Context, Arg->getType());
4004 if (ElTy.isNull() || !ElTy->isIntegerType()) {
4005 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4006 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
4007 << Arg->getType();
4008 return ExprError();
4009 }
4010
4011 TheCall->setType(ElTy);
4012 break;
4013 }
4014
4015 case Builtin::BI__builtin_reduce_assoc_fadd:
4016 case Builtin::BI__builtin_reduce_in_order_fadd: {
4017 // For in-order reductions require the user to specify the start value.
4018 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
4019 if (InOrder ? checkArgCount(TheCall, 2) : checkArgCountRange(TheCall, 1, 2))
4020 return ExprError();
4021
4022 ExprResult Vec = UsualUnaryConversions(TheCall->getArg(0));
4023 if (Vec.isInvalid())
4024 return ExprError();
4025
4026 TheCall->setArg(0, Vec.get());
4027
4028 QualType ElTy = getVectorElementType(Context, Vec.get()->getType());
4029 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
4030 Diag(Vec.get()->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4031 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4032 << Vec.get()->getType();
4033 return ExprError();
4034 }
4035
4036 if (TheCall->getNumArgs() == 2) {
4037 ExprResult StartValue = UsualUnaryConversions(TheCall->getArg(1));
4038 if (StartValue.isInvalid())
4039 return ExprError();
4040
4041 if (!StartValue.get()->getType()->isRealFloatingType()) {
4042 Diag(StartValue.get()->getBeginLoc(),
4043 diag::err_builtin_invalid_arg_type)
4044 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
4045 << StartValue.get()->getType();
4046 return ExprError();
4047 }
4048 TheCall->setArg(1, StartValue.get());
4049 }
4050
4051 TheCall->setType(ElTy);
4052 break;
4053 }
4054
4055 case Builtin::BI__builtin_matrix_transpose:
4056 return BuiltinMatrixTranspose(TheCall, TheCallResult);
4057
4058 case Builtin::BI__builtin_matrix_column_major_load:
4059 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
4060
4061 case Builtin::BI__builtin_matrix_column_major_store:
4062 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
4063
4064 case Builtin::BI__builtin_verbose_trap:
4065 if (!checkBuiltinVerboseTrap(TheCall, *this))
4066 return ExprError();
4067 break;
4068
4069 case Builtin::BI__builtin_get_device_side_mangled_name: {
4070 auto Check = [](CallExpr *TheCall) {
4071 if (TheCall->getNumArgs() != 1)
4072 return false;
4073 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
4074 if (!DRE)
4075 return false;
4076 auto *D = DRE->getDecl();
4077 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
4078 return false;
4079 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4080 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
4081 };
4082 if (!Check(TheCall)) {
4083 Diag(TheCall->getBeginLoc(),
4084 diag::err_hip_invalid_args_builtin_mangled_name);
4085 return ExprError();
4086 }
4087 break;
4088 }
4089 case Builtin::BI__builtin_bswapg:
4090 if (BuiltinBswapg(*this, TheCall))
4091 return ExprError();
4092 break;
4093 case Builtin::BI__builtin_bitreverseg:
4094 if (BuiltinBitreverseg(*this, TheCall))
4095 return ExprError();
4096 break;
4097 case Builtin::BI__builtin_popcountg:
4098 if (BuiltinPopcountg(*this, TheCall))
4099 return ExprError();
4100 break;
4101 case Builtin::BI__builtin_clzg:
4102 case Builtin::BI__builtin_ctzg:
4103 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
4104 return ExprError();
4105 break;
4106
4107 case Builtin::BI__builtin_stdc_rotate_left:
4108 case Builtin::BI__builtin_stdc_rotate_right:
4109 if (BuiltinRotateGeneric(*this, TheCall))
4110 return ExprError();
4111 break;
4112
4113 case Builtin::BI__builtin_stdc_memreverse8:
4114 case Builtin::BIstdc_memreverse8:
4115 case Builtin::BIstdc_memreverse8u8:
4116 case Builtin::BIstdc_memreverse8u16:
4117 case Builtin::BIstdc_memreverse8u32:
4118 case Builtin::BIstdc_memreverse8u64:
4119 if (Context.getTargetInfo().getCharWidth() != 8) {
4120 Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_char_bit_8)
4121 << TheCall->getDirectCallee()->getName();
4122 return ExprError();
4123 }
4124 break;
4125
4126 case Builtin::BI__builtin_stdc_bit_floor:
4127 case Builtin::BI__builtin_stdc_bit_ceil:
4128 if (BuiltinStdCBuiltin(*this, TheCall, QualType()))
4129 return ExprError();
4130 break;
4131 case Builtin::BI__builtin_stdc_has_single_bit:
4132 if (BuiltinStdCBuiltin(*this, TheCall, Context.BoolTy))
4133 return ExprError();
4134 break;
4135 case Builtin::BI__builtin_stdc_leading_zeros:
4136 case Builtin::BI__builtin_stdc_leading_ones:
4137 case Builtin::BI__builtin_stdc_trailing_zeros:
4138 case Builtin::BI__builtin_stdc_trailing_ones:
4139 case Builtin::BI__builtin_stdc_first_leading_zero:
4140 case Builtin::BI__builtin_stdc_first_leading_one:
4141 case Builtin::BI__builtin_stdc_first_trailing_zero:
4142 case Builtin::BI__builtin_stdc_first_trailing_one:
4143 case Builtin::BI__builtin_stdc_count_zeros:
4144 case Builtin::BI__builtin_stdc_count_ones:
4145 case Builtin::BI__builtin_stdc_bit_width:
4146 if (BuiltinStdCBuiltin(*this, TheCall, Context.UnsignedIntTy))
4147 return ExprError();
4148 break;
4149
4150 case Builtin::BI__builtin_allow_runtime_check: {
4151 Expr *Arg = TheCall->getArg(0);
4152 // Check if the argument is a string literal.
4154 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4155 << Arg->getSourceRange();
4156 return ExprError();
4157 }
4158 break;
4159 }
4160
4161 case Builtin::BI__builtin_allow_sanitize_check: {
4162 if (checkArgCount(TheCall, 1))
4163 return ExprError();
4164
4165 Expr *Arg = TheCall->getArg(0);
4166 // Check if the argument is a string literal.
4167 const StringLiteral *SanitizerName =
4168 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
4169 if (!SanitizerName) {
4170 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4171 << Arg->getSourceRange();
4172 return ExprError();
4173 }
4174 // Validate the sanitizer name.
4175 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
4176 .Cases({"address", "thread", "memory", "hwaddress",
4177 "kernel-address", "kernel-memory", "kernel-hwaddress"},
4178 true)
4179 .Default(false)) {
4180 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
4181 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
4182 << Arg->getSourceRange();
4183 return ExprError();
4184 }
4185 break;
4186 }
4187 case Builtin::BI__builtin_counted_by_ref:
4188 if (BuiltinCountedByRef(TheCall))
4189 return ExprError();
4190 break;
4191 }
4192
4193 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4194 return ExprError();
4195
4196 // Since the target specific builtins for each arch overlap, only check those
4197 // of the arch we are compiling for.
4198 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
4199 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
4200 assert(Context.getAuxTargetInfo() &&
4201 "Aux Target Builtin, but not an aux target?");
4202
4203 if (CheckTSBuiltinFunctionCall(
4204 *Context.getAuxTargetInfo(),
4205 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
4206 return ExprError();
4207 } else {
4208 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
4209 TheCall))
4210 return ExprError();
4211 }
4212 }
4213
4214 return TheCallResult;
4215}
4216
4217bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4218 llvm::APSInt Result;
4219 // We can't check the value of a dependent argument.
4220 Expr *Arg = TheCall->getArg(ArgNum);
4221 if (Arg->isTypeDependent() || Arg->isValueDependent())
4222 return false;
4223
4224 // Check constant-ness first.
4225 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4226 return true;
4227
4228 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4229 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4230 return false;
4231
4232 return Diag(TheCall->getBeginLoc(),
4233 diag::err_argument_not_contiguous_bit_field)
4234 << ArgNum << Arg->getSourceRange();
4235}
4236
4237bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4238 unsigned FirstArg, FormatStringInfo *FSI) {
4239 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4240 bool IsVariadic = false;
4241 if (const FunctionType *FnTy = D->getFunctionType())
4242 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
4243 else if (const auto *BD = dyn_cast<BlockDecl>(D))
4244 IsVariadic = BD->isVariadic();
4245 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
4246 IsVariadic = OMD->isVariadic();
4247
4248 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4249 IsVariadic, FSI);
4250}
4251
4252bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4253 bool HasImplicitThisParam, bool IsVariadic,
4254 FormatStringInfo *FSI) {
4255 if (FirstArg == 0)
4257 else if (IsVariadic)
4259 else
4261 FSI->FormatIdx = FormatIdx - 1;
4262 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4263
4264 // The way the format attribute works in GCC, the implicit this argument
4265 // of member functions is counted. However, it doesn't appear in our own
4266 // lists, so decrement format_idx in that case.
4267 if (HasImplicitThisParam) {
4268 if(FSI->FormatIdx == 0)
4269 return false;
4270 --FSI->FormatIdx;
4271 if (FSI->FirstDataArg != 0)
4272 --FSI->FirstDataArg;
4273 }
4274 return true;
4275}
4276
4277/// Checks if a the given expression evaluates to null.
4278///
4279/// Returns true if the value evaluates to null.
4280static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4281 // Treat (smart) pointers constructed from nullptr as null, whether we can
4282 // const-evaluate them or not.
4283 // This must happen first: the smart pointer expr might have _Nonnull type!
4287 return true;
4288
4289 // If the expression has non-null type, it doesn't evaluate to null.
4290 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4291 if (*nullability == NullabilityKind::NonNull)
4292 return false;
4293 }
4294
4295 // As a special case, transparent unions initialized with zero are
4296 // considered null for the purposes of the nonnull attribute.
4297 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4298 UT &&
4299 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4300 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
4301 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
4302 Expr = ILE->getInit(0);
4303 }
4304
4305 bool Result;
4306 return (!Expr->isValueDependent() &&
4308 !Result);
4309}
4310
4312 const Expr *ArgExpr,
4313 SourceLocation CallSiteLoc) {
4314 if (CheckNonNullExpr(S, ArgExpr))
4315 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4316 S.PDiag(diag::warn_null_arg)
4317 << ArgExpr->getSourceRange());
4318}
4319
4320/// Determine whether the given type has a non-null nullability annotation.
4322 if (auto nullability = type->getNullability())
4323 return *nullability == NullabilityKind::NonNull;
4324
4325 return false;
4326}
4327
4329 const NamedDecl *FDecl,
4330 const FunctionProtoType *Proto,
4332 SourceLocation CallSiteLoc) {
4333 assert((FDecl || Proto) && "Need a function declaration or prototype");
4334
4335 // Already checked by constant evaluator.
4337 return;
4338 // Check the attributes attached to the method/function itself.
4339 llvm::SmallBitVector NonNullArgs;
4340 if (FDecl) {
4341 // Handle the nonnull attribute on the function/method declaration itself.
4342 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4343 if (!NonNull->args_size()) {
4344 // Easy case: all pointer arguments are nonnull.
4345 for (const auto *Arg : Args)
4346 if (S.isValidPointerAttrType(Arg->getType()))
4347 CheckNonNullArgument(S, Arg, CallSiteLoc);
4348 return;
4349 }
4350
4351 for (const ParamIdx &Idx : NonNull->args()) {
4352 unsigned IdxAST = Idx.getASTIndex();
4353 if (IdxAST >= Args.size())
4354 continue;
4355 if (NonNullArgs.empty())
4356 NonNullArgs.resize(Args.size());
4357 NonNullArgs.set(IdxAST);
4358 }
4359 }
4360 }
4361
4362 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4363 // Handle the nonnull attribute on the parameters of the
4364 // function/method.
4366 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4367 parms = FD->parameters();
4368 else
4369 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4370
4371 unsigned ParamIndex = 0;
4372 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4373 I != E; ++I, ++ParamIndex) {
4374 const ParmVarDecl *PVD = *I;
4375 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
4376 if (NonNullArgs.empty())
4377 NonNullArgs.resize(Args.size());
4378
4379 NonNullArgs.set(ParamIndex);
4380 }
4381 }
4382 } else {
4383 // If we have a non-function, non-method declaration but no
4384 // function prototype, try to dig out the function prototype.
4385 if (!Proto) {
4386 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4387 QualType type = VD->getType().getNonReferenceType();
4388 if (auto pointerType = type->getAs<PointerType>())
4389 type = pointerType->getPointeeType();
4390 else if (auto blockType = type->getAs<BlockPointerType>())
4391 type = blockType->getPointeeType();
4392 // FIXME: data member pointers?
4393
4394 // Dig out the function prototype, if there is one.
4395 Proto = type->getAs<FunctionProtoType>();
4396 }
4397 }
4398
4399 // Fill in non-null argument information from the nullability
4400 // information on the parameter types (if we have them).
4401 if (Proto) {
4402 unsigned Index = 0;
4403 for (auto paramType : Proto->getParamTypes()) {
4404 if (isNonNullType(paramType)) {
4405 if (NonNullArgs.empty())
4406 NonNullArgs.resize(Args.size());
4407
4408 NonNullArgs.set(Index);
4409 }
4410
4411 ++Index;
4412 }
4413 }
4414 }
4415
4416 // Check for non-null arguments.
4417 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4418 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4419 if (NonNullArgs[ArgIndex])
4420 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
4421 }
4422}
4423
4424void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4425 StringRef ParamName, QualType ArgTy,
4426 QualType ParamTy) {
4427
4428 // If a function accepts a pointer or reference type
4429 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4430 return;
4431
4432 // If the parameter is a pointer type, get the pointee type for the
4433 // argument too. If the parameter is a reference type, don't try to get
4434 // the pointee type for the argument.
4435 if (ParamTy->isPointerType())
4436 ArgTy = ArgTy->getPointeeType();
4437
4438 // Remove reference or pointer
4439 ParamTy = ParamTy->getPointeeType();
4440
4441 // Find expected alignment, and the actual alignment of the passed object.
4442 // getTypeAlignInChars requires complete types
4443 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4444 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4445 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4446 return;
4447
4448 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4449 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4450
4451 // If the argument is less aligned than the parameter, there is a
4452 // potential alignment issue.
4453 if (ArgAlign < ParamAlign)
4454 Diag(Loc, diag::warn_param_mismatched_alignment)
4455 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4456 << ParamName << (FDecl != nullptr) << FDecl;
4457}
4458
4459void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4460 const Expr *ThisArg,
4462 if (!FD || Args.empty())
4463 return;
4464 auto GetArgAt = [&](int Idx) -> const Expr * {
4465 if (Idx == LifetimeCaptureByAttr::Global ||
4466 Idx == LifetimeCaptureByAttr::Unknown)
4467 return nullptr;
4468 if (IsMemberFunction && Idx == 0)
4469 return ThisArg;
4470 return Args[Idx - IsMemberFunction];
4471 };
4472 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4473 unsigned ArgIdx) {
4474 if (!Attr)
4475 return;
4476
4477 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4478 for (int CapturingParamIdx : Attr->params()) {
4479 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4480 continue;
4481 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4482 // initialization codepath.
4483 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4485 continue;
4486 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4487 CapturingEntity CE{Capturing};
4488 // Ensure that 'Captured' outlives the 'Capturing' entity.
4489 checkCaptureByLifetime(*this, CE, Captured);
4490 }
4491 };
4492 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4493 for (const auto *A :
4494 FD->getParamDecl(I)->specific_attrs<LifetimeCaptureByAttr>())
4495 HandleCaptureByAttr(A, I + IsMemberFunction);
4496 // Check when the implicit object param is captured.
4497 if (IsMemberFunction) {
4498 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4499 if (!TSI)
4500 return;
4502 for (TypeLoc TL = TSI->getTypeLoc();
4503 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4504 TL = ATL.getModifiedLoc())
4505 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4506 }
4507}
4508
4510 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4511 bool IsMemberFunction, SourceLocation Loc,
4512 SourceRange Range, VariadicCallType CallType) {
4513
4514 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4515 llvm::any_of(Args, [](const Expr *E) {
4516 return E && E->isInstantiationDependent();
4517 }))
4518 return;
4519
4520 // Printf and scanf checking.
4521 llvm::SmallBitVector CheckedVarArgs;
4522 if (FDecl) {
4523 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4524 // Only create vector if there are format attributes.
4525 CheckedVarArgs.resize(Args.size());
4526 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4527 CheckedVarArgs);
4528 }
4529
4530 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4531 CheckedVarArgs.resize(Args.size());
4532 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4533 CheckedVarArgs);
4534 }
4535 }
4536
4537 // Refuse POD arguments that weren't caught by the format string
4538 // checks above.
4539 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4540 if (CallType != VariadicCallType::DoesNotApply &&
4541 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4542 unsigned NumParams = Proto ? Proto->getNumParams()
4543 : isa_and_nonnull<FunctionDecl>(FDecl)
4544 ? cast<FunctionDecl>(FDecl)->getNumParams()
4545 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4546 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4547 : 0;
4548
4549 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4550 // Args[ArgIdx] can be null in malformed code.
4551 if (const Expr *Arg = Args[ArgIdx]) {
4552 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4553 checkVariadicArgument(Arg, CallType);
4554 }
4555 }
4556 }
4557 if (FD)
4558 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4559 if (FDecl || Proto) {
4560 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4561
4562 // Type safety checking.
4563 if (FDecl) {
4564 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4565 CheckArgumentWithTypeTag(I, Args, Loc);
4566 }
4567 }
4568
4569 // Check that passed arguments match the alignment of original arguments.
4570 // Try to get the missing prototype from the declaration.
4571 if (!Proto && FDecl) {
4572 const auto *FT = FDecl->getFunctionType();
4573 if (isa_and_nonnull<FunctionProtoType>(FT))
4574 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4575 }
4576 if (Proto) {
4577 // For variadic functions, we may have more args than parameters.
4578 // For some K&R functions, we may have less args than parameters.
4579 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4580 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4581 bool IsScalableArg = false;
4582 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4583 // Args[ArgIdx] can be null in malformed code.
4584 if (const Expr *Arg = Args[ArgIdx]) {
4585 if (Arg->containsErrors())
4586 continue;
4587
4588 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4589 FDecl->hasLinkage() &&
4590 FDecl->getFormalLinkage() != Linkage::Internal &&
4592 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4593
4594 QualType ParamTy = Proto->getParamType(ArgIdx);
4595 if (ParamTy->isSizelessVectorType())
4596 IsScalableArg = true;
4597 QualType ArgTy = Arg->getType();
4598 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4599 ArgTy, ParamTy);
4600 }
4601 }
4602
4603 // If the callee has an AArch64 SME attribute to indicate that it is an
4604 // __arm_streaming function, then the caller requires SME to be available.
4607 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4608 llvm::StringMap<bool> CallerFeatureMap;
4609 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4610 if (!CallerFeatureMap.contains("sme"))
4611 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4612 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4613 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4614 }
4615 }
4616
4617 // If the call requires a streaming-mode change and has scalable vector
4618 // arguments or return values, then warn the user that the streaming and
4619 // non-streaming vector lengths may be different.
4620 // When both streaming and non-streaming vector lengths are defined and
4621 // mismatched, produce an error.
4622 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4623 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4624 (IsScalableArg || IsScalableRet)) {
4625 bool IsCalleeStreaming =
4627 bool IsCalleeStreamingCompatible =
4628 ExtInfo.AArch64SMEAttributes &
4630 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4631 if (!IsCalleeStreamingCompatible &&
4632 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4633 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4634 const LangOptions &LO = getLangOpts();
4635 unsigned VL = LO.VScaleMin * 128;
4636 unsigned SVL = LO.VScaleStreamingMin * 128;
4637 bool IsVLMismatch = VL && SVL && VL != SVL;
4638
4639 auto EmitDiag = [&](bool IsArg) {
4640 if (IsVLMismatch) {
4641 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4642 // Emit warning for streaming-compatible callers
4643 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4644 << IsArg << IsCalleeStreaming << SVL << VL;
4645 else
4646 // Emit error otherwise
4647 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4648 << IsArg << SVL << VL;
4649 } else
4650 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4651 << IsArg;
4652 };
4653
4654 if (IsScalableArg)
4655 EmitDiag(true);
4656 if (IsScalableRet)
4657 EmitDiag(false);
4658 }
4659 }
4660
4661 FunctionType::ArmStateValue CalleeArmZAState =
4663 FunctionType::ArmStateValue CalleeArmZT0State =
4665 if (CalleeArmZAState != FunctionType::ARM_None ||
4666 CalleeArmZT0State != FunctionType::ARM_None) {
4667 bool CallerHasZAState = false;
4668 bool CallerHasZT0State = false;
4669 if (CallerFD) {
4670 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4671 if (Attr && Attr->isNewZA())
4672 CallerHasZAState = true;
4673 if (Attr && Attr->isNewZT0())
4674 CallerHasZT0State = true;
4675 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4676 CallerHasZAState |=
4678 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4680 CallerHasZT0State |=
4682 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4684 }
4685 }
4686
4687 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4688 Diag(Loc, diag::err_sme_za_call_no_za_state);
4689
4690 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4691 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4692
4693 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4694 CalleeArmZT0State != FunctionType::ARM_None) {
4695 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4696 Diag(Loc, diag::note_sme_use_preserves_za);
4697 }
4698 }
4699 }
4700
4701 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4702 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4703 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4704 if (!Arg->isValueDependent()) {
4705 Expr::EvalResult Align;
4706 if (Arg->EvaluateAsInt(Align, Context)) {
4707 const llvm::APSInt &I = Align.Val.getInt();
4708 if (!I.isPowerOf2())
4709 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4710 << Arg->getSourceRange();
4711
4712 if (I > Sema::MaximumAlignment)
4713 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4714 << Arg->getSourceRange() << Sema::MaximumAlignment;
4715 }
4716 }
4717 }
4718
4719 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4721 SYCL().DiagIfDeviceCode(Loc, diag::err_variadic_device_fn)
4722 << diag::OffloadLang::SYCL;
4723
4724 if (FD)
4725 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4726}
4727
4728void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4729 if (TemplateDecl *Decl =
4730 AutoT->getTypeConstraintConcept().getAsTemplateDecl()) {
4731 DiagnoseUseOfDecl(Decl, Loc);
4732 }
4733}
4734
4735void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4737 const FunctionProtoType *Proto,
4738 SourceLocation Loc) {
4739 VariadicCallType CallType = Proto->isVariadic()
4742
4743 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4744 CheckArgAlignment(
4745 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4746 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4747
4748 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4749 Loc, SourceRange(), CallType);
4750}
4751
4753 const FunctionProtoType *Proto) {
4754 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4755 isa<CXXMethodDecl>(FDecl);
4756 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4757 IsMemberOperatorCall;
4758 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4759 TheCall->getCallee());
4760 Expr** Args = TheCall->getArgs();
4761 unsigned NumArgs = TheCall->getNumArgs();
4762
4763 Expr *ImplicitThis = nullptr;
4764 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4765 // If this is a call to a member operator, hide the first
4766 // argument from checkCall.
4767 // FIXME: Our choice of AST representation here is less than ideal.
4768 ImplicitThis = Args[0];
4769 ++Args;
4770 --NumArgs;
4771 } else if (IsMemberFunction && !FDecl->isStatic() &&
4773 ImplicitThis =
4774 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4775
4776 if (ImplicitThis) {
4777 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4778 // used.
4779 QualType ThisType = ImplicitThis->getType();
4780 if (!ThisType->isPointerType()) {
4781 assert(!ThisType->isReferenceType());
4782 ThisType = Context.getPointerType(ThisType);
4783 }
4784
4785 QualType ThisTypeFromDecl = Context.getPointerType(
4786 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4787
4788 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4789 ThisTypeFromDecl);
4790 }
4791
4792 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4793 IsMemberFunction, TheCall->getRParenLoc(),
4794 TheCall->getCallee()->getSourceRange(), CallType);
4795
4796 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4797 // None of the checks below are needed for functions that don't have
4798 // simple names (e.g., C++ conversion functions).
4799 if (!FnInfo)
4800 return false;
4801
4802 // Enforce TCB except for builtin calls, which are always allowed.
4803 if (FDecl->getBuiltinID() == 0)
4804 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4805
4806 CheckAbsoluteValueFunction(TheCall, FDecl);
4807 CheckMaxUnsignedZero(TheCall, FDecl);
4808 CheckInfNaNFunction(TheCall, FDecl);
4809
4810 if (getLangOpts().ObjC)
4811 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4812
4813 unsigned CMId = FDecl->getMemoryFunctionKind();
4814
4815 // Handle memory setting and copying functions.
4816 switch (CMId) {
4817 case 0:
4818 return false;
4819 case Builtin::BIstrlcpy: // fallthrough
4820 case Builtin::BIstrlcat:
4821 CheckStrlcpycatArguments(TheCall, FnInfo);
4822 break;
4823 case Builtin::BIstrncat:
4824 CheckStrncatArguments(TheCall, FnInfo);
4825 break;
4826 case Builtin::BIfree:
4827 CheckFreeArguments(TheCall);
4828 break;
4829 default:
4830 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4831 }
4832
4833 return false;
4834}
4835
4836bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4837 const FunctionProtoType *Proto) {
4838 QualType Ty;
4839 if (const auto *V = dyn_cast<VarDecl>(NDecl))
4840 Ty = V->getType().getNonReferenceType();
4841 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4842 Ty = F->getType().getNonReferenceType();
4843 else
4844 return false;
4845
4846 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4847 !Ty->isFunctionProtoType())
4848 return false;
4849
4850 VariadicCallType CallType;
4851 if (!Proto || !Proto->isVariadic()) {
4853 } else if (Ty->isBlockPointerType()) {
4854 CallType = VariadicCallType::Block;
4855 } else { // Ty->isFunctionPointerType()
4856 CallType = VariadicCallType::Function;
4857 }
4858
4859 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4860 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4861 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4862 TheCall->getCallee()->getSourceRange(), CallType);
4863
4864 return false;
4865}
4866
4867bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4868 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4869 TheCall->getCallee());
4870 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4871 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4872 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4873 TheCall->getCallee()->getSourceRange(), CallType);
4874
4875 return false;
4876}
4877
4878static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4879 if (!llvm::isValidAtomicOrderingCABI(Ordering))
4880 return false;
4881
4882 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4883 switch (Op) {
4884 case AtomicExpr::AO__c11_atomic_init:
4885 case AtomicExpr::AO__opencl_atomic_init:
4886 llvm_unreachable("There is no ordering argument for an init");
4887
4888 case AtomicExpr::AO__c11_atomic_load:
4889 case AtomicExpr::AO__opencl_atomic_load:
4890 case AtomicExpr::AO__hip_atomic_load:
4891 case AtomicExpr::AO__atomic_load_n:
4892 case AtomicExpr::AO__atomic_load:
4893 case AtomicExpr::AO__scoped_atomic_load_n:
4894 case AtomicExpr::AO__scoped_atomic_load:
4895 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4896 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4897
4898 case AtomicExpr::AO__c11_atomic_store:
4899 case AtomicExpr::AO__opencl_atomic_store:
4900 case AtomicExpr::AO__hip_atomic_store:
4901 case AtomicExpr::AO__atomic_store:
4902 case AtomicExpr::AO__atomic_store_n:
4903 case AtomicExpr::AO__scoped_atomic_store:
4904 case AtomicExpr::AO__scoped_atomic_store_n:
4905 case AtomicExpr::AO__atomic_clear:
4906 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4907 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4908 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4909
4910 default:
4911 return true;
4912 }
4913}
4914
4915ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4917 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4918 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4919 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4920 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4921 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4922 Op);
4923}
4924
4925/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
4926/// equivalents. Provide a fixit when the scope is a compile-time constant and
4927/// there is a direct mapping from the HIP builtin to a Clang builtin. The
4928/// compare_exchange builtins differ in how they accept the desired value, so
4929/// only a warning (without a fixit) is emitted for those.
4931 MultiExprArg Args,
4933 StringRef OldName;
4934 StringRef NewName;
4935 bool CanFixIt;
4936
4937 switch (Op) {
4938#define HIP_ATOMIC_FIXABLE(hip, scoped) \
4939 case AtomicExpr::AO__hip_atomic_##hip: \
4940 OldName = "__hip_atomic_" #hip; \
4941 NewName = "__scoped_atomic_" #scoped; \
4942 CanFixIt = true; \
4943 break;
4944 HIP_ATOMIC_FIXABLE(load, load_n)
4945 HIP_ATOMIC_FIXABLE(store, store_n)
4946 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
4947 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
4948 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
4949 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
4950 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
4951 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
4952 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
4953 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
4954#undef HIP_ATOMIC_FIXABLE
4955 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4956 OldName = "__hip_atomic_compare_exchange_weak";
4957 NewName = "__scoped_atomic_compare_exchange";
4958 CanFixIt = false;
4959 break;
4960 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4961 OldName = "__hip_atomic_compare_exchange_strong";
4962 NewName = "__scoped_atomic_compare_exchange";
4963 CanFixIt = false;
4964 break;
4965 default:
4966 llvm_unreachable("unhandled HIP atomic op");
4967 }
4968
4969 auto DB = S.Diag(ExprRange.getBegin(), diag::warn_hip_deprecated_builtin)
4970 << OldName << NewName;
4971 if (!CanFixIt)
4972 return;
4973
4974 DB << FixItHint::CreateReplacement(ExprRange, NewName);
4975
4976 Expr *Scope = Args[Args.size() - 1];
4977 std::optional<llvm::APSInt> ScopeVal =
4978 Scope->getIntegerConstantExpr(S.Context);
4979 if (!ScopeVal)
4980 return;
4981
4982 StringRef ScopeName;
4983 switch (ScopeVal->getZExtValue()) {
4985 ScopeName = "__MEMORY_SCOPE_SINGLE";
4986 break;
4988 ScopeName = "__MEMORY_SCOPE_WVFRNT";
4989 break;
4991 ScopeName = "__MEMORY_SCOPE_WRKGRP";
4992 break;
4994 ScopeName = "__MEMORY_SCOPE_DEVICE";
4995 break;
4997 ScopeName = "__MEMORY_SCOPE_SYSTEM";
4998 break;
5000 ScopeName = "__MEMORY_SCOPE_CLUSTR";
5001 break;
5002 default:
5003 return;
5004 }
5005
5007 CharSourceRange::getTokenRange(Scope->getSourceRange()), ScopeName);
5008}
5009
5011 SourceLocation RParenLoc, MultiExprArg Args,
5013 AtomicArgumentOrder ArgOrder) {
5014 // All the non-OpenCL operations take one of the following forms.
5015 // The OpenCL operations take the __c11 forms with one extra argument for
5016 // synchronization scope.
5017 enum {
5018 // C __c11_atomic_init(A *, C)
5019 Init,
5020
5021 // C __c11_atomic_load(A *, int)
5022 Load,
5023
5024 // void __atomic_load(A *, CP, int)
5025 LoadCopy,
5026
5027 // void __atomic_store(A *, CP, int)
5028 Copy,
5029
5030 // C __c11_atomic_add(A *, M, int)
5031 Arithmetic,
5032
5033 // C __atomic_exchange_n(A *, CP, int)
5034 Xchg,
5035
5036 // void __atomic_exchange(A *, C *, CP, int)
5037 GNUXchg,
5038
5039 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5040 C11CmpXchg,
5041
5042 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5043 GNUCmpXchg,
5044
5045 // bool __atomic_test_and_set(A *, int)
5046 TestAndSetByte,
5047
5048 // void __atomic_clear(A *, int)
5049 ClearByte,
5050 } Form = Init;
5051
5052 const unsigned NumForm = ClearByte + 1;
5053 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
5054 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
5055 // where:
5056 // C is an appropriate type,
5057 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5058 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5059 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5060 // the int parameters are for orderings.
5061
5062 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5063 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5064 "need to update code for modified forms");
5065 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
5066 AtomicExpr::AO__atomic_xor_fetch + 1 ==
5067 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
5068 "need to update code for modified C11 atomics");
5069 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
5070 Op <= AtomicExpr::AO__opencl_atomic_store;
5071 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
5072 Op <= AtomicExpr::AO__hip_atomic_store;
5073 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
5074 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
5075 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
5076 Op <= AtomicExpr::AO__c11_atomic_store) ||
5077 IsOpenCL;
5078 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5079 Op == AtomicExpr::AO__atomic_store_n ||
5080 Op == AtomicExpr::AO__atomic_exchange_n ||
5081 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
5082 Op == AtomicExpr::AO__scoped_atomic_load_n ||
5083 Op == AtomicExpr::AO__scoped_atomic_store_n ||
5084 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
5085 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
5086 // Bit mask for extra allowed value types other than integers for atomic
5087 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
5088 // allow floating point.
5089 enum ArithOpExtraValueType {
5090 AOEVT_None = 0,
5091 AOEVT_Pointer = 1,
5092 AOEVT_FP = 2,
5093 AOEVT_Int = 4,
5094 };
5095 unsigned ArithAllows = AOEVT_None;
5096
5097 switch (Op) {
5098 case AtomicExpr::AO__c11_atomic_init:
5099 case AtomicExpr::AO__opencl_atomic_init:
5100 Form = Init;
5101 break;
5102
5103 case AtomicExpr::AO__c11_atomic_load:
5104 case AtomicExpr::AO__opencl_atomic_load:
5105 case AtomicExpr::AO__hip_atomic_load:
5106 case AtomicExpr::AO__atomic_load_n:
5107 case AtomicExpr::AO__scoped_atomic_load_n:
5108 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5109 Form = Load;
5110 break;
5111
5112 case AtomicExpr::AO__atomic_load:
5113 case AtomicExpr::AO__scoped_atomic_load:
5114 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5115 Form = LoadCopy;
5116 break;
5117
5118 case AtomicExpr::AO__c11_atomic_store:
5119 case AtomicExpr::AO__opencl_atomic_store:
5120 case AtomicExpr::AO__hip_atomic_store:
5121 case AtomicExpr::AO__atomic_store:
5122 case AtomicExpr::AO__atomic_store_n:
5123 case AtomicExpr::AO__scoped_atomic_store:
5124 case AtomicExpr::AO__scoped_atomic_store_n:
5125 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5126 Form = Copy;
5127 break;
5128 case AtomicExpr::AO__atomic_fetch_add:
5129 case AtomicExpr::AO__atomic_fetch_sub:
5130 case AtomicExpr::AO__atomic_add_fetch:
5131 case AtomicExpr::AO__atomic_sub_fetch:
5132 case AtomicExpr::AO__scoped_atomic_fetch_add:
5133 case AtomicExpr::AO__scoped_atomic_fetch_sub:
5134 case AtomicExpr::AO__scoped_atomic_add_fetch:
5135 case AtomicExpr::AO__scoped_atomic_sub_fetch:
5136 case AtomicExpr::AO__c11_atomic_fetch_add:
5137 case AtomicExpr::AO__c11_atomic_fetch_sub:
5138 case AtomicExpr::AO__opencl_atomic_fetch_add:
5139 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5140 case AtomicExpr::AO__hip_atomic_fetch_add:
5141 case AtomicExpr::AO__hip_atomic_fetch_sub:
5142 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5143 Form = Arithmetic;
5144 break;
5145 case AtomicExpr::AO__atomic_fetch_fminimum:
5146 case AtomicExpr::AO__atomic_fetch_fmaximum:
5147 case AtomicExpr::AO__atomic_fetch_fminimum_num:
5148 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
5149 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
5150 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
5151 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
5152 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
5153 ArithAllows = AOEVT_FP;
5154 Form = Arithmetic;
5155 break;
5156 case AtomicExpr::AO__atomic_fetch_max:
5157 case AtomicExpr::AO__atomic_fetch_min:
5158 case AtomicExpr::AO__atomic_max_fetch:
5159 case AtomicExpr::AO__atomic_min_fetch:
5160 case AtomicExpr::AO__scoped_atomic_fetch_max:
5161 case AtomicExpr::AO__scoped_atomic_fetch_min:
5162 case AtomicExpr::AO__scoped_atomic_max_fetch:
5163 case AtomicExpr::AO__scoped_atomic_min_fetch:
5164 case AtomicExpr::AO__c11_atomic_fetch_max:
5165 case AtomicExpr::AO__c11_atomic_fetch_min:
5166 case AtomicExpr::AO__opencl_atomic_fetch_max:
5167 case AtomicExpr::AO__opencl_atomic_fetch_min:
5168 case AtomicExpr::AO__hip_atomic_fetch_max:
5169 case AtomicExpr::AO__hip_atomic_fetch_min:
5170 ArithAllows = AOEVT_Int | AOEVT_FP;
5171 Form = Arithmetic;
5172 break;
5173 case AtomicExpr::AO__c11_atomic_fetch_and:
5174 case AtomicExpr::AO__c11_atomic_fetch_or:
5175 case AtomicExpr::AO__c11_atomic_fetch_xor:
5176 case AtomicExpr::AO__hip_atomic_fetch_and:
5177 case AtomicExpr::AO__hip_atomic_fetch_or:
5178 case AtomicExpr::AO__hip_atomic_fetch_xor:
5179 case AtomicExpr::AO__c11_atomic_fetch_nand:
5180 case AtomicExpr::AO__opencl_atomic_fetch_and:
5181 case AtomicExpr::AO__opencl_atomic_fetch_or:
5182 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5183 case AtomicExpr::AO__atomic_fetch_and:
5184 case AtomicExpr::AO__atomic_fetch_or:
5185 case AtomicExpr::AO__atomic_fetch_xor:
5186 case AtomicExpr::AO__atomic_fetch_nand:
5187 case AtomicExpr::AO__atomic_and_fetch:
5188 case AtomicExpr::AO__atomic_or_fetch:
5189 case AtomicExpr::AO__atomic_xor_fetch:
5190 case AtomicExpr::AO__atomic_nand_fetch:
5191 case AtomicExpr::AO__atomic_fetch_uinc:
5192 case AtomicExpr::AO__atomic_fetch_udec:
5193 case AtomicExpr::AO__scoped_atomic_fetch_and:
5194 case AtomicExpr::AO__scoped_atomic_fetch_or:
5195 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5196 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5197 case AtomicExpr::AO__scoped_atomic_and_fetch:
5198 case AtomicExpr::AO__scoped_atomic_or_fetch:
5199 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5200 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5201 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5202 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5203 Form = Arithmetic;
5204 break;
5205
5206 case AtomicExpr::AO__c11_atomic_exchange:
5207 case AtomicExpr::AO__hip_atomic_exchange:
5208 case AtomicExpr::AO__opencl_atomic_exchange:
5209 case AtomicExpr::AO__atomic_exchange_n:
5210 case AtomicExpr::AO__scoped_atomic_exchange_n:
5211 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5212 Form = Xchg;
5213 break;
5214
5215 case AtomicExpr::AO__atomic_exchange:
5216 case AtomicExpr::AO__scoped_atomic_exchange:
5217 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5218 Form = GNUXchg;
5219 break;
5220
5221 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5222 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5223 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5224 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5225 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5226 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5227 Form = C11CmpXchg;
5228 break;
5229
5230 case AtomicExpr::AO__atomic_compare_exchange:
5231 case AtomicExpr::AO__atomic_compare_exchange_n:
5232 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5233 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5234 ArithAllows = AOEVT_Pointer;
5235 Form = GNUCmpXchg;
5236 break;
5237
5238 case AtomicExpr::AO__atomic_test_and_set:
5239 Form = TestAndSetByte;
5240 break;
5241
5242 case AtomicExpr::AO__atomic_clear:
5243 Form = ClearByte;
5244 break;
5245 }
5246
5247 unsigned AdjustedNumArgs = NumArgs[Form];
5248 if ((IsOpenCL || IsHIP || IsScoped) &&
5249 Op != AtomicExpr::AO__opencl_atomic_init)
5250 ++AdjustedNumArgs;
5251 // Check we have the right number of arguments.
5252 if (Args.size() < AdjustedNumArgs) {
5253 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5254 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5255 << /*is non object*/ 0 << ExprRange;
5256 return ExprError();
5257 } else if (Args.size() > AdjustedNumArgs) {
5258 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5259 diag::err_typecheck_call_too_many_args)
5260 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5261 << /*is non object*/ 0 << ExprRange;
5262 return ExprError();
5263 }
5264
5265 // Inspect the first argument of the atomic operation.
5266 Expr *Ptr = Args[0];
5268 if (ConvertedPtr.isInvalid())
5269 return ExprError();
5270
5271 Ptr = ConvertedPtr.get();
5272 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5273 if (!pointerType) {
5274 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5275 << Ptr->getType() << 0 << Ptr->getSourceRange();
5276 return ExprError();
5277 }
5278
5279 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5280 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5281 QualType ValType = AtomTy; // 'C'
5282 if (IsC11) {
5283 if (!AtomTy->isAtomicType()) {
5284 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5285 << Ptr->getType() << Ptr->getSourceRange();
5286 return ExprError();
5287 }
5288 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5290 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5291 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5292 << Ptr->getSourceRange();
5293 return ExprError();
5294 }
5295 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5296 } else if (Form != Load && Form != LoadCopy) {
5297 if (ValType.isConstQualified()) {
5298 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5299 << Ptr->getType() << Ptr->getSourceRange();
5300 return ExprError();
5301 }
5302 }
5303
5304 if (Form != TestAndSetByte && Form != ClearByte) {
5305 // Pointer to object of size zero is not allowed.
5306 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
5307 diag::err_incomplete_type))
5308 return ExprError();
5309
5310 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
5311 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5312 << Ptr->getType() << 1 << Ptr->getSourceRange();
5313 return ExprError();
5314 }
5315 } else {
5316 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5317 // non-const pointer type, including void* and pointers to incomplete
5318 // structs, but only access the first byte.
5319 AtomTy = Context.CharTy;
5320 AtomTy = AtomTy.withCVRQualifiers(
5321 pointerType->getPointeeType().getCVRQualifiers());
5322 QualType PointerQT = Context.getPointerType(AtomTy);
5323 pointerType = PointerQT->getAs<PointerType>();
5324 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
5325 ValType = AtomTy;
5326 }
5327
5328 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5329 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5330 Diag(ExprRange.getBegin(),
5331 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5332 << 0 << Ptr->getType() << Ptr->getSourceRange();
5333 return ExprError();
5334 }
5335
5336 // For an arithmetic operation, the implied arithmetic must be well-formed.
5337 // For _n operations, the value type must also be a valid atomic type.
5338 if (Form == Arithmetic || IsN) {
5339 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5340 // trivial type errors.
5341 auto IsAllowedValueType = [&](QualType ValType,
5342 unsigned AllowedType) -> bool {
5343 bool IsX87LongDouble =
5344 ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5345 &Context.getTargetInfo().getLongDoubleFormat() ==
5346 &llvm::APFloat::x87DoubleExtended();
5347 if (ValType->isIntegerType())
5348 // Special case: f-prefixed operations (AOEVT_FP exactly) reject
5349 // integers. Explicit AOEVT_Int or other combinations allow integers.
5350 return (AllowedType & AOEVT_Int) || AllowedType != AOEVT_FP;
5351 if (ValType->isPointerType())
5352 return AllowedType & AOEVT_Pointer;
5353 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5354 return false;
5355 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5356 if (IsX87LongDouble)
5357 return false;
5358 return true;
5359 };
5360 if (!IsAllowedValueType(ValType, ArithAllows)) {
5361 auto DID =
5362 ArithAllows == AOEVT_FP
5363 ? diag::err_atomic_op_needs_atomic_fp
5364 : (ArithAllows & AOEVT_FP
5365 ? (ArithAllows & AOEVT_Pointer
5366 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5367 : diag::err_atomic_op_needs_atomic_int_or_fp)
5368 : (ArithAllows & AOEVT_Pointer
5369 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5370 : diag::err_atomic_op_needs_atomic_int));
5371 Diag(ExprRange.getBegin(), DID)
5372 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5373 return ExprError();
5374 }
5375 if (IsC11 && ValType->isPointerType() &&
5376 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5377 diag::err_incomplete_type)) {
5378 return ExprError();
5379 }
5380 }
5381
5382 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5383 !AtomTy->isScalarType()) {
5384 // For GNU atomics, require a trivially-copyable type. This is not part of
5385 // the GNU atomics specification but we enforce it for consistency with
5386 // other atomics which generally all require a trivially-copyable type. This
5387 // is because atomics just copy bits.
5388 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5389 << Ptr->getType() << Ptr->getSourceRange();
5390 return ExprError();
5391 }
5392
5393 switch (ValType.getObjCLifetime()) {
5396 // okay
5397 break;
5398
5402 // FIXME: Can this happen? By this point, ValType should be known
5403 // to be trivially copyable.
5404 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5405 << ValType << Ptr->getSourceRange();
5406 return ExprError();
5407 }
5408
5409 // All atomic operations have an overload which takes a pointer to a volatile
5410 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5411 // into the result or the other operands. Similarly atomic_load takes a
5412 // pointer to a const 'A'.
5413 ValType.removeLocalVolatile();
5414 ValType.removeLocalConst();
5415 QualType ResultType = ValType;
5416 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5417 Form == ClearByte)
5418 ResultType = Context.VoidTy;
5419 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5420 ResultType = Context.BoolTy;
5421
5422 // The type of a parameter passed 'by value'. In the GNU atomics, such
5423 // arguments are actually passed as pointers.
5424 QualType ByValType = ValType; // 'CP'
5425 bool IsPassedByAddress = false;
5426 if (!IsC11 && !IsHIP && !IsN) {
5427 ByValType = Ptr->getType();
5428 IsPassedByAddress = true;
5429 }
5430
5431 SmallVector<Expr *, 5> APIOrderedArgs;
5432 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5433 APIOrderedArgs.push_back(Args[0]);
5434 switch (Form) {
5435 case Init:
5436 case Load:
5437 APIOrderedArgs.push_back(Args[1]); // Val1/Order
5438 break;
5439 case LoadCopy:
5440 case Copy:
5441 case Arithmetic:
5442 case Xchg:
5443 APIOrderedArgs.push_back(Args[2]); // Val1
5444 APIOrderedArgs.push_back(Args[1]); // Order
5445 break;
5446 case GNUXchg:
5447 APIOrderedArgs.push_back(Args[2]); // Val1
5448 APIOrderedArgs.push_back(Args[3]); // Val2
5449 APIOrderedArgs.push_back(Args[1]); // Order
5450 break;
5451 case C11CmpXchg:
5452 APIOrderedArgs.push_back(Args[2]); // Val1
5453 APIOrderedArgs.push_back(Args[4]); // Val2
5454 APIOrderedArgs.push_back(Args[1]); // Order
5455 APIOrderedArgs.push_back(Args[3]); // OrderFail
5456 break;
5457 case GNUCmpXchg:
5458 APIOrderedArgs.push_back(Args[2]); // Val1
5459 APIOrderedArgs.push_back(Args[4]); // Val2
5460 APIOrderedArgs.push_back(Args[5]); // Weak
5461 APIOrderedArgs.push_back(Args[1]); // Order
5462 APIOrderedArgs.push_back(Args[3]); // OrderFail
5463 break;
5464 case TestAndSetByte:
5465 case ClearByte:
5466 APIOrderedArgs.push_back(Args[1]); // Order
5467 break;
5468 }
5469 } else
5470 APIOrderedArgs.append(Args.begin(), Args.end());
5471
5472 // The first argument's non-CV pointer type is used to deduce the type of
5473 // subsequent arguments, except for:
5474 // - weak flag (always converted to bool)
5475 // - memory order (always converted to int)
5476 // - scope (always converted to int)
5477 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5478 QualType Ty;
5479 if (i < NumVals[Form] + 1) {
5480 switch (i) {
5481 case 0:
5482 // The first argument is always a pointer. It has a fixed type.
5483 // It is always dereferenced, a nullptr is undefined.
5484 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5485 // Nothing else to do: we already know all we want about this pointer.
5486 continue;
5487 case 1:
5488 // The second argument is the non-atomic operand. For arithmetic, this
5489 // is always passed by value, and for a compare_exchange it is always
5490 // passed by address. For the rest, GNU uses by-address and C11 uses
5491 // by-value.
5492 assert(Form != Load);
5493 if (Form == Arithmetic && ValType->isPointerType())
5494 Ty = Context.getPointerDiffType();
5495 else if (Form == Init || Form == Arithmetic)
5496 Ty = ValType;
5497 else if (Form == Copy || Form == Xchg) {
5498 if (IsPassedByAddress) {
5499 // The value pointer is always dereferenced, a nullptr is undefined.
5500 CheckNonNullArgument(*this, APIOrderedArgs[i],
5501 ExprRange.getBegin());
5502 }
5503 Ty = ByValType;
5504 } else {
5505 Expr *ValArg = APIOrderedArgs[i];
5506 // The value pointer is always dereferenced, a nullptr is undefined.
5507 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5509 // Keep address space of non-atomic pointer type.
5510 if (const PointerType *PtrTy =
5511 ValArg->getType()->getAs<PointerType>()) {
5512 AS = PtrTy->getPointeeType().getAddressSpace();
5513 }
5514 Ty = Context.getPointerType(
5515 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5516 }
5517 break;
5518 case 2:
5519 // The third argument to compare_exchange / GNU exchange is the desired
5520 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5521 if (IsPassedByAddress)
5522 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5523 Ty = ByValType;
5524 break;
5525 case 3:
5526 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5527 Ty = Context.BoolTy;
5528 break;
5529 }
5530 } else {
5531 // The order(s) and scope are always converted to int.
5532 Ty = Context.IntTy;
5533 }
5534
5535 InitializedEntity Entity =
5537 ExprResult Arg = APIOrderedArgs[i];
5538 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5539 if (Arg.isInvalid())
5540 return true;
5541 APIOrderedArgs[i] = Arg.get();
5542 }
5543
5544 // Permute the arguments into a 'consistent' order.
5545 SmallVector<Expr*, 5> SubExprs;
5546 SubExprs.push_back(Ptr);
5547 switch (Form) {
5548 case Init:
5549 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5550 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5551 break;
5552 case Load:
5553 case TestAndSetByte:
5554 case ClearByte:
5555 SubExprs.push_back(APIOrderedArgs[1]); // Order
5556 break;
5557 case LoadCopy:
5558 case Copy:
5559 case Arithmetic:
5560 case Xchg:
5561 SubExprs.push_back(APIOrderedArgs[2]); // Order
5562 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5563 break;
5564 case GNUXchg:
5565 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5566 SubExprs.push_back(APIOrderedArgs[3]); // Order
5567 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5568 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5569 break;
5570 case C11CmpXchg:
5571 SubExprs.push_back(APIOrderedArgs[3]); // Order
5572 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5573 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5574 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5575 break;
5576 case GNUCmpXchg:
5577 SubExprs.push_back(APIOrderedArgs[4]); // Order
5578 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5579 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5580 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5581 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5582 break;
5583 }
5584
5585 // If the memory orders are constants, check they are valid.
5586 if (SubExprs.size() >= 2 && Form != Init) {
5587 std::optional<llvm::APSInt> Success =
5588 SubExprs[1]->getIntegerConstantExpr(Context);
5589 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
5590 Diag(SubExprs[1]->getBeginLoc(),
5591 diag::warn_atomic_op_has_invalid_memory_order)
5592 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5593 << SubExprs[1]->getSourceRange();
5594 }
5595 if (SubExprs.size() >= 5) {
5596 if (std::optional<llvm::APSInt> Failure =
5597 SubExprs[3]->getIntegerConstantExpr(Context)) {
5598 if (!llvm::is_contained(
5599 {llvm::AtomicOrderingCABI::relaxed,
5600 llvm::AtomicOrderingCABI::consume,
5601 llvm::AtomicOrderingCABI::acquire,
5602 llvm::AtomicOrderingCABI::seq_cst},
5603 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5604 Diag(SubExprs[3]->getBeginLoc(),
5605 diag::warn_atomic_op_has_invalid_memory_order)
5606 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5607 }
5608 }
5609 }
5610 }
5611
5612 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5613 auto *Scope = Args[Args.size() - 1];
5614 if (std::optional<llvm::APSInt> Result =
5615 Scope->getIntegerConstantExpr(Context)) {
5616 if (!ScopeModel->isValid(Result->getZExtValue()))
5617 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5618 << Scope->getSourceRange();
5619 }
5620 SubExprs.push_back(Scope);
5621 }
5622
5623 if (IsHIP)
5624 DiagnoseDeprecatedHIPAtomic(*this, ExprRange, Args, Op);
5625
5626 AtomicExpr *AE = new (Context)
5627 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5628
5629 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5630 Op == AtomicExpr::AO__c11_atomic_store ||
5631 Op == AtomicExpr::AO__opencl_atomic_load ||
5632 Op == AtomicExpr::AO__hip_atomic_load ||
5633 Op == AtomicExpr::AO__opencl_atomic_store ||
5634 Op == AtomicExpr::AO__hip_atomic_store) &&
5635 Context.AtomicUsesUnsupportedLibcall(AE))
5636 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5637 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5638 Op == AtomicExpr::AO__opencl_atomic_load ||
5639 Op == AtomicExpr::AO__hip_atomic_load)
5640 ? 0
5641 : 1);
5642
5643 if (ValType->isBitIntType()) {
5644 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5645 return ExprError();
5646 }
5647
5648 return AE;
5649}
5650
5651/// checkBuiltinArgument - Given a call to a builtin function, perform
5652/// normal type-checking on the given argument, updating the call in
5653/// place. This is useful when a builtin function requires custom
5654/// type-checking for some of its arguments but not necessarily all of
5655/// them.
5656///
5657/// Returns true on error.
5658static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5659 FunctionDecl *Fn = E->getDirectCallee();
5660 assert(Fn && "builtin call without direct callee!");
5661
5662 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5663 InitializedEntity Entity =
5665
5666 ExprResult Arg = E->getArg(ArgIndex);
5667 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5668 if (Arg.isInvalid())
5669 return true;
5670
5671 E->setArg(ArgIndex, Arg.get());
5672 return false;
5673}
5674
5675ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5676 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5677 Expr *Callee = TheCall->getCallee();
5678 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5679 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5680
5681 // Ensure that we have at least one argument to do type inference from.
5682 if (TheCall->getNumArgs() < 1) {
5683 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5684 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5685 << Callee->getSourceRange();
5686 return ExprError();
5687 }
5688
5689 // Inspect the first argument of the atomic builtin. This should always be
5690 // a pointer type, whose element is an integral scalar or pointer type.
5691 // Because it is a pointer type, we don't have to worry about any implicit
5692 // casts here.
5693 // FIXME: We don't allow floating point scalars as input.
5694 Expr *FirstArg = TheCall->getArg(0);
5695 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5696 if (FirstArgResult.isInvalid())
5697 return ExprError();
5698 FirstArg = FirstArgResult.get();
5699 TheCall->setArg(0, FirstArg);
5700
5701 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5702 if (!pointerType) {
5703 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5704 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5705 return ExprError();
5706 }
5707
5708 QualType ValType = pointerType->getPointeeType();
5709 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5710 !ValType->isBlockPointerType()) {
5711 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5712 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5713 return ExprError();
5714 }
5715 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5716 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5717 Diag(FirstArg->getBeginLoc(),
5718 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5719 << 1 << ValType << FirstArg->getSourceRange();
5720 return ExprError();
5721 }
5722
5723 if (ValType.isConstQualified()) {
5724 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5725 << FirstArg->getType() << FirstArg->getSourceRange();
5726 return ExprError();
5727 }
5728
5729 switch (ValType.getObjCLifetime()) {
5732 // okay
5733 break;
5734
5738 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5739 << ValType << FirstArg->getSourceRange();
5740 return ExprError();
5741 }
5742
5743 // Strip any qualifiers off ValType.
5744 ValType = ValType.getUnqualifiedType();
5745
5746 // The majority of builtins return a value, but a few have special return
5747 // types, so allow them to override appropriately below.
5748 QualType ResultType = ValType;
5749
5750 // We need to figure out which concrete builtin this maps onto. For example,
5751 // __sync_fetch_and_add with a 2 byte object turns into
5752 // __sync_fetch_and_add_2.
5753#define BUILTIN_ROW(x) \
5754 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5755 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5756
5757 static const unsigned BuiltinIndices[][5] = {
5758 BUILTIN_ROW(__sync_fetch_and_add),
5759 BUILTIN_ROW(__sync_fetch_and_sub),
5760 BUILTIN_ROW(__sync_fetch_and_or),
5761 BUILTIN_ROW(__sync_fetch_and_and),
5762 BUILTIN_ROW(__sync_fetch_and_xor),
5763 BUILTIN_ROW(__sync_fetch_and_nand),
5764
5765 BUILTIN_ROW(__sync_add_and_fetch),
5766 BUILTIN_ROW(__sync_sub_and_fetch),
5767 BUILTIN_ROW(__sync_and_and_fetch),
5768 BUILTIN_ROW(__sync_or_and_fetch),
5769 BUILTIN_ROW(__sync_xor_and_fetch),
5770 BUILTIN_ROW(__sync_nand_and_fetch),
5771
5772 BUILTIN_ROW(__sync_val_compare_and_swap),
5773 BUILTIN_ROW(__sync_bool_compare_and_swap),
5774 BUILTIN_ROW(__sync_lock_test_and_set),
5775 BUILTIN_ROW(__sync_lock_release),
5776 BUILTIN_ROW(__sync_swap)
5777 };
5778#undef BUILTIN_ROW
5779
5780 // Determine the index of the size.
5781 unsigned SizeIndex;
5782 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5783 case 1: SizeIndex = 0; break;
5784 case 2: SizeIndex = 1; break;
5785 case 4: SizeIndex = 2; break;
5786 case 8: SizeIndex = 3; break;
5787 case 16: SizeIndex = 4; break;
5788 default:
5789 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5790 << FirstArg->getType() << FirstArg->getSourceRange();
5791 return ExprError();
5792 }
5793
5794 // Each of these builtins has one pointer argument, followed by some number of
5795 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5796 // that we ignore. Find out which row of BuiltinIndices to read from as well
5797 // as the number of fixed args.
5798 unsigned BuiltinID = FDecl->getBuiltinID();
5799 unsigned BuiltinIndex, NumFixed = 1;
5800 bool WarnAboutSemanticsChange = false;
5801 switch (BuiltinID) {
5802 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5803 case Builtin::BI__sync_fetch_and_add:
5804 case Builtin::BI__sync_fetch_and_add_1:
5805 case Builtin::BI__sync_fetch_and_add_2:
5806 case Builtin::BI__sync_fetch_and_add_4:
5807 case Builtin::BI__sync_fetch_and_add_8:
5808 case Builtin::BI__sync_fetch_and_add_16:
5809 BuiltinIndex = 0;
5810 break;
5811
5812 case Builtin::BI__sync_fetch_and_sub:
5813 case Builtin::BI__sync_fetch_and_sub_1:
5814 case Builtin::BI__sync_fetch_and_sub_2:
5815 case Builtin::BI__sync_fetch_and_sub_4:
5816 case Builtin::BI__sync_fetch_and_sub_8:
5817 case Builtin::BI__sync_fetch_and_sub_16:
5818 BuiltinIndex = 1;
5819 break;
5820
5821 case Builtin::BI__sync_fetch_and_or:
5822 case Builtin::BI__sync_fetch_and_or_1:
5823 case Builtin::BI__sync_fetch_and_or_2:
5824 case Builtin::BI__sync_fetch_and_or_4:
5825 case Builtin::BI__sync_fetch_and_or_8:
5826 case Builtin::BI__sync_fetch_and_or_16:
5827 BuiltinIndex = 2;
5828 break;
5829
5830 case Builtin::BI__sync_fetch_and_and:
5831 case Builtin::BI__sync_fetch_and_and_1:
5832 case Builtin::BI__sync_fetch_and_and_2:
5833 case Builtin::BI__sync_fetch_and_and_4:
5834 case Builtin::BI__sync_fetch_and_and_8:
5835 case Builtin::BI__sync_fetch_and_and_16:
5836 BuiltinIndex = 3;
5837 break;
5838
5839 case Builtin::BI__sync_fetch_and_xor:
5840 case Builtin::BI__sync_fetch_and_xor_1:
5841 case Builtin::BI__sync_fetch_and_xor_2:
5842 case Builtin::BI__sync_fetch_and_xor_4:
5843 case Builtin::BI__sync_fetch_and_xor_8:
5844 case Builtin::BI__sync_fetch_and_xor_16:
5845 BuiltinIndex = 4;
5846 break;
5847
5848 case Builtin::BI__sync_fetch_and_nand:
5849 case Builtin::BI__sync_fetch_and_nand_1:
5850 case Builtin::BI__sync_fetch_and_nand_2:
5851 case Builtin::BI__sync_fetch_and_nand_4:
5852 case Builtin::BI__sync_fetch_and_nand_8:
5853 case Builtin::BI__sync_fetch_and_nand_16:
5854 BuiltinIndex = 5;
5855 WarnAboutSemanticsChange = true;
5856 break;
5857
5858 case Builtin::BI__sync_add_and_fetch:
5859 case Builtin::BI__sync_add_and_fetch_1:
5860 case Builtin::BI__sync_add_and_fetch_2:
5861 case Builtin::BI__sync_add_and_fetch_4:
5862 case Builtin::BI__sync_add_and_fetch_8:
5863 case Builtin::BI__sync_add_and_fetch_16:
5864 BuiltinIndex = 6;
5865 break;
5866
5867 case Builtin::BI__sync_sub_and_fetch:
5868 case Builtin::BI__sync_sub_and_fetch_1:
5869 case Builtin::BI__sync_sub_and_fetch_2:
5870 case Builtin::BI__sync_sub_and_fetch_4:
5871 case Builtin::BI__sync_sub_and_fetch_8:
5872 case Builtin::BI__sync_sub_and_fetch_16:
5873 BuiltinIndex = 7;
5874 break;
5875
5876 case Builtin::BI__sync_and_and_fetch:
5877 case Builtin::BI__sync_and_and_fetch_1:
5878 case Builtin::BI__sync_and_and_fetch_2:
5879 case Builtin::BI__sync_and_and_fetch_4:
5880 case Builtin::BI__sync_and_and_fetch_8:
5881 case Builtin::BI__sync_and_and_fetch_16:
5882 BuiltinIndex = 8;
5883 break;
5884
5885 case Builtin::BI__sync_or_and_fetch:
5886 case Builtin::BI__sync_or_and_fetch_1:
5887 case Builtin::BI__sync_or_and_fetch_2:
5888 case Builtin::BI__sync_or_and_fetch_4:
5889 case Builtin::BI__sync_or_and_fetch_8:
5890 case Builtin::BI__sync_or_and_fetch_16:
5891 BuiltinIndex = 9;
5892 break;
5893
5894 case Builtin::BI__sync_xor_and_fetch:
5895 case Builtin::BI__sync_xor_and_fetch_1:
5896 case Builtin::BI__sync_xor_and_fetch_2:
5897 case Builtin::BI__sync_xor_and_fetch_4:
5898 case Builtin::BI__sync_xor_and_fetch_8:
5899 case Builtin::BI__sync_xor_and_fetch_16:
5900 BuiltinIndex = 10;
5901 break;
5902
5903 case Builtin::BI__sync_nand_and_fetch:
5904 case Builtin::BI__sync_nand_and_fetch_1:
5905 case Builtin::BI__sync_nand_and_fetch_2:
5906 case Builtin::BI__sync_nand_and_fetch_4:
5907 case Builtin::BI__sync_nand_and_fetch_8:
5908 case Builtin::BI__sync_nand_and_fetch_16:
5909 BuiltinIndex = 11;
5910 WarnAboutSemanticsChange = true;
5911 break;
5912
5913 case Builtin::BI__sync_val_compare_and_swap:
5914 case Builtin::BI__sync_val_compare_and_swap_1:
5915 case Builtin::BI__sync_val_compare_and_swap_2:
5916 case Builtin::BI__sync_val_compare_and_swap_4:
5917 case Builtin::BI__sync_val_compare_and_swap_8:
5918 case Builtin::BI__sync_val_compare_and_swap_16:
5919 BuiltinIndex = 12;
5920 NumFixed = 2;
5921 break;
5922
5923 case Builtin::BI__sync_bool_compare_and_swap:
5924 case Builtin::BI__sync_bool_compare_and_swap_1:
5925 case Builtin::BI__sync_bool_compare_and_swap_2:
5926 case Builtin::BI__sync_bool_compare_and_swap_4:
5927 case Builtin::BI__sync_bool_compare_and_swap_8:
5928 case Builtin::BI__sync_bool_compare_and_swap_16:
5929 BuiltinIndex = 13;
5930 NumFixed = 2;
5931 ResultType = Context.BoolTy;
5932 break;
5933
5934 case Builtin::BI__sync_lock_test_and_set:
5935 case Builtin::BI__sync_lock_test_and_set_1:
5936 case Builtin::BI__sync_lock_test_and_set_2:
5937 case Builtin::BI__sync_lock_test_and_set_4:
5938 case Builtin::BI__sync_lock_test_and_set_8:
5939 case Builtin::BI__sync_lock_test_and_set_16:
5940 BuiltinIndex = 14;
5941 break;
5942
5943 case Builtin::BI__sync_lock_release:
5944 case Builtin::BI__sync_lock_release_1:
5945 case Builtin::BI__sync_lock_release_2:
5946 case Builtin::BI__sync_lock_release_4:
5947 case Builtin::BI__sync_lock_release_8:
5948 case Builtin::BI__sync_lock_release_16:
5949 BuiltinIndex = 15;
5950 NumFixed = 0;
5951 ResultType = Context.VoidTy;
5952 break;
5953
5954 case Builtin::BI__sync_swap:
5955 case Builtin::BI__sync_swap_1:
5956 case Builtin::BI__sync_swap_2:
5957 case Builtin::BI__sync_swap_4:
5958 case Builtin::BI__sync_swap_8:
5959 case Builtin::BI__sync_swap_16:
5960 BuiltinIndex = 16;
5961 break;
5962 }
5963
5964 // Now that we know how many fixed arguments we expect, first check that we
5965 // have at least that many.
5966 if (TheCall->getNumArgs() < 1+NumFixed) {
5967 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5968 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5969 << Callee->getSourceRange();
5970 return ExprError();
5971 }
5972
5973 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5974 << Callee->getSourceRange();
5975
5976 if (WarnAboutSemanticsChange) {
5977 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5978 << Callee->getSourceRange();
5979 }
5980
5981 // Get the decl for the concrete builtin from this, we can tell what the
5982 // concrete integer type we should convert to is.
5983 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5984 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5985 FunctionDecl *NewBuiltinDecl;
5986 if (NewBuiltinID == BuiltinID)
5987 NewBuiltinDecl = FDecl;
5988 else {
5989 // Perform builtin lookup to avoid redeclaring it.
5990 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5991 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5992 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5993 assert(Res.getFoundDecl());
5994 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5995 if (!NewBuiltinDecl)
5996 return ExprError();
5997 }
5998
5999 // The first argument --- the pointer --- has a fixed type; we
6000 // deduce the types of the rest of the arguments accordingly. Walk
6001 // the remaining arguments, converting them to the deduced value type.
6002 for (unsigned i = 0; i != NumFixed; ++i) {
6003 ExprResult Arg = TheCall->getArg(i+1);
6004
6005 // GCC does an implicit conversion to the pointer or integer ValType. This
6006 // can fail in some cases (1i -> int**), check for this error case now.
6007 // Initialize the argument.
6008 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6009 ValType, /*consume*/ false);
6010 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6011 if (Arg.isInvalid())
6012 return ExprError();
6013
6014 // Okay, we have something that *can* be converted to the right type. Check
6015 // to see if there is a potentially weird extension going on here. This can
6016 // happen when you do an atomic operation on something like an char* and
6017 // pass in 42. The 42 gets converted to char. This is even more strange
6018 // for things like 45.123 -> char, etc.
6019 // FIXME: Do this check.
6020 TheCall->setArg(i+1, Arg.get());
6021 }
6022
6023 // Create a new DeclRefExpr to refer to the new decl.
6024 DeclRefExpr *NewDRE = DeclRefExpr::Create(
6025 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6026 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6027 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6028
6029 // Set the callee in the CallExpr.
6030 // FIXME: This loses syntactic information.
6031 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6032 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6033 CK_BuiltinFnToFnPtr);
6034 TheCall->setCallee(PromotedCall.get());
6035
6036 // Change the result type of the call to match the original value type. This
6037 // is arbitrary, but the codegen for these builtins ins design to handle it
6038 // gracefully.
6039 TheCall->setType(ResultType);
6040
6041 // Prohibit problematic uses of bit-precise integer types with atomic
6042 // builtins. The arguments would have already been converted to the first
6043 // argument's type, so only need to check the first argument.
6044 const auto *BitIntValType = ValType->getAs<BitIntType>();
6045 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6046 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6047 return ExprError();
6048 }
6049
6050 return TheCallResult;
6051}
6052
6053ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6054 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6055 DeclRefExpr *DRE =
6057 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6058 unsigned BuiltinID = FDecl->getBuiltinID();
6059 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6060 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6061 "Unexpected nontemporal load/store builtin!");
6062 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6063 unsigned numArgs = isStore ? 2 : 1;
6064
6065 // Ensure that we have the proper number of arguments.
6066 if (checkArgCount(TheCall, numArgs))
6067 return ExprError();
6068
6069 // Inspect the last argument of the nontemporal builtin. This should always
6070 // be a pointer type, from which we imply the type of the memory access.
6071 // Because it is a pointer type, we don't have to worry about any implicit
6072 // casts here.
6073 Expr *PointerArg = TheCall->getArg(numArgs - 1);
6074 ExprResult PointerArgResult =
6076
6077 if (PointerArgResult.isInvalid())
6078 return ExprError();
6079 PointerArg = PointerArgResult.get();
6080 TheCall->setArg(numArgs - 1, PointerArg);
6081
6082 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6083 if (!pointerType) {
6084 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6085 << PointerArg->getType() << PointerArg->getSourceRange();
6086 return ExprError();
6087 }
6088
6089 QualType ValType = pointerType->getPointeeType();
6090
6091 // Strip any qualifiers off ValType.
6092 ValType = ValType.getUnqualifiedType();
6093 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6094 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6095 !ValType->isVectorType()) {
6096 Diag(DRE->getBeginLoc(),
6097 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6098 << PointerArg->getType() << PointerArg->getSourceRange();
6099 return ExprError();
6100 }
6101
6102 if (!isStore) {
6103 TheCall->setType(ValType);
6104 return TheCallResult;
6105 }
6106
6107 ExprResult ValArg = TheCall->getArg(0);
6108 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6109 Context, ValType, /*consume*/ false);
6110 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6111 if (ValArg.isInvalid())
6112 return ExprError();
6113
6114 TheCall->setArg(0, ValArg.get());
6115 TheCall->setType(Context.VoidTy);
6116 return TheCallResult;
6117}
6118
6119/// CheckObjCString - Checks that the format string argument to the os_log()
6120/// and os_trace() functions is correct, and converts it to const char *.
6121ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6122 Arg = Arg->IgnoreParenCasts();
6123 auto *Literal = dyn_cast<StringLiteral>(Arg);
6124 if (!Literal) {
6125 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6126 Literal = ObjcLiteral->getString();
6127 }
6128 }
6129
6130 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
6131 return ExprError(
6132 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6133 << Arg->getSourceRange());
6134 }
6135
6136 ExprResult Result(Literal);
6137 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6138 InitializedEntity Entity =
6140 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6141 return Result;
6142}
6143
6144/// Check that the user is calling the appropriate va_start builtin for the
6145/// target and calling convention.
6146static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6147 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6148 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6149 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6150 TT.getArch() == llvm::Triple::aarch64_32);
6151 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
6152 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6153 if (IsX64 || IsAArch64) {
6154 CallingConv CC = CC_C;
6155 if (const FunctionDecl *FD = S.getCurFunctionDecl())
6156 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6157 if (IsMSVAStart) {
6158 // Don't allow this in System V ABI functions.
6159 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
6160 return S.Diag(Fn->getBeginLoc(),
6161 diag::err_ms_va_start_used_in_sysv_function);
6162 } else {
6163 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6164 // On x64 Windows, don't allow this in System V ABI functions.
6165 // (Yes, that means there's no corresponding way to support variadic
6166 // System V ABI functions on Windows.)
6167 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
6168 (!IsWindowsOrUEFI && CC == CC_Win64))
6169 return S.Diag(Fn->getBeginLoc(),
6170 diag::err_va_start_used_in_wrong_abi_function)
6171 << !IsWindowsOrUEFI;
6172 }
6173 return false;
6174 }
6175
6176 if (IsMSVAStart)
6177 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6178 return false;
6179}
6180
6182 ParmVarDecl **LastParam = nullptr) {
6183 // Determine whether the current function, block, or obj-c method is variadic
6184 // and get its parameter list.
6185 bool IsVariadic = false;
6187 DeclContext *Caller = S.CurContext;
6188 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6189 IsVariadic = Block->isVariadic();
6190 Params = Block->parameters();
6191 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6192 IsVariadic = FD->isVariadic();
6193 Params = FD->parameters();
6194 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6195 IsVariadic = MD->isVariadic();
6196 // FIXME: This isn't correct for methods (results in bogus warning).
6197 Params = MD->parameters();
6198 } else if (isa<CapturedDecl>(Caller)) {
6199 // We don't support va_start in a CapturedDecl.
6200 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6201 return true;
6202 } else {
6203 // This must be some other declcontext that parses exprs.
6204 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6205 return true;
6206 }
6207
6208 if (!IsVariadic) {
6209 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6210 return true;
6211 }
6212
6213 if (LastParam)
6214 *LastParam = Params.empty() ? nullptr : Params.back();
6215
6216 return false;
6217}
6218
6219bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6220 Expr *Fn = TheCall->getCallee();
6221 if (checkVAStartABI(*this, BuiltinID, Fn))
6222 return true;
6223
6224 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6225 // This builtin requires one argument (the va_list), allows two arguments,
6226 // but diagnoses more than two arguments. e.g.,
6227 // __builtin_c23_va_start(); // error
6228 // __builtin_c23_va_start(list); // ok
6229 // __builtin_c23_va_start(list, param); // ok
6230 // __builtin_c23_va_start(list, anything, anything); // error
6231 // This differs from the GCC behavior in that they accept the last case
6232 // with a warning, but it doesn't seem like a useful behavior to allow.
6233 if (checkArgCountRange(TheCall, 1, 2))
6234 return true;
6235 } else {
6236 // In C23 mode, va_start only needs one argument. However, the builtin still
6237 // requires two arguments (which matches the behavior of the GCC builtin),
6238 // <stdarg.h> passes `0` as the second argument in C23 mode.
6239 if (checkArgCount(TheCall, 2))
6240 return true;
6241 }
6242
6243 // Type-check the first argument normally.
6244 if (checkBuiltinArgument(*this, TheCall, 0))
6245 return true;
6246
6247 // Check that the current function is variadic, and get its last parameter.
6248 ParmVarDecl *LastParam;
6249 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6250 return true;
6251
6252 // Verify that the second argument to the builtin is the last non-variadic
6253 // argument of the current function or method. In C23 mode, if the call is
6254 // not to __builtin_c23_va_start, and the second argument is an integer
6255 // constant expression with value 0, then we don't bother with this check.
6256 // For __builtin_c23_va_start, we only perform the check for the second
6257 // argument being the last argument to the current function if there is a
6258 // second argument present.
6259 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6260 TheCall->getNumArgs() < 2) {
6261 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6262 return false;
6263 }
6264
6265 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6266 if (std::optional<llvm::APSInt> Val =
6268 Val && LangOpts.C23 && *Val == 0 &&
6269 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6270 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6271 return false;
6272 }
6273
6274 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6275 // next block.
6276 QualType Type;
6277 SourceLocation ParamLoc;
6278 bool IsCRegister = false;
6279 bool SecondArgIsLastNonVariadicArgument = false;
6280 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6281 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6282 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6283
6284 Type = PV->getType();
6285 ParamLoc = PV->getLocation();
6286 IsCRegister =
6287 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6288 }
6289 }
6290
6291 if (!SecondArgIsLastNonVariadicArgument)
6292 Diag(TheCall->getArg(1)->getBeginLoc(),
6293 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6294 else if (IsCRegister || Type->isReferenceType() ||
6295 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6296 // Promotable integers are UB, but enumerations need a bit of
6297 // extra checking to see what their promotable type actually is.
6298 if (!Context.isPromotableIntegerType(Type))
6299 return false;
6300 const auto *ED = Type->getAsEnumDecl();
6301 if (!ED)
6302 return true;
6303 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
6304 }()) {
6305 unsigned Reason = 0;
6306 if (Type->isReferenceType()) Reason = 1;
6307 else if (IsCRegister) Reason = 2;
6308 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6309 Diag(ParamLoc, diag::note_parameter_type) << Type;
6310 }
6311
6312 return false;
6313}
6314
6315bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6316 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6317 const LangOptions &LO = getLangOpts();
6318
6319 if (LO.CPlusPlus)
6320 return Arg->getType()
6322 .getTypePtr()
6323 ->getPointeeType()
6325
6326 // In C, allow aliasing through `char *`, this is required for AArch64 at
6327 // least.
6328 return true;
6329 };
6330
6331 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6332 // const char *named_addr);
6333
6334 Expr *Func = Call->getCallee();
6335
6336 if (Call->getNumArgs() < 3)
6337 return Diag(Call->getEndLoc(),
6338 diag::err_typecheck_call_too_few_args_at_least)
6339 << 0 /*function call*/ << 3 << Call->getNumArgs()
6340 << /*is non object*/ 0;
6341
6342 // Type-check the first argument normally.
6343 if (checkBuiltinArgument(*this, Call, 0))
6344 return true;
6345
6346 // Check that the current function is variadic.
6348 return true;
6349
6350 // __va_start on Windows does not validate the parameter qualifiers
6351
6352 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6353 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6354
6355 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6356 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6357
6358 const QualType &ConstCharPtrTy =
6359 Context.getPointerType(Context.CharTy.withConst());
6360 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6361 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6362 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6363 << 0 /* qualifier difference */
6364 << 3 /* parameter mismatch */
6365 << 2 << Arg1->getType() << ConstCharPtrTy;
6366
6367 const QualType SizeTy = Context.getSizeType();
6368 if (!Context.hasSameType(
6370 SizeTy))
6371 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6372 << Arg2->getType() << SizeTy << 1 /* different class */
6373 << 0 /* qualifier difference */
6374 << 3 /* parameter mismatch */
6375 << 3 << Arg2->getType() << SizeTy;
6376
6377 return false;
6378}
6379
6380bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6381 if (checkArgCount(TheCall, 2))
6382 return true;
6383
6384 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6385 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
6386 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6387 << 1 << 0 << TheCall->getSourceRange();
6388
6389 ExprResult OrigArg0 = TheCall->getArg(0);
6390 ExprResult OrigArg1 = TheCall->getArg(1);
6391
6392 // Do standard promotions between the two arguments, returning their common
6393 // type.
6394 QualType Res = UsualArithmeticConversions(
6395 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
6396 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6397 return true;
6398
6399 // Make sure any conversions are pushed back into the call; this is
6400 // type safe since unordered compare builtins are declared as "_Bool
6401 // foo(...)".
6402 TheCall->setArg(0, OrigArg0.get());
6403 TheCall->setArg(1, OrigArg1.get());
6404
6405 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6406 return false;
6407
6408 // If the common type isn't a real floating type, then the arguments were
6409 // invalid for this operation.
6410 if (Res.isNull() || !Res->isRealFloatingType())
6411 return Diag(OrigArg0.get()->getBeginLoc(),
6412 diag::err_typecheck_call_invalid_ordered_compare)
6413 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6414 << SourceRange(OrigArg0.get()->getBeginLoc(),
6415 OrigArg1.get()->getEndLoc());
6416
6417 return false;
6418}
6419
6420bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6421 unsigned BuiltinID) {
6422 if (checkArgCount(TheCall, NumArgs))
6423 return true;
6424
6425 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
6426 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6427 BuiltinID == Builtin::BI__builtin_isinf ||
6428 BuiltinID == Builtin::BI__builtin_isinf_sign))
6429 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6430 << 0 << 0 << TheCall->getSourceRange();
6431
6432 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6433 BuiltinID == Builtin::BI__builtin_isunordered))
6434 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6435 << 1 << 0 << TheCall->getSourceRange();
6436
6437 bool IsFPClass = NumArgs == 2;
6438
6439 // Find out position of floating-point argument.
6440 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6441
6442 // We can count on all parameters preceding the floating-point just being int.
6443 // Try all of those.
6444 for (unsigned i = 0; i < FPArgNo; ++i) {
6445 Expr *Arg = TheCall->getArg(i);
6446
6447 if (Arg->isTypeDependent())
6448 return false;
6449
6452
6453 if (Res.isInvalid())
6454 return true;
6455 TheCall->setArg(i, Res.get());
6456 }
6457
6458 Expr *OrigArg = TheCall->getArg(FPArgNo);
6459
6460 if (OrigArg->isTypeDependent())
6461 return false;
6462
6463 // We want to leave the type how it is, but do normal L->Rvalue conversions.
6465 if (!Res.isUsable())
6466 return true;
6467 OrigArg = Res.get();
6468
6469 TheCall->setArg(FPArgNo, OrigArg);
6470
6471 QualType VectorResultTy;
6472 QualType ElementTy = OrigArg->getType();
6473 // TODO: When all classification function are implemented with is_fpclass,
6474 // vector argument can be supported in all of them.
6475 if (ElementTy->isVectorType() && IsFPClass) {
6476 VectorResultTy = GetSignedVectorType(ElementTy);
6477 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6478 }
6479
6480 // This operation requires a non-_Complex floating-point number.
6481 if (!ElementTy->isRealFloatingType())
6482 return Diag(OrigArg->getBeginLoc(),
6483 diag::err_typecheck_call_invalid_unary_fp)
6484 << OrigArg->getType() << OrigArg->getSourceRange();
6485
6486 // __builtin_isfpclass has integer parameter that specify test mask. It is
6487 // passed in (...), so it should be analyzed completely here.
6488 if (IsFPClass) {
6489 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
6490 return true;
6491
6493 TheCall->getArg(NumArgs - 1), Context.IntTy, AssignmentAction::Passing);
6494 if (!MaskRes.isUsable())
6495 return true;
6496 TheCall->setArg(NumArgs - 1, MaskRes.get());
6497 }
6498
6499 // TODO: enable this code to all classification functions.
6500 if (IsFPClass) {
6501 QualType ResultTy;
6502 if (!VectorResultTy.isNull())
6503 ResultTy = VectorResultTy;
6504 else
6505 ResultTy = Context.IntTy;
6506 TheCall->setType(ResultTy);
6507 }
6508
6509 return false;
6510}
6511
6512bool Sema::BuiltinComplex(CallExpr *TheCall) {
6513 if (checkArgCount(TheCall, 2))
6514 return true;
6515
6516 bool Dependent = false;
6517 for (unsigned I = 0; I != 2; ++I) {
6518 Expr *Arg = TheCall->getArg(I);
6519 QualType T = Arg->getType();
6520 if (T->isDependentType()) {
6521 Dependent = true;
6522 continue;
6523 }
6524
6525 // Despite supporting _Complex int, GCC requires a real floating point type
6526 // for the operands of __builtin_complex.
6527 if (!T->isRealFloatingType()) {
6528 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6529 << Arg->getType() << Arg->getSourceRange();
6530 }
6531
6532 ExprResult Converted = DefaultLvalueConversion(Arg);
6533 if (Converted.isInvalid())
6534 return true;
6535 TheCall->setArg(I, Converted.get());
6536 }
6537
6538 if (Dependent) {
6539 TheCall->setType(Context.DependentTy);
6540 return false;
6541 }
6542
6543 Expr *Real = TheCall->getArg(0);
6544 Expr *Imag = TheCall->getArg(1);
6545 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6546 return Diag(Real->getBeginLoc(),
6547 diag::err_typecheck_call_different_arg_types)
6548 << Real->getType() << Imag->getType()
6549 << Real->getSourceRange() << Imag->getSourceRange();
6550 }
6551
6552 TheCall->setType(Context.getComplexType(Real->getType()));
6553 return false;
6554}
6555
6556/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6557// This is declared to take (...), so we have to check everything.
6559 unsigned NumArgs = TheCall->getNumArgs();
6560 if (NumArgs < 2)
6561 return ExprError(Diag(TheCall->getEndLoc(),
6562 diag::err_typecheck_call_too_few_args_at_least)
6563 << 0 /*function call*/ << 2 << NumArgs
6564 << /*is non object*/ 0 << TheCall->getSourceRange());
6565
6566 // Determine which of the following types of shufflevector we're checking:
6567 // 1) unary, vector mask: (lhs, mask)
6568 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6569 QualType ResType = TheCall->getArg(0)->getType();
6570 unsigned NumElements = 0;
6571
6572 if (!TheCall->getArg(0)->isTypeDependent() &&
6573 !TheCall->getArg(1)->isTypeDependent()) {
6574 QualType LHSType = TheCall->getArg(0)->getType();
6575 QualType RHSType = TheCall->getArg(1)->getType();
6576
6577 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6578 return ExprError(
6579 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6580 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6581 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6582 TheCall->getArg(1)->getEndLoc()));
6583
6584 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6585 unsigned NumResElements = NumArgs - 2;
6586
6587 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6588 // with mask. If so, verify that RHS is an integer vector type with the
6589 // same number of elts as lhs.
6590 if (NumArgs == 2) {
6591 if (!RHSType->hasIntegerRepresentation() ||
6592 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6593 return ExprError(Diag(TheCall->getBeginLoc(),
6594 diag::err_vec_builtin_incompatible_vector)
6595 << TheCall->getDirectCallee()
6596 << /*isMoreThanTwoArgs*/ false
6597 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6598 TheCall->getArg(1)->getEndLoc()));
6599 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6600 return ExprError(Diag(TheCall->getBeginLoc(),
6601 diag::err_vec_builtin_incompatible_vector)
6602 << TheCall->getDirectCallee()
6603 << /*isMoreThanTwoArgs*/ false
6604 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6605 TheCall->getArg(1)->getEndLoc()));
6606 } else if (NumElements != NumResElements) {
6607 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6608 ResType = ResType->isExtVectorType()
6609 ? Context.getExtVectorType(EltType, NumResElements)
6610 : Context.getVectorType(EltType, NumResElements,
6612 }
6613 }
6614
6615 for (unsigned I = 2; I != NumArgs; ++I) {
6616 Expr *Arg = TheCall->getArg(I);
6617 if (Arg->isTypeDependent() || Arg->isValueDependent())
6618 continue;
6619
6620 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
6621 if (!Result)
6622 return ExprError(Diag(TheCall->getBeginLoc(),
6623 diag::err_shufflevector_nonconstant_argument)
6624 << Arg->getSourceRange());
6625
6626 // Allow -1 which will be translated to undef in the IR.
6627 if (Result->isSigned() && Result->isAllOnes())
6628 ;
6629 else if (Result->getActiveBits() > 64 ||
6630 Result->getZExtValue() >= NumElements * 2)
6631 return ExprError(Diag(TheCall->getBeginLoc(),
6632 diag::err_shufflevector_argument_too_large)
6633 << Arg->getSourceRange());
6634
6635 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
6636 }
6637
6638 auto *Result = new (Context) ShuffleVectorExpr(
6639 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6640 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6641
6642 // All moved to Result.
6643 TheCall->shrinkNumArgs(0);
6644 return Result;
6645}
6646
6648 SourceLocation BuiltinLoc,
6649 SourceLocation RParenLoc) {
6652 QualType DstTy = TInfo->getType();
6653 QualType SrcTy = E->getType();
6654
6655 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6656 return ExprError(Diag(BuiltinLoc,
6657 diag::err_convertvector_non_vector)
6658 << E->getSourceRange());
6659 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6660 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6661 << "second"
6662 << "__builtin_convertvector");
6663
6664 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6665 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6666 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6667 if (SrcElts != DstElts)
6668 return ExprError(Diag(BuiltinLoc,
6669 diag::err_convertvector_incompatible_vector)
6670 << E->getSourceRange());
6671 }
6672
6673 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
6674 RParenLoc, CurFPFeatureOverrides());
6675}
6676
6677bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6678 unsigned NumArgs = TheCall->getNumArgs();
6679
6680 if (NumArgs > 3)
6681 return Diag(TheCall->getEndLoc(),
6682 diag::err_typecheck_call_too_many_args_at_most)
6683 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6684 << TheCall->getSourceRange();
6685
6686 // Argument 0 is checked for us and the remaining arguments must be
6687 // constant integers.
6688 for (unsigned i = 1; i != NumArgs; ++i)
6689 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6690 return true;
6691
6692 return false;
6693}
6694
6695bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6696 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6697 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6698 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6699 if (checkArgCount(TheCall, 1))
6700 return true;
6701 Expr *Arg = TheCall->getArg(0);
6702 if (Arg->isInstantiationDependent())
6703 return false;
6704
6705 QualType ArgTy = Arg->getType();
6706 if (!ArgTy->hasFloatingRepresentation())
6707 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6708 << ArgTy;
6709 if (Arg->isLValue()) {
6710 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6711 TheCall->setArg(0, FirstArg.get());
6712 }
6713 TheCall->setType(TheCall->getArg(0)->getType());
6714 return false;
6715}
6716
6717bool Sema::BuiltinAssume(CallExpr *TheCall) {
6718 Expr *Arg = TheCall->getArg(0);
6719 if (Arg->isInstantiationDependent()) return false;
6720
6721 if (Arg->HasSideEffects(Context))
6722 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6723 << Arg->getSourceRange()
6724 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6725
6726 return false;
6727}
6728
6729bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6730 // The alignment must be a constant integer.
6731 Expr *Arg = TheCall->getArg(1);
6732
6733 // We can't check the value of a dependent argument.
6734 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6735 if (const auto *UE =
6736 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6737 if (UE->getKind() == UETT_AlignOf ||
6738 UE->getKind() == UETT_PreferredAlignOf)
6739 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6740 << Arg->getSourceRange();
6741
6742 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6743
6744 if (!Result.isPowerOf2())
6745 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6746 << Arg->getSourceRange();
6747
6748 if (Result < Context.getCharWidth())
6749 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6750 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6751
6752 if (Result > std::numeric_limits<int32_t>::max())
6753 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6754 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6755 }
6756
6757 return false;
6758}
6759
6760bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6761 if (checkArgCountRange(TheCall, 2, 3))
6762 return true;
6763
6764 unsigned NumArgs = TheCall->getNumArgs();
6765 Expr *FirstArg = TheCall->getArg(0);
6766
6767 {
6768 ExprResult FirstArgResult =
6770 if (!FirstArgResult.get()->getType()->isPointerType()) {
6771 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6772 << TheCall->getSourceRange();
6773 return true;
6774 }
6775 TheCall->setArg(0, FirstArgResult.get());
6776 }
6777
6778 // The alignment must be a constant integer.
6779 Expr *SecondArg = TheCall->getArg(1);
6780
6781 // We can't check the value of a dependent argument.
6782 if (!SecondArg->isValueDependent()) {
6783 llvm::APSInt Result;
6784 if (BuiltinConstantArg(TheCall, 1, Result))
6785 return true;
6786
6787 if (!Result.isPowerOf2())
6788 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6789 << SecondArg->getSourceRange();
6790
6792 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6793 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6794
6795 TheCall->setArg(1,
6797 }
6798
6799 if (NumArgs > 2) {
6800 Expr *ThirdArg = TheCall->getArg(2);
6801 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType()))
6802 return true;
6803 TheCall->setArg(2, ThirdArg);
6804 }
6805
6806 return false;
6807}
6808
6809bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6810 unsigned BuiltinID =
6811 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6812 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6813
6814 unsigned NumArgs = TheCall->getNumArgs();
6815 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6816 if (NumArgs < NumRequiredArgs) {
6817 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6818 << 0 /* function call */ << NumRequiredArgs << NumArgs
6819 << /*is non object*/ 0 << TheCall->getSourceRange();
6820 }
6821 if (NumArgs >= NumRequiredArgs + 0x100) {
6822 return Diag(TheCall->getEndLoc(),
6823 diag::err_typecheck_call_too_many_args_at_most)
6824 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6825 << /*is non object*/ 0 << TheCall->getSourceRange();
6826 }
6827 unsigned i = 0;
6828
6829 // For formatting call, check buffer arg.
6830 if (!IsSizeCall) {
6831 ExprResult Arg(TheCall->getArg(i));
6832 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6833 Context, Context.VoidPtrTy, false);
6834 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6835 if (Arg.isInvalid())
6836 return true;
6837 TheCall->setArg(i, Arg.get());
6838 i++;
6839 }
6840
6841 // Check string literal arg.
6842 unsigned FormatIdx = i;
6843 {
6844 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6845 if (Arg.isInvalid())
6846 return true;
6847 TheCall->setArg(i, Arg.get());
6848 i++;
6849 }
6850
6851 // Make sure variadic args are scalar.
6852 unsigned FirstDataArg = i;
6853 while (i < NumArgs) {
6855 TheCall->getArg(i), VariadicCallType::Function, nullptr);
6856 if (Arg.isInvalid())
6857 return true;
6858 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6859 if (ArgSize.getQuantity() >= 0x100) {
6860 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6861 << i << (int)ArgSize.getQuantity() << 0xff
6862 << TheCall->getSourceRange();
6863 }
6864 TheCall->setArg(i, Arg.get());
6865 i++;
6866 }
6867
6868 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6869 // call to avoid duplicate diagnostics.
6870 if (!IsSizeCall) {
6871 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6872 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6873 bool Success = CheckFormatArguments(
6874 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
6876 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
6877 if (!Success)
6878 return true;
6879 }
6880
6881 if (IsSizeCall) {
6882 TheCall->setType(Context.getSizeType());
6883 } else {
6884 TheCall->setType(Context.VoidPtrTy);
6885 }
6886 return false;
6887}
6888
6889bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6890 llvm::APSInt &Result) {
6891 Expr *Arg = TheCall->getArg(ArgNum);
6892
6893 if (Arg->isTypeDependent() || Arg->isValueDependent())
6894 return false;
6895
6896 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
6897 if (!R) {
6898 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6899 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
6900 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6901 << FDecl->getDeclName() << Arg->getSourceRange();
6902 }
6903 Result = *R;
6904
6905 return false;
6906}
6907
6908bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6909 int High, bool RangeIsError) {
6911 return false;
6912 llvm::APSInt Result;
6913
6914 // We can't check the value of a dependent argument.
6915 Expr *Arg = TheCall->getArg(ArgNum);
6916 if (Arg->isTypeDependent() || Arg->isValueDependent())
6917 return false;
6918
6919 // Check constant-ness first.
6920 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6921 return true;
6922
6923 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6924 if (RangeIsError)
6925 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6926 << toString(Result, 10) << Low << High << Arg->getSourceRange();
6927 else
6928 // Defer the warning until we know if the code will be emitted so that
6929 // dead code can ignore this.
6930 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6931 PDiag(diag::warn_argument_invalid_range)
6932 << toString(Result, 10) << Low << High
6933 << Arg->getSourceRange());
6934 }
6935
6936 return false;
6937}
6938
6939bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6940 unsigned Num) {
6941 llvm::APSInt Result;
6942
6943 // We can't check the value of a dependent argument.
6944 Expr *Arg = TheCall->getArg(ArgNum);
6945 if (Arg->isTypeDependent() || Arg->isValueDependent())
6946 return false;
6947
6948 // Check constant-ness first.
6949 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6950 return true;
6951
6952 if (Result.getSExtValue() % Num != 0)
6953 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6954 << Num << Arg->getSourceRange();
6955
6956 return false;
6957}
6958
6959bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6960 llvm::APSInt Result;
6961
6962 // We can't check the value of a dependent argument.
6963 Expr *Arg = TheCall->getArg(ArgNum);
6964 if (Arg->isTypeDependent() || Arg->isValueDependent())
6965 return false;
6966
6967 // Check constant-ness first.
6968 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6969 return true;
6970
6971 if (Result.isPowerOf2())
6972 return false;
6973
6974 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6975 << Arg->getSourceRange();
6976}
6977
6978static bool IsShiftedByte(llvm::APSInt Value) {
6979 if (Value.isNegative())
6980 return false;
6981
6982 // Check if it's a shifted byte, by shifting it down
6983 while (true) {
6984 // If the value fits in the bottom byte, the check passes.
6985 if (Value < 0x100)
6986 return true;
6987
6988 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6989 // fails.
6990 if ((Value & 0xFF) != 0)
6991 return false;
6992
6993 // If the bottom 8 bits are all 0, but something above that is nonzero,
6994 // then shifting the value right by 8 bits won't affect whether it's a
6995 // shifted byte or not. So do that, and go round again.
6996 Value >>= 8;
6997 }
6998}
6999
7000bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
7001 unsigned ArgBits) {
7002 llvm::APSInt Result;
7003
7004 // We can't check the value of a dependent argument.
7005 Expr *Arg = TheCall->getArg(ArgNum);
7006 if (Arg->isTypeDependent() || Arg->isValueDependent())
7007 return false;
7008
7009 // Check constant-ness first.
7010 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7011 return true;
7012
7013 // Truncate to the given size.
7014 Result = Result.getLoBits(ArgBits);
7015 Result.setIsUnsigned(true);
7016
7017 if (IsShiftedByte(Result))
7018 return false;
7019
7020 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7021 << Arg->getSourceRange();
7022}
7023
7025 unsigned ArgNum,
7026 unsigned ArgBits) {
7027 llvm::APSInt Result;
7028
7029 // We can't check the value of a dependent argument.
7030 Expr *Arg = TheCall->getArg(ArgNum);
7031 if (Arg->isTypeDependent() || Arg->isValueDependent())
7032 return false;
7033
7034 // Check constant-ness first.
7035 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7036 return true;
7037
7038 // Truncate to the given size.
7039 Result = Result.getLoBits(ArgBits);
7040 Result.setIsUnsigned(true);
7041
7042 // Check to see if it's in either of the required forms.
7043 if (IsShiftedByte(Result) ||
7044 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7045 return false;
7046
7047 return Diag(TheCall->getBeginLoc(),
7048 diag::err_argument_not_shifted_byte_or_xxff)
7049 << Arg->getSourceRange();
7050}
7051
7052bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
7053 if (!Context.getTargetInfo().hasSjLjLowering())
7054 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7055 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7056
7057 Expr *Arg = TheCall->getArg(1);
7058 llvm::APSInt Result;
7059
7060 // TODO: This is less than ideal. Overload this to take a value.
7061 if (BuiltinConstantArg(TheCall, 1, Result))
7062 return true;
7063
7064 if (Result != 1)
7065 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7066 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7067
7068 return false;
7069}
7070
7071bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
7072 if (!Context.getTargetInfo().hasSjLjLowering())
7073 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7074 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7075 return false;
7076}
7077
7078bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
7079 if (checkArgCount(TheCall, 1))
7080 return true;
7081
7082 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
7083 if (ArgRes.isInvalid())
7084 return true;
7085
7086 // For simplicity, we support only limited expressions for the argument.
7087 // Specifically a flexible array member or a pointer with counted_by:
7088 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
7089 // complex casting, which really shouldn't be a huge problem.
7090 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
7091 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
7092 return Diag(Arg->getBeginLoc(),
7093 diag::err_builtin_counted_by_ref_invalid_arg)
7094 << Arg->getSourceRange();
7095
7096 if (Arg->HasSideEffects(Context))
7097 return Diag(Arg->getBeginLoc(),
7098 diag::err_builtin_counted_by_ref_has_side_effects)
7099 << Arg->getSourceRange();
7100
7101 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
7102 const auto *CATy =
7103 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
7104
7105 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
7106 // Member has counted_by attribute - return pointer to count field
7107 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
7108 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
7109 TheCall->setType(Context.getPointerType(CountFD->getType()));
7110 return false;
7111 }
7112 }
7113
7114 // FAMs and pointers without counted_by return void*
7115 QualType MemberTy = ME->getMemberDecl()->getType();
7116 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
7117 return Diag(Arg->getBeginLoc(),
7118 diag::err_builtin_counted_by_ref_invalid_arg)
7119 << Arg->getSourceRange();
7120 } else {
7121 return Diag(Arg->getBeginLoc(),
7122 diag::err_builtin_counted_by_ref_invalid_arg)
7123 << Arg->getSourceRange();
7124 }
7125
7126 TheCall->setType(Context.getPointerType(Context.VoidTy));
7127 return false;
7128}
7129
7130/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
7131/// It allows leaking and modification of bounds safety information.
7132bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
7134 const CallExpr *CE =
7135 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
7136 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
7137 return false;
7138
7139 switch (K) {
7142 Diag(E->getExprLoc(),
7143 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7144 << 0 << E->getSourceRange();
7145 break;
7147 Diag(E->getExprLoc(),
7148 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7149 << 1 << E->getSourceRange();
7150 break;
7152 Diag(E->getExprLoc(),
7153 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7154 << 2 << E->getSourceRange();
7155 break;
7157 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7158 << 0 << E->getSourceRange();
7159 break;
7161 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7162 << 1 << E->getSourceRange();
7163 break;
7164 }
7165
7166 return true;
7167}
7168
7169namespace {
7170
7171class UncoveredArgHandler {
7172 enum { Unknown = -1, AllCovered = -2 };
7173
7174 signed FirstUncoveredArg = Unknown;
7175 SmallVector<const Expr *, 4> DiagnosticExprs;
7176
7177public:
7178 UncoveredArgHandler() = default;
7179
7180 bool hasUncoveredArg() const {
7181 return (FirstUncoveredArg >= 0);
7182 }
7183
7184 unsigned getUncoveredArg() const {
7185 assert(hasUncoveredArg() && "no uncovered argument");
7186 return FirstUncoveredArg;
7187 }
7188
7189 void setAllCovered() {
7190 // A string has been found with all arguments covered, so clear out
7191 // the diagnostics.
7192 DiagnosticExprs.clear();
7193 FirstUncoveredArg = AllCovered;
7194 }
7195
7196 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7197 assert(NewFirstUncoveredArg >= 0 && "Outside range");
7198
7199 // Don't update if a previous string covers all arguments.
7200 if (FirstUncoveredArg == AllCovered)
7201 return;
7202
7203 // UncoveredArgHandler tracks the highest uncovered argument index
7204 // and with it all the strings that match this index.
7205 if (NewFirstUncoveredArg == FirstUncoveredArg)
7206 DiagnosticExprs.push_back(StrExpr);
7207 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7208 DiagnosticExprs.clear();
7209 DiagnosticExprs.push_back(StrExpr);
7210 FirstUncoveredArg = NewFirstUncoveredArg;
7211 }
7212 }
7213
7214 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7215};
7216
7217enum StringLiteralCheckType {
7218 SLCT_NotALiteral,
7219 SLCT_UncheckedLiteral,
7220 SLCT_CheckedLiteral
7221};
7222
7223} // namespace
7224
7225static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7226 BinaryOperatorKind BinOpKind,
7227 bool AddendIsRight) {
7228 unsigned BitWidth = Offset.getBitWidth();
7229 unsigned AddendBitWidth = Addend.getBitWidth();
7230 // There might be negative interim results.
7231 if (Addend.isUnsigned()) {
7232 Addend = Addend.zext(++AddendBitWidth);
7233 Addend.setIsSigned(true);
7234 }
7235 // Adjust the bit width of the APSInts.
7236 if (AddendBitWidth > BitWidth) {
7237 Offset = Offset.sext(AddendBitWidth);
7238 BitWidth = AddendBitWidth;
7239 } else if (BitWidth > AddendBitWidth) {
7240 Addend = Addend.sext(BitWidth);
7241 }
7242
7243 bool Ov = false;
7244 llvm::APSInt ResOffset = Offset;
7245 if (BinOpKind == BO_Add)
7246 ResOffset = Offset.sadd_ov(Addend, Ov);
7247 else {
7248 assert(AddendIsRight && BinOpKind == BO_Sub &&
7249 "operator must be add or sub with addend on the right");
7250 ResOffset = Offset.ssub_ov(Addend, Ov);
7251 }
7252
7253 // We add an offset to a pointer here so we should support an offset as big as
7254 // possible.
7255 if (Ov) {
7256 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7257 "index (intermediate) result too big");
7258 Offset = Offset.sext(2 * BitWidth);
7259 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7260 return;
7261 }
7262
7263 Offset = std::move(ResOffset);
7264}
7265
7266namespace {
7267
7268// This is a wrapper class around StringLiteral to support offsetted string
7269// literals as format strings. It takes the offset into account when returning
7270// the string and its length or the source locations to display notes correctly.
7271class FormatStringLiteral {
7272 const StringLiteral *FExpr;
7273 int64_t Offset;
7274
7275public:
7276 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7277 : FExpr(fexpr), Offset(Offset) {}
7278
7279 const StringLiteral *getFormatString() const { return FExpr; }
7280
7281 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
7282
7283 unsigned getByteLength() const {
7284 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7285 }
7286
7287 unsigned getLength() const { return FExpr->getLength() - Offset; }
7288 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7289
7290 StringLiteralKind getKind() const { return FExpr->getKind(); }
7291
7292 QualType getType() const { return FExpr->getType(); }
7293
7294 bool isAscii() const { return FExpr->isOrdinary(); }
7295 bool isWide() const { return FExpr->isWide(); }
7296 bool isUTF8() const { return FExpr->isUTF8(); }
7297 bool isUTF16() const { return FExpr->isUTF16(); }
7298 bool isUTF32() const { return FExpr->isUTF32(); }
7299 bool isPascal() const { return FExpr->isPascal(); }
7300
7301 SourceLocation getLocationOfByte(
7302 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7303 const TargetInfo &Target, unsigned *StartToken = nullptr,
7304 unsigned *StartTokenByteOffset = nullptr) const {
7305 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7306 StartToken, StartTokenByteOffset);
7307 }
7308
7309 SourceLocation getBeginLoc() const LLVM_READONLY {
7310 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7311 }
7312
7313 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7314};
7315
7316} // namespace
7317
7318static void CheckFormatString(
7319 Sema &S, const FormatStringLiteral *FExpr,
7320 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7322 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7323 bool inFunctionCall, VariadicCallType CallType,
7324 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7325 bool IgnoreStringsWithoutSpecifiers);
7326
7327static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7328 const Expr *E);
7329
7330// Determine if an expression is a string literal or constant string.
7331// If this function returns false on the arguments to a function expecting a
7332// format string, we will usually need to emit a warning.
7333// True string literals are then checked by CheckFormatString.
7334static StringLiteralCheckType
7335checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7336 const Expr *E, ArrayRef<const Expr *> Args,
7337 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7338 unsigned firstDataArg, FormatStringType Type,
7339 VariadicCallType CallType, bool InFunctionCall,
7340 llvm::SmallBitVector &CheckedVarArgs,
7341 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7342 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7343 bool IgnoreStringsWithoutSpecifiers = false) {
7345 return SLCT_NotALiteral;
7346tryAgain:
7347 assert(Offset.isSigned() && "invalid offset");
7348
7349 if (E->isTypeDependent() || E->isValueDependent())
7350 return SLCT_NotALiteral;
7351
7352 E = E->IgnoreParenCasts();
7353
7355 // Technically -Wformat-nonliteral does not warn about this case.
7356 // The behavior of printf and friends in this case is implementation
7357 // dependent. Ideally if the format string cannot be null then
7358 // it should have a 'nonnull' attribute in the function prototype.
7359 return SLCT_UncheckedLiteral;
7360
7361 switch (E->getStmtClass()) {
7362 case Stmt::InitListExprClass:
7363 // Handle expressions like {"foobar"}.
7364 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
7365 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7366 format_idx, firstDataArg, Type, CallType,
7367 /*InFunctionCall*/ false, CheckedVarArgs,
7368 UncoveredArg, Offset, CallerFormatParamIdx,
7369 IgnoreStringsWithoutSpecifiers);
7370 }
7371 return SLCT_NotALiteral;
7372 case Stmt::BinaryConditionalOperatorClass:
7373 case Stmt::ConditionalOperatorClass: {
7374 // The expression is a literal if both sub-expressions were, and it was
7375 // completely checked only if both sub-expressions were checked.
7378
7379 // Determine whether it is necessary to check both sub-expressions, for
7380 // example, because the condition expression is a constant that can be
7381 // evaluated at compile time.
7382 bool CheckLeft = true, CheckRight = true;
7383
7384 bool Cond;
7385 if (C->getCond()->EvaluateAsBooleanCondition(
7386 Cond, S.getASTContext(), S.isConstantEvaluatedContext())) {
7387 if (Cond)
7388 CheckRight = false;
7389 else
7390 CheckLeft = false;
7391 }
7392
7393 // We need to maintain the offsets for the right and the left hand side
7394 // separately to check if every possible indexed expression is a valid
7395 // string literal. They might have different offsets for different string
7396 // literals in the end.
7397 StringLiteralCheckType Left;
7398 if (!CheckLeft)
7399 Left = SLCT_UncheckedLiteral;
7400 else {
7401 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
7402 Args, APK, format_idx, firstDataArg, Type,
7403 CallType, InFunctionCall, CheckedVarArgs,
7404 UncoveredArg, Offset, CallerFormatParamIdx,
7405 IgnoreStringsWithoutSpecifiers);
7406 if (Left == SLCT_NotALiteral || !CheckRight) {
7407 return Left;
7408 }
7409 }
7410
7411 StringLiteralCheckType Right = checkFormatStringExpr(
7412 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
7413 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7414 UncoveredArg, Offset, CallerFormatParamIdx,
7415 IgnoreStringsWithoutSpecifiers);
7416
7417 return (CheckLeft && Left < Right) ? Left : Right;
7418 }
7419
7420 case Stmt::ImplicitCastExprClass:
7421 E = cast<ImplicitCastExpr>(E)->getSubExpr();
7422 goto tryAgain;
7423
7424 case Stmt::OpaqueValueExprClass:
7425 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7426 E = src;
7427 goto tryAgain;
7428 }
7429 return SLCT_NotALiteral;
7430
7431 case Stmt::PredefinedExprClass:
7432 // While __func__, etc., are technically not string literals, they
7433 // cannot contain format specifiers and thus are not a security
7434 // liability.
7435 return SLCT_UncheckedLiteral;
7436
7437 case Stmt::DeclRefExprClass: {
7438 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7439
7440 // As an exception, do not flag errors for variables binding to
7441 // const string literals.
7442 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7443 bool isConstant = false;
7444 QualType T = DR->getType();
7445
7446 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7447 isConstant = AT->getElementType().isConstant(S.Context);
7448 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7449 isConstant = T.isConstant(S.Context) &&
7450 PT->getPointeeType().isConstant(S.Context);
7451 } else if (T->isObjCObjectPointerType()) {
7452 // In ObjC, there is usually no "const ObjectPointer" type,
7453 // so don't check if the pointee type is constant.
7454 isConstant = T.isConstant(S.Context);
7455 }
7456
7457 if (isConstant) {
7458 if (const Expr *Init = VD->getAnyInitializer()) {
7459 // Look through initializers like const char c[] = { "foo" }
7460 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7461 if (InitList->isStringLiteralInit())
7462 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7463 }
7464 return checkFormatStringExpr(
7465 S, ReferenceFormatString, Init, Args, APK, format_idx,
7466 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7467 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7468 }
7469 }
7470
7471 // When the format argument is an argument of this function, and this
7472 // function also has the format attribute, there are several interactions
7473 // for which there shouldn't be a warning. For instance, when calling
7474 // v*printf from a function that has the printf format attribute, we
7475 // should not emit a warning about using `fmt`, even though it's not
7476 // constant, because the arguments have already been checked for the
7477 // caller of `logmessage`:
7478 //
7479 // __attribute__((format(printf, 1, 2)))
7480 // void logmessage(char const *fmt, ...) {
7481 // va_list ap;
7482 // va_start(ap, fmt);
7483 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7484 // ...
7485 // }
7486 //
7487 // Another interaction that we need to support is using a format string
7488 // specified by the format_matches attribute:
7489 //
7490 // __attribute__((format_matches(printf, 1, "%s %d")))
7491 // void logmessage(char const *fmt, const char *a, int b) {
7492 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7493 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7494 // ...
7495 // }
7496 //
7497 // Yet another interaction that we need to support is calling a variadic
7498 // format function from a format function that has fixed arguments. For
7499 // instance:
7500 //
7501 // __attribute__((format(printf, 1, 2)))
7502 // void logstring(char const *fmt, char const *str) {
7503 // printf(fmt, str); /* do not emit a warning about "fmt" */
7504 // }
7505 //
7506 // Same (and perhaps more relatably) for the variadic template case:
7507 //
7508 // template<typename... Args>
7509 // __attribute__((format(printf, 1, 2)))
7510 // void log(const char *fmt, Args&&... args) {
7511 // printf(fmt, forward<Args>(args)...);
7512 // /* do not emit a warning about "fmt" */
7513 // }
7514 //
7515 // Due to implementation difficulty, we only check the format, not the
7516 // format arguments, in all cases.
7517 //
7518 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
7519 if (CallerFormatParamIdx)
7520 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7521 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
7522 for (const auto *PVFormatMatches :
7523 D->specific_attrs<FormatMatchesAttr>()) {
7524 Sema::FormatStringInfo CalleeFSI;
7525 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
7526 0, &CalleeFSI))
7527 continue;
7528 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7529 // If using the wrong type of format string, emit a diagnostic
7530 // here and stop checking to avoid irrelevant diagnostics.
7531 if (Type != S.GetFormatStringType(PVFormatMatches)) {
7532 S.Diag(Args[format_idx]->getBeginLoc(),
7533 diag::warn_format_string_type_incompatible)
7534 << PVFormatMatches->getType()->getName()
7536 if (!InFunctionCall) {
7537 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
7538 diag::note_format_string_defined);
7539 }
7540 return SLCT_UncheckedLiteral;
7541 }
7542 return checkFormatStringExpr(
7543 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
7544 Args, APK, format_idx, firstDataArg, Type, CallType,
7545 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7546 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7547 }
7548 }
7549
7550 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7551 Sema::FormatStringInfo CallerFSI;
7552 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
7553 PVFormat->getFirstArg(), &CallerFSI))
7554 continue;
7555 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7556 // We also check if the formats are compatible.
7557 // We can't pass a 'scanf' string to a 'printf' function.
7558 if (Type != S.GetFormatStringType(PVFormat)) {
7559 S.Diag(Args[format_idx]->getBeginLoc(),
7560 diag::warn_format_string_type_incompatible)
7561 << PVFormat->getType()->getName()
7563 if (!InFunctionCall) {
7564 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
7565 }
7566 return SLCT_UncheckedLiteral;
7567 }
7568 // Lastly, check that argument passing kinds transition in a
7569 // way that makes sense:
7570 // from a caller with FAPK_VAList, allow FAPK_VAList
7571 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7572 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7573 // from a caller with FAPK_Variadic, allow FAPK_VAList
7574 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
7579 return SLCT_UncheckedLiteral;
7580 }
7581 }
7582 }
7583 }
7584 }
7585 }
7586
7587 return SLCT_NotALiteral;
7588 }
7589
7590 case Stmt::CallExprClass:
7591 case Stmt::CXXMemberCallExprClass: {
7592 const CallExpr *CE = cast<CallExpr>(E);
7593 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7594 bool IsFirst = true;
7595 StringLiteralCheckType CommonResult;
7596 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7597 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7598 StringLiteralCheckType Result = checkFormatStringExpr(
7599 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7600 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7601 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7602 if (IsFirst) {
7603 CommonResult = Result;
7604 IsFirst = false;
7605 }
7606 }
7607 if (!IsFirst)
7608 return CommonResult;
7609
7610 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7611 unsigned BuiltinID = FD->getBuiltinID();
7612 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7613 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7614 const Expr *Arg = CE->getArg(0);
7615 return checkFormatStringExpr(
7616 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7617 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7618 UncoveredArg, Offset, CallerFormatParamIdx,
7619 IgnoreStringsWithoutSpecifiers);
7620 }
7621 }
7622 }
7623 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
7624 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7625 format_idx, firstDataArg, Type, CallType,
7626 /*InFunctionCall*/ false, CheckedVarArgs,
7627 UncoveredArg, Offset, CallerFormatParamIdx,
7628 IgnoreStringsWithoutSpecifiers);
7629 return SLCT_NotALiteral;
7630 }
7631 case Stmt::ObjCMessageExprClass: {
7632 const auto *ME = cast<ObjCMessageExpr>(E);
7633 if (const auto *MD = ME->getMethodDecl()) {
7634 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7635 // As a special case heuristic, if we're using the method -[NSBundle
7636 // localizedStringForKey:value:table:], ignore any key strings that lack
7637 // format specifiers. The idea is that if the key doesn't have any
7638 // format specifiers then its probably just a key to map to the
7639 // localized strings. If it does have format specifiers though, then its
7640 // likely that the text of the key is the format string in the
7641 // programmer's language, and should be checked.
7642 const ObjCInterfaceDecl *IFace;
7643 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7644 IFace->getIdentifier()->isStr("NSBundle") &&
7645 MD->getSelector().isKeywordSelector(
7646 {"localizedStringForKey", "value", "table"})) {
7647 IgnoreStringsWithoutSpecifiers = true;
7648 }
7649
7650 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7651 return checkFormatStringExpr(
7652 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7653 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7654 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7655 }
7656 }
7657
7658 return SLCT_NotALiteral;
7659 }
7660 case Stmt::ObjCStringLiteralClass:
7661 case Stmt::StringLiteralClass: {
7662 const StringLiteral *StrE = nullptr;
7663
7664 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7665 StrE = ObjCFExpr->getString();
7666 else
7667 StrE = cast<StringLiteral>(E);
7668
7669 if (StrE) {
7670 if (Offset.isNegative() || Offset > StrE->getLength()) {
7671 // TODO: It would be better to have an explicit warning for out of
7672 // bounds literals.
7673 return SLCT_NotALiteral;
7674 }
7675 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7676 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
7677 format_idx, firstDataArg, Type, InFunctionCall,
7678 CallType, CheckedVarArgs, UncoveredArg,
7679 IgnoreStringsWithoutSpecifiers);
7680 return SLCT_CheckedLiteral;
7681 }
7682
7683 return SLCT_NotALiteral;
7684 }
7685 case Stmt::BinaryOperatorClass: {
7686 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7687
7688 // A string literal + an int offset is still a string literal.
7689 if (BinOp->isAdditiveOp()) {
7690 Expr::EvalResult LResult, RResult;
7691
7692 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7693 LResult, S.Context, Expr::SE_NoSideEffects,
7695 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7696 RResult, S.Context, Expr::SE_NoSideEffects,
7698
7699 if (LIsInt != RIsInt) {
7700 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7701
7702 if (LIsInt) {
7703 if (BinOpKind == BO_Add) {
7704 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7705 E = BinOp->getRHS();
7706 goto tryAgain;
7707 }
7708 } else {
7709 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7710 E = BinOp->getLHS();
7711 goto tryAgain;
7712 }
7713 }
7714 }
7715
7716 return SLCT_NotALiteral;
7717 }
7718 case Stmt::UnaryOperatorClass: {
7719 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7720 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7721 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7722 Expr::EvalResult IndexResult;
7723 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7726 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7727 /*RHS is int*/ true);
7728 E = ASE->getBase();
7729 goto tryAgain;
7730 }
7731 }
7732
7733 return SLCT_NotALiteral;
7734 }
7735
7736 default:
7737 return SLCT_NotALiteral;
7738 }
7739}
7740
7741// If this expression can be evaluated at compile-time,
7742// check if the result is a StringLiteral and return it
7743// otherwise return nullptr
7745 const Expr *E) {
7747 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7748 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7749 if (isa_and_nonnull<StringLiteral>(LVE))
7750 return LVE;
7751 }
7752 return nullptr;
7753}
7754
7756 switch (FST) {
7758 return "scanf";
7760 return "printf";
7762 return "NSString";
7764 return "strftime";
7766 return "strfmon";
7768 return "kprintf";
7770 return "freebsd_kprintf";
7772 return "os_log";
7773 default:
7774 return "<unknown>";
7775 }
7776}
7777
7779 return llvm::StringSwitch<FormatStringType>(Flavor)
7780 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7781 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7783 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7784 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7785 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7786 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7788 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7789 .Case("os_trace", FormatStringType::OSLog)
7790 .Case("os_log", FormatStringType::OSLog)
7791 .Default(FormatStringType::Unknown);
7792}
7793
7795 return GetFormatStringType(Format->getType()->getName());
7796}
7797
7798FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7799 return GetFormatStringType(Format->getType()->getName());
7800}
7801
7802bool Sema::CheckFormatArguments(const FormatAttr *Format,
7803 ArrayRef<const Expr *> Args, bool IsCXXMember,
7804 VariadicCallType CallType, SourceLocation Loc,
7805 SourceRange Range,
7806 llvm::SmallBitVector &CheckedVarArgs) {
7807 FormatStringInfo FSI;
7808 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7809 IsCXXMember,
7810 CallType != VariadicCallType::DoesNotApply, &FSI))
7811 return CheckFormatArguments(
7812 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7813 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7814 return false;
7815}
7816
7817bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7818 ArrayRef<const Expr *> Args, bool IsCXXMember,
7819 VariadicCallType CallType, SourceLocation Loc,
7820 SourceRange Range,
7821 llvm::SmallBitVector &CheckedVarArgs) {
7822 FormatStringInfo FSI;
7823 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
7824 &FSI)) {
7825 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7826 return CheckFormatArguments(Args, FSI.ArgPassingKind,
7827 Format->getFormatString(), FSI.FormatIdx,
7828 FSI.FirstDataArg, GetFormatStringType(Format),
7829 CallType, Loc, Range, CheckedVarArgs);
7830 }
7831 return false;
7832}
7833
7836 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7837 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7838 SourceLocation Loc) {
7839 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
7840 return false;
7841
7842 DeclContext *DC = S->CurContext;
7843 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
7844 return false;
7845 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
7846
7847 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
7848
7849 // Find the offset to convert between attribute and parameter indexes.
7850 unsigned CallerArgumentIndexOffset =
7851 hasImplicitObjectParameter(Caller) ? 2 : 1;
7852
7853 unsigned FirstArgumentIndex = -1;
7854 switch (APK) {
7857 // As an extension, clang allows the format attribute on non-variadic
7858 // functions.
7859 // Caller must have fixed arguments to pass them to a fixed or variadic
7860 // function. Try to match caller and callee arguments. If successful, then
7861 // emit a diag with the caller idx, otherwise we can't determine the callee
7862 // arguments.
7863 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7864 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7865 // There aren't enough arguments in the caller to pass to callee.
7866 return false;
7867 }
7868 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7869 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7870 const auto *Arg =
7871 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
7872 if (!Arg)
7873 return false;
7874 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
7875 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7876 return false;
7877 }
7878 FirstArgumentIndex =
7879 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7880 break;
7881 }
7883 // Caller arguments are either variadic or a va_list.
7884 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
7885 ? (NumCallerParams + CallerArgumentIndexOffset)
7886 : 0;
7887 break;
7889 // The callee has a format_matches attribute. We will emit that instead.
7890 if (!ReferenceFormatString)
7891 return false;
7892 break;
7893 }
7894
7895 // Emit the diagnostic and fixit.
7896 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7897 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
7898 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
7899 do {
7900 std::string Attr, Fixit;
7901 llvm::raw_string_ostream AttrOS(Attr);
7903 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7904 << FirstArgumentIndex << ")";
7905 } else {
7906 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7907 << ", \"";
7908 AttrOS.write_escaped(ReferenceFormatString->getString());
7909 AttrOS << "\")";
7910 }
7911 AttrOS.flush();
7912 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
7913 if (ND)
7914 DB << ND;
7915 else
7916 DB << "block";
7917
7918 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7919 if (isa<BlockDecl>(Caller))
7920 break;
7921
7922 SourceLocation SL;
7923 llvm::raw_string_ostream IS(Fixit);
7924 // The attribute goes at the start of the declaration in C/C++ functions
7925 // and methods, but after the declaration for Objective-C methods.
7926 if (isa<ObjCMethodDecl>(Caller)) {
7927 IS << ' ';
7928 SL = Caller->getEndLoc();
7929 }
7930 const LangOptions &LO = S->getLangOpts();
7931 if (LO.C23 || LO.CPlusPlus11)
7932 IS << "[[gnu::" << Attr << "]]";
7933 else if (LO.ObjC || LO.GNUMode)
7934 IS << "__attribute__((" << Attr << "))";
7935 else
7936 break;
7937 if (!isa<ObjCMethodDecl>(Caller)) {
7938 IS << ' ';
7939 SL = Caller->getBeginLoc();
7940 }
7941 IS.flush();
7942
7943 DB << FixItHint::CreateInsertion(SL, Fixit);
7944 } while (false);
7945
7946 // Add implicit format or format_matches attribute.
7948 Caller->addAttr(FormatAttr::CreateImplicit(
7949 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7950 FormatStringIndex, FirstArgumentIndex));
7951 } else {
7952 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
7953 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
7954 FormatStringIndex, ReferenceFormatString));
7955 }
7956
7957 {
7958 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
7959 if (ND)
7960 DB << ND;
7961 else
7962 DB << "block";
7963 }
7964 return true;
7965}
7966
7967bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7969 StringLiteral *ReferenceFormatString,
7970 unsigned format_idx, unsigned firstDataArg,
7972 VariadicCallType CallType, SourceLocation Loc,
7973 SourceRange Range,
7974 llvm::SmallBitVector &CheckedVarArgs) {
7975 // CHECK: printf/scanf-like function is called with no format string.
7976 if (format_idx >= Args.size()) {
7977 Diag(Loc, diag::warn_missing_format_string) << Range;
7978 return false;
7979 }
7980
7981 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7982
7983 // CHECK: format string is not a string literal.
7984 //
7985 // Dynamically generated format strings are difficult to
7986 // automatically vet at compile time. Requiring that format strings
7987 // are string literals: (1) permits the checking of format strings by
7988 // the compiler and thereby (2) can practically remove the source of
7989 // many format string exploits.
7990
7991 // Format string can be either ObjC string (e.g. @"%d") or
7992 // C string (e.g. "%d")
7993 // ObjC string uses the same format specifiers as C string, so we can use
7994 // the same format string checking logic for both ObjC and C strings.
7995 UncoveredArgHandler UncoveredArg;
7996 std::optional<unsigned> CallerParamIdx;
7997 StringLiteralCheckType CT = checkFormatStringExpr(
7998 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
7999 firstDataArg, Type, CallType,
8000 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
8001 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
8002
8003 // Generate a diagnostic where an uncovered argument is detected.
8004 if (UncoveredArg.hasUncoveredArg()) {
8005 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8006 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8007 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8008 }
8009
8010 if (CT != SLCT_NotALiteral)
8011 // Literal format string found, check done!
8012 return CT == SLCT_CheckedLiteral;
8013
8014 // Do not emit diag when the string param is a macro expansion and the
8015 // format is either NSString or CFString. This is a hack to prevent
8016 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8017 // which are usually used in place of NS and CF string literals.
8018 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8020 SourceMgr.isInSystemMacro(FormatLoc))
8021 return false;
8022
8023 if (CallerParamIdx && CheckMissingFormatAttribute(
8024 this, Args, APK, ReferenceFormatString, format_idx,
8025 firstDataArg, Type, *CallerParamIdx, Loc))
8026 return false;
8027
8028 // Strftime is particular as it always uses a single 'time' argument,
8029 // so it is safe to pass a non-literal string.
8031 return false;
8032
8033 // If there are no arguments specified, warn with -Wformat-security, otherwise
8034 // warn only with -Wformat-nonliteral.
8035 if (Args.size() == firstDataArg) {
8036 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8037 << OrigFormatExpr->getSourceRange();
8038 switch (Type) {
8039 default:
8040 break;
8044 Diag(FormatLoc, diag::note_format_security_fixit)
8045 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8046 break;
8048 Diag(FormatLoc, diag::note_format_security_fixit)
8049 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8050 break;
8051 }
8052 } else {
8053 Diag(FormatLoc, diag::warn_format_nonliteral)
8054 << OrigFormatExpr->getSourceRange();
8055 }
8056 return false;
8057}
8058
8059namespace {
8060
8061class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8062protected:
8063 Sema &S;
8064 const FormatStringLiteral *FExpr;
8065 const Expr *OrigFormatExpr;
8066 const FormatStringType FSType;
8067 const unsigned FirstDataArg;
8068 const unsigned NumDataArgs;
8069 const char *Beg; // Start of format string.
8070 const Sema::FormatArgumentPassingKind ArgPassingKind;
8071 ArrayRef<const Expr *> Args;
8072 unsigned FormatIdx;
8073 llvm::SmallBitVector CoveredArgs;
8074 bool usesPositionalArgs = false;
8075 bool atFirstArg = true;
8076 bool inFunctionCall;
8077 VariadicCallType CallType;
8078 llvm::SmallBitVector &CheckedVarArgs;
8079 UncoveredArgHandler &UncoveredArg;
8080
8081public:
8082 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8083 const Expr *origFormatExpr, const FormatStringType type,
8084 unsigned firstDataArg, unsigned numDataArgs,
8085 const char *beg, Sema::FormatArgumentPassingKind APK,
8086 ArrayRef<const Expr *> Args, unsigned formatIdx,
8087 bool inFunctionCall, VariadicCallType callType,
8088 llvm::SmallBitVector &CheckedVarArgs,
8089 UncoveredArgHandler &UncoveredArg)
8090 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8091 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8092 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
8093 inFunctionCall(inFunctionCall), CallType(callType),
8094 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8095 CoveredArgs.resize(numDataArgs);
8096 CoveredArgs.reset();
8097 }
8098
8099 bool HasFormatArguments() const {
8100 return ArgPassingKind == Sema::FAPK_Fixed ||
8101 ArgPassingKind == Sema::FAPK_Variadic;
8102 }
8103
8104 void DoneProcessing();
8105
8106 void HandleIncompleteSpecifier(const char *startSpecifier,
8107 unsigned specifierLen) override;
8108
8109 void HandleInvalidLengthModifier(
8110 const analyze_format_string::FormatSpecifier &FS,
8111 const analyze_format_string::ConversionSpecifier &CS,
8112 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
8113
8114 void HandleNonStandardLengthModifier(
8115 const analyze_format_string::FormatSpecifier &FS,
8116 const char *startSpecifier, unsigned specifierLen);
8117
8118 void HandleNonStandardConversionSpecifier(
8119 const analyze_format_string::ConversionSpecifier &CS,
8120 const char *startSpecifier, unsigned specifierLen);
8121
8122 void HandlePosition(const char *startPos, unsigned posLen) override;
8123
8124 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
8126
8127 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8128
8129 void HandleNullChar(const char *nullCharacter) override;
8130
8131 template <typename Range>
8132 static void
8133 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8134 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8135 bool IsStringLocation, Range StringRange,
8136 ArrayRef<FixItHint> Fixit = {});
8137
8138protected:
8139 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8140 const char *startSpec,
8141 unsigned specifierLen,
8142 const char *csStart, unsigned csLen);
8143
8144 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8145 const char *startSpec,
8146 unsigned specifierLen);
8147
8148 SourceRange getFormatStringRange();
8149 CharSourceRange getSpecifierRange(const char *startSpecifier,
8150 unsigned specifierLen);
8151 SourceLocation getLocationOfByte(const char *x);
8152
8153 const Expr *getDataArg(unsigned i) const;
8154
8155 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8156 const analyze_format_string::ConversionSpecifier &CS,
8157 const char *startSpecifier, unsigned specifierLen,
8158 unsigned argIndex);
8159
8160 bool CheckUnsupportedType(const analyze_format_string::ArgType &AT,
8161 const Expr *E, const char *startSpecifier,
8162 unsigned specifierLen);
8163
8164 template <typename Range>
8165 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8166 bool IsStringLocation, Range StringRange,
8167 ArrayRef<FixItHint> Fixit = {});
8168};
8169
8170} // namespace
8171
8172SourceRange CheckFormatHandler::getFormatStringRange() {
8173 return OrigFormatExpr->getSourceRange();
8174}
8175
8177CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
8178 unsigned specifierLen) {
8179 SourceLocation Start = getLocationOfByte(startSpecifier);
8180 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
8181
8182 // Advance the end SourceLocation by one due to half-open ranges.
8183 End = End.getLocWithOffset(1);
8184
8185 return CharSourceRange::getCharRange(Start, End);
8186}
8187
8188SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8189 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8191}
8192
8193void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8194 unsigned specifierLen) {
8195 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8196 getLocationOfByte(startSpecifier),
8197 /*IsStringLocation*/ true,
8198 getSpecifierRange(startSpecifier, specifierLen));
8199}
8200
8201bool CheckFormatHandler::CheckUnsupportedType(
8202 const analyze_format_string::ArgType &AT, const Expr *E,
8203 const char *StartSpecifier, unsigned SpecifierLen) {
8204 if (!AT.isUnsupported())
8205 return false;
8206
8207 EmitFormatDiagnostic(S.PDiag(diag::warn_format_unsupported_type)
8209 E->getExprLoc(), /*IsStringLocation=*/false,
8210 getSpecifierRange(StartSpecifier, SpecifierLen));
8211 return true;
8212}
8213
8214void CheckFormatHandler::HandleInvalidLengthModifier(
8217 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8218 using namespace analyze_format_string;
8219
8220 const LengthModifier &LM = FS.getLengthModifier();
8221 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8222
8223 // See if we know how to fix this length modifier.
8224 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8225 if (FixedLM) {
8226 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8227 getLocationOfByte(LM.getStart()),
8228 /*IsStringLocation*/ true,
8229 getSpecifierRange(startSpecifier, specifierLen));
8230
8231 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8232 << FixedLM->toString()
8233 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8234
8235 } else {
8236 FixItHint Hint;
8237 if (DiagID == diag::warn_format_nonsensical_length)
8238 Hint = FixItHint::CreateRemoval(LMRange);
8239
8240 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8241 getLocationOfByte(LM.getStart()),
8242 /*IsStringLocation*/ true,
8243 getSpecifierRange(startSpecifier, specifierLen), Hint);
8244 }
8245}
8246
8247void CheckFormatHandler::HandleNonStandardLengthModifier(
8249 const char *startSpecifier, unsigned specifierLen) {
8250 using namespace analyze_format_string;
8251
8252 const LengthModifier &LM = FS.getLengthModifier();
8253 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8254
8255 // See if we know how to fix this length modifier.
8256 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8257 if (FixedLM) {
8258 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8259 << LM.toString() << 0,
8260 getLocationOfByte(LM.getStart()),
8261 /*IsStringLocation*/ true,
8262 getSpecifierRange(startSpecifier, specifierLen));
8263
8264 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8265 << FixedLM->toString()
8266 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8267
8268 } else {
8269 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8270 << LM.toString() << 0,
8271 getLocationOfByte(LM.getStart()),
8272 /*IsStringLocation*/ true,
8273 getSpecifierRange(startSpecifier, specifierLen));
8274 }
8275}
8276
8277void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8279 const char *startSpecifier, unsigned specifierLen) {
8280 using namespace analyze_format_string;
8281
8282 // See if we know how to fix this conversion specifier.
8283 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8284 if (FixedCS) {
8285 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8286 << CS.toString() << /*conversion specifier*/ 1,
8287 getLocationOfByte(CS.getStart()),
8288 /*IsStringLocation*/ true,
8289 getSpecifierRange(startSpecifier, specifierLen));
8290
8291 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8292 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8293 << FixedCS->toString()
8294 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8295 } else {
8296 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8297 << CS.toString() << /*conversion specifier*/ 1,
8298 getLocationOfByte(CS.getStart()),
8299 /*IsStringLocation*/ true,
8300 getSpecifierRange(startSpecifier, specifierLen));
8301 }
8302}
8303
8304void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8305 if (!S.getDiagnostics().isIgnored(
8306 diag::warn_format_non_standard_positional_arg, SourceLocation()))
8307 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8308 getLocationOfByte(startPos),
8309 /*IsStringLocation*/ true,
8310 getSpecifierRange(startPos, posLen));
8311}
8312
8313void CheckFormatHandler::HandleInvalidPosition(
8314 const char *startSpecifier, unsigned specifierLen,
8316 if (!S.getDiagnostics().isIgnored(
8317 diag::warn_format_invalid_positional_specifier, SourceLocation()))
8318 EmitFormatDiagnostic(
8319 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8320 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
8321 getSpecifierRange(startSpecifier, specifierLen));
8322}
8323
8324void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8325 unsigned posLen) {
8326 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
8327 SourceLocation()))
8328 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8329 getLocationOfByte(startPos),
8330 /*IsStringLocation*/ true,
8331 getSpecifierRange(startPos, posLen));
8332}
8333
8334void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8335 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8336 // The presence of a null character is likely an error.
8337 EmitFormatDiagnostic(
8338 S.PDiag(diag::warn_printf_format_string_contains_null_char),
8339 getLocationOfByte(nullCharacter), /*IsStringLocation*/ true,
8340 getFormatStringRange());
8341 }
8342}
8343
8344// Note that this may return NULL if there was an error parsing or building
8345// one of the argument expressions.
8346const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8347 return Args[FirstDataArg + i];
8348}
8349
8350void CheckFormatHandler::DoneProcessing() {
8351 // Does the number of data arguments exceed the number of
8352 // format conversions in the format string?
8353 if (HasFormatArguments()) {
8354 // Find any arguments that weren't covered.
8355 CoveredArgs.flip();
8356 signed notCoveredArg = CoveredArgs.find_first();
8357 if (notCoveredArg >= 0) {
8358 assert((unsigned)notCoveredArg < NumDataArgs);
8359 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8360 } else {
8361 UncoveredArg.setAllCovered();
8362 }
8363 }
8364}
8365
8366void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8367 const Expr *ArgExpr) {
8368 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8369
8370 if (!ArgExpr)
8371 return;
8372
8373 SourceLocation Loc = ArgExpr->getBeginLoc();
8374
8375 if (S.getSourceManager().isInSystemMacro(Loc))
8376 return;
8377
8378 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8379 for (auto E : DiagnosticExprs)
8380 PDiag << E->getSourceRange();
8381
8382 CheckFormatHandler::EmitFormatDiagnostic(
8383 S, IsFunctionCall, DiagnosticExprs[0], PDiag, Loc,
8384 /*IsStringLocation*/ false, DiagnosticExprs[0]->getSourceRange());
8385}
8386
8387bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8388 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8389 unsigned specifierLen, const char *csStart, unsigned csLen) {
8390 bool keepGoing = true;
8391 if (argIndex < NumDataArgs) {
8392 // Consider the argument coverered, even though the specifier doesn't
8393 // make sense.
8394 CoveredArgs.set(argIndex);
8395 } else {
8396 // If argIndex exceeds the number of data arguments we
8397 // don't issue a warning because that is just a cascade of warnings (and
8398 // they may have intended '%%' anyway). We don't want to continue processing
8399 // the format string after this point, however, as we will like just get
8400 // gibberish when trying to match arguments.
8401 keepGoing = false;
8402 }
8403
8404 StringRef Specifier(csStart, csLen);
8405
8406 // If the specifier in non-printable, it could be the first byte of a UTF-8
8407 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8408 // hex value.
8409 std::string CodePointStr;
8410 if (!llvm::sys::locale::isPrint(*csStart)) {
8411 llvm::UTF32 CodePoint;
8412 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8413 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8414 llvm::ConversionResult Result =
8415 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8416
8417 if (Result != llvm::conversionOK) {
8418 unsigned char FirstChar = *csStart;
8419 CodePoint = (llvm::UTF32)FirstChar;
8420 }
8421
8422 llvm::raw_string_ostream OS(CodePointStr);
8423 if (CodePoint < 256)
8424 OS << "\\x" << llvm::format("%02x", CodePoint);
8425 else if (CodePoint <= 0xFFFF)
8426 OS << "\\u" << llvm::format("%04x", CodePoint);
8427 else
8428 OS << "\\U" << llvm::format("%08x", CodePoint);
8429 Specifier = CodePointStr;
8430 }
8431
8432 EmitFormatDiagnostic(
8433 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8434 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8435
8436 return keepGoing;
8437}
8438
8439void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8440 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8441 EmitFormatDiagnostic(
8442 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), Loc,
8443 /*isStringLoc*/ true, getSpecifierRange(startSpec, specifierLen));
8444}
8445
8446bool CheckFormatHandler::CheckNumArgs(
8449 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8450
8451 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8452 PartialDiagnostic PDiag =
8454 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8455 << (argIndex + 1) << NumDataArgs)
8456 : S.PDiag(diag::warn_printf_insufficient_data_args);
8457 EmitFormatDiagnostic(PDiag, getLocationOfByte(CS.getStart()),
8458 /*IsStringLocation*/ true,
8459 getSpecifierRange(startSpecifier, specifierLen));
8460
8461 // Since more arguments than conversion tokens are given, by extension
8462 // all arguments are covered, so mark this as so.
8463 UncoveredArg.setAllCovered();
8464 return false;
8465 }
8466 return true;
8467}
8468
8469template <typename Range>
8470void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8471 SourceLocation Loc,
8472 bool IsStringLocation,
8473 Range StringRange,
8474 ArrayRef<FixItHint> FixIt) {
8475 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8476 IsStringLocation, StringRange, FixIt);
8477}
8478
8479/// If the format string is not within the function call, emit a note
8480/// so that the function call and string are in diagnostic messages.
8481///
8482/// \param InFunctionCall if true, the format string is within the function
8483/// call and only one diagnostic message will be produced. Otherwise, an
8484/// extra note will be emitted pointing to location of the format string.
8485///
8486/// \param ArgumentExpr the expression that is passed as the format string
8487/// argument in the function call. Used for getting locations when two
8488/// diagnostics are emitted.
8489///
8490/// \param PDiag the callee should already have provided any strings for the
8491/// diagnostic message. This function only adds locations and fixits
8492/// to diagnostics.
8493///
8494/// \param Loc primary location for diagnostic. If two diagnostics are
8495/// required, one will be at Loc and a new SourceLocation will be created for
8496/// the other one.
8497///
8498/// \param IsStringLocation if true, Loc points to the format string should be
8499/// used for the note. Otherwise, Loc points to the argument list and will
8500/// be used with PDiag.
8501///
8502/// \param StringRange some or all of the string to highlight. This is
8503/// templated so it can accept either a CharSourceRange or a SourceRange.
8504///
8505/// \param FixIt optional fix it hint for the format string.
8506template <typename Range>
8507void CheckFormatHandler::EmitFormatDiagnostic(
8508 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8509 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8510 Range StringRange, ArrayRef<FixItHint> FixIt) {
8511 if (InFunctionCall) {
8512 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8513 D << StringRange;
8514 D << FixIt;
8515 } else {
8516 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8517 << ArgumentExpr->getSourceRange();
8518
8520 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8521 diag::note_format_string_defined);
8522
8523 Note << StringRange;
8524 Note << FixIt;
8525 }
8526}
8527
8528//===--- CHECK: Printf format string checking -----------------------------===//
8529
8530namespace {
8531
8532class CheckPrintfHandler : public CheckFormatHandler {
8533public:
8534 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8535 const Expr *origFormatExpr, const FormatStringType type,
8536 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8537 const char *beg, Sema::FormatArgumentPassingKind APK,
8538 ArrayRef<const Expr *> Args, unsigned formatIdx,
8539 bool inFunctionCall, VariadicCallType CallType,
8540 llvm::SmallBitVector &CheckedVarArgs,
8541 UncoveredArgHandler &UncoveredArg)
8542 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8543 numDataArgs, beg, APK, Args, formatIdx,
8544 inFunctionCall, CallType, CheckedVarArgs,
8545 UncoveredArg) {}
8546
8547 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8548
8549 /// Returns true if '%@' specifiers are allowed in the format string.
8550 bool allowsObjCArg() const {
8551 return FSType == FormatStringType::NSString ||
8552 FSType == FormatStringType::OSLog ||
8553 FSType == FormatStringType::OSTrace;
8554 }
8555
8556 bool HandleInvalidPrintfConversionSpecifier(
8557 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8558 unsigned specifierLen) override;
8559
8560 void handleInvalidMaskType(StringRef MaskType) override;
8561
8562 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8563 const char *startSpecifier, unsigned specifierLen,
8564 const TargetInfo &Target) override;
8565 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8566 const char *StartSpecifier, unsigned SpecifierLen,
8567 const Expr *E);
8568
8569 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8570 unsigned k, const char *startSpecifier,
8571 unsigned specifierLen);
8572 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8573 const analyze_printf::OptionalAmount &Amt,
8574 unsigned type, const char *startSpecifier,
8575 unsigned specifierLen);
8576 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8577 const analyze_printf::OptionalFlag &flag,
8578 const char *startSpecifier, unsigned specifierLen);
8579 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8580 const analyze_printf::OptionalFlag &ignoredFlag,
8581 const analyze_printf::OptionalFlag &flag,
8582 const char *startSpecifier, unsigned specifierLen);
8583 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8584
8585 void HandleEmptyObjCModifierFlag(const char *startFlag,
8586 unsigned flagLen) override;
8587
8588 void HandleInvalidObjCModifierFlag(const char *startFlag,
8589 unsigned flagLen) override;
8590
8591 void
8592 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8593 const char *flagsEnd,
8594 const char *conversionPosition) override;
8595};
8596
8597/// Keeps around the information needed to verify that two specifiers are
8598/// compatible.
8599class EquatableFormatArgument {
8600public:
8601 enum SpecifierSensitivity : unsigned {
8602 SS_None,
8603 SS_Private,
8604 SS_Public,
8605 SS_Sensitive
8606 };
8607
8608 enum FormatArgumentRole : unsigned {
8609 FAR_Data,
8610 FAR_FieldWidth,
8611 FAR_Precision,
8612 FAR_Auxiliary, // FreeBSD kernel %b and %D
8613 };
8614
8615private:
8616 analyze_format_string::ArgType ArgType;
8617 analyze_format_string::LengthModifier LengthMod;
8618 StringRef SpecifierLetter;
8619 CharSourceRange Range;
8620 SourceLocation ElementLoc;
8621 FormatArgumentRole Role : 2;
8622 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8623 unsigned Position : 14;
8624 unsigned ModifierFor : 14; // not set for FAR_Data
8625
8626 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8627 bool InFunctionCall) const;
8628
8629public:
8630 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8631 analyze_format_string::LengthModifier LengthMod,
8632 StringRef SpecifierLetter,
8633 analyze_format_string::ArgType ArgType,
8634 FormatArgumentRole Role,
8635 SpecifierSensitivity Sensitivity, unsigned Position,
8636 unsigned ModifierFor)
8637 : ArgType(ArgType), LengthMod(LengthMod),
8638 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8639 Role(Role), Sensitivity(Sensitivity), Position(Position),
8640 ModifierFor(ModifierFor) {}
8641
8642 unsigned getPosition() const { return Position; }
8643 SourceLocation getSourceLocation() const { return ElementLoc; }
8644 CharSourceRange getSourceRange() const { return Range; }
8645 analyze_format_string::LengthModifier getLengthModifier() const {
8646 return LengthMod;
8647 }
8648 void setModifierFor(unsigned V) { ModifierFor = V; }
8649
8650 std::string buildFormatSpecifier() const {
8651 std::string result;
8652 llvm::raw_string_ostream(result)
8653 << getLengthModifier().toString() << SpecifierLetter;
8654 return result;
8655 }
8656
8657 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8658 const Expr *FmtExpr, bool InFunctionCall) const;
8659};
8660
8661/// Turns format strings into lists of EquatableSpecifier objects.
8662class DecomposePrintfHandler : public CheckPrintfHandler {
8663 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8664 bool HadError;
8665
8666 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8667 const Expr *origFormatExpr,
8668 const FormatStringType type, unsigned firstDataArg,
8669 unsigned numDataArgs, bool isObjC, const char *beg,
8671 ArrayRef<const Expr *> Args, unsigned formatIdx,
8672 bool inFunctionCall, VariadicCallType CallType,
8673 llvm::SmallBitVector &CheckedVarArgs,
8674 UncoveredArgHandler &UncoveredArg,
8675 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8676 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8677 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8678 inFunctionCall, CallType, CheckedVarArgs,
8679 UncoveredArg),
8680 Specs(Specs), HadError(false) {}
8681
8682public:
8683 static bool
8684 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8685 FormatStringType type, bool IsObjC, bool InFunctionCall,
8686 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8687
8688 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8689 const char *startSpecifier,
8690 unsigned specifierLen,
8691 const TargetInfo &Target) override;
8692};
8693
8694} // namespace
8695
8696bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8697 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8698 unsigned specifierLen) {
8701
8702 return HandleInvalidConversionSpecifier(
8703 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
8704 specifierLen, CS.getStart(), CS.getLength());
8705}
8706
8707void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8708 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8709}
8710
8711// Error out if struct or complex type argments are passed to os_log.
8713 QualType T) {
8714 if (FSType != FormatStringType::OSLog)
8715 return false;
8716 return T->isRecordType() || T->isComplexType();
8717}
8718
8719bool CheckPrintfHandler::HandleAmount(
8720 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8721 const char *startSpecifier, unsigned specifierLen) {
8722 if (Amt.hasDataArgument()) {
8723 if (HasFormatArguments()) {
8724 unsigned argIndex = Amt.getArgIndex();
8725 if (argIndex >= NumDataArgs) {
8726 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8727 << k,
8728 getLocationOfByte(Amt.getStart()),
8729 /*IsStringLocation*/ true,
8730 getSpecifierRange(startSpecifier, specifierLen));
8731 // Don't do any more checking. We will just emit
8732 // spurious errors.
8733 return false;
8734 }
8735
8736 // Type check the data argument. It should be an 'int'.
8737 // Although not in conformance with C99, we also allow the argument to be
8738 // an 'unsigned int' as that is a reasonably safe case. GCC also
8739 // doesn't emit a warning for that case.
8740 CoveredArgs.set(argIndex);
8741 const Expr *Arg = getDataArg(argIndex);
8742 if (!Arg)
8743 return false;
8744
8745 QualType T = Arg->getType();
8746
8747 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8748 assert(AT.isValid());
8749
8750 if (!AT.matchesType(S.Context, T)) {
8751 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8752 ? diag::err_printf_asterisk_wrong_type
8753 : diag::warn_printf_asterisk_wrong_type;
8754 EmitFormatDiagnostic(S.PDiag(DiagID)
8756 << T << Arg->getSourceRange(),
8757 getLocationOfByte(Amt.getStart()),
8758 /*IsStringLocation*/ true,
8759 getSpecifierRange(startSpecifier, specifierLen));
8760 // Don't do any more checking. We will just emit
8761 // spurious errors.
8762 return false;
8763 }
8764 }
8765 }
8766 return true;
8767}
8768
8769void CheckPrintfHandler::HandleInvalidAmount(
8771 const analyze_printf::OptionalAmount &Amt, unsigned type,
8772 const char *startSpecifier, unsigned specifierLen) {
8775
8776 FixItHint fixit =
8779 getSpecifierRange(Amt.getStart(), Amt.getConstantLength()))
8780 : FixItHint();
8781
8782 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8783 << type << CS.toString(),
8784 getLocationOfByte(Amt.getStart()),
8785 /*IsStringLocation*/ true,
8786 getSpecifierRange(startSpecifier, specifierLen), fixit);
8787}
8788
8789void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8790 const analyze_printf::OptionalFlag &flag,
8791 const char *startSpecifier,
8792 unsigned specifierLen) {
8793 // Warn about pointless flag with a fixit removal.
8796 EmitFormatDiagnostic(
8797 S.PDiag(diag::warn_printf_nonsensical_flag)
8798 << flag.toString() << CS.toString(),
8799 getLocationOfByte(flag.getPosition()),
8800 /*IsStringLocation*/ true,
8801 getSpecifierRange(startSpecifier, specifierLen),
8802 FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1)));
8803}
8804
8805void CheckPrintfHandler::HandleIgnoredFlag(
8807 const analyze_printf::OptionalFlag &ignoredFlag,
8808 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
8809 unsigned specifierLen) {
8810 // Warn about ignored flag with a fixit removal.
8811 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8812 << ignoredFlag.toString() << flag.toString(),
8813 getLocationOfByte(ignoredFlag.getPosition()),
8814 /*IsStringLocation*/ true,
8815 getSpecifierRange(startSpecifier, specifierLen),
8817 getSpecifierRange(ignoredFlag.getPosition(), 1)));
8818}
8819
8820void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8821 unsigned flagLen) {
8822 // Warn about an empty flag.
8823 EmitFormatDiagnostic(
8824 S.PDiag(diag::warn_printf_empty_objc_flag), getLocationOfByte(startFlag),
8825 /*IsStringLocation*/ true, getSpecifierRange(startFlag, flagLen));
8826}
8827
8828void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8829 unsigned flagLen) {
8830 // Warn about an invalid flag.
8831 auto Range = getSpecifierRange(startFlag, flagLen);
8832 StringRef flag(startFlag, flagLen);
8833 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8834 getLocationOfByte(startFlag),
8835 /*IsStringLocation*/ true, Range,
8837}
8838
8839void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8840 const char *flagsStart, const char *flagsEnd,
8841 const char *conversionPosition) {
8842 // Warn about using '[...]' without a '@' conversion.
8843 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8844 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8845 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8846 getLocationOfByte(conversionPosition),
8847 /*IsStringLocation*/ true, Range,
8849}
8850
8851void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8852 const Expr *FmtExpr,
8853 bool InFunctionCall) const {
8854 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
8855 ElementLoc, true, Range);
8856}
8857
8858bool EquatableFormatArgument::VerifyCompatible(
8859 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8860 bool InFunctionCall) const {
8862 if (Role != Other.Role) {
8863 // diagnose and stop
8864 EmitDiagnostic(
8865 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8866 FmtExpr, InFunctionCall);
8867 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8868 return false;
8869 }
8870
8871 if (Role != FAR_Data) {
8872 if (ModifierFor != Other.ModifierFor) {
8873 // diagnose and stop
8874 EmitDiagnostic(S,
8875 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
8876 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8877 FmtExpr, InFunctionCall);
8878 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
8879 return false;
8880 }
8881 return true;
8882 }
8883
8884 bool HadError = false;
8885 if (Sensitivity != Other.Sensitivity) {
8886 // diagnose and continue
8887 EmitDiagnostic(S,
8888 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
8889 << Sensitivity << Other.Sensitivity,
8890 FmtExpr, InFunctionCall);
8891 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8892 << 0 << Other.Range;
8893 }
8894
8895 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
8896 case MK::Match:
8897 break;
8898
8899 case MK::MatchPromotion:
8900 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8901 // MatchPromotion is treated as a failure by format_matches.
8902 case MK::NoMatch:
8903 case MK::NoMatchTypeConfusion:
8904 case MK::NoMatchPromotionTypeConfusion:
8905 EmitDiagnostic(S,
8906 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
8907 << buildFormatSpecifier()
8908 << Other.buildFormatSpecifier(),
8909 FmtExpr, InFunctionCall);
8910 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8911 << 0 << Other.Range;
8912 break;
8913
8914 case MK::NoMatchPedantic:
8915 EmitDiagnostic(S,
8916 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
8917 << buildFormatSpecifier()
8918 << Other.buildFormatSpecifier(),
8919 FmtExpr, InFunctionCall);
8920 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8921 << 0 << Other.Range;
8922 break;
8923
8924 case MK::NoMatchSignedness:
8925 EmitDiagnostic(S,
8926 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
8927 << buildFormatSpecifier()
8928 << Other.buildFormatSpecifier(),
8929 FmtExpr, InFunctionCall);
8930 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
8931 << 0 << Other.Range;
8932 break;
8933 }
8934 return !HadError;
8935}
8936
8937bool DecomposePrintfHandler::GetSpecifiers(
8938 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8939 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8941 StringRef Data = FSL->getString();
8942 const char *Str = Data.data();
8943 llvm::SmallBitVector BV;
8944 UncoveredArgHandler UA;
8945 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8946 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8947 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8948 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8949 UA, Args);
8950
8952 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
8954 H.DoneProcessing();
8955 if (H.HadError)
8956 return false;
8957
8958 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
8959 const EquatableFormatArgument &B) {
8960 return A.getPosition() < B.getPosition();
8961 });
8962 return true;
8963}
8964
8965bool DecomposePrintfHandler::HandlePrintfSpecifier(
8966 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8967 unsigned specifierLen, const TargetInfo &Target) {
8968 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8969 specifierLen, Target)) {
8970 HadError = true;
8971 return false;
8972 }
8973
8974 // Do not add any specifiers to the list for %%. This is possibly incorrect
8975 // if using a precision/width with a data argument, but that combination is
8976 // meaningless and we wouldn't know which format to attach the
8977 // precision/width to.
8978 const auto &CS = FS.getConversionSpecifier();
8980 return true;
8981
8982 // have to patch these to have the right ModifierFor if they are used
8983 const unsigned Unset = ~0;
8984 unsigned FieldWidthIndex = Unset;
8985 unsigned PrecisionIndex = Unset;
8986
8987 // field width?
8988 const auto &FieldWidth = FS.getFieldWidth();
8989 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8990 FieldWidthIndex = Specs.size();
8991 Specs.emplace_back(
8992 getSpecifierRange(startSpecifier, specifierLen),
8993 getLocationOfByte(FieldWidth.getStart()),
8994 analyze_format_string::LengthModifier(), FieldWidth.getCharacters(),
8995 FieldWidth.getArgType(S.Context),
8996 EquatableFormatArgument::FAR_FieldWidth,
8997 EquatableFormatArgument::SS_None,
8998 FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
8999 : FieldWidthIndex,
9000 0);
9001 }
9002 // precision?
9003 const auto &Precision = FS.getPrecision();
9004 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
9005 PrecisionIndex = Specs.size();
9006 Specs.emplace_back(
9007 getSpecifierRange(startSpecifier, specifierLen),
9008 getLocationOfByte(Precision.getStart()),
9009 analyze_format_string::LengthModifier(), Precision.getCharacters(),
9010 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
9011 EquatableFormatArgument::SS_None,
9012 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
9013 : PrecisionIndex,
9014 0);
9015 }
9016
9017 // this specifier
9018 unsigned SpecIndex =
9019 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
9020 if (FieldWidthIndex != Unset)
9021 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
9022 if (PrecisionIndex != Unset)
9023 Specs[PrecisionIndex].setModifierFor(SpecIndex);
9024
9025 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
9026 if (FS.isPrivate())
9027 Sensitivity = EquatableFormatArgument::SS_Private;
9028 else if (FS.isPublic())
9029 Sensitivity = EquatableFormatArgument::SS_Public;
9030 else if (FS.isSensitive())
9031 Sensitivity = EquatableFormatArgument::SS_Sensitive;
9032 else
9033 Sensitivity = EquatableFormatArgument::SS_None;
9034
9035 Specs.emplace_back(
9036 getSpecifierRange(startSpecifier, specifierLen),
9037 getLocationOfByte(CS.getStart()), FS.getLengthModifier(),
9038 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
9039 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
9040
9041 // auxiliary argument?
9044 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
9045 getLocationOfByte(CS.getStart()),
9047 CS.getCharacters(),
9049 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
9050 SpecIndex + 1, SpecIndex);
9051 }
9052 return true;
9053}
9054
9055// Determines if the specified is a C++ class or struct containing
9056// a member with the specified name and kind (e.g. a CXXMethodDecl named
9057// "c_str()").
9058template<typename MemberKind>
9060CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9061 auto *RD = Ty->getAsCXXRecordDecl();
9063
9064 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
9065 return Results;
9066
9067 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9069 R.suppressDiagnostics();
9070
9071 // We just need to include all members of the right kind turned up by the
9072 // filter, at this point.
9073 if (S.LookupQualifiedName(R, RD))
9074 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9075 NamedDecl *decl = (*I)->getUnderlyingDecl();
9076 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9077 Results.insert(FK);
9078 }
9079 return Results;
9080}
9081
9082/// Check if we could call '.c_str()' on an object.
9083///
9084/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9085/// allow the call, or if it would be ambiguous).
9087 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9088
9089 MethodSet Results =
9090 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9091 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9092 MI != ME; ++MI)
9093 if ((*MI)->getMinRequiredArguments() == 0)
9094 return true;
9095 return false;
9096}
9097
9098// Check if a (w)string was passed when a (w)char* was needed, and offer a
9099// better diagnostic if so. AT is assumed to be valid.
9100// Returns true when a c_str() conversion method is found.
9101bool CheckPrintfHandler::checkForCStrMembers(
9102 const analyze_printf::ArgType &AT, const Expr *E) {
9103 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9104
9105 MethodSet Results =
9107
9108 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9109 MI != ME; ++MI) {
9110 const CXXMethodDecl *Method = *MI;
9111 if (Method->getMinRequiredArguments() == 0 &&
9112 AT.matchesType(S.Context, Method->getReturnType())) {
9113 // FIXME: Suggest parens if the expression needs them.
9115 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9116 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9117 return true;
9118 }
9119 }
9120
9121 return false;
9122}
9123
9124bool CheckPrintfHandler::HandlePrintfSpecifier(
9125 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9126 unsigned specifierLen, const TargetInfo &Target) {
9127 using namespace analyze_format_string;
9128 using namespace analyze_printf;
9129
9130 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9131
9132 if (FS.consumesDataArgument()) {
9133 if (atFirstArg) {
9134 atFirstArg = false;
9135 usesPositionalArgs = FS.usesPositionalArg();
9136 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9137 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9138 startSpecifier, specifierLen);
9139 return false;
9140 }
9141 }
9142
9143 // First check if the field width, precision, and conversion specifier
9144 // have matching data arguments.
9145 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, startSpecifier,
9146 specifierLen)) {
9147 return false;
9148 }
9149
9150 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, startSpecifier,
9151 specifierLen)) {
9152 return false;
9153 }
9154
9155 if (!CS.consumesDataArgument()) {
9156 // FIXME: Technically specifying a precision or field width here
9157 // makes no sense. Worth issuing a warning at some point.
9158 return true;
9159 }
9160
9161 // Consume the argument.
9162 unsigned argIndex = FS.getArgIndex();
9163 if (argIndex < NumDataArgs) {
9164 // The check to see if the argIndex is valid will come later.
9165 // We set the bit here because we may exit early from this
9166 // function if we encounter some other error.
9167 CoveredArgs.set(argIndex);
9168 }
9169
9170 // FreeBSD kernel extensions.
9171 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9172 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9173 // We need at least two arguments.
9174 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9175 return false;
9176
9177 if (HasFormatArguments()) {
9178 // Claim the second argument.
9179 CoveredArgs.set(argIndex + 1);
9180
9181 // Type check the first argument (int for %b, pointer for %D)
9182 const Expr *Ex = getDataArg(argIndex);
9183 const analyze_printf::ArgType &AT =
9184 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
9185 ? ArgType(S.Context.IntTy)
9186 : ArgType::CPointerTy;
9187 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9188 EmitFormatDiagnostic(
9189 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9190 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9191 << false << Ex->getSourceRange(),
9192 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9193 getSpecifierRange(startSpecifier, specifierLen));
9194
9195 // Type check the second argument (char * for both %b and %D)
9196 Ex = getDataArg(argIndex + 1);
9198 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9199 EmitFormatDiagnostic(
9200 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9201 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9202 << false << Ex->getSourceRange(),
9203 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9204 getSpecifierRange(startSpecifier, specifierLen));
9205 }
9206 return true;
9207 }
9208
9209 // Check for using an Objective-C specific conversion specifier
9210 // in a non-ObjC literal.
9211 if (!allowsObjCArg() && CS.isObjCArg()) {
9212 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9213 specifierLen);
9214 }
9215
9216 // %P can only be used with os_log.
9217 if (FSType != FormatStringType::OSLog &&
9218 CS.getKind() == ConversionSpecifier::PArg) {
9219 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9220 specifierLen);
9221 }
9222
9223 // %n is not allowed with os_log.
9224 if (FSType == FormatStringType::OSLog &&
9225 CS.getKind() == ConversionSpecifier::nArg) {
9226 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9227 getLocationOfByte(CS.getStart()),
9228 /*IsStringLocation*/ false,
9229 getSpecifierRange(startSpecifier, specifierLen));
9230
9231 return true;
9232 }
9233
9234 // Only scalars are allowed for os_trace.
9235 if (FSType == FormatStringType::OSTrace &&
9236 (CS.getKind() == ConversionSpecifier::PArg ||
9237 CS.getKind() == ConversionSpecifier::sArg ||
9238 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9239 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9240 specifierLen);
9241 }
9242
9243 // Check for use of public/private annotation outside of os_log().
9244 if (FSType != FormatStringType::OSLog) {
9245 if (FS.isPublic().isSet()) {
9246 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9247 << "public",
9248 getLocationOfByte(FS.isPublic().getPosition()),
9249 /*IsStringLocation*/ false,
9250 getSpecifierRange(startSpecifier, specifierLen));
9251 }
9252 if (FS.isPrivate().isSet()) {
9253 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9254 << "private",
9255 getLocationOfByte(FS.isPrivate().getPosition()),
9256 /*IsStringLocation*/ false,
9257 getSpecifierRange(startSpecifier, specifierLen));
9258 }
9259 }
9260
9261 const llvm::Triple &Triple = Target.getTriple();
9262 if (CS.getKind() == ConversionSpecifier::nArg &&
9263 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9264 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9265 getLocationOfByte(CS.getStart()),
9266 /*IsStringLocation*/ false,
9267 getSpecifierRange(startSpecifier, specifierLen));
9268 }
9269
9270 // Check for invalid use of field width
9271 if (!FS.hasValidFieldWidth()) {
9272 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9273 startSpecifier, specifierLen);
9274 }
9275
9276 // Check for invalid use of precision
9277 if (!FS.hasValidPrecision()) {
9278 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9279 startSpecifier, specifierLen);
9280 }
9281
9282 // Precision is mandatory for %P specifier.
9283 if (CS.getKind() == ConversionSpecifier::PArg &&
9285 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9286 getLocationOfByte(startSpecifier),
9287 /*IsStringLocation*/ false,
9288 getSpecifierRange(startSpecifier, specifierLen));
9289 }
9290
9291 // Check each flag does not conflict with any other component.
9293 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9294 if (!FS.hasValidLeadingZeros())
9295 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9296 if (!FS.hasValidPlusPrefix())
9297 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9298 if (!FS.hasValidSpacePrefix())
9299 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9300 if (!FS.hasValidAlternativeForm())
9301 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9302 if (!FS.hasValidLeftJustified())
9303 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9304
9305 // Check that flags are not ignored by another flag
9306 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9307 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9308 startSpecifier, specifierLen);
9309 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9310 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9311 startSpecifier, specifierLen);
9312
9313 // Check the length modifier is valid with the given conversion specifier.
9315 S.getLangOpts()))
9316 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9317 diag::warn_format_nonsensical_length);
9318 else if (!FS.hasStandardLengthModifier())
9319 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9321 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9322 diag::warn_format_non_standard_conversion_spec);
9323
9325 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9326
9327 // The remaining checks depend on the data arguments.
9328 if (!HasFormatArguments())
9329 return true;
9330
9331 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9332 return false;
9333
9334 const Expr *Arg = getDataArg(argIndex);
9335 if (!Arg)
9336 return true;
9337
9338 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9339}
9340
9341static bool requiresParensToAddCast(const Expr *E) {
9342 // FIXME: We should have a general way to reason about operator
9343 // precedence and whether parens are actually needed here.
9344 // Take care of a few common cases where they aren't.
9345 const Expr *Inside = E->IgnoreImpCasts();
9346 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9347 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9348
9349 switch (Inside->getStmtClass()) {
9350 case Stmt::ArraySubscriptExprClass:
9351 case Stmt::CallExprClass:
9352 case Stmt::CharacterLiteralClass:
9353 case Stmt::CXXBoolLiteralExprClass:
9354 case Stmt::DeclRefExprClass:
9355 case Stmt::FloatingLiteralClass:
9356 case Stmt::IntegerLiteralClass:
9357 case Stmt::MemberExprClass:
9358 case Stmt::ObjCArrayLiteralClass:
9359 case Stmt::ObjCBoolLiteralExprClass:
9360 case Stmt::ObjCBoxedExprClass:
9361 case Stmt::ObjCDictionaryLiteralClass:
9362 case Stmt::ObjCEncodeExprClass:
9363 case Stmt::ObjCIvarRefExprClass:
9364 case Stmt::ObjCMessageExprClass:
9365 case Stmt::ObjCPropertyRefExprClass:
9366 case Stmt::ObjCStringLiteralClass:
9367 case Stmt::ObjCSubscriptRefExprClass:
9368 case Stmt::ParenExprClass:
9369 case Stmt::StringLiteralClass:
9370 case Stmt::UnaryOperatorClass:
9371 return false;
9372 default:
9373 return true;
9374 }
9375}
9376
9377static std::pair<QualType, StringRef>
9378shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9379 const Expr *E) {
9380 // Use a 'while' to peel off layers of typedefs.
9381 QualType TyTy = IntendedTy;
9382 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9383 StringRef Name = UserTy->getDecl()->getName();
9384 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9385 .Case("CFIndex", Context.getNSIntegerType())
9386 .Case("NSInteger", Context.getNSIntegerType())
9387 .Case("NSUInteger", Context.getNSUIntegerType())
9388 .Case("SInt32", Context.IntTy)
9389 .Case("UInt32", Context.UnsignedIntTy)
9390 .Default(QualType());
9391
9392 if (!CastTy.isNull())
9393 return std::make_pair(CastTy, Name);
9394
9395 TyTy = UserTy->desugar();
9396 }
9397
9398 // Strip parens if necessary.
9399 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9400 return shouldNotPrintDirectly(Context, PE->getSubExpr()->getType(),
9401 PE->getSubExpr());
9402
9403 // If this is a conditional expression, then its result type is constructed
9404 // via usual arithmetic conversions and thus there might be no necessary
9405 // typedef sugar there. Recurse to operands to check for NSInteger &
9406 // Co. usage condition.
9407 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9408 QualType TrueTy, FalseTy;
9409 StringRef TrueName, FalseName;
9410
9411 std::tie(TrueTy, TrueName) = shouldNotPrintDirectly(
9412 Context, CO->getTrueExpr()->getType(), CO->getTrueExpr());
9413 std::tie(FalseTy, FalseName) = shouldNotPrintDirectly(
9414 Context, CO->getFalseExpr()->getType(), CO->getFalseExpr());
9415
9416 if (TrueTy == FalseTy)
9417 return std::make_pair(TrueTy, TrueName);
9418 else if (TrueTy.isNull())
9419 return std::make_pair(FalseTy, FalseName);
9420 else if (FalseTy.isNull())
9421 return std::make_pair(TrueTy, TrueName);
9422 }
9423
9424 return std::make_pair(QualType(), StringRef());
9425}
9426
9427/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9428/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9429/// type do not count.
9431 const ImplicitCastExpr *ICE) {
9432 QualType From = ICE->getSubExpr()->getType();
9433 QualType To = ICE->getType();
9434 // It's an integer promotion if the destination type is the promoted
9435 // source type.
9436 if (ICE->getCastKind() == CK_IntegralCast &&
9438 S.Context.getPromotedIntegerType(From) == To)
9439 return true;
9440 // Look through vector types, since we do default argument promotion for
9441 // those in OpenCL.
9442 if (const auto *VecTy = From->getAs<ExtVectorType>())
9443 From = VecTy->getElementType();
9444 if (const auto *VecTy = To->getAs<ExtVectorType>())
9445 To = VecTy->getElementType();
9446 // It's a floating promotion if the source type is a lower rank.
9447 return ICE->getCastKind() == CK_FloatingCast &&
9448 S.Context.getFloatingTypeOrder(From, To) < 0;
9449}
9450
9453 DiagnosticsEngine &Diags, SourceLocation Loc) {
9455 if (Diags.isIgnored(
9456 diag::warn_format_conversion_argument_type_mismatch_signedness,
9457 Loc) ||
9458 Diags.isIgnored(
9459 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9460 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9462 }
9463 }
9464 return Match;
9465}
9466
9467bool CheckPrintfHandler::checkFormatExpr(
9468 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9469 unsigned SpecifierLen, const Expr *E) {
9470 using namespace analyze_format_string;
9471 using namespace analyze_printf;
9472
9473 // Now type check the data expression that matches the
9474 // format specifier.
9475 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9476 if (!AT.isValid())
9477 return true;
9478
9479 QualType ExprTy = E->getType();
9480 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9481 ExprTy = TET->getUnderlyingExpr()->getType();
9482 }
9483
9484 if (const OverflowBehaviorType *OBT =
9485 dyn_cast<OverflowBehaviorType>(ExprTy.getCanonicalType()))
9486 ExprTy = OBT->getUnderlyingType();
9487
9488 // When using the format attribute in C++, you can receive a function or an
9489 // array that will necessarily decay to a pointer when passed to the final
9490 // format consumer. Apply decay before type comparison.
9491 if (ExprTy->canDecayToPointerType())
9492 ExprTy = S.Context.getDecayedType(ExprTy);
9493
9494 // Diagnose attempts to print a boolean value as a character. Unlike other
9495 // -Wformat diagnostics, this is fine from a type perspective, but it still
9496 // doesn't make sense.
9499 const CharSourceRange &CSR =
9500 getSpecifierRange(StartSpecifier, SpecifierLen);
9501 SmallString<4> FSString;
9502 llvm::raw_svector_ostream os(FSString);
9503 FS.toString(os);
9504 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9505 << FSString,
9506 E->getExprLoc(), false, CSR);
9507 return true;
9508 }
9509
9510 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9511 // dumping raw class data (like is-a pointer), not actual data.
9513 ExprTy->isObjCObjectPointerType()) {
9514 const CharSourceRange &CSR =
9515 getSpecifierRange(StartSpecifier, SpecifierLen);
9516 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
9517 E->getExprLoc(), false, CSR);
9518 return true;
9519 }
9520
9521 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9522 return true;
9523
9524 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9526 ArgType::MatchKind OrigMatch = Match;
9527
9529 if (Match == ArgType::Match)
9530 return true;
9531
9532 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9533 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9534
9535 // Look through argument promotions for our error message's reported type.
9536 // This includes the integral and floating promotions, but excludes array
9537 // and function pointer decay (seeing that an argument intended to be a
9538 // string has type 'char [6]' is probably more confusing than 'char *') and
9539 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9540 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9541 if (isArithmeticArgumentPromotion(S, ICE)) {
9542 E = ICE->getSubExpr();
9543 ExprTy = E->getType();
9544
9545 // Check if we didn't match because of an implicit cast from a 'char'
9546 // or 'short' to an 'int'. This is done because printf is a varargs
9547 // function.
9548 if (ICE->getType() == S.Context.IntTy ||
9549 ICE->getType() == S.Context.UnsignedIntTy) {
9550 // All further checking is done on the subexpression
9551 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
9552 if (OrigMatch == ArgType::NoMatchSignedness &&
9553 ImplicitMatch != ArgType::NoMatchSignedness)
9554 // If the original match was a signedness match this match on the
9555 // implicit cast type also need to be signedness match otherwise we
9556 // might introduce new unexpected warnings from -Wformat-signedness.
9557 return true;
9558 ImplicitMatch = handleFormatSignedness(
9559 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
9560 if (ImplicitMatch == ArgType::Match)
9561 return true;
9562 }
9563 }
9564 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9565 // Special case for 'a', which has type 'int' in C.
9566 // Note, however, that we do /not/ want to treat multibyte constants like
9567 // 'MooV' as characters! This form is deprecated but still exists. In
9568 // addition, don't treat expressions as of type 'char' if one byte length
9569 // modifier is provided.
9570 if (ExprTy == S.Context.IntTy &&
9572 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
9573 ExprTy = S.Context.CharTy;
9574 // To improve check results, we consider a character literal in C
9575 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9576 // more likely a type confusion situation, so we will suggest to
9577 // use '%hhd' instead by discarding the MatchPromotion.
9578 if (Match == ArgType::MatchPromotion)
9580 }
9581 }
9582 if (Match == ArgType::MatchPromotion) {
9583 // WG14 N2562 only clarified promotions in *printf
9584 // For NSLog in ObjC, just preserve -Wformat behavior
9585 if (!S.getLangOpts().ObjC &&
9586 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9587 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9588 return true;
9590 }
9591 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9592 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9593 Match = ImplicitMatch;
9594 assert(Match != ArgType::MatchPromotion);
9595
9596 // Look through unscoped enums to their underlying type.
9597 bool IsEnum = false;
9598 bool IsScopedEnum = false;
9599 QualType IntendedTy = ExprTy;
9600 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9601 IntendedTy = ED->getIntegerType();
9602 if (!ED->isScoped()) {
9603 ExprTy = IntendedTy;
9604 // This controls whether we're talking about the underlying type or not,
9605 // which we only want to do when it's an unscoped enum.
9606 IsEnum = true;
9607 } else {
9608 IsScopedEnum = true;
9609 }
9610 }
9611
9612 // %C in an Objective-C context prints a unichar, not a wchar_t.
9613 // If the argument is an integer of some kind, believe the %C and suggest
9614 // a cast instead of changing the conversion specifier.
9615 if (isObjCContext() &&
9618 !ExprTy->isCharType()) {
9619 // 'unichar' is defined as a typedef of unsigned short, but we should
9620 // prefer using the typedef if it is visible.
9621 IntendedTy = S.Context.UnsignedShortTy;
9622
9623 // While we are here, check if the value is an IntegerLiteral that happens
9624 // to be within the valid range.
9625 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9626 const llvm::APInt &V = IL->getValue();
9627 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9628 return true;
9629 }
9630
9631 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9633 if (S.LookupName(Result, S.getCurScope())) {
9634 NamedDecl *ND = Result.getFoundDecl();
9635 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9636 if (TD->getUnderlyingType() == IntendedTy)
9637 IntendedTy =
9639 /*Qualifier=*/std::nullopt, TD);
9640 }
9641 }
9642 }
9643
9644 // Special-case some of Darwin's platform-independence types by suggesting
9645 // casts to primitive types that are known to be large enough.
9646 bool ShouldNotPrintDirectly = false;
9647 StringRef CastTyName;
9648 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9649 QualType CastTy;
9650 std::tie(CastTy, CastTyName) =
9651 shouldNotPrintDirectly(S.Context, IntendedTy, E);
9652 if (!CastTy.isNull()) {
9653 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9654 // (long in ASTContext). Only complain to pedants or when they're the
9655 // underlying type of a scoped enum (which always needs a cast).
9656 if (!IsScopedEnum &&
9657 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9658 (AT.isSizeT() || AT.isPtrdiffT()) &&
9659 AT.matchesType(S.Context, CastTy))
9661 IntendedTy = CastTy;
9662 ShouldNotPrintDirectly = true;
9663 }
9664 }
9665
9666 // We may be able to offer a FixItHint if it is a supported type.
9667 PrintfSpecifier fixedFS = FS;
9668 bool Success =
9669 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9670
9671 if (Success) {
9672 // Get the fix string from the fixed format specifier
9673 SmallString<16> buf;
9674 llvm::raw_svector_ostream os(buf);
9675 fixedFS.toString(os);
9676
9677 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9678
9679 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9680 unsigned Diag;
9681 switch (Match) {
9682 case ArgType::Match:
9685 llvm_unreachable("expected non-matching");
9687 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9688 break;
9690 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9691 break;
9693 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9694 break;
9695 case ArgType::NoMatch:
9696 Diag = diag::warn_format_conversion_argument_type_mismatch;
9697 break;
9698 }
9699
9700 // In this case, the specifier is wrong and should be changed to match
9701 // the argument.
9702 EmitFormatDiagnostic(S.PDiag(Diag)
9704 << IntendedTy << IsEnum << E->getSourceRange(),
9705 E->getBeginLoc(),
9706 /*IsStringLocation*/ false, SpecRange,
9707 FixItHint::CreateReplacement(SpecRange, os.str()));
9708 } else {
9709 // The canonical type for formatting this value is different from the
9710 // actual type of the expression. (This occurs, for example, with Darwin's
9711 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9712 // should be printed as 'long' for 64-bit compatibility.)
9713 // Rather than emitting a normal format/argument mismatch, we want to
9714 // add a cast to the recommended type (and correct the format string
9715 // if necessary). We should also do so for scoped enumerations.
9716 SmallString<16> CastBuf;
9717 llvm::raw_svector_ostream CastFix(CastBuf);
9718 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9719 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9720 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9721
9723 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9724 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9725 E->getExprLoc());
9726 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9727 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9728
9729 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9730 // If there's already a cast present, just replace it.
9731 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9732 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9733
9734 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9735 // If the expression has high enough precedence,
9736 // just write the C-style cast.
9737 Hints.push_back(
9738 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9739 } else {
9740 // Otherwise, add parens around the expression as well as the cast.
9741 CastFix << "(";
9742 Hints.push_back(
9743 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9744
9745 // We don't use getLocForEndOfToken because it returns invalid source
9746 // locations for macro expansions (by design).
9750 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9751 }
9752
9753 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9754 // The expression has a type that should not be printed directly.
9755 // We extract the name from the typedef because we don't want to show
9756 // the underlying type in the diagnostic.
9757 StringRef Name;
9758 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9759 Name = TypedefTy->getDecl()->getName();
9760 else
9761 Name = CastTyName;
9762 unsigned Diag = Match == ArgType::NoMatchPedantic
9763 ? diag::warn_format_argument_needs_cast_pedantic
9764 : diag::warn_format_argument_needs_cast;
9765 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9766 << E->getSourceRange(),
9767 E->getBeginLoc(), /*IsStringLocation=*/false,
9768 SpecRange, Hints);
9769 } else {
9770 // In this case, the expression could be printed using a different
9771 // specifier, but we've decided that the specifier is probably correct
9772 // and we should cast instead. Just use the normal warning message.
9773
9774 unsigned Diag =
9775 IsScopedEnum
9776 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9777 : diag::warn_format_conversion_argument_type_mismatch;
9778
9779 EmitFormatDiagnostic(
9780 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9781 << IsEnum << E->getSourceRange(),
9782 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9783 }
9784 }
9785 } else {
9786 const CharSourceRange &CSR =
9787 getSpecifierRange(StartSpecifier, SpecifierLen);
9788 // Since the warning for passing non-POD types to variadic functions
9789 // was deferred until now, we emit a warning for non-POD
9790 // arguments here.
9791 bool EmitTypeMismatch = false;
9792 // Record and complex type arguments cannot be code generated for os_log
9793 // and would crash CodeGen, so they are rejected with a hard error emitted
9794 // after the switch below.
9795 bool EmitOSLogError = false;
9796 switch (S.isValidVarArgType(ExprTy)) {
9797 case VarArgKind::Valid:
9799 unsigned Diag;
9800 switch (Match) {
9801 case ArgType::Match:
9804 llvm_unreachable("expected non-matching");
9806 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9807 break;
9809 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9810 break;
9812 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9813 break;
9814 case ArgType::NoMatch:
9815 EmitOSLogError = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy);
9816 Diag = diag::warn_format_conversion_argument_type_mismatch;
9817 break;
9818 }
9819
9820 if (!EmitOSLogError)
9821 EmitFormatDiagnostic(
9822 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9823 << IsEnum << CSR << E->getSourceRange(),
9824 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9825 break;
9826 }
9829 if (CallType == VariadicCallType::DoesNotApply) {
9830 EmitTypeMismatch = true;
9831 } else if (isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)) {
9832 // Emit a hard error rather than the -Wnon-pod-varargs warning, which
9833 // does not stop compilation.
9834 EmitOSLogError = true;
9835 } else {
9836 EmitFormatDiagnostic(
9837 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9838 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9839 << AT.getRepresentativeTypeName(S.Context) << CSR
9840 << E->getSourceRange(),
9841 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9842 checkForCStrMembers(AT, E);
9843 }
9844 break;
9845
9847 if (CallType == VariadicCallType::DoesNotApply)
9848 EmitTypeMismatch = true;
9849 else if (ExprTy->isObjCObjectType())
9850 EmitFormatDiagnostic(
9851 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9852 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9853 << AT.getRepresentativeTypeName(S.Context) << CSR
9854 << E->getSourceRange(),
9855 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9856 else
9857 // FIXME: If this is an initializer list, suggest removing the braces
9858 // or inserting a cast to the target type.
9859 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9860 << isa<InitListExpr>(E) << ExprTy << CallType
9862 break;
9863 }
9864
9865 if (EmitOSLogError)
9866 EmitFormatDiagnostic(
9867 S.PDiag(diag::err_format_conversion_argument_type_mismatch)
9868 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9869 << CSR << E->getSourceRange(),
9870 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9871
9872 if (EmitTypeMismatch) {
9873 // The function is not variadic, so we do not generate warnings about
9874 // being allowed to pass that object as a variadic argument. Instead,
9875 // since there are inherently no printf specifiers for types which cannot
9876 // be passed as variadic arguments, emit a plain old specifier mismatch
9877 // argument.
9878 EmitFormatDiagnostic(
9879 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9880 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
9881 << E->getSourceRange(),
9882 E->getBeginLoc(), false, CSR);
9883 }
9884
9885 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9886 "format string specifier index out of range");
9887 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9888 }
9889
9890 return true;
9891}
9892
9893//===--- CHECK: Scanf format string checking ------------------------------===//
9894
9895namespace {
9896
9897class CheckScanfHandler : public CheckFormatHandler {
9898public:
9899 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9900 const Expr *origFormatExpr, FormatStringType type,
9901 unsigned firstDataArg, unsigned numDataArgs,
9902 const char *beg, Sema::FormatArgumentPassingKind APK,
9903 ArrayRef<const Expr *> Args, unsigned formatIdx,
9904 bool inFunctionCall, VariadicCallType CallType,
9905 llvm::SmallBitVector &CheckedVarArgs,
9906 UncoveredArgHandler &UncoveredArg)
9907 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9908 numDataArgs, beg, APK, Args, formatIdx,
9909 inFunctionCall, CallType, CheckedVarArgs,
9910 UncoveredArg) {}
9911
9912 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9913 const char *startSpecifier,
9914 unsigned specifierLen) override;
9915
9916 bool
9917 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9918 const char *startSpecifier,
9919 unsigned specifierLen) override;
9920
9921 void HandleIncompleteScanList(const char *start, const char *end) override;
9922};
9923
9924} // namespace
9925
9926void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9927 const char *end) {
9928 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9929 getLocationOfByte(end), /*IsStringLocation*/ true,
9930 getSpecifierRange(start, end - start));
9931}
9932
9933bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9934 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9935 unsigned specifierLen) {
9938
9939 return HandleInvalidConversionSpecifier(
9940 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
9941 specifierLen, CS.getStart(), CS.getLength());
9942}
9943
9944bool CheckScanfHandler::HandleScanfSpecifier(
9945 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9946 unsigned specifierLen) {
9947 using namespace analyze_scanf;
9948 using namespace analyze_format_string;
9949
9950 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9951
9952 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9953 // be used to decide if we are using positional arguments consistently.
9954 if (FS.consumesDataArgument()) {
9955 if (atFirstArg) {
9956 atFirstArg = false;
9957 usesPositionalArgs = FS.usesPositionalArg();
9958 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9959 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9960 startSpecifier, specifierLen);
9961 return false;
9962 }
9963 }
9964
9965 // Check if the field with is non-zero.
9966 const OptionalAmount &Amt = FS.getFieldWidth();
9968 if (Amt.getConstantAmount() == 0) {
9969 const CharSourceRange &R =
9970 getSpecifierRange(Amt.getStart(), Amt.getConstantLength());
9971 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9972 getLocationOfByte(Amt.getStart()),
9973 /*IsStringLocation*/ true, R,
9975 }
9976 }
9977
9978 if (!FS.consumesDataArgument()) {
9979 // FIXME: Technically specifying a precision or field width here
9980 // makes no sense. Worth issuing a warning at some point.
9981 return true;
9982 }
9983
9984 // Consume the argument.
9985 unsigned argIndex = FS.getArgIndex();
9986 if (argIndex < NumDataArgs) {
9987 // The check to see if the argIndex is valid will come later.
9988 // We set the bit here because we may exit early from this
9989 // function if we encounter some other error.
9990 CoveredArgs.set(argIndex);
9991 }
9992
9993 // Check the length modifier is valid with the given conversion specifier.
9995 S.getLangOpts()))
9996 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9997 diag::warn_format_nonsensical_length);
9998 else if (!FS.hasStandardLengthModifier())
9999 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10001 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10002 diag::warn_format_non_standard_conversion_spec);
10003
10005 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10006
10007 // The remaining checks depend on the data arguments.
10008 if (!HasFormatArguments())
10009 return true;
10010
10011 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10012 return false;
10013
10014 // Check that the argument type matches the format specifier.
10015 const Expr *Ex = getDataArg(argIndex);
10016 if (!Ex)
10017 return true;
10018
10020
10021 if (!AT.isValid()) {
10022 return true;
10023 }
10024
10025 if (CheckUnsupportedType(AT, Ex, startSpecifier, specifierLen))
10026 return true;
10027
10029 AT.matchesType(S.Context, Ex->getType());
10032 return true;
10035
10036 ScanfSpecifier fixedFS = FS;
10037 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
10038 S.getLangOpts(), S.Context);
10039
10040 unsigned Diag =
10041 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10042 : Signedness
10043 ? diag::warn_format_conversion_argument_type_mismatch_signedness
10044 : diag::warn_format_conversion_argument_type_mismatch;
10045
10046 if (Success) {
10047 // Get the fix string from the fixed format specifier.
10048 SmallString<128> buf;
10049 llvm::raw_svector_ostream os(buf);
10050 fixedFS.toString(os);
10051
10052 EmitFormatDiagnostic(
10054 << Ex->getType() << false << Ex->getSourceRange(),
10055 Ex->getBeginLoc(),
10056 /*IsStringLocation*/ false,
10057 getSpecifierRange(startSpecifier, specifierLen),
10059 getSpecifierRange(startSpecifier, specifierLen), os.str()));
10060 } else {
10061 EmitFormatDiagnostic(S.PDiag(Diag)
10063 << Ex->getType() << false << Ex->getSourceRange(),
10064 Ex->getBeginLoc(),
10065 /*IsStringLocation*/ false,
10066 getSpecifierRange(startSpecifier, specifierLen));
10067 }
10068
10069 return true;
10070}
10071
10072static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
10074 const StringLiteral *Fmt,
10076 const Expr *FmtExpr, bool InFunctionCall) {
10077 bool HadError = false;
10078 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
10079 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
10080 while (FmtIter < FmtEnd && RefIter < RefEnd) {
10081 // In positional-style format strings, the same specifier can appear
10082 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
10083 // are sorted by getPosition(), and we process each range of equal
10084 // getPosition() values as one group.
10085 // RefArgs are taken from a string literal that was given to
10086 // attribute(format_matches), and if we got this far, we have already
10087 // verified that if it has positional specifiers that appear in multiple
10088 // locations, then they are all mutually compatible. What's left for us to
10089 // do is verify that all specifiers with the same position in FmtArgs are
10090 // compatible with the RefArgs specifiers. We check each specifier from
10091 // FmtArgs against the first member of the RefArgs group.
10092 for (; FmtIter < FmtEnd; ++FmtIter) {
10093 // Clang does not diagnose missing format specifiers in positional-style
10094 // strings (TODO: which it probably should do, as it is UB to skip over a
10095 // format argument). Skip specifiers if needed.
10096 if (FmtIter->getPosition() < RefIter->getPosition())
10097 continue;
10098
10099 // Delimits a new getPosition() value.
10100 if (FmtIter->getPosition() > RefIter->getPosition())
10101 break;
10102
10103 HadError |=
10104 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
10105 }
10106
10107 // Jump RefIter to the start of the next group.
10108 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
10109 return Arg.getPosition() != RefIter->getPosition();
10110 });
10111 }
10112
10113 if (FmtIter < FmtEnd) {
10114 CheckFormatHandler::EmitFormatDiagnostic(
10115 S, InFunctionCall, FmtExpr,
10116 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
10117 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
10118 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
10119 } else if (RefIter < RefEnd) {
10120 CheckFormatHandler::EmitFormatDiagnostic(
10121 S, InFunctionCall, FmtExpr,
10122 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
10123 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
10124 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
10125 << 1 << RefIter->getSourceRange();
10126 }
10127 return !HadError;
10128}
10129
10131 Sema &S, const FormatStringLiteral *FExpr,
10132 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
10134 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
10135 bool inFunctionCall, VariadicCallType CallType,
10136 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10137 bool IgnoreStringsWithoutSpecifiers) {
10138 // CHECK: is the format string a wide literal?
10139 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10140 CheckFormatHandler::EmitFormatDiagnostic(
10141 S, inFunctionCall, Args[format_idx],
10142 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10143 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10144 return;
10145 }
10146
10147 // Str - The format string. NOTE: this is NOT null-terminated!
10148 StringRef StrRef = FExpr->getString();
10149 const char *Str = StrRef.data();
10150 // Account for cases where the string literal is truncated in a declaration.
10151 const ConstantArrayType *T =
10152 S.Context.getAsConstantArrayType(FExpr->getType());
10153 assert(T && "String literal not of constant array type!");
10154 size_t TypeSize = T->getZExtSize();
10155 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10156 const unsigned numDataArgs = Args.size() - firstDataArg;
10157
10158 if (IgnoreStringsWithoutSpecifiers &&
10160 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10161 return;
10162
10163 // Emit a warning if the string literal is truncated and does not contain an
10164 // embedded null character.
10165 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10166 CheckFormatHandler::EmitFormatDiagnostic(
10167 S, inFunctionCall, Args[format_idx],
10168 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10169 FExpr->getBeginLoc(),
10170 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10171 return;
10172 }
10173
10174 // CHECK: empty format string?
10175 if (StrLen == 0 && numDataArgs > 0) {
10176 CheckFormatHandler::EmitFormatDiagnostic(
10177 S, inFunctionCall, Args[format_idx],
10178 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10179 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10180 return;
10181 }
10182
10187 bool IsObjC =
10189 if (ReferenceFormatString == nullptr) {
10190 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10191 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10192 inFunctionCall, CallType, CheckedVarArgs,
10193 UncoveredArg);
10194
10196 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
10199 H.DoneProcessing();
10200 } else {
10202 Type, ReferenceFormatString, FExpr->getFormatString(),
10203 inFunctionCall ? nullptr : Args[format_idx]);
10204 }
10205 } else if (Type == FormatStringType::Scanf) {
10206 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10207 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10208 CallType, CheckedVarArgs, UncoveredArg);
10209
10211 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10212 H.DoneProcessing();
10213 } // TODO: handle other formats
10214}
10215
10217 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
10218 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
10223 return true;
10224
10225 bool IsObjC =
10228 FormatStringLiteral RefLit = AuthoritativeFormatString;
10229 FormatStringLiteral TestLit = TestedFormatString;
10230 const Expr *Arg;
10231 bool DiagAtStringLiteral;
10232 if (FunctionCallArg) {
10233 Arg = FunctionCallArg;
10234 DiagAtStringLiteral = false;
10235 } else {
10236 Arg = TestedFormatString;
10237 DiagAtStringLiteral = true;
10238 }
10239 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
10240 AuthoritativeFormatString, Type,
10241 IsObjC, true, RefArgs) &&
10242 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
10243 DiagAtStringLiteral, FmtArgs)) {
10244 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
10245 TestedFormatString, FmtArgs, Arg,
10246 DiagAtStringLiteral);
10247 }
10248 return false;
10249}
10250
10252 const StringLiteral *Str) {
10257 return true;
10258
10259 FormatStringLiteral RefLit = Str;
10261 bool IsObjC =
10263 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
10264 true, Args))
10265 return false;
10266
10267 // Group arguments by getPosition() value, and check that each member of the
10268 // group is compatible with the first member. This verifies that when
10269 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10270 // are mutually compatible. As an optimization, don't test the first member
10271 // against itself.
10272 bool HadError = false;
10273 auto Iter = Args.begin();
10274 auto End = Args.end();
10275 while (Iter != End) {
10276 const auto &FirstInGroup = *Iter;
10277 for (++Iter;
10278 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10279 ++Iter) {
10280 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
10281 }
10282 }
10283 return !HadError;
10284}
10285
10287 // Str - The format string. NOTE: this is NOT null-terminated!
10288 StringRef StrRef = FExpr->getString();
10289 const char *Str = StrRef.data();
10290 // Account for cases where the string literal is truncated in a declaration.
10291 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10292 assert(T && "String literal not of constant array type!");
10293 size_t TypeSize = T->getZExtSize();
10294 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10296 Str, Str + StrLen, getLangOpts(), Context.getTargetInfo());
10297}
10298
10299//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10300
10301// Returns the related absolute value function that is larger, of 0 if one
10302// does not exist.
10303static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10304 switch (AbsFunction) {
10305 default:
10306 return 0;
10307
10308 case Builtin::BI__builtin_abs:
10309 return Builtin::BI__builtin_labs;
10310 case Builtin::BI__builtin_labs:
10311 return Builtin::BI__builtin_llabs;
10312 case Builtin::BI__builtin_llabs:
10313 return 0;
10314
10315 case Builtin::BI__builtin_fabsf:
10316 return Builtin::BI__builtin_fabs;
10317 case Builtin::BI__builtin_fabs:
10318 return Builtin::BI__builtin_fabsl;
10319 case Builtin::BI__builtin_fabsl:
10320 return 0;
10321
10322 case Builtin::BI__builtin_cabsf:
10323 return Builtin::BI__builtin_cabs;
10324 case Builtin::BI__builtin_cabs:
10325 return Builtin::BI__builtin_cabsl;
10326 case Builtin::BI__builtin_cabsl:
10327 return 0;
10328
10329 case Builtin::BIabs:
10330 return Builtin::BIlabs;
10331 case Builtin::BIlabs:
10332 return Builtin::BIllabs;
10333 case Builtin::BIllabs:
10334 return 0;
10335
10336 case Builtin::BIfabsf:
10337 return Builtin::BIfabs;
10338 case Builtin::BIfabs:
10339 return Builtin::BIfabsl;
10340 case Builtin::BIfabsl:
10341 return 0;
10342
10343 case Builtin::BIcabsf:
10344 return Builtin::BIcabs;
10345 case Builtin::BIcabs:
10346 return Builtin::BIcabsl;
10347 case Builtin::BIcabsl:
10348 return 0;
10349 }
10350}
10351
10352// Returns the argument type of the absolute value function.
10354 unsigned AbsType) {
10355 if (AbsType == 0)
10356 return QualType();
10357
10359 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10361 return QualType();
10362
10364 if (!FT)
10365 return QualType();
10366
10367 if (FT->getNumParams() != 1)
10368 return QualType();
10369
10370 return FT->getParamType(0);
10371}
10372
10373// Returns the best absolute value function, or zero, based on type and
10374// current absolute value function.
10375static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10376 unsigned AbsFunctionKind) {
10377 unsigned BestKind = 0;
10378 uint64_t ArgSize = Context.getTypeSize(ArgType);
10379 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10380 Kind = getLargerAbsoluteValueFunction(Kind)) {
10381 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10382 if (Context.getTypeSize(ParamType) >= ArgSize) {
10383 if (BestKind == 0)
10384 BestKind = Kind;
10385 else if (Context.hasSameType(ParamType, ArgType)) {
10386 BestKind = Kind;
10387 break;
10388 }
10389 }
10390 }
10391 return BestKind;
10392}
10393
10399
10401 if (T->isIntegralOrEnumerationType())
10402 return AVK_Integer;
10403 if (T->isRealFloatingType())
10404 return AVK_Floating;
10405 if (T->isAnyComplexType())
10406 return AVK_Complex;
10407
10408 llvm_unreachable("Type not integer, floating, or complex");
10409}
10410
10411// Changes the absolute value function to a different type. Preserves whether
10412// the function is a builtin.
10413static unsigned changeAbsFunction(unsigned AbsKind,
10414 AbsoluteValueKind ValueKind) {
10415 switch (ValueKind) {
10416 case AVK_Integer:
10417 switch (AbsKind) {
10418 default:
10419 return 0;
10420 case Builtin::BI__builtin_fabsf:
10421 case Builtin::BI__builtin_fabs:
10422 case Builtin::BI__builtin_fabsl:
10423 case Builtin::BI__builtin_cabsf:
10424 case Builtin::BI__builtin_cabs:
10425 case Builtin::BI__builtin_cabsl:
10426 return Builtin::BI__builtin_abs;
10427 case Builtin::BIfabsf:
10428 case Builtin::BIfabs:
10429 case Builtin::BIfabsl:
10430 case Builtin::BIcabsf:
10431 case Builtin::BIcabs:
10432 case Builtin::BIcabsl:
10433 return Builtin::BIabs;
10434 }
10435 case AVK_Floating:
10436 switch (AbsKind) {
10437 default:
10438 return 0;
10439 case Builtin::BI__builtin_abs:
10440 case Builtin::BI__builtin_labs:
10441 case Builtin::BI__builtin_llabs:
10442 case Builtin::BI__builtin_cabsf:
10443 case Builtin::BI__builtin_cabs:
10444 case Builtin::BI__builtin_cabsl:
10445 return Builtin::BI__builtin_fabsf;
10446 case Builtin::BIabs:
10447 case Builtin::BIlabs:
10448 case Builtin::BIllabs:
10449 case Builtin::BIcabsf:
10450 case Builtin::BIcabs:
10451 case Builtin::BIcabsl:
10452 return Builtin::BIfabsf;
10453 }
10454 case AVK_Complex:
10455 switch (AbsKind) {
10456 default:
10457 return 0;
10458 case Builtin::BI__builtin_abs:
10459 case Builtin::BI__builtin_labs:
10460 case Builtin::BI__builtin_llabs:
10461 case Builtin::BI__builtin_fabsf:
10462 case Builtin::BI__builtin_fabs:
10463 case Builtin::BI__builtin_fabsl:
10464 return Builtin::BI__builtin_cabsf;
10465 case Builtin::BIabs:
10466 case Builtin::BIlabs:
10467 case Builtin::BIllabs:
10468 case Builtin::BIfabsf:
10469 case Builtin::BIfabs:
10470 case Builtin::BIfabsl:
10471 return Builtin::BIcabsf;
10472 }
10473 }
10474 llvm_unreachable("Unable to convert function");
10475}
10476
10477static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10478 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10479 if (!FnInfo)
10480 return 0;
10481
10482 switch (FDecl->getBuiltinID()) {
10483 default:
10484 return 0;
10485 case Builtin::BI__builtin_abs:
10486 case Builtin::BI__builtin_fabs:
10487 case Builtin::BI__builtin_fabsf:
10488 case Builtin::BI__builtin_fabsl:
10489 case Builtin::BI__builtin_labs:
10490 case Builtin::BI__builtin_llabs:
10491 case Builtin::BI__builtin_cabs:
10492 case Builtin::BI__builtin_cabsf:
10493 case Builtin::BI__builtin_cabsl:
10494 case Builtin::BIabs:
10495 case Builtin::BIlabs:
10496 case Builtin::BIllabs:
10497 case Builtin::BIfabs:
10498 case Builtin::BIfabsf:
10499 case Builtin::BIfabsl:
10500 case Builtin::BIcabs:
10501 case Builtin::BIcabsf:
10502 case Builtin::BIcabsl:
10503 return FDecl->getBuiltinID();
10504 }
10505 llvm_unreachable("Unknown Builtin type");
10506}
10507
10508// If the replacement is valid, emit a note with replacement function.
10509// Additionally, suggest including the proper header if not already included.
10511 unsigned AbsKind, QualType ArgType) {
10512 bool EmitHeaderHint = true;
10513 const char *HeaderName = nullptr;
10514 std::string FunctionName;
10515 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10516 FunctionName = "std::abs";
10517 if (ArgType->isIntegralOrEnumerationType()) {
10518 HeaderName = "cstdlib";
10519 } else if (ArgType->isRealFloatingType()) {
10520 HeaderName = "cmath";
10521 } else {
10522 llvm_unreachable("Invalid Type");
10523 }
10524
10525 // Lookup all std::abs
10526 if (NamespaceDecl *Std = S.getStdNamespace()) {
10527 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10528 R.suppressDiagnostics();
10529 S.LookupQualifiedName(R, Std);
10530
10531 for (const auto *I : R) {
10532 const FunctionDecl *FDecl = nullptr;
10533 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10534 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10535 } else {
10536 FDecl = dyn_cast<FunctionDecl>(I);
10537 }
10538 if (!FDecl)
10539 continue;
10540
10541 // Found std::abs(), check that they are the right ones.
10542 if (FDecl->getNumParams() != 1)
10543 continue;
10544
10545 // Check that the parameter type can handle the argument.
10546 QualType ParamType = FDecl->getParamDecl(0)->getType();
10547 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10548 S.Context.getTypeSize(ArgType) <=
10549 S.Context.getTypeSize(ParamType)) {
10550 // Found a function, don't need the header hint.
10551 EmitHeaderHint = false;
10552 break;
10553 }
10554 }
10555 }
10556 } else {
10557 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10558 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10559
10560 if (HeaderName) {
10561 DeclarationName DN(&S.Context.Idents.get(FunctionName));
10562 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10563 R.suppressDiagnostics();
10564 S.LookupName(R, S.getCurScope());
10565
10566 if (R.isSingleResult()) {
10567 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10568 if (FD && FD->getBuiltinID() == AbsKind) {
10569 EmitHeaderHint = false;
10570 } else {
10571 return;
10572 }
10573 } else if (!R.empty()) {
10574 return;
10575 }
10576 }
10577 }
10578
10579 S.Diag(Loc, diag::note_replace_abs_function)
10580 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10581
10582 if (!HeaderName)
10583 return;
10584
10585 if (!EmitHeaderHint)
10586 return;
10587
10588 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10589 << FunctionName;
10590}
10591
10592template <std::size_t StrLen>
10593static bool IsStdFunction(const FunctionDecl *FDecl,
10594 const char (&Str)[StrLen]) {
10595 if (!FDecl)
10596 return false;
10597 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10598 return false;
10599 if (!FDecl->isInStdNamespace())
10600 return false;
10601
10602 return true;
10603}
10604
10605enum class MathCheck { NaN, Inf };
10606static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10607 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10608 return llvm::is_contained(names, calleeName);
10609 };
10610
10611 switch (Check) {
10612 case MathCheck::NaN:
10613 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10614 "__builtin_nanf16", "__builtin_nanf128"});
10615 case MathCheck::Inf:
10616 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10617 "__builtin_inff16", "__builtin_inff128"});
10618 }
10619 llvm_unreachable("unknown MathCheck");
10620}
10621
10622static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10623 if (FDecl->getName() != "infinity")
10624 return false;
10625
10626 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10627 const CXXRecordDecl *RDecl = MDecl->getParent();
10628 if (RDecl->getName() != "numeric_limits")
10629 return false;
10630
10631 if (const NamespaceDecl *NSDecl =
10632 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
10633 return NSDecl->isStdNamespace();
10634 }
10635
10636 return false;
10637}
10638
10639void Sema::CheckInfNaNFunction(const CallExpr *Call,
10640 const FunctionDecl *FDecl) {
10641 if (!FDecl->getIdentifier())
10642 return;
10643
10644 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
10645 if (FPO.getNoHonorNaNs() &&
10646 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
10648 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10649 << 1 << 0 << Call->getSourceRange();
10650 return;
10651 }
10652
10653 if (FPO.getNoHonorInfs() &&
10654 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
10655 IsInfinityFunction(FDecl) ||
10657 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10658 << 0 << 0 << Call->getSourceRange();
10659 }
10660}
10661
10662void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10663 const FunctionDecl *FDecl) {
10664 if (Call->getNumArgs() != 1)
10665 return;
10666
10667 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10668 bool IsStdAbs = IsStdFunction(FDecl, "abs");
10669 if (AbsKind == 0 && !IsStdAbs)
10670 return;
10671
10672 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10673 QualType ParamType = Call->getArg(0)->getType();
10674
10675 // Unsigned types cannot be negative. Suggest removing the absolute value
10676 // function call.
10677 if (ArgType->isUnsignedIntegerType()) {
10678 std::string FunctionName =
10679 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10680 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10681 Diag(Call->getExprLoc(), diag::note_remove_abs)
10682 << FunctionName
10683 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10684 return;
10685 }
10686
10687 // Taking the absolute value of a pointer is very suspicious, they probably
10688 // wanted to index into an array, dereference a pointer, call a function, etc.
10689 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10690 unsigned DiagType = 0;
10691 if (ArgType->isFunctionType())
10692 DiagType = 1;
10693 else if (ArgType->isArrayType())
10694 DiagType = 2;
10695
10696 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10697 return;
10698 }
10699
10700 // std::abs has overloads which prevent most of the absolute value problems
10701 // from occurring.
10702 if (IsStdAbs)
10703 return;
10704
10705 // Prevent reaching unreachable code in getAbsoluteValueKind for unsupported
10706 // types.
10707 if (!ArgType->isIntegralOrEnumerationType() &&
10708 !ArgType->isRealFloatingType() && !ArgType->isAnyComplexType())
10709 return;
10710
10711 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10712 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10713
10714 // The argument and parameter are the same kind. Check if they are the right
10715 // size.
10716 if (ArgValueKind == ParamValueKind) {
10717 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10718 return;
10719
10720 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10721 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10722 << FDecl << ArgType << ParamType;
10723
10724 if (NewAbsKind == 0)
10725 return;
10726
10727 emitReplacement(*this, Call->getExprLoc(),
10728 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10729 return;
10730 }
10731
10732 // ArgValueKind != ParamValueKind
10733 // The wrong type of absolute value function was used. Attempt to find the
10734 // proper one.
10735 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10736 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10737 if (NewAbsKind == 0)
10738 return;
10739
10740 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10741 << FDecl << ParamValueKind << ArgValueKind;
10742
10743 emitReplacement(*this, Call->getExprLoc(),
10744 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10745}
10746
10747//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10748void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10749 const FunctionDecl *FDecl) {
10750 if (!Call || !FDecl) return;
10751
10752 // Ignore template specializations and macros.
10753 if (inTemplateInstantiation()) return;
10754 if (Call->getExprLoc().isMacroID()) return;
10755
10756 // Only care about the one template argument, two function parameter std::max
10757 if (Call->getNumArgs() != 2) return;
10758 if (!IsStdFunction(FDecl, "max")) return;
10759 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10760 if (!ArgList) return;
10761 if (ArgList->size() != 1) return;
10762
10763 // Check that template type argument is unsigned integer.
10764 const auto& TA = ArgList->get(0);
10765 if (TA.getKind() != TemplateArgument::Type) return;
10766 QualType ArgType = TA.getAsType();
10767 if (!ArgType->isUnsignedIntegerType()) return;
10768
10769 // See if either argument is a literal zero.
10770 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10771 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10772 if (!MTE) return false;
10773 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10774 if (!Num) return false;
10775 if (Num->getValue() != 0) return false;
10776 return true;
10777 };
10778
10779 const Expr *FirstArg = Call->getArg(0);
10780 const Expr *SecondArg = Call->getArg(1);
10781 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10782 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10783
10784 // Only warn when exactly one argument is zero.
10785 if (IsFirstArgZero == IsSecondArgZero) return;
10786
10787 SourceRange FirstRange = FirstArg->getSourceRange();
10788 SourceRange SecondRange = SecondArg->getSourceRange();
10789
10790 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10791
10792 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10793 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10794
10795 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10796 SourceRange RemovalRange;
10797 if (IsFirstArgZero) {
10798 RemovalRange = SourceRange(FirstRange.getBegin(),
10799 SecondRange.getBegin().getLocWithOffset(-1));
10800 } else {
10801 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10802 SecondRange.getEnd());
10803 }
10804
10805 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10806 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10807 << FixItHint::CreateRemoval(RemovalRange);
10808}
10809
10810//===--- CHECK: Standard memory functions ---------------------------------===//
10811
10812/// Takes the expression passed to the size_t parameter of functions
10813/// such as memcmp, strncat, etc and warns if it's a comparison.
10814///
10815/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10817 const IdentifierInfo *FnName,
10818 SourceLocation FnLoc,
10819 SourceLocation RParenLoc) {
10820 const auto *Size = dyn_cast<BinaryOperator>(E);
10821 if (!Size)
10822 return false;
10823
10824 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10825 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10826 return false;
10827
10828 SourceRange SizeRange = Size->getSourceRange();
10829 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10830 << SizeRange << FnName;
10831 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10832 << FnName
10834 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10835 << FixItHint::CreateRemoval(RParenLoc);
10836 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10837 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10839 ")");
10840
10841 return true;
10842}
10843
10844/// Determine whether the given type is or contains a dynamic class type
10845/// (e.g., whether it has a vtable).
10847 bool &IsContained) {
10848 // Look through array types while ignoring qualifiers.
10849 const Type *Ty = T->getBaseElementTypeUnsafe();
10850 IsContained = false;
10851
10852 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10853 RD = RD ? RD->getDefinition() : nullptr;
10854 if (!RD || RD->isInvalidDecl())
10855 return nullptr;
10856
10857 if (RD->isDynamicClass())
10858 return RD;
10859
10860 // Check all the fields. If any bases were dynamic, the class is dynamic.
10861 // It's impossible for a class to transitively contain itself by value, so
10862 // infinite recursion is impossible.
10863 for (auto *FD : RD->fields()) {
10864 bool SubContained;
10865 if (const CXXRecordDecl *ContainedRD =
10866 getContainedDynamicClass(FD->getType(), SubContained)) {
10867 IsContained = true;
10868 return ContainedRD;
10869 }
10870 }
10871
10872 return nullptr;
10873}
10874
10876 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10877 if (Unary->getKind() == UETT_SizeOf)
10878 return Unary;
10879 return nullptr;
10880}
10881
10882/// If E is a sizeof expression, returns its argument expression,
10883/// otherwise returns NULL.
10884static const Expr *getSizeOfExprArg(const Expr *E) {
10886 if (!SizeOf->isArgumentType())
10887 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10888 return nullptr;
10889}
10890
10891/// If E is a sizeof expression, returns its argument type.
10894 return SizeOf->getTypeOfArgument();
10895 return QualType();
10896}
10897
10898namespace {
10899
10900struct SearchNonTrivialToInitializeField
10901 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10902 using Super =
10903 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10904
10905 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10906
10907 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10908 SourceLocation SL) {
10909 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10910 asDerived().visitArray(PDIK, AT, SL);
10911 return;
10912 }
10913
10914 Super::visitWithKind(PDIK, FT, SL);
10915 }
10916
10917 void visitARCStrong(QualType FT, SourceLocation SL) {
10918 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10919 }
10920 void visitARCWeak(QualType FT, SourceLocation SL) {
10921 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10922 }
10923 void visitStruct(QualType FT, SourceLocation SL) {
10924 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10925 visit(FD->getType(), FD->getLocation());
10926 }
10927 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10928 const ArrayType *AT, SourceLocation SL) {
10929 visit(getContext().getBaseElementType(AT), SL);
10930 }
10931 void visitTrivial(QualType FT, SourceLocation SL) {}
10932
10933 static void diag(QualType RT, const Expr *E, Sema &S) {
10934 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10935 }
10936
10937 ASTContext &getContext() { return S.getASTContext(); }
10938
10939 const Expr *E;
10940 Sema &S;
10941};
10942
10943struct SearchNonTrivialToCopyField
10944 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10945 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10946
10947 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10948
10949 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10950 SourceLocation SL) {
10951 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10952 asDerived().visitArray(PCK, AT, SL);
10953 return;
10954 }
10955
10956 Super::visitWithKind(PCK, FT, SL);
10957 }
10958
10959 void visitARCStrong(QualType FT, SourceLocation SL) {
10960 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10961 }
10962 void visitARCWeak(QualType FT, SourceLocation SL) {
10963 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10964 }
10965 void visitPtrAuth(QualType FT, SourceLocation SL) {
10966 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10967 }
10968 void visitStruct(QualType FT, SourceLocation SL) {
10969 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10970 visit(FD->getType(), FD->getLocation());
10971 }
10972 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10973 SourceLocation SL) {
10974 visit(getContext().getBaseElementType(AT), SL);
10975 }
10976 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10977 SourceLocation SL) {}
10978 void visitTrivial(QualType FT, SourceLocation SL) {}
10979 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10980
10981 static void diag(QualType RT, const Expr *E, Sema &S) {
10982 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10983 }
10984
10985 ASTContext &getContext() { return S.getASTContext(); }
10986
10987 const Expr *E;
10988 Sema &S;
10989};
10990
10991}
10992
10993/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10994static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10995 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10996
10997 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10998 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10999 return false;
11000
11001 return doesExprLikelyComputeSize(BO->getLHS()) ||
11002 doesExprLikelyComputeSize(BO->getRHS());
11003 }
11004
11005 return getAsSizeOfExpr(SizeofExpr) != nullptr;
11006}
11007
11008/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
11009///
11010/// \code
11011/// #define MACRO 0
11012/// foo(MACRO);
11013/// foo(0);
11014/// \endcode
11015///
11016/// This should return true for the first call to foo, but not for the second
11017/// (regardless of whether foo is a macro or function).
11019 SourceLocation CallLoc,
11020 SourceLocation ArgLoc) {
11021 if (!CallLoc.isMacroID())
11022 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
11023
11024 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
11026}
11027
11028/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
11029/// last two arguments transposed.
11030static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
11031 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
11032 return;
11033
11034 const Expr *SizeArg =
11035 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
11036
11037 auto isLiteralZero = [](const Expr *E) {
11038 return (isa<IntegerLiteral>(E) &&
11039 cast<IntegerLiteral>(E)->getValue() == 0) ||
11041 cast<CharacterLiteral>(E)->getValue() == 0);
11042 };
11043
11044 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
11045 SourceLocation CallLoc = Call->getRParenLoc();
11047 if (isLiteralZero(SizeArg) &&
11048 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
11049
11050 SourceLocation DiagLoc = SizeArg->getExprLoc();
11051
11052 // Some platforms #define bzero to __builtin_memset. See if this is the
11053 // case, and if so, emit a better diagnostic.
11054 if (BId == Builtin::BIbzero ||
11056 CallLoc, SM, S.getLangOpts()) == "bzero")) {
11057 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
11058 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
11059 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
11060 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
11061 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
11062 }
11063 return;
11064 }
11065
11066 // If the second argument to a memset is a sizeof expression and the third
11067 // isn't, this is also likely an error. This should catch
11068 // 'memset(buf, sizeof(buf), 0xff)'.
11069 if (BId == Builtin::BImemset &&
11070 doesExprLikelyComputeSize(Call->getArg(1)) &&
11071 !doesExprLikelyComputeSize(Call->getArg(2))) {
11072 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
11073 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
11074 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
11075 return;
11076 }
11077}
11078
11079void Sema::CheckMemaccessArguments(const CallExpr *Call,
11080 unsigned BId,
11081 IdentifierInfo *FnName) {
11082 assert(BId != 0);
11083
11084 // It is possible to have a non-standard definition of memset. Validate
11085 // we have enough arguments, and if not, abort further checking.
11086 unsigned ExpectedNumArgs =
11087 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11088 if (Call->getNumArgs() < ExpectedNumArgs)
11089 return;
11090
11091 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11092 BId == Builtin::BIstrndup ? 1 : 2);
11093 unsigned LenArg =
11094 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11095 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
11096
11097 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
11098 Call->getBeginLoc(), Call->getRParenLoc()))
11099 return;
11100
11101 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11102 CheckMemaccessSize(*this, BId, Call);
11103
11104 // We have special checking when the length is a sizeof expression.
11105 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
11106
11107 // Although widely used, 'bzero' is not a standard function. Be more strict
11108 // with the argument types before allowing diagnostics and only allow the
11109 // form bzero(ptr, sizeof(...)).
11110 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
11111 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11112 return;
11113
11114 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11115 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
11116 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
11117
11118 QualType DestTy = Dest->getType();
11119 QualType PointeeTy;
11120 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11121 PointeeTy = DestPtrTy->getPointeeType();
11122
11123 // Never warn about void type pointers. This can be used to suppress
11124 // false positives.
11125 if (PointeeTy->isVoidType())
11126 continue;
11127
11128 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11129 // actually comparing the expressions for equality. Because computing the
11130 // expression IDs can be expensive, we only do this if the diagnostic is
11131 // enabled.
11132 if (CheckSizeofMemaccessArgument(LenExpr, Dest, FnName))
11133 break;
11134
11135 // Also check for cases where the sizeof argument is the exact same
11136 // type as the memory argument, and where it points to a user-defined
11137 // record type.
11138 if (SizeOfArgTy != QualType()) {
11139 if (PointeeTy->isRecordType() &&
11140 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
11141 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
11142 PDiag(diag::warn_sizeof_pointer_type_memaccess)
11143 << FnName << SizeOfArgTy << ArgIdx
11144 << PointeeTy << Dest->getSourceRange()
11145 << LenExpr->getSourceRange());
11146 break;
11147 }
11148 }
11149 } else if (DestTy->isArrayType()) {
11150 PointeeTy = DestTy;
11151 }
11152
11153 if (PointeeTy == QualType())
11154 continue;
11155
11156 // Always complain about dynamic classes.
11157 bool IsContained;
11158 if (const CXXRecordDecl *ContainedRD =
11159 getContainedDynamicClass(PointeeTy, IsContained)) {
11160
11161 unsigned OperationType = 0;
11162 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11163 // "overwritten" if we're warning about the destination for any call
11164 // but memcmp; otherwise a verb appropriate to the call.
11165 if (ArgIdx != 0 || IsCmp) {
11166 if (BId == Builtin::BImemcpy)
11167 OperationType = 1;
11168 else if(BId == Builtin::BImemmove)
11169 OperationType = 2;
11170 else if (IsCmp)
11171 OperationType = 3;
11172 }
11173
11174 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11175 PDiag(diag::warn_dyn_class_memaccess)
11176 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11177 << IsContained << ContainedRD << OperationType
11178 << Call->getCallee()->getSourceRange());
11179 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11180 BId != Builtin::BImemset)
11182 Dest->getExprLoc(), Dest,
11183 PDiag(diag::warn_arc_object_memaccess)
11184 << ArgIdx << FnName << PointeeTy
11185 << Call->getCallee()->getSourceRange());
11186 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
11187
11188 // FIXME: Do not consider incomplete types even though they may be
11189 // completed later. GCC does not diagnose such code, but we may want to
11190 // consider diagnosing it in the future, perhaps under a different, but
11191 // related, diagnostic group.
11192 bool NonTriviallyCopyableCXXRecord =
11193 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
11194 !PointeeTy.isTriviallyCopyableType(Context);
11195
11196 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11198 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11199 PDiag(diag::warn_cstruct_memaccess)
11200 << ArgIdx << FnName << PointeeTy << 0);
11201 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11202 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11203 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11204 // FIXME: Limiting this warning to dest argument until we decide
11205 // whether it's valid for source argument too.
11206 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11207 PDiag(diag::warn_cxxstruct_memaccess)
11208 << FnName << PointeeTy);
11209 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11211 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11212 PDiag(diag::warn_cstruct_memaccess)
11213 << ArgIdx << FnName << PointeeTy << 1);
11214 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11215 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11216 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11217 // FIXME: Limiting this warning to dest argument until we decide
11218 // whether it's valid for source argument too.
11219 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11220 PDiag(diag::warn_cxxstruct_memaccess)
11221 << FnName << PointeeTy);
11222 } else {
11223 continue;
11224 }
11225 } else
11226 continue;
11227
11229 Dest->getExprLoc(), Dest,
11230 PDiag(diag::note_bad_memaccess_silence)
11231 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11232 break;
11233 }
11234}
11235
11236bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
11237 IdentifierInfo *FnName) {
11238 llvm::FoldingSetNodeID SizeOfArgID;
11239 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
11240 if (!SizeOfArg)
11241 return false;
11242 // Computing this warning is expensive, so we only do so if the warning is
11243 // enabled.
11244 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
11245 SizeOfArg->getExprLoc()))
11246 return false;
11247 QualType DestTy = Dest->getType();
11248 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
11249 if (!DestPtrTy)
11250 return false;
11251
11252 QualType PointeeTy = DestPtrTy->getPointeeType();
11253
11254 if (SizeOfArgID == llvm::FoldingSetNodeID())
11255 SizeOfArg->Profile(SizeOfArgID, Context, true);
11256
11257 llvm::FoldingSetNodeID DestID;
11258 Dest->Profile(DestID, Context, true);
11259 if (DestID == SizeOfArgID) {
11260 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11261 // over sizeof(src) as well.
11262 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11263 StringRef ReadableName = FnName->getName();
11264
11265 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest);
11266 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11267 ActionIdx = 1; // If its an address-of operator, just remove it.
11268 if (!PointeeTy->isIncompleteType() &&
11269 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
11270 ActionIdx = 2; // If the pointee's size is sizeof(char),
11271 // suggest an explicit length.
11272
11273 // If the function is defined as a builtin macro, do not show macro
11274 // expansion.
11275 SourceLocation SL = SizeOfArg->getExprLoc();
11276 SourceRange DSR = Dest->getSourceRange();
11277 SourceRange SSR = SizeOfArg->getSourceRange();
11278 SourceManager &SM = getSourceManager();
11279
11280 if (SM.isMacroArgExpansion(SL)) {
11281 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
11282 SL = SM.getSpellingLoc(SL);
11283 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
11284 SM.getSpellingLoc(DSR.getEnd()));
11285 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
11286 SM.getSpellingLoc(SSR.getEnd()));
11287 }
11288
11289 DiagRuntimeBehavior(SL, SizeOfArg,
11290 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11291 << ReadableName << PointeeTy << DestTy << DSR
11292 << SSR);
11293 DiagRuntimeBehavior(SL, SizeOfArg,
11294 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11295 << ActionIdx << SSR);
11296 return true;
11297 }
11298 return false;
11299}
11300
11301// A little helper routine: ignore addition and subtraction of integer literals.
11302// This intentionally does not ignore all integer constant expressions because
11303// we don't want to remove sizeof().
11304static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11305 Ex = Ex->IgnoreParenCasts();
11306
11307 while (true) {
11308 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11309 if (!BO || !BO->isAdditiveOp())
11310 break;
11311
11312 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11313 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11314
11315 if (isa<IntegerLiteral>(RHS))
11316 Ex = LHS;
11317 else if (isa<IntegerLiteral>(LHS))
11318 Ex = RHS;
11319 else
11320 break;
11321 }
11322
11323 return Ex;
11324}
11325
11327 ASTContext &Context) {
11328 // Only handle constant-sized or VLAs, but not flexible members.
11329 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11330 // Only issue the FIXIT for arrays of size > 1.
11331 if (CAT->getZExtSize() <= 1)
11332 return false;
11333 } else if (!Ty->isVariableArrayType()) {
11334 return false;
11335 }
11336 return true;
11337}
11338
11339void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11340 IdentifierInfo *FnName) {
11341
11342 // Don't crash if the user has the wrong number of arguments
11343 unsigned NumArgs = Call->getNumArgs();
11344 if ((NumArgs != 3) && (NumArgs != 4))
11345 return;
11346
11347 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11348 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11349 const Expr *CompareWithSrc = nullptr;
11350
11351 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11352 Call->getBeginLoc(), Call->getRParenLoc()))
11353 return;
11354
11355 // Look for 'strlcpy(dst, x, sizeof(x))'
11356 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11357 CompareWithSrc = Ex;
11358 else {
11359 // Look for 'strlcpy(dst, x, strlen(x))'
11360 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11361 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11362 SizeCall->getNumArgs() == 1)
11363 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11364 }
11365 }
11366
11367 if (!CompareWithSrc)
11368 return;
11369
11370 // Determine if the argument to sizeof/strlen is equal to the source
11371 // argument. In principle there's all kinds of things you could do
11372 // here, for instance creating an == expression and evaluating it with
11373 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11374 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11375 if (!SrcArgDRE)
11376 return;
11377
11378 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11379 if (!CompareWithSrcDRE ||
11380 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11381 return;
11382
11383 const Expr *OriginalSizeArg = Call->getArg(2);
11384 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11385 << OriginalSizeArg->getSourceRange() << FnName;
11386
11387 // Output a FIXIT hint if the destination is an array (rather than a
11388 // pointer to an array). This could be enhanced to handle some
11389 // pointers if we know the actual size, like if DstArg is 'array+2'
11390 // we could say 'sizeof(array)-2'.
11391 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11393 return;
11394
11395 SmallString<128> sizeString;
11396 llvm::raw_svector_ostream OS(sizeString);
11397 OS << "sizeof(";
11398 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11399 OS << ")";
11400
11401 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11402 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11403 OS.str());
11404}
11405
11406/// Check if two expressions refer to the same declaration.
11407static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11408 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11409 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11410 return D1->getDecl() == D2->getDecl();
11411 return false;
11412}
11413
11414static const Expr *getStrlenExprArg(const Expr *E) {
11415 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11416 const FunctionDecl *FD = CE->getDirectCallee();
11417 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11418 return nullptr;
11419 return CE->getArg(0)->IgnoreParenCasts();
11420 }
11421 return nullptr;
11422}
11423
11424void Sema::CheckStrncatArguments(const CallExpr *CE,
11425 const IdentifierInfo *FnName) {
11426 // Don't crash if the user has the wrong number of arguments.
11427 if (CE->getNumArgs() < 3)
11428 return;
11429 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11430 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11431 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11432
11433 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11434 CE->getRParenLoc()))
11435 return;
11436
11437 // Identify common expressions, which are wrongly used as the size argument
11438 // to strncat and may lead to buffer overflows.
11439 unsigned PatternType = 0;
11440 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11441 // - sizeof(dst)
11442 if (referToTheSameDecl(SizeOfArg, DstArg))
11443 PatternType = 1;
11444 // - sizeof(src)
11445 else if (referToTheSameDecl(SizeOfArg, SrcArg))
11446 PatternType = 2;
11447 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11448 if (BE->getOpcode() == BO_Sub) {
11449 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11450 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11451 // - sizeof(dst) - strlen(dst)
11452 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11454 PatternType = 1;
11455 // - sizeof(src) - (anything)
11456 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11457 PatternType = 2;
11458 }
11459 }
11460
11461 if (PatternType == 0)
11462 return;
11463
11464 // Generate the diagnostic.
11465 SourceLocation SL = LenArg->getBeginLoc();
11466 SourceRange SR = LenArg->getSourceRange();
11467 SourceManager &SM = getSourceManager();
11468
11469 // If the function is defined as a builtin macro, do not show macro expansion.
11470 if (SM.isMacroArgExpansion(SL)) {
11471 SL = SM.getSpellingLoc(SL);
11472 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11473 SM.getSpellingLoc(SR.getEnd()));
11474 }
11475
11476 // Check if the destination is an array (rather than a pointer to an array).
11477 QualType DstTy = DstArg->getType();
11478 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11479 Context);
11480 if (!isKnownSizeArray) {
11481 if (PatternType == 1)
11482 Diag(SL, diag::warn_strncat_wrong_size) << SR;
11483 else
11484 Diag(SL, diag::warn_strncat_src_size) << SR;
11485 return;
11486 }
11487
11488 if (PatternType == 1)
11489 Diag(SL, diag::warn_strncat_large_size) << SR;
11490 else
11491 Diag(SL, diag::warn_strncat_src_size) << SR;
11492
11493 SmallString<128> sizeString;
11494 llvm::raw_svector_ostream OS(sizeString);
11495 OS << "sizeof(";
11496 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11497 OS << ") - ";
11498 OS << "strlen(";
11499 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11500 OS << ") - 1";
11501
11502 Diag(SL, diag::note_strncat_wrong_size)
11503 << FixItHint::CreateReplacement(SR, OS.str());
11504}
11505
11506namespace {
11507void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11508 const UnaryOperator *UnaryExpr, const Decl *D) {
11510 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11511 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11512 return;
11513 }
11514}
11515
11516void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11517 const UnaryOperator *UnaryExpr) {
11518 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11519 const Decl *D = Lvalue->getDecl();
11520 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11521 if (!DD->getType()->isReferenceType())
11522 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11523 }
11524 }
11525
11526 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11527 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11528 Lvalue->getMemberDecl());
11529}
11530
11531void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11532 const UnaryOperator *UnaryExpr) {
11533 const auto *Lambda = dyn_cast<LambdaExpr>(
11535 if (!Lambda)
11536 return;
11537
11538 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11539 << CalleeName << 2 /*object: lambda expression*/;
11540}
11541
11542void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11543 const DeclRefExpr *Lvalue) {
11544 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11545 if (Var == nullptr)
11546 return;
11547
11548 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11549 << CalleeName << 0 /*object: */ << Var;
11550}
11551
11552void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11553 const CastExpr *Cast) {
11554 SmallString<128> SizeString;
11555 llvm::raw_svector_ostream OS(SizeString);
11556
11557 clang::CastKind Kind = Cast->getCastKind();
11558 if (Kind == clang::CK_BitCast &&
11559 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11560 return;
11561 if (Kind == clang::CK_IntegralToPointer &&
11563 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11564 return;
11565
11566 switch (Cast->getCastKind()) {
11567 case clang::CK_BitCast:
11568 case clang::CK_IntegralToPointer:
11569 case clang::CK_FunctionToPointerDecay:
11570 OS << '\'';
11571 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11572 OS << '\'';
11573 break;
11574 default:
11575 return;
11576 }
11577
11578 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11579 << CalleeName << 0 /*object: */ << OS.str();
11580}
11581} // namespace
11582
11583void Sema::CheckFreeArguments(const CallExpr *E) {
11584 const std::string CalleeName =
11585 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11586
11587 { // Prefer something that doesn't involve a cast to make things simpler.
11588 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11589 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11590 switch (UnaryExpr->getOpcode()) {
11591 case UnaryOperator::Opcode::UO_AddrOf:
11592 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11593 case UnaryOperator::Opcode::UO_Plus:
11594 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11595 default:
11596 break;
11597 }
11598
11599 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11600 if (Lvalue->getType()->isArrayType())
11601 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11602
11603 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11604 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11605 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11606 return;
11607 }
11608
11609 if (isa<BlockExpr>(Arg)) {
11610 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11611 << CalleeName << 1 /*object: block*/;
11612 return;
11613 }
11614 }
11615 // Maybe the cast was important, check after the other cases.
11616 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11617 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11618}
11619
11620void
11621Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11622 SourceLocation ReturnLoc,
11623 bool isObjCMethod,
11624 const AttrVec *Attrs,
11625 const FunctionDecl *FD) {
11626 // Check if the return value is null but should not be.
11627 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11628 (!isObjCMethod && isNonNullType(lhsType))) &&
11629 CheckNonNullExpr(*this, RetValExp))
11630 Diag(ReturnLoc, diag::warn_null_ret)
11631 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11632
11633 // C++11 [basic.stc.dynamic.allocation]p4:
11634 // If an allocation function declared with a non-throwing
11635 // exception-specification fails to allocate storage, it shall return
11636 // a null pointer. Any other allocation function that fails to allocate
11637 // storage shall indicate failure only by throwing an exception [...]
11638 if (FD) {
11640 if (Op == OO_New || Op == OO_Array_New) {
11641 const FunctionProtoType *Proto
11642 = FD->getType()->castAs<FunctionProtoType>();
11643 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11644 CheckNonNullExpr(*this, RetValExp))
11645 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11646 << FD << getLangOpts().CPlusPlus11;
11647 }
11648 }
11649
11650 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11651 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11652 }
11653
11654 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11655 // here prevent the user from using a PPC MMA type as trailing return type.
11656 if (Context.getTargetInfo().getTriple().isPPC64())
11657 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11658}
11659
11661 const Expr *RHS, BinaryOperatorKind Opcode) {
11662 if (!BinaryOperator::isEqualityOp(Opcode))
11663 return;
11664
11665 // Match and capture subexpressions such as "(float) X == 0.1".
11666 const FloatingLiteral *FPLiteral;
11667 const CastExpr *FPCast;
11668 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11669 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11670 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11671 return FPLiteral && FPCast;
11672 };
11673
11674 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11675 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11676 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11677 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11678 TargetTy->isFloatingPoint()) {
11679 bool Lossy;
11680 llvm::APFloat TargetC = FPLiteral->getValue();
11681 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11682 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11683 if (Lossy) {
11684 // If the literal cannot be represented in the source type, then a
11685 // check for == is always false and check for != is always true.
11686 Diag(Loc, diag::warn_float_compare_literal)
11687 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11688 << LHS->getSourceRange() << RHS->getSourceRange();
11689 return;
11690 }
11691 }
11692 }
11693
11694 // Match a more general floating-point equality comparison (-Wfloat-equal).
11695 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11696 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11697
11698 // Special case: check for x == x (which is OK).
11699 // Do not emit warnings for such cases.
11700 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11701 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11702 if (DRL->getDecl() == DRR->getDecl())
11703 return;
11704
11705 // Special case: check for comparisons against literals that can be exactly
11706 // represented by APFloat. In such cases, do not emit a warning. This
11707 // is a heuristic: often comparison against such literals are used to
11708 // detect if a value in a variable has not changed. This clearly can
11709 // lead to false negatives.
11710 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11711 if (FLL->isExact())
11712 return;
11713 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11714 if (FLR->isExact())
11715 return;
11716
11717 // Check for comparisons with builtin types.
11718 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
11719 CL && CL->getBuiltinCallee())
11720 return;
11721
11722 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11723 CR && CR->getBuiltinCallee())
11724 return;
11725
11726 // Emit the diagnostic.
11727 Diag(Loc, diag::warn_floatingpoint_eq)
11728 << LHS->getSourceRange() << RHS->getSourceRange();
11729}
11730
11731//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11732//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11733
11734namespace {
11735
11736/// Structure recording the 'active' range of an integer-valued
11737/// expression.
11738struct IntRange {
11739 /// The number of bits active in the int. Note that this includes exactly one
11740 /// sign bit if !NonNegative.
11741 unsigned Width;
11742
11743 /// True if the int is known not to have negative values. If so, all leading
11744 /// bits before Width are known zero, otherwise they are known to be the
11745 /// same as the MSB within Width.
11746 bool NonNegative;
11747
11748 IntRange(unsigned Width, bool NonNegative)
11749 : Width(Width), NonNegative(NonNegative) {}
11750
11751 /// Number of bits excluding the sign bit.
11752 unsigned valueBits() const {
11753 return NonNegative ? Width : Width - 1;
11754 }
11755
11756 /// Returns the range of the bool type.
11757 static IntRange forBoolType() {
11758 return IntRange(1, true);
11759 }
11760
11761 /// Returns the range of an opaque value of the given integral type.
11762 static IntRange forValueOfType(ASTContext &C, QualType T) {
11763 return forValueOfCanonicalType(C,
11765 }
11766
11767 /// Returns the range of an opaque value of a canonical integral type.
11768 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11769 assert(T->isCanonicalUnqualified());
11770
11771 if (const auto *VT = dyn_cast<VectorType>(T))
11772 T = VT->getElementType().getTypePtr();
11773 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11774 T = MT->getElementType().getTypePtr();
11775 if (const auto *CT = dyn_cast<ComplexType>(T))
11776 T = CT->getElementType().getTypePtr();
11777 if (const auto *AT = dyn_cast<AtomicType>(T))
11778 T = AT->getValueType().getTypePtr();
11779 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11780 T = OBT->getUnderlyingType().getTypePtr();
11781
11782 if (!C.getLangOpts().CPlusPlus) {
11783 // For enum types in C code, use the underlying datatype.
11784 if (const auto *ED = T->getAsEnumDecl())
11785 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11786 } else if (auto *Enum = T->getAsEnumDecl()) {
11787 // For enum types in C++, use the known bit width of the enumerators.
11788 // In C++11, enums can have a fixed underlying type. Use this type to
11789 // compute the range.
11790 if (Enum->isFixed()) {
11791 return IntRange(C.getIntWidth(QualType(T, 0)),
11792 !Enum->getIntegerType()->isSignedIntegerType());
11793 }
11794
11795 unsigned NumPositive = Enum->getNumPositiveBits();
11796 unsigned NumNegative = Enum->getNumNegativeBits();
11797
11798 if (NumNegative == 0)
11799 return IntRange(NumPositive, true/*NonNegative*/);
11800 else
11801 return IntRange(std::max(NumPositive + 1, NumNegative),
11802 false/*NonNegative*/);
11803 }
11804
11805 if (const auto *EIT = dyn_cast<BitIntType>(T))
11806 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11807
11808 const BuiltinType *BT = cast<BuiltinType>(T);
11809 assert(BT->isInteger());
11810
11811 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11812 }
11813
11814 /// Returns the "target" range of a canonical integral type, i.e.
11815 /// the range of values expressible in the type.
11816 ///
11817 /// This matches forValueOfCanonicalType except that enums have the
11818 /// full range of their type, not the range of their enumerators.
11819 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11820 assert(T->isCanonicalUnqualified());
11821
11822 if (const VectorType *VT = dyn_cast<VectorType>(T))
11823 T = VT->getElementType().getTypePtr();
11824 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11825 T = MT->getElementType().getTypePtr();
11826 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11827 T = CT->getElementType().getTypePtr();
11828 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11829 T = AT->getValueType().getTypePtr();
11830 if (const auto *ED = T->getAsEnumDecl())
11831 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
11832 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11833 T = OBT->getUnderlyingType().getTypePtr();
11834
11835 if (const auto *EIT = dyn_cast<BitIntType>(T))
11836 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11837
11838 const BuiltinType *BT = cast<BuiltinType>(T);
11839 assert(BT->isInteger());
11840
11841 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11842 }
11843
11844 /// Returns the supremum of two ranges: i.e. their conservative merge.
11845 static IntRange join(IntRange L, IntRange R) {
11846 bool Unsigned = L.NonNegative && R.NonNegative;
11847 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11848 L.NonNegative && R.NonNegative);
11849 }
11850
11851 /// Return the range of a bitwise-AND of the two ranges.
11852 static IntRange bit_and(IntRange L, IntRange R) {
11853 unsigned Bits = std::max(L.Width, R.Width);
11854 bool NonNegative = false;
11855 if (L.NonNegative) {
11856 Bits = std::min(Bits, L.Width);
11857 NonNegative = true;
11858 }
11859 if (R.NonNegative) {
11860 Bits = std::min(Bits, R.Width);
11861 NonNegative = true;
11862 }
11863 return IntRange(Bits, NonNegative);
11864 }
11865
11866 /// Return the range of a sum of the two ranges.
11867 static IntRange sum(IntRange L, IntRange R) {
11868 bool Unsigned = L.NonNegative && R.NonNegative;
11869 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11870 Unsigned);
11871 }
11872
11873 /// Return the range of a difference of the two ranges.
11874 static IntRange difference(IntRange L, IntRange R) {
11875 // We need a 1-bit-wider range if:
11876 // 1) LHS can be negative: least value can be reduced.
11877 // 2) RHS can be negative: greatest value can be increased.
11878 bool CanWiden = !L.NonNegative || !R.NonNegative;
11879 bool Unsigned = L.NonNegative && R.Width == 0;
11880 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11881 !Unsigned,
11882 Unsigned);
11883 }
11884
11885 /// Return the range of a product of the two ranges.
11886 static IntRange product(IntRange L, IntRange R) {
11887 // If both LHS and RHS can be negative, we can form
11888 // -2^L * -2^R = 2^(L + R)
11889 // which requires L + R + 1 value bits to represent.
11890 bool CanWiden = !L.NonNegative && !R.NonNegative;
11891 bool Unsigned = L.NonNegative && R.NonNegative;
11892 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11893 Unsigned);
11894 }
11895
11896 /// Return the range of a remainder operation between the two ranges.
11897 static IntRange rem(IntRange L, IntRange R) {
11898 // The result of a remainder can't be larger than the result of
11899 // either side. The sign of the result is the sign of the LHS.
11900 bool Unsigned = L.NonNegative;
11901 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11902 Unsigned);
11903 }
11904};
11905
11906} // namespace
11907
11908static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11909 if (value.isSigned() && value.isNegative())
11910 return IntRange(value.getSignificantBits(), false);
11911
11912 if (value.getBitWidth() > MaxWidth)
11913 value = value.trunc(MaxWidth);
11914
11915 // isNonNegative() just checks the sign bit without considering
11916 // signedness.
11917 return IntRange(value.getActiveBits(), true);
11918}
11919
11920static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11921 if (result.isInt())
11922 return GetValueRange(result.getInt(), MaxWidth);
11923
11924 if (result.isVector()) {
11925 IntRange R = GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
11926 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11927 IntRange El = GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
11928 R = IntRange::join(R, El);
11929 }
11930 return R;
11931 }
11932
11933 if (result.isComplexInt()) {
11934 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
11935 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
11936 return IntRange::join(R, I);
11937 }
11938
11939 // This can happen with lossless casts to intptr_t of "based" lvalues.
11940 // Assume it might use arbitrary bits.
11941 // FIXME: The only reason we need to pass the type in here is to get
11942 // the sign right on this one case. It would be nice if APValue
11943 // preserved this.
11944 assert(result.isLValue() || result.isAddrLabelDiff());
11945 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11946}
11947
11948static QualType GetExprType(const Expr *E) {
11949 QualType Ty = E->getType();
11950 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11951 Ty = AtomicRHS->getValueType();
11952 return Ty;
11953}
11954
11955/// Attempts to estimate an approximate range for the given integer expression.
11956/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11957/// reliable estimation cannot be determined.
11958///
11959/// \param MaxWidth The width to which the value will be truncated.
11960/// \param InConstantContext If \c true, interpret the expression within a
11961/// constant context.
11962/// \param Approximate If \c true, provide a likely range of values by assuming
11963/// that arithmetic on narrower types remains within those types.
11964/// If \c false, return a range that includes all possible values
11965/// resulting from the expression.
11966/// \returns A range of values that the expression might take, or
11967/// std::nullopt if a reliable estimation cannot be determined.
11968static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11969 unsigned MaxWidth,
11970 bool InConstantContext,
11971 bool Approximate) {
11972 E = E->IgnoreParens();
11973
11974 // Try a full evaluation first.
11975 Expr::EvalResult result;
11976 if (E->EvaluateAsRValue(result, C, InConstantContext))
11977 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
11978
11979 // I think we only want to look through implicit casts here; if the
11980 // user has an explicit widening cast, we should treat the value as
11981 // being of the new, wider type.
11982 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11983 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11984 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11985 Approximate);
11986
11987 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11988
11989 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11990 CE->getCastKind() == CK_BooleanToSignedIntegral;
11991
11992 // Assume that non-integer casts can span the full range of the type.
11993 if (!isIntegerCast)
11994 return OutputTypeRange;
11995
11996 std::optional<IntRange> SubRange = TryGetExprRange(
11997 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
11998 InConstantContext, Approximate);
11999 if (!SubRange)
12000 return std::nullopt;
12001
12002 // Bail out if the subexpr's range is as wide as the cast type.
12003 if (SubRange->Width >= OutputTypeRange.Width)
12004 return OutputTypeRange;
12005
12006 // Otherwise, we take the smaller width, and we're non-negative if
12007 // either the output type or the subexpr is.
12008 return IntRange(SubRange->Width,
12009 SubRange->NonNegative || OutputTypeRange.NonNegative);
12010 }
12011
12012 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12013 // If we can fold the condition, just take that operand.
12014 bool CondResult;
12015 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
12016 return TryGetExprRange(
12017 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
12018 InConstantContext, Approximate);
12019
12020 // Otherwise, conservatively merge.
12021 // TryGetExprRange requires an integer expression, but a throw expression
12022 // results in a void type.
12023 Expr *TrueExpr = CO->getTrueExpr();
12024 if (TrueExpr->getType()->isVoidType())
12025 return std::nullopt;
12026
12027 std::optional<IntRange> L =
12028 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
12029 if (!L)
12030 return std::nullopt;
12031
12032 Expr *FalseExpr = CO->getFalseExpr();
12033 if (FalseExpr->getType()->isVoidType())
12034 return std::nullopt;
12035
12036 std::optional<IntRange> R =
12037 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
12038 if (!R)
12039 return std::nullopt;
12040
12041 return IntRange::join(*L, *R);
12042 }
12043
12044 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12045 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
12046
12047 switch (BO->getOpcode()) {
12048 case BO_Cmp:
12049 llvm_unreachable("builtin <=> should have class type");
12050
12051 // Boolean-valued operations are single-bit and positive.
12052 case BO_LAnd:
12053 case BO_LOr:
12054 case BO_LT:
12055 case BO_GT:
12056 case BO_LE:
12057 case BO_GE:
12058 case BO_EQ:
12059 case BO_NE:
12060 return IntRange::forBoolType();
12061
12062 // The type of the assignments is the type of the LHS, so the RHS
12063 // is not necessarily the same type.
12064 case BO_MulAssign:
12065 case BO_DivAssign:
12066 case BO_RemAssign:
12067 case BO_AddAssign:
12068 case BO_SubAssign:
12069 case BO_XorAssign:
12070 case BO_OrAssign:
12071 // TODO: bitfields?
12072 return IntRange::forValueOfType(C, GetExprType(E));
12073
12074 // Simple assignments just pass through the RHS, which will have
12075 // been coerced to the LHS type.
12076 case BO_Assign:
12077 // TODO: bitfields?
12078 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12079 Approximate);
12080
12081 // Operations with opaque sources are black-listed.
12082 case BO_PtrMemD:
12083 case BO_PtrMemI:
12084 return IntRange::forValueOfType(C, GetExprType(E));
12085
12086 // Bitwise-and uses the *infinum* of the two source ranges.
12087 case BO_And:
12088 case BO_AndAssign:
12089 Combine = IntRange::bit_and;
12090 break;
12091
12092 // Left shift gets black-listed based on a judgement call.
12093 case BO_Shl:
12094 // ...except that we want to treat '1 << (blah)' as logically
12095 // positive. It's an important idiom.
12096 if (IntegerLiteral *I
12097 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
12098 if (I->getValue() == 1) {
12099 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
12100 return IntRange(R.Width, /*NonNegative*/ true);
12101 }
12102 }
12103 [[fallthrough]];
12104
12105 case BO_ShlAssign:
12106 return IntRange::forValueOfType(C, GetExprType(E));
12107
12108 // Right shift by a constant can narrow its left argument.
12109 case BO_Shr:
12110 case BO_ShrAssign: {
12111 std::optional<IntRange> L = TryGetExprRange(
12112 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
12113 if (!L)
12114 return std::nullopt;
12115
12116 // If the shift amount is a positive constant, drop the width by
12117 // that much.
12118 if (std::optional<llvm::APSInt> shift =
12119 BO->getRHS()->getIntegerConstantExpr(C)) {
12120 if (shift->isNonNegative()) {
12121 if (shift->uge(L->Width))
12122 L->Width = (L->NonNegative ? 0 : 1);
12123 else
12124 L->Width -= shift->getZExtValue();
12125 }
12126 }
12127
12128 return L;
12129 }
12130
12131 // Comma acts as its right operand.
12132 case BO_Comma:
12133 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12134 Approximate);
12135
12136 case BO_Add:
12137 if (!Approximate)
12138 Combine = IntRange::sum;
12139 break;
12140
12141 case BO_Sub:
12142 if (BO->getLHS()->getType()->isPointerType())
12143 return IntRange::forValueOfType(C, GetExprType(E));
12144 if (!Approximate)
12145 Combine = IntRange::difference;
12146 break;
12147
12148 case BO_Mul:
12149 if (!Approximate)
12150 Combine = IntRange::product;
12151 break;
12152
12153 // The width of a division result is mostly determined by the size
12154 // of the LHS.
12155 case BO_Div: {
12156 // Don't 'pre-truncate' the operands.
12157 unsigned opWidth = C.getIntWidth(GetExprType(E));
12158 std::optional<IntRange> L = TryGetExprRange(
12159 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
12160 if (!L)
12161 return std::nullopt;
12162
12163 // If the divisor is constant, use that.
12164 if (std::optional<llvm::APSInt> divisor =
12165 BO->getRHS()->getIntegerConstantExpr(C)) {
12166 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12167 if (log2 >= L->Width)
12168 L->Width = (L->NonNegative ? 0 : 1);
12169 else
12170 L->Width = std::min(L->Width - log2, MaxWidth);
12171 return L;
12172 }
12173
12174 // Otherwise, just use the LHS's width.
12175 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12176 // could be -1.
12177 std::optional<IntRange> R = TryGetExprRange(
12178 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
12179 if (!R)
12180 return std::nullopt;
12181
12182 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12183 }
12184
12185 case BO_Rem:
12186 Combine = IntRange::rem;
12187 break;
12188
12189 // The default behavior is okay for these.
12190 case BO_Xor:
12191 case BO_Or:
12192 break;
12193 }
12194
12195 // Combine the two ranges, but limit the result to the type in which we
12196 // performed the computation.
12197 QualType T = GetExprType(E);
12198 unsigned opWidth = C.getIntWidth(T);
12199 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
12200 InConstantContext, Approximate);
12201 if (!L)
12202 return std::nullopt;
12203
12204 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
12205 InConstantContext, Approximate);
12206 if (!R)
12207 return std::nullopt;
12208
12209 IntRange C = Combine(*L, *R);
12210 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12211 C.Width = std::min(C.Width, MaxWidth);
12212 return C;
12213 }
12214
12215 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12216 switch (UO->getOpcode()) {
12217 // Boolean-valued operations are white-listed.
12218 case UO_LNot:
12219 return IntRange::forBoolType();
12220
12221 // Operations with opaque sources are black-listed.
12222 case UO_Deref:
12223 case UO_AddrOf: // should be impossible
12224 return IntRange::forValueOfType(C, GetExprType(E));
12225
12226 case UO_Minus: {
12227 if (E->getType()->isUnsignedIntegerType()) {
12228 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12229 Approximate);
12230 }
12231
12232 std::optional<IntRange> SubRange = TryGetExprRange(
12233 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12234
12235 if (!SubRange)
12236 return std::nullopt;
12237
12238 // If the range was previously non-negative, we need an extra bit for the
12239 // sign bit. Otherwise, we need an extra bit because the negation of the
12240 // most-negative value is one bit wider than that value.
12241 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
12242 }
12243
12244 case UO_Not: {
12245 if (E->getType()->isUnsignedIntegerType()) {
12246 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12247 Approximate);
12248 }
12249
12250 std::optional<IntRange> SubRange = TryGetExprRange(
12251 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12252
12253 if (!SubRange)
12254 return std::nullopt;
12255
12256 // The width increments by 1 if the sub-expression cannot be negative
12257 // since it now can be.
12258 return IntRange(
12259 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
12260 false);
12261 }
12262
12263 default:
12264 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12265 Approximate);
12266 }
12267 }
12268
12269 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12270 // The source expression is null for the OpaqueValueExpr that stands in for
12271 // a non-type template argument of pointer or reference type; fall back to
12272 // the range of the type in that case.
12273 if (const Expr *SourceExpr = OVE->getSourceExpr())
12274 return TryGetExprRange(C, SourceExpr, MaxWidth, InConstantContext,
12275 Approximate);
12276 }
12277
12278 if (const auto *BitField = E->getSourceBitField())
12279 return IntRange(BitField->getBitWidthValue(),
12280 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12281
12282 if (GetExprType(E)->isVoidType())
12283 return std::nullopt;
12284
12285 return IntRange::forValueOfType(C, GetExprType(E));
12286}
12287
12288static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12289 bool InConstantContext,
12290 bool Approximate) {
12291 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
12292 Approximate);
12293}
12294
12295/// Checks whether the given value, which currently has the given
12296/// source semantics, has the same value when coerced through the
12297/// target semantics.
12298static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12299 const llvm::fltSemantics &Src,
12300 const llvm::fltSemantics &Tgt) {
12301 llvm::APFloat truncated = value;
12302
12303 bool ignored;
12304 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12305 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12306
12307 return truncated.bitwiseIsEqual(value);
12308}
12309
12310/// Checks whether the given value, which currently has the given
12311/// source semantics, has the same value when coerced through the
12312/// target semantics.
12313///
12314/// The value might be a vector of floats (or a complex number).
12315static bool IsSameFloatAfterCast(const APValue &value,
12316 const llvm::fltSemantics &Src,
12317 const llvm::fltSemantics &Tgt) {
12318 if (value.isFloat())
12319 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12320
12321 if (value.isVector()) {
12322 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12323 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12324 return false;
12325 return true;
12326 }
12327
12328 if (value.isMatrix()) {
12329 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12330 if (!IsSameFloatAfterCast(value.getMatrixElt(i), Src, Tgt))
12331 return false;
12332 return true;
12333 }
12334
12335 assert(value.isComplexFloat());
12336 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12337 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12338}
12339
12340static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12341 bool IsListInit = false);
12342
12343static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12344 // Suppress cases where we are comparing against an enum constant.
12345 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12346 if (isa<EnumConstantDecl>(DR->getDecl()))
12347 return true;
12348
12349 // Suppress cases where the value is expanded from a macro, unless that macro
12350 // is how a language represents a boolean literal. This is the case in both C
12351 // and Objective-C.
12352 SourceLocation BeginLoc = E->getBeginLoc();
12353 if (BeginLoc.isMacroID()) {
12354 StringRef MacroName = Lexer::getImmediateMacroName(
12355 BeginLoc, S.getSourceManager(), S.getLangOpts());
12356 return MacroName != "YES" && MacroName != "NO" &&
12357 MacroName != "true" && MacroName != "false";
12358 }
12359
12360 return false;
12361}
12362
12363static bool isKnownToHaveUnsignedValue(const Expr *E) {
12364 return E->getType()->isIntegerType() &&
12365 (!E->getType()->isSignedIntegerType() ||
12367}
12368
12369namespace {
12370/// The promoted range of values of a type. In general this has the
12371/// following structure:
12372///
12373/// |-----------| . . . |-----------|
12374/// ^ ^ ^ ^
12375/// Min HoleMin HoleMax Max
12376///
12377/// ... where there is only a hole if a signed type is promoted to unsigned
12378/// (in which case Min and Max are the smallest and largest representable
12379/// values).
12380struct PromotedRange {
12381 // Min, or HoleMax if there is a hole.
12382 llvm::APSInt PromotedMin;
12383 // Max, or HoleMin if there is a hole.
12384 llvm::APSInt PromotedMax;
12385
12386 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12387 if (R.Width == 0)
12388 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12389 else if (R.Width >= BitWidth && !Unsigned) {
12390 // Promotion made the type *narrower*. This happens when promoting
12391 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12392 // Treat all values of 'signed int' as being in range for now.
12393 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12394 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12395 } else {
12396 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12397 .extOrTrunc(BitWidth);
12398 PromotedMin.setIsUnsigned(Unsigned);
12399
12400 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12401 .extOrTrunc(BitWidth);
12402 PromotedMax.setIsUnsigned(Unsigned);
12403 }
12404 }
12405
12406 // Determine whether this range is contiguous (has no hole).
12407 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12408
12409 // Where a constant value is within the range.
12410 enum ComparisonResult {
12411 LT = 0x1,
12412 LE = 0x2,
12413 GT = 0x4,
12414 GE = 0x8,
12415 EQ = 0x10,
12416 NE = 0x20,
12417 InRangeFlag = 0x40,
12418
12419 Less = LE | LT | NE,
12420 Min = LE | InRangeFlag,
12421 InRange = InRangeFlag,
12422 Max = GE | InRangeFlag,
12423 Greater = GE | GT | NE,
12424
12425 OnlyValue = LE | GE | EQ | InRangeFlag,
12426 InHole = NE
12427 };
12428
12429 ComparisonResult compare(const llvm::APSInt &Value) const {
12430 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12431 Value.isUnsigned() == PromotedMin.isUnsigned());
12432 if (!isContiguous()) {
12433 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12434 if (Value.isMinValue()) return Min;
12435 if (Value.isMaxValue()) return Max;
12436 if (Value >= PromotedMin) return InRange;
12437 if (Value <= PromotedMax) return InRange;
12438 return InHole;
12439 }
12440
12441 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12442 case -1: return Less;
12443 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12444 case 1:
12445 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12446 case -1: return InRange;
12447 case 0: return Max;
12448 case 1: return Greater;
12449 }
12450 }
12451
12452 llvm_unreachable("impossible compare result");
12453 }
12454
12455 static std::optional<StringRef>
12456 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12457 if (Op == BO_Cmp) {
12458 ComparisonResult LTFlag = LT, GTFlag = GT;
12459 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12460
12461 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12462 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12463 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12464 return std::nullopt;
12465 }
12466
12467 ComparisonResult TrueFlag, FalseFlag;
12468 if (Op == BO_EQ) {
12469 TrueFlag = EQ;
12470 FalseFlag = NE;
12471 } else if (Op == BO_NE) {
12472 TrueFlag = NE;
12473 FalseFlag = EQ;
12474 } else {
12475 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12476 TrueFlag = LT;
12477 FalseFlag = GE;
12478 } else {
12479 TrueFlag = GT;
12480 FalseFlag = LE;
12481 }
12482 if (Op == BO_GE || Op == BO_LE)
12483 std::swap(TrueFlag, FalseFlag);
12484 }
12485 if (R & TrueFlag)
12486 return StringRef("true");
12487 if (R & FalseFlag)
12488 return StringRef("false");
12489 return std::nullopt;
12490 }
12491};
12492}
12493
12494static bool HasEnumType(const Expr *E) {
12495 // Strip off implicit integral promotions.
12496 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12497 if (ICE->getCastKind() != CK_IntegralCast &&
12498 ICE->getCastKind() != CK_NoOp)
12499 break;
12500 E = ICE->getSubExpr();
12501 }
12502
12503 return E->getType()->isEnumeralType();
12504}
12505
12507 // The values of this enumeration are used in the diagnostics
12508 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12509 enum ConstantValueKind {
12510 Miscellaneous = 0,
12511 LiteralTrue,
12512 LiteralFalse
12513 };
12514 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12515 return BL->getValue() ? ConstantValueKind::LiteralTrue
12516 : ConstantValueKind::LiteralFalse;
12517 return ConstantValueKind::Miscellaneous;
12518}
12519
12522 const llvm::APSInt &Value,
12523 bool RhsConstant) {
12525 return false;
12526
12527 Expr *OriginalOther = Other;
12528
12529 Constant = Constant->IgnoreParenImpCasts();
12530 Other = Other->IgnoreParenImpCasts();
12531
12532 // Suppress warnings on tautological comparisons between values of the same
12533 // enumeration type. There are only two ways we could warn on this:
12534 // - If the constant is outside the range of representable values of
12535 // the enumeration. In such a case, we should warn about the cast
12536 // to enumeration type, not about the comparison.
12537 // - If the constant is the maximum / minimum in-range value. For an
12538 // enumeratin type, such comparisons can be meaningful and useful.
12539 if (Constant->getType()->isEnumeralType() &&
12540 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12541 return false;
12542
12543 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12544 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
12545 if (!OtherValueRange)
12546 return false;
12547
12548 QualType OtherT = Other->getType();
12549 if (const auto *AT = OtherT->getAs<AtomicType>())
12550 OtherT = AT->getValueType();
12551 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12552
12553 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12554 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12555 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12556 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
12557 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12558
12559 // Whether we're treating Other as being a bool because of the form of
12560 // expression despite it having another type (typically 'int' in C).
12561 bool OtherIsBooleanDespiteType =
12562 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12563 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12564 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12565
12566 // Check if all values in the range of possible values of this expression
12567 // lead to the same comparison outcome.
12568 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12569 Value.isUnsigned());
12570 auto Cmp = OtherPromotedValueRange.compare(Value);
12571 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12572 if (!Result)
12573 return false;
12574
12575 // Also consider the range determined by the type alone. This allows us to
12576 // classify the warning under the proper diagnostic group.
12577 bool TautologicalTypeCompare = false;
12578 {
12579 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12580 Value.isUnsigned());
12581 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12582 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12583 RhsConstant)) {
12584 TautologicalTypeCompare = true;
12585 Cmp = TypeCmp;
12587 }
12588 }
12589
12590 // Don't warn if the non-constant operand actually always evaluates to the
12591 // same value.
12592 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12593 return false;
12594
12595 // Suppress the diagnostic for an in-range comparison if the constant comes
12596 // from a macro or enumerator. We don't want to diagnose
12597 //
12598 // some_long_value <= INT_MAX
12599 //
12600 // when sizeof(int) == sizeof(long).
12601 bool InRange = Cmp & PromotedRange::InRangeFlag;
12602 if (InRange && IsEnumConstOrFromMacro(S, Constant))
12603 return false;
12604
12605 // A comparison of an unsigned bit-field against 0 is really a type problem,
12606 // even though at the type level the bit-field might promote to 'signed int'.
12607 if (Other->refersToBitField() && InRange && Value == 0 &&
12608 Other->getType()->isUnsignedIntegerOrEnumerationType())
12609 TautologicalTypeCompare = true;
12610
12611 // If this is a comparison to an enum constant, include that
12612 // constant in the diagnostic.
12613 const EnumConstantDecl *ED = nullptr;
12614 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
12615 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12616
12617 // Should be enough for uint128 (39 decimal digits)
12618 SmallString<64> PrettySourceValue;
12619 llvm::raw_svector_ostream OS(PrettySourceValue);
12620 if (ED) {
12621 OS << '\'' << *ED << "' (" << Value << ")";
12622 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12623 Constant->IgnoreParenImpCasts())) {
12624 OS << (BL->getValue() ? "YES" : "NO");
12625 } else {
12626 OS << Value;
12627 }
12628
12629 if (!TautologicalTypeCompare) {
12630 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12631 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12632 << E->getOpcodeStr() << OS.str() << *Result
12633 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12634 return true;
12635 }
12636
12637 if (IsObjCSignedCharBool) {
12639 S.PDiag(diag::warn_tautological_compare_objc_bool)
12640 << OS.str() << *Result);
12641 return true;
12642 }
12643
12644 // FIXME: We use a somewhat different formatting for the in-range cases and
12645 // cases involving boolean values for historical reasons. We should pick a
12646 // consistent way of presenting these diagnostics.
12647 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12648
12650 E->getOperatorLoc(), E,
12651 S.PDiag(!InRange ? diag::warn_out_of_range_compare
12652 : diag::warn_tautological_bool_compare)
12653 << OS.str() << classifyConstantValue(Constant) << OtherT
12654 << OtherIsBooleanDespiteType << *Result
12655 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12656 } else {
12657 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12658 unsigned Diag =
12659 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12660 ? (HasEnumType(OriginalOther)
12661 ? diag::warn_unsigned_enum_always_true_comparison
12662 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12663 : diag::warn_unsigned_always_true_comparison)
12664 : diag::warn_tautological_constant_compare;
12665
12666 S.Diag(E->getOperatorLoc(), Diag)
12667 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12668 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12669 }
12670
12671 return true;
12672}
12673
12674/// Analyze the operands of the given comparison. Implements the
12675/// fallback case from AnalyzeComparison.
12680
12681/// Implements -Wsign-compare.
12682///
12683/// \param E the binary operator to check for warnings
12685 // The type the comparison is being performed in.
12686 QualType T = E->getLHS()->getType();
12687
12688 // Only analyze comparison operators where both sides have been converted to
12689 // the same type.
12691 return AnalyzeImpConvsInComparison(S, E);
12692
12693 // Don't analyze value-dependent comparisons directly.
12694 if (E->isValueDependent())
12695 return AnalyzeImpConvsInComparison(S, E);
12696
12697 Expr *LHS = E->getLHS();
12698 Expr *RHS = E->getRHS();
12699
12700 if (T->isIntegralType(S.Context)) {
12701 std::optional<llvm::APSInt> RHSValue =
12703 std::optional<llvm::APSInt> LHSValue =
12705
12706 // We don't care about expressions whose result is a constant.
12707 if (RHSValue && LHSValue)
12708 return AnalyzeImpConvsInComparison(S, E);
12709
12710 // We only care about expressions where just one side is literal
12711 if ((bool)RHSValue ^ (bool)LHSValue) {
12712 // Is the constant on the RHS or LHS?
12713 const bool RhsConstant = (bool)RHSValue;
12714 Expr *Const = RhsConstant ? RHS : LHS;
12715 Expr *Other = RhsConstant ? LHS : RHS;
12716 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12717
12718 // Check whether an integer constant comparison results in a value
12719 // of 'true' or 'false'.
12720 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12721 return AnalyzeImpConvsInComparison(S, E);
12722 }
12723 }
12724
12725 if (!T->hasUnsignedIntegerRepresentation()) {
12726 // We don't do anything special if this isn't an unsigned integral
12727 // comparison: we're only interested in integral comparisons, and
12728 // signed comparisons only happen in cases we don't care to warn about.
12729 return AnalyzeImpConvsInComparison(S, E);
12730 }
12731
12732 LHS = LHS->IgnoreParenImpCasts();
12733 RHS = RHS->IgnoreParenImpCasts();
12734
12735 if (!S.getLangOpts().CPlusPlus) {
12736 // Avoid warning about comparison of integers with different signs when
12737 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12738 // the type of `E`.
12739 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12740 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12741 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12742 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12743 }
12744
12745 // Check to see if one of the (unmodified) operands is of different
12746 // signedness.
12747 Expr *signedOperand, *unsignedOperand;
12749 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12750 "unsigned comparison between two signed integer expressions?");
12751 signedOperand = LHS;
12752 unsignedOperand = RHS;
12753 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12754 signedOperand = RHS;
12755 unsignedOperand = LHS;
12756 } else {
12757 return AnalyzeImpConvsInComparison(S, E);
12758 }
12759
12760 // Otherwise, calculate the effective range of the signed operand.
12761 std::optional<IntRange> signedRange =
12763 /*Approximate=*/true);
12764 if (!signedRange)
12765 return;
12766
12767 // Go ahead and analyze implicit conversions in the operands. Note
12768 // that we skip the implicit conversions on both sides.
12771
12772 // If the signed range is non-negative, -Wsign-compare won't fire.
12773 if (signedRange->NonNegative)
12774 return;
12775
12776 // For (in)equality comparisons, if the unsigned operand is a
12777 // constant which cannot collide with a overflowed signed operand,
12778 // then reinterpreting the signed operand as unsigned will not
12779 // change the result of the comparison.
12780 if (E->isEqualityOp()) {
12781 unsigned comparisonWidth = S.Context.getIntWidth(T);
12782 std::optional<IntRange> unsignedRange = TryGetExprRange(
12783 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12784 /*Approximate=*/true);
12785 if (!unsignedRange)
12786 return;
12787
12788 // We should never be unable to prove that the unsigned operand is
12789 // non-negative.
12790 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12791
12792 if (unsignedRange->Width < comparisonWidth)
12793 return;
12794 }
12795
12797 S.PDiag(diag::warn_mixed_sign_comparison)
12798 << LHS->getType() << RHS->getType()
12799 << LHS->getSourceRange() << RHS->getSourceRange());
12800}
12801
12802/// Analyzes an attempt to assign the given value to a bitfield.
12803///
12804/// Returns true if there was something fishy about the attempt.
12806 SourceLocation InitLoc) {
12807 assert(Bitfield->isBitField());
12808 if (Bitfield->isInvalidDecl())
12809 return false;
12810
12811 // White-list bool bitfields.
12812 QualType BitfieldType = Bitfield->getType();
12813 if (BitfieldType->isBooleanType())
12814 return false;
12815
12816 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12817 // If the underlying enum type was not explicitly specified as an unsigned
12818 // type and the enum contain only positive values, MSVC++ will cause an
12819 // inconsistency by storing this as a signed type.
12820 if (S.getLangOpts().CPlusPlus11 &&
12821 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12822 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12823 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12824 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12825 << BitfieldEnumDecl;
12826 }
12827 }
12828
12829 // Ignore value- or type-dependent expressions.
12830 if (Bitfield->getBitWidth()->isValueDependent() ||
12831 Bitfield->getBitWidth()->isTypeDependent() ||
12832 Init->isValueDependent() ||
12833 Init->isTypeDependent())
12834 return false;
12835
12836 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12837 unsigned FieldWidth = Bitfield->getBitWidthValue();
12838
12840 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12842 // The RHS is not constant. If the RHS has an enum type, make sure the
12843 // bitfield is wide enough to hold all the values of the enum without
12844 // truncation.
12845 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12846 const PreferredTypeAttr *PTAttr = nullptr;
12847 if (!ED) {
12848 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12849 if (PTAttr)
12850 ED = PTAttr->getType()->getAsEnumDecl();
12851 }
12852 if (ED) {
12853 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12854
12855 // Enum types are implicitly signed on Windows, so check if there are any
12856 // negative enumerators to see if the enum was intended to be signed or
12857 // not.
12858 bool SignedEnum = ED->getNumNegativeBits() > 0;
12859
12860 // Check for surprising sign changes when assigning enum values to a
12861 // bitfield of different signedness. If the bitfield is signed and we
12862 // have exactly the right number of bits to store this unsigned enum,
12863 // suggest changing the enum to an unsigned type. This typically happens
12864 // on Windows where unfixed enums always use an underlying type of 'int'.
12865 unsigned DiagID = 0;
12866 if (SignedEnum && !SignedBitfield) {
12867 DiagID =
12868 PTAttr == nullptr
12869 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12870 : diag::
12871 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12872 } else if (SignedBitfield && !SignedEnum &&
12873 ED->getNumPositiveBits() == FieldWidth) {
12874 DiagID =
12875 PTAttr == nullptr
12876 ? diag::warn_signed_bitfield_enum_conversion
12877 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12878 }
12879 if (DiagID) {
12880 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12881 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12882 SourceRange TypeRange =
12883 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12884 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12885 << SignedEnum << TypeRange;
12886 if (PTAttr)
12887 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12888 << ED;
12889 }
12890
12891 // Compute the required bitwidth. If the enum has negative values, we need
12892 // one more bit than the normal number of positive bits to represent the
12893 // sign bit.
12894 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12895 ED->getNumNegativeBits())
12896 : ED->getNumPositiveBits();
12897
12898 // Check the bitwidth.
12899 if (BitsNeeded > FieldWidth) {
12900 Expr *WidthExpr = Bitfield->getBitWidth();
12901 auto DiagID =
12902 PTAttr == nullptr
12903 ? diag::warn_bitfield_too_small_for_enum
12904 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12905 S.Diag(InitLoc, DiagID) << Bitfield << ED;
12906 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12907 << BitsNeeded << ED << WidthExpr->getSourceRange();
12908 if (PTAttr)
12909 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
12910 << ED;
12911 }
12912 }
12913
12914 return false;
12915 }
12916
12917 llvm::APSInt Value = Result.Val.getInt();
12918
12919 unsigned OriginalWidth = Value.getBitWidth();
12920
12921 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12922 // false positives where the user is demonstrating they intend to use the
12923 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12924 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12925 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12926 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12927 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12928 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
12929 S.findMacroSpelling(MaybeMacroLoc, "true"))
12930 return false;
12931 }
12932
12933 if (!Value.isSigned() || Value.isNegative())
12934 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12935 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12936 OriginalWidth = Value.getSignificantBits();
12937
12938 if (OriginalWidth <= FieldWidth)
12939 return false;
12940
12941 // Compute the value which the bitfield will contain.
12942 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12943 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12944
12945 // Check whether the stored value is equal to the original value.
12946 TruncatedValue = TruncatedValue.extend(OriginalWidth);
12947 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12948 return false;
12949
12950 std::string PrettyValue = toString(Value, 10);
12951 std::string PrettyTrunc = toString(TruncatedValue, 10);
12952
12953 S.Diag(InitLoc, OneAssignedToOneBitBitfield
12954 ? diag::warn_impcast_single_bit_bitield_precision_constant
12955 : diag::warn_impcast_bitfield_precision_constant)
12956 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12957 << Init->getSourceRange();
12958
12959 return true;
12960}
12961
12962/// Analyze the given simple or compound assignment for warning-worthy
12963/// operations.
12965 // Just recurse on the LHS.
12967
12968 // We want to recurse on the RHS as normal unless we're assigning to
12969 // a bitfield.
12970 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12971 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12972 E->getOperatorLoc())) {
12973 // Recurse, ignoring any implicit conversions on the RHS.
12975 E->getOperatorLoc());
12976 }
12977 }
12978
12979 // Set context flag for overflow behavior type assignment analysis, use RAII
12980 // pattern to handle nested assignments.
12981 llvm::SaveAndRestore OBTAssignmentContext(
12983
12985
12986 // Diagnose implicitly sequentially-consistent atomic assignment.
12987 if (E->getLHS()->getType()->isAtomicType())
12988 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12989}
12990
12991/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12992static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12993 QualType T, SourceLocation CContext, unsigned diag,
12994 bool PruneControlFlow = false) {
12995 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12996 // address space annotations isn't really useful. The warnings aren't because
12997 // you're converting a `private int` to `unsigned int`, it is because you're
12998 // conerting `int` to `unsigned int`.
12999 if (SourceType.hasAddressSpace())
13000 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
13001 if (T.hasAddressSpace())
13003 if (PruneControlFlow) {
13005 S.PDiag(diag)
13006 << SourceType << T << E->getSourceRange()
13007 << SourceRange(CContext));
13008 return;
13009 }
13010 S.Diag(E->getExprLoc(), diag)
13011 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
13012}
13013
13014/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13015static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
13016 SourceLocation CContext, unsigned diag,
13017 bool PruneControlFlow = false) {
13018 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
13019}
13020
13021/// Diagnose an implicit cast from a floating point value to an integer value.
13022static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
13023 SourceLocation CContext) {
13024 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
13025 bool PruneWarnings = S.inTemplateInstantiation();
13026
13027 const Expr *InnerE = E->IgnoreParenImpCasts();
13028 // We also want to warn on, e.g., "int i = -1.234"
13029 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
13030 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
13031 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
13032
13033 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
13034
13035 llvm::APFloat Value(0.0);
13036 bool IsConstant =
13038 if (!IsConstant) {
13039 if (S.ObjC().isSignedCharBool(T)) {
13041 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
13042 << E->getType());
13043 }
13044
13045 return DiagnoseImpCast(S, E, T, CContext,
13046 diag::warn_impcast_float_integer, PruneWarnings);
13047 }
13048
13049 bool isExact = false;
13050
13051 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
13052 T->hasUnsignedIntegerRepresentation());
13053 llvm::APFloat::opStatus Result = Value.convertToInteger(
13054 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
13055
13056 // FIXME: Force the precision of the source value down so we don't print
13057 // digits which are usually useless (we don't really care here if we
13058 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
13059 // would automatically print the shortest representation, but it's a bit
13060 // tricky to implement.
13061 SmallString<16> PrettySourceValue;
13062 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
13063 precision = (precision * 59 + 195) / 196;
13064 Value.toString(PrettySourceValue, precision);
13065
13066 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
13068 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
13069 << PrettySourceValue);
13070 }
13071
13072 if (Result == llvm::APFloat::opOK && isExact) {
13073 if (IsLiteral) return;
13074 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
13075 PruneWarnings);
13076 }
13077
13078 // Conversion of a floating-point value to a non-bool integer where the
13079 // integral part cannot be represented by the integer type is undefined.
13080 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
13081 return DiagnoseImpCast(
13082 S, E, T, CContext,
13083 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13084 : diag::warn_impcast_float_to_integer_out_of_range,
13085 PruneWarnings);
13086
13087 unsigned DiagID = 0;
13088 if (IsLiteral) {
13089 // Warn on floating point literal to integer.
13090 DiagID = diag::warn_impcast_literal_float_to_integer;
13091 } else if (IntegerValue == 0) {
13092 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
13093 return DiagnoseImpCast(S, E, T, CContext,
13094 diag::warn_impcast_float_integer, PruneWarnings);
13095 }
13096 // Warn on non-zero to zero conversion.
13097 DiagID = diag::warn_impcast_float_to_integer_zero;
13098 } else {
13099 if (IntegerValue.isUnsigned()) {
13100 if (!IntegerValue.isMaxValue()) {
13101 return DiagnoseImpCast(S, E, T, CContext,
13102 diag::warn_impcast_float_integer, PruneWarnings);
13103 }
13104 } else { // IntegerValue.isSigned()
13105 if (!IntegerValue.isMaxSignedValue() &&
13106 !IntegerValue.isMinSignedValue()) {
13107 return DiagnoseImpCast(S, E, T, CContext,
13108 diag::warn_impcast_float_integer, PruneWarnings);
13109 }
13110 }
13111 // Warn on evaluatable floating point expression to integer conversion.
13112 DiagID = diag::warn_impcast_float_to_integer;
13113 }
13114
13115 SmallString<16> PrettyTargetValue;
13116 if (IsBool)
13117 PrettyTargetValue = Value.isZero() ? "false" : "true";
13118 else
13119 IntegerValue.toString(PrettyTargetValue);
13120
13121 if (PruneWarnings) {
13123 S.PDiag(DiagID)
13124 << E->getType() << T.getUnqualifiedType()
13125 << PrettySourceValue << PrettyTargetValue
13126 << E->getSourceRange() << SourceRange(CContext));
13127 } else {
13128 S.Diag(E->getExprLoc(), DiagID)
13129 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
13130 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
13131 }
13132}
13133
13134/// Analyze the given compound assignment for the possible losing of
13135/// floating-point precision.
13137 assert(isa<CompoundAssignOperator>(E) &&
13138 "Must be compound assignment operation");
13139 // Recurse on the LHS and RHS in here
13142
13143 if (E->getLHS()->getType()->isAtomicType())
13144 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
13145
13146 // Now check the outermost expression
13147 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13148 const auto *RBT = cast<CompoundAssignOperator>(E)
13149 ->getComputationResultType()
13150 ->getAs<BuiltinType>();
13151
13152 // The below checks assume source is floating point.
13153 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13154
13155 // If source is floating point but target is an integer.
13156 if (ResultBT->isInteger())
13157 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
13158 E->getExprLoc(), diag::warn_impcast_float_integer);
13159
13160 if (!ResultBT->isFloatingPoint())
13161 return;
13162
13163 // If both source and target are floating points, warn about losing precision.
13165 QualType(ResultBT, 0), QualType(RBT, 0));
13166 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
13167 // warn about dropping FP rank.
13168 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
13169 diag::warn_impcast_float_result_precision);
13170}
13171
13172static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13173 IntRange Range) {
13174 if (!Range.Width) return "0";
13175
13176 llvm::APSInt ValueInRange = Value;
13177 ValueInRange.setIsSigned(!Range.NonNegative);
13178 ValueInRange = ValueInRange.trunc(Range.Width);
13179 return toString(ValueInRange, 10);
13180}
13181
13182static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
13183 bool ToBool) {
13184 if (!isa<ImplicitCastExpr>(Ex))
13185 return false;
13186
13187 const Expr *InnerE = Ex->IgnoreParenImpCasts();
13189 const Type *Source =
13191 if (Target->isDependentType())
13192 return false;
13193
13194 const auto *FloatCandidateBT =
13195 dyn_cast<BuiltinType>(ToBool ? Source : Target);
13196 const Type *BoolCandidateType = ToBool ? Target : Source;
13197
13198 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
13199 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13200}
13201
13202static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
13203 SourceLocation CC) {
13204 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
13205 const Expr *CurrA = TheCall->getArg(I);
13206 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
13207 continue;
13208
13209 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
13210 S, TheCall->getArg(I - 1), false));
13211 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
13212 S, TheCall->getArg(I + 1), false));
13213 if (IsSwapped) {
13214 // Warn on this floating-point to bool conversion.
13216 CurrA->getType(), CC,
13217 diag::warn_impcast_floating_point_to_bool);
13218 }
13219 }
13220}
13221
13223 SourceLocation CC) {
13224 // Don't warn on functions which have return type nullptr_t.
13225 if (isa<CallExpr>(E))
13226 return;
13227
13228 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13229 const Expr *NewE = E->IgnoreParenImpCasts();
13230 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
13231 bool HasNullPtrType = NewE->getType()->isNullPtrType();
13232 if (!IsGNUNullExpr && !HasNullPtrType)
13233 return;
13234
13235 // Return if target type is a safe conversion.
13236 if (T->isAnyPointerType() || T->isBlockPointerType() ||
13237 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13238 return;
13239
13240 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
13241 E->getExprLoc()))
13242 return;
13243
13245
13246 // Venture through the macro stacks to get to the source of macro arguments.
13247 // The new location is a better location than the complete location that was
13248 // passed in.
13249 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13251
13252 // __null is usually wrapped in a macro. Go up a macro if that is the case.
13253 if (IsGNUNullExpr && Loc.isMacroID()) {
13254 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13255 Loc, S.SourceMgr, S.getLangOpts());
13256 if (MacroName == "NULL")
13258 }
13259
13260 // Only warn if the null and context location are in the same macro expansion.
13261 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
13262 return;
13263
13264 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
13265 << HasNullPtrType << T << SourceRange(CC)
13268}
13269
13270// Helper function to filter out cases for constant width constant conversion.
13271// Don't warn on char array initialization or for non-decimal values.
13273 SourceLocation CC) {
13274 // If initializing from a constant, and the constant starts with '0',
13275 // then it is a binary, octal, or hexadecimal. Allow these constants
13276 // to fill all the bits, even if there is a sign change.
13277 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13278 const char FirstLiteralCharacter =
13279 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13280 if (FirstLiteralCharacter == '0')
13281 return false;
13282 }
13283
13284 // If the CC location points to a '{', and the type is char, then assume
13285 // assume it is an array initialization.
13286 if (CC.isValid() && T->isCharType()) {
13287 const char FirstContextCharacter =
13289 if (FirstContextCharacter == '{')
13290 return false;
13291 }
13292
13293 return true;
13294}
13295
13297 const auto *IL = dyn_cast<IntegerLiteral>(E);
13298 if (!IL) {
13299 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13300 if (UO->getOpcode() == UO_Minus)
13301 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13302 }
13303 }
13304
13305 return IL;
13306}
13307
13309 E = E->IgnoreParenImpCasts();
13310 SourceLocation ExprLoc = E->getExprLoc();
13311
13312 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13313 BinaryOperator::Opcode Opc = BO->getOpcode();
13315 // Do not diagnose unsigned shifts.
13316 if (Opc == BO_Shl) {
13317 const auto *LHS = getIntegerLiteral(BO->getLHS());
13318 const auto *RHS = getIntegerLiteral(BO->getRHS());
13319 if (LHS && LHS->getValue() == 0)
13320 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13321 else if (!E->isValueDependent() && LHS && RHS &&
13322 RHS->getValue().isNonNegative() &&
13324 S.Diag(ExprLoc, diag::warn_left_shift_always)
13325 << (Result.Val.getInt() != 0);
13326 else if (E->getType()->isSignedIntegerType())
13327 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
13330 ") != 0");
13331 }
13332 }
13333
13334 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13335 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13336 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13337 if (!LHS || !RHS)
13338 return;
13339 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13340 (RHS->getValue() == 0 || RHS->getValue() == 1))
13341 // Do not diagnose common idioms.
13342 return;
13343 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13344 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13345 }
13346}
13347
13349 const Type *Target, Expr *E,
13350 QualType T,
13351 SourceLocation CC) {
13352 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13353 Source != Target);
13354
13355 // Lone surrogates have a distinct representation in UTF-32.
13356 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13357 // so don't warn on such conversion.
13358 if (Source->isChar16Type() && Target->isChar32Type())
13359 return;
13360
13364 llvm::APSInt Value(32);
13365 Value = Result.Val.getInt();
13366 bool IsASCII = Value <= 0x7F;
13367 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13368 bool ConversionPreservesSemantics =
13369 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13370
13371 if (!ConversionPreservesSemantics) {
13372 auto IsSingleCodeUnitCP = [](const QualType &T,
13373 const llvm::APSInt &Value) {
13374 if (T->isChar8Type())
13375 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13376 if (T->isChar16Type())
13377 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13378 assert(T->isChar32Type());
13379 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13380 };
13381
13382 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
13383 << E->getType() << T
13384 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13385 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
13386 }
13387 } else {
13388 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
13390 DiagnoseImpCast(S, E, T, CC,
13391 LosesPrecision ? diag::warn_impcast_unicode_precision
13392 : diag::warn_impcast_unicode_char_type);
13393 }
13394}
13395
13397 From = Context.getCanonicalType(From);
13398 To = Context.getCanonicalType(To);
13399 QualType MaybePointee = From->getPointeeType();
13400 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13401 From = MaybePointee;
13402 MaybePointee = To->getPointeeType();
13403 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13404 To = MaybePointee;
13405
13406 if (const auto *FromFn = From->getAs<FunctionType>()) {
13407 if (const auto *ToFn = To->getAs<FunctionType>()) {
13408 if (FromFn->getCFIUncheckedCalleeAttr() &&
13409 !ToFn->getCFIUncheckedCalleeAttr())
13410 return true;
13411 }
13412 }
13413 return false;
13414}
13415
13417 bool *ICContext, bool IsListInit) {
13418 if (E->isTypeDependent() || E->isValueDependent()) return;
13419
13420 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
13421 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13422 if (Source == Target) return;
13423 if (Target->isDependentType()) return;
13424
13425 // If the conversion context location is invalid don't complain. We also
13426 // don't want to emit a warning if the issue occurs from the expansion of
13427 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13428 // delay this check as long as possible. Once we detect we are in that
13429 // scenario, we just return.
13430 if (CC.isInvalid())
13431 return;
13432
13433 if (Source->isAtomicType())
13434 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13435
13436 // Diagnose implicit casts to bool.
13437 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13438 if (isa<StringLiteral>(E))
13439 // Warn on string literal to bool. Checks for string literals in logical
13440 // and expressions, for instance, assert(0 && "error here"), are
13441 // prevented by a check in AnalyzeImplicitConversions().
13442 return DiagnoseImpCast(*this, E, T, CC,
13443 diag::warn_impcast_string_literal_to_bool);
13446 // This covers the literal expressions that evaluate to Objective-C
13447 // objects.
13448 return DiagnoseImpCast(*this, E, T, CC,
13449 diag::warn_impcast_objective_c_literal_to_bool);
13450 }
13451 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13452 // Warn on pointer to bool conversion that is always true.
13454 SourceRange(CC));
13455 }
13456 }
13457
13459
13460 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13461 // is a typedef for signed char (macOS), then that constant value has to be 1
13462 // or 0.
13463 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
13466 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13468 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13469 << toString(Result.Val.getInt(), 10));
13470 }
13471 return;
13472 }
13473 }
13474
13475 // Check implicit casts from Objective-C collection literals to specialized
13476 // collection types, e.g., NSArray<NSString *> *.
13477 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13478 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
13479 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13480 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
13481
13482 // Strip complex types.
13483 if (isa<ComplexType>(Source)) {
13484 if (!isa<ComplexType>(Target)) {
13485 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13486 return;
13487
13488 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13489 return DiagnoseImpCast(*this, E, T, CC,
13490 diag::err_impcast_incompatible_type);
13491 }
13492
13493 return DiagnoseImpCast(*this, E, T, CC,
13495 ? diag::err_impcast_complex_scalar
13496 : diag::warn_impcast_complex_scalar);
13497 }
13498
13499 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13500 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13501 }
13502
13503 // Strip vector types.
13504 if (isa<VectorType>(Source)) {
13505 if (Target->isSveVLSBuiltinType() &&
13506 (ARM().areCompatibleSveTypes(QualType(Target, 0),
13507 QualType(Source, 0)) ||
13508 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
13509 QualType(Source, 0))))
13510 return;
13511
13512 if (Target->isRVVVLSBuiltinType() &&
13513 (Context.areCompatibleRVVTypes(QualType(Target, 0),
13514 QualType(Source, 0)) ||
13515 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
13516 QualType(Source, 0))))
13517 return;
13518
13519 if (!isa<VectorType>(Target)) {
13520 if (SourceMgr.isInSystemMacro(CC))
13521 return;
13522 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
13523 }
13524 if (getLangOpts().HLSL &&
13525 Target->castAs<VectorType>()->getNumElements() <
13526 Source->castAs<VectorType>()->getNumElements()) {
13527 // Diagnose vector truncation but don't return. We may also want to
13528 // diagnose an element conversion.
13529 DiagnoseImpCast(*this, E, T, CC,
13530 diag::warn_hlsl_impcast_vector_truncation);
13531 }
13532
13533 // If the vector cast is cast between two vectors of the same size, it is
13534 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13535 if (!getLangOpts().HLSL &&
13536 Context.getTypeSize(Source) == Context.getTypeSize(Target))
13537 return;
13538
13539 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13540 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13541 }
13542 if (const auto *VecTy = dyn_cast<VectorType>(Target))
13543 Target = VecTy->getElementType().getTypePtr();
13544
13545 // Strip matrix types.
13546 if (isa<ConstantMatrixType>(Source)) {
13547 if (Target->isScalarType())
13548 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
13549
13552 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13553 // Diagnose Matrix truncation but don't return. We may also want to
13554 // diagnose an element conversion.
13555 DiagnoseImpCast(*this, E, T, CC,
13556 diag::warn_hlsl_impcast_matrix_truncation);
13557 }
13558
13559 Source = cast<ConstantMatrixType>(Source)->getElementType().getTypePtr();
13560 Target = cast<ConstantMatrixType>(Target)->getElementType().getTypePtr();
13561 }
13562 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Target))
13563 Target = MatTy->getElementType().getTypePtr();
13564
13565 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13566 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13567
13568 // Strip SVE vector types
13569 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13570 // Need the original target type for vector type checks
13571 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13572 // Handle conversion from scalable to fixed when msve-vector-bits is
13573 // specified
13574 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
13575 QualType(Source, 0)) ||
13576 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
13577 QualType(Source, 0)))
13578 return;
13579
13580 // If the vector cast is cast between two vectors of the same size, it is
13581 // a bitcast, not a conversion.
13582 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
13583 return;
13584
13585 Source = SourceBT->getSveEltType(Context).getTypePtr();
13586 }
13587
13588 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13589 Target = TargetBT->getSveEltType(Context).getTypePtr();
13590
13591 // If the source is floating point...
13592 if (SourceBT && SourceBT->isFloatingPoint()) {
13593 // ...and the target is floating point...
13594 if (TargetBT && TargetBT->isFloatingPoint()) {
13595 // ...then warn if we're dropping FP rank.
13596
13598 QualType(SourceBT, 0), QualType(TargetBT, 0));
13599 if (Order > 0) {
13600 // Don't warn about float constants that are precisely
13601 // representable in the target type.
13602 Expr::EvalResult result;
13603 if (E->EvaluateAsRValue(result, Context)) {
13604 // Value might be a float, a float vector, or a float complex.
13606 result.Val,
13607 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13608 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13609 return;
13610 }
13611
13612 if (SourceMgr.isInSystemMacro(CC))
13613 return;
13614
13615 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
13616 }
13617 // ... or possibly if we're increasing rank, too
13618 else if (Order < 0) {
13619 if (SourceMgr.isInSystemMacro(CC))
13620 return;
13621
13622 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
13623 }
13624 return;
13625 }
13626
13627 // If the target is integral, always warn.
13628 if (TargetBT && TargetBT->isInteger()) {
13629 if (SourceMgr.isInSystemMacro(CC))
13630 return;
13631
13632 DiagnoseFloatingImpCast(*this, E, T, CC);
13633 }
13634
13635 // Detect the case where a call result is converted from floating-point to
13636 // to bool, and the final argument to the call is converted from bool, to
13637 // discover this typo:
13638 //
13639 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13640 //
13641 // FIXME: This is an incredibly special case; is there some more general
13642 // way to detect this class of misplaced-parentheses bug?
13643 if (Target->isBooleanType() && isa<CallExpr>(E)) {
13644 // Check last argument of function call to see if it is an
13645 // implicit cast from a type matching the type the result
13646 // is being cast to.
13647 CallExpr *CEx = cast<CallExpr>(E);
13648 if (unsigned NumArgs = CEx->getNumArgs()) {
13649 Expr *LastA = CEx->getArg(NumArgs - 1);
13650 Expr *InnerE = LastA->IgnoreParenImpCasts();
13651 if (isa<ImplicitCastExpr>(LastA) &&
13652 InnerE->getType()->isBooleanType()) {
13653 // Warn on this floating-point to bool conversion
13654 DiagnoseImpCast(*this, E, T, CC,
13655 diag::warn_impcast_floating_point_to_bool);
13656 }
13657 }
13658 }
13659 return;
13660 }
13661
13662 // Valid casts involving fixed point types should be accounted for here.
13663 if (Source->isFixedPointType()) {
13664 if (Target->isUnsaturatedFixedPointType()) {
13668 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13669 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
13670 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
13671 if (Value > MaxVal || Value < MinVal) {
13673 PDiag(diag::warn_impcast_fixed_point_range)
13674 << Value.toString() << T
13675 << E->getSourceRange()
13676 << clang::SourceRange(CC));
13677 return;
13678 }
13679 }
13680 } else if (Target->isIntegerType()) {
13684 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13685
13686 bool Overflowed;
13687 llvm::APSInt IntResult = FXResult.convertToInt(
13688 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
13689 &Overflowed);
13690
13691 if (Overflowed) {
13693 PDiag(diag::warn_impcast_fixed_point_range)
13694 << FXResult.toString() << T
13695 << E->getSourceRange()
13696 << clang::SourceRange(CC));
13697 return;
13698 }
13699 }
13700 }
13701 } else if (Target->isUnsaturatedFixedPointType()) {
13702 if (Source->isIntegerType()) {
13706 llvm::APSInt Value = Result.Val.getInt();
13707
13708 bool Overflowed;
13709 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13710 Value, Context.getFixedPointSemantics(T), &Overflowed);
13711
13712 if (Overflowed) {
13714 PDiag(diag::warn_impcast_fixed_point_range)
13715 << toString(Value, /*Radix=*/10) << T
13716 << E->getSourceRange()
13717 << clang::SourceRange(CC));
13718 return;
13719 }
13720 }
13721 }
13722 }
13723
13724 // If we are casting an integer type to a floating point type without
13725 // initialization-list syntax, we might lose accuracy if the floating
13726 // point type has a narrower significand than the integer type.
13727 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13728 TargetBT->isFloatingType() && !IsListInit) {
13729 // Determine the number of precision bits in the source integer type.
13730 std::optional<IntRange> SourceRange =
13732 /*Approximate=*/true);
13733 if (!SourceRange)
13734 return;
13735 unsigned int SourcePrecision = SourceRange->Width;
13736
13737 // Determine the number of precision bits in the
13738 // target floating point type.
13739 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13740 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13741
13742 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13743 SourcePrecision > TargetPrecision) {
13744
13745 if (std::optional<llvm::APSInt> SourceInt =
13747 // If the source integer is a constant, convert it to the target
13748 // floating point type. Issue a warning if the value changes
13749 // during the whole conversion.
13750 llvm::APFloat TargetFloatValue(
13751 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13752 llvm::APFloat::opStatus ConversionStatus =
13753 TargetFloatValue.convertFromAPInt(
13754 *SourceInt, SourceBT->isSignedInteger(),
13755 llvm::APFloat::rmNearestTiesToEven);
13756
13757 if (ConversionStatus != llvm::APFloat::opOK) {
13758 SmallString<32> PrettySourceValue;
13759 SourceInt->toString(PrettySourceValue, 10);
13760 SmallString<32> PrettyTargetValue;
13761 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13762
13764 E->getExprLoc(), E,
13765 PDiag(diag::warn_impcast_integer_float_precision_constant)
13766 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13767 << E->getSourceRange() << clang::SourceRange(CC));
13768 }
13769 } else {
13770 // Otherwise, the implicit conversion may lose precision.
13771 DiagnoseImpCast(*this, E, T, CC,
13772 diag::warn_impcast_integer_float_precision);
13773 }
13774 }
13775 }
13776
13777 DiagnoseNullConversion(*this, E, T, CC);
13778
13780
13781 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13782 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
13783 return;
13784 }
13785
13786 if (Target->isBooleanType())
13787 DiagnoseIntInBoolContext(*this, E);
13788
13790 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13791 << QualType(Source, 0) << QualType(Target, 0);
13792 }
13793
13794 if (!Source->isIntegerType() || !Target->isIntegerType())
13795 return;
13796
13797 // TODO: remove this early return once the false positives for constant->bool
13798 // in templates, macros, etc, are reduced or removed.
13799 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13800 return;
13801
13802 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
13803 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13805 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13806 << E->getType());
13807 }
13808 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13809 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
13810 if (!LikelySourceRange)
13811 return;
13812
13813 IntRange SourceTypeRange =
13814 IntRange::forTargetOfCanonicalType(Context, Source);
13815 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
13816
13817 if (LikelySourceRange->Width > TargetRange.Width) {
13818 // Check if target is a wrapping OBT - if so, don't warn about constant
13819 // conversion as this type may be used intentionally with implicit
13820 // truncation, especially during assignments.
13821 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13822 if (TargetOBT->isWrapKind()) {
13823 return;
13824 }
13825 }
13826
13827 // Check if source expression has an explicit __ob_wrap cast because if so,
13828 // wrapping was explicitly requested and we shouldn't warn
13829 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13830 if (SourceOBT->isWrapKind()) {
13831 return;
13832 }
13833 }
13834
13835 // If the source is a constant, use a default-on diagnostic.
13836 // TODO: this should happen for bitfield stores, too.
13840 llvm::APSInt Value(32);
13841 Value = Result.Val.getInt();
13842
13843 if (SourceMgr.isInSystemMacro(CC))
13844 return;
13845
13846 std::string PrettySourceValue = toString(Value, 10);
13847 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13848
13850 PDiag(diag::warn_impcast_integer_precision_constant)
13851 << PrettySourceValue << PrettyTargetValue
13852 << E->getType() << T << E->getSourceRange()
13853 << SourceRange(CC));
13854 return;
13855 }
13856
13857 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13858 if (SourceMgr.isInSystemMacro(CC))
13859 return;
13860
13861 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
13862 if (UO->getOpcode() == UO_Minus)
13863 return DiagnoseImpCast(
13864 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
13865 }
13866
13867 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
13868 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
13869 /* pruneControlFlow */ true);
13870 return DiagnoseImpCast(*this, E, T, CC,
13871 diag::warn_impcast_integer_precision);
13872 }
13873
13874 if (TargetRange.Width > SourceTypeRange.Width) {
13875 if (auto *UO = dyn_cast<UnaryOperator>(E))
13876 if (UO->getOpcode() == UO_Minus)
13877 if (Source->isUnsignedIntegerType()) {
13878 if (Target->isUnsignedIntegerType())
13879 return DiagnoseImpCast(*this, E, T, CC,
13880 diag::warn_impcast_high_order_zero_bits);
13881 if (Target->isSignedIntegerType())
13882 return DiagnoseImpCast(*this, E, T, CC,
13883 diag::warn_impcast_nonnegative_result);
13884 }
13885 }
13886
13887 if (TargetRange.Width == LikelySourceRange->Width &&
13888 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13889 Source->isSignedIntegerType()) {
13890 // Warn when doing a signed to signed conversion, warn if the positive
13891 // source value is exactly the width of the target type, which will
13892 // cause a negative value to be stored.
13893
13896 !SourceMgr.isInSystemMacro(CC)) {
13897 llvm::APSInt Value = Result.Val.getInt();
13898 if (isSameWidthConstantConversion(*this, E, T, CC)) {
13899 std::string PrettySourceValue = toString(Value, 10);
13900 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13901
13902 Diag(E->getExprLoc(),
13903 PDiag(diag::warn_impcast_integer_precision_constant)
13904 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13905 << E->getSourceRange() << SourceRange(CC));
13906 return;
13907 }
13908 }
13909
13910 // Fall through for non-constants to give a sign conversion warning.
13911 }
13912
13913 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
13914 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13915 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13916 LikelySourceRange->Width == TargetRange.Width))) {
13917 if (SourceMgr.isInSystemMacro(CC))
13918 return;
13919
13920 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13921 TargetBT->isInteger() &&
13922 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13923 return;
13924 }
13925
13926 unsigned DiagID = diag::warn_impcast_integer_sign;
13927
13928 // Traditionally, gcc has warned about this under -Wsign-compare.
13929 // We also want to warn about it in -Wconversion.
13930 // So if -Wconversion is off, use a completely identical diagnostic
13931 // in the sign-compare group.
13932 // The conditional-checking code will
13933 if (ICContext) {
13934 DiagID = diag::warn_impcast_integer_sign_conditional;
13935 *ICContext = true;
13936 }
13937
13938 DiagnoseImpCast(*this, E, T, CC, DiagID);
13939 }
13940
13941 // If we're implicitly converting from an integer into an enumeration, that
13942 // is valid in C but invalid in C++.
13943 QualType SourceType = E->getEnumCoercedType(Context);
13944 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13945 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
13946 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
13947
13948 // Diagnose conversions between different enumeration types.
13949 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13950 // type, to give us better diagnostics.
13951 Source = Context.getCanonicalType(SourceType).getTypePtr();
13952
13953 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13954 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13955 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13956 TargetEnum->getDecl()->hasNameForLinkage() &&
13957 SourceEnum != TargetEnum) {
13958 if (SourceMgr.isInSystemMacro(CC))
13959 return;
13960
13961 return DiagnoseImpCast(*this, E, SourceType, T, CC,
13962 diag::warn_impcast_different_enum_types);
13963 }
13964}
13965
13968
13970 SourceLocation CC, bool &ICContext) {
13971 E = E->IgnoreParenImpCasts();
13972 // Diagnose incomplete type for second or third operand in C.
13973 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13974 S.RequireCompleteExprType(E, diag::err_incomplete_type);
13975
13976 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13977 return CheckConditionalOperator(S, CO, CC, T);
13978
13980 if (E->getType() != T)
13981 return S.CheckImplicitConversion(E, T, CC, &ICContext);
13982}
13983
13987
13988 Expr *TrueExpr = E->getTrueExpr();
13989 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13990 TrueExpr = BCO->getCommon();
13991
13992 bool Suspicious = false;
13993 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13994 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13995
13996 if (T->isBooleanType())
13998
13999 // If -Wconversion would have warned about either of the candidates
14000 // for a signedness conversion to the context type...
14001 if (!Suspicious) return;
14002
14003 // ...but it's currently ignored...
14004 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
14005 return;
14006
14007 // ...then check whether it would have warned about either of the
14008 // candidates for a signedness conversion to the condition type.
14009 if (E->getType() == T) return;
14010
14011 Suspicious = false;
14012 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
14013 &Suspicious);
14014 if (!Suspicious)
14016 E->getType(), CC, &Suspicious);
14017}
14018
14019/// Check conversion of given expression to boolean.
14020/// Input argument E is a logical expression.
14022 // Run the bool-like conversion checks only for C since there bools are
14023 // still not used as the return type from "boolean" operators or as the input
14024 // type for conditional operators.
14025 if (S.getLangOpts().CPlusPlus)
14026 return;
14028 return;
14030}
14031
14032namespace {
14033struct AnalyzeImplicitConversionsWorkItem {
14034 Expr *E;
14035 SourceLocation CC;
14036 bool IsListInit;
14037};
14038}
14039
14041 Sema &S, Expr *E, QualType T, SourceLocation CC,
14042 bool ExtraCheckForImplicitConversion,
14044 E = E->IgnoreParenImpCasts();
14045 WorkList.push_back({E, CC, false});
14046
14047 if (ExtraCheckForImplicitConversion && E->getType() != T)
14048 S.CheckImplicitConversion(E, T, CC);
14049}
14050
14051/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
14052/// that should be visited are added to WorkList.
14054 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
14056 Expr *OrigE = Item.E;
14057 SourceLocation CC = Item.CC;
14058
14059 QualType T = OrigE->getType();
14060 Expr *E = OrigE->IgnoreParenImpCasts();
14061
14062 // Propagate whether we are in a C++ list initialization expression.
14063 // If so, we do not issue warnings for implicit int-float conversion
14064 // precision loss, because C++11 narrowing already handles it.
14065 //
14066 // HLSL's initialization lists are special, so they shouldn't observe the C++
14067 // behavior here.
14068 bool IsListInit =
14069 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
14070 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
14071
14072 if (E->isTypeDependent() || E->isValueDependent())
14073 return;
14074
14075 Expr *SourceExpr = E;
14076 // Examine, but don't traverse into the source expression of an
14077 // OpaqueValueExpr, since it may have multiple parents and we don't want to
14078 // emit duplicate diagnostics. Its fine to examine the form or attempt to
14079 // evaluate it in the context of checking the specific conversion to T though.
14080 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
14081 if (auto *Src = OVE->getSourceExpr())
14082 SourceExpr = Src;
14083
14084 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
14085 if (UO->getOpcode() == UO_Not &&
14086 UO->getSubExpr()->isKnownToHaveBooleanValue())
14087 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
14088 << OrigE->getSourceRange() << T->isBooleanType()
14089 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
14090
14091 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
14092 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14093 BO->getLHS()->isKnownToHaveBooleanValue() &&
14094 BO->getRHS()->isKnownToHaveBooleanValue() &&
14095 BO->getLHS()->HasSideEffects(S.Context) &&
14096 BO->getRHS()->HasSideEffects(S.Context)) {
14098 const LangOptions &LO = S.getLangOpts();
14099 SourceLocation BLoc = BO->getOperatorLoc();
14100 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
14101 StringRef SR = clang::Lexer::getSourceText(
14102 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
14103 // To reduce false positives, only issue the diagnostic if the operator
14104 // is explicitly spelled as a punctuator. This suppresses the diagnostic
14105 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
14106 // in C, along with other macro spellings the user might invent.
14107 if (SR.str() == "&" || SR.str() == "|") {
14108
14109 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
14110 << (BO->getOpcode() == BO_And ? "&" : "|")
14111 << OrigE->getSourceRange()
14113 BO->getOperatorLoc(),
14114 (BO->getOpcode() == BO_And ? "&&" : "||"));
14115 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
14116 }
14117 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
14118 /// Analyze the given comma operator. The basic idea behind the analysis
14119 /// is to analyze the left and right operands slightly differently. The
14120 /// left operand needs to check whether the operand itself has an implicit
14121 /// conversion, but not whether the left operand induces an implicit
14122 /// conversion for the entire comma expression itself. This is similar to
14123 /// how CheckConditionalOperand behaves; it's as-if the correct operand
14124 /// were directly used for the implicit conversion check.
14125 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
14126 /*ExtraCheckForImplicitConversion=*/false, WorkList);
14127 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
14128 /*ExtraCheckForImplicitConversion=*/true, WorkList);
14129 return;
14130 }
14131 }
14132
14133 // For conditional operators, we analyze the arguments as if they
14134 // were being fed directly into the output.
14135 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
14136 CheckConditionalOperator(S, CO, CC, T);
14137 return;
14138 }
14139
14140 // Check implicit argument conversions for function calls.
14141 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
14143
14144 // Go ahead and check any implicit conversions we might have skipped.
14145 // The non-canonical typecheck is just an optimization;
14146 // CheckImplicitConversion will filter out dead implicit conversions.
14147 if (SourceExpr->getType() != T)
14148 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
14149
14150 // Now continue drilling into this expression.
14151
14152 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
14153 // The bound subexpressions in a PseudoObjectExpr are not reachable
14154 // as transitive children.
14155 // FIXME: Use a more uniform representation for this.
14156 for (auto *SE : POE->semantics())
14157 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
14158 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
14159 }
14160
14161 // Skip past explicit casts.
14162 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
14163 E = CE->getSubExpr();
14164 // In the special case of a C++ function-style cast with braces,
14165 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
14166 // initializer. This InitListExpr basically belongs to the cast itself, so
14167 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
14169 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
14170 if (InitListE->getNumInits() == 1) {
14171 E = InitListE->getInit(0);
14172 }
14173 }
14174 }
14175 E = E->IgnoreParenImpCasts();
14176 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14177 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
14178 WorkList.push_back({E, CC, IsListInit});
14179 return;
14180 }
14181
14182 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
14183 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
14184 // The base expression is only used to initialize the parameter for
14185 // arguments to `inout` parameters, so we only traverse down the base
14186 // expression for `inout` cases.
14187 if (OutArgE->isInOut())
14188 WorkList.push_back(
14189 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
14190 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
14191 return;
14192 }
14193
14194 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14195 // Do a somewhat different check with comparison operators.
14196 if (BO->isComparisonOp())
14197 return AnalyzeComparison(S, BO);
14198
14199 // And with simple assignments.
14200 if (BO->getOpcode() == BO_Assign)
14201 return AnalyzeAssignment(S, BO);
14202 // And with compound assignments.
14203 if (BO->isAssignmentOp())
14204 return AnalyzeCompoundAssignment(S, BO);
14205 }
14206
14207 // These break the otherwise-useful invariant below. Fortunately,
14208 // we don't really need to recurse into them, because any internal
14209 // expressions should have been analyzed already when they were
14210 // built into statements.
14211 if (isa<StmtExpr>(E)) return;
14212
14213 // Don't descend into unevaluated contexts.
14214 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
14215
14216 // Now just recurse over the expression's children.
14217 CC = E->getExprLoc();
14218 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
14219 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14220 for (Stmt *SubStmt : E->children()) {
14221 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
14222 if (!ChildExpr)
14223 continue;
14224
14225 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
14226 if (ChildExpr == CSE->getOperand())
14227 // Do not recurse over a CoroutineSuspendExpr's operand.
14228 // The operand is also a subexpression of getCommonExpr(), and
14229 // recursing into it directly would produce duplicate diagnostics.
14230 continue;
14231
14232 if (IsLogicalAndOperator &&
14234 // Ignore checking string literals that are in logical and operators.
14235 // This is a common pattern for asserts.
14236 continue;
14237 WorkList.push_back({ChildExpr, CC, IsListInit});
14238 }
14239
14240 if (BO && BO->isLogicalOp()) {
14241 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14242 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14243 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14244
14245 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14246 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14247 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14248 }
14249
14250 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
14251 if (U->getOpcode() == UO_LNot) {
14252 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
14253 } else if (U->getOpcode() != UO_AddrOf) {
14254 if (U->getSubExpr()->getType()->isAtomicType())
14255 S.Diag(U->getSubExpr()->getBeginLoc(),
14256 diag::warn_atomic_implicit_seq_cst);
14257 }
14258 }
14259}
14260
14261/// AnalyzeImplicitConversions - Find and report any interesting
14262/// implicit conversions in the given expression. There are a couple
14263/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14265 bool IsListInit/*= false*/) {
14267 WorkList.push_back({OrigE, CC, IsListInit});
14268 while (!WorkList.empty())
14269 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
14270}
14271
14272// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14273// Returns true when emitting a warning about taking the address of a reference.
14274static bool CheckForReference(Sema &SemaRef, const Expr *E,
14275 const PartialDiagnostic &PD) {
14276 E = E->IgnoreParenImpCasts();
14277
14278 const FunctionDecl *FD = nullptr;
14279
14280 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14281 if (!DRE->getDecl()->getType()->isReferenceType())
14282 return false;
14283 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14284 if (!M->getMemberDecl()->getType()->isReferenceType())
14285 return false;
14286 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
14287 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
14288 return false;
14289 FD = Call->getDirectCallee();
14290 } else {
14291 return false;
14292 }
14293
14294 SemaRef.Diag(E->getExprLoc(), PD);
14295
14296 // If possible, point to location of function.
14297 if (FD) {
14298 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
14299 }
14300
14301 return true;
14302}
14303
14304// Returns true if the SourceLocation is expanded from any macro body.
14305// Returns false if the SourceLocation is invalid, is from not in a macro
14306// expansion, or is from expanded from a top-level macro argument.
14307static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
14308 if (Loc.isInvalid())
14309 return false;
14310
14311 while (Loc.isMacroID()) {
14312 if (SM.isMacroBodyExpansion(Loc))
14313 return true;
14314 Loc = SM.getImmediateMacroCallerLoc(Loc);
14315 }
14316
14317 return false;
14318}
14319
14322 bool IsEqual, SourceRange Range) {
14323 if (!E)
14324 return;
14325
14326 // Don't warn inside macros.
14327 if (E->getExprLoc().isMacroID()) {
14328 const SourceManager &SM = getSourceManager();
14329 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
14330 IsInAnyMacroBody(SM, Range.getBegin()))
14331 return;
14332 }
14333 E = E->IgnoreImpCasts();
14334
14335 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14336
14337 if (isa<CXXThisExpr>(E)) {
14338 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14339 : diag::warn_this_bool_conversion;
14340 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14341 return;
14342 }
14343
14344 bool IsAddressOf = false;
14345
14346 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
14347 if (UO->getOpcode() != UO_AddrOf)
14348 return;
14349 IsAddressOf = true;
14350 E = UO->getSubExpr();
14351 }
14352
14353 if (IsAddressOf) {
14354 unsigned DiagID = IsCompare
14355 ? diag::warn_address_of_reference_null_compare
14356 : diag::warn_address_of_reference_bool_conversion;
14357 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14358 << IsEqual;
14359 if (CheckForReference(*this, E, PD)) {
14360 return;
14361 }
14362 }
14363
14364 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14365 bool IsParam = isa<NonNullAttr>(NonnullAttr);
14366 std::string Str;
14367 llvm::raw_string_ostream S(Str);
14368 E->printPretty(S, nullptr, getPrintingPolicy());
14369 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14370 : diag::warn_cast_nonnull_to_bool;
14371 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
14372 << E->getSourceRange() << Range << IsEqual;
14373 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
14374 };
14375
14376 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14377 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
14378 if (auto *Callee = Call->getDirectCallee()) {
14379 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14380 ComplainAboutNonnullParamOrCall(A);
14381 return;
14382 }
14383 }
14384 }
14385
14386 // Complain if we are converting a lambda expression to a boolean value
14387 // outside of instantiation.
14388 if (!inTemplateInstantiation()) {
14389 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
14390 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14391 MRecordDecl && MRecordDecl->isLambda()) {
14392 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
14393 << /*LambdaPointerConversionOperatorType=*/3
14394 << MRecordDecl->getSourceRange() << Range << IsEqual;
14395 return;
14396 }
14397 }
14398 }
14399
14400 // Expect to find a single Decl. Skip anything more complicated.
14401 ValueDecl *D = nullptr;
14402 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14403 D = R->getDecl();
14404 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14405 D = M->getMemberDecl();
14406 }
14407
14408 // Weak Decls can be null.
14409 if (!D || D->isWeak())
14410 return;
14411
14412 // Check for parameter decl with nonnull attribute
14413 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14414 if (getCurFunction() &&
14415 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14416 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14417 ComplainAboutNonnullParamOrCall(A);
14418 return;
14419 }
14420
14421 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14422 // Skip function template not specialized yet.
14424 return;
14425 auto ParamIter = llvm::find(FD->parameters(), PV);
14426 assert(ParamIter != FD->param_end());
14427 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14428
14429 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14430 if (!NonNull->args_size()) {
14431 ComplainAboutNonnullParamOrCall(NonNull);
14432 return;
14433 }
14434
14435 for (const ParamIdx &ArgNo : NonNull->args()) {
14436 if (ArgNo.getASTIndex() == ParamNo) {
14437 ComplainAboutNonnullParamOrCall(NonNull);
14438 return;
14439 }
14440 }
14441 }
14442 }
14443 }
14444 }
14445
14446 QualType T = D->getType();
14447 // A reference to a function is never null either; look through it.
14448 const bool IsFunctionReference =
14449 T->isReferenceType() && T->getPointeeType()->isFunctionType();
14450 if (IsFunctionReference)
14451 T = T->getPointeeType();
14452 const bool IsArray = T->isArrayType();
14453 const bool IsFunction = T->isFunctionType();
14454
14455 // Address of function is used to silence the function warning.
14456 if (IsAddressOf && IsFunction) {
14457 return;
14458 }
14459
14460 // Found nothing.
14461 if (!IsAddressOf && !IsFunction && !IsArray)
14462 return;
14463
14464 // Pretty print the expression for the diagnostic.
14465 std::string Str;
14466 llvm::raw_string_ostream S(Str);
14467 E->printPretty(S, nullptr, getPrintingPolicy());
14468
14469 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14470 : diag::warn_impcast_pointer_to_bool;
14471 enum {
14472 AddressOf,
14473 FunctionPointer,
14474 ArrayPointer
14475 } DiagType;
14476 if (IsAddressOf)
14477 DiagType = AddressOf;
14478 else if (IsFunction)
14479 DiagType = FunctionPointer;
14480 else if (IsArray)
14481 DiagType = ArrayPointer;
14482 else
14483 llvm_unreachable("Could not determine diagnostic.");
14484 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14485 << Range << IsEqual;
14486
14487 // The fix-it notes below only apply to a bare function name, not a reference.
14488 if (!IsFunction || IsFunctionReference)
14489 return;
14490
14491 // Suggest '&' to silence the function warning.
14492 Diag(E->getExprLoc(), diag::note_function_warning_silence)
14494
14495 // Check to see if '()' fixit should be emitted.
14496 QualType ReturnType;
14497 UnresolvedSet<4> NonTemplateOverloads;
14498 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14499 if (ReturnType.isNull())
14500 return;
14501
14502 if (IsCompare) {
14503 // There are two cases here. If there is null constant, the only suggest
14504 // for a pointer return type. If the null is 0, then suggest if the return
14505 // type is a pointer or an integer type.
14506 if (!ReturnType->isPointerType()) {
14507 if (NullKind == Expr::NPCK_ZeroExpression ||
14508 NullKind == Expr::NPCK_ZeroLiteral) {
14509 if (!ReturnType->isIntegerType())
14510 return;
14511 } else {
14512 return;
14513 }
14514 }
14515 } else { // !IsCompare
14516 // For function to bool, only suggest if the function pointer has bool
14517 // return type.
14518 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14519 return;
14520 }
14521 Diag(E->getExprLoc(), diag::note_function_to_function_call)
14523}
14524
14526 SourceLocation CC) {
14527 QualType Source = E->getType();
14528 QualType Target = T;
14529
14530 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14531 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14532 // Overflow behavior type is being stripped - issue warning
14533 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14534 Target->isUnsignedIntegerType()) {
14535 // For unsigned wrap to unsigned conversions, use pedantic version
14536 unsigned DiagId =
14538 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14539 : diag::warn_impcast_overflow_behavior_pedantic;
14540 DiagnoseImpCast(*this, E, T, CC, DiagId);
14541 } else {
14542 unsigned DiagId = InOverflowBehaviorAssignmentContext
14543 ? diag::warn_impcast_overflow_behavior_assignment
14544 : diag::warn_impcast_overflow_behavior;
14545 DiagnoseImpCast(*this, E, T, CC, DiagId);
14546 }
14547 }
14548 }
14549
14550 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14551 if (TargetOBT->isWrapKind()) {
14552 return true;
14553 }
14554 }
14555
14556 return false;
14557}
14558
14559void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14560 // Don't diagnose in unevaluated contexts.
14562 return;
14563
14564 // Don't diagnose for value- or type-dependent expressions.
14565 if (E->isTypeDependent() || E->isValueDependent())
14566 return;
14567
14568 // Check for array bounds violations in cases where the check isn't triggered
14569 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14570 // ArraySubscriptExpr is on the RHS of a variable initialization.
14571 CheckArrayAccess(E);
14572
14573 // This is not the right CC for (e.g.) a variable initialization.
14574 AnalyzeImplicitConversions(*this, E, CC);
14575}
14576
14577void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14578 ::CheckBoolLikeConversion(*this, E, CC);
14579}
14580
14581void Sema::CheckForIntOverflow (const Expr *E) {
14582 // Use a work list to deal with nested struct initializers.
14583 SmallVector<const Expr *, 2> Exprs(1, E);
14584
14585 do {
14586 const Expr *OriginalE = Exprs.pop_back_val();
14587 const Expr *E = OriginalE->IgnoreParenCasts();
14588
14589 if (isa<BinaryOperator>(E) ||
14590 (isa<UnaryOperator>(E) && cast<UnaryOperator>(E)->canOverflow())) {
14592 continue;
14593 }
14594
14595 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
14596 Exprs.append(InitList->inits().begin(), InitList->inits().end());
14597 else if (isa<ObjCBoxedExpr>(OriginalE))
14599 else if (const auto *Call = dyn_cast<CallExpr>(E))
14600 Exprs.append(Call->arg_begin(), Call->arg_end());
14601 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
14602 Exprs.append(Message->arg_begin(), Message->arg_end());
14603 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
14604 Exprs.append(Construct->arg_begin(), Construct->arg_end());
14605 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
14606 Exprs.push_back(Temporary->getSubExpr());
14607 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
14608 Exprs.push_back(Array->getIdx());
14609 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
14610 Exprs.push_back(Compound->getInitializer());
14611 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
14612 New && New->isArray()) {
14613 if (auto ArraySize = New->getArraySize())
14614 Exprs.push_back(*ArraySize);
14615 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
14616 Exprs.push_back(MTE->getSubExpr());
14617 } while (!Exprs.empty());
14618}
14619
14620namespace {
14621
14622/// Visitor for expressions which looks for unsequenced operations on the
14623/// same object.
14624class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14625 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14626
14627 /// A tree of sequenced regions within an expression. Two regions are
14628 /// unsequenced if one is an ancestor or a descendent of the other. When we
14629 /// finish processing an expression with sequencing, such as a comma
14630 /// expression, we fold its tree nodes into its parent, since they are
14631 /// unsequenced with respect to nodes we will visit later.
14632 class SequenceTree {
14633 struct Value {
14634 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14635 unsigned Parent : 31;
14636 LLVM_PREFERRED_TYPE(bool)
14637 unsigned Merged : 1;
14638 };
14639 SmallVector<Value, 8> Values;
14640
14641 public:
14642 /// A region within an expression which may be sequenced with respect
14643 /// to some other region.
14644 class Seq {
14645 friend class SequenceTree;
14646
14647 unsigned Index;
14648
14649 explicit Seq(unsigned N) : Index(N) {}
14650
14651 public:
14652 Seq() : Index(0) {}
14653 };
14654
14655 SequenceTree() { Values.push_back(Value(0)); }
14656 Seq root() const { return Seq(0); }
14657
14658 /// Create a new sequence of operations, which is an unsequenced
14659 /// subset of \p Parent. This sequence of operations is sequenced with
14660 /// respect to other children of \p Parent.
14661 Seq allocate(Seq Parent) {
14662 Values.push_back(Value(Parent.Index));
14663 return Seq(Values.size() - 1);
14664 }
14665
14666 /// Merge a sequence of operations into its parent.
14667 void merge(Seq S) {
14668 Values[S.Index].Merged = true;
14669 }
14670
14671 /// Determine whether two operations are unsequenced. This operation
14672 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14673 /// should have been merged into its parent as appropriate.
14674 bool isUnsequenced(Seq Cur, Seq Old) {
14675 unsigned C = representative(Cur.Index);
14676 unsigned Target = representative(Old.Index);
14677 while (C >= Target) {
14678 if (C == Target)
14679 return true;
14680 C = Values[C].Parent;
14681 }
14682 return false;
14683 }
14684
14685 private:
14686 /// Pick a representative for a sequence.
14687 unsigned representative(unsigned K) {
14688 if (Values[K].Merged)
14689 // Perform path compression as we go.
14690 return Values[K].Parent = representative(Values[K].Parent);
14691 return K;
14692 }
14693 };
14694
14695 /// An object for which we can track unsequenced uses.
14696 using Object = const NamedDecl *;
14697
14698 /// Different flavors of object usage which we track. We only track the
14699 /// least-sequenced usage of each kind.
14700 enum UsageKind {
14701 /// A read of an object. Multiple unsequenced reads are OK.
14702 UK_Use,
14703
14704 /// A modification of an object which is sequenced before the value
14705 /// computation of the expression, such as ++n in C++.
14706 UK_ModAsValue,
14707
14708 /// A modification of an object which is not sequenced before the value
14709 /// computation of the expression, such as n++.
14710 UK_ModAsSideEffect,
14711
14712 UK_Count = UK_ModAsSideEffect + 1
14713 };
14714
14715 /// Bundle together a sequencing region and the expression corresponding
14716 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14717 struct Usage {
14718 const Expr *UsageExpr = nullptr;
14719 SequenceTree::Seq Seq;
14720
14721 Usage() = default;
14722 };
14723
14724 struct UsageInfo {
14725 Usage Uses[UK_Count];
14726
14727 /// Have we issued a diagnostic for this object already?
14728 bool Diagnosed = false;
14729
14730 UsageInfo();
14731 };
14732 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14733
14734 Sema &SemaRef;
14735
14736 /// Sequenced regions within the expression.
14737 SequenceTree Tree;
14738
14739 /// Declaration modifications and references which we have seen.
14740 UsageInfoMap UsageMap;
14741
14742 /// The region we are currently within.
14743 SequenceTree::Seq Region;
14744
14745 /// Filled in with declarations which were modified as a side-effect
14746 /// (that is, post-increment operations).
14747 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14748
14749 /// Expressions to check later. We defer checking these to reduce
14750 /// stack usage.
14751 SmallVectorImpl<const Expr *> &WorkList;
14752
14753 /// RAII object wrapping the visitation of a sequenced subexpression of an
14754 /// expression. At the end of this process, the side-effects of the evaluation
14755 /// become sequenced with respect to the value computation of the result, so
14756 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14757 /// UK_ModAsValue.
14758 struct SequencedSubexpression {
14759 SequencedSubexpression(SequenceChecker &Self)
14760 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14761 Self.ModAsSideEffect = &ModAsSideEffect;
14762 }
14763
14764 ~SequencedSubexpression() {
14765 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14766 // Add a new usage with usage kind UK_ModAsValue, and then restore
14767 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14768 // the previous one was empty).
14769 UsageInfo &UI = Self.UsageMap[M.first];
14770 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14771 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14772 SideEffectUsage = M.second;
14773 }
14774 Self.ModAsSideEffect = OldModAsSideEffect;
14775 }
14776
14777 SequenceChecker &Self;
14778 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14779 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14780 };
14781
14782 /// RAII object wrapping the visitation of a subexpression which we might
14783 /// choose to evaluate as a constant. If any subexpression is evaluated and
14784 /// found to be non-constant, this allows us to suppress the evaluation of
14785 /// the outer expression.
14786 class EvaluationTracker {
14787 public:
14788 EvaluationTracker(SequenceChecker &Self)
14789 : Self(Self), Prev(Self.EvalTracker) {
14790 Self.EvalTracker = this;
14791 }
14792
14793 ~EvaluationTracker() {
14794 Self.EvalTracker = Prev;
14795 if (Prev)
14796 Prev->EvalOK &= EvalOK;
14797 }
14798
14799 bool evaluate(const Expr *E, bool &Result) {
14800 if (!EvalOK || E->isValueDependent())
14801 return false;
14802 EvalOK = E->EvaluateAsBooleanCondition(
14803 Result, Self.SemaRef.Context,
14804 Self.SemaRef.isConstantEvaluatedContext());
14805 return EvalOK;
14806 }
14807
14808 private:
14809 SequenceChecker &Self;
14810 EvaluationTracker *Prev;
14811 bool EvalOK = true;
14812 } *EvalTracker = nullptr;
14813
14814 /// Find the object which is produced by the specified expression,
14815 /// if any.
14816 Object getObject(const Expr *E, bool Mod) const {
14817 E = E->IgnoreParenCasts();
14818 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
14819 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14820 return getObject(UO->getSubExpr(), Mod);
14821 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14822 if (BO->getOpcode() == BO_Comma)
14823 return getObject(BO->getRHS(), Mod);
14824 if (Mod && BO->isAssignmentOp())
14825 return getObject(BO->getLHS(), Mod);
14826 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14827 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14828 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
14829 return ME->getMemberDecl();
14830 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14831 // FIXME: If this is a reference, map through to its value.
14832 return DRE->getDecl();
14833 return nullptr;
14834 }
14835
14836 /// Note that an object \p O was modified or used by an expression
14837 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14838 /// the object \p O as obtained via the \p UsageMap.
14839 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14840 // Get the old usage for the given object and usage kind.
14841 Usage &U = UI.Uses[UK];
14842 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
14843 // If we have a modification as side effect and are in a sequenced
14844 // subexpression, save the old Usage so that we can restore it later
14845 // in SequencedSubexpression::~SequencedSubexpression.
14846 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14847 ModAsSideEffect->push_back(std::make_pair(O, U));
14848 // Then record the new usage with the current sequencing region.
14849 U.UsageExpr = UsageExpr;
14850 U.Seq = Region;
14851 }
14852 }
14853
14854 /// Check whether a modification or use of an object \p O in an expression
14855 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14856 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14857 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14858 /// usage and false we are checking for a mod-use unsequenced usage.
14859 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14860 UsageKind OtherKind, bool IsModMod) {
14861 if (UI.Diagnosed)
14862 return;
14863
14864 const Usage &U = UI.Uses[OtherKind];
14865 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
14866 return;
14867
14868 const Expr *Mod = U.UsageExpr;
14869 const Expr *ModOrUse = UsageExpr;
14870 if (OtherKind == UK_Use)
14871 std::swap(Mod, ModOrUse);
14872
14873 SemaRef.DiagRuntimeBehavior(
14874 Mod->getExprLoc(), {Mod, ModOrUse},
14875 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
14876 : diag::warn_unsequenced_mod_use)
14877 << O << SourceRange(ModOrUse->getExprLoc()));
14878 UI.Diagnosed = true;
14879 }
14880
14881 // A note on note{Pre, Post}{Use, Mod}:
14882 //
14883 // (It helps to follow the algorithm with an expression such as
14884 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14885 // operations before C++17 and both are well-defined in C++17).
14886 //
14887 // When visiting a node which uses/modify an object we first call notePreUse
14888 // or notePreMod before visiting its sub-expression(s). At this point the
14889 // children of the current node have not yet been visited and so the eventual
14890 // uses/modifications resulting from the children of the current node have not
14891 // been recorded yet.
14892 //
14893 // We then visit the children of the current node. After that notePostUse or
14894 // notePostMod is called. These will 1) detect an unsequenced modification
14895 // as side effect (as in "k++ + k") and 2) add a new usage with the
14896 // appropriate usage kind.
14897 //
14898 // We also have to be careful that some operation sequences modification as
14899 // side effect as well (for example: || or ,). To account for this we wrap
14900 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14901 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14902 // which record usages which are modifications as side effect, and then
14903 // downgrade them (or more accurately restore the previous usage which was a
14904 // modification as side effect) when exiting the scope of the sequenced
14905 // subexpression.
14906
14907 void notePreUse(Object O, const Expr *UseExpr) {
14908 UsageInfo &UI = UsageMap[O];
14909 // Uses conflict with other modifications.
14910 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14911 }
14912
14913 void notePostUse(Object O, const Expr *UseExpr) {
14914 UsageInfo &UI = UsageMap[O];
14915 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14916 /*IsModMod=*/false);
14917 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14918 }
14919
14920 void notePreMod(Object O, const Expr *ModExpr) {
14921 UsageInfo &UI = UsageMap[O];
14922 // Modifications conflict with other modifications and with uses.
14923 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14924 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14925 }
14926
14927 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14928 UsageInfo &UI = UsageMap[O];
14929 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14930 /*IsModMod=*/true);
14931 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14932 }
14933
14934public:
14935 SequenceChecker(Sema &S, const Expr *E,
14936 SmallVectorImpl<const Expr *> &WorkList)
14937 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14938 Visit(E);
14939 // Silence a -Wunused-private-field since WorkList is now unused.
14940 // TODO: Evaluate if it can be used, and if not remove it.
14941 (void)this->WorkList;
14942 }
14943
14944 void VisitStmt(const Stmt *S) {
14945 // Skip all statements which aren't expressions for now.
14946 }
14947
14948 void VisitExpr(const Expr *E) {
14949 // By default, just recurse to evaluated subexpressions.
14950 Base::VisitStmt(E);
14951 }
14952
14953 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14954 for (auto *Sub : CSE->children()) {
14955 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
14956 if (!ChildExpr)
14957 continue;
14958
14959 if (ChildExpr == CSE->getOperand())
14960 // Do not recurse over a CoroutineSuspendExpr's operand.
14961 // The operand is also a subexpression of getCommonExpr(), and
14962 // recursing into it directly could confuse object management
14963 // for the sake of sequence tracking.
14964 continue;
14965
14966 Visit(Sub);
14967 }
14968 }
14969
14970 void VisitCastExpr(const CastExpr *E) {
14971 Object O = Object();
14972 if (E->getCastKind() == CK_LValueToRValue)
14973 O = getObject(E->getSubExpr(), false);
14974
14975 if (O)
14976 notePreUse(O, E);
14977 VisitExpr(E);
14978 if (O)
14979 notePostUse(O, E);
14980 }
14981
14982 void VisitSequencedExpressions(const Expr *SequencedBefore,
14983 const Expr *SequencedAfter) {
14984 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14985 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14986 SequenceTree::Seq OldRegion = Region;
14987
14988 {
14989 SequencedSubexpression SeqBefore(*this);
14990 Region = BeforeRegion;
14991 Visit(SequencedBefore);
14992 }
14993
14994 Region = AfterRegion;
14995 Visit(SequencedAfter);
14996
14997 Region = OldRegion;
14998
14999 Tree.merge(BeforeRegion);
15000 Tree.merge(AfterRegion);
15001 }
15002
15003 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
15004 // C++17 [expr.sub]p1:
15005 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
15006 // expression E1 is sequenced before the expression E2.
15007 if (SemaRef.getLangOpts().CPlusPlus17)
15008 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
15009 else {
15010 Visit(ASE->getLHS());
15011 Visit(ASE->getRHS());
15012 }
15013 }
15014
15015 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15016 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15017 void VisitBinPtrMem(const BinaryOperator *BO) {
15018 // C++17 [expr.mptr.oper]p4:
15019 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
15020 // the expression E1 is sequenced before the expression E2.
15021 if (SemaRef.getLangOpts().CPlusPlus17)
15022 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15023 else {
15024 Visit(BO->getLHS());
15025 Visit(BO->getRHS());
15026 }
15027 }
15028
15029 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15030 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15031 void VisitBinShlShr(const BinaryOperator *BO) {
15032 // C++17 [expr.shift]p4:
15033 // The expression E1 is sequenced before the expression E2.
15034 if (SemaRef.getLangOpts().CPlusPlus17)
15035 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15036 else {
15037 Visit(BO->getLHS());
15038 Visit(BO->getRHS());
15039 }
15040 }
15041
15042 void VisitBinComma(const BinaryOperator *BO) {
15043 // C++11 [expr.comma]p1:
15044 // Every value computation and side effect associated with the left
15045 // expression is sequenced before every value computation and side
15046 // effect associated with the right expression.
15047 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15048 }
15049
15050 void VisitBinAssign(const BinaryOperator *BO) {
15051 SequenceTree::Seq RHSRegion;
15052 SequenceTree::Seq LHSRegion;
15053 if (SemaRef.getLangOpts().CPlusPlus17) {
15054 RHSRegion = Tree.allocate(Region);
15055 LHSRegion = Tree.allocate(Region);
15056 } else {
15057 RHSRegion = Region;
15058 LHSRegion = Region;
15059 }
15060 SequenceTree::Seq OldRegion = Region;
15061
15062 // C++11 [expr.ass]p1:
15063 // [...] the assignment is sequenced after the value computation
15064 // of the right and left operands, [...]
15065 //
15066 // so check it before inspecting the operands and update the
15067 // map afterwards.
15068 Object O = getObject(BO->getLHS(), /*Mod=*/true);
15069 if (O)
15070 notePreMod(O, BO);
15071
15072 if (SemaRef.getLangOpts().CPlusPlus17) {
15073 // C++17 [expr.ass]p1:
15074 // [...] The right operand is sequenced before the left operand. [...]
15075 {
15076 SequencedSubexpression SeqBefore(*this);
15077 Region = RHSRegion;
15078 Visit(BO->getRHS());
15079 }
15080
15081 Region = LHSRegion;
15082 Visit(BO->getLHS());
15083
15084 if (O && isa<CompoundAssignOperator>(BO))
15085 notePostUse(O, BO);
15086
15087 } else {
15088 // C++11 does not specify any sequencing between the LHS and RHS.
15089 Region = LHSRegion;
15090 Visit(BO->getLHS());
15091
15092 if (O && isa<CompoundAssignOperator>(BO))
15093 notePostUse(O, BO);
15094
15095 Region = RHSRegion;
15096 Visit(BO->getRHS());
15097 }
15098
15099 // C++11 [expr.ass]p1:
15100 // the assignment is sequenced [...] before the value computation of the
15101 // assignment expression.
15102 // C11 6.5.16/3 has no such rule.
15103 Region = OldRegion;
15104 if (O)
15105 notePostMod(O, BO,
15106 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15107 : UK_ModAsSideEffect);
15108 if (SemaRef.getLangOpts().CPlusPlus17) {
15109 Tree.merge(RHSRegion);
15110 Tree.merge(LHSRegion);
15111 }
15112 }
15113
15114 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
15115 VisitBinAssign(CAO);
15116 }
15117
15118 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15119 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15120 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
15121 Object O = getObject(UO->getSubExpr(), true);
15122 if (!O)
15123 return VisitExpr(UO);
15124
15125 notePreMod(O, UO);
15126 Visit(UO->getSubExpr());
15127 // C++11 [expr.pre.incr]p1:
15128 // the expression ++x is equivalent to x+=1
15129 notePostMod(O, UO,
15130 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15131 : UK_ModAsSideEffect);
15132 }
15133
15134 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15135 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15136 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
15137 Object O = getObject(UO->getSubExpr(), true);
15138 if (!O)
15139 return VisitExpr(UO);
15140
15141 notePreMod(O, UO);
15142 Visit(UO->getSubExpr());
15143 notePostMod(O, UO, UK_ModAsSideEffect);
15144 }
15145
15146 void VisitBinLOr(const BinaryOperator *BO) {
15147 // C++11 [expr.log.or]p2:
15148 // If the second expression is evaluated, every value computation and
15149 // side effect associated with the first expression is sequenced before
15150 // every value computation and side effect associated with the
15151 // second expression.
15152 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15153 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15154 SequenceTree::Seq OldRegion = Region;
15155
15156 EvaluationTracker Eval(*this);
15157 {
15158 SequencedSubexpression Sequenced(*this);
15159 Region = LHSRegion;
15160 Visit(BO->getLHS());
15161 }
15162
15163 // C++11 [expr.log.or]p1:
15164 // [...] the second operand is not evaluated if the first operand
15165 // evaluates to true.
15166 bool EvalResult = false;
15167 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15168 bool ShouldVisitRHS = !EvalOK || !EvalResult;
15169 if (ShouldVisitRHS) {
15170 Region = RHSRegion;
15171 Visit(BO->getRHS());
15172 }
15173
15174 Region = OldRegion;
15175 Tree.merge(LHSRegion);
15176 Tree.merge(RHSRegion);
15177 }
15178
15179 void VisitBinLAnd(const BinaryOperator *BO) {
15180 // C++11 [expr.log.and]p2:
15181 // If the second expression is evaluated, every value computation and
15182 // side effect associated with the first expression is sequenced before
15183 // every value computation and side effect associated with the
15184 // second expression.
15185 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15186 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15187 SequenceTree::Seq OldRegion = Region;
15188
15189 EvaluationTracker Eval(*this);
15190 {
15191 SequencedSubexpression Sequenced(*this);
15192 Region = LHSRegion;
15193 Visit(BO->getLHS());
15194 }
15195
15196 // C++11 [expr.log.and]p1:
15197 // [...] the second operand is not evaluated if the first operand is false.
15198 bool EvalResult = false;
15199 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15200 bool ShouldVisitRHS = !EvalOK || EvalResult;
15201 if (ShouldVisitRHS) {
15202 Region = RHSRegion;
15203 Visit(BO->getRHS());
15204 }
15205
15206 Region = OldRegion;
15207 Tree.merge(LHSRegion);
15208 Tree.merge(RHSRegion);
15209 }
15210
15211 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15212 // C++11 [expr.cond]p1:
15213 // [...] Every value computation and side effect associated with the first
15214 // expression is sequenced before every value computation and side effect
15215 // associated with the second or third expression.
15216 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
15217
15218 // No sequencing is specified between the true and false expression.
15219 // However since exactly one of both is going to be evaluated we can
15220 // consider them to be sequenced. This is needed to avoid warning on
15221 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15222 // both the true and false expressions because we can't evaluate x.
15223 // This will still allow us to detect an expression like (pre C++17)
15224 // "(x ? y += 1 : y += 2) = y".
15225 //
15226 // We don't wrap the visitation of the true and false expression with
15227 // SequencedSubexpression because we don't want to downgrade modifications
15228 // as side effect in the true and false expressions after the visition
15229 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15230 // not warn between the two "y++", but we should warn between the "y++"
15231 // and the "y".
15232 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
15233 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
15234 SequenceTree::Seq OldRegion = Region;
15235
15236 EvaluationTracker Eval(*this);
15237 {
15238 SequencedSubexpression Sequenced(*this);
15239 Region = ConditionRegion;
15240 Visit(CO->getCond());
15241 }
15242
15243 // C++11 [expr.cond]p1:
15244 // [...] The first expression is contextually converted to bool (Clause 4).
15245 // It is evaluated and if it is true, the result of the conditional
15246 // expression is the value of the second expression, otherwise that of the
15247 // third expression. Only one of the second and third expressions is
15248 // evaluated. [...]
15249 bool EvalResult = false;
15250 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
15251 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15252 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15253 if (ShouldVisitTrueExpr) {
15254 Region = TrueRegion;
15255 Visit(CO->getTrueExpr());
15256 }
15257 if (ShouldVisitFalseExpr) {
15258 Region = FalseRegion;
15259 Visit(CO->getFalseExpr());
15260 }
15261
15262 Region = OldRegion;
15263 Tree.merge(ConditionRegion);
15264 Tree.merge(TrueRegion);
15265 Tree.merge(FalseRegion);
15266 }
15267
15268 void VisitCallExpr(const CallExpr *CE) {
15269 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15270
15271 if (CE->isUnevaluatedBuiltinCall(Context))
15272 return;
15273
15274 // C++11 [intro.execution]p15:
15275 // When calling a function [...], every value computation and side effect
15276 // associated with any argument expression, or with the postfix expression
15277 // designating the called function, is sequenced before execution of every
15278 // expression or statement in the body of the function [and thus before
15279 // the value computation of its result].
15280 SequencedSubexpression Sequenced(*this);
15281 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
15282 // C++17 [expr.call]p5
15283 // The postfix-expression is sequenced before each expression in the
15284 // expression-list and any default argument. [...]
15285 SequenceTree::Seq CalleeRegion;
15286 SequenceTree::Seq OtherRegion;
15287 if (SemaRef.getLangOpts().CPlusPlus17) {
15288 CalleeRegion = Tree.allocate(Region);
15289 OtherRegion = Tree.allocate(Region);
15290 } else {
15291 CalleeRegion = Region;
15292 OtherRegion = Region;
15293 }
15294 SequenceTree::Seq OldRegion = Region;
15295
15296 // Visit the callee expression first.
15297 Region = CalleeRegion;
15298 if (SemaRef.getLangOpts().CPlusPlus17) {
15299 SequencedSubexpression Sequenced(*this);
15300 Visit(CE->getCallee());
15301 } else {
15302 Visit(CE->getCallee());
15303 }
15304
15305 // Then visit the argument expressions.
15306 Region = OtherRegion;
15307 for (const Expr *Argument : CE->arguments())
15308 Visit(Argument);
15309
15310 Region = OldRegion;
15311 if (SemaRef.getLangOpts().CPlusPlus17) {
15312 Tree.merge(CalleeRegion);
15313 Tree.merge(OtherRegion);
15314 }
15315 });
15316 }
15317
15318 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15319 // C++17 [over.match.oper]p2:
15320 // [...] the operator notation is first transformed to the equivalent
15321 // function-call notation as summarized in Table 12 (where @ denotes one
15322 // of the operators covered in the specified subclause). However, the
15323 // operands are sequenced in the order prescribed for the built-in
15324 // operator (Clause 8).
15325 //
15326 // From the above only overloaded binary operators and overloaded call
15327 // operators have sequencing rules in C++17 that we need to handle
15328 // separately.
15329 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15330 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15331 return VisitCallExpr(CXXOCE);
15332
15333 enum {
15334 NoSequencing,
15335 LHSBeforeRHS,
15336 RHSBeforeLHS,
15337 LHSBeforeRest
15338 } SequencingKind;
15339 switch (CXXOCE->getOperator()) {
15340 case OO_Equal:
15341 case OO_PlusEqual:
15342 case OO_MinusEqual:
15343 case OO_StarEqual:
15344 case OO_SlashEqual:
15345 case OO_PercentEqual:
15346 case OO_CaretEqual:
15347 case OO_AmpEqual:
15348 case OO_PipeEqual:
15349 case OO_LessLessEqual:
15350 case OO_GreaterGreaterEqual:
15351 SequencingKind = RHSBeforeLHS;
15352 break;
15353
15354 case OO_LessLess:
15355 case OO_GreaterGreater:
15356 case OO_AmpAmp:
15357 case OO_PipePipe:
15358 case OO_Comma:
15359 case OO_ArrowStar:
15360 case OO_Subscript:
15361 SequencingKind = LHSBeforeRHS;
15362 break;
15363
15364 case OO_Call:
15365 SequencingKind = LHSBeforeRest;
15366 break;
15367
15368 default:
15369 SequencingKind = NoSequencing;
15370 break;
15371 }
15372
15373 if (SequencingKind == NoSequencing)
15374 return VisitCallExpr(CXXOCE);
15375
15376 // This is a call, so all subexpressions are sequenced before the result.
15377 SequencedSubexpression Sequenced(*this);
15378
15379 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
15380 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15381 "Should only get there with C++17 and above!");
15382 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15383 "Should only get there with an overloaded binary operator"
15384 " or an overloaded call operator!");
15385
15386 if (SequencingKind == LHSBeforeRest) {
15387 assert(CXXOCE->getOperator() == OO_Call &&
15388 "We should only have an overloaded call operator here!");
15389
15390 // This is very similar to VisitCallExpr, except that we only have the
15391 // C++17 case. The postfix-expression is the first argument of the
15392 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15393 // are in the following arguments.
15394 //
15395 // Note that we intentionally do not visit the callee expression since
15396 // it is just a decayed reference to a function.
15397 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
15398 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
15399 SequenceTree::Seq OldRegion = Region;
15400
15401 assert(CXXOCE->getNumArgs() >= 1 &&
15402 "An overloaded call operator must have at least one argument"
15403 " for the postfix-expression!");
15404 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15405 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15406 CXXOCE->getNumArgs() - 1);
15407
15408 // Visit the postfix-expression first.
15409 {
15410 Region = PostfixExprRegion;
15411 SequencedSubexpression Sequenced(*this);
15412 Visit(PostfixExpr);
15413 }
15414
15415 // Then visit the argument expressions.
15416 Region = ArgsRegion;
15417 for (const Expr *Arg : Args)
15418 Visit(Arg);
15419
15420 Region = OldRegion;
15421 Tree.merge(PostfixExprRegion);
15422 Tree.merge(ArgsRegion);
15423 } else {
15424 assert(CXXOCE->getNumArgs() == 2 &&
15425 "Should only have two arguments here!");
15426 assert((SequencingKind == LHSBeforeRHS ||
15427 SequencingKind == RHSBeforeLHS) &&
15428 "Unexpected sequencing kind!");
15429
15430 // We do not visit the callee expression since it is just a decayed
15431 // reference to a function.
15432 const Expr *E1 = CXXOCE->getArg(0);
15433 const Expr *E2 = CXXOCE->getArg(1);
15434 if (SequencingKind == RHSBeforeLHS)
15435 std::swap(E1, E2);
15436
15437 return VisitSequencedExpressions(E1, E2);
15438 }
15439 });
15440 }
15441
15442 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15443 // This is a call, so all subexpressions are sequenced before the result.
15444 SequencedSubexpression Sequenced(*this);
15445
15446 if (!CCE->isListInitialization())
15447 return VisitExpr(CCE);
15448
15449 // In C++11, list initializations are sequenced.
15450 SequenceExpressionsInOrder(
15451 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15452 }
15453
15454 void VisitInitListExpr(const InitListExpr *ILE) {
15455 if (!SemaRef.getLangOpts().CPlusPlus11)
15456 return VisitExpr(ILE);
15457
15458 // In C++11, list initializations are sequenced.
15459 SequenceExpressionsInOrder(ILE->inits());
15460 }
15461
15462 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15463 // C++20 parenthesized list initializations are sequenced. See C++20
15464 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15465 SequenceExpressionsInOrder(PLIE->getInitExprs());
15466 }
15467
15468private:
15469 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15471 SequenceTree::Seq Parent = Region;
15472 for (const Expr *E : ExpressionList) {
15473 if (!E)
15474 continue;
15475 Region = Tree.allocate(Parent);
15476 Elts.push_back(Region);
15477 Visit(E);
15478 }
15479
15480 // Forget that the initializers are sequenced.
15481 Region = Parent;
15482 for (unsigned I = 0; I < Elts.size(); ++I)
15483 Tree.merge(Elts[I]);
15484 }
15485};
15486
15487SequenceChecker::UsageInfo::UsageInfo() = default;
15488
15489} // namespace
15490
15491void Sema::CheckUnsequencedOperations(const Expr *E) {
15492 SmallVector<const Expr *, 8> WorkList;
15493 WorkList.push_back(E);
15494 while (!WorkList.empty()) {
15495 const Expr *Item = WorkList.pop_back_val();
15496 SequenceChecker(*this, Item, WorkList);
15497 }
15498}
15499
15500void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15501 bool IsConstexpr) {
15502 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15503 IsConstexpr || isa<ConstantExpr>(E));
15504 CheckImplicitConversions(E, CheckLoc);
15505 if (!E->isInstantiationDependent())
15506 CheckUnsequencedOperations(E);
15507 if (!IsConstexpr && !E->isValueDependent())
15508 CheckForIntOverflow(E);
15509}
15510
15511void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15512 FieldDecl *BitField,
15513 Expr *Init) {
15514 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15515}
15516
15518 SourceLocation Loc) {
15519 if (!PType->isVariablyModifiedType())
15520 return;
15521 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15522 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15523 return;
15524 }
15525 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15526 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15527 return;
15528 }
15529 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15530 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15531 return;
15532 }
15533
15534 const ArrayType *AT = S.Context.getAsArrayType(PType);
15535 if (!AT)
15536 return;
15537
15540 return;
15541 }
15542
15543 S.Diag(Loc, diag::err_array_star_in_function_definition);
15544}
15545
15547 bool CheckParameterNames) {
15548 bool HasInvalidParm = false;
15549 for (ParmVarDecl *Param : Parameters) {
15550 assert(Param && "null in a parameter list");
15551 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15552 // function declarator that is part of a function definition of
15553 // that function shall not have incomplete type.
15554 //
15555 // C++23 [dcl.fct.def.general]/p2
15556 // The type of a parameter [...] for a function definition
15557 // shall not be a (possibly cv-qualified) class type that is incomplete
15558 // or abstract within the function body unless the function is deleted.
15559 if (!Param->isInvalidDecl() &&
15560 (RequireCompleteType(Param->getLocation(), Param->getType(),
15561 diag::err_typecheck_decl_incomplete_type) ||
15562 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
15563 diag::err_abstract_type_in_decl,
15565 Param->setInvalidDecl();
15566 HasInvalidParm = true;
15567 }
15568
15569 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15570 // declaration of each parameter shall include an identifier.
15571 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15572 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15573 // Diagnose this as an extension in C17 and earlier.
15574 if (!getLangOpts().C23)
15575 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
15576 }
15577
15578 // C99 6.7.5.3p12:
15579 // If the function declarator is not part of a definition of that
15580 // function, parameters may have incomplete type and may use the [*]
15581 // notation in their sequences of declarator specifiers to specify
15582 // variable length array types.
15583 QualType PType = Param->getOriginalType();
15584 // FIXME: This diagnostic should point the '[*]' if source-location
15585 // information is added for it.
15586 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15587
15588 // If the parameter is a c++ class type and it has to be destructed in the
15589 // callee function, declare the destructor so that it can be called by the
15590 // callee function. Do not perform any direct access check on the dtor here.
15591 if (!Param->isInvalidDecl()) {
15592 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15593 if (!ClassDecl->isInvalidDecl() &&
15594 !ClassDecl->hasIrrelevantDestructor() &&
15595 !ClassDecl->isDependentContext() &&
15596 ClassDecl->isParamDestroyedInCallee()) {
15598 MarkFunctionReferenced(Param->getLocation(), Destructor);
15599 DiagnoseUseOfDecl(Destructor, Param->getLocation());
15600 }
15601 }
15602 }
15603
15604 // Parameters with the pass_object_size attribute only need to be marked
15605 // constant at function definitions. Because we lack information about
15606 // whether we're on a declaration or definition when we're instantiating the
15607 // attribute, we need to check for constness here.
15608 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15609 if (!Param->getType().isConstQualified())
15610 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15611 << Attr->getSpelling() << 1;
15612
15613 // Check for parameter names shadowing fields from the class.
15614 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15615 // The owning context for the parameter should be the function, but we
15616 // want to see if this function's declaration context is a record.
15617 DeclContext *DC = Param->getDeclContext();
15618 if (DC && DC->isFunctionOrMethod()) {
15619 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15620 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15621 RD, /*DeclIsField*/ false);
15622 }
15623 }
15624
15625 if (!Param->isInvalidDecl() &&
15626 Param->getOriginalType()->isWebAssemblyTableType()) {
15627 Param->setInvalidDecl();
15628 HasInvalidParm = true;
15629 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
15630 }
15631 }
15632
15633 return HasInvalidParm;
15634}
15635
15636std::optional<std::pair<
15638 *E,
15640 &Ctx);
15641
15642/// Compute the alignment and offset of the base class object given the
15643/// derived-to-base cast expression and the alignment and offset of the derived
15644/// class object.
15645static std::pair<CharUnits, CharUnits>
15647 CharUnits BaseAlignment, CharUnits Offset,
15648 ASTContext &Ctx) {
15649 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15650 ++PathI) {
15651 const CXXBaseSpecifier *Base = *PathI;
15652 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15653 if (Base->isVirtual()) {
15654 // The complete object may have a lower alignment than the non-virtual
15655 // alignment of the base, in which case the base may be misaligned. Choose
15656 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15657 // conservative lower bound of the complete object alignment.
15658 CharUnits NonVirtualAlignment =
15660 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15661 Offset = CharUnits::Zero();
15662 } else {
15663 const ASTRecordLayout &RL =
15664 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15665 Offset += RL.getBaseClassOffset(BaseDecl);
15666 }
15667 DerivedType = Base->getType();
15668 }
15669
15670 return std::make_pair(BaseAlignment, Offset);
15671}
15672
15673/// Compute the alignment and offset of a binary additive operator.
15674static std::optional<std::pair<CharUnits, CharUnits>>
15676 bool IsSub, ASTContext &Ctx) {
15677 QualType PointeeType = PtrE->getType()->getPointeeType();
15678
15679 if (!PointeeType->isConstantSizeType())
15680 return std::nullopt;
15681
15682 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15683
15684 if (!P)
15685 return std::nullopt;
15686
15687 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15688 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15689 CharUnits Offset = EltSize * IdxRes->getExtValue();
15690 if (IsSub)
15691 Offset = -Offset;
15692 return std::make_pair(P->first, P->second + Offset);
15693 }
15694
15695 // If the integer expression isn't a constant expression, compute the lower
15696 // bound of the alignment using the alignment and offset of the pointer
15697 // expression and the element size.
15698 return std::make_pair(
15699 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15700 CharUnits::Zero());
15701}
15702
15703/// This helper function takes an lvalue expression and returns the alignment of
15704/// a VarDecl and a constant offset from the VarDecl.
15705std::optional<std::pair<
15706 CharUnits,
15708 ASTContext &Ctx) {
15709 E = E->IgnoreParens();
15710 switch (E->getStmtClass()) {
15711 default:
15712 break;
15713 case Stmt::CStyleCastExprClass:
15714 case Stmt::CXXStaticCastExprClass:
15715 case Stmt::ImplicitCastExprClass: {
15716 auto *CE = cast<CastExpr>(E);
15717 const Expr *From = CE->getSubExpr();
15718 switch (CE->getCastKind()) {
15719 default:
15720 break;
15721 case CK_NoOp:
15722 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15723 case CK_UncheckedDerivedToBase:
15724 case CK_DerivedToBase: {
15725 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15726 if (!P)
15727 break;
15728 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15729 P->second, Ctx);
15730 }
15731 }
15732 break;
15733 }
15734 case Stmt::ArraySubscriptExprClass: {
15735 auto *ASE = cast<ArraySubscriptExpr>(E);
15737 false, Ctx);
15738 }
15739 case Stmt::DeclRefExprClass: {
15740 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15741 // FIXME: If VD is captured by copy or is an escaping __block variable,
15742 // use the alignment of VD's type.
15743 if (!VD->getType()->isReferenceType()) {
15744 // Dependent alignment cannot be resolved -> bail out.
15745 if (VD->hasDependentAlignment())
15746 break;
15747 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15748 }
15749 if (VD->hasInit())
15750 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15751 }
15752 break;
15753 }
15754 case Stmt::MemberExprClass: {
15755 auto *ME = cast<MemberExpr>(E);
15756 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15757 if (!FD || FD->getType()->isReferenceType() ||
15759 break;
15760 std::optional<std::pair<CharUnits, CharUnits>> P;
15761 if (ME->isArrow())
15762 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15763 else
15764 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15765 if (!P)
15766 break;
15767 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15768 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15769 return std::make_pair(P->first,
15770 P->second + CharUnits::fromQuantity(Offset));
15771 }
15772 case Stmt::UnaryOperatorClass: {
15773 auto *UO = cast<UnaryOperator>(E);
15774 switch (UO->getOpcode()) {
15775 default:
15776 break;
15777 case UO_Deref:
15779 }
15780 break;
15781 }
15782 case Stmt::BinaryOperatorClass: {
15783 auto *BO = cast<BinaryOperator>(E);
15784 auto Opcode = BO->getOpcode();
15785 switch (Opcode) {
15786 default:
15787 break;
15788 case BO_Comma:
15790 }
15791 break;
15792 }
15793 }
15794 return std::nullopt;
15795}
15796
15797/// This helper function takes a pointer expression and returns the alignment of
15798/// a VarDecl and a constant offset from the VarDecl.
15799std::optional<std::pair<
15801 *E,
15803 &Ctx) {
15804 E = E->IgnoreParens();
15805 switch (E->getStmtClass()) {
15806 default:
15807 break;
15808 case Stmt::CStyleCastExprClass:
15809 case Stmt::CXXStaticCastExprClass:
15810 case Stmt::ImplicitCastExprClass: {
15811 auto *CE = cast<CastExpr>(E);
15812 const Expr *From = CE->getSubExpr();
15813 switch (CE->getCastKind()) {
15814 default:
15815 break;
15816 case CK_NoOp:
15817 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15818 case CK_ArrayToPointerDecay:
15819 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15820 case CK_UncheckedDerivedToBase:
15821 case CK_DerivedToBase: {
15822 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
15823 if (!P)
15824 break;
15826 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
15827 }
15828 }
15829 break;
15830 }
15831 case Stmt::CXXThisExprClass: {
15832 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15834 return std::make_pair(Alignment, CharUnits::Zero());
15835 }
15836 case Stmt::UnaryOperatorClass: {
15837 auto *UO = cast<UnaryOperator>(E);
15838 if (UO->getOpcode() == UO_AddrOf)
15840 break;
15841 }
15842 case Stmt::BinaryOperatorClass: {
15843 auto *BO = cast<BinaryOperator>(E);
15844 auto Opcode = BO->getOpcode();
15845 switch (Opcode) {
15846 default:
15847 break;
15848 case BO_Add:
15849 case BO_Sub: {
15850 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15851 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15852 std::swap(LHS, RHS);
15853 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
15854 Ctx);
15855 }
15856 case BO_Comma:
15857 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
15858 }
15859 break;
15860 }
15861 }
15862 return std::nullopt;
15863}
15864
15866 // See if we can compute the alignment of a VarDecl and an offset from it.
15867 std::optional<std::pair<CharUnits, CharUnits>> P =
15869
15870 if (P)
15871 return P->first.alignmentAtOffset(P->second);
15872
15873 // If that failed, return the type's alignment.
15875}
15876
15878 // This is actually a lot of work to potentially be doing on every
15879 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15880 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
15881 return;
15882
15883 // Ignore dependent types.
15884 if (T->isDependentType() || Op->getType()->isDependentType())
15885 return;
15886
15887 // Require that the destination be a pointer type.
15888 const PointerType *DestPtr = T->getAs<PointerType>();
15889 if (!DestPtr) return;
15890
15891 // If the destination has alignment 1, we're done.
15892 QualType DestPointee = DestPtr->getPointeeType();
15893 if (DestPointee->isIncompleteType()) return;
15894 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
15895 if (DestAlign.isOne()) return;
15896
15897 // Require that the source be a pointer type.
15898 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15899 if (!SrcPtr) return;
15900 QualType SrcPointee = SrcPtr->getPointeeType();
15901
15902 // Explicitly allow casts from cv void*. We already implicitly
15903 // allowed casts to cv void*, since they have alignment 1.
15904 // Also allow casts involving incomplete types, which implicitly
15905 // includes 'void'.
15906 if (SrcPointee->isIncompleteType()) return;
15907
15908 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
15909
15910 if (SrcAlign >= DestAlign) return;
15911
15912 Diag(TRange.getBegin(), diag::warn_cast_align)
15913 << Op->getType() << T
15914 << static_cast<unsigned>(SrcAlign.getQuantity())
15915 << static_cast<unsigned>(DestAlign.getQuantity())
15916 << TRange << Op->getSourceRange();
15917}
15918
15919void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15920 const ArraySubscriptExpr *ASE,
15921 bool AllowOnePastEnd, bool IndexNegated) {
15922 // Already diagnosed by the constant evaluator.
15924 return;
15925
15926 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15927 if (IndexExpr->isValueDependent())
15928 return;
15929
15930 const Type *EffectiveType =
15932 BaseExpr = BaseExpr->IgnoreParenCasts();
15933 const ConstantArrayType *ArrayTy =
15934 Context.getAsConstantArrayType(BaseExpr->getType());
15935
15937 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15938
15939 const Type *BaseType =
15940 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15941 bool IsUnboundedArray =
15942 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15943 Context, StrictFlexArraysLevel,
15944 /*IgnoreTemplateOrMacroSubstitution=*/true);
15945 if (EffectiveType->isDependentType() ||
15946 (!IsUnboundedArray && BaseType->isDependentType()))
15947 return;
15948
15950 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15951 return;
15952
15953 llvm::APSInt index = Result.Val.getInt();
15954 if (IndexNegated) {
15955 index.setIsUnsigned(false);
15956 index = -index;
15957 }
15958
15959 if (IsUnboundedArray) {
15960 if (EffectiveType->isFunctionType())
15961 return;
15962 if (index.isUnsigned() || !index.isNegative()) {
15963 const auto &ASTC = getASTContext();
15964 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15965 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15966 if (index.getBitWidth() < AddrBits)
15967 index = index.zext(AddrBits);
15968 std::optional<CharUnits> ElemCharUnits =
15969 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15970 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15971 // pointer) bounds-checking isn't meaningful.
15972 if (!ElemCharUnits || ElemCharUnits->isZero())
15973 return;
15974 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15975 // If index has more active bits than address space, we already know
15976 // we have a bounds violation to warn about. Otherwise, compute
15977 // address of (index + 1)th element, and warn about bounds violation
15978 // only if that address exceeds address space.
15979 if (index.getActiveBits() <= AddrBits) {
15980 bool Overflow;
15981 llvm::APInt Product(index);
15982 Product += 1;
15983 Product = Product.umul_ov(ElemBytes, Overflow);
15984 if (!Overflow && Product.getActiveBits() <= AddrBits)
15985 return;
15986 }
15987
15988 // Need to compute max possible elements in address space, since that
15989 // is included in diag message.
15990 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15991 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15992 MaxElems += 1;
15993 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15994 MaxElems = MaxElems.udiv(ElemBytes);
15995
15996 unsigned DiagID =
15997 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15998 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15999
16000 // Diag message shows element size in bits and in "bytes" (platform-
16001 // dependent CharUnits)
16002 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16003 PDiag(DiagID) << index << AddrBits
16004 << (unsigned)ASTC.toBits(*ElemCharUnits)
16005 << ElemBytes << MaxElems
16006 << MaxElems.getZExtValue()
16007 << IndexExpr->getSourceRange());
16008
16009 const NamedDecl *ND = nullptr;
16010 // Try harder to find a NamedDecl to point at in the note.
16011 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16012 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16013 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16014 ND = DRE->getDecl();
16015 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16016 ND = ME->getMemberDecl();
16017
16018 if (ND)
16019 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
16020 PDiag(diag::note_array_declared_here) << ND);
16021 }
16022 return;
16023 }
16024
16025 if (index.isUnsigned() || !index.isNegative()) {
16026 // It is possible that the type of the base expression after
16027 // IgnoreParenCasts is incomplete, even though the type of the base
16028 // expression before IgnoreParenCasts is complete (see PR39746 for an
16029 // example). In this case we have no information about whether the array
16030 // access exceeds the array bounds. However we can still diagnose an array
16031 // access which precedes the array bounds.
16032 if (BaseType->isIncompleteType())
16033 return;
16034
16035 llvm::APInt size = ArrayTy->getSize();
16036
16037 if (BaseType != EffectiveType) {
16038 // Make sure we're comparing apples to apples when comparing index to
16039 // size.
16040 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
16041 uint64_t array_typesize = Context.getTypeSize(BaseType);
16042
16043 // Handle ptrarith_typesize being zero, such as when casting to void*.
16044 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
16045 if (!ptrarith_typesize)
16046 ptrarith_typesize = Context.getCharWidth();
16047
16048 if (ptrarith_typesize != array_typesize) {
16049 // There's a cast to a different size type involved.
16050 uint64_t ratio = array_typesize / ptrarith_typesize;
16051
16052 // TODO: Be smarter about handling cases where array_typesize is not a
16053 // multiple of ptrarith_typesize.
16054 if (ptrarith_typesize * ratio == array_typesize)
16055 size *= llvm::APInt(size.getBitWidth(), ratio);
16056 }
16057 }
16058
16059 if (size.getBitWidth() > index.getBitWidth())
16060 index = index.zext(size.getBitWidth());
16061 else if (size.getBitWidth() < index.getBitWidth())
16062 size = size.zext(index.getBitWidth());
16063
16064 // For array subscripting the index must be less than size, but for pointer
16065 // arithmetic also allow the index (offset) to be equal to size since
16066 // computing the next address after the end of the array is legal and
16067 // commonly done e.g. in C++ iterators and range-based for loops.
16068 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
16069 return;
16070
16071 // Suppress the warning if the subscript expression (as identified by the
16072 // ']' location) and the index expression are both from macro expansions
16073 // within a system header.
16074 if (ASE) {
16075 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
16076 ASE->getRBracketLoc());
16077 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
16078 SourceLocation IndexLoc =
16079 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
16080 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
16081 return;
16082 }
16083 }
16084
16085 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
16086 : diag::warn_ptr_arith_exceeds_bounds;
16087 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
16088 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
16089
16090 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16091 PDiag(DiagID)
16092 << index << ArrayTy->desugar() << CastMsg
16093 << CastMsgTy << IndexExpr->getSourceRange());
16094 } else {
16095 unsigned DiagID = diag::warn_array_index_precedes_bounds;
16096 if (!ASE) {
16097 DiagID = diag::warn_ptr_arith_precedes_bounds;
16098 if (index.isNegative()) index = -index;
16099 }
16100
16101 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16102 PDiag(DiagID) << index << IndexExpr->getSourceRange());
16103 }
16104
16105 const NamedDecl *ND = nullptr;
16106 // Try harder to find a NamedDecl to point at in the note.
16107 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16108 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16109 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16110 ND = DRE->getDecl();
16111 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16112 ND = ME->getMemberDecl();
16113
16114 if (ND)
16115 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
16116 PDiag(diag::note_array_declared_here) << ND);
16117}
16118
16119void Sema::CheckArrayAccess(const Expr *expr) {
16120 int AllowOnePastEnd = 0;
16121 while (expr) {
16122 expr = expr->IgnoreParenImpCasts();
16123 switch (expr->getStmtClass()) {
16124 case Stmt::ArraySubscriptExprClass: {
16125 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
16126 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
16127 AllowOnePastEnd > 0);
16128 expr = ASE->getBase();
16129 break;
16130 }
16131 case Stmt::MemberExprClass: {
16132 expr = cast<MemberExpr>(expr)->getBase();
16133 break;
16134 }
16135 case Stmt::CXXMemberCallExprClass: {
16136 expr = cast<CXXMemberCallExpr>(expr)->getImplicitObjectArgument();
16137 break;
16138 }
16139 case Stmt::ArraySectionExprClass: {
16140 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
16141 // FIXME: We should probably be checking all of the elements to the
16142 // 'length' here as well.
16143 if (ASE->getLowerBound())
16144 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
16145 /*ASE=*/nullptr, AllowOnePastEnd > 0);
16146 return;
16147 }
16148 case Stmt::UnaryOperatorClass: {
16149 // Only unwrap the * and & unary operators
16150 const UnaryOperator *UO = cast<UnaryOperator>(expr);
16151 expr = UO->getSubExpr();
16152 switch (UO->getOpcode()) {
16153 case UO_AddrOf:
16154 AllowOnePastEnd++;
16155 break;
16156 case UO_Deref:
16157 AllowOnePastEnd--;
16158 break;
16159 default:
16160 return;
16161 }
16162 break;
16163 }
16164 case Stmt::ConditionalOperatorClass: {
16165 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
16166 if (const Expr *lhs = cond->getLHS())
16167 CheckArrayAccess(lhs);
16168 if (const Expr *rhs = cond->getRHS())
16169 CheckArrayAccess(rhs);
16170 return;
16171 }
16172 case Stmt::CXXOperatorCallExprClass: {
16173 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
16174 for (const auto *Arg : OCE->arguments())
16175 CheckArrayAccess(Arg);
16176 return;
16177 }
16178 default:
16179 return;
16180 }
16181 }
16182}
16183
16185 Expr *RHS, bool isProperty) {
16186 // Check if RHS is an Objective-C object literal, which also can get
16187 // immediately zapped in a weak reference. Note that we explicitly
16188 // allow ObjCStringLiterals, since those are designed to never really die.
16189 RHS = RHS->IgnoreParenImpCasts();
16190
16191 // This enum needs to match with the 'select' in
16192 // warn_objc_arc_literal_assign (off-by-1).
16194 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
16195 return false;
16196
16197 S.Diag(Loc, diag::warn_arc_literal_assign)
16198 << (unsigned) Kind
16199 << (isProperty ? 0 : 1)
16200 << RHS->getSourceRange();
16201
16202 return true;
16203}
16204
16207 Expr *RHS, bool isProperty) {
16208 // Strip off any implicit cast added to get to the one ARC-specific.
16209 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16210 if (cast->getCastKind() == CK_ARCConsumeObject) {
16211 S.Diag(Loc, diag::warn_arc_retained_assign)
16213 << (isProperty ? 0 : 1)
16214 << RHS->getSourceRange();
16215 return true;
16216 }
16217 RHS = cast->getSubExpr();
16218 }
16219
16220 if (LT == Qualifiers::OCL_Weak &&
16221 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16222 return true;
16223
16224 return false;
16225}
16226
16228 QualType LHS, Expr *RHS) {
16230
16232 return false;
16233
16234 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16235 return true;
16236
16237 return false;
16238}
16239
16241 Expr *LHS, Expr *RHS) {
16242 QualType LHSType;
16243 // PropertyRef on LHS type need be directly obtained from
16244 // its declaration as it has a PseudoType.
16246 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16247 if (PRE && !PRE->isImplicitProperty()) {
16248 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16249 if (PD)
16250 LHSType = PD->getType();
16251 }
16252
16253 if (LHSType.isNull())
16254 LHSType = LHS->getType();
16255
16257
16258 if (LT == Qualifiers::OCL_Weak) {
16259 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16261 }
16262
16263 if (checkUnsafeAssigns(Loc, LHSType, RHS))
16264 return;
16265
16266 // FIXME. Check for other life times.
16267 if (LT != Qualifiers::OCL_None)
16268 return;
16269
16270 if (PRE) {
16271 if (PRE->isImplicitProperty())
16272 return;
16273 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16274 if (!PD)
16275 return;
16276
16277 unsigned Attributes = PD->getPropertyAttributes();
16278 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16279 // when 'assign' attribute was not explicitly specified
16280 // by user, ignore it and rely on property type itself
16281 // for lifetime info.
16282 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16283 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16284 LHSType->isObjCRetainableType())
16285 return;
16286
16287 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16288 if (cast->getCastKind() == CK_ARCConsumeObject) {
16289 Diag(Loc, diag::warn_arc_retained_property_assign)
16290 << RHS->getSourceRange();
16291 return;
16292 }
16293 RHS = cast->getSubExpr();
16294 }
16295 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16296 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16297 return;
16298 }
16299 }
16300}
16301
16302//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16303
16304static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16305 SourceLocation StmtLoc,
16306 const NullStmt *Body) {
16307 // Do not warn if the body is a macro that expands to nothing, e.g:
16308 //
16309 // #define CALL(x)
16310 // if (condition)
16311 // CALL(0);
16312 if (Body->hasLeadingEmptyMacro())
16313 return false;
16314
16315 // Get line numbers of statement and body.
16316 bool StmtLineInvalid;
16317 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16318 &StmtLineInvalid);
16319 if (StmtLineInvalid)
16320 return false;
16321
16322 bool BodyLineInvalid;
16323 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16324 &BodyLineInvalid);
16325 if (BodyLineInvalid)
16326 return false;
16327
16328 // Warn if null statement and body are on the same line.
16329 if (StmtLine != BodyLine)
16330 return false;
16331
16332 return true;
16333}
16334
16336 const Stmt *Body,
16337 unsigned DiagID) {
16338 // Since this is a syntactic check, don't emit diagnostic for template
16339 // instantiations, this just adds noise.
16341 return;
16342
16343 // The body should be a null statement.
16344 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16345 if (!NBody)
16346 return;
16347
16348 // Do the usual checks.
16349 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16350 return;
16351
16352 Diag(NBody->getSemiLoc(), DiagID);
16353 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16354}
16355
16357 const Stmt *PossibleBody) {
16358 assert(!CurrentInstantiationScope); // Ensured by caller
16359
16360 SourceLocation StmtLoc;
16361 const Stmt *Body;
16362 unsigned DiagID;
16363 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16364 StmtLoc = FS->getRParenLoc();
16365 Body = FS->getBody();
16366 DiagID = diag::warn_empty_for_body;
16367 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16368 StmtLoc = WS->getRParenLoc();
16369 Body = WS->getBody();
16370 DiagID = diag::warn_empty_while_body;
16371 } else
16372 return; // Neither `for' nor `while'.
16373
16374 // The body should be a null statement.
16375 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16376 if (!NBody)
16377 return;
16378
16379 // Skip expensive checks if diagnostic is disabled.
16380 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16381 return;
16382
16383 // Do the usual checks.
16384 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16385 return;
16386
16387 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16388 // noise level low, emit diagnostics only if for/while is followed by a
16389 // CompoundStmt, e.g.:
16390 // for (int i = 0; i < n; i++);
16391 // {
16392 // a(i);
16393 // }
16394 // or if for/while is followed by a statement with more indentation
16395 // than for/while itself:
16396 // for (int i = 0; i < n; i++);
16397 // a(i);
16398 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16399 if (!ProbableTypo) {
16400 bool BodyColInvalid;
16401 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16402 PossibleBody->getBeginLoc(), &BodyColInvalid);
16403 if (BodyColInvalid)
16404 return;
16405
16406 bool StmtColInvalid;
16407 unsigned StmtCol =
16408 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16409 if (StmtColInvalid)
16410 return;
16411
16412 if (BodyCol > StmtCol)
16413 ProbableTypo = true;
16414 }
16415
16416 if (ProbableTypo) {
16417 Diag(NBody->getSemiLoc(), DiagID);
16418 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16419 }
16420}
16421
16422//===--- CHECK: Warn on self move with std::move. -------------------------===//
16423
16424void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16425 SourceLocation OpLoc) {
16426 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16427 return;
16428
16430 return;
16431
16432 // Strip parens and casts away.
16433 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16434 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16435
16436 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16437 // which we can treat as an inlined std::move
16438 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
16439 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16440 RHSExpr = CE->getArg(0);
16441 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
16442 CXXSCE && CXXSCE->isXValue())
16443 RHSExpr = CXXSCE->getSubExpr();
16444 else
16445 return;
16446
16447 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16448 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16449
16450 // Two DeclRefExpr's, check that the decls are the same.
16451 if (LHSDeclRef && RHSDeclRef) {
16452 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16453 return;
16454 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16455 RHSDeclRef->getDecl()->getCanonicalDecl())
16456 return;
16457
16458 auto D = Diag(OpLoc, diag::warn_self_move)
16459 << LHSExpr->getType() << LHSExpr->getSourceRange()
16460 << RHSExpr->getSourceRange();
16461 if (const FieldDecl *F =
16463 D << 1 << F
16464 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
16465 else
16466 D << 0;
16467 return;
16468 }
16469
16470 // Member variables require a different approach to check for self moves.
16471 // MemberExpr's are the same if every nested MemberExpr refers to the same
16472 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16473 // the base Expr's are CXXThisExpr's.
16474 const Expr *LHSBase = LHSExpr;
16475 const Expr *RHSBase = RHSExpr;
16476 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16477 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16478 if (!LHSME || !RHSME)
16479 return;
16480
16481 while (LHSME && RHSME) {
16482 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16483 RHSME->getMemberDecl()->getCanonicalDecl())
16484 return;
16485
16486 LHSBase = LHSME->getBase();
16487 RHSBase = RHSME->getBase();
16488 LHSME = dyn_cast<MemberExpr>(LHSBase);
16489 RHSME = dyn_cast<MemberExpr>(RHSBase);
16490 }
16491
16492 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16493 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16494 if (LHSDeclRef && RHSDeclRef) {
16495 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16496 return;
16497 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16498 RHSDeclRef->getDecl()->getCanonicalDecl())
16499 return;
16500
16501 Diag(OpLoc, diag::warn_self_move)
16502 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16503 << RHSExpr->getSourceRange();
16504 return;
16505 }
16506
16507 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16508 Diag(OpLoc, diag::warn_self_move)
16509 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16510 << RHSExpr->getSourceRange();
16511}
16512
16513//===--- Layout compatibility ----------------------------------------------//
16514
16515static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16516
16517/// Check if two enumeration types are layout-compatible.
16518static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16519 const EnumDecl *ED2) {
16520 // C++11 [dcl.enum] p8:
16521 // Two enumeration types are layout-compatible if they have the same
16522 // underlying type.
16523 return ED1->isComplete() && ED2->isComplete() &&
16524 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16525}
16526
16527/// Check if two fields are layout-compatible.
16528/// Can be used on union members, which are exempt from alignment requirement
16529/// of common initial sequence.
16530static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16531 const FieldDecl *Field2,
16532 bool AreUnionMembers = false) {
16533#ifndef NDEBUG
16534 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16535 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16536 assert(((Field1Parent->isStructureOrClassType() &&
16537 Field2Parent->isStructureOrClassType()) ||
16538 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16539 "Can't evaluate layout compatibility between a struct field and a "
16540 "union field.");
16541 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16542 (AreUnionMembers && Field1Parent->isUnionType())) &&
16543 "AreUnionMembers should be 'true' for union fields (only).");
16544#endif
16545
16546 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16547 return false;
16548
16549 if (Field1->isBitField() != Field2->isBitField())
16550 return false;
16551
16552 if (Field1->isBitField()) {
16553 // Make sure that the bit-fields are the same length.
16554 unsigned Bits1 = Field1->getBitWidthValue();
16555 unsigned Bits2 = Field2->getBitWidthValue();
16556
16557 if (Bits1 != Bits2)
16558 return false;
16559 }
16560
16561 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16562 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16563 return false;
16564
16565 if (!AreUnionMembers &&
16566 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16567 return false;
16568
16569 return true;
16570}
16571
16572/// Check if two standard-layout structs are layout-compatible.
16573/// (C++11 [class.mem] p17)
16574static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16575 const RecordDecl *RD2) {
16576 // Get to the class where the fields are declared
16577 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
16578 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16579
16580 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
16581 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16582
16583 // Check the fields.
16584 return llvm::equal(RD1->fields(), RD2->fields(),
16585 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16586 return isLayoutCompatible(C, F1, F2);
16587 });
16588}
16589
16590/// Check if two standard-layout unions are layout-compatible.
16591/// (C++11 [class.mem] p18)
16592static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16593 const RecordDecl *RD2) {
16594 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16595 RD2->fields());
16596
16597 for (auto *Field1 : RD1->fields()) {
16598 auto It = llvm::find_if(UnmatchedFields, [&](const FieldDecl *Field2) {
16599 return isLayoutCompatible(C, Field1, Field2, /*IsUnionMember=*/true);
16600 });
16601 if (It == UnmatchedFields.end())
16602 return false;
16603 [[maybe_unused]] bool Result = UnmatchedFields.erase(*It);
16604 assert(Result);
16605 }
16606
16607 return UnmatchedFields.empty();
16608}
16609
16610static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16611 const RecordDecl *RD2) {
16612 if (RD1->isUnion() != RD2->isUnion())
16613 return false;
16614
16615 if (RD1->isUnion())
16616 return isLayoutCompatibleUnion(C, RD1, RD2);
16617 else
16618 return isLayoutCompatibleStruct(C, RD1, RD2);
16619}
16620
16621/// Check if two types are layout-compatible in C++11 sense.
16622static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16623 if (T1.isNull() || T2.isNull())
16624 return false;
16625
16626 // C++20 [basic.types] p11:
16627 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16628 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16629 // or layout-compatible standard-layout class types (11.4).
16632
16633 if (C.hasSameType(T1, T2))
16634 return true;
16635
16636 const Type::TypeClass TC1 = T1->getTypeClass();
16637 const Type::TypeClass TC2 = T2->getTypeClass();
16638
16639 if (TC1 != TC2)
16640 return false;
16641
16642 if (TC1 == Type::Enum)
16643 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
16644 if (TC1 == Type::Record) {
16645 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16646 return false;
16647
16649 T2->castAsRecordDecl());
16650 }
16651
16652 return false;
16653}
16654
16656 return isLayoutCompatible(getASTContext(), T1, T2);
16657}
16658
16659//===-------------- Pointer interconvertibility ----------------------------//
16660
16662 const TypeSourceInfo *Derived) {
16663 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16664 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16665
16666 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16667 getASTContext().hasSameType(BaseT, DerivedT))
16668 return true;
16669
16670 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
16671 return false;
16672
16673 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16674 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16675 return true;
16676
16677 return false;
16678}
16679
16680//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16681
16682/// Given a type tag expression find the type tag itself.
16683///
16684/// \param TypeExpr Type tag expression, as it appears in user's code.
16685///
16686/// \param VD Declaration of an identifier that appears in a type tag.
16687///
16688/// \param MagicValue Type tag magic value.
16689///
16690/// \param isConstantEvaluated whether the evalaution should be performed in
16691
16692/// constant context.
16693static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16694 const ValueDecl **VD, uint64_t *MagicValue,
16695 bool isConstantEvaluated) {
16696 while(true) {
16697 if (!TypeExpr)
16698 return false;
16699
16700 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16701
16702 switch (TypeExpr->getStmtClass()) {
16703 case Stmt::UnaryOperatorClass: {
16704 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16705 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16706 TypeExpr = UO->getSubExpr();
16707 continue;
16708 }
16709 return false;
16710 }
16711
16712 case Stmt::DeclRefExprClass: {
16713 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16714 *VD = DRE->getDecl();
16715 return true;
16716 }
16717
16718 case Stmt::IntegerLiteralClass: {
16719 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16720 llvm::APInt MagicValueAPInt = IL->getValue();
16721 if (MagicValueAPInt.getActiveBits() <= 64) {
16722 *MagicValue = MagicValueAPInt.getZExtValue();
16723 return true;
16724 } else
16725 return false;
16726 }
16727
16728 case Stmt::BinaryConditionalOperatorClass:
16729 case Stmt::ConditionalOperatorClass: {
16730 const AbstractConditionalOperator *ACO =
16732 bool Result;
16733 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16734 isConstantEvaluated)) {
16735 if (Result)
16736 TypeExpr = ACO->getTrueExpr();
16737 else
16738 TypeExpr = ACO->getFalseExpr();
16739 continue;
16740 }
16741 return false;
16742 }
16743
16744 case Stmt::BinaryOperatorClass: {
16745 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16746 if (BO->getOpcode() == BO_Comma) {
16747 TypeExpr = BO->getRHS();
16748 continue;
16749 }
16750 return false;
16751 }
16752
16753 default:
16754 return false;
16755 }
16756 }
16757}
16758
16759/// Retrieve the C type corresponding to type tag TypeExpr.
16760///
16761/// \param TypeExpr Expression that specifies a type tag.
16762///
16763/// \param MagicValues Registered magic values.
16764///
16765/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16766/// kind.
16767///
16768/// \param TypeInfo Information about the corresponding C type.
16769///
16770/// \param isConstantEvaluated whether the evalaution should be performed in
16771/// constant context.
16772///
16773/// \returns true if the corresponding C type was found.
16775 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16776 const ASTContext &Ctx,
16777 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16778 *MagicValues,
16779 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16780 bool isConstantEvaluated) {
16781 FoundWrongKind = false;
16782
16783 // Variable declaration that has type_tag_for_datatype attribute.
16784 const ValueDecl *VD = nullptr;
16785
16786 uint64_t MagicValue;
16787
16788 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16789 return false;
16790
16791 if (VD) {
16792 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16793 if (I->getArgumentKind() != ArgumentKind) {
16794 FoundWrongKind = true;
16795 return false;
16796 }
16797 TypeInfo.Type = I->getMatchingCType();
16798 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16799 TypeInfo.MustBeNull = I->getMustBeNull();
16800 return true;
16801 }
16802 return false;
16803 }
16804
16805 if (!MagicValues)
16806 return false;
16807
16808 llvm::DenseMap<Sema::TypeTagMagicValue,
16810 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16811 if (I == MagicValues->end())
16812 return false;
16813
16814 TypeInfo = I->second;
16815 return true;
16816}
16817
16819 uint64_t MagicValue, QualType Type,
16820 bool LayoutCompatible,
16821 bool MustBeNull) {
16822 if (!TypeTagForDatatypeMagicValues)
16823 TypeTagForDatatypeMagicValues.reset(
16824 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16825
16826 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16827 (*TypeTagForDatatypeMagicValues)[Magic] =
16828 TypeTagData(Type, LayoutCompatible, MustBeNull);
16829}
16830
16831static bool IsSameCharType(QualType T1, QualType T2) {
16832 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16833 if (!BT1)
16834 return false;
16835
16836 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16837 if (!BT2)
16838 return false;
16839
16840 BuiltinType::Kind T1Kind = BT1->getKind();
16841 BuiltinType::Kind T2Kind = BT2->getKind();
16842
16843 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16844 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16845 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16846 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16847}
16848
16849void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16850 const ArrayRef<const Expr *> ExprArgs,
16851 SourceLocation CallSiteLoc) {
16852 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16853 bool IsPointerAttr = Attr->getIsPointer();
16854
16855 // Retrieve the argument representing the 'type_tag'.
16856 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16857 if (TypeTagIdxAST >= ExprArgs.size()) {
16858 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16859 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16860 return;
16861 }
16862 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16863 bool FoundWrongKind;
16864 TypeTagData TypeInfo;
16865 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16866 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16867 TypeInfo, isConstantEvaluatedContext())) {
16868 if (FoundWrongKind)
16869 Diag(TypeTagExpr->getExprLoc(),
16870 diag::warn_type_tag_for_datatype_wrong_kind)
16871 << TypeTagExpr->getSourceRange();
16872 return;
16873 }
16874
16875 // Retrieve the argument representing the 'arg_idx'.
16876 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16877 if (ArgumentIdxAST >= ExprArgs.size()) {
16878 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16879 << 1 << Attr->getArgumentIdx().getSourceIndex();
16880 return;
16881 }
16882 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16883 if (IsPointerAttr) {
16884 // Skip implicit cast of pointer to `void *' (as a function argument).
16885 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16886 if (ICE->getType()->isVoidPointerType() &&
16887 ICE->getCastKind() == CK_BitCast)
16888 ArgumentExpr = ICE->getSubExpr();
16889 }
16890 QualType ArgumentType = ArgumentExpr->getType();
16891
16892 // Passing a `void*' pointer shouldn't trigger a warning.
16893 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16894 return;
16895
16896 if (TypeInfo.MustBeNull) {
16897 // Type tag with matching void type requires a null pointer.
16898 if (!ArgumentExpr->isNullPointerConstant(Context,
16900 Diag(ArgumentExpr->getExprLoc(),
16901 diag::warn_type_safety_null_pointer_required)
16902 << ArgumentKind->getName()
16903 << ArgumentExpr->getSourceRange()
16904 << TypeTagExpr->getSourceRange();
16905 }
16906 return;
16907 }
16908
16909 QualType RequiredType = TypeInfo.Type;
16910 if (IsPointerAttr)
16911 RequiredType = Context.getPointerType(RequiredType);
16912
16913 bool mismatch = false;
16914 if (!TypeInfo.LayoutCompatible) {
16915 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16916
16917 // C++11 [basic.fundamental] p1:
16918 // Plain char, signed char, and unsigned char are three distinct types.
16919 //
16920 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16921 // char' depending on the current char signedness mode.
16922 if (mismatch)
16923 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16924 RequiredType->getPointeeType())) ||
16925 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16926 mismatch = false;
16927 } else
16928 if (IsPointerAttr)
16929 mismatch = !isLayoutCompatible(Context,
16930 ArgumentType->getPointeeType(),
16931 RequiredType->getPointeeType());
16932 else
16933 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16934
16935 if (mismatch)
16936 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16937 << ArgumentType << ArgumentKind
16938 << TypeInfo.LayoutCompatible << RequiredType
16939 << ArgumentExpr->getSourceRange()
16940 << TypeTagExpr->getSourceRange();
16941}
16942
16943void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16944 CharUnits Alignment) {
16945 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
16946 Alignment);
16947}
16948
16950 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16951 const NamedDecl *ND = m.RD;
16952 if (ND->getName().empty()) {
16953 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16954 ND = TD;
16955 }
16956 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16957 << m.MD << ND << m.E->getSourceRange();
16958 }
16960}
16961
16963 E = E->IgnoreParens();
16964 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16965 return;
16966 if (isa<UnaryOperator>(E) &&
16967 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16968 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16969 if (isa<MemberExpr>(Op)) {
16970 auto &MisalignedMembersForExpr =
16972 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
16973 if (MA != MisalignedMembersForExpr.end() &&
16974 (T->isDependentType() || T->isIntegerType() ||
16975 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16976 Context.getTypeAlignInChars(
16977 T->getPointeeType()) <= MA->Alignment))))
16978 MisalignedMembersForExpr.erase(MA);
16979 }
16980 }
16981}
16982
16984 Expr *E,
16985 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16986 Action) {
16987 const auto *ME = dyn_cast<MemberExpr>(E);
16988 if (!ME)
16989 return;
16990
16991 // No need to check expressions with an __unaligned-qualified type.
16992 if (E->getType().getQualifiers().hasUnaligned())
16993 return;
16994
16995 // For a chain of MemberExpr like "a.b.c.d" this list
16996 // will keep FieldDecl's like [d, c, b].
16997 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16998 const MemberExpr *TopME = nullptr;
16999 bool AnyIsPacked = false;
17000 do {
17001 QualType BaseType = ME->getBase()->getType();
17002 if (BaseType->isDependentType())
17003 return;
17004 if (ME->isArrow())
17005 BaseType = BaseType->getPointeeType();
17006 auto *RD = BaseType->castAsRecordDecl();
17007 if (RD->isInvalidDecl())
17008 return;
17009
17010 ValueDecl *MD = ME->getMemberDecl();
17011 auto *FD = dyn_cast<FieldDecl>(MD);
17012 // We do not care about non-data members.
17013 if (!FD || FD->isInvalidDecl())
17014 return;
17015
17016 AnyIsPacked =
17017 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17018 ReverseMemberChain.push_back(FD);
17019
17020 TopME = ME;
17021 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
17022 } while (ME);
17023 assert(TopME && "We did not compute a topmost MemberExpr!");
17024
17025 // Not the scope of this diagnostic.
17026 if (!AnyIsPacked)
17027 return;
17028
17029 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17030 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
17031 // TODO: The innermost base of the member expression may be too complicated.
17032 // For now, just disregard these cases. This is left for future
17033 // improvement.
17034 if (!DRE && !isa<CXXThisExpr>(TopBase))
17035 return;
17036
17037 // Alignment expected by the whole expression.
17038 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
17039
17040 // No need to do anything else with this case.
17041 if (ExpectedAlignment.isOne())
17042 return;
17043
17044 // Synthesize offset of the whole access.
17045 CharUnits Offset;
17046 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
17047 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
17048
17049 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17050 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17051 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
17052
17053 // The base expression of the innermost MemberExpr may give
17054 // stronger guarantees than the class containing the member.
17055 if (DRE && !TopME->isArrow()) {
17056 const ValueDecl *VD = DRE->getDecl();
17057 if (!VD->getType()->isReferenceType())
17058 CompleteObjectAlignment =
17059 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
17060 }
17061
17062 // Check if the synthesized offset fulfills the alignment.
17063 if (!Offset.isMultipleOf(ExpectedAlignment) ||
17064 // It may fulfill the offset it but the effective alignment may still be
17065 // lower than the expected expression alignment.
17066 CompleteObjectAlignment < ExpectedAlignment) {
17067 // If this happens, we want to determine a sensible culprit of this.
17068 // Intuitively, watching the chain of member expressions from right to
17069 // left, we start with the required alignment (as required by the field
17070 // type) but some packed attribute in that chain has reduced the alignment.
17071 // It may happen that another packed structure increases it again. But if
17072 // we are here such increase has not been enough. So pointing the first
17073 // FieldDecl that either is packed or else its RecordDecl is,
17074 // seems reasonable.
17075 FieldDecl *FD = nullptr;
17076 CharUnits Alignment;
17077 for (FieldDecl *FDI : ReverseMemberChain) {
17078 if (FDI->hasAttr<PackedAttr>() ||
17079 FDI->getParent()->hasAttr<PackedAttr>()) {
17080 FD = FDI;
17081 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
17082 Context.getTypeAlignInChars(
17083 Context.getCanonicalTagType(FD->getParent())));
17084 break;
17085 }
17086 }
17087 assert(FD && "We did not find a packed FieldDecl!");
17088 Action(E, FD->getParent(), FD, Alignment);
17089 }
17090}
17091
17092void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17093 using namespace std::placeholders;
17094
17096 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
17097 _2, _3, _4));
17098}
17099
17101 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17102 if (checkArgCount(TheCall, 1))
17103 return true;
17104
17105 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
17106 if (A.isInvalid())
17107 return true;
17108
17109 TheCall->setArg(0, A.get());
17110 QualType TyA = A.get()->getType();
17111
17112 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
17113 ArgTyRestr, 1))
17114 return true;
17115
17116 TheCall->setType(TyA);
17117 return false;
17118}
17119
17120bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
17121 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17122 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
17123 TheCall->setType(*Res);
17124 return false;
17125 }
17126 return true;
17127}
17128
17130 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
17131 if (!Res)
17132 return true;
17133
17134 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
17135 TheCall->setType(VecTy0->getElementType());
17136 else
17137 TheCall->setType(*Res);
17138
17139 return false;
17140}
17141
17143 SourceLocation Loc) {
17145 R = RHS->getEnumCoercedType(S.Context);
17146 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
17148 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
17149 << LHS->getSourceRange() << RHS->getSourceRange()
17150 << /*Arithmetic Between*/ 0 << L << R;
17151 }
17152 return false;
17153}
17154
17155/// Check if all arguments have the same type. If the types don't match, emit an
17156/// error message and return true. Otherwise return false.
17157///
17158/// For scalars we directly compare their unqualified types. But even if we
17159/// compare unqualified vector types, a difference in qualifiers in the element
17160/// types can make the vector types be considered not equal. For example,
17161/// vector of 4 'const float' values vs vector of 4 'float' values.
17162/// So we compare unqualified types of their elements and number of elements.
17164 ArrayRef<Expr *> Args) {
17165 assert(!Args.empty() && "Should have at least one argument.");
17166
17167 Expr *Arg0 = Args.front();
17168 QualType Ty0 = Arg0->getType();
17169
17170 auto EmitError = [&](Expr *ArgI) {
17171 SemaRef.Diag(Arg0->getBeginLoc(),
17172 diag::err_typecheck_call_different_arg_types)
17173 << Arg0->getType() << ArgI->getType();
17174 };
17175
17176 // Compare scalar types.
17177 if (!Ty0->isVectorType()) {
17178 for (Expr *ArgI : Args.drop_front())
17179 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
17180 EmitError(ArgI);
17181 return true;
17182 }
17183
17184 return false;
17185 }
17186
17187 // Compare vector types.
17188 const auto *Vec0 = Ty0->castAs<VectorType>();
17189 for (Expr *ArgI : Args.drop_front()) {
17190 const auto *VecI = ArgI->getType()->getAs<VectorType>();
17191 if (!VecI ||
17192 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
17193 VecI->getElementType()) ||
17194 Vec0->getNumElements() != VecI->getNumElements()) {
17195 EmitError(ArgI);
17196 return true;
17197 }
17198 }
17199
17200 return false;
17201}
17202
17203std::optional<QualType>
17205 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17206 if (checkArgCount(TheCall, 2))
17207 return std::nullopt;
17208
17210 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
17211 return std::nullopt;
17212
17213 Expr *Args[2];
17214 for (int I = 0; I < 2; ++I) {
17215 ExprResult Converted =
17216 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17217 if (Converted.isInvalid())
17218 return std::nullopt;
17219 Args[I] = Converted.get();
17220 }
17221
17222 SourceLocation LocA = Args[0]->getBeginLoc();
17223 QualType TyA = Args[0]->getType();
17224
17225 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
17226 return std::nullopt;
17227
17228 if (checkBuiltinVectorMathArgTypes(*this, Args))
17229 return std::nullopt;
17230
17231 TheCall->setArg(0, Args[0]);
17232 TheCall->setArg(1, Args[1]);
17233 return TyA;
17234}
17235
17237 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17238 if (checkArgCount(TheCall, 3))
17239 return true;
17240
17241 SourceLocation Loc = TheCall->getExprLoc();
17242 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
17243 TheCall->getArg(1), Loc) ||
17244 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
17245 TheCall->getArg(2), Loc))
17246 return true;
17247
17248 Expr *Args[3];
17249 for (int I = 0; I < 3; ++I) {
17250 ExprResult Converted =
17251 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17252 if (Converted.isInvalid())
17253 return true;
17254 Args[I] = Converted.get();
17255 }
17256
17257 int ArgOrdinal = 1;
17258 for (Expr *Arg : Args) {
17259 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
17260 ArgTyRestr, ArgOrdinal++))
17261 return true;
17262 }
17263
17264 if (checkBuiltinVectorMathArgTypes(*this, Args))
17265 return true;
17266
17267 for (int I = 0; I < 3; ++I)
17268 TheCall->setArg(I, Args[I]);
17269
17270 TheCall->setType(Args[0]->getType());
17271 return false;
17272}
17273
17274bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17275 if (checkArgCount(TheCall, 1))
17276 return true;
17277
17278 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17279 if (A.isInvalid())
17280 return true;
17281
17282 TheCall->setArg(0, A.get());
17283 return false;
17284}
17285
17286bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17287 if (checkArgCount(TheCall, 1))
17288 return true;
17289
17290 ExprResult Arg = TheCall->getArg(0);
17291 QualType TyArg = Arg.get()->getType();
17292
17293 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17294 return Diag(TheCall->getArg(0)->getBeginLoc(),
17295 diag::err_builtin_invalid_arg_type)
17296 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17297
17298 TheCall->setType(TyArg);
17299 return false;
17300}
17301
17302ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17303 ExprResult CallResult) {
17304 if (checkArgCount(TheCall, 1))
17305 return ExprError();
17306
17307 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17308 if (MatrixArg.isInvalid())
17309 return MatrixArg;
17310 Expr *Matrix = MatrixArg.get();
17311
17312 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17313 if (!MType) {
17314 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17315 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17316 << Matrix->getType();
17317 return ExprError();
17318 }
17319
17320 // Create returned matrix type by swapping rows and columns of the argument
17321 // matrix type.
17322 QualType ResultType = Context.getConstantMatrixType(
17323 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17324
17325 // Change the return type to the type of the returned matrix.
17326 TheCall->setType(ResultType);
17327
17328 // Update call argument to use the possibly converted matrix argument.
17329 TheCall->setArg(0, Matrix);
17330 return CallResult;
17331}
17332
17333// Get and verify the matrix dimensions.
17334static std::optional<unsigned>
17336 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
17337 if (!Value) {
17338 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17339 << Name;
17340 return {};
17341 }
17342 uint64_t Dim = Value->getZExtValue();
17343 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17344 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17345 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17346 return {};
17347 }
17348 return Dim;
17349}
17350
17351ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17352 ExprResult CallResult) {
17353 if (!getLangOpts().MatrixTypes) {
17354 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17355 return ExprError();
17356 }
17357
17358 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17360 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17361 << /*column*/ 1 << /*load*/ 0;
17362 return ExprError();
17363 }
17364
17365 if (checkArgCount(TheCall, 4))
17366 return ExprError();
17367
17368 unsigned PtrArgIdx = 0;
17369 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17370 Expr *RowsExpr = TheCall->getArg(1);
17371 Expr *ColumnsExpr = TheCall->getArg(2);
17372 Expr *StrideExpr = TheCall->getArg(3);
17373
17374 bool ArgError = false;
17375
17376 // Check pointer argument.
17377 {
17379 if (PtrConv.isInvalid())
17380 return PtrConv;
17381 PtrExpr = PtrConv.get();
17382 TheCall->setArg(0, PtrExpr);
17383 if (PtrExpr->isTypeDependent()) {
17384 TheCall->setType(Context.DependentTy);
17385 return TheCall;
17386 }
17387 }
17388
17389 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17390 QualType ElementTy;
17391 if (!PtrTy) {
17392 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17393 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17394 << PtrExpr->getType();
17395 ArgError = true;
17396 } else {
17397 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17398
17400 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17401 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17402 << /* no fp */ 0 << PtrExpr->getType();
17403 ArgError = true;
17404 }
17405 }
17406
17407 // Apply default Lvalue conversions and convert the expression to size_t.
17408 auto ApplyArgumentConversions = [this](Expr *E) {
17410 if (Conv.isInvalid())
17411 return Conv;
17412
17413 return tryConvertExprToType(Conv.get(), Context.getSizeType());
17414 };
17415
17416 // Apply conversion to row and column expressions.
17417 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17418 if (!RowsConv.isInvalid()) {
17419 RowsExpr = RowsConv.get();
17420 TheCall->setArg(1, RowsExpr);
17421 } else
17422 RowsExpr = nullptr;
17423
17424 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17425 if (!ColumnsConv.isInvalid()) {
17426 ColumnsExpr = ColumnsConv.get();
17427 TheCall->setArg(2, ColumnsExpr);
17428 } else
17429 ColumnsExpr = nullptr;
17430
17431 // If any part of the result matrix type is still pending, just use
17432 // Context.DependentTy, until all parts are resolved.
17433 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17434 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17435 TheCall->setType(Context.DependentTy);
17436 return CallResult;
17437 }
17438
17439 // Check row and column dimensions.
17440 std::optional<unsigned> MaybeRows;
17441 if (RowsExpr)
17442 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17443
17444 std::optional<unsigned> MaybeColumns;
17445 if (ColumnsExpr)
17446 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17447
17448 // Check stride argument.
17449 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17450 if (StrideConv.isInvalid())
17451 return ExprError();
17452 StrideExpr = StrideConv.get();
17453 TheCall->setArg(3, StrideExpr);
17454
17455 if (MaybeRows) {
17456 if (std::optional<llvm::APSInt> Value =
17457 StrideExpr->getIntegerConstantExpr(Context)) {
17458 uint64_t Stride = Value->getZExtValue();
17459 if (Stride < *MaybeRows) {
17460 Diag(StrideExpr->getBeginLoc(),
17461 diag::err_builtin_matrix_stride_too_small);
17462 ArgError = true;
17463 }
17464 }
17465 }
17466
17467 if (ArgError || !MaybeRows || !MaybeColumns)
17468 return ExprError();
17469
17470 TheCall->setType(
17471 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17472 return CallResult;
17473}
17474
17475ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17476 ExprResult CallResult) {
17477 if (!getLangOpts().MatrixTypes) {
17478 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17479 return ExprError();
17480 }
17481
17482 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17484 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17485 << /*column*/ 1 << /*store*/ 1;
17486 return ExprError();
17487 }
17488
17489 if (checkArgCount(TheCall, 3))
17490 return ExprError();
17491
17492 unsigned PtrArgIdx = 1;
17493 Expr *MatrixExpr = TheCall->getArg(0);
17494 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17495 Expr *StrideExpr = TheCall->getArg(2);
17496
17497 bool ArgError = false;
17498
17499 {
17500 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17501 if (MatrixConv.isInvalid())
17502 return MatrixConv;
17503 MatrixExpr = MatrixConv.get();
17504 TheCall->setArg(0, MatrixExpr);
17505 }
17506 if (MatrixExpr->isTypeDependent()) {
17507 TheCall->setType(Context.DependentTy);
17508 return TheCall;
17509 }
17510
17511 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17512 if (!MatrixTy) {
17513 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17514 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17515 ArgError = true;
17516 }
17517
17518 {
17520 if (PtrConv.isInvalid())
17521 return PtrConv;
17522 PtrExpr = PtrConv.get();
17523 TheCall->setArg(1, PtrExpr);
17524 if (PtrExpr->isTypeDependent()) {
17525 TheCall->setType(Context.DependentTy);
17526 return TheCall;
17527 }
17528 }
17529
17530 // Check pointer argument.
17531 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17532 if (!PtrTy) {
17533 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17534 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17535 << PtrExpr->getType();
17536 ArgError = true;
17537 } else {
17538 QualType ElementTy = PtrTy->getPointeeType();
17539 if (ElementTy.isConstQualified()) {
17540 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17541 ArgError = true;
17542 }
17543 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17544 if (MatrixTy &&
17545 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17546 Diag(PtrExpr->getBeginLoc(),
17547 diag::err_builtin_matrix_pointer_arg_mismatch)
17548 << ElementTy << MatrixTy->getElementType();
17549 ArgError = true;
17550 }
17551 }
17552
17553 // Apply default Lvalue conversions and convert the stride expression to
17554 // size_t.
17555 {
17556 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17557 if (StrideConv.isInvalid())
17558 return StrideConv;
17559
17560 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17561 if (StrideConv.isInvalid())
17562 return StrideConv;
17563 StrideExpr = StrideConv.get();
17564 TheCall->setArg(2, StrideExpr);
17565 }
17566
17567 // Check stride argument.
17568 if (MatrixTy) {
17569 if (std::optional<llvm::APSInt> Value =
17570 StrideExpr->getIntegerConstantExpr(Context)) {
17571 uint64_t Stride = Value->getZExtValue();
17572 if (Stride < MatrixTy->getNumRows()) {
17573 Diag(StrideExpr->getBeginLoc(),
17574 diag::err_builtin_matrix_stride_too_small);
17575 ArgError = true;
17576 }
17577 }
17578 }
17579
17580 if (ArgError)
17581 return ExprError();
17582
17583 return CallResult;
17584}
17585
17587 const NamedDecl *Callee) {
17588 // This warning does not make sense in code that has no runtime behavior.
17590 return;
17591
17592 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17593
17594 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17595 return;
17596
17597 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17598 // all TCBs the callee is a part of.
17599 llvm::StringSet<> CalleeTCBs;
17600 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17601 CalleeTCBs.insert(A->getTCBName());
17602 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17603 CalleeTCBs.insert(A->getTCBName());
17604
17605 // Go through the TCBs the caller is a part of and emit warnings if Caller
17606 // is in a TCB that the Callee is not.
17607 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17608 StringRef CallerTCB = A->getTCBName();
17609 if (CalleeTCBs.count(CallerTCB) == 0) {
17610 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17611 << Callee << CallerTCB;
17612 }
17613 }
17614}
Defines the clang::ASTContext interface.
#define V(N, I)
Provides definitions for the various language-specific address spaces.
Defines the Diagnostic-related interfaces.
Defines enumerations for traits support.
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.
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.
TokenType getType() const
Returns the token's type, e.g.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
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
llvm::MachO::Record Record
Definition MachO.h:31
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)
llvm::json::Object Object
llvm::json::Array Array
static std::string getFunctionName(const CallEvent &Call)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to BPF.
static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue, bool isConstantEvaluated)
Given a type tag expression find the type tag itself.
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, SourceLocation CC, QualType T)
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind, bool RequireConstant=false)
static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall)
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 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)
static QualType GetExprType(const Expr *E)
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx)
This helper function takes an lvalue expression and returns the alignment of a VarDecl and a constant...
static 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 BuiltinRotateGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_stdc_rotate_{left,right} was called with two arguments, that the first argument...
static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref, ArrayRef< EquatableFormatArgument > RefArgs, const StringLiteral *Fmt, ArrayRef< EquatableFormatArgument > FmtArgs, const Expr *FmtExpr, bool InFunctionCall)
static bool BuiltinBswapg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bswapg was called with a single argument, which is an unsigned integer,...
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 isValidMathElementType(QualType T)
static void DiagnoseDeprecatedHIPAtomic(Sema &S, SourceRange ExprRange, MultiExprArg Args, AtomicExpr::AtomicOp Op)
Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_* equivalents.
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)
#define HIP_ATOMIC_FIXABLE(hip, scoped)
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 QualType getVectorElementType(ASTContext &Context, QualType VecTy)
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 bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bitreverseg was called with a single argument, which is an integer.
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 bool CheckMissingFormatAttribute(Sema *S, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, StringLiteral *ReferenceFormatString, unsigned FormatIdx, unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx, SourceLocation Loc)
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 ExprResult PointerAuthAuthWithPCAndResign(Sema &S, CallExpr *Call)
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 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, std::optional< unsigned > *CallerFormatParamIdx=nullptr, bool IgnoreStringsWithoutSpecifiers=false)
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)
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 ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call)
static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall, QualType ReturnType)
Checks the __builtin_stdc_* builtins that take a single unsigned integer argument and return either i...
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 for SYCL 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.
C Language Family Type Representation.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ int min(int __a, int __b)
static bool hasLayout(const RecordDecl *D)
Whether layout (offset and size) information can be queried for D.
@ 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 * getStart() const
StringRef toString() 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
Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when the only matching conversion function is explicit.
Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when the expression has incomplete class type.
Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for one of the candidate conversions.
Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when there are multiple possible conversion functions.
Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for the explicit conversion function.
bool match(QualType T) override
Determine whether the specified type is a valid destination type for this conversion.
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
APSInt & getInt()
Definition APValue.h:511
bool isVector() const
Definition APValue.h:494
APSInt & getComplexIntImag()
Definition APValue.h:549
bool isComplexInt() const
Definition APValue.h:491
bool isFloat() const
Definition APValue.h:489
bool isComplexFloat() const
Definition APValue.h:492
APValue & getVectorElt(unsigned I)
Definition APValue.h:585
unsigned getVectorLength() const
Definition APValue.h:593
bool isLValue() const
Definition APValue.h:493
bool isInt() const
Definition APValue.h:488
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:609
APSInt & getComplexIntReal()
Definition APValue.h:541
APFloat & getComplexFloatImag()
Definition APValue.h:565
APFloat & getComplexFloatReal()
Definition APValue.h:557
APFloat & getFloat()
Definition APValue.h:525
bool isMatrix() const
Definition APValue.h:495
unsigned getMatrixNumElements() const
Definition APValue.h:606
bool isAddrLabelDiff() const
Definition APValue.h:500
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:828
Builtin::Context & BuiltinInfo
Definition ASTContext.h:830
const LangOptions & getLangOpts() const
Definition ASTContext.h:985
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:881
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
CanQualType UnsignedIntTy
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
CanQualType UnsignedShortTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:947
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
@ GE_None
No error.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4397
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4575
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4581
SourceLocation getQuestionLoc() const
Definition Expr.h:4424
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4587
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:7347
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7351
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2765
SourceLocation getRBracketLoc() const
Definition Expr.h:2813
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2794
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3836
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3850
QualType getElementType() const
Definition TypeBase.h:3848
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:6978
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7127
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7109
Attr - This represents one attribute.
Definition Attr.h:46
const char * getSpelling() const
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4082
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4215
Expr * getLHS() const
Definition Expr.h:4132
SourceLocation getOperatorLoc() const
Definition Expr.h:4124
SourceLocation getExprLoc() const
Definition Expr.h:4123
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2164
Expr * getRHS() const
Definition Expr.h:4134
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4168
Opcode getOpcode() const
Definition Expr.h:4127
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4179
BinaryOperatorKind Opcode
Definition Expr.h:4087
Pointer to a block type.
Definition TypeBase.h:3656
This class is used for builtin types like 'int'.
Definition TypeBase.h:3241
bool isInteger() const
Definition TypeBase.h:3305
bool isFloatingPoint() const
Definition TypeBase.h:3317
bool isSignedInteger() const
Definition TypeBase.h:3309
bool isUnsignedInteger() const
Definition TypeBase.h:3313
Kind getKind() const
Definition TypeBase.h:3292
std::string getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
Definition Builtins.cpp:99
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:383
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition Builtins.cpp:94
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Definition Expr.h:4013
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1634
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2976
Represents a C++ destructor within a class.
Definition DeclCXX.h:2906
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2149
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:85
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:158
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:115
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5194
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5234
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:1234
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:1223
bool isDynamicClass() const
Definition DeclCXX.h:574
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
SourceLocation getBeginLoc() const
Definition Expr.h:3321
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3204
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1620
arg_iterator arg_begin()
Definition Expr.h:3244
arg_iterator arg_end()
Definition Expr.h:3247
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3170
bool isCallToStdMove() const
Definition Expr.cpp:3676
Expr * getCallee()
Definition Expr.h:3134
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3178
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3280
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3181
arg_range arguments()
Definition Expr.h:3239
SourceLocation getEndLoc() const
Definition Expr.h:3340
SourceLocation getRParenLoc() const
Definition Expr.h:3318
Decl * getCalleeDecl()
Definition Expr.h:3164
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:1625
void setCallee(Expr *F)
Definition Expr.h:3136
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3223
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:3720
path_iterator path_begin()
Definition Expr.h:3790
CastKind getCastKind() const
Definition Expr.h:3764
path_iterator path_end()
Definition Expr.h:3791
Expr * getSubExpr()
Definition Expr.h:3770
Represents a byte-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:4435
Expr * getLHS() const
Definition Expr.h:4469
Expr * getRHS() const
Definition Expr.h:4470
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3874
QualType desugar() const
Definition TypeBase.h:3975
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3930
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4501
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4523
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:5718
Expr * getOperand() const
Definition ExprCXX.h:5377
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:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2403
bool isFunctionOrMethod() const
Definition DeclBase.h:2178
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1290
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:494
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1383
ValueDecl * getDecl()
Definition Expr.h:1358
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1488
SourceLocation getBeginLoc() const
Definition Expr.h:1369
SourceLocation getLocation() const
Definition Expr.h:1366
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInStdNamespace() const
Definition DeclBase.cpp:453
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
T * getAttr() const
Definition DeclBase.h:581
void addAttr(Attr *A)
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition DeclBase.cpp:564
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:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:439
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2006
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:234
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:972
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3558
Represents an enum.
Definition Decl.h:4146
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4378
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4319
This represents one expression.
Definition Expr.h:113
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,...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3150
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:695
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:692
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3128
void setType(QualType t)
Definition Expr.h:146
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:448
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:195
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3123
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3111
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
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:3119
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:212
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:285
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4265
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:851
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:855
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:455
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 * IgnoreCasts() LLVM_READONLY
Skip past any casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3107
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3115
std::optional< uint64_t > tryEvaluateStrLen(const ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
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:3722
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:224
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3103
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:822
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:831
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:834
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:824
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:4104
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:272
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:465
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:468
QualType getType() const
Definition Expr.h:145
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:527
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:232
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:138
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Definition TypeBase.h:4381
Represents a member of a struct/union/class.
Definition Decl.h:3295
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3398
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4816
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3531
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3411
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:81
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:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
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:105
llvm::APFloat getValue() const
Definition Expr.h:1686
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2900
Represents a function declaration or definition.
Definition Decl.h:2059
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4614
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3806
param_iterator param_end()
Definition Decl.h:2918
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3909
QualType getReturnType() const
Definition Decl.h:2976
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
param_iterator param_begin()
Definition Decl.h:2917
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3121
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4370
bool isStatic() const
Definition Decl.h:3060
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4185
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4171
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3870
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5421
unsigned getNumParams() const
Definition TypeBase.h:5699
QualType getParamType(unsigned i) const
Definition TypeBase.h:5701
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5825
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5710
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5820
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5706
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4617
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4926
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4922
QualType getReturnType() const
Definition TypeBase.h:4957
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:3897
Describes an C or C++ initializer list.
Definition Expr.h:5352
ArrayRef< Expr * > inits() const
Definition Expr.h:5405
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:981
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:1075
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1111
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:509
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1158
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:882
Represents the results of name lookup.
Definition Lookup.h:147
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4451
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4472
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3408
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3491
Expr * getBase() const
Definition Expr.h:3485
bool isArrow() const
Definition Expr.h:3592
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3767
This represents a decl that may have a name.
Definition Decl.h:275
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1208
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1946
Represent a C++ namespace.
Definition Decl.h:593
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1715
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1729
SourceLocation getSemiLoc() const
Definition Stmt.h:1726
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:734
QualType getType() const
Definition DeclObjC.h:810
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
Definition DeclObjC.h:833
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition DeclObjC.h:821
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition ExprObjC.h:649
ObjCPropertyDecl * getExplicitProperty() const
Definition ExprObjC.h:738
bool isImplicitProperty() const
Definition ExprObjC.h:735
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:83
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2226
Represents a parameter to a function.
Definition Decl.h:1820
Pointer-authentication qualifiers.
Definition TypeBase.h:153
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
Definition TypeBase.h:233
bool isAddressDiscriminated() const
Definition TypeBase.h:266
ARM8_3Key
Hardware pointer-signing keys in ARM8.3.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3408
QualType getPointeeType() const
Definition TypeBase.h:3418
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6854
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5225
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8585
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:2998
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
QualType withoutLocalFastQualifiers() const
Definition TypeBase.h:1230
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8501
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8627
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8541
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition TypeBase.h:8553
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8595
void removeLocalVolatile()
Definition TypeBase.h:8617
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1195
void removeLocalConst()
Definition TypeBase.h:8609
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8574
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8622
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1745
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8547
bool hasNonTrivialObjCLifetime() const
Definition TypeBase.h:1458
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
bool hasUnaligned() const
Definition TypeBase.h:512
Represents a struct/union/class.
Definition Decl.h:4460
bool hasFlexibleArrayMember() const
Definition Decl.h:4493
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4546
field_range fields() const
Definition Decl.h:4663
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4538
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:602
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
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(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaARM.cpp:1038
@ 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:1121
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
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
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:113
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
Definition SemaPPC.cpp:32
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition SemaPPC.cpp:422
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
SemaDiagnosticBuilder DiagIfDeviceCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition SemaSYCL.cpp:31
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaWasm.cpp:289
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Definition SemaX86.cpp:534
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10361
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10366
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
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:1446
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:13158
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1137
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:2801
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9370
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9378
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9415
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:6965
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.
bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T, SourceLocation CC)
Check for overflow behavior type related implicit conversion diagnostics.
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2079
SemaHexagon & Hexagon()
Definition Sema.h:1486
SemaSYCL & SYCL()
Definition Sema.h:1556
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:1768
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:843
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1576
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:1304
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:228
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:932
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:1516
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1371
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:764
ASTContext & getASTContext() const
Definition Sema.h:935
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:777
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2639
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:1208
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
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:2746
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
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:928
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:1461
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:1476
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:1302
static const uint64_t MaximumAlignment
Definition Sema.h:1231
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:962
SemaHLSL & HLSL()
Definition Sema.h:1481
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1501
SemaRISCV & RISCV()
Definition Sema.h:1546
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:2812
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7001
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1780
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:1339
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
Definition Sema.h:2719
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15554
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:2456
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:648
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:1444
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:1526
FormatArgumentPassingKind
Definition Sema.h:2649
@ FAPK_Elsewhere
Definition Sema.h:2653
@ FAPK_Fixed
Definition Sema.h:2650
@ FAPK_Variadic
Definition Sema.h:2651
@ FAPK_VAList
Definition Sema.h:2652
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:8209
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:14055
SourceManager & getSourceManager() const
Definition Sema.h:933
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 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:2641
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:1536
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:1263
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 FormatStringI...
SemaSystemZ & SystemZ()
Definition Sema.h:1566
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:1307
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:793
DiagnosticsEngine & Diags
Definition Sema.h:1306
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:1511
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:646
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:6318
SemaSPIRV & SPIRV()
Definition Sema.h:1551
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:1491
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6453
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:1571
SemaARM & ARM()
Definition Sema.h:1451
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:4687
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.
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) const
bool isMacroArgExpansion(SourceLocation Loc, SourceLocation *StartLoc=nullptr) const
Tests whether the given source location represents a macro argument's expansion into the function-lik...
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const
Gets the location of the immediate macro caller, one level up the stack toward the initial macro type...
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:367
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:304
StmtClass getStmtClass() const
Definition Stmt.h:1505
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
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:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1819
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2017
bool isUTF8() const
Definition Expr.h:1954
bool isWide() const
Definition Expr.h:1953
bool isPascal() const
Definition Expr.h:1958
unsigned getLength() const
Definition Expr.h:1944
StringLiteralKind getKind() const
Definition Expr.h:1948
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
Return a source location that points to the specified byte of this string literal.
Definition Expr.cpp:1332
bool isUTF32() const
Definition Expr.h:1956
unsigned getByteLength() const
Definition Expr.h:1942
StringRef getString() const
Definition Expr.h:1887
bool isUTF16() const
Definition Expr.h:1955
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:2018
bool isOrdinary() const
Definition Expr.h:1952
unsigned getCharByteWidth() const
Definition Expr.h:1946
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3973
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3953
bool isUnion() const
Definition Decl.h:4063
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:394
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:2766
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:6331
A container of type source information.
Definition TypeBase.h:8472
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8483
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isBlockPointerType() const
Definition TypeBase.h:8758
bool isVoidType() const
Definition TypeBase.h:9110
bool isBooleanType() const
Definition TypeBase.h:9247
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2319
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9297
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:824
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2296
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2387
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2203
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:9277
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:2149
bool isVoidPointerType() const
Definition Type.cpp:749
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2549
bool isArrayType() const
Definition TypeBase.h:8837
bool isCharType() const
Definition Type.cpp:2223
bool isFunctionPointerType() const
Definition TypeBase.h:8805
bool isPointerType() const
Definition TypeBase.h:8738
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9154
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9404
bool isReferenceType() const
Definition TypeBase.h:8762
bool isEnumeralType() const
Definition TypeBase.h:8869
bool isScalarType() const
Definition TypeBase.h:9216
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:1984
bool isVariableArrayType() const
Definition TypeBase.h:8849
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2733
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9232
bool isExtVectorType() const
Definition TypeBase.h:8881
bool isExtVectorBoolType() const
Definition TypeBase.h:8885
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2772
bool isBitIntType() const
Definition TypeBase.h:9013
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9079
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8861
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8873
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2340
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3196
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2683
bool isMemberPointerType() const
Definition TypeBase.h:8819
bool isAtomicType() const
Definition TypeBase.h:8930
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isMatrixType() const
Definition TypeBase.h:8901
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3233
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:2877
bool isUnscopedEnumerationType() const
Definition Type.cpp:2216
bool isObjCObjectType() const
Definition TypeBase.h:8921
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9390
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9253
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2574
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:2559
bool isFunctionType() const
Definition TypeBase.h:8734
bool isObjCObjectPointerType() const
Definition TypeBase.h:8917
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2429
bool isStructureOrClassType() const
Definition Type.cpp:743
bool isVectorType() const
Definition TypeBase.h:8877
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2437
bool isFloatingType() const
Definition Type.cpp:2421
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:2364
bool isAnyPointerType() const
Definition TypeBase.h:8746
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition TypeBase.h:2475
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9337
bool isNullPtrType() const
Definition TypeBase.h:9147
bool isRecordType() const
Definition TypeBase.h:8865
bool isObjCRetainableType() const
Definition Type.cpp:5468
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2695
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5187
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2760
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3697
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2669
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2288
Expr * getSubExpr() const
Definition Expr.h:2329
Opcode getOpcode() const
Definition Expr.h:2324
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2406
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1039
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1127
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3428
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
QualType getType() const
Definition Decl.h:724
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5645
Represents a variable declaration or definition.
Definition Decl.h:933
Represents a GCC generic vector type.
Definition TypeBase.h:4289
unsigned getNumElements() const
Definition TypeBase.h:4304
QualType getElementType() const
Definition TypeBase.h:4303
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2709
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
Represents the length modifier in a format string in scanf/printf.
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.
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:238
@ 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:1539
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1524
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1517
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1531
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2881
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1485
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1546
SetTy< T > join(SetTy< T > A, SetTy< T > B, typename SetTy< T >::Factory &F)
Computes the union of two ImmutableSets.
Definition Utils.h:49
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
RangeSelector merge(RangeSelector First, RangeSelector Second)
Selects the merge of the two ranges, i.e.
Top level wrappers for InstallAPI frontend operations.
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:824
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
Definition IgnoreExpr.h:115
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
VariadicCallType
Definition Sema.h:507
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:657
@ Comparison
A comparison.
Definition Sema.h:661
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:349
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:24
@ 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:150
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
PointerAuthDiscArgKind
Definition Sema.h:588
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:125
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:258
@ 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:556
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:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
const FunctionProtoType * T
bool isFunctionOrMethodVariadic(const Decl *D)
Definition Attr.h:144
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:558
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:493
CastKind
CastKind - The kind of operation required for a conversion.
BuiltinCountedByRefKind
Definition Sema.h:515
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool hasImplicitObjectParameter(const Decl *D)
Definition Attr.h:158
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
for(const auto &A :T->param_types())
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition IgnoreExpr.h:144
unsigned getFunctionOrMethodNumParams(const Decl *D)
getFunctionOrMethodNumParams - Return number of function or method parameters.
Definition Attr.h:65
StringLiteralKind
Definition Expr.h:1783
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_Win64
Definition Specifiers.h:286
@ CC_X86_64SysV
Definition Specifiers.h:287
@ Generic
not a target-specific vector type
Definition TypeBase.h:4250
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6040
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6033
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1775
unsigned long uint64_t
long int64_t
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:668
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:650
Extra information about a function prototype.
Definition TypeBase.h:5506
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:13340
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13366
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13356
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13304
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6859
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2661
#define log2(__x)
Definition tgmath.h:970