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
276 // Unlike '&', nothing resolves the overload set later, so resolve it now.
277 // FIXME: Resolve the overload set from the target type, like '&' does.
278 if (Arg.get()->getType() == S.Context.OverloadTy) {
279 Arg = S.CheckPlaceholderExpr(Arg.get());
280 if (Arg.isInvalid())
281 return true;
282 }
283
284 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
285 if (ResultType.isNull())
286 return true;
287
288 TheCall->setArg(0, Arg.get());
289 TheCall->setType(ResultType);
290 return false;
291}
292
293/// Check that the argument to __builtin_function_start is a function.
294static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
295 if (S.checkArgCount(TheCall, 1))
296 return true;
297
298 if (TheCall->getArg(0)->containsErrors())
299 return true;
300
302 if (Arg.isInvalid())
303 return true;
304
305 TheCall->setArg(0, Arg.get());
306 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
308
309 if (!FD) {
310 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type)
311 << TheCall->getSourceRange();
312 return true;
313 }
314
315 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
316 TheCall->getBeginLoc());
317}
318
319/// Check the number of arguments and set the result type to
320/// the argument type.
321static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
322 if (S.checkArgCount(TheCall, 1))
323 return true;
324
325 TheCall->setType(TheCall->getArg(0)->getType());
326 return false;
327}
328
329/// Check that the value argument for __builtin_is_aligned(value, alignment) and
330/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
331/// type (but not a function pointer) and that the alignment is a power-of-two.
332static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
333 if (S.checkArgCount(TheCall, 2))
334 return true;
335
336 clang::Expr *Source = TheCall->getArg(0);
337 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
338
339 auto IsValidIntegerType = [](QualType Ty) {
340 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
341 };
342 QualType SrcTy = Source->getType();
343 // We should also be able to use it with arrays (but not functions!).
344 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
345 SrcTy = S.Context.getDecayedType(SrcTy);
346 }
347 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
348 SrcTy->isFunctionPointerType()) {
349 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
350 << SrcTy;
351 if (SrcTy->isFloatingType())
352 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_type);
353 else if (SrcTy->isMemberPointerType())
354 S.Diag(Source->getExprLoc(), diag::note_alignment_invalid_member_pointer);
355 else if (SrcTy->isFunctionPointerType())
356 S.Diag(Source->getExprLoc(),
357 diag::note_alignment_invalid_function_pointer);
358 return true;
359 }
360
361 clang::Expr *AlignOp = TheCall->getArg(1);
362 if (!IsValidIntegerType(AlignOp->getType())) {
363 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
364 << AlignOp->getType();
365 return true;
366 }
367 Expr::EvalResult AlignResult;
368 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
369 // We can't check validity of alignment if it is value dependent.
370 if (!AlignOp->isValueDependent() &&
371 AlignOp->EvaluateAsInt(AlignResult, S.Context,
373 llvm::APSInt AlignValue = AlignResult.Val.getInt();
374 llvm::APSInt MaxValue(
375 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
376 if (AlignValue < 1) {
377 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
378 return true;
379 }
380 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
381 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
382 << toString(MaxValue, 10);
383 return true;
384 }
385 if (!AlignValue.isPowerOf2()) {
386 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
387 return true;
388 }
389 if (AlignValue == 1) {
390 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
391 << IsBooleanAlignBuiltin;
392 }
393 }
394
397 SourceLocation(), Source);
398 if (SrcArg.isInvalid())
399 return true;
400 TheCall->setArg(0, SrcArg.get());
401 ExprResult AlignArg =
403 S.Context, AlignOp->getType(), false),
404 SourceLocation(), AlignOp);
405 if (AlignArg.isInvalid())
406 return true;
407 TheCall->setArg(1, AlignArg.get());
408 // For align_up/align_down, the return type is the same as the (potentially
409 // decayed) argument type including qualifiers. For is_aligned(), the result
410 // is always bool.
411 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
412 return false;
413}
414
415static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
416 if (S.checkArgCount(TheCall, 3))
417 return true;
418
419 std::pair<unsigned, const char *> Builtins[] = {
420 { Builtin::BI__builtin_add_overflow, "ckd_add" },
421 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
422 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
423 };
424
425 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned,
426 const char *> &P) {
427 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
429 S.getSourceManager(), S.getLangOpts()) == P.second;
430 });
431
432 auto ValidCkdIntType = [](QualType QT) {
433 // A valid checked integer type is an integer type other than a plain char,
434 // bool, a bit-precise type, or an enumeration type.
435 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
436 return (BT->getKind() >= BuiltinType::Short &&
437 BT->getKind() <= BuiltinType::Int128) || (
438 BT->getKind() >= BuiltinType::UShort &&
439 BT->getKind() <= BuiltinType::UInt128) ||
440 BT->getKind() == BuiltinType::UChar ||
441 BT->getKind() == BuiltinType::SChar;
442 return false;
443 };
444
445 // First two arguments should be integers.
446 for (unsigned I = 0; I < 2; ++I) {
448 if (Arg.isInvalid()) return true;
449 TheCall->setArg(I, Arg.get());
450
451 QualType Ty = Arg.get()->getType();
452 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
453 if (!IsValid) {
454 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
455 << CkdOperation << Ty << Arg.get()->getSourceRange();
456 return true;
457 }
458 }
459
460 // Third argument should be a pointer to a non-const integer.
461 // IRGen correctly handles volatile, restrict, and address spaces, and
462 // the other qualifiers aren't possible.
463 {
465 if (Arg.isInvalid()) return true;
466 TheCall->setArg(2, Arg.get());
467
468 QualType Ty = Arg.get()->getType();
469 const auto *PtrTy = Ty->getAs<PointerType>();
470 if (!PtrTy ||
471 !PtrTy->getPointeeType()->isIntegerType() ||
472 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
473 PtrTy->getPointeeType().isConstQualified()) {
474 S.Diag(Arg.get()->getBeginLoc(),
475 diag::err_overflow_builtin_must_be_ptr_int)
476 << CkdOperation << Ty << Arg.get()->getSourceRange();
477 return true;
478 }
479 }
480
481 // Disallow signed bit-precise integer args larger than 128 bits to mul
482 // function until we improve backend support.
483 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
484 for (unsigned I = 0; I < 3; ++I) {
485 const auto Arg = TheCall->getArg(I);
486 // Third argument will be a pointer.
487 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
488 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
489 S.getASTContext().getIntWidth(Ty) > 128)
490 return S.Diag(Arg->getBeginLoc(),
491 diag::err_overflow_builtin_bit_int_max_size)
492 << 128;
493 }
494 }
495
496 return false;
497}
498
499namespace {
500struct BuiltinDumpStructGenerator {
501 Sema &S;
502 CallExpr *TheCall;
503 SourceLocation Loc = TheCall->getBeginLoc();
504 SmallVector<Expr *, 32> Actions;
505 DiagnosticErrorTrap ErrorTracker;
506 PrintingPolicy Policy;
507
508 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
509 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
510 Policy(S.Context.getPrintingPolicy()) {
511 Policy.AnonymousTagNameStyle =
512 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
513 }
514
515 Expr *makeOpaqueValueExpr(Expr *Inner) {
516 auto *OVE = new (S.Context)
517 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
518 Inner->getObjectKind(), Inner);
519 Actions.push_back(OVE);
520 return OVE;
521 }
522
523 Expr *getStringLiteral(llvm::StringRef Str) {
525 // Wrap the literal in parentheses to attach a source location.
526 return new (S.Context) ParenExpr(Loc, Loc, Lit);
527 }
528
529 bool callPrintFunction(llvm::StringRef Format,
530 llvm::ArrayRef<Expr *> Exprs = {}) {
531 SmallVector<Expr *, 8> Args;
532 assert(TheCall->getNumArgs() >= 2);
533 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
534 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end());
535 Args.push_back(getStringLiteral(Format));
536 llvm::append_range(Args, Exprs);
537
538 // Register a note to explain why we're performing the call.
539 Sema::CodeSynthesisContext Ctx;
541 Ctx.PointOfInstantiation = Loc;
542 Ctx.CallArgs = Args.data();
543 Ctx.NumCallArgs = Args.size();
545
546 ExprResult RealCall =
547 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1),
548 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc());
549
551 if (!RealCall.isInvalid())
552 Actions.push_back(RealCall.get());
553 // Bail out if we've hit any unrecoverable errors, even if we managed
554 // to build the call.
555 return RealCall.isInvalid() || ErrorTracker.hasUnrecoverableErrorOccurred();
556 }
557
558 Expr *getIndentString(unsigned Depth) {
559 if (!Depth)
560 return nullptr;
561
562 llvm::SmallString<32> Indent;
563 Indent.resize(Depth * Policy.Indentation, ' ');
564 return getStringLiteral(Indent);
565 }
566
567 Expr *getTypeString(QualType T) {
568 return getStringLiteral(T.getAsString(Policy));
569 }
570
571 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
572 llvm::raw_svector_ostream OS(Str);
573
574 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
575 // than trying to print a single character.
576 if (auto *BT = T->getAs<BuiltinType>()) {
577 switch (BT->getKind()) {
578 case BuiltinType::Bool:
579 OS << "%d";
580 return true;
581 case BuiltinType::Char_U:
582 case BuiltinType::UChar:
583 OS << "%hhu";
584 return true;
585 case BuiltinType::Char_S:
586 case BuiltinType::SChar:
587 OS << "%hhd";
588 return true;
589 default:
590 break;
591 }
592 }
593
594 analyze_printf::PrintfSpecifier Specifier;
595 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) {
596 // We were able to guess how to format this.
597 if (Specifier.getConversionSpecifier().getKind() ==
598 analyze_printf::PrintfConversionSpecifier::sArg) {
599 // Wrap double-quotes around a '%s' specifier and limit its maximum
600 // length. Ideally we'd also somehow escape special characters in the
601 // contents but printf doesn't support that.
602 // FIXME: '%s' formatting is not safe in general.
603 OS << '"';
604 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
605 Specifier.toString(OS);
606 OS << '"';
607 // FIXME: It would be nice to include a '...' if the string doesn't fit
608 // in the length limit.
609 } else {
610 Specifier.toString(OS);
611 }
612 return true;
613 }
614
615 if (T->isPointerType()) {
616 // Format all pointers with '%p'.
617 OS << "%p";
618 return true;
619 }
620
621 return false;
622 }
623
624 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
625 Expr *IndentLit = getIndentString(Depth);
626 Expr *TypeLit = getTypeString(S.Context.getCanonicalTagType(RD));
627 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit})
628 : callPrintFunction("%s", {TypeLit}))
629 return true;
630
631 return dumpRecordValue(RD, E, IndentLit, Depth);
632 }
633
634 // Dump a record value. E should be a pointer or lvalue referring to an RD.
635 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
636 unsigned Depth) {
637 // FIXME: Decide what to do if RD is a union. At least we should probably
638 // turn off printing `const char*` members with `%s`, because that is very
639 // likely to crash if that's not the active member. Whatever we decide, we
640 // should document it.
641
642 // Build an OpaqueValueExpr so we can refer to E more than once without
643 // triggering re-evaluation.
644 Expr *RecordArg = makeOpaqueValueExpr(E);
645 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
646
647 if (callPrintFunction(" {\n"))
648 return true;
649
650 // Dump each base class, regardless of whether they're aggregates.
651 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
652 for (const auto &Base : CXXRD->bases()) {
653 QualType BaseType =
654 RecordArgIsPtr ? S.Context.getPointerType(Base.getType())
655 : S.Context.getLValueReferenceType(Base.getType());
657 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc,
658 RecordArg);
659 if (BasePtr.isInvalid() ||
660 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(),
661 Depth + 1))
662 return true;
663 }
664 }
665
666 Expr *FieldIndentArg = getIndentString(Depth + 1);
667
668 // Dump each field.
669 for (auto *D : RD->decls()) {
670 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
671 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
672 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
673 continue;
674
675 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
676 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
677 getTypeString(FD->getType()),
678 getStringLiteral(FD->getName())};
679
680 if (FD->isBitField()) {
681 Format += ": %zu ";
682 QualType SizeT = S.Context.getSizeType();
683 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT),
684 FD->getBitWidthValue());
685 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc));
686 }
687
688 Format += "=";
689
692 CXXScopeSpec(), Loc, IFD,
693 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc)
695 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
697 DeclarationNameInfo(FD->getDeclName(), Loc));
698 if (Field.isInvalid())
699 return true;
700
701 auto *InnerRD = FD->getType()->getAsRecordDecl();
702 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
703 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
704 // Recursively print the values of members of aggregate record type.
705 if (callPrintFunction(Format, Args) ||
706 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1))
707 return true;
708 } else {
709 Format += " ";
710 if (appendFormatSpecifier(FD->getType(), Format)) {
711 // We know how to print this field.
712 Args.push_back(Field.get());
713 } else {
714 // We don't know how to print this field. Print out its address
715 // with a format specifier that a smart tool will be able to
716 // recognize and treat specially.
717 Format += "*%p";
718 ExprResult FieldAddr =
719 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get());
720 if (FieldAddr.isInvalid())
721 return true;
722 Args.push_back(FieldAddr.get());
723 }
724 Format += "\n";
725 if (callPrintFunction(Format, Args))
726 return true;
727 }
728 }
729
730 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent)
731 : callPrintFunction("}\n");
732 }
733
734 Expr *buildWrapper() {
735 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions,
737 TheCall->setType(Wrapper->getType());
738 TheCall->setValueKind(Wrapper->getValueKind());
739 return Wrapper;
740 }
741};
742} // namespace
743
745 if (S.checkArgCountAtLeast(TheCall, 2))
746 return ExprError();
747
748 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0));
749 if (PtrArgResult.isInvalid())
750 return ExprError();
751 TheCall->setArg(0, PtrArgResult.get());
752
753 // First argument should be a pointer to a struct.
754 QualType PtrArgType = PtrArgResult.get()->getType();
755 if (!PtrArgType->isPointerType() ||
756 !PtrArgType->getPointeeType()->isRecordType()) {
757 S.Diag(PtrArgResult.get()->getBeginLoc(),
758 diag::err_expected_struct_pointer_argument)
759 << 1 << TheCall->getDirectCallee() << PtrArgType;
760 return ExprError();
761 }
762 QualType Pointee = PtrArgType->getPointeeType();
763 const RecordDecl *RD = Pointee->getAsRecordDecl();
764 // Try to instantiate the class template as appropriate; otherwise, access to
765 // its data() may lead to a crash.
766 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee,
767 diag::err_incomplete_type))
768 return ExprError();
769 // Second argument is a callable, but we can't fully validate it until we try
770 // calling it.
771 QualType FnArgType = TheCall->getArg(1)->getType();
772 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
773 !FnArgType->isBlockPointerType() &&
774 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
775 auto *BT = FnArgType->getAs<BuiltinType>();
776 switch (BT ? BT->getKind() : BuiltinType::Void) {
777 case BuiltinType::Dependent:
778 case BuiltinType::Overload:
779 case BuiltinType::BoundMember:
780 case BuiltinType::PseudoObject:
781 case BuiltinType::UnknownAny:
782 case BuiltinType::BuiltinFn:
783 // This might be a callable.
784 break;
785
786 default:
787 S.Diag(TheCall->getArg(1)->getBeginLoc(),
788 diag::err_expected_callable_argument)
789 << 2 << TheCall->getDirectCallee() << FnArgType;
790 return ExprError();
791 }
792 }
793
794 BuiltinDumpStructGenerator Generator(S, TheCall);
795
796 // Wrap parentheses around the given pointer. This is not necessary for
797 // correct code generation, but it means that when we pretty-print the call
798 // arguments in our diagnostics we will produce '(&s)->n' instead of the
799 // incorrect '&s->n'.
800 Expr *PtrArg = PtrArgResult.get();
801 PtrArg = new (S.Context)
802 ParenExpr(PtrArg->getBeginLoc(),
803 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg);
804 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
805 return ExprError();
806
807 return Generator.buildWrapper();
808}
809
810static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
811 if (S.checkArgCount(BuiltinCall, 2))
812 return true;
813
814 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
815 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
816 Expr *Call = BuiltinCall->getArg(0);
817 Expr *Chain = BuiltinCall->getArg(1);
818
819 if (Call->getStmtClass() != Stmt::CallExprClass) {
820 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
821 << Call->getSourceRange();
822 return true;
823 }
824
825 auto CE = cast<CallExpr>(Call);
826 if (CE->getCallee()->getType()->isBlockPointerType()) {
827 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
828 << Call->getSourceRange();
829 return true;
830 }
831
832 const Decl *TargetDecl = CE->getCalleeDecl();
833 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
834 if (FD->getBuiltinID()) {
835 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
836 << Call->getSourceRange();
837 return true;
838 }
839
840 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
841 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
842 << Call->getSourceRange();
843 return true;
844 }
845
846 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
847 if (ChainResult.isInvalid())
848 return true;
849 if (!ChainResult.get()->getType()->isPointerType()) {
850 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
851 << Chain->getSourceRange();
852 return true;
853 }
854
855 QualType ReturnTy = CE->getCallReturnType(S.Context);
856 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
857 QualType BuiltinTy = S.Context.getFunctionType(
858 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
859 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
860
861 Builtin =
862 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
863
864 BuiltinCall->setType(CE->getType());
865 BuiltinCall->setValueKind(CE->getValueKind());
866 BuiltinCall->setObjectKind(CE->getObjectKind());
867 BuiltinCall->setCallee(Builtin);
868 BuiltinCall->setArg(1, ChainResult.get());
869
870 return false;
871}
872
873namespace {
874
875class ScanfDiagnosticFormatHandler
877 // Accepts the argument index (relative to the first destination index) of the
878 // argument whose size we want.
879 using ComputeSizeFunction =
880 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
881
882 // Accepts the argument index (relative to the first destination index), the
883 // destination size, and the source size).
884 using DiagnoseFunction =
885 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
886
887 ComputeSizeFunction ComputeSizeArgument;
888 DiagnoseFunction Diagnose;
889
890public:
891 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
892 DiagnoseFunction Diagnose)
893 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
894
895 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
896 const char *StartSpecifier,
897 unsigned specifierLen) override {
898 if (!FS.consumesDataArgument())
899 return true;
900
901 unsigned NulByte = 0;
902 switch ((FS.getConversionSpecifier().getKind())) {
903 default:
904 return true;
907 NulByte = 1;
908 break;
910 break;
911 }
912
913 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
914 if (FW.getHowSpecified() !=
915 analyze_format_string::OptionalAmount::HowSpecified::Constant)
916 return true;
917
918 unsigned SourceSize = FW.getConstantAmount() + NulByte;
919
920 std::optional<llvm::APSInt> DestSizeAPS =
921 ComputeSizeArgument(FS.getArgIndex());
922 if (!DestSizeAPS)
923 return true;
924
925 unsigned DestSize = DestSizeAPS->getZExtValue();
926
927 if (DestSize < SourceSize)
928 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
929
930 return true;
931 }
932};
933
934class EstimateSizeFormatHandler
936 size_t Size;
937 /// Whether the format string contains Linux kernel's format specifier
938 /// extension.
939 bool IsKernelCompatible = true;
940
941public:
942 EstimateSizeFormatHandler(StringRef Format)
943 : Size(std::min(Format.find(0), Format.size()) +
944 1 /* null byte always written by sprintf */) {}
945
946 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
947 const char *, unsigned SpecifierLen,
948 const TargetInfo &) override {
949
950 const size_t FieldWidth = computeFieldWidth(FS);
951 const size_t Precision = computePrecision(FS);
952
953 // The actual format.
954 switch (FS.getConversionSpecifier().getKind()) {
955 // Just a char.
958 Size += std::max(FieldWidth, (size_t)1);
959 break;
960 // Just an integer.
970 Size += std::max(FieldWidth, Precision);
971 break;
972
973 // %g style conversion switches between %f or %e style dynamically.
974 // %g removes trailing zeros, and does not print decimal point if there are
975 // no digits that follow it. Thus %g can print a single digit.
976 // FIXME: If it is alternative form:
977 // For g and G conversions, trailing zeros are not removed from the result.
980 Size += 1;
981 break;
982
983 // Floating point number in the form '[+]ddd.ddd'.
986 Size += std::max(FieldWidth, 1 /* integer part */ +
987 (Precision ? 1 + Precision
988 : 0) /* period + decimal */);
989 break;
990
991 // Floating point number in the form '[-]d.ddde[+-]dd'.
994 Size +=
995 std::max(FieldWidth,
996 1 /* integer part */ +
997 (Precision ? 1 + Precision : 0) /* period + decimal */ +
998 1 /* e or E letter */ + 2 /* exponent */);
999 break;
1000
1001 // Floating point number in the form '[-]0xh.hhhhp±dd'.
1004 Size +=
1005 std::max(FieldWidth,
1006 2 /* 0x */ + 1 /* integer part */ +
1007 (Precision ? 1 + Precision : 0) /* period + decimal */ +
1008 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
1009 break;
1010
1011 // Just a string.
1014 Size += FieldWidth;
1015 break;
1016
1017 // Just a pointer in the form '0xddd'.
1019 // Linux kernel has its own extension for `%p` specifier.
1020 // Kernel Document:
1021 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1022 IsKernelCompatible = false;
1023 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
1024 break;
1025
1026 // A plain percent.
1028 Size += 1;
1029 break;
1030
1031 default:
1032 break;
1033 }
1034
1035 // If field width is specified, the sign/space is already accounted for
1036 // within the field width, so no additional size is needed.
1037 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1038 Size += 1;
1039
1040 if (FS.hasAlternativeForm()) {
1041 switch (FS.getConversionSpecifier().getKind()) {
1042 // For o conversion, it increases the precision, if and only if necessary,
1043 // to force the first digit of the result to be a zero
1044 // (if the value and precision are both 0, a single 0 is printed)
1046 // For b conversion, a nonzero result has 0b prefixed to it.
1048 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1049 // it.
1052 // Note: even when the prefix is added, if
1053 // (prefix_width <= FieldWidth - formatted_length) holds,
1054 // the prefix does not increase the format
1055 // size. e.g.(("%#3x", 0xf) is "0xf")
1056
1057 // If the result is zero, o, b, x, X adds nothing.
1058 break;
1059 // For a, A, e, E, f, F, g, and G conversions,
1060 // the result of converting a floating-point number always contains a
1061 // decimal-point
1070 Size += (Precision ? 0 : 1);
1071 break;
1072 // For other conversions, the behavior is undefined.
1073 default:
1074 break;
1075 }
1076 }
1077 assert(SpecifierLen <= Size && "no underflow");
1078 Size -= SpecifierLen;
1079 return true;
1080 }
1081
1082 size_t getSizeLowerBound() const { return Size; }
1083 bool isKernelCompatible() const { return IsKernelCompatible; }
1084
1085private:
1086 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1087 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1088 size_t FieldWidth = 0;
1090 FieldWidth = FW.getConstantAmount();
1091 return FieldWidth;
1092 }
1093
1094 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1095 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1096 size_t Precision = 0;
1097
1098 // See man 3 printf for default precision value based on the specifier.
1099 switch (FW.getHowSpecified()) {
1101 switch (FS.getConversionSpecifier().getKind()) {
1102 default:
1103 break;
1107 Precision = 1;
1108 break;
1115 Precision = 1;
1116 break;
1123 Precision = 6;
1124 break;
1126 Precision = 1;
1127 break;
1128 }
1129 break;
1131 Precision = FW.getConstantAmount();
1132 break;
1133 default:
1134 break;
1135 }
1136 return Precision;
1137 }
1138};
1139
1140} // namespace
1141
1142static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1143 StringRef &FormatStrRef, size_t &StrLen,
1144 ASTContext &Context) {
1145 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1146 Format && (Format->isOrdinary() || Format->isUTF8())) {
1147 FormatStrRef = Format->getString();
1148 const ConstantArrayType *T =
1149 Context.getAsConstantArrayType(Format->getType());
1150 assert(T && "String literal not of constant array type!");
1151 size_t TypeSize = T->getZExtSize();
1152 // In case there's a null byte somewhere.
1153 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
1154 return true;
1155 }
1156 return false;
1157}
1158
1159namespace {
1160/// Helper class for buffer overflow/overread checking in fortified functions.
1161class FortifiedBufferChecker {
1162public:
1163 FortifiedBufferChecker(Sema &S, FunctionDecl *FD, CallExpr *TheCall)
1164 : S(S), TheCall(TheCall), FD(FD),
1165 DABAttr(FD ? FD->getAttr<DiagnoseAsBuiltinAttr>() : nullptr) {
1166 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1167 SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
1168 }
1169
1170 std::optional<unsigned> TranslateIndex(unsigned Index) {
1171 // If we refer to a diagnose_as_builtin attribute, we need to change the
1172 // argument index to refer to the arguments of the called function. Unless
1173 // the index is out of bounds, which presumably means it's a variadic
1174 // function.
1175 unsigned NewIndex = Index;
1176 if (DABAttr) {
1177 unsigned DABIndices = DABAttr->argIndices_size();
1178 NewIndex = Index < DABIndices ? DABAttr->argIndices_begin()[Index]
1179 : Index - DABIndices + FD->getNumParams();
1180 }
1181 if (NewIndex >= TheCall->getNumArgs())
1182 return std::nullopt;
1183 return NewIndex;
1184 }
1185
1186 /// Evaluate the argument at Index as an integer constant while preserving
1187 /// its signedness, or return std::nullopt if it cannot be evaluated.
1188 std::optional<llvm::APSInt> EvaluateIntegerArgument(unsigned Index) {
1189 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1190 if (!IndexOptional)
1191 return std::nullopt;
1192 Expr::EvalResult Result;
1193 Expr *Arg = TheCall->getArg(*IndexOptional);
1194 if (!Arg->EvaluateAsInt(Result, S.getASTContext()))
1195 return std::nullopt;
1196
1197 return Result.Val.getInt();
1198 }
1199
1200 std::optional<llvm::APSInt>
1201 ComputeExplicitObjectSizeArgument(unsigned Index) {
1202 std::optional<llvm::APSInt> Integer = EvaluateIntegerArgument(Index);
1203 if (!Integer)
1204 return std::nullopt;
1205 *Integer = Integer->extOrTrunc(SizeTypeWidth);
1206 Integer->setIsUnsigned(true);
1207 return Integer;
1208 }
1209
1210 std::optional<llvm::APSInt> ComputeSizeArgument(unsigned Index) {
1211 // If the parameter has a pass_object_size attribute, then we should use its
1212 // (potentially) more strict checking mode. Otherwise, conservatively assume
1213 // type 0.
1214 int BOSType = 0;
1215 // This check can fail for variadic functions.
1216 if (Index < FD->getNumParams()) {
1217 if (const auto *POS =
1218 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
1219 BOSType = POS->getType();
1220 }
1221
1222 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1223 if (!IndexOptional)
1224 return std::nullopt;
1225
1226 const Expr *ObjArg = TheCall->getArg(*IndexOptional);
1227 if (std::optional<uint64_t> ObjSize =
1228 ObjArg->tryEvaluateObjectSize(S.getASTContext(), BOSType)) {
1229 // Get the object size in the target's size_t width.
1230 return llvm::APSInt::getUnsigned(*ObjSize).extOrTrunc(SizeTypeWidth);
1231 }
1232 return std::nullopt;
1233 }
1234
1235 std::optional<llvm::APSInt>
1236 ComputeExplicitObjectSizeArgumentProduct(unsigned LIndex, unsigned RIndex) {
1237 auto L = ComputeExplicitObjectSizeArgument(LIndex);
1238 auto R = ComputeExplicitObjectSizeArgument(RIndex);
1239 if (!L || !R)
1240 return std::nullopt;
1241
1242 unsigned W =
1243 2 * std::max({L->getBitWidth(), R->getBitWidth(), SizeTypeWidth});
1244
1245 llvm::APSInt LE = L->extOrTrunc(W);
1246 llvm::APSInt RE = R->extOrTrunc(W);
1247
1248 return LE * RE;
1249 }
1250
1251 std::optional<llvm::APSInt> ComputeStrLenArgument(unsigned Index) {
1252 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1253 if (!IndexOptional)
1254 return std::nullopt;
1255 unsigned NewIndex = *IndexOptional;
1256
1257 const Expr *ObjArg = TheCall->getArg(NewIndex);
1258
1259 if (std::optional<uint64_t> Result =
1260 ObjArg->tryEvaluateStrLen(S.getASTContext())) {
1261 // Add 1 for null byte.
1262 return llvm::APSInt::getUnsigned(*Result + 1).extOrTrunc(SizeTypeWidth);
1263 }
1264 return std::nullopt;
1265 }
1266
1267 unsigned getSizeTypeWidth() const { return SizeTypeWidth; }
1268
1269 unsigned getBuiltinID() const {
1270 const FunctionDecl *UseDecl = FD;
1271 if (DABAttr) {
1272 UseDecl = DABAttr->getFunction();
1273 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1274 }
1275 return UseDecl->getBuiltinID(/*ConsiderWrappers=*/true);
1276 }
1277
1278 /// Return function name after stripping __builtin_ and _chk affixes.
1279 std::string getFunctionName() const {
1280 unsigned ID = getBuiltinID();
1281 if (!ID) {
1282 // Use callee name directly if not a builtin.
1283 const FunctionDecl *Callee = TheCall->getDirectCallee();
1284 assert(Callee && "expected callee");
1285 return Callee->getName().str();
1286 }
1287 std::string Name = S.getASTContext().BuiltinInfo.getName(ID);
1288 StringRef Ref = Name;
1289 // Strip __builtin___*_chk or __builtin_ prefix.
1290 if (!(Ref.consume_front("__builtin___") && Ref.consume_back("_chk")))
1291 Ref.consume_front("__builtin_");
1292 assert(!Ref.empty() && "expected non-empty function name");
1293 return Ref.str();
1294 }
1295
1296 /// Check for source buffer overread in memory functions.
1297 void checkSourceOverread(unsigned SrcArgIdx, unsigned SizeArgIdx) {
1299 return;
1300
1301 const Expr *SrcArg = TheCall->getArg(SrcArgIdx);
1302 const Expr *SizeArg = TheCall->getArg(SizeArgIdx);
1303 if (SrcArg->isInstantiationDependent() ||
1304 SizeArg->isInstantiationDependent())
1305 return;
1306
1307 std::optional<llvm::APSInt> CopyLen =
1308 ComputeExplicitObjectSizeArgument(SizeArgIdx);
1309 std::optional<llvm::APSInt> SrcBufSize = ComputeSizeArgument(SrcArgIdx);
1310
1311 if (!CopyLen || !SrcBufSize)
1312 return;
1313
1314 // Warn only if copy length exceeds source buffer size.
1315 if (llvm::APSInt::compareValues(*CopyLen, *SrcBufSize) <= 0)
1316 return;
1317
1318 S.DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1319 S.PDiag(diag::warn_stringop_overread)
1320 << getFunctionName() << CopyLen->getZExtValue()
1321 << SrcBufSize->getZExtValue());
1322 }
1323
1324private:
1325 Sema &S;
1326 CallExpr *TheCall;
1327 FunctionDecl *FD;
1328 const DiagnoseAsBuiltinAttr *DABAttr;
1329 unsigned SizeTypeWidth;
1330};
1331} // anonymous namespace
1332
1333void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1334 CallExpr *TheCall) {
1336 return;
1337
1338 FortifiedBufferChecker Checker(*this, FD, TheCall);
1339
1340 unsigned BuiltinID = Checker.getBuiltinID();
1341 if (!BuiltinID)
1342 return;
1343
1344 unsigned SizeTypeWidth = Checker.getSizeTypeWidth();
1345
1346 std::optional<llvm::APSInt> AccessSize;
1347 std::optional<llvm::APSInt> BufferSize;
1348 unsigned DiagID = 0;
1349
1350 switch (BuiltinID) {
1351 default:
1352 return;
1353 case Builtin::BI__builtin_strcat:
1354 case Builtin::BIstrcat:
1355 case Builtin::BI__builtin_stpcpy:
1356 case Builtin::BIstpcpy:
1357 case Builtin::BI__builtin_strcpy:
1358 case Builtin::BIstrcpy: {
1359 DiagID = diag::warn_fortify_strlen_overflow;
1360 AccessSize = Checker.ComputeStrLenArgument(1);
1361 BufferSize = Checker.ComputeSizeArgument(0);
1362 break;
1363 }
1364
1365 case Builtin::BI__builtin___strcat_chk:
1366 case Builtin::BI__builtin___stpcpy_chk:
1367 case Builtin::BI__builtin___strcpy_chk: {
1368 DiagID = diag::warn_fortify_strlen_overflow;
1369 AccessSize = Checker.ComputeStrLenArgument(1);
1370 BufferSize = Checker.ComputeExplicitObjectSizeArgument(2);
1371 break;
1372 }
1373
1374 case Builtin::BIscanf:
1375 case Builtin::BIfscanf:
1376 case Builtin::BIsscanf: {
1377 unsigned FormatIndex = 1;
1378 unsigned DataIndex = 2;
1379 if (BuiltinID == Builtin::BIscanf) {
1380 FormatIndex = 0;
1381 DataIndex = 1;
1382 }
1383
1384 const auto *FormatExpr =
1385 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
1386
1387 StringRef FormatStrRef;
1388 size_t StrLen;
1389 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1390 return;
1391
1392 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1393 unsigned SourceSize) {
1394 DiagID = diag::warn_fortify_scanf_overflow;
1395 unsigned Index = ArgIndex + DataIndex;
1396 std::string FunctionName = Checker.getFunctionName();
1397 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall,
1398 PDiag(DiagID) << FunctionName << (Index + 1)
1399 << DestSize << SourceSize);
1400 };
1401
1402 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1403 return Checker.ComputeSizeArgument(Index + DataIndex);
1404 };
1405 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1406 const char *FormatBytes = FormatStrRef.data();
1408 FormatBytes + StrLen, getLangOpts(),
1409 Context.getTargetInfo());
1410
1411 // Unlike the other cases, in this one we have already issued the diagnostic
1412 // here, so no need to continue (because unlike the other cases, here the
1413 // diagnostic refers to the argument number).
1414 return;
1415 }
1416
1417 case Builtin::BIsprintf:
1418 case Builtin::BI__builtin_sprintf:
1419 case Builtin::BI__builtin___sprintf_chk:
1420 case Builtin::BIvsprintf:
1421 case Builtin::BI__builtin_vsprintf:
1422 case Builtin::BI__builtin___vsprintf_chk: {
1423 bool IsChk = BuiltinID == Builtin::BI__builtin___sprintf_chk ||
1424 BuiltinID == Builtin::BI__builtin___vsprintf_chk;
1425 std::optional<unsigned> FormatIndex = Checker.TranslateIndex(IsChk ? 3 : 1);
1426 if (!FormatIndex)
1427 return;
1428 const auto *FormatExpr =
1429 TheCall->getArg(*FormatIndex)->IgnoreParenImpCasts();
1430
1431 StringRef FormatStrRef;
1432 size_t StrLen;
1433 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1434 EstimateSizeFormatHandler H(FormatStrRef);
1435 const char *FormatBytes = FormatStrRef.data();
1437 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1438 Context.getTargetInfo(), false)) {
1439 DiagID = H.isKernelCompatible()
1440 ? diag::warn_format_overflow
1441 : diag::warn_format_overflow_non_kprintf;
1442 AccessSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1443 .extOrTrunc(SizeTypeWidth);
1444 if (IsChk) {
1445 BufferSize = Checker.ComputeExplicitObjectSizeArgument(2);
1446 } else {
1447 BufferSize = Checker.ComputeSizeArgument(0);
1448 }
1449 break;
1450 }
1451 }
1452 return;
1453 }
1454 case Builtin::BI__builtin___memcpy_chk:
1455 case Builtin::BI__builtin___memmove_chk:
1456 case Builtin::BI__builtin___memset_chk:
1457 case Builtin::BI__builtin___strlcat_chk:
1458 case Builtin::BI__builtin___strlcpy_chk:
1459 case Builtin::BI__builtin___strncat_chk:
1460 case Builtin::BI__builtin___strncpy_chk:
1461 case Builtin::BI__builtin___stpncpy_chk:
1462 case Builtin::BI__builtin___memccpy_chk:
1463 case Builtin::BI__builtin___mempcpy_chk: {
1464 DiagID = diag::warn_builtin_chk_overflow;
1465 AccessSize =
1466 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1467 BufferSize =
1468 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1469
1470 if (BuiltinID == Builtin::BI__builtin___memcpy_chk ||
1471 BuiltinID == Builtin::BI__builtin___memmove_chk ||
1472 BuiltinID == Builtin::BI__builtin___mempcpy_chk) {
1473 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1474 }
1475 break;
1476 }
1477
1478 case Builtin::BI__builtin___snprintf_chk:
1479 case Builtin::BI__builtin___vsnprintf_chk: {
1480 DiagID = diag::warn_builtin_chk_overflow;
1481 AccessSize = Checker.ComputeExplicitObjectSizeArgument(1);
1482 BufferSize = Checker.ComputeExplicitObjectSizeArgument(3);
1483 break;
1484 }
1485
1486 case Builtin::BIstrncat:
1487 case Builtin::BI__builtin_strncat:
1488 case Builtin::BIstrncpy:
1489 case Builtin::BI__builtin_strncpy:
1490 case Builtin::BIstpncpy:
1491 case Builtin::BI__builtin_stpncpy:
1492 case Builtin::BIstrlcat:
1493 case Builtin::BI__builtin_strlcat:
1494 case Builtin::BIstrlcpy:
1495 case Builtin::BI__builtin_strlcpy: {
1496 // Whether these functions overflow depends on the runtime strlen of the
1497 // string, not just the buffer size, so emitting the "always overflow"
1498 // diagnostic isn't quite right. We should still diagnose passing a buffer
1499 // size larger than the destination buffer though; this is a runtime abort
1500 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1501 DiagID = diag::warn_fortify_source_size_mismatch;
1502 AccessSize =
1503 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1504 BufferSize = Checker.ComputeSizeArgument(0);
1505 break;
1506 }
1507
1508 case Builtin::BIrecv:
1509 case Builtin::BIrecvfrom: {
1510 unsigned ExpectedArgs = BuiltinID == Builtin::BIrecv ? 4 : 6;
1511 if (TheCall->getNumArgs() != ExpectedArgs ||
1512 !TheCall->getArg(1)->getType()->isPointerType() ||
1513 !TheCall->getArg(2)->getType()->isIntegerType())
1514 return;
1515 DiagID = diag::warn_fortify_source_size_mismatch;
1516 AccessSize = Checker.ComputeExplicitObjectSizeArgument(2);
1517 BufferSize = Checker.ComputeSizeArgument(1);
1518 break;
1519 }
1520
1521 case Builtin::BIpoll:
1522 case Builtin::BIppoll:
1523 case Builtin::BIppoll64: {
1524 unsigned ExpectedArgs = BuiltinID == Builtin::BIpoll ? 3 : 4;
1525 if (TheCall->getNumArgs() != ExpectedArgs ||
1526 !TheCall->getArg(1)->getType()->isIntegerType())
1527 return;
1528 QualType PointeeTy = TheCall->getArg(0)->getType()->getPointeeType();
1529 if (PointeeTy.isNull())
1530 return;
1531 const RecordDecl *RD = PointeeTy->getAsRecordDecl();
1532 if (!RD || !RD->getIdentifier() || RD->getName() != "pollfd")
1533 return;
1534 if (BuiltinID == Builtin::BIpoll) {
1535 if (!TheCall->getArg(2)->getType()->isIntegerType())
1536 return;
1537 } else {
1538 QualType TmoPointeeTy = TheCall->getArg(2)->getType()->getPointeeType();
1539 if (TmoPointeeTy.isNull())
1540 return;
1541 const RecordDecl *TmoRD = TmoPointeeTy->getAsRecordDecl();
1542 if (!TmoRD || !TmoRD->getIdentifier() || TmoRD->getName() != "timespec" ||
1543 !TheCall->getArg(3)->getType()->isPointerType())
1544 return;
1545 }
1546 std::optional<CharUnits> ElemSize =
1547 Context.getTypeSizeInCharsIfKnown(PointeeTy);
1548 if (!ElemSize)
1549 return;
1550 std::optional<llvm::APSInt> Count =
1551 Checker.ComputeExplicitObjectSizeArgument(1);
1552 if (!Count)
1553 return;
1554 DiagID = diag::warn_fortify_source_size_mismatch;
1555 unsigned WideWidth = SizeTypeWidth * 2;
1556 AccessSize = Count->extOrTrunc(WideWidth) *
1557 llvm::APSInt(llvm::APInt(WideWidth, ElemSize->getQuantity()),
1558 /*isUnsigned=*/true);
1559 BufferSize = Checker.ComputeSizeArgument(0);
1560 break;
1561 }
1562
1563 case Builtin::BIbzero:
1564 case Builtin::BI__builtin_bzero:
1565 case Builtin::BImemcpy:
1566 case Builtin::BI__builtin_memcpy:
1567 case Builtin::BImemmove:
1568 case Builtin::BI__builtin_memmove:
1569 case Builtin::BImemset:
1570 case Builtin::BI__builtin_memset:
1571 case Builtin::BImempcpy:
1572 case Builtin::BI__builtin_mempcpy: {
1573 DiagID = diag::warn_fortify_source_overflow;
1574 AccessSize =
1575 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1576 BufferSize = Checker.ComputeSizeArgument(0);
1577
1578 // Buffer overread doesn't make sense for memset/bzero.
1579 if (BuiltinID != Builtin::BImemset &&
1580 BuiltinID != Builtin::BI__builtin_memset &&
1581 BuiltinID != Builtin::BIbzero &&
1582 BuiltinID != Builtin::BI__builtin_bzero) {
1583 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1584 }
1585 break;
1586 }
1587 case Builtin::BIbcopy:
1588 case Builtin::BI__builtin_bcopy: {
1589 DiagID = diag::warn_fortify_source_overflow;
1590 AccessSize =
1591 Checker.ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1592 BufferSize = Checker.ComputeSizeArgument(1);
1593 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1594 break;
1595 }
1596 case Builtin::BIfread: {
1597 DiagID = diag::warn_fortify_source_overflow;
1598 AccessSize = Checker.ComputeExplicitObjectSizeArgumentProduct(1, 2);
1599 BufferSize = Checker.ComputeSizeArgument(0);
1600 break;
1601 }
1602 case Builtin::BIfwrite: {
1603 DiagID = diag::warn_fortify_source_overread;
1604 AccessSize = Checker.ComputeExplicitObjectSizeArgumentProduct(1, 2);
1605 BufferSize = Checker.ComputeSizeArgument(0);
1606 break;
1607 }
1608 case Builtin::BIfgets: {
1609 AccessSize = Checker.EvaluateIntegerArgument(1);
1610
1611 if (AccessSize && AccessSize->isNegative()) {
1612 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1613 PDiag(diag::warn_fortify_source_negative_size)
1614 << Checker.getFunctionName());
1615 return;
1616 }
1617
1618 DiagID = diag::warn_fortify_source_size_mismatch;
1619 BufferSize = Checker.ComputeSizeArgument(0);
1620 break;
1621 }
1622 // memchr(buf, val, size)
1623 case Builtin::BImemchr:
1624 case Builtin::BI__builtin_memchr: {
1625 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1626 return;
1627 }
1628
1629 // memcmp/bcmp(buf0, buf1, size)
1630 // Two checks since each buffer is read
1631 case Builtin::BImemcmp:
1632 case Builtin::BI__builtin_memcmp:
1633 case Builtin::BIbcmp:
1634 case Builtin::BI__builtin_bcmp: {
1635 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1636 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1637 return;
1638 }
1639 case Builtin::BIsnprintf:
1640 case Builtin::BI__builtin_snprintf:
1641 case Builtin::BIvsnprintf:
1642 case Builtin::BI__builtin_vsnprintf: {
1643 DiagID = diag::warn_fortify_source_size_mismatch;
1644 AccessSize = Checker.ComputeExplicitObjectSizeArgument(1);
1645 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts();
1646 StringRef FormatStrRef;
1647 size_t StrLen;
1648 if (AccessSize &&
1649 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1650 EstimateSizeFormatHandler H(FormatStrRef);
1651 const char *FormatBytes = FormatStrRef.data();
1653 H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
1654 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1655 llvm::APSInt FormatSize =
1656 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1657 .extOrTrunc(SizeTypeWidth);
1658 if (FormatSize > *AccessSize && *AccessSize != 0) {
1659 unsigned TruncationDiagID =
1660 H.isKernelCompatible() ? diag::warn_format_truncation
1661 : diag::warn_format_truncation_non_kprintf;
1662 SmallString<16> SpecifiedSizeStr;
1663 SmallString<16> FormatSizeStr;
1664 AccessSize->toString(SpecifiedSizeStr, /*Radix=*/10);
1665 FormatSize.toString(FormatSizeStr, /*Radix=*/10);
1666 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1667 PDiag(TruncationDiagID)
1668 << Checker.getFunctionName()
1669 << SpecifiedSizeStr << FormatSizeStr);
1670 }
1671 }
1672 }
1673 BufferSize = Checker.ComputeSizeArgument(0);
1674 const Expr *LenArg = TheCall->getArg(1)->IgnoreCasts();
1675 const Expr *Dest = TheCall->getArg(0)->IgnoreCasts();
1676 IdentifierInfo *FnInfo = FD->getIdentifier();
1677 CheckSizeofMemaccessArgument(LenArg, Dest, FnInfo);
1678 }
1679 }
1680
1681 if (!AccessSize || !BufferSize ||
1682 llvm::APSInt::compareValues(*AccessSize, *BufferSize) <= 0)
1683 return;
1684
1685 std::string FunctionName = Checker.getFunctionName();
1686
1687 SmallString<16> BufferSizeStr;
1688 SmallString<16> AccessSizeStr;
1689 BufferSize->toString(BufferSizeStr, /*Radix=*/10);
1690 AccessSize->toString(AccessSizeStr, /*Radix=*/10);
1691 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
1692 PDiag(DiagID)
1693 << FunctionName << BufferSizeStr << AccessSizeStr);
1694}
1695
1696void Sema::checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall) {
1697 if (TheCall->isValueDependent() || TheCall->isTypeDependent())
1698 return;
1699
1700 // Recognize the libc function by builtin identity rather than by name and
1701 // system-header origin. umask is a LibBuiltin marked IgnoreSignature, so the
1702 // builtin id is attached to any file-scope, C-linkage declaration of umask
1703 // regardless of the libc's mode_t spelling -- including a hand-written
1704 // forward declaration without <sys/stat.h>. A static/local lookalike or a
1705 // C++ (non-extern-"C") declaration keeps a zero builtin id and is ignored.
1706 if (FD->getBuiltinID() != Builtin::BIumask)
1707 return;
1708
1709 // umask(mode_t): warn when the constant-evaluated argument has bits set
1710 // outside the file-permission mask (0777). Those bits are ignored.
1711 if (TheCall->getNumArgs() != 1)
1712 return;
1713 Expr *Arg = TheCall->getArg(0);
1714 if (!Arg->getType()->isIntegerType())
1715 return;
1716 Expr::EvalResult R;
1717 if (!Arg->EvaluateAsInt(R, getASTContext()))
1718 return;
1719 // Operate on the raw two's-complement bit pattern so that negative literals
1720 // (which convert to large unsigned mode_t values) are caught.
1721 llvm::APInt RawValue = R.Val.getInt();
1722 llvm::APInt Mask(RawValue.getBitWidth(), 0777);
1723 llvm::APInt Extra = RawValue & ~Mask;
1724 if (Extra == 0)
1725 return;
1726 SmallString<16> ExtraStr;
1727 Extra.toString(ExtraStr, /*Radix=*/8, /*Signed=*/false);
1728 Diag(TheCall->getBeginLoc(), diag::warn_fortify_umask_unused_bits)
1729 << ExtraStr;
1730}
1731
1732static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1733 Scope::ScopeFlags NeededScopeFlags,
1734 unsigned DiagID) {
1735 // Scopes aren't available during instantiation. Fortunately, builtin
1736 // functions cannot be template args so they cannot be formed through template
1737 // instantiation. Therefore checking once during the parse is sufficient.
1738 if (SemaRef.inTemplateInstantiation())
1739 return false;
1740
1741 Scope *S = SemaRef.getCurScope();
1742 while (S && !S->isSEHExceptScope())
1743 S = S->getParent();
1744 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1745 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1746 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
1747 << DRE->getDecl()->getIdentifier();
1748 return true;
1749 }
1750
1751 return false;
1752}
1753
1754// In OpenCL, __builtin_alloca_* should return a pointer to address space
1755// that corresponds to the stack address space i.e private address space.
1756static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1757 QualType RT = TheCall->getType();
1758 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1759 "__builtin_alloca has invalid address space");
1760
1761 RT = RT->getPointeeType();
1763 TheCall->setType(S.Context.getPointerType(RT));
1764}
1765
1766static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1767 if (S.checkArgCountAtLeast(TheCall, 1))
1768 return true;
1769
1770 for (Expr *Arg : TheCall->arguments()) {
1771 // If argument is dependent on a template parameter, we can't resolve now.
1772 if (Arg->isTypeDependent() || Arg->isValueDependent())
1773 continue;
1774 // Reject void types.
1775 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1776 if (ArgTy->isVoidType())
1777 return S.Diag(Arg->getBeginLoc(), diag::err_param_with_void_type);
1778 }
1779
1780 TheCall->setType(S.Context.getSizeType());
1781 return false;
1782}
1783
1784namespace {
1785enum PointerAuthOpKind {
1786 PAO_Strip,
1787 PAO_Sign,
1788 PAO_Auth,
1789 PAO_SignGeneric,
1790 PAO_Discriminator,
1791 PAO_BlendPointer,
1792 PAO_BlendInteger,
1793 PAO_BlendPC
1794};
1795}
1796
1798 if (getLangOpts().PointerAuthIntrinsics)
1799 return false;
1800
1801 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1802 return true;
1803}
1804
1805static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1807}
1808
1809static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1810 // Convert it to type 'int'.
1811 if (S.convertArgumentToType(Arg, S.Context.IntTy))
1812 return true;
1813
1814 // Value-dependent expressions are okay; wait for template instantiation.
1815 if (Arg->isValueDependent())
1816 return false;
1817
1818 unsigned KeyValue;
1819 return S.checkConstantPointerAuthKey(Arg, KeyValue);
1820}
1821
1823 // Attempt to constant-evaluate the expression.
1824 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context);
1825 if (!KeyValue) {
1826 Diag(Arg->getExprLoc(), diag::err_expr_not_ice)
1827 << 0 << Arg->getSourceRange();
1828 return true;
1829 }
1830
1831 // Ask the target to validate the key parameter.
1832 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1834 {
1835 llvm::raw_svector_ostream Str(Value);
1836 Str << *KeyValue;
1837 }
1838
1839 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key)
1840 << Value << Arg->getSourceRange();
1841 return true;
1842 }
1843
1844 Result = KeyValue->getZExtValue();
1845 return false;
1846}
1847
1850 unsigned &IntVal) {
1851 if (!Arg) {
1852 IntVal = 0;
1853 return true;
1854 }
1855
1856 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
1857 if (!Result) {
1858 Diag(Arg->getExprLoc(), diag::err_ptrauth_arg_not_ice);
1859 return false;
1860 }
1861
1862 unsigned Max;
1863 bool IsAddrDiscArg = false;
1864
1865 switch (Kind) {
1867 Max = 1;
1868 IsAddrDiscArg = true;
1869 break;
1872 break;
1873 };
1874
1876 if (IsAddrDiscArg)
1877 Diag(Arg->getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1878 << Result->getExtValue();
1879 else
1880 Diag(Arg->getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1881 << Result->getExtValue() << Max;
1882
1883 return false;
1884 };
1885
1886 IntVal = Result->getZExtValue();
1887 return true;
1888}
1889
1890static std::pair<const ValueDecl *, CharUnits>
1892 // Must evaluate as a pointer.
1894 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue())
1895 return {nullptr, CharUnits()};
1896
1897 const auto *BaseDecl =
1898 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1899 if (!BaseDecl)
1900 return {nullptr, CharUnits()};
1901
1902 return {BaseDecl, Result.Val.getLValueOffset()};
1903}
1904
1905static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1906 bool RequireConstant = false) {
1907 if (Arg->hasPlaceholderType()) {
1909 if (R.isInvalid())
1910 return true;
1911 Arg = R.get();
1912 }
1913
1914 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1915 return OpKind != PAO_BlendInteger;
1916 };
1917 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1918 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1919 OpKind == PAO_SignGeneric || OpKind == PAO_BlendPC;
1920 };
1921
1922 // Require the value to have the right range of type.
1923 QualType ExpectedTy;
1924 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1925 ExpectedTy = Arg->getType().getUnqualifiedType();
1926 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1927 ExpectedTy = S.Context.VoidPtrTy;
1928 } else if (AllowsInteger(OpKind) &&
1930 ExpectedTy = S.Context.getUIntPtrType();
1931
1932 } else {
1933 // Diagnose the failures.
1934 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type)
1935 << unsigned(OpKind == PAO_Discriminator ? 1
1936 : OpKind == PAO_BlendPointer ? 2
1937 : OpKind == PAO_BlendInteger ? 3
1938 : OpKind == PAO_BlendPC ? 4
1939 : 0)
1940 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1941 << Arg->getType() << Arg->getSourceRange();
1942 return true;
1943 }
1944
1945 // Convert to that type. This should just be an lvalue-to-rvalue
1946 // conversion.
1947 if (S.convertArgumentToType(Arg, ExpectedTy))
1948 return true;
1949
1950 if (!RequireConstant) {
1951 // Warn about null pointers for non-generic sign and auth operations.
1952 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1954 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign
1955 ? diag::warn_ptrauth_sign_null_pointer
1956 : diag::warn_ptrauth_auth_null_pointer)
1957 << Arg->getSourceRange();
1958 }
1959
1960 return false;
1961 }
1962
1963 // Perform special checking on the arguments to ptrauth_sign_constant.
1964
1965 // The main argument.
1966 if (OpKind == PAO_Sign) {
1967 // Require the value we're signing to have a special form.
1968 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg);
1969 bool Invalid;
1970
1971 // Must be rooted in a declaration reference.
1972 if (!BaseDecl)
1973 Invalid = true;
1974
1975 // If it's a function declaration, we can't have an offset.
1976 else if (isa<FunctionDecl>(BaseDecl))
1977 Invalid = !Offset.isZero();
1978
1979 // Otherwise we're fine.
1980 else
1981 Invalid = false;
1982
1983 if (Invalid)
1984 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
1985 return Invalid;
1986 }
1987
1988 // The discriminator argument.
1989 assert(OpKind == PAO_Discriminator);
1990
1991 // Must be a pointer or integer or blend thereof.
1992 Expr *Pointer = nullptr;
1993 Expr *Integer = nullptr;
1994 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) {
1995 if (Call->getBuiltinCallee() ==
1996 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1997 Pointer = Call->getArg(0);
1998 Integer = Call->getArg(1);
1999 }
2000 }
2001 if (!Pointer && !Integer) {
2002 if (Arg->getType()->isPointerType())
2003 Pointer = Arg;
2004 else
2005 Integer = Arg;
2006 }
2007
2008 // Check the pointer.
2009 bool Invalid = false;
2010 if (Pointer) {
2011 assert(Pointer->getType()->isPointerType());
2012
2013 // TODO: if we're initializing a global, check that the address is
2014 // somehow related to what we're initializing. This probably will
2015 // never really be feasible and we'll have to catch it at link-time.
2016 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer);
2017 if (!BaseDecl || !isa<VarDecl>(BaseDecl))
2018 Invalid = true;
2019 }
2020
2021 // Check the integer.
2022 if (Integer) {
2023 assert(Integer->getType()->isIntegerType());
2024 if (!Integer->isEvaluatable(S.Context))
2025 Invalid = true;
2026 }
2027
2028 if (Invalid)
2029 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
2030 return Invalid;
2031}
2032
2034 if (S.checkArgCount(Call, 2))
2035 return ExprError();
2037 return ExprError();
2038 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) ||
2039 checkPointerAuthKey(S, Call->getArgs()[1]))
2040 return ExprError();
2041
2042 Call->setType(Call->getArgs()[0]->getType());
2043 return Call;
2044}
2045
2047 if (S.checkArgCount(Call, 2))
2048 return ExprError();
2050 return ExprError();
2051 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) ||
2052 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger))
2053 return ExprError();
2054
2055 Call->setType(S.Context.getUIntPtrType());
2056 return Call;
2057}
2058
2060 if (S.checkArgCount(Call, 2))
2061 return ExprError();
2063 return ExprError();
2064 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) ||
2065 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator))
2066 return ExprError();
2067
2068 Call->setType(S.Context.getUIntPtrType());
2069 return Call;
2070}
2071
2073 PointerAuthOpKind OpKind,
2074 bool RequireConstant) {
2075 if (S.checkArgCount(Call, 3))
2076 return ExprError();
2078 return ExprError();
2079 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) ||
2080 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2081 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator,
2082 RequireConstant))
2083 return ExprError();
2084
2085 Call->setType(Call->getArgs()[0]->getType());
2086 return Call;
2087}
2088
2090 if (S.checkArgCount(Call, 5))
2091 return ExprError();
2093 return ExprError();
2094 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2095 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2096 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2097 checkPointerAuthKey(S, Call->getArgs()[3]) ||
2098 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator))
2099 return ExprError();
2100
2101 Call->setType(Call->getArgs()[0]->getType());
2102 return Call;
2103}
2104
2106 if (S.checkArgCount(Call, 6))
2107 return ExprError();
2109 return ExprError();
2110 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2111 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2112 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2113 checkPointerAuthValue(S, Call->getArgs()[3], PAO_BlendPC) ||
2114 checkPointerAuthKey(S, Call->getArgs()[4]) ||
2115 checkPointerAuthValue(S, Call->getArgs()[5], PAO_Discriminator))
2116 return ExprError();
2117
2118 // Validate that the oldKey is IA or IB, not DA or DB.
2119 // This enforces the constraint that auth_with_pc_and_resign only supports
2120 // IA/IB keys for authentication, as only those keys support the PC-based
2121 // signing instructions (paciasppc/pacibsppc).
2122 unsigned OldKey = 0;
2123 if (!S.checkConstantPointerAuthKey(Call->getArgs()[1], OldKey)) {
2125 if (OldKey != static_cast<unsigned>(AK::ASIA) &&
2126 OldKey != static_cast<unsigned>(AK::ASIB)) {
2127 S.Diag(Call->getArgs()[1]->getExprLoc(),
2128 diag::err_ptrauth_auth_with_pc_and_resign_invalid_key)
2129 << OldKey << Call->getArgs()[1]->getSourceRange();
2130 return ExprError();
2131 }
2132 }
2133
2134 Call->setType(Call->getArgs()[0]->getType());
2135 return Call;
2136}
2137
2139 if (S.checkArgCount(Call, 6))
2140 return ExprError();
2142 return ExprError();
2143 const Expr *AddendExpr = Call->getArg(5);
2144 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(S.Context);
2145 if (!AddendIsConstInt) {
2146 const Expr *Arg = Call->getArg(5)->IgnoreParenImpCasts();
2147 DeclRefExpr *DRE = cast<DeclRefExpr>(Call->getCallee()->IgnoreParenCasts());
2148 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2149 S.Diag(Arg->getBeginLoc(), diag::err_constant_integer_last_arg_type)
2150 << FDecl->getDeclName() << Arg->getSourceRange();
2151 }
2152 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) ||
2153 checkPointerAuthKey(S, Call->getArgs()[1]) ||
2154 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) ||
2155 checkPointerAuthKey(S, Call->getArgs()[3]) ||
2156 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator) ||
2157 !AddendIsConstInt)
2158 return ExprError();
2159
2160 Call->setType(Call->getArgs()[0]->getType());
2161 return Call;
2162}
2163
2166 return ExprError();
2167
2168 // We've already performed normal call type-checking.
2169 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts();
2170
2171 // Operand must be an ordinary or UTF-8 string literal.
2172 const auto *Literal = dyn_cast<StringLiteral>(Arg);
2173 if (!Literal || Literal->getCharByteWidth() != 1) {
2174 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal)
2175 << (Literal ? 1 : 0) << Arg->getSourceRange();
2176 return ExprError();
2177 }
2178
2179 return Call;
2180}
2181
2183 if (S.checkArgCount(Call, 1))
2184 return ExprError();
2185 Expr *FirstArg = Call->getArg(0);
2186 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(FirstArg);
2187 if (FirstValue.isInvalid())
2188 return ExprError();
2189 Call->setArg(0, FirstValue.get());
2190 QualType FirstArgType = FirstArg->getType();
2191 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
2192 FirstArgType = S.Context.getDecayedType(FirstArgType);
2193
2194 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
2195 if (!FirstArgRecord) {
2196 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
2197 << /*isPolymorphic=*/0 << FirstArgType;
2198 return ExprError();
2199 }
2200 if (S.RequireCompleteType(
2201 FirstArg->getBeginLoc(), FirstArgType->getPointeeType(),
2202 diag::err_get_vtable_pointer_requires_complete_type)) {
2203 return ExprError();
2204 }
2205
2206 if (!FirstArgRecord->isPolymorphic()) {
2207 S.Diag(FirstArg->getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
2208 << /*isPolymorphic=*/1 << FirstArgRecord;
2209 return ExprError();
2210 }
2212 Call->setType(ReturnType);
2213 return Call;
2214}
2215
2217 if (S.checkArgCount(TheCall, 1))
2218 return ExprError();
2219
2220 // Compute __builtin_launder's parameter type from the argument.
2221 // The parameter type is:
2222 // * The type of the argument if it's not an array or function type,
2223 // Otherwise,
2224 // * The decayed argument type.
2225 QualType ParamTy = [&]() {
2226 QualType ArgTy = TheCall->getArg(0)->getType();
2227 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
2228 return S.Context.getPointerType(Ty->getElementType());
2229 if (ArgTy->isFunctionType()) {
2230 return S.Context.getPointerType(ArgTy);
2231 }
2232 return ArgTy;
2233 }();
2234
2235 TheCall->setType(ParamTy);
2236
2237 auto DiagSelect = [&]() -> std::optional<unsigned> {
2238 if (!ParamTy->isPointerType())
2239 return 0;
2240 if (ParamTy->isFunctionPointerType())
2241 return 1;
2242 if (ParamTy->isVoidPointerType())
2243 return 2;
2244 return std::optional<unsigned>{};
2245 }();
2246 if (DiagSelect) {
2247 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
2248 << *DiagSelect << TheCall->getSourceRange();
2249 return ExprError();
2250 }
2251
2252 // We either have an incomplete class type, or we have a class template
2253 // whose instantiation has not been forced. Example:
2254 //
2255 // template <class T> struct Foo { T value; };
2256 // Foo<int> *p = nullptr;
2257 // auto *d = __builtin_launder(p);
2258 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
2259 diag::err_incomplete_type))
2260 return ExprError();
2261
2262 assert(ParamTy->getPointeeType()->isObjectType() &&
2263 "Unhandled non-object pointer case");
2264
2265 InitializedEntity Entity =
2267 ExprResult Arg =
2268 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
2269 if (Arg.isInvalid())
2270 return ExprError();
2271 TheCall->setArg(0, Arg.get());
2272
2273 return TheCall;
2274}
2275
2277 if (S.checkArgCount(TheCall, 1))
2278 return ExprError();
2279
2281 if (Arg.isInvalid())
2282 return ExprError();
2283 QualType ParamTy = Arg.get()->getType();
2284 TheCall->setArg(0, Arg.get());
2285 TheCall->setType(S.Context.BoolTy);
2286
2287 // Only accept pointers to objects as arguments, which should have object
2288 // pointer or void pointer types.
2289 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2290 // LWG4138: Function pointer types not allowed
2291 if (PT->getPointeeType()->isFunctionType()) {
2292 S.Diag(TheCall->getArg(0)->getExprLoc(),
2293 diag::err_builtin_is_within_lifetime_invalid_arg)
2294 << 1;
2295 return ExprError();
2296 }
2297 // Disallow VLAs too since those shouldn't be able to
2298 // be a template parameter for `std::is_within_lifetime`
2299 if (PT->getPointeeType()->isVariableArrayType()) {
2300 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported)
2301 << 1 << "__builtin_is_within_lifetime";
2302 return ExprError();
2303 }
2304 } else {
2305 S.Diag(TheCall->getArg(0)->getExprLoc(),
2306 diag::err_builtin_is_within_lifetime_invalid_arg)
2307 << 0;
2308 return ExprError();
2309 }
2310 return TheCall;
2311}
2312
2314 if (S.checkArgCount(TheCall, 3))
2315 return ExprError();
2316
2317 QualType Dest = TheCall->getArg(0)->getType();
2318 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2319 S.Diag(TheCall->getArg(0)->getExprLoc(),
2320 diag::err_builtin_trivially_relocate_invalid_arg_type)
2321 << /*a pointer*/ 0;
2322 return ExprError();
2323 }
2324
2325 QualType T = Dest->getPointeeType();
2326 if (S.RequireCompleteType(TheCall->getBeginLoc(), T,
2327 diag::err_incomplete_type))
2328 return ExprError();
2329
2330 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2331 T->isIncompleteArrayType()) {
2332 S.Diag(TheCall->getArg(0)->getExprLoc(),
2333 diag::err_builtin_trivially_relocate_invalid_arg_type)
2334 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2335 return ExprError();
2336 }
2337
2338 TheCall->setType(Dest);
2339
2340 QualType Src = TheCall->getArg(1)->getType();
2341 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2342 S.Diag(TheCall->getArg(1)->getExprLoc(),
2343 diag::err_builtin_trivially_relocate_invalid_arg_type)
2344 << /*the same*/ 3;
2345 return ExprError();
2346 }
2347
2348 Expr *SizeExpr = TheCall->getArg(2);
2349 ExprResult Size = S.DefaultLvalueConversion(SizeExpr);
2350 if (Size.isInvalid())
2351 return ExprError();
2352
2353 Size = S.tryConvertExprToType(Size.get(), S.getASTContext().getSizeType());
2354 if (Size.isInvalid())
2355 return ExprError();
2356 SizeExpr = Size.get();
2357 TheCall->setArg(2, SizeExpr);
2358
2359 return TheCall;
2360}
2361
2362// Emit an error and return true if the current object format type is in the
2363// list of unsupported types.
2365 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2366 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2367 llvm::Triple::ObjectFormatType CurObjFormat =
2368 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2369 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2370 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2371 << TheCall->getSourceRange();
2372 return true;
2373 }
2374 return false;
2375}
2376
2377// Emit an error and return true if the current architecture is not in the list
2378// of supported architectures.
2379static bool
2381 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2382 llvm::Triple::ArchType CurArch =
2383 S.getASTContext().getTargetInfo().getTriple().getArch();
2384 if (llvm::is_contained(SupportedArchs, CurArch))
2385 return false;
2386 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
2387 << TheCall->getSourceRange();
2388 return true;
2389}
2390
2391static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2392 SourceLocation CallSiteLoc);
2393
2394bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2395 CallExpr *TheCall) {
2396 switch (TI.getTriple().getArch()) {
2397 default:
2398 // Some builtins don't require additional checking, so just consider these
2399 // acceptable.
2400 return false;
2401 case llvm::Triple::arm:
2402 case llvm::Triple::armeb:
2403 case llvm::Triple::thumb:
2404 case llvm::Triple::thumbeb:
2405 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2406 case llvm::Triple::aarch64:
2407 case llvm::Triple::aarch64_32:
2408 case llvm::Triple::aarch64_be:
2409 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2410 case llvm::Triple::bpfeb:
2411 case llvm::Triple::bpfel:
2412 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2413 case llvm::Triple::dxil:
2414 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2415 case llvm::Triple::hexagon:
2416 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2417 case llvm::Triple::mips:
2418 case llvm::Triple::mipsel:
2419 case llvm::Triple::mips64:
2420 case llvm::Triple::mips64el:
2421 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2422 case llvm::Triple::spirv:
2423 case llvm::Triple::spirv32:
2424 case llvm::Triple::spirv64:
2425 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2426 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2427 return false;
2428 case llvm::Triple::systemz:
2429 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2430 case llvm::Triple::x86:
2431 case llvm::Triple::x86_64:
2432 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2433 case llvm::Triple::ppc:
2434 case llvm::Triple::ppcle:
2435 case llvm::Triple::ppc64:
2436 case llvm::Triple::ppc64le:
2437 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2438 case llvm::Triple::amdgpu:
2439 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(TI, BuiltinID, TheCall);
2440 case llvm::Triple::riscv32:
2441 case llvm::Triple::riscv64:
2442 case llvm::Triple::riscv32be:
2443 case llvm::Triple::riscv64be:
2444 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2445 case llvm::Triple::loongarch32:
2446 case llvm::Triple::loongarch64:
2447 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2448 TheCall);
2449 case llvm::Triple::wasm32:
2450 case llvm::Triple::wasm64:
2451 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2452 case llvm::Triple::nvptx:
2453 case llvm::Triple::nvptx64:
2454 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2455 }
2456}
2457
2459 return T->isDependentType() ||
2460 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2461}
2462
2463// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2464// not a valid type, emit an error message and return true. Otherwise return
2465// false.
2466static bool
2469 int ArgOrdinal) {
2470 clang::QualType EltTy =
2471 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2472 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2473 : ArgTy;
2474
2475 switch (ArgTyRestr) {
2477 if (!ArgTy->getAs<VectorType>() && !ArgTy->getAs<MatrixType>() &&
2478 !isValidMathElementType(ArgTy)) {
2479 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2480 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2481 << ArgTy;
2482 }
2483 break;
2485 if (!EltTy->isRealFloatingType()) {
2486 // FIXME: make diagnostic's wording correct for matrices
2487 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2488 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2489 << /* floating-point */ 1 << ArgTy;
2490 }
2491 break;
2493 if (!EltTy->isIntegerType()) {
2494 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2495 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2496 << /* no fp */ 0 << ArgTy;
2497 }
2498 break;
2500 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2501 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2502 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2503 << /* or fp */ 1 << ArgTy;
2504 }
2505 break;
2506 }
2507
2508 return false;
2509}
2510
2511/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2512/// This checks that the target supports the builtin and that the string
2513/// argument is constant and valid.
2514static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2515 const TargetInfo *AuxTI, unsigned BuiltinID) {
2516 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2517 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2518 "Expecting __builtin_cpu_...");
2519
2520 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2521 const TargetInfo *TheTI = &TI;
2522 auto SupportsBI = [=](const TargetInfo *TInfo) {
2523 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2524 (!IsCPUSupports && TInfo->supportsCpuIs()));
2525 };
2526 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2527 TheTI = AuxTI;
2528
2529 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2530 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2531 return S.Diag(TheCall->getBeginLoc(),
2532 TI.getTriple().isOSAIX()
2533 ? diag::err_builtin_aix_os_unsupported
2534 : diag::err_builtin_target_unsupported)
2535 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2536
2537 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts();
2538 // Check if the argument is a string literal.
2539 if (!isa<StringLiteral>(Arg))
2540 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
2541 << Arg->getSourceRange();
2542
2543 // Check the contents of the string.
2544 StringRef Feature = cast<StringLiteral>(Arg)->getString();
2545 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) {
2546 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports)
2547 << Arg->getSourceRange();
2548 return false;
2549 }
2550 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature))
2551 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
2552 << Arg->getSourceRange();
2553 return false;
2554}
2555
2556/// Checks that __builtin_bswapg was called with a single argument, which is an
2557/// unsigned integer, and overrides the return value type to the integer type.
2558static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2559 if (S.checkArgCount(TheCall, 1))
2560 return true;
2561 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2562 if (ArgRes.isInvalid())
2563 return true;
2564
2565 Expr *Arg = ArgRes.get();
2566 TheCall->setArg(0, Arg);
2567 if (Arg->isTypeDependent())
2568 return false;
2569
2570 QualType ArgTy = Arg->getType();
2571
2572 if (!ArgTy->isIntegerType()) {
2573 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2574 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2575 << ArgTy;
2576 return true;
2577 }
2578 if (const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2579 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2580 BT->getNumBits() != 1) {
2581 S.Diag(Arg->getBeginLoc(), diag::err_bswapg_invalid_bit_width)
2582 << ArgTy << BT->getNumBits();
2583 return true;
2584 }
2585 }
2586 TheCall->setType(ArgTy);
2587 return false;
2588}
2589
2590/// Checks that __builtin_bitreverseg was called with a single argument, which
2591/// is an integer
2592static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2593 if (S.checkArgCount(TheCall, 1))
2594 return true;
2595 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2596 if (ArgRes.isInvalid())
2597 return true;
2598
2599 Expr *Arg = ArgRes.get();
2600 TheCall->setArg(0, Arg);
2601 if (Arg->isTypeDependent())
2602 return false;
2603
2604 QualType ArgTy = Arg->getType();
2605
2606 if (!ArgTy->isIntegerType()) {
2607 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2608 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2609 << ArgTy;
2610 return true;
2611 }
2612 TheCall->setType(ArgTy);
2613 return false;
2614}
2615
2616/// Checks that __builtin_popcountg was called with a single argument, which is
2617/// an unsigned integer.
2618static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2619 if (S.checkArgCount(TheCall, 1))
2620 return true;
2621
2622 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2623 if (ArgRes.isInvalid())
2624 return true;
2625
2626 Expr *Arg = ArgRes.get();
2627 TheCall->setArg(0, Arg);
2628
2629 QualType ArgTy = Arg->getType();
2630
2631 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2632 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2633 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2634 << ArgTy;
2635 return true;
2636 }
2637 return false;
2638}
2639
2640/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2641/// argument and return either int, bool, or the argument type.
2642static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2643 QualType ReturnType) {
2644 if (S.checkArgCount(TheCall, 1))
2645 return true;
2646
2647 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0));
2648 if (ArgRes.isInvalid())
2649 return true;
2650
2651 Expr *Arg = ArgRes.get();
2652 TheCall->setArg(0, Arg);
2653
2654 QualType ArgTy = Arg->getType();
2655 // C23 stdbit.h functions do not permit bool or enumeration types.
2656 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2657 return S.Diag(Arg->getBeginLoc(),
2658 diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2659 << 1 /*1st argument*/ << ArgTy;
2660 if (!ArgTy->isUnsignedIntegerType())
2661 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_invalid_arg_type)
2662 << 1 /*1st argument*/ << ArgTy;
2663
2664 // For builtins returning unsigned int, verify the argument's bit width fits.
2665 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2666 // produce a count that overflows the return type.
2667 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2668 uint64_t ArgWidth = S.Context.getIntWidth(ArgTy);
2669 uint64_t ReturnTypeWidth = S.Context.getIntWidth(S.Context.UnsignedIntTy);
2670 if (!llvm::isUIntN(ReturnTypeWidth, ArgWidth))
2671 return S.Diag(Arg->getBeginLoc(), diag::err_builtin_stdc_result_overflow)
2672 << ArgTy;
2673 }
2674
2675 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2676 return false;
2677}
2678
2679/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2680/// an unsigned integer, and an optional second argument, which is promoted to
2681/// an 'int'.
2682static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2683 if (S.checkArgCountRange(TheCall, 1, 2))
2684 return true;
2685
2686 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0));
2687 if (Arg0Res.isInvalid())
2688 return true;
2689
2690 Expr *Arg0 = Arg0Res.get();
2691 TheCall->setArg(0, Arg0);
2692
2693 QualType Arg0Ty = Arg0->getType();
2694
2695 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2696 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2697 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2698 << Arg0Ty;
2699 return true;
2700 }
2701
2702 if (TheCall->getNumArgs() > 1) {
2703 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1));
2704 if (Arg1Res.isInvalid())
2705 return true;
2706
2707 Expr *Arg1 = Arg1Res.get();
2708 TheCall->setArg(1, Arg1);
2709
2710 QualType Arg1Ty = Arg1->getType();
2711
2712 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) {
2713 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2714 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2715 return true;
2716 }
2717 }
2718
2719 return false;
2720}
2721
2723 unsigned ArgIndex;
2724 bool OnlyUnsigned;
2725
2727 QualType T) {
2728 return S.Diag(Loc, diag::err_builtin_invalid_arg_type)
2729 << ArgIndex << /*scalar*/ 1
2730 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2731 << /*no fp*/ 0 << T;
2732 }
2733
2734public:
2735 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2736 : ContextualImplicitConverter(/*Suppress=*/false,
2737 /*SuppressConversion=*/true),
2738 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2739
2740 bool match(QualType T) override {
2741 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2742 }
2743
2745 QualType T) override {
2746 return emitError(S, Loc, T);
2747 }
2748
2750 QualType T) override {
2751 return emitError(S, Loc, T);
2752 }
2753
2755 QualType T,
2756 QualType ConvTy) override {
2757 return emitError(S, Loc, T);
2758 }
2759
2761 QualType ConvTy) override {
2762 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2763 }
2764
2766 QualType T) override {
2767 return emitError(S, Loc, T);
2768 }
2769
2771 QualType ConvTy) override {
2772 return S.Diag(Conv->getLocation(), diag::note_conv_function_declared_at);
2773 }
2774
2776 QualType T,
2777 QualType ConvTy) override {
2778 llvm_unreachable("conversion functions are permitted");
2779 }
2780};
2781
2782/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2783/// arguments, that the first argument is an unsigned integer type, and that
2784/// the second argument is an integer type.
2785static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2786 if (S.checkArgCount(TheCall, 2))
2787 return true;
2788
2789 // First argument (value to rotate) must be unsigned integer type.
2790 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2792 TheCall->getArg(0)->getBeginLoc(), TheCall->getArg(0), Arg0Converter);
2793 if (Arg0Res.isInvalid())
2794 return true;
2795
2796 Expr *Arg0 = Arg0Res.get();
2797 TheCall->setArg(0, Arg0);
2798
2799 QualType Arg0Ty = Arg0->getType();
2800 if (!Arg0Ty->isUnsignedIntegerType())
2801 return true;
2802
2803 // Second argument (rotation count) must be integer type.
2804 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2806 TheCall->getArg(1)->getBeginLoc(), TheCall->getArg(1), Arg1Converter);
2807 if (Arg1Res.isInvalid())
2808 return true;
2809
2810 Expr *Arg1 = Arg1Res.get();
2811 TheCall->setArg(1, Arg1);
2812
2813 QualType Arg1Ty = Arg1->getType();
2814 if (!Arg1Ty->isIntegerType())
2815 return true;
2816
2817 TheCall->setType(Arg0Ty);
2818 return false;
2819}
2820
2821static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2822 unsigned Pos, bool AllowConst,
2823 bool AllowAS) {
2824 QualType MaskTy = MaskArg->getType();
2825 if (!MaskTy->isExtVectorBoolType())
2826 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2827 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2828 << MaskTy;
2829
2830 QualType PtrTy = PtrArg->getType();
2831 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2832 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2833 << Pos << "scalar pointer";
2834
2835 QualType PointeeTy = PtrTy->getPointeeType();
2836 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2837 (!AllowConst && PointeeTy.isConstQualified()) ||
2838 (!AllowAS && PointeeTy.hasAddressSpace())) {
2841 return S.Diag(PtrArg->getExprLoc(),
2842 diag::err_typecheck_convert_incompatible)
2843 << PtrTy << Target << /*different qualifiers=*/5
2844 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2845 << PtrTy << Target;
2846 }
2847 return false;
2848}
2849
2850static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2851 bool TypeDependent = false;
2852 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2853 ExprResult Converted =
2855 if (Converted.isInvalid())
2856 return true;
2857 TheCall->setArg(Arg, Converted.get());
2858 TypeDependent |= Converted.get()->isTypeDependent();
2859 }
2860
2861 if (TypeDependent)
2862 TheCall->setType(S.Context.DependentTy);
2863 return false;
2864}
2865
2867 if (S.checkArgCountRange(TheCall, 2, 3))
2868 return ExprError();
2869
2870 if (ConvertMaskedBuiltinArgs(S, TheCall))
2871 return ExprError();
2872
2873 Expr *MaskArg = TheCall->getArg(0);
2874 Expr *PtrArg = TheCall->getArg(1);
2875 if (TheCall->isTypeDependent())
2876 return TheCall;
2877
2878 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 2, /*AllowConst=*/true,
2879 TheCall->getBuiltinCallee() ==
2880 Builtin::BI__builtin_masked_load))
2881 return ExprError();
2882
2883 QualType MaskTy = MaskArg->getType();
2884 QualType PtrTy = PtrArg->getType();
2885 QualType PointeeTy = PtrTy->getPointeeType();
2886 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2887
2889 MaskVecTy->getNumElements());
2890 if (TheCall->getNumArgs() == 3) {
2891 Expr *PassThruArg = TheCall->getArg(2);
2892 QualType PassThruTy = PassThruArg->getType();
2893 if (!S.Context.hasSameType(PassThruTy, RetTy))
2894 return S.Diag(PtrArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2895 << /* third argument */ 3 << RetTy;
2896 }
2897
2898 TheCall->setType(RetTy);
2899 return TheCall;
2900}
2901
2903 if (S.checkArgCount(TheCall, 3))
2904 return ExprError();
2905
2906 if (ConvertMaskedBuiltinArgs(S, TheCall))
2907 return ExprError();
2908
2909 Expr *MaskArg = TheCall->getArg(0);
2910 Expr *ValArg = TheCall->getArg(1);
2911 Expr *PtrArg = TheCall->getArg(2);
2912 if (TheCall->isTypeDependent())
2913 return TheCall;
2914
2915 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/false,
2916 TheCall->getBuiltinCallee() ==
2917 Builtin::BI__builtin_masked_store))
2918 return ExprError();
2919
2920 QualType MaskTy = MaskArg->getType();
2921 QualType PtrTy = PtrArg->getType();
2922 QualType ValTy = ValArg->getType();
2923 if (!ValTy->isVectorType())
2924 return ExprError(
2925 S.Diag(ValArg->getExprLoc(), diag::err_vec_masked_load_store_ptr)
2926 << 2 << "vector");
2927
2928 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2929 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2930
2931 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2932 return ExprError(
2933 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2935 TheCall->getBuiltinCallee())
2936 << MaskTy << ValTy);
2937 }
2938
2939 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
2940 PtrTy->getPointeeType().getUnqualifiedType()))
2941 return ExprError(S.Diag(TheCall->getBeginLoc(),
2942 diag::err_vec_builtin_incompatible_vector)
2943 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2944 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
2945 TheCall->getArg(1)->getEndLoc()));
2946
2947 TheCall->setType(S.Context.VoidTy);
2948 return TheCall;
2949}
2950
2952 if (S.checkArgCountRange(TheCall, 3, 4))
2953 return ExprError();
2954
2955 if (ConvertMaskedBuiltinArgs(S, TheCall))
2956 return ExprError();
2957
2958 Expr *MaskArg = TheCall->getArg(0);
2959 Expr *IdxArg = TheCall->getArg(1);
2960 Expr *PtrArg = TheCall->getArg(2);
2961 if (TheCall->isTypeDependent())
2962 return TheCall;
2963
2964 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 3, /*AllowConst=*/true,
2965 /*AllowAS=*/true))
2966 return ExprError();
2967
2968 QualType IdxTy = IdxArg->getType();
2969 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2970 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2971 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
2972 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2973 << IdxTy;
2974
2975 QualType MaskTy = MaskArg->getType();
2976 QualType PtrTy = PtrArg->getType();
2977 QualType PointeeTy = PtrTy->getPointeeType();
2978 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2979 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2980 return ExprError(
2981 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
2983 TheCall->getBuiltinCallee())
2984 << MaskTy << IdxTy);
2985
2987 MaskVecTy->getNumElements());
2988 if (TheCall->getNumArgs() == 4) {
2989 Expr *PassThruArg = TheCall->getArg(3);
2990 QualType PassThruTy = PassThruArg->getType();
2991 if (!S.Context.hasSameType(PassThruTy, RetTy))
2992 return S.Diag(PassThruArg->getExprLoc(),
2993 diag::err_vec_masked_load_store_ptr)
2994 << /* fourth argument */ 4 << RetTy;
2995 }
2996
2997 TheCall->setType(RetTy);
2998 return TheCall;
2999}
3000
3002 if (S.checkArgCount(TheCall, 4))
3003 return ExprError();
3004
3005 if (ConvertMaskedBuiltinArgs(S, TheCall))
3006 return ExprError();
3007
3008 Expr *MaskArg = TheCall->getArg(0);
3009 Expr *IdxArg = TheCall->getArg(1);
3010 Expr *ValArg = TheCall->getArg(2);
3011 Expr *PtrArg = TheCall->getArg(3);
3012 if (TheCall->isTypeDependent())
3013 return TheCall;
3014
3015 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, 4, /*AllowConst=*/false,
3016 /*AllowAS=*/true))
3017 return ExprError();
3018
3019 QualType IdxTy = IdxArg->getType();
3020 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
3021 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
3022 return S.Diag(MaskArg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
3023 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
3024 << IdxTy;
3025
3026 QualType ValTy = ValArg->getType();
3027 QualType MaskTy = MaskArg->getType();
3028 QualType PtrTy = PtrArg->getType();
3029
3030 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
3031 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
3032 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
3033 return ExprError(
3034 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
3036 TheCall->getBuiltinCallee())
3037 << MaskTy << IdxTy);
3038 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
3039 return ExprError(
3040 S.Diag(TheCall->getBeginLoc(), diag::err_vec_masked_load_store_size)
3042 TheCall->getBuiltinCallee())
3043 << MaskTy << ValTy);
3044
3045 if (!S.Context.hasSameType(ValVecTy->getElementType().getUnqualifiedType(),
3046 PtrTy->getPointeeType().getUnqualifiedType()))
3047 return ExprError(S.Diag(TheCall->getBeginLoc(),
3048 diag::err_vec_builtin_incompatible_vector)
3049 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
3050 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
3051 TheCall->getArg(1)->getEndLoc()));
3052
3053 TheCall->setType(S.Context.VoidTy);
3054 return TheCall;
3055}
3056
3058 SourceLocation Loc = TheCall->getBeginLoc();
3059 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
3060 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
3061
3062 if (Args.size() == 0) {
3063 S.Diag(TheCall->getBeginLoc(),
3064 diag::err_typecheck_call_too_few_args_at_least)
3065 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
3066 << /*is_non_object=*/0 << TheCall->getSourceRange();
3067 return ExprError();
3068 }
3069
3070 QualType FuncT = Args[0]->getType();
3071
3072 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
3073 if (Args.size() < 2) {
3074 S.Diag(TheCall->getBeginLoc(),
3075 diag::err_typecheck_call_too_few_args_at_least)
3076 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
3077 << /*is_non_object=*/0 << TheCall->getSourceRange();
3078 return ExprError();
3079 }
3080
3081 const Type *MemPtrClass = MPT->getQualifier().getAsType();
3082 QualType ObjectT = Args[1]->getType();
3083
3084 if (MPT->isMemberDataPointer() && S.checkArgCount(TheCall, 2))
3085 return ExprError();
3086
3087 ExprResult ObjectArg = [&]() -> ExprResult {
3088 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
3089 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
3090 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
3091 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
3092 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
3093 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
3094 if (S.Context.hasSameType(QualType(MemPtrClass, 0),
3095 S.BuiltinRemoveCVRef(ObjectT, Loc)) ||
3096 S.BuiltinIsBaseOf(Args[1]->getBeginLoc(), QualType(MemPtrClass, 0),
3097 S.BuiltinRemoveCVRef(ObjectT, Loc))) {
3098 return Args[1];
3099 }
3100
3101 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
3102 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
3103 // reference_wrapper;
3104 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
3105 if (RD->isInStdNamespace() &&
3106 RD->getDeclName().getAsString() == "reference_wrapper") {
3107 CXXScopeSpec SS;
3108 IdentifierInfo *GetName = &S.Context.Idents.get("get");
3109 UnqualifiedId GetID;
3110 GetID.setIdentifier(GetName, Loc);
3111
3113 S.getCurScope(), Args[1], Loc, tok::period, SS,
3114 /*TemplateKWLoc=*/SourceLocation(), GetID, nullptr);
3115
3116 if (MemExpr.isInvalid())
3117 return ExprError();
3118
3119 return S.ActOnCallExpr(S.getCurScope(), MemExpr.get(), Loc, {}, Loc);
3120 }
3121 }
3122
3123 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
3124 // class T and t1 does not satisfy the previous two items;
3125
3126 return S.ActOnUnaryOp(S.getCurScope(), Loc, tok::star, Args[1]);
3127 }();
3128
3129 if (ObjectArg.isInvalid())
3130 return ExprError();
3131
3132 ExprResult BinOp = S.ActOnBinOp(S.getCurScope(), TheCall->getBeginLoc(),
3133 tok::periodstar, ObjectArg.get(), Args[0]);
3134 if (BinOp.isInvalid())
3135 return ExprError();
3136
3137 if (MPT->isMemberDataPointer())
3138 return BinOp;
3139
3140 // Give the synthesized expression a valid source range for diagnostics.
3141 auto *MemCall = new (S.Context)
3142 ParenExpr(TheCall->getBeginLoc(), TheCall->getRParenLoc(), BinOp.get());
3143
3144 return S.ActOnCallExpr(S.getCurScope(), MemCall, TheCall->getBeginLoc(),
3145 Args.drop_front(2), TheCall->getRParenLoc());
3146 }
3147 return S.ActOnCallExpr(S.getCurScope(), Args.front(), TheCall->getBeginLoc(),
3148 Args.drop_front(), TheCall->getRParenLoc());
3149}
3150
3151// Performs a similar job to Sema::UsualUnaryConversions, but without any
3152// implicit promotion of integral/enumeration types.
3154 // First, convert to an r-value.
3156 if (Res.isInvalid())
3157 return ExprError();
3158
3159 // Promote floating-point types.
3160 return S.UsualUnaryFPConversions(Res.get());
3161}
3162
3164 if (const auto *TyA = VecTy->getAs<VectorType>())
3165 return TyA->getElementType();
3166 if (VecTy->isSizelessVectorType())
3167 return VecTy->getSizelessVectorEltType(Context);
3168 return QualType();
3169}
3170
3172Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3173 CallExpr *TheCall) {
3174 ExprResult TheCallResult(TheCall);
3175
3176 // Find out if any arguments are required to be integer constant expressions.
3177 unsigned ICEArguments = 0;
3179 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
3181 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
3182
3183 // If any arguments are required to be ICE's, check and diagnose.
3184 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
3185 // Skip arguments not required to be ICE's.
3186 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
3187
3188 llvm::APSInt Result;
3189 // If we don't have enough arguments, continue so we can issue better
3190 // diagnostic in checkArgCount(...)
3191 if (ArgNo < TheCall->getNumArgs() &&
3192 BuiltinConstantArg(TheCall, ArgNo, Result))
3193 return true;
3194 ICEArguments &= ~(1 << ArgNo);
3195 }
3196
3197 FPOptions FPO;
3198 switch (BuiltinID) {
3199 case Builtin::BI__builtin___get_unsafe_stack_start:
3200 case Builtin::BI__builtin___get_unsafe_stack_bottom:
3201 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3202 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3203 << "__safestack_get_unsafe_stack_bottom";
3204 break;
3205 case Builtin::BI__builtin___get_unsafe_stack_top:
3206 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3207 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3208 << "__safestack_get_unsafe_stack_top";
3209 break;
3210 case Builtin::BI__builtin___get_unsafe_stack_ptr:
3211 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin)
3212 << Context.BuiltinInfo.getQuotedName(BuiltinID)
3213 << "__safestack_get_unsafe_stack_ptr";
3214 break;
3215 case Builtin::BI__builtin_cpu_supports:
3216 case Builtin::BI__builtin_cpu_is:
3217 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall,
3218 Context.getAuxTargetInfo(), BuiltinID))
3219 return ExprError();
3220 break;
3221 case Builtin::BI__builtin_cpu_init:
3222 if (!Context.getTargetInfo().supportsCpuInit()) {
3223 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3224 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
3225 return ExprError();
3226 }
3227 break;
3228 case Builtin::BI__builtin___CFStringMakeConstantString:
3229 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
3230 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
3232 *this, BuiltinID, TheCall,
3233 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
3234 return ExprError();
3235 assert(TheCall->getNumArgs() == 1 &&
3236 "Wrong # arguments to builtin CFStringMakeConstantString");
3237 if (ObjC().CheckObjCString(TheCall->getArg(0)))
3238 return ExprError();
3239 break;
3240 case Builtin::BI__builtin_ms_va_start:
3241 case Builtin::BI__builtin_zos_va_start:
3242 case Builtin::BI__builtin_stdarg_start:
3243 case Builtin::BI__builtin_va_start:
3244 case Builtin::BI__builtin_c23_va_start:
3245 if (BuiltinVAStart(BuiltinID, TheCall))
3246 return ExprError();
3247 break;
3248 case Builtin::BI__va_start: {
3249 switch (Context.getTargetInfo().getTriple().getArch()) {
3250 case llvm::Triple::aarch64:
3251 case llvm::Triple::arm:
3252 case llvm::Triple::thumb:
3253 if (BuiltinVAStartARMMicrosoft(TheCall))
3254 return ExprError();
3255 break;
3256 default:
3257 if (BuiltinVAStart(BuiltinID, TheCall))
3258 return ExprError();
3259 break;
3260 }
3261 break;
3262 }
3263
3264 // The acquire, release, and no fence variants are ARM and AArch64 only.
3265 case Builtin::BI_interlockedbittestandset_acq:
3266 case Builtin::BI_interlockedbittestandset_rel:
3267 case Builtin::BI_interlockedbittestandset_nf:
3268 case Builtin::BI_interlockedbittestandreset_acq:
3269 case Builtin::BI_interlockedbittestandreset_rel:
3270 case Builtin::BI_interlockedbittestandreset_nf:
3272 *this, TheCall,
3273 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
3274 return ExprError();
3275 break;
3276
3277 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
3278 case Builtin::BI_bittest64:
3279 case Builtin::BI_bittestandcomplement64:
3280 case Builtin::BI_bittestandreset64:
3281 case Builtin::BI_bittestandset64:
3282 case Builtin::BI_interlockedbittestandreset64:
3283 case Builtin::BI_interlockedbittestandset64:
3285 *this, TheCall,
3286 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3287 llvm::Triple::aarch64, llvm::Triple::amdgpu}))
3288 return ExprError();
3289 break;
3290
3291 // The 64-bit acquire, release, and no fence variants are AArch64 only.
3292 case Builtin::BI_interlockedbittestandreset64_acq:
3293 case Builtin::BI_interlockedbittestandreset64_rel:
3294 case Builtin::BI_interlockedbittestandreset64_nf:
3295 case Builtin::BI_interlockedbittestandset64_acq:
3296 case Builtin::BI_interlockedbittestandset64_rel:
3297 case Builtin::BI_interlockedbittestandset64_nf:
3298 if (CheckBuiltinTargetInSupported(*this, TheCall, {llvm::Triple::aarch64}))
3299 return ExprError();
3300 break;
3301
3302 case Builtin::BI__builtin_set_flt_rounds:
3304 *this, TheCall,
3305 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3306 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgpu,
3307 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3308 llvm::Triple::ppc64le}))
3309 return ExprError();
3310 break;
3311
3312 case Builtin::BI__builtin_isgreater:
3313 case Builtin::BI__builtin_isgreaterequal:
3314 case Builtin::BI__builtin_isless:
3315 case Builtin::BI__builtin_islessequal:
3316 case Builtin::BI__builtin_islessgreater:
3317 case Builtin::BI__builtin_isunordered:
3318 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3319 return ExprError();
3320 break;
3321 case Builtin::BI__builtin_fpclassify:
3322 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
3323 return ExprError();
3324 break;
3325 case Builtin::BI__builtin_isfpclass:
3326 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
3327 return ExprError();
3328 break;
3329 case Builtin::BI__builtin_isfinite:
3330 case Builtin::BI__builtin_isinf:
3331 case Builtin::BI__builtin_isinf_sign:
3332 case Builtin::BI__builtin_isnan:
3333 case Builtin::BI__builtin_issignaling:
3334 case Builtin::BI__builtin_isnormal:
3335 case Builtin::BI__builtin_issubnormal:
3336 case Builtin::BI__builtin_iszero:
3337 case Builtin::BI__builtin_signbit:
3338 case Builtin::BI__builtin_signbitf:
3339 case Builtin::BI__builtin_signbitl:
3340 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
3341 return ExprError();
3342 break;
3343 case Builtin::BI__builtin_shufflevector:
3344 return BuiltinShuffleVector(TheCall);
3345 // TheCall will be freed by the smart pointer here, but that's fine, since
3346 // BuiltinShuffleVector guts it, but then doesn't release it.
3347 case Builtin::BI__builtin_masked_load:
3348 case Builtin::BI__builtin_masked_expand_load:
3349 return BuiltinMaskedLoad(*this, TheCall);
3350 case Builtin::BI__builtin_masked_store:
3351 case Builtin::BI__builtin_masked_compress_store:
3352 return BuiltinMaskedStore(*this, TheCall);
3353 case Builtin::BI__builtin_masked_gather:
3354 return BuiltinMaskedGather(*this, TheCall);
3355 case Builtin::BI__builtin_masked_scatter:
3356 return BuiltinMaskedScatter(*this, TheCall);
3357 case Builtin::BI__builtin_invoke:
3358 return BuiltinInvoke(*this, TheCall);
3359 case Builtin::BI__builtin_prefetch:
3360 if (BuiltinPrefetch(TheCall))
3361 return ExprError();
3362 break;
3363 case Builtin::BI__builtin_alloca_with_align:
3364 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3365 if (BuiltinAllocaWithAlign(TheCall))
3366 return ExprError();
3367 [[fallthrough]];
3368 case Builtin::BI__builtin_alloca:
3369 case Builtin::BI__builtin_alloca_uninitialized:
3370 Diag(TheCall->getBeginLoc(), diag::warn_alloca)
3371 << TheCall->getDirectCallee();
3372 if (getLangOpts().OpenCL) {
3373 builtinAllocaAddrSpace(*this, TheCall);
3374 }
3375 break;
3376 case Builtin::BI__builtin_infer_alloc_token:
3377 if (checkBuiltinInferAllocToken(*this, TheCall))
3378 return ExprError();
3379 break;
3380 case Builtin::BI__arithmetic_fence:
3381 if (BuiltinArithmeticFence(TheCall))
3382 return ExprError();
3383 break;
3384 case Builtin::BI__assume:
3385 case Builtin::BI__builtin_assume:
3386 if (BuiltinAssume(TheCall))
3387 return ExprError();
3388 break;
3389 case Builtin::BI__builtin_assume_aligned:
3390 if (BuiltinAssumeAligned(TheCall))
3391 return ExprError();
3392 break;
3393 case Builtin::BI__builtin_dynamic_object_size:
3394 case Builtin::BI__builtin_object_size:
3395 if (BuiltinConstantArgRange(TheCall, 1, 0, 3))
3396 return ExprError();
3397 break;
3398 case Builtin::BI__builtin_longjmp:
3399 if (BuiltinLongjmp(TheCall))
3400 return ExprError();
3401 break;
3402 case Builtin::BI__builtin_setjmp:
3403 if (BuiltinSetjmp(TheCall))
3404 return ExprError();
3405 break;
3406 case Builtin::BI__builtin_complex:
3407 if (BuiltinComplex(TheCall))
3408 return ExprError();
3409 break;
3410 case Builtin::BI__builtin_classify_type:
3411 case Builtin::BI__builtin_constant_p: {
3412 if (checkArgCount(TheCall, 1))
3413 return true;
3415 if (Arg.isInvalid()) return true;
3416 TheCall->setArg(0, Arg.get());
3417 TheCall->setType(Context.IntTy);
3418 break;
3419 }
3420 case Builtin::BI__builtin_launder:
3421 return BuiltinLaunder(*this, TheCall);
3422 case Builtin::BI__builtin_is_within_lifetime:
3423 return BuiltinIsWithinLifetime(*this, TheCall);
3424 case Builtin::BI__builtin_trivially_relocate:
3425 return BuiltinTriviallyRelocate(*this, TheCall);
3426 case Builtin::BI__builtin_clear_padding: {
3427 if (checkArgCount(TheCall, 1))
3428 return ExprError();
3429
3430 const Expr *PtrArg = TheCall->getArg(0);
3431 const QualType PtrArgType = PtrArg->getType();
3432 if (!PtrArgType->isPointerType()) {
3433 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
3434 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3435 << "pointer";
3436 return ExprError();
3437 }
3438 QualType PointeeType = PtrArgType->getPointeeType();
3439 if (PointeeType.isConstQualified()) {
3440 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_assign_const)
3441 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3442 return ExprError();
3443 }
3444 if (RequireCompleteType(PtrArg->getBeginLoc(), PointeeType,
3445 diag::err_typecheck_decl_incomplete_type))
3446 return ExprError();
3447
3448 // For non trivially copyable types, we try to match gcc's behaviour.
3449 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3450 // object, either a local variable or a function parameter passed by value
3451 auto IsAddrOfDeclExpr = [&]() {
3452 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Context);
3453 const auto *UnaryOp = dyn_cast<UnaryOperator>(Inner);
3454 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3455 return false;
3456
3457 const Expr *Operand =
3458 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Context);
3459 const auto *DeclRef = dyn_cast<DeclRefExpr>(Operand);
3460 if (!DeclRef)
3461 return false;
3462
3463 const auto *VarDecl = dyn_cast<::clang::VarDecl>(DeclRef->getDecl());
3464 if (!VarDecl || VarDecl->getType()->isReferenceType())
3465 return false;
3466
3467 // matching GCC behaviour
3468 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3469 QualType VarQType = VarDecl->getType();
3470 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3471 Context.hasSameUnqualifiedType(PointeeType, VarQType);
3472 };
3473
3474 if (!PointeeType.isTriviallyCopyableType(Context) &&
3475 !PointeeType->isAtomicType() // _Atomic is not copyable
3476 && !IsAddrOfDeclExpr()) {
3477 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_needs_trivial_copy)
3478 << PtrArg->getType() << PtrArg->getSourceRange();
3479 return ExprError();
3480 }
3481
3482 if (auto *Record = PointeeType->getAsRecordDecl();
3484 Diag(PtrArg->getBeginLoc(), diag::err_clear_padding_no_flexible_array)
3485 << PointeeType << PtrArg->getSourceRange();
3486 return ExprError();
3487 }
3488
3489 break;
3490 }
3491 case Builtin::BI__sync_fetch_and_add:
3492 case Builtin::BI__sync_fetch_and_add_1:
3493 case Builtin::BI__sync_fetch_and_add_2:
3494 case Builtin::BI__sync_fetch_and_add_4:
3495 case Builtin::BI__sync_fetch_and_add_8:
3496 case Builtin::BI__sync_fetch_and_add_16:
3497 case Builtin::BI__sync_fetch_and_sub:
3498 case Builtin::BI__sync_fetch_and_sub_1:
3499 case Builtin::BI__sync_fetch_and_sub_2:
3500 case Builtin::BI__sync_fetch_and_sub_4:
3501 case Builtin::BI__sync_fetch_and_sub_8:
3502 case Builtin::BI__sync_fetch_and_sub_16:
3503 case Builtin::BI__sync_fetch_and_or:
3504 case Builtin::BI__sync_fetch_and_or_1:
3505 case Builtin::BI__sync_fetch_and_or_2:
3506 case Builtin::BI__sync_fetch_and_or_4:
3507 case Builtin::BI__sync_fetch_and_or_8:
3508 case Builtin::BI__sync_fetch_and_or_16:
3509 case Builtin::BI__sync_fetch_and_and:
3510 case Builtin::BI__sync_fetch_and_and_1:
3511 case Builtin::BI__sync_fetch_and_and_2:
3512 case Builtin::BI__sync_fetch_and_and_4:
3513 case Builtin::BI__sync_fetch_and_and_8:
3514 case Builtin::BI__sync_fetch_and_and_16:
3515 case Builtin::BI__sync_fetch_and_xor:
3516 case Builtin::BI__sync_fetch_and_xor_1:
3517 case Builtin::BI__sync_fetch_and_xor_2:
3518 case Builtin::BI__sync_fetch_and_xor_4:
3519 case Builtin::BI__sync_fetch_and_xor_8:
3520 case Builtin::BI__sync_fetch_and_xor_16:
3521 case Builtin::BI__sync_fetch_and_nand:
3522 case Builtin::BI__sync_fetch_and_nand_1:
3523 case Builtin::BI__sync_fetch_and_nand_2:
3524 case Builtin::BI__sync_fetch_and_nand_4:
3525 case Builtin::BI__sync_fetch_and_nand_8:
3526 case Builtin::BI__sync_fetch_and_nand_16:
3527 case Builtin::BI__sync_add_and_fetch:
3528 case Builtin::BI__sync_add_and_fetch_1:
3529 case Builtin::BI__sync_add_and_fetch_2:
3530 case Builtin::BI__sync_add_and_fetch_4:
3531 case Builtin::BI__sync_add_and_fetch_8:
3532 case Builtin::BI__sync_add_and_fetch_16:
3533 case Builtin::BI__sync_sub_and_fetch:
3534 case Builtin::BI__sync_sub_and_fetch_1:
3535 case Builtin::BI__sync_sub_and_fetch_2:
3536 case Builtin::BI__sync_sub_and_fetch_4:
3537 case Builtin::BI__sync_sub_and_fetch_8:
3538 case Builtin::BI__sync_sub_and_fetch_16:
3539 case Builtin::BI__sync_and_and_fetch:
3540 case Builtin::BI__sync_and_and_fetch_1:
3541 case Builtin::BI__sync_and_and_fetch_2:
3542 case Builtin::BI__sync_and_and_fetch_4:
3543 case Builtin::BI__sync_and_and_fetch_8:
3544 case Builtin::BI__sync_and_and_fetch_16:
3545 case Builtin::BI__sync_or_and_fetch:
3546 case Builtin::BI__sync_or_and_fetch_1:
3547 case Builtin::BI__sync_or_and_fetch_2:
3548 case Builtin::BI__sync_or_and_fetch_4:
3549 case Builtin::BI__sync_or_and_fetch_8:
3550 case Builtin::BI__sync_or_and_fetch_16:
3551 case Builtin::BI__sync_xor_and_fetch:
3552 case Builtin::BI__sync_xor_and_fetch_1:
3553 case Builtin::BI__sync_xor_and_fetch_2:
3554 case Builtin::BI__sync_xor_and_fetch_4:
3555 case Builtin::BI__sync_xor_and_fetch_8:
3556 case Builtin::BI__sync_xor_and_fetch_16:
3557 case Builtin::BI__sync_nand_and_fetch:
3558 case Builtin::BI__sync_nand_and_fetch_1:
3559 case Builtin::BI__sync_nand_and_fetch_2:
3560 case Builtin::BI__sync_nand_and_fetch_4:
3561 case Builtin::BI__sync_nand_and_fetch_8:
3562 case Builtin::BI__sync_nand_and_fetch_16:
3563 case Builtin::BI__sync_val_compare_and_swap:
3564 case Builtin::BI__sync_val_compare_and_swap_1:
3565 case Builtin::BI__sync_val_compare_and_swap_2:
3566 case Builtin::BI__sync_val_compare_and_swap_4:
3567 case Builtin::BI__sync_val_compare_and_swap_8:
3568 case Builtin::BI__sync_val_compare_and_swap_16:
3569 case Builtin::BI__sync_bool_compare_and_swap:
3570 case Builtin::BI__sync_bool_compare_and_swap_1:
3571 case Builtin::BI__sync_bool_compare_and_swap_2:
3572 case Builtin::BI__sync_bool_compare_and_swap_4:
3573 case Builtin::BI__sync_bool_compare_and_swap_8:
3574 case Builtin::BI__sync_bool_compare_and_swap_16:
3575 case Builtin::BI__sync_lock_test_and_set:
3576 case Builtin::BI__sync_lock_test_and_set_1:
3577 case Builtin::BI__sync_lock_test_and_set_2:
3578 case Builtin::BI__sync_lock_test_and_set_4:
3579 case Builtin::BI__sync_lock_test_and_set_8:
3580 case Builtin::BI__sync_lock_test_and_set_16:
3581 case Builtin::BI__sync_lock_release:
3582 case Builtin::BI__sync_lock_release_1:
3583 case Builtin::BI__sync_lock_release_2:
3584 case Builtin::BI__sync_lock_release_4:
3585 case Builtin::BI__sync_lock_release_8:
3586 case Builtin::BI__sync_lock_release_16:
3587 case Builtin::BI__sync_swap:
3588 case Builtin::BI__sync_swap_1:
3589 case Builtin::BI__sync_swap_2:
3590 case Builtin::BI__sync_swap_4:
3591 case Builtin::BI__sync_swap_8:
3592 case Builtin::BI__sync_swap_16:
3593 return BuiltinAtomicOverloaded(TheCallResult);
3594 case Builtin::BI__sync_synchronize:
3595 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
3596 << TheCall->getCallee()->getSourceRange();
3597 break;
3598 case Builtin::BI__builtin_nontemporal_load:
3599 case Builtin::BI__builtin_nontemporal_store:
3600 return BuiltinNontemporalOverloaded(TheCallResult);
3601 case Builtin::BI__builtin_memcpy_inline: {
3602 clang::Expr *SizeOp = TheCall->getArg(2);
3603 // We warn about copying to or from `nullptr` pointers when `size` is
3604 // greater than 0. When `size` is value dependent we cannot evaluate its
3605 // value so we bail out.
3606 if (SizeOp->isValueDependent())
3607 break;
3608 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
3609 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3610 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
3611 }
3612 break;
3613 }
3614 case Builtin::BI__builtin_memset_inline: {
3615 clang::Expr *SizeOp = TheCall->getArg(2);
3616 // We warn about filling to `nullptr` pointers when `size` is greater than
3617 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3618 // out.
3619 if (SizeOp->isValueDependent())
3620 break;
3621 if (!SizeOp->EvaluateKnownConstInt(Context).isZero())
3622 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
3623 break;
3624 }
3625#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3626 case Builtin::BI##ID: \
3627 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3628#include "clang/Basic/Builtins.inc"
3629 case Builtin::BI__annotation: {
3630 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3631 if (!TT.isOSWindows() && !TT.isUEFI()) {
3632 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
3633 << TheCall->getSourceRange();
3634 return ExprError();
3635 }
3636 if (BuiltinMSVCAnnotation(*this, TheCall))
3637 return ExprError();
3638 break;
3639 }
3640 case Builtin::BI__builtin_annotation:
3641 if (BuiltinAnnotation(*this, TheCall))
3642 return ExprError();
3643 break;
3644 case Builtin::BI__builtin_addressof:
3645 if (BuiltinAddressof(*this, TheCall))
3646 return ExprError();
3647 break;
3648 case Builtin::BI__builtin_function_start:
3649 if (BuiltinFunctionStart(*this, TheCall))
3650 return ExprError();
3651 break;
3652 case Builtin::BI__builtin_is_aligned:
3653 case Builtin::BI__builtin_align_up:
3654 case Builtin::BI__builtin_align_down:
3655 if (BuiltinAlignment(*this, TheCall, BuiltinID))
3656 return ExprError();
3657 break;
3658 case Builtin::BI__builtin_add_overflow:
3659 case Builtin::BI__builtin_sub_overflow:
3660 case Builtin::BI__builtin_mul_overflow:
3661 if (BuiltinOverflow(*this, TheCall, BuiltinID))
3662 return ExprError();
3663 break;
3664 case Builtin::BI__builtin_operator_new:
3665 case Builtin::BI__builtin_operator_delete: {
3666 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3667 ExprResult Res =
3668 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3669 return Res;
3670 }
3671 case Builtin::BI__builtin_dump_struct:
3672 return BuiltinDumpStruct(*this, TheCall);
3673 case Builtin::BI__builtin_expect_with_probability: {
3674 // We first want to ensure we are called with 3 arguments
3675 if (checkArgCount(TheCall, 3))
3676 return ExprError();
3677 // then check probability is constant float in range [0.0, 1.0]
3678 const Expr *ProbArg = TheCall->getArg(2);
3679 SmallVector<PartialDiagnosticAt, 8> Notes;
3680 Expr::EvalResult Eval;
3681 Eval.Diag = &Notes;
3682 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
3683 !Eval.Val.isFloat()) {
3684 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
3685 << ProbArg->getSourceRange();
3686 for (const PartialDiagnosticAt &PDiag : Notes)
3687 Diag(PDiag.first, PDiag.second);
3688 return ExprError();
3689 }
3690 llvm::APFloat Probability = Eval.Val.getFloat();
3691 bool LoseInfo = false;
3692 Probability.convert(llvm::APFloat::IEEEdouble(),
3693 llvm::RoundingMode::Dynamic, &LoseInfo);
3694 if (!(Probability >= llvm::APFloat(0.0) &&
3695 Probability <= llvm::APFloat(1.0))) {
3696 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
3697 << ProbArg->getSourceRange();
3698 return ExprError();
3699 }
3700 break;
3701 }
3702 case Builtin::BI__builtin_preserve_access_index:
3703 if (BuiltinPreserveAI(*this, TheCall))
3704 return ExprError();
3705 break;
3706 case Builtin::BI__builtin_call_with_static_chain:
3707 if (BuiltinCallWithStaticChain(*this, TheCall))
3708 return ExprError();
3709 break;
3710 case Builtin::BI__exception_code:
3711 case Builtin::BI_exception_code:
3712 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
3713 diag::err_seh___except_block))
3714 return ExprError();
3715 break;
3716 case Builtin::BI__exception_info:
3717 case Builtin::BI_exception_info:
3718 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
3719 diag::err_seh___except_filter))
3720 return ExprError();
3721 break;
3722 case Builtin::BI__GetExceptionInfo:
3723 if (checkArgCount(TheCall, 1))
3724 return ExprError();
3725
3727 TheCall->getBeginLoc(),
3728 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
3729 TheCall))
3730 return ExprError();
3731
3732 TheCall->setType(Context.VoidPtrTy);
3733 break;
3734 case Builtin::BIaddressof:
3735 case Builtin::BI__addressof:
3736 case Builtin::BIforward:
3737 case Builtin::BIforward_like:
3738 case Builtin::BImove:
3739 case Builtin::BImove_if_noexcept:
3740 case Builtin::BIas_const: {
3741 // These are all expected to be of the form
3742 // T &/&&/* f(U &/&&)
3743 // where T and U only differ in qualification.
3744 if (checkArgCount(TheCall, 1))
3745 return ExprError();
3746 QualType Param = FDecl->getParamDecl(0)->getType();
3747 QualType Result = FDecl->getReturnType();
3748 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3749 BuiltinID == Builtin::BI__addressof;
3750 if (!(Param->isReferenceType() &&
3751 (ReturnsPointer ? Result->isAnyPointerType()
3752 : Result->isReferenceType()) &&
3753 Context.hasSameUnqualifiedType(Param->getPointeeType(),
3754 Result->getPointeeType()))) {
3755 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3756 << FDecl;
3757 return ExprError();
3758 }
3759 break;
3760 }
3761 case Builtin::BI__builtin_ptrauth_strip:
3762 return PointerAuthStrip(*this, TheCall);
3763 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3764 return PointerAuthBlendDiscriminator(*this, TheCall);
3765 case Builtin::BI__builtin_ptrauth_sign_constant:
3766 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3767 /*RequireConstant=*/true);
3768 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3769 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign,
3770 /*RequireConstant=*/false);
3771 case Builtin::BI__builtin_ptrauth_auth:
3772 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth,
3773 /*RequireConstant=*/false);
3774 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3775 return PointerAuthSignGenericData(*this, TheCall);
3776 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3777 return PointerAuthAuthAndResign(*this, TheCall);
3778 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
3779 return PointerAuthAuthWithPCAndResign(*this, TheCall);
3780 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3781 return PointerAuthAuthLoadRelativeAndSign(*this, TheCall);
3782 case Builtin::BI__builtin_ptrauth_string_discriminator:
3783 return PointerAuthStringDiscriminator(*this, TheCall);
3784
3785 case Builtin::BI__builtin_get_vtable_pointer:
3786 return GetVTablePointer(*this, TheCall);
3787
3788 // OpenCL v2.0, s6.13.16 - Pipe functions
3789 case Builtin::BIread_pipe:
3790 case Builtin::BIwrite_pipe:
3791 // Since those two functions are declared with var args, we need a semantic
3792 // check for the argument.
3793 if (OpenCL().checkBuiltinRWPipe(TheCall))
3794 return ExprError();
3795 break;
3796 case Builtin::BIreserve_read_pipe:
3797 case Builtin::BIreserve_write_pipe:
3798 case Builtin::BIwork_group_reserve_read_pipe:
3799 case Builtin::BIwork_group_reserve_write_pipe:
3800 if (OpenCL().checkBuiltinReserveRWPipe(TheCall))
3801 return ExprError();
3802 break;
3803 case Builtin::BIsub_group_reserve_read_pipe:
3804 case Builtin::BIsub_group_reserve_write_pipe:
3805 if (OpenCL().checkSubgroupExt(TheCall) ||
3806 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3807 return ExprError();
3808 break;
3809 case Builtin::BIcommit_read_pipe:
3810 case Builtin::BIcommit_write_pipe:
3811 case Builtin::BIwork_group_commit_read_pipe:
3812 case Builtin::BIwork_group_commit_write_pipe:
3813 if (OpenCL().checkBuiltinCommitRWPipe(TheCall))
3814 return ExprError();
3815 break;
3816 case Builtin::BIsub_group_commit_read_pipe:
3817 case Builtin::BIsub_group_commit_write_pipe:
3818 if (OpenCL().checkSubgroupExt(TheCall) ||
3819 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3820 return ExprError();
3821 break;
3822 case Builtin::BIget_pipe_num_packets:
3823 case Builtin::BIget_pipe_max_packets:
3824 if (OpenCL().checkBuiltinPipePackets(TheCall))
3825 return ExprError();
3826 break;
3827 case Builtin::BIto_global:
3828 case Builtin::BIto_local:
3829 case Builtin::BIto_private:
3830 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3831 return ExprError();
3832 break;
3833 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3834 case Builtin::BIenqueue_kernel:
3835 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3836 return ExprError();
3837 break;
3838 case Builtin::BIget_kernel_work_group_size:
3839 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3840 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3841 return ExprError();
3842 break;
3843 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3844 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3845 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3846 return ExprError();
3847 break;
3848 case Builtin::BI__builtin_os_log_format:
3849 Cleanup.setExprNeedsCleanups(true);
3850 [[fallthrough]];
3851 case Builtin::BI__builtin_os_log_format_buffer_size:
3852 if (BuiltinOSLogFormat(TheCall))
3853 return ExprError();
3854 break;
3855 case Builtin::BI__builtin_frame_address:
3856 case Builtin::BI__builtin_return_address: {
3857 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
3858 return ExprError();
3859
3860 // -Wframe-address warning if non-zero passed to builtin
3861 // return/frame address.
3862 Expr::EvalResult Result;
3863 if (!TheCall->getArg(0)->isValueDependent() &&
3864 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
3865 Result.Val.getInt() != 0)
3866 Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
3867 << ((BuiltinID == Builtin::BI__builtin_return_address)
3868 ? "__builtin_return_address"
3869 : "__builtin_frame_address")
3870 << TheCall->getSourceRange();
3871 break;
3872 }
3873
3874 case Builtin::BI__builtin_nondeterministic_value: {
3875 if (BuiltinNonDeterministicValue(TheCall))
3876 return ExprError();
3877 break;
3878 }
3879
3880 // __builtin_elementwise_abs restricts the element type to signed integers or
3881 // floating point types only.
3882 case Builtin::BI__builtin_elementwise_abs:
3885 return ExprError();
3886 break;
3887
3888 // These builtins restrict the element type to floating point
3889 // types only.
3890 case Builtin::BI__builtin_elementwise_acos:
3891 case Builtin::BI__builtin_elementwise_asin:
3892 case Builtin::BI__builtin_elementwise_atan:
3893 case Builtin::BI__builtin_elementwise_ceil:
3894 case Builtin::BI__builtin_elementwise_cos:
3895 case Builtin::BI__builtin_elementwise_cosh:
3896 case Builtin::BI__builtin_elementwise_exp:
3897 case Builtin::BI__builtin_elementwise_exp2:
3898 case Builtin::BI__builtin_elementwise_exp10:
3899 case Builtin::BI__builtin_elementwise_floor:
3900 case Builtin::BI__builtin_elementwise_log:
3901 case Builtin::BI__builtin_elementwise_log2:
3902 case Builtin::BI__builtin_elementwise_log10:
3903 case Builtin::BI__builtin_elementwise_roundeven:
3904 case Builtin::BI__builtin_elementwise_round:
3905 case Builtin::BI__builtin_elementwise_rint:
3906 case Builtin::BI__builtin_elementwise_nearbyint:
3907 case Builtin::BI__builtin_elementwise_sin:
3908 case Builtin::BI__builtin_elementwise_sinh:
3909 case Builtin::BI__builtin_elementwise_sqrt:
3910 case Builtin::BI__builtin_elementwise_tan:
3911 case Builtin::BI__builtin_elementwise_tanh:
3912 case Builtin::BI__builtin_elementwise_trunc:
3913 case Builtin::BI__builtin_elementwise_canonicalize:
3916 return ExprError();
3917 break;
3918 case Builtin::BI__builtin_elementwise_fma:
3919 if (BuiltinElementwiseTernaryMath(TheCall))
3920 return ExprError();
3921 break;
3922
3923 case Builtin::BI__builtin_elementwise_ldexp: {
3924 if (checkArgCount(TheCall, 2))
3925 return ExprError();
3926
3927 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
3928 if (A.isInvalid())
3929 return ExprError();
3930 QualType TyA = A.get()->getType();
3931 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
3933 return ExprError();
3934
3935 ExprResult Exp = UsualUnaryConversions(TheCall->getArg(1));
3936 if (Exp.isInvalid())
3937 return ExprError();
3938 QualType TyExp = Exp.get()->getType();
3939 if (checkMathBuiltinElementType(*this, Exp.get()->getBeginLoc(), TyExp,
3941 2))
3942 return ExprError();
3943
3944 // Check the two arguments are either scalars or vectors of equal length.
3945 const auto *Vec0 = TyA->getAs<VectorType>();
3946 const auto *Vec1 = TyExp->getAs<VectorType>();
3947 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3948 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3949 if (Arg0Length != Arg1Length) {
3950 Diag(Exp.get()->getBeginLoc(),
3951 diag::err_typecheck_vector_lengths_not_equal)
3952 << TyA << TyExp << A.get()->getSourceRange()
3953 << Exp.get()->getSourceRange();
3954 return ExprError();
3955 }
3956
3957 TheCall->setArg(0, A.get());
3958 TheCall->setArg(1, Exp.get());
3959 TheCall->setType(TyA);
3960 break;
3961 }
3962
3963 // These builtins restrict the element type to floating point
3964 // types only, and take in two arguments.
3965 case Builtin::BI__builtin_elementwise_minnum:
3966 case Builtin::BI__builtin_elementwise_maxnum:
3967 case Builtin::BI__builtin_elementwise_minimum:
3968 case Builtin::BI__builtin_elementwise_maximum:
3969 case Builtin::BI__builtin_elementwise_minimumnum:
3970 case Builtin::BI__builtin_elementwise_maximumnum:
3971 case Builtin::BI__builtin_elementwise_atan2:
3972 case Builtin::BI__builtin_elementwise_fmod:
3973 case Builtin::BI__builtin_elementwise_pow:
3974 if (BuiltinElementwiseMath(TheCall,
3976 return ExprError();
3977 break;
3978 // These builtins restrict the element type to integer
3979 // types only.
3980 case Builtin::BI__builtin_elementwise_add_sat:
3981 case Builtin::BI__builtin_elementwise_sub_sat:
3982 case Builtin::BI__builtin_elementwise_clmul:
3983 case Builtin::BI__builtin_elementwise_pext:
3984 case Builtin::BI__builtin_elementwise_pdep:
3985 if (BuiltinElementwiseMath(TheCall,
3987 return ExprError();
3988 break;
3989 case Builtin::BI__builtin_elementwise_fshl:
3990 case Builtin::BI__builtin_elementwise_fshr:
3993 return ExprError();
3994 break;
3995 case Builtin::BI__builtin_elementwise_min:
3996 case Builtin::BI__builtin_elementwise_max: {
3997 if (BuiltinElementwiseMath(TheCall))
3998 return ExprError();
3999 Expr *Arg0 = TheCall->getArg(0);
4000 Expr *Arg1 = TheCall->getArg(1);
4001 QualType Ty0 = Arg0->getType();
4002 QualType Ty1 = Arg1->getType();
4003 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
4004 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
4005 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
4006 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
4007 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
4008 Diag(TheCall->getBeginLoc(), diag::warn_deprecated_builtin_no_suggestion)
4009 << Context.BuiltinInfo.getQuotedName(BuiltinID);
4010 break;
4011 }
4012 case Builtin::BI__builtin_elementwise_popcount:
4013 case Builtin::BI__builtin_elementwise_bitreverse:
4016 return ExprError();
4017 break;
4018 case Builtin::BI__builtin_elementwise_copysign: {
4019 if (checkArgCount(TheCall, 2))
4020 return ExprError();
4021
4022 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0));
4023 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1));
4024 if (Magnitude.isInvalid() || Sign.isInvalid())
4025 return ExprError();
4026
4027 QualType MagnitudeTy = Magnitude.get()->getType();
4028 QualType SignTy = Sign.get()->getType();
4030 *this, TheCall->getArg(0)->getBeginLoc(), MagnitudeTy,
4033 *this, TheCall->getArg(1)->getBeginLoc(), SignTy,
4035 return ExprError();
4036 }
4037
4038 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
4039 return Diag(Sign.get()->getBeginLoc(),
4040 diag::err_typecheck_call_different_arg_types)
4041 << MagnitudeTy << SignTy;
4042 }
4043
4044 TheCall->setArg(0, Magnitude.get());
4045 TheCall->setArg(1, Sign.get());
4046 TheCall->setType(Magnitude.get()->getType());
4047 break;
4048 }
4049 case Builtin::BI__builtin_elementwise_clzg:
4050 case Builtin::BI__builtin_elementwise_ctzg:
4051 // These builtins can be unary or binary. Note for empty calls we call the
4052 // unary checker in order to not emit an error that says the function
4053 // expects 2 arguments, which would be misleading.
4054 if (TheCall->getNumArgs() <= 1) {
4057 return ExprError();
4058 } else if (BuiltinElementwiseMath(
4060 return ExprError();
4061 break;
4062 case Builtin::BI__builtin_reduce_max:
4063 case Builtin::BI__builtin_reduce_min: {
4064 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4065 return ExprError();
4066
4067 const Expr *Arg = TheCall->getArg(0);
4068 const auto *TyA = Arg->getType()->getAs<VectorType>();
4069
4070 QualType ElTy;
4071 if (TyA)
4072 ElTy = TyA->getElementType();
4073 else if (Arg->getType()->isSizelessVectorType())
4075
4076 if (ElTy.isNull()) {
4077 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4078 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
4079 << Arg->getType();
4080 return ExprError();
4081 }
4082
4083 TheCall->setType(ElTy);
4084 break;
4085 }
4086 case Builtin::BI__builtin_reduce_maximum:
4087 case Builtin::BI__builtin_reduce_minimum: {
4088 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4089 return ExprError();
4090
4091 const Expr *Arg = TheCall->getArg(0);
4092 const auto *TyA = Arg->getType()->getAs<VectorType>();
4093
4094 QualType ElTy;
4095 if (TyA)
4096 ElTy = TyA->getElementType();
4097 else if (Arg->getType()->isSizelessVectorType())
4099
4100 if (ElTy.isNull() || !ElTy->isFloatingType()) {
4101 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4102 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4103 << Arg->getType();
4104 return ExprError();
4105 }
4106
4107 TheCall->setType(ElTy);
4108 break;
4109 }
4110
4111 // These builtins support vectors of integers only.
4112 // TODO: ADD/MUL should support floating-point types.
4113 case Builtin::BI__builtin_reduce_add:
4114 case Builtin::BI__builtin_reduce_mul:
4115 case Builtin::BI__builtin_reduce_xor:
4116 case Builtin::BI__builtin_reduce_or:
4117 case Builtin::BI__builtin_reduce_and: {
4118 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4119 return ExprError();
4120
4121 const Expr *Arg = TheCall->getArg(0);
4122
4123 QualType ElTy = getVectorElementType(Context, Arg->getType());
4124 if (ElTy.isNull() || !ElTy->isIntegerType()) {
4125 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4126 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
4127 << Arg->getType();
4128 return ExprError();
4129 }
4130
4131 TheCall->setType(ElTy);
4132 break;
4133 }
4134
4135 case Builtin::BI__builtin_reduce_assoc_fadd:
4136 case Builtin::BI__builtin_reduce_in_order_fadd: {
4137 // For in-order reductions require the user to specify the start value.
4138 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
4139 if (InOrder ? checkArgCount(TheCall, 2) : checkArgCountRange(TheCall, 1, 2))
4140 return ExprError();
4141
4142 ExprResult Vec = UsualUnaryConversions(TheCall->getArg(0));
4143 if (Vec.isInvalid())
4144 return ExprError();
4145
4146 TheCall->setArg(0, Vec.get());
4147
4148 QualType ElTy = getVectorElementType(Context, Vec.get()->getType());
4149 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
4150 Diag(Vec.get()->getBeginLoc(), diag::err_builtin_invalid_arg_type)
4151 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4152 << Vec.get()->getType();
4153 return ExprError();
4154 }
4155
4156 if (TheCall->getNumArgs() == 2) {
4157 ExprResult StartValue = UsualUnaryConversions(TheCall->getArg(1));
4158 if (StartValue.isInvalid())
4159 return ExprError();
4160
4161 if (!StartValue.get()->getType()->isRealFloatingType()) {
4162 Diag(StartValue.get()->getBeginLoc(),
4163 diag::err_builtin_invalid_arg_type)
4164 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
4165 << StartValue.get()->getType();
4166 return ExprError();
4167 }
4168 TheCall->setArg(1, StartValue.get());
4169 }
4170
4171 TheCall->setType(ElTy);
4172 break;
4173 }
4174
4175 case Builtin::BI__builtin_matrix_transpose:
4176 return BuiltinMatrixTranspose(TheCall, TheCallResult);
4177
4178 case Builtin::BI__builtin_matrix_column_major_load:
4179 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
4180
4181 case Builtin::BI__builtin_matrix_column_major_store:
4182 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
4183
4184 case Builtin::BI__builtin_verbose_trap:
4185 if (!checkBuiltinVerboseTrap(TheCall, *this))
4186 return ExprError();
4187 break;
4188
4189 case Builtin::BI__builtin_get_device_side_mangled_name: {
4190 auto Check = [](CallExpr *TheCall) {
4191 if (TheCall->getNumArgs() != 1)
4192 return false;
4193 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
4194 if (!DRE)
4195 return false;
4196 auto *D = DRE->getDecl();
4197 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
4198 return false;
4199 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4200 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
4201 };
4202 if (!Check(TheCall)) {
4203 Diag(TheCall->getBeginLoc(),
4204 diag::err_hip_invalid_args_builtin_mangled_name);
4205 return ExprError();
4206 }
4207 break;
4208 }
4209 case Builtin::BI__builtin_bswapg:
4210 if (BuiltinBswapg(*this, TheCall))
4211 return ExprError();
4212 break;
4213 case Builtin::BI__builtin_bitreverseg:
4214 if (BuiltinBitreverseg(*this, TheCall))
4215 return ExprError();
4216 break;
4217 case Builtin::BI__builtin_popcountg:
4218 if (BuiltinPopcountg(*this, TheCall))
4219 return ExprError();
4220 break;
4221 case Builtin::BI__builtin_clzg:
4222 case Builtin::BI__builtin_ctzg:
4223 if (BuiltinCountZeroBitsGeneric(*this, TheCall))
4224 return ExprError();
4225 break;
4226
4227 case Builtin::BI__builtin_stdc_rotate_left:
4228 case Builtin::BI__builtin_stdc_rotate_right:
4229 if (BuiltinRotateGeneric(*this, TheCall))
4230 return ExprError();
4231 break;
4232
4233 case Builtin::BI__builtin_stdc_memreverse8:
4234 case Builtin::BIstdc_memreverse8:
4235 case Builtin::BIstdc_memreverse8u8:
4236 case Builtin::BIstdc_memreverse8u16:
4237 case Builtin::BIstdc_memreverse8u32:
4238 case Builtin::BIstdc_memreverse8u64:
4239 case Builtin::BIstdc_load8_leu8:
4240 case Builtin::BIstdc_load8_leu16:
4241 case Builtin::BIstdc_load8_leu32:
4242 case Builtin::BIstdc_load8_leu64:
4243 case Builtin::BIstdc_load8_les8:
4244 case Builtin::BIstdc_load8_les16:
4245 case Builtin::BIstdc_load8_les32:
4246 case Builtin::BIstdc_load8_les64:
4247 case Builtin::BIstdc_load8_beu8:
4248 case Builtin::BIstdc_load8_beu16:
4249 case Builtin::BIstdc_load8_beu32:
4250 case Builtin::BIstdc_load8_beu64:
4251 case Builtin::BIstdc_load8_bes8:
4252 case Builtin::BIstdc_load8_bes16:
4253 case Builtin::BIstdc_load8_bes32:
4254 case Builtin::BIstdc_load8_bes64:
4255 case Builtin::BIstdc_load8_aligned_leu8:
4256 case Builtin::BIstdc_load8_aligned_leu16:
4257 case Builtin::BIstdc_load8_aligned_leu32:
4258 case Builtin::BIstdc_load8_aligned_leu64:
4259 case Builtin::BIstdc_load8_aligned_les8:
4260 case Builtin::BIstdc_load8_aligned_les16:
4261 case Builtin::BIstdc_load8_aligned_les32:
4262 case Builtin::BIstdc_load8_aligned_les64:
4263 case Builtin::BIstdc_load8_aligned_beu8:
4264 case Builtin::BIstdc_load8_aligned_beu16:
4265 case Builtin::BIstdc_load8_aligned_beu32:
4266 case Builtin::BIstdc_load8_aligned_beu64:
4267 case Builtin::BIstdc_load8_aligned_bes8:
4268 case Builtin::BIstdc_load8_aligned_bes16:
4269 case Builtin::BIstdc_load8_aligned_bes32:
4270 case Builtin::BIstdc_load8_aligned_bes64:
4271 if (Context.getTargetInfo().getCharWidth() != 8) {
4272 Diag(TheCall->getBeginLoc(), diag::err_builtin_requires_char_bit_8)
4273 << TheCall->getDirectCallee()->getName();
4274 return ExprError();
4275 }
4276 break;
4277
4278 case Builtin::BI__builtin_stdc_bit_floor:
4279 case Builtin::BI__builtin_stdc_bit_ceil:
4280 if (BuiltinStdCBuiltin(*this, TheCall, QualType()))
4281 return ExprError();
4282 break;
4283 case Builtin::BI__builtin_stdc_has_single_bit:
4284 if (BuiltinStdCBuiltin(*this, TheCall, Context.BoolTy))
4285 return ExprError();
4286 break;
4287 case Builtin::BI__builtin_stdc_leading_zeros:
4288 case Builtin::BI__builtin_stdc_leading_ones:
4289 case Builtin::BI__builtin_stdc_trailing_zeros:
4290 case Builtin::BI__builtin_stdc_trailing_ones:
4291 case Builtin::BI__builtin_stdc_first_leading_zero:
4292 case Builtin::BI__builtin_stdc_first_leading_one:
4293 case Builtin::BI__builtin_stdc_first_trailing_zero:
4294 case Builtin::BI__builtin_stdc_first_trailing_one:
4295 case Builtin::BI__builtin_stdc_count_zeros:
4296 case Builtin::BI__builtin_stdc_count_ones:
4297 case Builtin::BI__builtin_stdc_bit_width:
4298 if (BuiltinStdCBuiltin(*this, TheCall, Context.UnsignedIntTy))
4299 return ExprError();
4300 break;
4301
4302 case Builtin::BI__builtin_allow_runtime_check: {
4303 Expr *Arg = TheCall->getArg(0);
4304 // Check if the argument is a string literal.
4306 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4307 << Arg->getSourceRange();
4308 return ExprError();
4309 }
4310 break;
4311 }
4312
4313 case Builtin::BI__builtin_allow_sanitize_check: {
4314 if (checkArgCount(TheCall, 1))
4315 return ExprError();
4316
4317 Expr *Arg = TheCall->getArg(0);
4318 // Check if the argument is a string literal.
4319 const StringLiteral *SanitizerName =
4320 dyn_cast<StringLiteral>(Arg->IgnoreParenImpCasts());
4321 if (!SanitizerName) {
4322 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
4323 << Arg->getSourceRange();
4324 return ExprError();
4325 }
4326 // Validate the sanitizer name.
4327 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
4328 .Cases({"address", "thread", "memory", "hwaddress",
4329 "kernel-address", "kernel-memory", "kernel-hwaddress"},
4330 true)
4331 .Default(false)) {
4332 Diag(TheCall->getBeginLoc(), diag::err_invalid_builtin_argument)
4333 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
4334 << Arg->getSourceRange();
4335 return ExprError();
4336 }
4337 break;
4338 }
4339 case Builtin::BI__builtin_counted_by_ref:
4340 if (BuiltinCountedByRef(TheCall))
4341 return ExprError();
4342 break;
4343 }
4344
4345 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4346 return ExprError();
4347
4348 // Since the target specific builtins for each arch overlap, only check those
4349 // of the arch we are compiling for.
4350 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
4351 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
4352 assert(Context.getAuxTargetInfo() &&
4353 "Aux Target Builtin, but not an aux target?");
4354
4355 // Host target builtins cannot be lowered for a SYCL device. Defer the
4356 // diagnostic so that they are still accepted in code that is not
4357 // reachable from device code.
4358 if (getLangOpts().SYCLIsDevice && !isUnevaluatedContext())
4359 SYCL().DiagIfDeviceCode(TheCall->getBeginLoc(),
4360 diag::err_builtin_target_unsupported)
4361 << TheCall->getSourceRange();
4362
4363 if (CheckTSBuiltinFunctionCall(
4364 *Context.getAuxTargetInfo(),
4365 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
4366 return ExprError();
4367 } else {
4368 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
4369 TheCall))
4370 return ExprError();
4371 }
4372 }
4373
4374 return TheCallResult;
4375}
4376
4377bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4378 llvm::APSInt Result;
4379 // We can't check the value of a dependent argument.
4380 Expr *Arg = TheCall->getArg(ArgNum);
4381 if (Arg->isTypeDependent() || Arg->isValueDependent())
4382 return false;
4383
4384 // Check constant-ness first.
4385 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4386 return true;
4387
4388 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4389 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4390 return false;
4391
4392 return Diag(TheCall->getBeginLoc(),
4393 diag::err_argument_not_contiguous_bit_field)
4394 << ArgNum << Arg->getSourceRange();
4395}
4396
4397bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4398 unsigned FirstArg, FormatStringInfo *FSI) {
4399 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4400 bool IsVariadic = false;
4401 if (const FunctionType *FnTy = D->getFunctionType())
4402 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic();
4403 else if (const auto *BD = dyn_cast<BlockDecl>(D))
4404 IsVariadic = BD->isVariadic();
4405 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
4406 IsVariadic = OMD->isVariadic();
4407
4408 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4409 IsVariadic, FSI);
4410}
4411
4412bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4413 bool HasImplicitThisParam, bool IsVariadic,
4414 FormatStringInfo *FSI) {
4415 if (FirstArg == 0)
4417 else if (IsVariadic)
4419 else
4421 FSI->FormatIdx = FormatIdx - 1;
4422 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4423
4424 // The way the format attribute works in GCC, the implicit this argument
4425 // of member functions is counted. However, it doesn't appear in our own
4426 // lists, so decrement format_idx in that case.
4427 if (HasImplicitThisParam) {
4428 if(FSI->FormatIdx == 0)
4429 return false;
4430 --FSI->FormatIdx;
4431 if (FSI->FirstDataArg != 0)
4432 --FSI->FirstDataArg;
4433 }
4434 return true;
4435}
4436
4437/// Checks if a the given expression evaluates to null.
4438///
4439/// Returns true if the value evaluates to null.
4440static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4441 // Treat (smart) pointers constructed from nullptr as null, whether we can
4442 // const-evaluate them or not.
4443 // This must happen first: the smart pointer expr might have _Nonnull type!
4447 return true;
4448
4449 // If the expression has non-null type, it doesn't evaluate to null.
4450 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4451 if (*nullability == NullabilityKind::NonNull)
4452 return false;
4453 }
4454
4455 // As a special case, transparent unions initialized with zero are
4456 // considered null for the purposes of the nonnull attribute.
4457 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4458 UT &&
4459 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4460 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr))
4461 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
4462 Expr = ILE->getInit(0);
4463 }
4464
4465 bool Result;
4466 return (!Expr->isValueDependent() &&
4468 !Result);
4469}
4470
4472 const Expr *ArgExpr,
4473 SourceLocation CallSiteLoc) {
4474 if (CheckNonNullExpr(S, ArgExpr))
4475 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4476 S.PDiag(diag::warn_null_arg)
4477 << ArgExpr->getSourceRange());
4478}
4479
4480/// Determine whether the given type has a non-null nullability annotation.
4482 if (auto nullability = type->getNullability())
4483 return *nullability == NullabilityKind::NonNull;
4484
4485 return false;
4486}
4487
4489 const NamedDecl *FDecl,
4490 const FunctionProtoType *Proto,
4492 SourceLocation CallSiteLoc) {
4493 assert((FDecl || Proto) && "Need a function declaration or prototype");
4494
4495 // Already checked by constant evaluator.
4497 return;
4498 // Check the attributes attached to the method/function itself.
4499 llvm::SmallBitVector NonNullArgs;
4500 if (FDecl) {
4501 // Handle the nonnull attribute on the function/method declaration itself.
4502 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4503 if (!NonNull->args_size()) {
4504 // Easy case: all pointer arguments are nonnull.
4505 for (const auto *Arg : Args)
4506 if (S.isValidPointerAttrType(Arg->getType()))
4507 CheckNonNullArgument(S, Arg, CallSiteLoc);
4508 return;
4509 }
4510
4511 for (const ParamIdx &Idx : NonNull->args()) {
4512 unsigned IdxAST = Idx.getASTIndex();
4513 if (IdxAST >= Args.size())
4514 continue;
4515 if (NonNullArgs.empty())
4516 NonNullArgs.resize(Args.size());
4517 NonNullArgs.set(IdxAST);
4518 }
4519 }
4520 }
4521
4522 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4523 // Handle the nonnull attribute on the parameters of the
4524 // function/method.
4526 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4527 parms = FD->parameters();
4528 else
4529 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4530
4531 unsigned ParamIndex = 0;
4532 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4533 I != E; ++I, ++ParamIndex) {
4534 const ParmVarDecl *PVD = *I;
4535 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) {
4536 if (NonNullArgs.empty())
4537 NonNullArgs.resize(Args.size());
4538
4539 NonNullArgs.set(ParamIndex);
4540 }
4541 }
4542 } else {
4543 // If we have a non-function, non-method declaration but no
4544 // function prototype, try to dig out the function prototype.
4545 if (!Proto) {
4546 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4547 QualType type = VD->getType().getNonReferenceType();
4548 if (auto pointerType = type->getAs<PointerType>())
4549 type = pointerType->getPointeeType();
4550 else if (auto blockType = type->getAs<BlockPointerType>())
4551 type = blockType->getPointeeType();
4552 // FIXME: data member pointers?
4553
4554 // Dig out the function prototype, if there is one.
4555 Proto = type->getAs<FunctionProtoType>();
4556 }
4557 }
4558
4559 // Fill in non-null argument information from the nullability
4560 // information on the parameter types (if we have them).
4561 if (Proto) {
4562 unsigned Index = 0;
4563 for (auto paramType : Proto->getParamTypes()) {
4564 if (isNonNullType(paramType)) {
4565 if (NonNullArgs.empty())
4566 NonNullArgs.resize(Args.size());
4567
4568 NonNullArgs.set(Index);
4569 }
4570
4571 ++Index;
4572 }
4573 }
4574 }
4575
4576 // Check for non-null arguments.
4577 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4578 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4579 if (NonNullArgs[ArgIndex])
4580 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc());
4581 }
4582}
4583
4584void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4585 StringRef ParamName, QualType ArgTy,
4586 QualType ParamTy) {
4587
4588 // If a function accepts a pointer or reference type
4589 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4590 return;
4591
4592 // If the parameter is a pointer type, get the pointee type for the
4593 // argument too. If the parameter is a reference type, don't try to get
4594 // the pointee type for the argument.
4595 if (ParamTy->isPointerType())
4596 ArgTy = ArgTy->getPointeeType();
4597
4598 // Remove reference or pointer
4599 ParamTy = ParamTy->getPointeeType();
4600
4601 // Find expected alignment, and the actual alignment of the passed object.
4602 // getTypeAlignInChars requires complete types
4603 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4604 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4605 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4606 return;
4607
4608 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4609 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4610
4611 // If the argument is less aligned than the parameter, there is a
4612 // potential alignment issue.
4613 if (ArgAlign < ParamAlign)
4614 Diag(Loc, diag::warn_param_mismatched_alignment)
4615 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4616 << ParamName << (FDecl != nullptr) << FDecl;
4617}
4618
4619void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4620 const Expr *ThisArg,
4622 if (!FD || Args.empty())
4623 return;
4624 auto GetArgAt = [&](int Idx) -> const Expr * {
4625 if (Idx == LifetimeCaptureByAttr::Global ||
4626 Idx == LifetimeCaptureByAttr::Unknown)
4627 return nullptr;
4628 if (IsMemberFunction && Idx == 0)
4629 return ThisArg;
4630 return Args[Idx - IsMemberFunction];
4631 };
4632 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4633 unsigned ArgIdx) {
4634 if (!Attr)
4635 return;
4636
4637 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4638 for (int CapturingParamIdx : Attr->params()) {
4639 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4640 continue;
4641 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4642 // initialization codepath.
4643 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4645 continue;
4646 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4647 CapturingEntity CE{Capturing};
4648 // Ensure that 'Captured' outlives the 'Capturing' entity.
4649 checkCaptureByLifetime(*this, CE, Captured);
4650 }
4651 };
4652 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4653 for (const auto *A :
4654 FD->getParamDecl(I)->specific_attrs<LifetimeCaptureByAttr>())
4655 HandleCaptureByAttr(A, I + IsMemberFunction);
4656 // Check when the implicit object param is captured.
4657 if (IsMemberFunction) {
4658 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4659 if (!TSI)
4660 return;
4662 for (TypeLoc TL = TSI->getTypeLoc();
4663 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4664 TL = ATL.getModifiedLoc())
4665 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4666 }
4667}
4668
4670 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4671 bool IsMemberFunction, SourceLocation Loc,
4672 SourceRange Range, VariadicCallType CallType) {
4673
4674 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4675 llvm::any_of(Args, [](const Expr *E) {
4676 return E && E->isInstantiationDependent();
4677 }))
4678 return;
4679
4680 // Printf and scanf checking.
4681 llvm::SmallBitVector CheckedVarArgs;
4682 if (FDecl) {
4683 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4684 // Only create vector if there are format attributes.
4685 CheckedVarArgs.resize(Args.size());
4686 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4687 CheckedVarArgs);
4688 }
4689
4690 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4691 CheckedVarArgs.resize(Args.size());
4692 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4693 CheckedVarArgs);
4694 }
4695 }
4696
4697 // Refuse POD arguments that weren't caught by the format string
4698 // checks above.
4699 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4700 if (CallType != VariadicCallType::DoesNotApply &&
4701 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4702 unsigned NumParams = Proto ? Proto->getNumParams()
4703 : isa_and_nonnull<FunctionDecl>(FDecl)
4704 ? cast<FunctionDecl>(FDecl)->getNumParams()
4705 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4706 ? cast<ObjCMethodDecl>(FDecl)->param_size()
4707 : 0;
4708
4709 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4710 // Args[ArgIdx] can be null in malformed code.
4711 if (const Expr *Arg = Args[ArgIdx]) {
4712 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4713 checkVariadicArgument(Arg, CallType);
4714 }
4715 }
4716 }
4717 if (FD)
4718 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4719 if (FDecl || Proto) {
4720 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4721
4722 // Type safety checking.
4723 if (FDecl) {
4724 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4725 CheckArgumentWithTypeTag(I, Args, Loc);
4726 }
4727 }
4728
4729 // Check that passed arguments match the alignment of original arguments.
4730 // Try to get the missing prototype from the declaration.
4731 if (!Proto && FDecl) {
4732 const auto *FT = FDecl->getFunctionType();
4733 if (isa_and_nonnull<FunctionProtoType>(FT))
4734 Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4735 }
4736 if (Proto) {
4737 // For variadic functions, we may have more args than parameters.
4738 // For some K&R functions, we may have less args than parameters.
4739 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4740 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4741 bool IsScalableArg = false;
4742 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4743 // Args[ArgIdx] can be null in malformed code.
4744 if (const Expr *Arg = Args[ArgIdx]) {
4745 if (Arg->containsErrors())
4746 continue;
4747
4748 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4749 FDecl->hasLinkage() &&
4750 FDecl->getFormalLinkage() != Linkage::Internal &&
4752 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg);
4753
4754 QualType ParamTy = Proto->getParamType(ArgIdx);
4755 if (ParamTy->isSizelessVectorType())
4756 IsScalableArg = true;
4757 QualType ArgTy = Arg->getType();
4758 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4759 ArgTy, ParamTy);
4760 }
4761 }
4762
4763 // If the callee has an AArch64 SME attribute to indicate that it is an
4764 // __arm_streaming function, then the caller requires SME to be available.
4767 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) {
4768 llvm::StringMap<bool> CallerFeatureMap;
4769 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4770 if (!CallerFeatureMap.contains("sme"))
4771 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4772 } else if (!Context.getTargetInfo().hasFeature("sme")) {
4773 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4774 }
4775 }
4776
4777 // If the call requires a streaming-mode change and has scalable vector
4778 // arguments or return values, then warn the user that the streaming and
4779 // non-streaming vector lengths may be different.
4780 // When both streaming and non-streaming vector lengths are defined and
4781 // mismatched, produce an error.
4782 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext);
4783 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4784 (IsScalableArg || IsScalableRet)) {
4785 bool IsCalleeStreaming =
4787 bool IsCalleeStreamingCompatible =
4788 ExtInfo.AArch64SMEAttributes &
4790 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD);
4791 if (!IsCalleeStreamingCompatible &&
4792 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4793 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4794 const LangOptions &LO = getLangOpts();
4795 unsigned VL = LO.VScaleMin * 128;
4796 unsigned SVL = LO.VScaleStreamingMin * 128;
4797 bool IsVLMismatch = VL && SVL && VL != SVL;
4798
4799 auto EmitDiag = [&](bool IsArg) {
4800 if (IsVLMismatch) {
4801 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4802 // Emit warning for streaming-compatible callers
4803 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4804 << IsArg << IsCalleeStreaming << SVL << VL;
4805 else
4806 // Emit error otherwise
4807 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4808 << IsArg << SVL << VL;
4809 } else
4810 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4811 << IsArg;
4812 };
4813
4814 if (IsScalableArg)
4815 EmitDiag(true);
4816 if (IsScalableRet)
4817 EmitDiag(false);
4818 }
4819 }
4820
4821 FunctionType::ArmStateValue CalleeArmZAState =
4823 FunctionType::ArmStateValue CalleeArmZT0State =
4825 if (CalleeArmZAState != FunctionType::ARM_None ||
4826 CalleeArmZT0State != FunctionType::ARM_None) {
4827 bool CallerHasZAState = false;
4828 bool CallerHasZT0State = false;
4829 if (CallerFD) {
4830 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4831 if (Attr && Attr->isNewZA())
4832 CallerHasZAState = true;
4833 if (Attr && Attr->isNewZT0())
4834 CallerHasZT0State = true;
4835 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4836 CallerHasZAState |=
4838 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4840 CallerHasZT0State |=
4842 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4844 }
4845 }
4846
4847 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4848 Diag(Loc, diag::err_sme_za_call_no_za_state);
4849
4850 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4851 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4852
4853 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4854 CalleeArmZT0State != FunctionType::ARM_None) {
4855 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4856 Diag(Loc, diag::note_sme_use_preserves_za);
4857 }
4858 }
4859 }
4860
4861 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4862 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4863 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4864 if (!Arg->isValueDependent()) {
4865 Expr::EvalResult Align;
4866 if (Arg->EvaluateAsInt(Align, Context)) {
4867 const llvm::APSInt &I = Align.Val.getInt();
4868 if (!I.isPowerOf2())
4869 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4870 << Arg->getSourceRange();
4871
4872 if (I > Sema::MaximumAlignment)
4873 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4874 << Arg->getSourceRange() << Sema::MaximumAlignment;
4875 }
4876 }
4877 }
4878
4879 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4881 SYCL().DiagIfDeviceCode(Loc, diag::err_variadic_device_fn)
4882 << diag::OffloadLang::SYCL;
4883
4884 if (FD)
4885 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4886}
4887
4888void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4889 if (TemplateDecl *Decl =
4890 AutoT->getTypeConstraintConcept().getAsTemplateDecl()) {
4891 DiagnoseUseOfDecl(Decl, Loc);
4892 }
4893}
4894
4895void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4897 const FunctionProtoType *Proto,
4898 SourceLocation Loc) {
4899 VariadicCallType CallType = Proto->isVariadic()
4902
4903 auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4904 CheckArgAlignment(
4905 Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4906 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4907
4908 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4909 Loc, SourceRange(), CallType);
4910}
4911
4913 const FunctionProtoType *Proto) {
4914 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4915 isa<CXXMethodDecl>(FDecl);
4916 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4917 IsMemberOperatorCall;
4918 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4919 TheCall->getCallee());
4920 Expr** Args = TheCall->getArgs();
4921 unsigned NumArgs = TheCall->getNumArgs();
4922
4923 Expr *ImplicitThis = nullptr;
4924 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4925 // If this is a call to a member operator, hide the first
4926 // argument from checkCall.
4927 // FIXME: Our choice of AST representation here is less than ideal.
4928 ImplicitThis = Args[0];
4929 ++Args;
4930 --NumArgs;
4931 } else if (IsMemberFunction && !FDecl->isStatic() &&
4933 ImplicitThis =
4934 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4935
4936 if (ImplicitThis) {
4937 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4938 // used.
4939 QualType ThisType = ImplicitThis->getType();
4940 if (!ThisType->isPointerType()) {
4941 assert(!ThisType->isReferenceType());
4942 ThisType = Context.getPointerType(ThisType);
4943 }
4944
4945 QualType ThisTypeFromDecl = Context.getPointerType(
4946 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType());
4947
4948 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4949 ThisTypeFromDecl);
4950 }
4951
4952 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs),
4953 IsMemberFunction, TheCall->getRParenLoc(),
4954 TheCall->getCallee()->getSourceRange(), CallType);
4955
4956 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4957 // None of the checks below are needed for functions that don't have
4958 // simple names (e.g., C++ conversion functions).
4959 if (!FnInfo)
4960 return false;
4961
4962 // Enforce TCB except for builtin calls, which are always allowed.
4963 if (FDecl->getBuiltinID() == 0)
4964 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl);
4965
4966 CheckAbsoluteValueFunction(TheCall, FDecl);
4967 CheckMaxUnsignedZero(TheCall, FDecl);
4968 CheckInfNaNFunction(TheCall, FDecl);
4969
4970 if (getLangOpts().ObjC)
4971 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4972
4973 unsigned CMId = FDecl->getMemoryFunctionKind();
4974
4975 // Handle memory setting and copying functions.
4976 switch (CMId) {
4977 case 0:
4978 return false;
4979 case Builtin::BIstrlcpy: // fallthrough
4980 case Builtin::BIstrlcat:
4981 CheckStrlcpycatArguments(TheCall, FnInfo);
4982 break;
4983 case Builtin::BIstrncat:
4984 CheckStrncatArguments(TheCall, FnInfo);
4985 break;
4986 case Builtin::BIfree:
4987 CheckFreeArguments(TheCall);
4988 break;
4989 default:
4990 CheckMemaccessArguments(TheCall, CMId, FnInfo);
4991 }
4992
4993 return false;
4994}
4995
4996bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4997 const FunctionProtoType *Proto) {
4998 QualType Ty;
4999 if (const auto *V = dyn_cast<VarDecl>(NDecl))
5000 Ty = V->getType().getNonReferenceType();
5001 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5002 Ty = F->getType().getNonReferenceType();
5003 else
5004 return false;
5005
5006 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5007 !Ty->isFunctionProtoType())
5008 return false;
5009
5010 VariadicCallType CallType;
5011 if (!Proto || !Proto->isVariadic()) {
5013 } else if (Ty->isBlockPointerType()) {
5014 CallType = VariadicCallType::Block;
5015 } else { // Ty->isFunctionPointerType()
5016 CallType = VariadicCallType::Function;
5017 }
5018
5019 checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5020 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5021 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5022 TheCall->getCallee()->getSourceRange(), CallType);
5023
5024 return false;
5025}
5026
5027bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5028 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5029 TheCall->getCallee());
5030 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5031 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5032 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5033 TheCall->getCallee()->getSourceRange(), CallType);
5034
5035 return false;
5036}
5037
5039 if (!llvm::isValidAtomicOrderingCABI(Ordering))
5040 return false;
5041
5042 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5043 switch (Op) {
5044 case AtomicExpr::AO__c11_atomic_init:
5045 case AtomicExpr::AO__opencl_atomic_init:
5046 llvm_unreachable("There is no ordering argument for an init");
5047
5048 case AtomicExpr::AO__c11_atomic_load:
5049 case AtomicExpr::AO__opencl_atomic_load:
5050 case AtomicExpr::AO__hip_atomic_load:
5051 case AtomicExpr::AO__atomic_load_n:
5052 case AtomicExpr::AO__atomic_load:
5053 case AtomicExpr::AO__scoped_atomic_load_n:
5054 case AtomicExpr::AO__scoped_atomic_load:
5055 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5056 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5057
5058 case AtomicExpr::AO__c11_atomic_store:
5059 case AtomicExpr::AO__opencl_atomic_store:
5060 case AtomicExpr::AO__hip_atomic_store:
5061 case AtomicExpr::AO__atomic_store:
5062 case AtomicExpr::AO__atomic_store_n:
5063 case AtomicExpr::AO__scoped_atomic_store:
5064 case AtomicExpr::AO__scoped_atomic_store_n:
5065 case AtomicExpr::AO__atomic_clear:
5066 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5067 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5068 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5069
5070 default:
5071 return true;
5072 }
5073}
5074
5075ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
5077 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5078 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5079 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5080 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5081 DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5082 Op);
5083}
5084
5085/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
5086/// equivalents. Provide a fixit when the scope is a compile-time constant and
5087/// there is a direct mapping from the HIP builtin to a Clang builtin. The
5088/// compare_exchange builtins differ in how they accept the desired value, so
5089/// only a warning (without a fixit) is emitted for those.
5091 MultiExprArg Args,
5093 StringRef OldName;
5094 StringRef NewName;
5095 bool CanFixIt;
5096
5097 switch (Op) {
5098#define HIP_ATOMIC_FIXABLE(hip, scoped) \
5099 case AtomicExpr::AO__hip_atomic_##hip: \
5100 OldName = "__hip_atomic_" #hip; \
5101 NewName = "__scoped_atomic_" #scoped; \
5102 CanFixIt = true; \
5103 break;
5104 HIP_ATOMIC_FIXABLE(load, load_n)
5105 HIP_ATOMIC_FIXABLE(store, store_n)
5106 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
5107 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
5108 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
5109 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
5110 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
5111 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
5112 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
5113 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
5114#undef HIP_ATOMIC_FIXABLE
5115 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5116 OldName = "__hip_atomic_compare_exchange_weak";
5117 NewName = "__scoped_atomic_compare_exchange";
5118 CanFixIt = false;
5119 break;
5120 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5121 OldName = "__hip_atomic_compare_exchange_strong";
5122 NewName = "__scoped_atomic_compare_exchange";
5123 CanFixIt = false;
5124 break;
5125 default:
5126 llvm_unreachable("unhandled HIP atomic op");
5127 }
5128
5129 auto DB = S.Diag(ExprRange.getBegin(), diag::warn_hip_deprecated_builtin)
5130 << OldName << NewName;
5131 if (!CanFixIt)
5132 return;
5133
5134 DB << FixItHint::CreateReplacement(ExprRange, NewName);
5135
5136 Expr *Scope = Args[Args.size() - 1];
5137 std::optional<llvm::APSInt> ScopeVal =
5138 Scope->getIntegerConstantExpr(S.Context);
5139 if (!ScopeVal)
5140 return;
5141
5142 StringRef ScopeName;
5143 switch (ScopeVal->getZExtValue()) {
5145 ScopeName = "__MEMORY_SCOPE_SINGLE";
5146 break;
5148 ScopeName = "__MEMORY_SCOPE_WVFRNT";
5149 break;
5151 ScopeName = "__MEMORY_SCOPE_WRKGRP";
5152 break;
5154 ScopeName = "__MEMORY_SCOPE_DEVICE";
5155 break;
5157 ScopeName = "__MEMORY_SCOPE_SYSTEM";
5158 break;
5160 ScopeName = "__MEMORY_SCOPE_CLUSTR";
5161 break;
5162 default:
5163 return;
5164 }
5165
5167 CharSourceRange::getTokenRange(Scope->getSourceRange()), ScopeName);
5168}
5169
5171 SourceLocation RParenLoc, MultiExprArg Args,
5173 AtomicArgumentOrder ArgOrder) {
5174 // All the non-OpenCL operations take one of the following forms.
5175 // The OpenCL operations take the __c11 forms with one extra argument for
5176 // synchronization scope.
5177 enum {
5178 // C __c11_atomic_init(A *, C)
5179 Init,
5180
5181 // C __c11_atomic_load(A *, int)
5182 Load,
5183
5184 // void __atomic_load(A *, CP, int)
5185 LoadCopy,
5186
5187 // void __atomic_store(A *, CP, int)
5188 Copy,
5189
5190 // C __c11_atomic_add(A *, M, int)
5191 Arithmetic,
5192
5193 // C __atomic_exchange_n(A *, CP, int)
5194 Xchg,
5195
5196 // void __atomic_exchange(A *, C *, CP, int)
5197 GNUXchg,
5198
5199 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5200 C11CmpXchg,
5201
5202 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5203 GNUCmpXchg,
5204
5205 // bool __atomic_test_and_set(A *, int)
5206 TestAndSetByte,
5207
5208 // void __atomic_clear(A *, int)
5209 ClearByte,
5210 } Form = Init;
5211
5212 const unsigned NumForm = ClearByte + 1;
5213 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
5214 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
5215 // where:
5216 // C is an appropriate type,
5217 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5218 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5219 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5220 // the int parameters are for orderings.
5221
5222 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5223 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5224 "need to update code for modified forms");
5225 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
5226 AtomicExpr::AO__atomic_xor_fetch + 1 ==
5227 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
5228 "need to update code for modified C11 atomics");
5229 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
5230 Op <= AtomicExpr::AO__opencl_atomic_store;
5231 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
5232 Op <= AtomicExpr::AO__hip_atomic_store;
5233 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
5234 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
5235 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
5236 Op <= AtomicExpr::AO__c11_atomic_store) ||
5237 IsOpenCL;
5238 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5239 Op == AtomicExpr::AO__atomic_store_n ||
5240 Op == AtomicExpr::AO__atomic_exchange_n ||
5241 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
5242 Op == AtomicExpr::AO__scoped_atomic_load_n ||
5243 Op == AtomicExpr::AO__scoped_atomic_store_n ||
5244 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
5245 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
5246 // Bit mask for extra allowed value types other than integers for atomic
5247 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
5248 // allow floating point.
5249 enum ArithOpExtraValueType {
5250 AOEVT_None = 0,
5251 AOEVT_Pointer = 1,
5252 AOEVT_FP = 2,
5253 AOEVT_Int = 4,
5254 };
5255 unsigned ArithAllows = AOEVT_None;
5256
5257 switch (Op) {
5258 case AtomicExpr::AO__c11_atomic_init:
5259 case AtomicExpr::AO__opencl_atomic_init:
5260 Form = Init;
5261 break;
5262
5263 case AtomicExpr::AO__c11_atomic_load:
5264 case AtomicExpr::AO__opencl_atomic_load:
5265 case AtomicExpr::AO__hip_atomic_load:
5266 case AtomicExpr::AO__atomic_load_n:
5267 case AtomicExpr::AO__scoped_atomic_load_n:
5268 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5269 Form = Load;
5270 break;
5271
5272 case AtomicExpr::AO__atomic_load:
5273 case AtomicExpr::AO__scoped_atomic_load:
5274 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5275 Form = LoadCopy;
5276 break;
5277
5278 case AtomicExpr::AO__c11_atomic_store:
5279 case AtomicExpr::AO__opencl_atomic_store:
5280 case AtomicExpr::AO__hip_atomic_store:
5281 case AtomicExpr::AO__atomic_store:
5282 case AtomicExpr::AO__atomic_store_n:
5283 case AtomicExpr::AO__scoped_atomic_store:
5284 case AtomicExpr::AO__scoped_atomic_store_n:
5285 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5286 Form = Copy;
5287 break;
5288 case AtomicExpr::AO__atomic_fetch_add:
5289 case AtomicExpr::AO__atomic_fetch_sub:
5290 case AtomicExpr::AO__atomic_add_fetch:
5291 case AtomicExpr::AO__atomic_sub_fetch:
5292 case AtomicExpr::AO__scoped_atomic_fetch_add:
5293 case AtomicExpr::AO__scoped_atomic_fetch_sub:
5294 case AtomicExpr::AO__scoped_atomic_add_fetch:
5295 case AtomicExpr::AO__scoped_atomic_sub_fetch:
5296 case AtomicExpr::AO__c11_atomic_fetch_add:
5297 case AtomicExpr::AO__c11_atomic_fetch_sub:
5298 case AtomicExpr::AO__opencl_atomic_fetch_add:
5299 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5300 case AtomicExpr::AO__hip_atomic_fetch_add:
5301 case AtomicExpr::AO__hip_atomic_fetch_sub:
5302 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5303 Form = Arithmetic;
5304 break;
5305 case AtomicExpr::AO__atomic_fetch_fminimum:
5306 case AtomicExpr::AO__atomic_fetch_fmaximum:
5307 case AtomicExpr::AO__atomic_fetch_fminimum_num:
5308 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
5309 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
5310 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
5311 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
5312 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
5313 ArithAllows = AOEVT_FP;
5314 Form = Arithmetic;
5315 break;
5316 case AtomicExpr::AO__atomic_fetch_max:
5317 case AtomicExpr::AO__atomic_fetch_min:
5318 case AtomicExpr::AO__atomic_max_fetch:
5319 case AtomicExpr::AO__atomic_min_fetch:
5320 case AtomicExpr::AO__scoped_atomic_fetch_max:
5321 case AtomicExpr::AO__scoped_atomic_fetch_min:
5322 case AtomicExpr::AO__scoped_atomic_max_fetch:
5323 case AtomicExpr::AO__scoped_atomic_min_fetch:
5324 case AtomicExpr::AO__c11_atomic_fetch_max:
5325 case AtomicExpr::AO__c11_atomic_fetch_min:
5326 case AtomicExpr::AO__opencl_atomic_fetch_max:
5327 case AtomicExpr::AO__opencl_atomic_fetch_min:
5328 case AtomicExpr::AO__hip_atomic_fetch_max:
5329 case AtomicExpr::AO__hip_atomic_fetch_min:
5330 ArithAllows = AOEVT_Int | AOEVT_FP;
5331 Form = Arithmetic;
5332 break;
5333 case AtomicExpr::AO__c11_atomic_fetch_and:
5334 case AtomicExpr::AO__c11_atomic_fetch_or:
5335 case AtomicExpr::AO__c11_atomic_fetch_xor:
5336 case AtomicExpr::AO__hip_atomic_fetch_and:
5337 case AtomicExpr::AO__hip_atomic_fetch_or:
5338 case AtomicExpr::AO__hip_atomic_fetch_xor:
5339 case AtomicExpr::AO__c11_atomic_fetch_nand:
5340 case AtomicExpr::AO__opencl_atomic_fetch_and:
5341 case AtomicExpr::AO__opencl_atomic_fetch_or:
5342 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5343 case AtomicExpr::AO__atomic_fetch_and:
5344 case AtomicExpr::AO__atomic_fetch_or:
5345 case AtomicExpr::AO__atomic_fetch_xor:
5346 case AtomicExpr::AO__atomic_fetch_nand:
5347 case AtomicExpr::AO__atomic_and_fetch:
5348 case AtomicExpr::AO__atomic_or_fetch:
5349 case AtomicExpr::AO__atomic_xor_fetch:
5350 case AtomicExpr::AO__atomic_nand_fetch:
5351 case AtomicExpr::AO__atomic_fetch_uinc:
5352 case AtomicExpr::AO__atomic_fetch_udec:
5353 case AtomicExpr::AO__scoped_atomic_fetch_and:
5354 case AtomicExpr::AO__scoped_atomic_fetch_or:
5355 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5356 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5357 case AtomicExpr::AO__scoped_atomic_and_fetch:
5358 case AtomicExpr::AO__scoped_atomic_or_fetch:
5359 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5360 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5361 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5362 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5363 Form = Arithmetic;
5364 break;
5365
5366 case AtomicExpr::AO__c11_atomic_exchange:
5367 case AtomicExpr::AO__hip_atomic_exchange:
5368 case AtomicExpr::AO__opencl_atomic_exchange:
5369 case AtomicExpr::AO__atomic_exchange_n:
5370 case AtomicExpr::AO__scoped_atomic_exchange_n:
5371 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5372 Form = Xchg;
5373 break;
5374
5375 case AtomicExpr::AO__atomic_exchange:
5376 case AtomicExpr::AO__scoped_atomic_exchange:
5377 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5378 Form = GNUXchg;
5379 break;
5380
5381 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5382 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5383 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5384 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5385 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5386 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5387 Form = C11CmpXchg;
5388 break;
5389
5390 case AtomicExpr::AO__atomic_compare_exchange:
5391 case AtomicExpr::AO__atomic_compare_exchange_n:
5392 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5393 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5394 ArithAllows = AOEVT_Pointer;
5395 Form = GNUCmpXchg;
5396 break;
5397
5398 case AtomicExpr::AO__atomic_test_and_set:
5399 Form = TestAndSetByte;
5400 break;
5401
5402 case AtomicExpr::AO__atomic_clear:
5403 Form = ClearByte;
5404 break;
5405 }
5406
5407 unsigned AdjustedNumArgs = NumArgs[Form];
5408 if ((IsOpenCL || IsHIP || IsScoped) &&
5409 Op != AtomicExpr::AO__opencl_atomic_init)
5410 ++AdjustedNumArgs;
5411 // Check we have the right number of arguments.
5412 if (Args.size() < AdjustedNumArgs) {
5413 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5414 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5415 << /*is non object*/ 0 << ExprRange;
5416 return ExprError();
5417 } else if (Args.size() > AdjustedNumArgs) {
5418 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5419 diag::err_typecheck_call_too_many_args)
5420 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5421 << /*is non object*/ 0 << ExprRange;
5422 return ExprError();
5423 }
5424
5425 // Inspect the first argument of the atomic operation.
5426 Expr *Ptr = Args[0];
5428 if (ConvertedPtr.isInvalid())
5429 return ExprError();
5430
5431 Ptr = ConvertedPtr.get();
5432 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5433 if (!pointerType) {
5434 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5435 << Ptr->getType() << 0 << Ptr->getSourceRange();
5436 return ExprError();
5437 }
5438
5439 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5440 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5441 QualType ValType = AtomTy; // 'C'
5442 if (IsC11) {
5443 if (!AtomTy->isAtomicType()) {
5444 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5445 << Ptr->getType() << Ptr->getSourceRange();
5446 return ExprError();
5447 }
5448 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5450 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5451 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5452 << Ptr->getSourceRange();
5453 return ExprError();
5454 }
5455 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5456 } else if (Form != Load && Form != LoadCopy) {
5457 if (ValType.isConstQualified()) {
5458 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5459 << Ptr->getType() << Ptr->getSourceRange();
5460 return ExprError();
5461 }
5462 }
5463
5464 if (Form != TestAndSetByte && Form != ClearByte) {
5465 // Pointer to object of size zero is not allowed.
5466 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy,
5467 diag::err_incomplete_type))
5468 return ExprError();
5469
5470 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
5471 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5472 << Ptr->getType() << 1 << Ptr->getSourceRange();
5473 return ExprError();
5474 }
5475 } else {
5476 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5477 // non-const pointer type, including void* and pointers to incomplete
5478 // structs, but only access the first byte.
5479 AtomTy = Context.CharTy;
5480 AtomTy = AtomTy.withCVRQualifiers(
5481 pointerType->getPointeeType().getCVRQualifiers());
5482 QualType PointerQT = Context.getPointerType(AtomTy);
5483 pointerType = PointerQT->getAs<PointerType>();
5484 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get();
5485 ValType = AtomTy;
5486 }
5487
5488 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5489 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5490 Diag(ExprRange.getBegin(),
5491 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5492 << 0 << Ptr->getType() << Ptr->getSourceRange();
5493 return ExprError();
5494 }
5495
5496 // For an arithmetic operation, the implied arithmetic must be well-formed.
5497 // For _n operations, the value type must also be a valid atomic type.
5498 if (Form == Arithmetic || IsN) {
5499 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5500 // trivial type errors.
5501 auto IsAllowedValueType = [&](QualType ValType,
5502 unsigned AllowedType) -> bool {
5503 bool IsX87LongDouble =
5504 ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5505 &Context.getTargetInfo().getLongDoubleFormat() ==
5506 &llvm::APFloat::x87DoubleExtended();
5507 if (ValType->isIntegerType())
5508 // Special case: f-prefixed operations (AOEVT_FP exactly) reject
5509 // integers. Explicit AOEVT_Int or other combinations allow integers.
5510 return (AllowedType & AOEVT_Int) || AllowedType != AOEVT_FP;
5511 if (ValType->isPointerType())
5512 return AllowedType & AOEVT_Pointer;
5513 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5514 return false;
5515 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5516 if (IsX87LongDouble)
5517 return false;
5518 return true;
5519 };
5520 if (!IsAllowedValueType(ValType, ArithAllows)) {
5521 auto DID =
5522 ArithAllows == AOEVT_FP
5523 ? diag::err_atomic_op_needs_atomic_fp
5524 : (ArithAllows & AOEVT_FP
5525 ? (ArithAllows & AOEVT_Pointer
5526 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5527 : diag::err_atomic_op_needs_atomic_int_or_fp)
5528 : (ArithAllows & AOEVT_Pointer
5529 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5530 : diag::err_atomic_op_needs_atomic_int));
5531 Diag(ExprRange.getBegin(), DID)
5532 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5533 return ExprError();
5534 }
5535 if (IsC11 && ValType->isPointerType() &&
5536 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5537 diag::err_incomplete_type)) {
5538 return ExprError();
5539 }
5540 }
5541
5542 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5543 !AtomTy->isScalarType()) {
5544 // For GNU atomics, require a trivially-copyable type. This is not part of
5545 // the GNU atomics specification but we enforce it for consistency with
5546 // other atomics which generally all require a trivially-copyable type. This
5547 // is because atomics just copy bits.
5548 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5549 << Ptr->getType() << Ptr->getSourceRange();
5550 return ExprError();
5551 }
5552
5553 switch (ValType.getObjCLifetime()) {
5556 // okay
5557 break;
5558
5562 // FIXME: Can this happen? By this point, ValType should be known
5563 // to be trivially copyable.
5564 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5565 << ValType << Ptr->getSourceRange();
5566 return ExprError();
5567 }
5568
5569 // All atomic operations have an overload which takes a pointer to a volatile
5570 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5571 // into the result or the other operands. Similarly atomic_load takes a
5572 // pointer to a const 'A'.
5573 ValType.removeLocalVolatile();
5574 ValType.removeLocalConst();
5575 QualType ResultType = ValType;
5576 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5577 Form == ClearByte)
5578 ResultType = Context.VoidTy;
5579 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5580 ResultType = Context.BoolTy;
5581
5582 // The type of a parameter passed 'by value'. In the GNU atomics, such
5583 // arguments are actually passed as pointers.
5584 QualType ByValType = ValType; // 'CP'
5585 bool IsPassedByAddress = false;
5586 if (!IsC11 && !IsHIP && !IsN) {
5587 ByValType = Ptr->getType();
5588 IsPassedByAddress = true;
5589 }
5590
5591 SmallVector<Expr *, 5> APIOrderedArgs;
5592 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5593 APIOrderedArgs.push_back(Args[0]);
5594 switch (Form) {
5595 case Init:
5596 case Load:
5597 APIOrderedArgs.push_back(Args[1]); // Val1/Order
5598 break;
5599 case LoadCopy:
5600 case Copy:
5601 case Arithmetic:
5602 case Xchg:
5603 APIOrderedArgs.push_back(Args[2]); // Val1
5604 APIOrderedArgs.push_back(Args[1]); // Order
5605 break;
5606 case GNUXchg:
5607 APIOrderedArgs.push_back(Args[2]); // Val1
5608 APIOrderedArgs.push_back(Args[3]); // Val2
5609 APIOrderedArgs.push_back(Args[1]); // Order
5610 break;
5611 case C11CmpXchg:
5612 APIOrderedArgs.push_back(Args[2]); // Val1
5613 APIOrderedArgs.push_back(Args[4]); // Val2
5614 APIOrderedArgs.push_back(Args[1]); // Order
5615 APIOrderedArgs.push_back(Args[3]); // OrderFail
5616 break;
5617 case GNUCmpXchg:
5618 APIOrderedArgs.push_back(Args[2]); // Val1
5619 APIOrderedArgs.push_back(Args[4]); // Val2
5620 APIOrderedArgs.push_back(Args[5]); // Weak
5621 APIOrderedArgs.push_back(Args[1]); // Order
5622 APIOrderedArgs.push_back(Args[3]); // OrderFail
5623 break;
5624 case TestAndSetByte:
5625 case ClearByte:
5626 APIOrderedArgs.push_back(Args[1]); // Order
5627 break;
5628 }
5629 } else
5630 APIOrderedArgs.append(Args.begin(), Args.end());
5631
5632 // The first argument's non-CV pointer type is used to deduce the type of
5633 // subsequent arguments, except for:
5634 // - weak flag (always converted to bool)
5635 // - memory order (always converted to int)
5636 // - scope (always converted to int)
5637 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5638 QualType Ty;
5639 if (i < NumVals[Form] + 1) {
5640 switch (i) {
5641 case 0:
5642 // The first argument is always a pointer. It has a fixed type.
5643 // It is always dereferenced, a nullptr is undefined.
5644 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5645 // Nothing else to do: we already know all we want about this pointer.
5646 continue;
5647 case 1:
5648 // The second argument is the non-atomic operand. For arithmetic, this
5649 // is always passed by value, and for a compare_exchange it is always
5650 // passed by address. For the rest, GNU uses by-address and C11 uses
5651 // by-value.
5652 assert(Form != Load);
5653 if (Form == Arithmetic && ValType->isPointerType())
5654 Ty = Context.getPointerDiffType();
5655 else if (Form == Init || Form == Arithmetic)
5656 Ty = ValType;
5657 else if (Form == Copy || Form == Xchg) {
5658 if (IsPassedByAddress) {
5659 // The value pointer is always dereferenced, a nullptr is undefined.
5660 CheckNonNullArgument(*this, APIOrderedArgs[i],
5661 ExprRange.getBegin());
5662 }
5663 Ty = ByValType;
5664 } else {
5665 Expr *ValArg = APIOrderedArgs[i];
5666 // The value pointer is always dereferenced, a nullptr is undefined.
5667 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5669 // Keep address space of non-atomic pointer type.
5670 if (const PointerType *PtrTy =
5671 ValArg->getType()->getAs<PointerType>()) {
5672 AS = PtrTy->getPointeeType().getAddressSpace();
5673 }
5674 Ty = Context.getPointerType(
5675 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5676 }
5677 break;
5678 case 2:
5679 // The third argument to compare_exchange / GNU exchange is the desired
5680 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5681 if (IsPassedByAddress)
5682 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5683 Ty = ByValType;
5684 break;
5685 case 3:
5686 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5687 Ty = Context.BoolTy;
5688 break;
5689 }
5690 } else {
5691 // The order(s) and scope are always converted to int.
5692 Ty = Context.IntTy;
5693 }
5694
5695 InitializedEntity Entity =
5697 ExprResult Arg = APIOrderedArgs[i];
5698 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5699 if (Arg.isInvalid())
5700 return true;
5701 APIOrderedArgs[i] = Arg.get();
5702 }
5703
5704 // Permute the arguments into a 'consistent' order.
5705 SmallVector<Expr*, 5> SubExprs;
5706 SubExprs.push_back(Ptr);
5707 switch (Form) {
5708 case Init:
5709 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5710 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5711 break;
5712 case Load:
5713 case TestAndSetByte:
5714 case ClearByte:
5715 SubExprs.push_back(APIOrderedArgs[1]); // Order
5716 break;
5717 case LoadCopy:
5718 case Copy:
5719 case Arithmetic:
5720 case Xchg:
5721 SubExprs.push_back(APIOrderedArgs[2]); // Order
5722 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5723 break;
5724 case GNUXchg:
5725 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5726 SubExprs.push_back(APIOrderedArgs[3]); // Order
5727 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5728 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5729 break;
5730 case C11CmpXchg:
5731 SubExprs.push_back(APIOrderedArgs[3]); // Order
5732 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5733 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5734 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5735 break;
5736 case GNUCmpXchg:
5737 SubExprs.push_back(APIOrderedArgs[4]); // Order
5738 SubExprs.push_back(APIOrderedArgs[1]); // Val1
5739 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5740 SubExprs.push_back(APIOrderedArgs[2]); // Val2
5741 SubExprs.push_back(APIOrderedArgs[3]); // Weak
5742 break;
5743 }
5744
5745 // If the memory orders are constants, check they are valid.
5746 if (SubExprs.size() >= 2 && Form != Init) {
5747 std::optional<llvm::APSInt> Success =
5748 SubExprs[1]->getIntegerConstantExpr(Context);
5749 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) {
5750 Diag(SubExprs[1]->getBeginLoc(),
5751 diag::warn_atomic_op_has_invalid_memory_order)
5752 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5753 << SubExprs[1]->getSourceRange();
5754 }
5755 if (SubExprs.size() >= 5) {
5756 if (std::optional<llvm::APSInt> Failure =
5757 SubExprs[3]->getIntegerConstantExpr(Context)) {
5758 if (!llvm::is_contained(
5759 {llvm::AtomicOrderingCABI::relaxed,
5760 llvm::AtomicOrderingCABI::consume,
5761 llvm::AtomicOrderingCABI::acquire,
5762 llvm::AtomicOrderingCABI::seq_cst},
5763 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5764 Diag(SubExprs[3]->getBeginLoc(),
5765 diag::warn_atomic_op_has_invalid_memory_order)
5766 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5767 }
5768 }
5769 }
5770 }
5771
5772 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5773 auto *Scope = Args[Args.size() - 1];
5774 if (std::optional<llvm::APSInt> Result =
5775 Scope->getIntegerConstantExpr(Context)) {
5776 if (!ScopeModel->isValid(Result->getZExtValue()))
5777 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5778 << Scope->getSourceRange();
5779 }
5780 SubExprs.push_back(Scope);
5781 }
5782
5783 if (IsHIP)
5784 DiagnoseDeprecatedHIPAtomic(*this, ExprRange, Args, Op);
5785
5786 AtomicExpr *AE = new (Context)
5787 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5788
5789 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5790 Op == AtomicExpr::AO__c11_atomic_store ||
5791 Op == AtomicExpr::AO__opencl_atomic_load ||
5792 Op == AtomicExpr::AO__hip_atomic_load ||
5793 Op == AtomicExpr::AO__opencl_atomic_store ||
5794 Op == AtomicExpr::AO__hip_atomic_store) &&
5795 Context.AtomicUsesUnsupportedLibcall(AE))
5796 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5797 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5798 Op == AtomicExpr::AO__opencl_atomic_load ||
5799 Op == AtomicExpr::AO__hip_atomic_load)
5800 ? 0
5801 : 1);
5802
5803 if (ValType->isBitIntType()) {
5804 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5805 return ExprError();
5806 }
5807
5808 return AE;
5809}
5810
5811/// checkBuiltinArgument - Given a call to a builtin function, perform
5812/// normal type-checking on the given argument, updating the call in
5813/// place. This is useful when a builtin function requires custom
5814/// type-checking for some of its arguments but not necessarily all of
5815/// them.
5816///
5817/// Returns true on error.
5818static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5819 FunctionDecl *Fn = E->getDirectCallee();
5820 assert(Fn && "builtin call without direct callee!");
5821
5822 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5823 InitializedEntity Entity =
5825
5826 ExprResult Arg = E->getArg(ArgIndex);
5827 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5828 if (Arg.isInvalid())
5829 return true;
5830
5831 E->setArg(ArgIndex, Arg.get());
5832 return false;
5833}
5834
5835ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5836 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5837 Expr *Callee = TheCall->getCallee();
5838 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5839 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5840
5841 // Ensure that we have at least one argument to do type inference from.
5842 if (TheCall->getNumArgs() < 1) {
5843 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5844 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5845 << Callee->getSourceRange();
5846 return ExprError();
5847 }
5848
5849 // Inspect the first argument of the atomic builtin. This should always be
5850 // a pointer type, whose element is an integral scalar or pointer type.
5851 // Because it is a pointer type, we don't have to worry about any implicit
5852 // casts here.
5853 // FIXME: We don't allow floating point scalars as input.
5854 Expr *FirstArg = TheCall->getArg(0);
5855 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5856 if (FirstArgResult.isInvalid())
5857 return ExprError();
5858 FirstArg = FirstArgResult.get();
5859 TheCall->setArg(0, FirstArg);
5860
5861 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5862 if (!pointerType) {
5863 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5864 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5865 return ExprError();
5866 }
5867
5868 QualType ValType = pointerType->getPointeeType();
5869 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5870 !ValType->isBlockPointerType()) {
5871 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5872 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5873 return ExprError();
5874 }
5875 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5876 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5877 Diag(FirstArg->getBeginLoc(),
5878 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5879 << 1 << ValType << FirstArg->getSourceRange();
5880 return ExprError();
5881 }
5882
5883 if (ValType.isConstQualified()) {
5884 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5885 << FirstArg->getType() << FirstArg->getSourceRange();
5886 return ExprError();
5887 }
5888
5889 switch (ValType.getObjCLifetime()) {
5892 // okay
5893 break;
5894
5898 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5899 << ValType << FirstArg->getSourceRange();
5900
5901 return ExprError();
5902 }
5903
5904 // Strip any qualifiers off ValType.
5905 ValType = ValType.getUnqualifiedType();
5906
5907 // The majority of builtins return a value, but a few have special return
5908 // types, so allow them to override appropriately below.
5909 QualType ResultType = ValType;
5910
5911 // We need to figure out which concrete builtin this maps onto. For example,
5912 // __sync_fetch_and_add with a 2 byte object turns into
5913 // __sync_fetch_and_add_2.
5914#define BUILTIN_ROW(x) \
5915 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5916 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5917
5918 static const unsigned BuiltinIndices[][5] = {
5919 BUILTIN_ROW(__sync_fetch_and_add),
5920 BUILTIN_ROW(__sync_fetch_and_sub),
5921 BUILTIN_ROW(__sync_fetch_and_or),
5922 BUILTIN_ROW(__sync_fetch_and_and),
5923 BUILTIN_ROW(__sync_fetch_and_xor),
5924 BUILTIN_ROW(__sync_fetch_and_nand),
5925
5926 BUILTIN_ROW(__sync_add_and_fetch),
5927 BUILTIN_ROW(__sync_sub_and_fetch),
5928 BUILTIN_ROW(__sync_and_and_fetch),
5929 BUILTIN_ROW(__sync_or_and_fetch),
5930 BUILTIN_ROW(__sync_xor_and_fetch),
5931 BUILTIN_ROW(__sync_nand_and_fetch),
5932
5933 BUILTIN_ROW(__sync_val_compare_and_swap),
5934 BUILTIN_ROW(__sync_bool_compare_and_swap),
5935 BUILTIN_ROW(__sync_lock_test_and_set),
5936 BUILTIN_ROW(__sync_lock_release),
5937 BUILTIN_ROW(__sync_swap)
5938 };
5939#undef BUILTIN_ROW
5940
5941 // Determine the index of the size.
5942 unsigned SizeIndex;
5943 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5944 case 1: SizeIndex = 0; break;
5945 case 2: SizeIndex = 1; break;
5946 case 4: SizeIndex = 2; break;
5947 case 8: SizeIndex = 3; break;
5948 case 16: SizeIndex = 4; break;
5949 default:
5950 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5951 << FirstArg->getType() << FirstArg->getSourceRange();
5952 return ExprError();
5953 }
5954
5955 // Each of these builtins has one pointer argument, followed by some number of
5956 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5957 // that we ignore. Find out which row of BuiltinIndices to read from as well
5958 // as the number of fixed args.
5959 unsigned BuiltinID = FDecl->getBuiltinID();
5960 unsigned BuiltinIndex, NumFixed = 1;
5961 bool WarnAboutSemanticsChange = false;
5962 switch (BuiltinID) {
5963 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5964 case Builtin::BI__sync_fetch_and_add:
5965 case Builtin::BI__sync_fetch_and_add_1:
5966 case Builtin::BI__sync_fetch_and_add_2:
5967 case Builtin::BI__sync_fetch_and_add_4:
5968 case Builtin::BI__sync_fetch_and_add_8:
5969 case Builtin::BI__sync_fetch_and_add_16:
5970 BuiltinIndex = 0;
5971 break;
5972
5973 case Builtin::BI__sync_fetch_and_sub:
5974 case Builtin::BI__sync_fetch_and_sub_1:
5975 case Builtin::BI__sync_fetch_and_sub_2:
5976 case Builtin::BI__sync_fetch_and_sub_4:
5977 case Builtin::BI__sync_fetch_and_sub_8:
5978 case Builtin::BI__sync_fetch_and_sub_16:
5979 BuiltinIndex = 1;
5980 break;
5981
5982 case Builtin::BI__sync_fetch_and_or:
5983 case Builtin::BI__sync_fetch_and_or_1:
5984 case Builtin::BI__sync_fetch_and_or_2:
5985 case Builtin::BI__sync_fetch_and_or_4:
5986 case Builtin::BI__sync_fetch_and_or_8:
5987 case Builtin::BI__sync_fetch_and_or_16:
5988 BuiltinIndex = 2;
5989 break;
5990
5991 case Builtin::BI__sync_fetch_and_and:
5992 case Builtin::BI__sync_fetch_and_and_1:
5993 case Builtin::BI__sync_fetch_and_and_2:
5994 case Builtin::BI__sync_fetch_and_and_4:
5995 case Builtin::BI__sync_fetch_and_and_8:
5996 case Builtin::BI__sync_fetch_and_and_16:
5997 BuiltinIndex = 3;
5998 break;
5999
6000 case Builtin::BI__sync_fetch_and_xor:
6001 case Builtin::BI__sync_fetch_and_xor_1:
6002 case Builtin::BI__sync_fetch_and_xor_2:
6003 case Builtin::BI__sync_fetch_and_xor_4:
6004 case Builtin::BI__sync_fetch_and_xor_8:
6005 case Builtin::BI__sync_fetch_and_xor_16:
6006 BuiltinIndex = 4;
6007 break;
6008
6009 case Builtin::BI__sync_fetch_and_nand:
6010 case Builtin::BI__sync_fetch_and_nand_1:
6011 case Builtin::BI__sync_fetch_and_nand_2:
6012 case Builtin::BI__sync_fetch_and_nand_4:
6013 case Builtin::BI__sync_fetch_and_nand_8:
6014 case Builtin::BI__sync_fetch_and_nand_16:
6015 BuiltinIndex = 5;
6016 WarnAboutSemanticsChange = true;
6017 break;
6018
6019 case Builtin::BI__sync_add_and_fetch:
6020 case Builtin::BI__sync_add_and_fetch_1:
6021 case Builtin::BI__sync_add_and_fetch_2:
6022 case Builtin::BI__sync_add_and_fetch_4:
6023 case Builtin::BI__sync_add_and_fetch_8:
6024 case Builtin::BI__sync_add_and_fetch_16:
6025 BuiltinIndex = 6;
6026 break;
6027
6028 case Builtin::BI__sync_sub_and_fetch:
6029 case Builtin::BI__sync_sub_and_fetch_1:
6030 case Builtin::BI__sync_sub_and_fetch_2:
6031 case Builtin::BI__sync_sub_and_fetch_4:
6032 case Builtin::BI__sync_sub_and_fetch_8:
6033 case Builtin::BI__sync_sub_and_fetch_16:
6034 BuiltinIndex = 7;
6035 break;
6036
6037 case Builtin::BI__sync_and_and_fetch:
6038 case Builtin::BI__sync_and_and_fetch_1:
6039 case Builtin::BI__sync_and_and_fetch_2:
6040 case Builtin::BI__sync_and_and_fetch_4:
6041 case Builtin::BI__sync_and_and_fetch_8:
6042 case Builtin::BI__sync_and_and_fetch_16:
6043 BuiltinIndex = 8;
6044 break;
6045
6046 case Builtin::BI__sync_or_and_fetch:
6047 case Builtin::BI__sync_or_and_fetch_1:
6048 case Builtin::BI__sync_or_and_fetch_2:
6049 case Builtin::BI__sync_or_and_fetch_4:
6050 case Builtin::BI__sync_or_and_fetch_8:
6051 case Builtin::BI__sync_or_and_fetch_16:
6052 BuiltinIndex = 9;
6053 break;
6054
6055 case Builtin::BI__sync_xor_and_fetch:
6056 case Builtin::BI__sync_xor_and_fetch_1:
6057 case Builtin::BI__sync_xor_and_fetch_2:
6058 case Builtin::BI__sync_xor_and_fetch_4:
6059 case Builtin::BI__sync_xor_and_fetch_8:
6060 case Builtin::BI__sync_xor_and_fetch_16:
6061 BuiltinIndex = 10;
6062 break;
6063
6064 case Builtin::BI__sync_nand_and_fetch:
6065 case Builtin::BI__sync_nand_and_fetch_1:
6066 case Builtin::BI__sync_nand_and_fetch_2:
6067 case Builtin::BI__sync_nand_and_fetch_4:
6068 case Builtin::BI__sync_nand_and_fetch_8:
6069 case Builtin::BI__sync_nand_and_fetch_16:
6070 BuiltinIndex = 11;
6071 WarnAboutSemanticsChange = true;
6072 break;
6073
6074 case Builtin::BI__sync_val_compare_and_swap:
6075 case Builtin::BI__sync_val_compare_and_swap_1:
6076 case Builtin::BI__sync_val_compare_and_swap_2:
6077 case Builtin::BI__sync_val_compare_and_swap_4:
6078 case Builtin::BI__sync_val_compare_and_swap_8:
6079 case Builtin::BI__sync_val_compare_and_swap_16:
6080 BuiltinIndex = 12;
6081 NumFixed = 2;
6082 break;
6083
6084 case Builtin::BI__sync_bool_compare_and_swap:
6085 case Builtin::BI__sync_bool_compare_and_swap_1:
6086 case Builtin::BI__sync_bool_compare_and_swap_2:
6087 case Builtin::BI__sync_bool_compare_and_swap_4:
6088 case Builtin::BI__sync_bool_compare_and_swap_8:
6089 case Builtin::BI__sync_bool_compare_and_swap_16:
6090 BuiltinIndex = 13;
6091 NumFixed = 2;
6092 ResultType = Context.BoolTy;
6093 break;
6094
6095 case Builtin::BI__sync_lock_test_and_set:
6096 case Builtin::BI__sync_lock_test_and_set_1:
6097 case Builtin::BI__sync_lock_test_and_set_2:
6098 case Builtin::BI__sync_lock_test_and_set_4:
6099 case Builtin::BI__sync_lock_test_and_set_8:
6100 case Builtin::BI__sync_lock_test_and_set_16:
6101 BuiltinIndex = 14;
6102 break;
6103
6104 case Builtin::BI__sync_lock_release:
6105 case Builtin::BI__sync_lock_release_1:
6106 case Builtin::BI__sync_lock_release_2:
6107 case Builtin::BI__sync_lock_release_4:
6108 case Builtin::BI__sync_lock_release_8:
6109 case Builtin::BI__sync_lock_release_16:
6110 BuiltinIndex = 15;
6111 NumFixed = 0;
6112 ResultType = Context.VoidTy;
6113 break;
6114
6115 case Builtin::BI__sync_swap:
6116 case Builtin::BI__sync_swap_1:
6117 case Builtin::BI__sync_swap_2:
6118 case Builtin::BI__sync_swap_4:
6119 case Builtin::BI__sync_swap_8:
6120 case Builtin::BI__sync_swap_16:
6121 BuiltinIndex = 16;
6122 break;
6123 }
6124
6125 // Now that we know how many fixed arguments we expect, first check that we
6126 // have at least that many.
6127 if (TheCall->getNumArgs() < 1+NumFixed) {
6128 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6129 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
6130 << Callee->getSourceRange();
6131 return ExprError();
6132 }
6133
6134 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6135 << Callee->getSourceRange();
6136
6137 if (WarnAboutSemanticsChange) {
6138 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6139 << Callee->getSourceRange();
6140 }
6141
6142 // Get the decl for the concrete builtin from this, we can tell what the
6143 // concrete integer type we should convert to is.
6144 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6145 std::string NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6146 FunctionDecl *NewBuiltinDecl;
6147 if (NewBuiltinID == BuiltinID)
6148 NewBuiltinDecl = FDecl;
6149 else {
6150 // Perform builtin lookup to avoid redeclaring it.
6151 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6152 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6153 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6154 assert(Res.getFoundDecl());
6155 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6156 if (!NewBuiltinDecl)
6157 return ExprError();
6158 }
6159
6160 // The first argument --- the pointer --- has a fixed type; we
6161 // deduce the types of the rest of the arguments accordingly. Walk
6162 // the remaining arguments, converting them to the deduced value type.
6163 for (unsigned i = 0; i != NumFixed; ++i) {
6164 ExprResult Arg = TheCall->getArg(i+1);
6165
6166 // GCC does an implicit conversion to the pointer or integer ValType. This
6167 // can fail in some cases (1i -> int**), check for this error case now.
6168 // Initialize the argument.
6169 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6170 ValType, /*consume*/ false);
6171 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6172 if (Arg.isInvalid())
6173 return ExprError();
6174
6175 // Okay, we have something that *can* be converted to the right type. Check
6176 // to see if there is a potentially weird extension going on here. This can
6177 // happen when you do an atomic operation on something like an char* and
6178 // pass in 42. The 42 gets converted to char. This is even more strange
6179 // for things like 45.123 -> char, etc.
6180 // FIXME: Do this check.
6181 TheCall->setArg(i+1, Arg.get());
6182 }
6183
6184 // Create a new DeclRefExpr to refer to the new decl.
6185 DeclRefExpr *NewDRE = DeclRefExpr::Create(
6186 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6187 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6188 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6189
6190 // Set the callee in the CallExpr.
6191 // FIXME: This loses syntactic information.
6192 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6193 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6194 CK_BuiltinFnToFnPtr);
6195 TheCall->setCallee(PromotedCall.get());
6196
6197 // Change the result type of the call to match the original value type. This
6198 // is arbitrary, but the codegen for these builtins ins design to handle it
6199 // gracefully.
6200 TheCall->setType(ResultType);
6201
6202 // Prohibit problematic uses of bit-precise integer types with atomic
6203 // builtins. The arguments would have already been converted to the first
6204 // argument's type, so only need to check the first argument.
6205 const auto *BitIntValType = ValType->getAs<BitIntType>();
6206 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6207 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6208 return ExprError();
6209 }
6210
6211 return TheCallResult;
6212}
6213
6214ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6215 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6216 DeclRefExpr *DRE =
6218 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6219 unsigned BuiltinID = FDecl->getBuiltinID();
6220 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6221 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6222 "Unexpected nontemporal load/store builtin!");
6223 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6224 unsigned numArgs = isStore ? 2 : 1;
6225
6226 // Ensure that we have the proper number of arguments.
6227 if (checkArgCount(TheCall, numArgs))
6228 return ExprError();
6229
6230 // Inspect the last argument of the nontemporal builtin. This should always
6231 // be a pointer type, from which we imply the type of the memory access.
6232 // Because it is a pointer type, we don't have to worry about any implicit
6233 // casts here.
6234 Expr *PointerArg = TheCall->getArg(numArgs - 1);
6235 ExprResult PointerArgResult =
6237
6238 if (PointerArgResult.isInvalid())
6239 return ExprError();
6240 PointerArg = PointerArgResult.get();
6241 TheCall->setArg(numArgs - 1, PointerArg);
6242
6243 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6244 if (!pointerType) {
6245 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6246 << PointerArg->getType() << PointerArg->getSourceRange();
6247 return ExprError();
6248 }
6249
6250 QualType ValType = pointerType->getPointeeType();
6251
6252 // Strip any qualifiers off ValType.
6253 ValType = ValType.getUnqualifiedType();
6254 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6255 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6256 !ValType->isVectorType()) {
6257 Diag(DRE->getBeginLoc(),
6258 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6259 << PointerArg->getType() << PointerArg->getSourceRange();
6260 return ExprError();
6261 }
6262
6263 if (!isStore) {
6264 TheCall->setType(ValType);
6265 return TheCallResult;
6266 }
6267
6268 ExprResult ValArg = TheCall->getArg(0);
6269 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6270 Context, ValType, /*consume*/ false);
6271 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6272 if (ValArg.isInvalid())
6273 return ExprError();
6274
6275 TheCall->setArg(0, ValArg.get());
6276 TheCall->setType(Context.VoidTy);
6277 return TheCallResult;
6278}
6279
6280/// CheckObjCString - Checks that the format string argument to the os_log()
6281/// and os_trace() functions is correct, and converts it to const char *.
6282ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6283 Arg = Arg->IgnoreParenCasts();
6284 auto *Literal = dyn_cast<StringLiteral>(Arg);
6285 if (!Literal) {
6286 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6287 Literal = ObjcLiteral->getString();
6288 }
6289 }
6290
6291 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
6292 return ExprError(
6293 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6294 << Arg->getSourceRange());
6295 }
6296
6297 ExprResult Result(Literal);
6298 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6299 InitializedEntity Entity =
6301 Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6302 return Result;
6303}
6304
6305/// Check that the user is calling the appropriate va_start builtin for the
6306/// target and calling convention.
6307static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6308 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6309 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6310 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6311 TT.getArch() == llvm::Triple::aarch64_32);
6312 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
6313 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6314 if (IsX64 || IsAArch64) {
6315 CallingConv CC = CC_C;
6316 if (const FunctionDecl *FD = S.getCurFunctionDecl())
6317 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6318 if (IsMSVAStart) {
6319 // Don't allow this in System V ABI functions.
6320 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
6321 return S.Diag(Fn->getBeginLoc(),
6322 diag::err_ms_va_start_used_in_sysv_function);
6323 } else {
6324 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6325 // On x64 Windows, don't allow this in System V ABI functions.
6326 // (Yes, that means there's no corresponding way to support variadic
6327 // System V ABI functions on Windows.)
6328 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
6329 (!IsWindowsOrUEFI && CC == CC_Win64))
6330 return S.Diag(Fn->getBeginLoc(),
6331 diag::err_va_start_used_in_wrong_abi_function)
6332 << !IsWindowsOrUEFI;
6333 }
6334 return false;
6335 }
6336
6337 if (IsMSVAStart)
6338 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6339 return false;
6340}
6341
6343 ParmVarDecl **LastParam = nullptr) {
6344 // Determine whether the current function, block, or obj-c method is variadic
6345 // and get its parameter list.
6346 bool IsVariadic = false;
6348 DeclContext *Caller =
6350 if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6351 IsVariadic = Block->isVariadic();
6352 Params = Block->parameters();
6353 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6354 IsVariadic = FD->isVariadic();
6355 Params = FD->parameters();
6356 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6357 IsVariadic = MD->isVariadic();
6358 // FIXME: This isn't correct for methods (results in bogus warning).
6359 Params = MD->parameters();
6360 } else if (isa<CapturedDecl>(Caller)) {
6361 // We don't support va_start in a CapturedDecl.
6362 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6363 return true;
6364 } else {
6365 // This must be some other declcontext that parses exprs.
6366 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6367 return true;
6368 }
6369
6370 if (!IsVariadic) {
6371 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6372 return true;
6373 }
6374
6375 if (LastParam)
6376 *LastParam = Params.empty() ? nullptr : Params.back();
6377
6378 return false;
6379}
6380
6381bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6382 Expr *Fn = TheCall->getCallee();
6383 if (checkVAStartABI(*this, BuiltinID, Fn))
6384 return true;
6385
6386 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6387 // This builtin requires one argument (the va_list), allows two arguments,
6388 // but diagnoses more than two arguments. e.g.,
6389 // __builtin_c23_va_start(); // error
6390 // __builtin_c23_va_start(list); // ok
6391 // __builtin_c23_va_start(list, param); // ok
6392 // __builtin_c23_va_start(list, anything, anything); // error
6393 // This differs from the GCC behavior in that they accept the last case
6394 // with a warning, but it doesn't seem like a useful behavior to allow.
6395 if (checkArgCountRange(TheCall, 1, 2))
6396 return true;
6397 } else {
6398 // In C23 mode, va_start only needs one argument. However, the builtin still
6399 // requires two arguments (which matches the behavior of the GCC builtin),
6400 // <stdarg.h> passes `0` as the second argument in C23 mode.
6401 if (checkArgCount(TheCall, 2))
6402 return true;
6403 }
6404
6405 // Type-check the first argument normally.
6406 if (checkBuiltinArgument(*this, TheCall, 0))
6407 return true;
6408
6409 // Check that the current function is variadic, and get its last parameter.
6410 ParmVarDecl *LastParam;
6411 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6412 return true;
6413
6414 // Verify that the second argument to the builtin is the last non-variadic
6415 // argument of the current function or method. In C23 mode, if the call is
6416 // not to __builtin_c23_va_start, and the second argument is an integer
6417 // constant expression with value 0, then we don't bother with this check.
6418 // For __builtin_c23_va_start, we only perform the check for the second
6419 // argument being the last argument to the current function if there is a
6420 // second argument present.
6421 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6422 TheCall->getNumArgs() < 2) {
6423 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6424 return false;
6425 }
6426
6427 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6428 if (std::optional<llvm::APSInt> Val =
6430 Val && LangOpts.C23 && *Val == 0 &&
6431 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6432 Diag(TheCall->getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6433 return false;
6434 }
6435
6436 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6437 // next block.
6438 QualType Type;
6439 SourceLocation ParamLoc;
6440 bool IsCRegister = false;
6441 bool SecondArgIsLastNonVariadicArgument = false;
6442 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6443 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6444 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6445
6446 Type = PV->getType();
6447 ParamLoc = PV->getLocation();
6448 IsCRegister =
6449 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6450 }
6451 }
6452
6453 if (!SecondArgIsLastNonVariadicArgument)
6454 Diag(TheCall->getArg(1)->getBeginLoc(),
6455 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6456 else if (IsCRegister || Type->isReferenceType() ||
6457 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6458 // Promotable integers are UB, but enumerations need a bit of
6459 // extra checking to see what their promotable type actually is.
6460 if (!Context.isPromotableIntegerType(Type))
6461 return false;
6462 const auto *ED = Type->getAsEnumDecl();
6463 if (!ED)
6464 return true;
6465 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
6466 }()) {
6467 unsigned Reason = 0;
6468 if (Type->isReferenceType()) Reason = 1;
6469 else if (IsCRegister) Reason = 2;
6470 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6471 Diag(ParamLoc, diag::note_parameter_type) << Type;
6472 }
6473
6474 return false;
6475}
6476
6477bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6478 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6479 const LangOptions &LO = getLangOpts();
6480
6481 if (LO.CPlusPlus)
6482 return Arg->getType()
6484 .getTypePtr()
6485 ->getPointeeType()
6487
6488 // In C, allow aliasing through `char *`, this is required for AArch64 at
6489 // least.
6490 return true;
6491 };
6492
6493 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6494 // const char *named_addr);
6495
6496 Expr *Func = Call->getCallee();
6497
6498 if (Call->getNumArgs() < 3)
6499 return Diag(Call->getEndLoc(),
6500 diag::err_typecheck_call_too_few_args_at_least)
6501 << 0 /*function call*/ << 3 << Call->getNumArgs()
6502 << /*is non object*/ 0;
6503
6504 // Type-check the first argument normally.
6505 if (checkBuiltinArgument(*this, Call, 0))
6506 return true;
6507
6508 // Check that the current function is variadic.
6510 return true;
6511
6512 // __va_start on Windows does not validate the parameter qualifiers
6513
6514 const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6515 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6516
6517 const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6518 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6519
6520 const QualType &ConstCharPtrTy =
6521 Context.getPointerType(Context.CharTy.withConst());
6522 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6523 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6524 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6525 << 0 /* qualifier difference */
6526 << 3 /* parameter mismatch */
6527 << 2 << Arg1->getType() << ConstCharPtrTy;
6528
6529 const QualType SizeTy = Context.getSizeType();
6530 if (!Context.hasSameType(
6532 SizeTy))
6533 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6534 << Arg2->getType() << SizeTy << 1 /* different class */
6535 << 0 /* qualifier difference */
6536 << 3 /* parameter mismatch */
6537 << 3 << Arg2->getType() << SizeTy;
6538
6539 return false;
6540}
6541
6542bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6543 if (checkArgCount(TheCall, 2))
6544 return true;
6545
6546 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6547 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs())
6548 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6549 << 1 << 0 << TheCall->getSourceRange();
6550
6551 ExprResult OrigArg0 = TheCall->getArg(0);
6552 ExprResult OrigArg1 = TheCall->getArg(1);
6553
6554 // Do standard promotions between the two arguments, returning their common
6555 // type.
6556 QualType Res = UsualArithmeticConversions(
6557 OrigArg0, OrigArg1, TheCall->getExprLoc(), ArithConvKind::Comparison);
6558 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6559 return true;
6560
6561 // Make sure any conversions are pushed back into the call; this is
6562 // type safe since unordered compare builtins are declared as "_Bool
6563 // foo(...)".
6564 TheCall->setArg(0, OrigArg0.get());
6565 TheCall->setArg(1, OrigArg1.get());
6566
6567 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6568 return false;
6569
6570 // If the common type isn't a real floating type, then the arguments were
6571 // invalid for this operation.
6572 if (Res.isNull() || !Res->isRealFloatingType())
6573 return Diag(OrigArg0.get()->getBeginLoc(),
6574 diag::err_typecheck_call_invalid_ordered_compare)
6575 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6576 << SourceRange(OrigArg0.get()->getBeginLoc(),
6577 OrigArg1.get()->getEndLoc());
6578
6579 return false;
6580}
6581
6582bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6583 unsigned BuiltinID) {
6584 if (checkArgCount(TheCall, NumArgs))
6585 return true;
6586
6587 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts());
6588 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6589 BuiltinID == Builtin::BI__builtin_isinf ||
6590 BuiltinID == Builtin::BI__builtin_isinf_sign))
6591 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6592 << 0 << 0 << TheCall->getSourceRange();
6593
6594 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6595 BuiltinID == Builtin::BI__builtin_isunordered))
6596 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
6597 << 1 << 0 << TheCall->getSourceRange();
6598
6599 bool IsFPClass = NumArgs == 2;
6600
6601 // Find out position of floating-point argument.
6602 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6603
6604 // We can count on all parameters preceding the floating-point just being int.
6605 // Try all of those.
6606 for (unsigned i = 0; i < FPArgNo; ++i) {
6607 Expr *Arg = TheCall->getArg(i);
6608
6609 if (Arg->isTypeDependent())
6610 return false;
6611
6614
6615 if (Res.isInvalid())
6616 return true;
6617 TheCall->setArg(i, Res.get());
6618 }
6619
6620 Expr *OrigArg = TheCall->getArg(FPArgNo);
6621
6622 if (OrigArg->isTypeDependent())
6623 return false;
6624
6625 // We want to leave the type how it is, but do normal L->Rvalue conversions.
6627 if (!Res.isUsable())
6628 return true;
6629 OrigArg = Res.get();
6630
6631 TheCall->setArg(FPArgNo, OrigArg);
6632
6633 QualType VectorResultTy;
6634 QualType ElementTy = OrigArg->getType();
6635 // TODO: When all classification function are implemented with is_fpclass,
6636 // vector argument can be supported in all of them.
6637 if (ElementTy->isVectorType() && IsFPClass) {
6638 VectorResultTy = GetSignedVectorType(ElementTy);
6639 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6640 }
6641
6642 // This operation requires a non-_Complex floating-point number.
6643 if (!ElementTy->isRealFloatingType())
6644 return Diag(OrigArg->getBeginLoc(),
6645 diag::err_typecheck_call_invalid_unary_fp)
6646 << OrigArg->getType() << OrigArg->getSourceRange();
6647
6648 // __builtin_isfpclass has integer parameter that specify test mask. It is
6649 // passed in (...), so it should be analyzed completely here.
6650 if (IsFPClass) {
6651 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags))
6652 return true;
6653
6655 TheCall->getArg(NumArgs - 1), Context.IntTy, AssignmentAction::Passing);
6656 if (!MaskRes.isUsable())
6657 return true;
6658 TheCall->setArg(NumArgs - 1, MaskRes.get());
6659 }
6660
6661 // TODO: enable this code to all classification functions.
6662 if (IsFPClass) {
6663 QualType ResultTy;
6664 if (!VectorResultTy.isNull())
6665 ResultTy = VectorResultTy;
6666 else
6667 ResultTy = Context.IntTy;
6668 TheCall->setType(ResultTy);
6669 }
6670
6671 return false;
6672}
6673
6674bool Sema::BuiltinComplex(CallExpr *TheCall) {
6675 if (checkArgCount(TheCall, 2))
6676 return true;
6677
6678 bool Dependent = false;
6679 for (unsigned I = 0; I != 2; ++I) {
6680 Expr *Arg = TheCall->getArg(I);
6681 QualType T = Arg->getType();
6682 if (T->isDependentType()) {
6683 Dependent = true;
6684 continue;
6685 }
6686
6687 // Despite supporting _Complex int, GCC requires a real floating point type
6688 // for the operands of __builtin_complex.
6689 if (!T->isRealFloatingType()) {
6690 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6691 << Arg->getType() << Arg->getSourceRange();
6692 }
6693
6694 ExprResult Converted = DefaultLvalueConversion(Arg);
6695 if (Converted.isInvalid())
6696 return true;
6697 TheCall->setArg(I, Converted.get());
6698 }
6699
6700 if (Dependent) {
6701 TheCall->setType(Context.DependentTy);
6702 return false;
6703 }
6704
6705 Expr *Real = TheCall->getArg(0);
6706 Expr *Imag = TheCall->getArg(1);
6707 if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6708 return Diag(Real->getBeginLoc(),
6709 diag::err_typecheck_call_different_arg_types)
6710 << Real->getType() << Imag->getType()
6711 << Real->getSourceRange() << Imag->getSourceRange();
6712 }
6713
6714 TheCall->setType(Context.getComplexType(Real->getType()));
6715 return false;
6716}
6717
6718/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6719// This is declared to take (...), so we have to check everything.
6721 unsigned NumArgs = TheCall->getNumArgs();
6722 if (NumArgs < 2)
6723 return ExprError(Diag(TheCall->getEndLoc(),
6724 diag::err_typecheck_call_too_few_args_at_least)
6725 << 0 /*function call*/ << 2 << NumArgs
6726 << /*is non object*/ 0 << TheCall->getSourceRange());
6727
6728 // Determine which of the following types of shufflevector we're checking:
6729 // 1) unary, vector mask: (lhs, mask)
6730 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6731 QualType ResType = TheCall->getArg(0)->getType();
6732 unsigned NumElements = 0;
6733
6734 if (!TheCall->getArg(0)->isTypeDependent() &&
6735 !TheCall->getArg(1)->isTypeDependent()) {
6736 QualType LHSType = TheCall->getArg(0)->getType();
6737 QualType RHSType = TheCall->getArg(1)->getType();
6738
6739 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6740 return ExprError(
6741 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6742 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6743 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6744 TheCall->getArg(1)->getEndLoc()));
6745
6746 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6747 unsigned NumResElements = NumArgs - 2;
6748
6749 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6750 // with mask. If so, verify that RHS is an integer vector type with the
6751 // same number of elts as lhs.
6752 if (NumArgs == 2) {
6753 auto *RHSVecType = RHSType->castAs<VectorType>();
6754 if (RHSVecType->getElementType()->isBooleanType() ||
6755 !RHSVecType->getElementType()->isIntegerType()) {
6756 return ExprError(
6757 Diag(TheCall->getBeginLoc(), diag::err_builtin_invalid_arg_type)
6758 << /* Arg ordinal */ 2 << /*vector of*/ 4 << /*integer*/ 1
6759 << /*no fp*/ 0 << RHSType
6760 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6761 TheCall->getArg(1)->getEndLoc()));
6762 }
6763
6764 if (RHSVecType->getNumElements() != NumElements)
6765 return ExprError(Diag(TheCall->getBeginLoc(),
6766 diag::err_typecheck_vector_lengths_not_equal)
6767 << LHSType << RHSType << /*isMoreThanTwoArgs*/ false
6768 << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6769 TheCall->getArg(1)->getEndLoc()));
6770 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6771 return ExprError(Diag(TheCall->getBeginLoc(),
6772 diag::err_vec_builtin_incompatible_vector)
6773 << TheCall->getDirectCallee()
6774 << /*isMoreThanTwoArgs*/ false
6775 << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6776 TheCall->getArg(1)->getEndLoc()));
6777 } else if (NumElements != NumResElements) {
6778 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6779 ResType = ResType->isExtVectorType()
6780 ? Context.getExtVectorType(EltType, NumResElements)
6781 : Context.getVectorType(EltType, NumResElements,
6783 }
6784 }
6785
6786 for (unsigned I = 2; I != NumArgs; ++I) {
6787 Expr *Arg = TheCall->getArg(I);
6788 if (Arg->isTypeDependent() || Arg->isValueDependent())
6789 continue;
6790
6791 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Context);
6792 if (!Result)
6793 return ExprError(Diag(TheCall->getBeginLoc(),
6794 diag::err_shufflevector_nonconstant_argument)
6795 << Arg->getSourceRange());
6796
6797 // Allow -1 which will be translated to undef in the IR.
6798 if (Result->isSigned() && Result->isAllOnes())
6799 ;
6800 else if (Result->getActiveBits() > 64 ||
6801 Result->getZExtValue() >= NumElements * 2)
6802 return ExprError(Diag(TheCall->getBeginLoc(),
6803 diag::err_shufflevector_argument_too_large)
6804 << Arg->getSourceRange());
6805
6806 TheCall->setArg(I, ConstantExpr::Create(Context, Arg, APValue(*Result)));
6807 }
6808
6809 auto *Result = new (Context) ShuffleVectorExpr(
6810 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6811 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6812
6813 // All moved to Result.
6814 TheCall->shrinkNumArgs(0);
6815 return Result;
6816}
6817
6819 SourceLocation BuiltinLoc,
6820 SourceLocation RParenLoc) {
6823 QualType DstTy = TInfo->getType();
6824 QualType SrcTy = E->getType();
6825
6826 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6827 return ExprError(Diag(BuiltinLoc,
6828 diag::err_convertvector_non_vector)
6829 << E->getSourceRange());
6830 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6831 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6832 << "second"
6833 << "__builtin_convertvector");
6834
6835 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6836 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6837 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6838 if (SrcElts != DstElts)
6839 return ExprError(Diag(BuiltinLoc,
6840 diag::err_convertvector_incompatible_vector)
6841 << E->getSourceRange());
6842 }
6843
6844 return ConvertVectorExpr::Create(Context, E, TInfo, DstTy, VK, OK, BuiltinLoc,
6845 RParenLoc, CurFPFeatureOverrides());
6846}
6847
6848bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6849 unsigned NumArgs = TheCall->getNumArgs();
6850
6851 if (NumArgs > 3)
6852 return Diag(TheCall->getEndLoc(),
6853 diag::err_typecheck_call_too_many_args_at_most)
6854 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6855 << TheCall->getSourceRange();
6856
6857 // Argument 0 is checked for us and the remaining arguments must be
6858 // constant integers.
6859 for (unsigned i = 1; i != NumArgs; ++i) {
6860 if (convertArgumentToType(TheCall->getArgs()[i], Context.IntTy))
6861 return true;
6862 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6863 return true;
6864 }
6865
6866 return false;
6867}
6868
6869bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6870 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6871 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6872 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6873 if (checkArgCount(TheCall, 1))
6874 return true;
6875 Expr *Arg = TheCall->getArg(0);
6876 if (Arg->isInstantiationDependent())
6877 return false;
6878
6879 QualType ArgTy = Arg->getType();
6880 if (!ArgTy->hasFloatingRepresentation())
6881 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6882 << ArgTy;
6883 if (Arg->isLValue()) {
6884 ExprResult FirstArg = DefaultLvalueConversion(Arg);
6885 TheCall->setArg(0, FirstArg.get());
6886 }
6887 TheCall->setType(TheCall->getArg(0)->getType());
6888 return false;
6889}
6890
6891bool Sema::BuiltinAssume(CallExpr *TheCall) {
6892 Expr *Arg = TheCall->getArg(0);
6893 if (Arg->isInstantiationDependent()) return false;
6894
6895 if (Arg->HasSideEffects(Context))
6896 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6897 << Arg->getSourceRange()
6898 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6899
6900 return false;
6901}
6902
6903bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6904 // The alignment must be a constant integer.
6905 Expr *Arg = TheCall->getArg(1);
6906
6907 // We can't check the value of a dependent argument.
6908 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6909 if (const auto *UE =
6910 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6911 if (UE->getKind() == UETT_AlignOf ||
6912 UE->getKind() == UETT_PreferredAlignOf)
6913 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6914 << Arg->getSourceRange();
6915
6916 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6917
6918 if (!Result.isPowerOf2())
6919 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6920 << Arg->getSourceRange();
6921
6922 if (Result < Context.getCharWidth())
6923 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6924 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6925
6926 if (Result > std::numeric_limits<int32_t>::max())
6927 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6928 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6929 }
6930
6931 return false;
6932}
6933
6934bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6935 if (checkArgCountRange(TheCall, 2, 3))
6936 return true;
6937
6938 unsigned NumArgs = TheCall->getNumArgs();
6939 Expr *FirstArg = TheCall->getArg(0);
6940
6941 {
6942 ExprResult FirstArgResult =
6944 if (FirstArgResult.isInvalid())
6945 return true;
6946 if (!FirstArgResult.get()->getType()->isPointerType()) {
6947 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
6948 << TheCall->getSourceRange();
6949 return true;
6950 }
6951 TheCall->setArg(0, FirstArgResult.get());
6952 }
6953
6954 // The alignment must be a constant integer.
6955 Expr *SecondArg = TheCall->getArg(1);
6956
6957 // We can't check the value of a dependent argument.
6958 if (!SecondArg->isValueDependent()) {
6959 llvm::APSInt Result;
6960 if (BuiltinConstantArg(TheCall, 1, Result))
6961 return true;
6962
6963 if (!Result.isPowerOf2())
6964 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6965 << SecondArg->getSourceRange();
6966
6968 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6969 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6970
6971 TheCall->setArg(1,
6973 }
6974
6975 if (NumArgs > 2) {
6976 Expr *ThirdArg = TheCall->getArg(2);
6977 if (convertArgumentToType(ThirdArg, Context.getSizeType()))
6978 return true;
6979 TheCall->setArg(2, ThirdArg);
6980 }
6981
6982 return false;
6983}
6984
6985bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6986 unsigned BuiltinID =
6987 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6988 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6989
6990 unsigned NumArgs = TheCall->getNumArgs();
6991 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6992 if (NumArgs < NumRequiredArgs) {
6993 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6994 << 0 /* function call */ << NumRequiredArgs << NumArgs
6995 << /*is non object*/ 0 << TheCall->getSourceRange();
6996 }
6997 if (NumArgs >= NumRequiredArgs + 0x100) {
6998 return Diag(TheCall->getEndLoc(),
6999 diag::err_typecheck_call_too_many_args_at_most)
7000 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7001 << /*is non object*/ 0 << TheCall->getSourceRange();
7002 }
7003 unsigned i = 0;
7004
7005 // For formatting call, check buffer arg.
7006 if (!IsSizeCall) {
7007 ExprResult Arg(TheCall->getArg(i));
7008 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7009 Context, Context.VoidPtrTy, false);
7010 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7011 if (Arg.isInvalid())
7012 return true;
7013 TheCall->setArg(i, Arg.get());
7014 i++;
7015 }
7016
7017 // Check string literal arg.
7018 unsigned FormatIdx = i;
7019 {
7020 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7021 if (Arg.isInvalid())
7022 return true;
7023 TheCall->setArg(i, Arg.get());
7024 i++;
7025 }
7026
7027 // Make sure variadic args are scalar.
7028 unsigned FirstDataArg = i;
7029 while (i < NumArgs) {
7031 TheCall->getArg(i), VariadicCallType::Function, nullptr);
7032 if (Arg.isInvalid())
7033 return true;
7034 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7035 if (ArgSize.getQuantity() >= 0x100) {
7036 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7037 << i << (int)ArgSize.getQuantity() << 0xff
7038 << TheCall->getSourceRange();
7039 }
7040 TheCall->setArg(i, Arg.get());
7041 i++;
7042 }
7043
7044 // Check formatting specifiers. NOTE: We're only doing this for the non-size
7045 // call to avoid duplicate diagnostics.
7046 if (!IsSizeCall) {
7047 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7048 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7049 bool Success = CheckFormatArguments(
7050 Args, FAPK_Variadic, nullptr, FormatIdx, FirstDataArg,
7052 TheCall->getBeginLoc(), SourceRange(), CheckedVarArgs);
7053 if (!Success)
7054 return true;
7055 }
7056
7057 if (IsSizeCall) {
7058 TheCall->setType(Context.getSizeType());
7059 } else {
7060 TheCall->setType(Context.VoidPtrTy);
7061 }
7062 return false;
7063}
7064
7065bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
7066 llvm::APSInt &Result) {
7067 Expr *Arg = TheCall->getArg(ArgNum);
7068
7069 if (Arg->isTypeDependent() || Arg->isValueDependent())
7070 return false;
7071
7072 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Context);
7073 if (!R) {
7074 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7075 auto *FDecl = cast<FunctionDecl>(DRE->getDecl());
7076 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7077 << FDecl->getDeclName() << Arg->getSourceRange();
7078 }
7079 Result = *R;
7080
7081 return false;
7082}
7083
7084bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
7085 int High, bool RangeIsError) {
7087 return false;
7088 llvm::APSInt Result;
7089
7090 // We can't check the value of a dependent argument.
7091 Expr *Arg = TheCall->getArg(ArgNum);
7092 if (Arg->isTypeDependent() || Arg->isValueDependent())
7093 return false;
7094
7095 // Check constant-ness first.
7096 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7097 return true;
7098
7099 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7100 if (RangeIsError)
7101 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7102 << toString(Result, 10) << Low << High << Arg->getSourceRange();
7103 else
7104 // Defer the warning until we know if the code will be emitted so that
7105 // dead code can ignore this.
7106 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7107 PDiag(diag::warn_argument_invalid_range)
7108 << toString(Result, 10) << Low << High
7109 << Arg->getSourceRange());
7110 }
7111
7112 return false;
7113}
7114
7115bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
7116 unsigned Num) {
7117 llvm::APSInt Result;
7118
7119 // We can't check the value of a dependent argument.
7120 Expr *Arg = TheCall->getArg(ArgNum);
7121 if (Arg->isTypeDependent() || Arg->isValueDependent())
7122 return false;
7123
7124 // Check constant-ness first.
7125 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7126 return true;
7127
7128 if (Result.getSExtValue() % Num != 0)
7129 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7130 << Num << Arg->getSourceRange();
7131
7132 return false;
7133}
7134
7135bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
7136 llvm::APSInt Result;
7137
7138 // We can't check the value of a dependent argument.
7139 Expr *Arg = TheCall->getArg(ArgNum);
7140 if (Arg->isTypeDependent() || Arg->isValueDependent())
7141 return false;
7142
7143 // Check constant-ness first.
7144 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7145 return true;
7146
7147 if (Result.isPowerOf2())
7148 return false;
7149
7150 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7151 << Arg->getSourceRange();
7152}
7153
7154static bool IsShiftedByte(llvm::APSInt Value) {
7155 if (Value.isNegative())
7156 return false;
7157
7158 // Check if it's a shifted byte, by shifting it down
7159 while (true) {
7160 // If the value fits in the bottom byte, the check passes.
7161 if (Value < 0x100)
7162 return true;
7163
7164 // Otherwise, if the value has _any_ bits in the bottom byte, the check
7165 // fails.
7166 if ((Value & 0xFF) != 0)
7167 return false;
7168
7169 // If the bottom 8 bits are all 0, but something above that is nonzero,
7170 // then shifting the value right by 8 bits won't affect whether it's a
7171 // shifted byte or not. So do that, and go round again.
7172 Value >>= 8;
7173 }
7174}
7175
7176bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
7177 unsigned ArgBits) {
7178 llvm::APSInt Result;
7179
7180 // We can't check the value of a dependent argument.
7181 Expr *Arg = TheCall->getArg(ArgNum);
7182 if (Arg->isTypeDependent() || Arg->isValueDependent())
7183 return false;
7184
7185 // Check constant-ness first.
7186 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7187 return true;
7188
7189 // Truncate to the given size.
7190 Result = Result.getLoBits(ArgBits);
7191 Result.setIsUnsigned(true);
7192
7193 if (IsShiftedByte(Result))
7194 return false;
7195
7196 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7197 << Arg->getSourceRange();
7198}
7199
7201 unsigned ArgNum,
7202 unsigned ArgBits) {
7203 llvm::APSInt Result;
7204
7205 // We can't check the value of a dependent argument.
7206 Expr *Arg = TheCall->getArg(ArgNum);
7207 if (Arg->isTypeDependent() || Arg->isValueDependent())
7208 return false;
7209
7210 // Check constant-ness first.
7211 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7212 return true;
7213
7214 // Truncate to the given size.
7215 Result = Result.getLoBits(ArgBits);
7216 Result.setIsUnsigned(true);
7217
7218 // Check to see if it's in either of the required forms.
7219 if (IsShiftedByte(Result) ||
7220 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7221 return false;
7222
7223 return Diag(TheCall->getBeginLoc(),
7224 diag::err_argument_not_shifted_byte_or_xxff)
7225 << Arg->getSourceRange();
7226}
7227
7228bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
7229 if (!Context.getTargetInfo().hasSjLjLowering())
7230 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7231 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7232
7233 Expr *Arg = TheCall->getArg(1);
7234 llvm::APSInt Result;
7235
7236 // TODO: This is less than ideal. Overload this to take a value.
7237 if (BuiltinConstantArg(TheCall, 1, Result))
7238 return true;
7239
7240 if (Result != 1)
7241 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7242 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7243
7244 return false;
7245}
7246
7247bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
7248 if (!Context.getTargetInfo().hasSjLjLowering())
7249 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7250 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7251 return false;
7252}
7253
7254bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
7255 if (checkArgCount(TheCall, 1))
7256 return true;
7257
7258 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0));
7259 if (ArgRes.isInvalid())
7260 return true;
7261
7262 // For simplicity, we support only limited expressions for the argument.
7263 // Specifically a flexible array member or a pointer with counted_by:
7264 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
7265 // complex casting, which really shouldn't be a huge problem.
7266 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
7267 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
7268 return Diag(Arg->getBeginLoc(),
7269 diag::err_builtin_counted_by_ref_invalid_arg)
7270 << Arg->getSourceRange();
7271
7272 if (Arg->HasSideEffects(Context))
7273 return Diag(Arg->getBeginLoc(),
7274 diag::err_builtin_counted_by_ref_has_side_effects)
7275 << Arg->getSourceRange();
7276
7277 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) {
7278 const auto *CATy =
7279 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
7280
7281 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
7282 // Member has counted_by attribute - return pointer to count field
7283 const auto *MemberDecl = cast<FieldDecl>(ME->getMemberDecl());
7284 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
7285 if (CountFD->isBitField()) {
7286 Diag(ME->getBeginLoc(),
7287 diag::err_builtin_counted_by_ref_counter_field_is_bitfield)
7288 << Arg << CountFD << ME->getSourceRange();
7289 return Diag(CountFD->getBeginLoc(),
7290 diag::note_counted_by_counter_field)
7291 << CountFD << CountFD->getSourceRange();
7292 }
7293
7294 TheCall->setType(Context.getPointerType(CountFD->getType()));
7295 return false;
7296 }
7297 }
7298
7299 // FAMs and pointers without counted_by return void*
7300 QualType MemberTy = ME->getMemberDecl()->getType();
7301 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
7302 return Diag(Arg->getBeginLoc(),
7303 diag::err_builtin_counted_by_ref_invalid_arg)
7304 << Arg->getSourceRange();
7305 } else {
7306 return Diag(Arg->getBeginLoc(),
7307 diag::err_builtin_counted_by_ref_invalid_arg)
7308 << Arg->getSourceRange();
7309 }
7310
7311 TheCall->setType(Context.getPointerType(Context.VoidTy));
7312 return false;
7313}
7314
7315/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
7316/// It allows leaking and modification of bounds safety information.
7317bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
7319 const CallExpr *CE =
7320 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr;
7321 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
7322 return false;
7323
7324 switch (K) {
7327 Diag(E->getExprLoc(),
7328 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7329 << 0 << E->getSourceRange();
7330 break;
7332 Diag(E->getExprLoc(),
7333 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7334 << 1 << E->getSourceRange();
7335 break;
7337 Diag(E->getExprLoc(),
7338 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7339 << 2 << E->getSourceRange();
7340 break;
7342 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7343 << 0 << E->getSourceRange();
7344 break;
7346 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7347 << 1 << E->getSourceRange();
7348 break;
7349 }
7350
7351 return true;
7352}
7353
7354namespace {
7355
7356class UncoveredArgHandler {
7357 enum { Unknown = -1, AllCovered = -2 };
7358
7359 signed FirstUncoveredArg = Unknown;
7360 SmallVector<const Expr *, 4> DiagnosticExprs;
7361
7362public:
7363 UncoveredArgHandler() = default;
7364
7365 bool hasUncoveredArg() const {
7366 return (FirstUncoveredArg >= 0);
7367 }
7368
7369 unsigned getUncoveredArg() const {
7370 assert(hasUncoveredArg() && "no uncovered argument");
7371 return FirstUncoveredArg;
7372 }
7373
7374 void setAllCovered() {
7375 // A string has been found with all arguments covered, so clear out
7376 // the diagnostics.
7377 DiagnosticExprs.clear();
7378 FirstUncoveredArg = AllCovered;
7379 }
7380
7381 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7382 assert(NewFirstUncoveredArg >= 0 && "Outside range");
7383
7384 // Don't update if a previous string covers all arguments.
7385 if (FirstUncoveredArg == AllCovered)
7386 return;
7387
7388 // UncoveredArgHandler tracks the highest uncovered argument index
7389 // and with it all the strings that match this index.
7390 if (NewFirstUncoveredArg == FirstUncoveredArg)
7391 DiagnosticExprs.push_back(StrExpr);
7392 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7393 DiagnosticExprs.clear();
7394 DiagnosticExprs.push_back(StrExpr);
7395 FirstUncoveredArg = NewFirstUncoveredArg;
7396 }
7397 }
7398
7399 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7400};
7401
7402enum StringLiteralCheckType {
7403 SLCT_NotALiteral,
7404 SLCT_UncheckedLiteral,
7405 SLCT_CheckedLiteral
7406};
7407
7408} // namespace
7409
7410static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7411 BinaryOperatorKind BinOpKind,
7412 bool AddendIsRight) {
7413 unsigned BitWidth = Offset.getBitWidth();
7414 unsigned AddendBitWidth = Addend.getBitWidth();
7415 // There might be negative interim results.
7416 if (Addend.isUnsigned()) {
7417 Addend = Addend.zext(++AddendBitWidth);
7418 Addend.setIsSigned(true);
7419 }
7420 // Adjust the bit width of the APSInts.
7421 if (AddendBitWidth > BitWidth) {
7422 Offset = Offset.sext(AddendBitWidth);
7423 BitWidth = AddendBitWidth;
7424 } else if (BitWidth > AddendBitWidth) {
7425 Addend = Addend.sext(BitWidth);
7426 }
7427
7428 bool Ov = false;
7429 llvm::APSInt ResOffset = Offset;
7430 if (BinOpKind == BO_Add)
7431 ResOffset = Offset.sadd_ov(Addend, Ov);
7432 else {
7433 assert(AddendIsRight && BinOpKind == BO_Sub &&
7434 "operator must be add or sub with addend on the right");
7435 ResOffset = Offset.ssub_ov(Addend, Ov);
7436 }
7437
7438 // We add an offset to a pointer here so we should support an offset as big as
7439 // possible.
7440 if (Ov) {
7441 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7442 "index (intermediate) result too big");
7443 Offset = Offset.sext(2 * BitWidth);
7444 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7445 return;
7446 }
7447
7448 Offset = std::move(ResOffset);
7449}
7450
7451namespace {
7452
7453// This is a wrapper class around StringLiteral to support offsetted string
7454// literals as format strings. It takes the offset into account when returning
7455// the string and its length or the source locations to display notes correctly.
7456class FormatStringLiteral {
7457 const StringLiteral *FExpr;
7458 int64_t Offset;
7459
7460public:
7461 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7462 : FExpr(fexpr), Offset(Offset) {}
7463
7464 const StringLiteral *getFormatString() const { return FExpr; }
7465
7466 StringRef getString() const { return FExpr->getString().drop_front(Offset); }
7467
7468 unsigned getByteLength() const {
7469 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7470 }
7471
7472 unsigned getLength() const { return FExpr->getLength() - Offset; }
7473 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7474
7475 StringLiteralKind getKind() const { return FExpr->getKind(); }
7476
7477 QualType getType() const { return FExpr->getType(); }
7478
7479 bool isAscii() const { return FExpr->isOrdinary(); }
7480 bool isWide() const { return FExpr->isWide(); }
7481 bool isUTF8() const { return FExpr->isUTF8(); }
7482 bool isUTF16() const { return FExpr->isUTF16(); }
7483 bool isUTF32() const { return FExpr->isUTF32(); }
7484 bool isPascal() const { return FExpr->isPascal(); }
7485
7486 SourceLocation getLocationOfByte(
7487 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7488 const TargetInfo &Target, unsigned *StartToken = nullptr,
7489 unsigned *StartTokenByteOffset = nullptr) const {
7490 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7491 StartToken, StartTokenByteOffset);
7492 }
7493
7494 SourceLocation getBeginLoc() const LLVM_READONLY {
7495 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7496 }
7497
7498 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7499};
7500
7501} // namespace
7502
7503static void CheckFormatString(
7504 Sema &S, const FormatStringLiteral *FExpr,
7505 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7507 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7508 bool inFunctionCall, VariadicCallType CallType,
7509 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7510 bool IgnoreStringsWithoutSpecifiers);
7511
7512static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7513 const Expr *E);
7514
7515// Determine if an expression is a string literal or constant string.
7516// If this function returns false on the arguments to a function expecting a
7517// format string, we will usually need to emit a warning.
7518// True string literals are then checked by CheckFormatString.
7519static StringLiteralCheckType
7520checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7521 const Expr *E, ArrayRef<const Expr *> Args,
7522 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7523 unsigned firstDataArg, FormatStringType Type,
7524 VariadicCallType CallType, bool InFunctionCall,
7525 llvm::SmallBitVector &CheckedVarArgs,
7526 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7527 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7528 bool IgnoreStringsWithoutSpecifiers = false) {
7530 return SLCT_NotALiteral;
7531tryAgain:
7532 assert(Offset.isSigned() && "invalid offset");
7533
7534 if (E->isTypeDependent() || E->isValueDependent())
7535 return SLCT_NotALiteral;
7536
7537 E = E->IgnoreParenCasts();
7538
7540 // Technically -Wformat-nonliteral does not warn about this case.
7541 // The behavior of printf and friends in this case is implementation
7542 // dependent. Ideally if the format string cannot be null then
7543 // it should have a 'nonnull' attribute in the function prototype.
7544 return SLCT_UncheckedLiteral;
7545
7546 switch (E->getStmtClass()) {
7547 case Stmt::InitListExprClass:
7548 // Handle expressions like {"foobar"}.
7549 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) {
7550 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7551 format_idx, firstDataArg, Type, CallType,
7552 /*InFunctionCall*/ false, CheckedVarArgs,
7553 UncoveredArg, Offset, CallerFormatParamIdx,
7554 IgnoreStringsWithoutSpecifiers);
7555 }
7556 return SLCT_NotALiteral;
7557 case Stmt::BinaryConditionalOperatorClass:
7558 case Stmt::ConditionalOperatorClass: {
7559 // The expression is a literal if both sub-expressions were, and it was
7560 // completely checked only if both sub-expressions were checked.
7563
7564 // Determine whether it is necessary to check both sub-expressions, for
7565 // example, because the condition expression is a constant that can be
7566 // evaluated at compile time.
7567 bool CheckLeft = true, CheckRight = true;
7568
7569 bool Cond;
7570 if (C->getCond()->EvaluateAsBooleanCondition(
7571 Cond, S.getASTContext(), S.isConstantEvaluatedContext())) {
7572 if (Cond)
7573 CheckRight = false;
7574 else
7575 CheckLeft = false;
7576 }
7577
7578 // We need to maintain the offsets for the right and the left hand side
7579 // separately to check if every possible indexed expression is a valid
7580 // string literal. They might have different offsets for different string
7581 // literals in the end.
7582 StringLiteralCheckType Left;
7583 if (!CheckLeft)
7584 Left = SLCT_UncheckedLiteral;
7585 else {
7586 Left = checkFormatStringExpr(S, ReferenceFormatString, C->getTrueExpr(),
7587 Args, APK, format_idx, firstDataArg, Type,
7588 CallType, InFunctionCall, CheckedVarArgs,
7589 UncoveredArg, Offset, CallerFormatParamIdx,
7590 IgnoreStringsWithoutSpecifiers);
7591 if (Left == SLCT_NotALiteral || !CheckRight) {
7592 return Left;
7593 }
7594 }
7595
7596 StringLiteralCheckType Right = checkFormatStringExpr(
7597 S, ReferenceFormatString, C->getFalseExpr(), Args, APK, format_idx,
7598 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7599 UncoveredArg, Offset, CallerFormatParamIdx,
7600 IgnoreStringsWithoutSpecifiers);
7601
7602 return (CheckLeft && Left < Right) ? Left : Right;
7603 }
7604
7605 case Stmt::ImplicitCastExprClass:
7606 E = cast<ImplicitCastExpr>(E)->getSubExpr();
7607 goto tryAgain;
7608
7609 case Stmt::OpaqueValueExprClass:
7610 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7611 E = src;
7612 goto tryAgain;
7613 }
7614 return SLCT_NotALiteral;
7615
7616 case Stmt::PredefinedExprClass:
7617 // While __func__, etc., are technically not string literals, they
7618 // cannot contain format specifiers and thus are not a security
7619 // liability.
7620 return SLCT_UncheckedLiteral;
7621
7622 case Stmt::DeclRefExprClass: {
7623 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7624
7625 // As an exception, do not flag errors for variables binding to
7626 // const string literals.
7627 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7628 bool isConstant = false;
7629 QualType T = DR->getType();
7630
7631 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7632 isConstant = AT->getElementType().isConstant(S.Context);
7633 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7634 isConstant = T.isConstant(S.Context) &&
7635 PT->getPointeeType().isConstant(S.Context);
7636 } else if (T->isObjCObjectPointerType()) {
7637 // In ObjC, there is usually no "const ObjectPointer" type,
7638 // so don't check if the pointee type is constant.
7639 isConstant = T.isConstant(S.Context);
7640 }
7641
7642 if (isConstant) {
7643 if (const Expr *Init = VD->getAnyInitializer()) {
7644 // Look through initializers like const char c[] = { "foo" }
7645 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7646 if (InitList->isStringLiteralInit())
7647 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7648 }
7649 return checkFormatStringExpr(
7650 S, ReferenceFormatString, Init, Args, APK, format_idx,
7651 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7652 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7653 }
7654 }
7655
7656 // When the format argument is an argument of this function, and this
7657 // function also has the format attribute, there are several interactions
7658 // for which there shouldn't be a warning. For instance, when calling
7659 // v*printf from a function that has the printf format attribute, we
7660 // should not emit a warning about using `fmt`, even though it's not
7661 // constant, because the arguments have already been checked for the
7662 // caller of `logmessage`:
7663 //
7664 // __attribute__((format(printf, 1, 2)))
7665 // void logmessage(char const *fmt, ...) {
7666 // va_list ap;
7667 // va_start(ap, fmt);
7668 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7669 // ...
7670 // }
7671 //
7672 // Another interaction that we need to support is using a format string
7673 // specified by the format_matches attribute:
7674 //
7675 // __attribute__((format_matches(printf, 1, "%s %d")))
7676 // void logmessage(char const *fmt, const char *a, int b) {
7677 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7678 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7679 // ...
7680 // }
7681 //
7682 // Yet another interaction that we need to support is calling a variadic
7683 // format function from a format function that has fixed arguments. For
7684 // instance:
7685 //
7686 // __attribute__((format(printf, 1, 2)))
7687 // void logstring(char const *fmt, char const *str) {
7688 // printf(fmt, str); /* do not emit a warning about "fmt" */
7689 // }
7690 //
7691 // Same (and perhaps more relatably) for the variadic template case:
7692 //
7693 // template<typename... Args>
7694 // __attribute__((format(printf, 1, 2)))
7695 // void log(const char *fmt, Args&&... args) {
7696 // printf(fmt, forward<Args>(args)...);
7697 // /* do not emit a warning about "fmt" */
7698 // }
7699 //
7700 // Due to implementation difficulty, we only check the format, not the
7701 // format arguments, in all cases.
7702 //
7703 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
7704 if (CallerFormatParamIdx)
7705 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7706 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
7707 for (const auto *PVFormatMatches :
7708 D->specific_attrs<FormatMatchesAttr>()) {
7709 Sema::FormatStringInfo CalleeFSI;
7710 if (!Sema::getFormatStringInfo(D, PVFormatMatches->getFormatIdx(),
7711 0, &CalleeFSI))
7712 continue;
7713 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7714 // If using the wrong type of format string, emit a diagnostic
7715 // here and stop checking to avoid irrelevant diagnostics.
7716 if (Type != S.GetFormatStringType(PVFormatMatches)) {
7717 S.Diag(Args[format_idx]->getBeginLoc(),
7718 diag::warn_format_string_type_incompatible)
7719 << PVFormatMatches->getType()->getName()
7721 if (!InFunctionCall) {
7722 S.Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
7723 diag::note_format_string_defined);
7724 }
7725 return SLCT_UncheckedLiteral;
7726 }
7727 return checkFormatStringExpr(
7728 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
7729 Args, APK, format_idx, firstDataArg, Type, CallType,
7730 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7731 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7732 }
7733 }
7734
7735 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7736 Sema::FormatStringInfo CallerFSI;
7737 if (!Sema::getFormatStringInfo(D, PVFormat->getFormatIdx(),
7738 PVFormat->getFirstArg(), &CallerFSI))
7739 continue;
7740 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7741 // We also check if the formats are compatible.
7742 // We can't pass a 'scanf' string to a 'printf' function.
7743 if (Type != S.GetFormatStringType(PVFormat)) {
7744 S.Diag(Args[format_idx]->getBeginLoc(),
7745 diag::warn_format_string_type_incompatible)
7746 << PVFormat->getType()->getName()
7748 if (!InFunctionCall) {
7749 S.Diag(E->getBeginLoc(), diag::note_format_string_defined);
7750 }
7751 return SLCT_UncheckedLiteral;
7752 }
7753 // Lastly, check that argument passing kinds transition in a
7754 // way that makes sense:
7755 // from a caller with FAPK_VAList, allow FAPK_VAList
7756 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7757 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7758 // from a caller with FAPK_Variadic, allow FAPK_VAList
7759 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) {
7764 return SLCT_UncheckedLiteral;
7765 }
7766 }
7767 }
7768 }
7769 }
7770 }
7771
7772 return SLCT_NotALiteral;
7773 }
7774
7775 case Stmt::CallExprClass:
7776 case Stmt::CXXMemberCallExprClass: {
7777 const CallExpr *CE = cast<CallExpr>(E);
7778 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7779 bool IsFirst = true;
7780 StringLiteralCheckType CommonResult;
7781 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7782 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7783 StringLiteralCheckType Result = checkFormatStringExpr(
7784 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7785 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7786 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7787 if (IsFirst) {
7788 CommonResult = Result;
7789 IsFirst = false;
7790 }
7791 }
7792 if (!IsFirst)
7793 return CommonResult;
7794
7795 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7796 unsigned BuiltinID = FD->getBuiltinID();
7797 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7798 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7799 const Expr *Arg = CE->getArg(0);
7800 return checkFormatStringExpr(
7801 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7802 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7803 UncoveredArg, Offset, CallerFormatParamIdx,
7804 IgnoreStringsWithoutSpecifiers);
7805 }
7806 }
7807 }
7808 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E))
7809 return checkFormatStringExpr(S, ReferenceFormatString, SLE, Args, APK,
7810 format_idx, firstDataArg, Type, CallType,
7811 /*InFunctionCall*/ false, CheckedVarArgs,
7812 UncoveredArg, Offset, CallerFormatParamIdx,
7813 IgnoreStringsWithoutSpecifiers);
7814 return SLCT_NotALiteral;
7815 }
7816 case Stmt::ObjCMessageExprClass: {
7817 const auto *ME = cast<ObjCMessageExpr>(E);
7818 if (const auto *MD = ME->getMethodDecl()) {
7819 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7820 // As a special case heuristic, if we're using the method -[NSBundle
7821 // localizedStringForKey:value:table:], ignore any key strings that lack
7822 // format specifiers. The idea is that if the key doesn't have any
7823 // format specifiers then its probably just a key to map to the
7824 // localized strings. If it does have format specifiers though, then its
7825 // likely that the text of the key is the format string in the
7826 // programmer's language, and should be checked.
7827 const ObjCInterfaceDecl *IFace;
7828 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7829 IFace->getIdentifier()->isStr("NSBundle") &&
7830 MD->getSelector().isKeywordSelector(
7831 {"localizedStringForKey", "value", "table"})) {
7832 IgnoreStringsWithoutSpecifiers = true;
7833 }
7834
7835 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7836 return checkFormatStringExpr(
7837 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7838 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7839 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7840 }
7841 }
7842
7843 return SLCT_NotALiteral;
7844 }
7845 case Stmt::ObjCStringLiteralClass:
7846 case Stmt::StringLiteralClass: {
7847 const StringLiteral *StrE = nullptr;
7848
7849 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7850 StrE = ObjCFExpr->getString();
7851 else
7852 StrE = cast<StringLiteral>(E);
7853
7854 if (StrE) {
7855 if (Offset.isNegative() || Offset > StrE->getLength()) {
7856 // TODO: It would be better to have an explicit warning for out of
7857 // bounds literals.
7858 return SLCT_NotALiteral;
7859 }
7860 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7861 CheckFormatString(S, &FStr, ReferenceFormatString, E, Args, APK,
7862 format_idx, firstDataArg, Type, InFunctionCall,
7863 CallType, CheckedVarArgs, UncoveredArg,
7864 IgnoreStringsWithoutSpecifiers);
7865 return SLCT_CheckedLiteral;
7866 }
7867
7868 return SLCT_NotALiteral;
7869 }
7870 case Stmt::BinaryOperatorClass: {
7871 const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7872
7873 // A string literal + an int offset is still a string literal.
7874 if (BinOp->isAdditiveOp()) {
7875 Expr::EvalResult LResult, RResult;
7876
7877 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7878 LResult, S.Context, Expr::SE_NoSideEffects,
7880 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7881 RResult, S.Context, Expr::SE_NoSideEffects,
7883
7884 if (LIsInt != RIsInt) {
7885 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7886
7887 if (LIsInt) {
7888 if (BinOpKind == BO_Add) {
7889 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7890 E = BinOp->getRHS();
7891 goto tryAgain;
7892 }
7893 } else {
7894 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7895 E = BinOp->getLHS();
7896 goto tryAgain;
7897 }
7898 }
7899 }
7900
7901 return SLCT_NotALiteral;
7902 }
7903 case Stmt::UnaryOperatorClass: {
7904 const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7905 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7906 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7907 Expr::EvalResult IndexResult;
7908 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7911 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7912 /*RHS is int*/ true);
7913 E = ASE->getBase();
7914 goto tryAgain;
7915 }
7916 }
7917
7918 return SLCT_NotALiteral;
7919 }
7920
7921 default:
7922 return SLCT_NotALiteral;
7923 }
7924}
7925
7926// If this expression can be evaluated at compile-time,
7927// check if the result is a StringLiteral and return it
7928// otherwise return nullptr
7930 const Expr *E) {
7932 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) {
7933 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7934 if (isa_and_nonnull<StringLiteral>(LVE))
7935 return LVE;
7936 }
7937 return nullptr;
7938}
7939
7941 switch (FST) {
7943 return "scanf";
7945 return "printf";
7947 return "NSString";
7949 return "strftime";
7951 return "strfmon";
7953 return "kprintf";
7955 return "freebsd_kprintf";
7957 return "os_log";
7958 default:
7959 return "<unknown>";
7960 }
7961}
7962
7964 return llvm::StringSwitch<FormatStringType>(Flavor)
7965 .Cases({"gnu_scanf", "scanf"}, FormatStringType::Scanf)
7966 .Cases({"gnu_printf", "printf", "printf0", "syslog"},
7968 .Cases({"NSString", "CFString"}, FormatStringType::NSString)
7969 .Cases({"gnu_strftime", "strftime"}, FormatStringType::Strftime)
7970 .Cases({"gnu_strfmon", "strfmon"}, FormatStringType::Strfmon)
7971 .Cases({"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7973 .Case("freebsd_kprintf", FormatStringType::FreeBSDKPrintf)
7974 .Case("os_trace", FormatStringType::OSLog)
7975 .Case("os_log", FormatStringType::OSLog)
7976 .Default(FormatStringType::Unknown);
7977}
7978
7980 return GetFormatStringType(Format->getType()->getName());
7981}
7982
7983FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7984 return GetFormatStringType(Format->getType()->getName());
7985}
7986
7987bool Sema::CheckFormatArguments(const FormatAttr *Format,
7988 ArrayRef<const Expr *> Args, bool IsCXXMember,
7989 VariadicCallType CallType, SourceLocation Loc,
7990 SourceRange Range,
7991 llvm::SmallBitVector &CheckedVarArgs) {
7992 FormatStringInfo FSI;
7993 if (getFormatStringInfo(Format->getFormatIdx(), Format->getFirstArg(),
7994 IsCXXMember,
7995 CallType != VariadicCallType::DoesNotApply, &FSI))
7996 return CheckFormatArguments(
7997 Args, FSI.ArgPassingKind, nullptr, FSI.FormatIdx, FSI.FirstDataArg,
7998 GetFormatStringType(Format), CallType, Loc, Range, CheckedVarArgs);
7999 return false;
8000}
8001
8002bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
8003 ArrayRef<const Expr *> Args, bool IsCXXMember,
8004 VariadicCallType CallType, SourceLocation Loc,
8005 SourceRange Range,
8006 llvm::SmallBitVector &CheckedVarArgs) {
8007 FormatStringInfo FSI;
8008 if (getFormatStringInfo(Format->getFormatIdx(), 0, IsCXXMember, false,
8009 &FSI)) {
8010 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
8011 return CheckFormatArguments(Args, FSI.ArgPassingKind,
8012 Format->getFormatString(), FSI.FormatIdx,
8013 FSI.FirstDataArg, GetFormatStringType(Format),
8014 CallType, Loc, Range, CheckedVarArgs);
8015 }
8016 return false;
8017}
8018
8021 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
8022 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
8023 SourceLocation Loc) {
8024 if (S->getDiagnostics().isIgnored(diag::warn_missing_format_attribute, Loc))
8025 return false;
8026
8028 if (!isa<ObjCMethodDecl>(DC) && !isa<FunctionDecl>(DC) && !isa<BlockDecl>(DC))
8029 return false;
8030 Decl *Caller = cast<Decl>(DC)->getCanonicalDecl();
8031
8032 unsigned NumCallerParams = getFunctionOrMethodNumParams(Caller);
8033
8034 // Find the offset to convert between attribute and parameter indexes.
8035 unsigned CallerArgumentIndexOffset =
8036 hasImplicitObjectParameter(Caller) ? 2 : 1;
8037
8038 unsigned FirstArgumentIndex = -1;
8039 switch (APK) {
8042 // As an extension, clang allows the format attribute on non-variadic
8043 // functions.
8044 // Caller must have fixed arguments to pass them to a fixed or variadic
8045 // function. Try to match caller and callee arguments. If successful, then
8046 // emit a diag with the caller idx, otherwise we can't determine the callee
8047 // arguments.
8048 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
8049 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
8050 // There aren't enough arguments in the caller to pass to callee.
8051 return false;
8052 }
8053 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
8054 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
8055 const auto *Arg =
8056 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
8057 if (!Arg)
8058 return false;
8059 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
8060 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
8061 return false;
8062 }
8063 FirstArgumentIndex =
8064 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
8065 break;
8066 }
8068 // Caller arguments are either variadic or a va_list.
8069 FirstArgumentIndex = isFunctionOrMethodVariadic(Caller)
8070 ? (NumCallerParams + CallerArgumentIndexOffset)
8071 : 0;
8072 break;
8074 // The callee has a format_matches attribute. We will emit that instead.
8075 if (!ReferenceFormatString)
8076 return false;
8077 break;
8078 }
8079
8080 // Emit the diagnostic and fixit.
8081 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
8082 StringRef FormatTypeName = S->GetFormatStringTypeName(FormatType);
8083 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
8084 do {
8085 std::string Attr, Fixit;
8086 llvm::raw_string_ostream AttrOS(Attr);
8088 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
8089 << FirstArgumentIndex << ")";
8090 } else {
8091 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
8092 << ", \"";
8093 AttrOS.write_escaped(ReferenceFormatString->getString());
8094 AttrOS << "\")";
8095 }
8096 AttrOS.flush();
8097 auto DB = S->Diag(Loc, diag::warn_missing_format_attribute) << Attr;
8098 if (ND)
8099 DB << ND;
8100 else
8101 DB << "block";
8102
8103 // Blocks don't provide a correct end loc, so skip emitting a fixit.
8104 if (isa<BlockDecl>(Caller))
8105 break;
8106
8107 SourceLocation SL;
8108 llvm::raw_string_ostream IS(Fixit);
8109 // The attribute goes at the start of the declaration in C/C++ functions
8110 // and methods, but after the declaration for Objective-C methods.
8111 if (isa<ObjCMethodDecl>(Caller)) {
8112 IS << ' ';
8113 SL = Caller->getEndLoc();
8114 }
8115 const LangOptions &LO = S->getLangOpts();
8116 if (LO.C23 || LO.CPlusPlus11)
8117 IS << "[[gnu::" << Attr << "]]";
8118 else if (LO.ObjC || LO.GNUMode)
8119 IS << "__attribute__((" << Attr << "))";
8120 else
8121 break;
8122 if (!isa<ObjCMethodDecl>(Caller)) {
8123 IS << ' ';
8124 SL = Caller->getBeginLoc();
8125 }
8126 IS.flush();
8127
8128 DB << FixItHint::CreateInsertion(SL, Fixit);
8129 } while (false);
8130
8131 // Add implicit format or format_matches attribute.
8133 Caller->addAttr(FormatAttr::CreateImplicit(
8134 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
8135 FormatStringIndex, FirstArgumentIndex));
8136 } else {
8137 Caller->addAttr(FormatMatchesAttr::CreateImplicit(
8138 S->getASTContext(), &S->getASTContext().Idents.get(FormatTypeName),
8139 FormatStringIndex, ReferenceFormatString));
8140 }
8141
8142 {
8143 auto DB = S->Diag(Caller->getLocation(), diag::note_entity_declared_at);
8144 if (ND)
8145 DB << ND;
8146 else
8147 DB << "block";
8148 }
8149 return true;
8150}
8151
8152bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8154 StringLiteral *ReferenceFormatString,
8155 unsigned format_idx, unsigned firstDataArg,
8157 VariadicCallType CallType, SourceLocation Loc,
8158 SourceRange Range,
8159 llvm::SmallBitVector &CheckedVarArgs) {
8160 // CHECK: printf/scanf-like function is called with no format string.
8161 if (format_idx >= Args.size()) {
8162 Diag(Loc, diag::warn_missing_format_string) << Range;
8163 return false;
8164 }
8165
8166 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8167
8168 // CHECK: format string is not a string literal.
8169 //
8170 // Dynamically generated format strings are difficult to
8171 // automatically vet at compile time. Requiring that format strings
8172 // are string literals: (1) permits the checking of format strings by
8173 // the compiler and thereby (2) can practically remove the source of
8174 // many format string exploits.
8175
8176 // Format string can be either ObjC string (e.g. @"%d") or
8177 // C string (e.g. "%d")
8178 // ObjC string uses the same format specifiers as C string, so we can use
8179 // the same format string checking logic for both ObjC and C strings.
8180 UncoveredArgHandler UncoveredArg;
8181 std::optional<unsigned> CallerParamIdx;
8182 StringLiteralCheckType CT = checkFormatStringExpr(
8183 *this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
8184 firstDataArg, Type, CallType,
8185 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg,
8186 /*no string offset*/ llvm::APSInt(64, false) = 0, &CallerParamIdx);
8187
8188 // Generate a diagnostic where an uncovered argument is detected.
8189 if (UncoveredArg.hasUncoveredArg()) {
8190 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8191 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8192 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8193 }
8194
8195 if (CT != SLCT_NotALiteral)
8196 // Literal format string found, check done!
8197 return CT == SLCT_CheckedLiteral;
8198
8199 // Do not emit diag when the string param is a macro expansion and the
8200 // format is either NSString or CFString. This is a hack to prevent
8201 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8202 // which are usually used in place of NS and CF string literals.
8203 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8205 SourceMgr.isInSystemMacro(FormatLoc))
8206 return false;
8207
8208 if (CallerParamIdx && CheckMissingFormatAttribute(
8209 this, Args, APK, ReferenceFormatString, format_idx,
8210 firstDataArg, Type, *CallerParamIdx, Loc))
8211 return false;
8212
8213 // Strftime is particular as it always uses a single 'time' argument,
8214 // so it is safe to pass a non-literal string.
8216 return false;
8217
8218 // If there are no arguments specified, warn with -Wformat-security, otherwise
8219 // warn only with -Wformat-nonliteral.
8220 if (Args.size() == firstDataArg) {
8221 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8222 << OrigFormatExpr->getSourceRange();
8223 switch (Type) {
8224 default:
8225 break;
8229 Diag(FormatLoc, diag::note_format_security_fixit)
8230 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8231 break;
8233 Diag(FormatLoc, diag::note_format_security_fixit)
8234 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8235 break;
8236 }
8237 } else {
8238 Diag(FormatLoc, diag::warn_format_nonliteral)
8239 << OrigFormatExpr->getSourceRange();
8240 }
8241 return false;
8242}
8243
8244namespace {
8245
8246class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8247protected:
8248 Sema &S;
8249 const FormatStringLiteral *FExpr;
8250 const Expr *OrigFormatExpr;
8251 const FormatStringType FSType;
8252 const unsigned FirstDataArg;
8253 const unsigned NumDataArgs;
8254 const char *Beg; // Start of format string.
8255 const Sema::FormatArgumentPassingKind ArgPassingKind;
8256 ArrayRef<const Expr *> Args;
8257 unsigned FormatIdx;
8258 llvm::SmallBitVector CoveredArgs;
8259 bool usesPositionalArgs = false;
8260 bool atFirstArg = true;
8261 bool inFunctionCall;
8262 VariadicCallType CallType;
8263 llvm::SmallBitVector &CheckedVarArgs;
8264 UncoveredArgHandler &UncoveredArg;
8265
8266public:
8267 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8268 const Expr *origFormatExpr, const FormatStringType type,
8269 unsigned firstDataArg, unsigned numDataArgs,
8270 const char *beg, Sema::FormatArgumentPassingKind APK,
8271 ArrayRef<const Expr *> Args, unsigned formatIdx,
8272 bool inFunctionCall, VariadicCallType callType,
8273 llvm::SmallBitVector &CheckedVarArgs,
8274 UncoveredArgHandler &UncoveredArg)
8275 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8276 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8277 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
8278 inFunctionCall(inFunctionCall), CallType(callType),
8279 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8280 CoveredArgs.resize(numDataArgs);
8281 CoveredArgs.reset();
8282 }
8283
8284 bool HasFormatArguments() const {
8285 return ArgPassingKind == Sema::FAPK_Fixed ||
8286 ArgPassingKind == Sema::FAPK_Variadic;
8287 }
8288
8289 void DoneProcessing();
8290
8291 void HandleIncompleteSpecifier(const char *startSpecifier,
8292 unsigned specifierLen) override;
8293
8294 void HandleInvalidLengthModifier(
8295 const analyze_format_string::FormatSpecifier &FS,
8296 const analyze_format_string::ConversionSpecifier &CS,
8297 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
8298
8299 void HandleNonStandardLengthModifier(
8300 const analyze_format_string::FormatSpecifier &FS,
8301 const char *startSpecifier, unsigned specifierLen);
8302
8303 void HandleNonStandardConversionSpecifier(
8304 const analyze_format_string::ConversionSpecifier &CS,
8305 const char *startSpecifier, unsigned specifierLen);
8306
8307 void HandlePosition(const char *startPos, unsigned posLen) override;
8308
8309 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
8311
8312 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8313
8314 void HandleNullChar(const char *nullCharacter) override;
8315
8316 template <typename Range>
8317 static void
8318 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8319 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8320 bool IsStringLocation, Range StringRange,
8321 ArrayRef<FixItHint> Fixit = {});
8322
8323protected:
8324 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8325 const char *startSpec,
8326 unsigned specifierLen,
8327 const char *csStart, unsigned csLen);
8328
8329 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8330 const char *startSpec,
8331 unsigned specifierLen);
8332
8333 SourceRange getFormatStringRange();
8334 CharSourceRange getSpecifierRange(const char *startSpecifier,
8335 unsigned specifierLen);
8336 SourceLocation getLocationOfByte(const char *x);
8337
8338 const Expr *getDataArg(unsigned i) const;
8339
8340 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8341 const analyze_format_string::ConversionSpecifier &CS,
8342 const char *startSpecifier, unsigned specifierLen,
8343 unsigned argIndex);
8344
8345 bool CheckUnsupportedType(const analyze_format_string::ArgType &AT,
8346 const Expr *E, const char *startSpecifier,
8347 unsigned specifierLen);
8348
8349 template <typename Range>
8350 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8351 bool IsStringLocation, Range StringRange,
8352 ArrayRef<FixItHint> Fixit = {});
8353};
8354
8355} // namespace
8356
8357SourceRange CheckFormatHandler::getFormatStringRange() {
8358 return OrigFormatExpr->getSourceRange();
8359}
8360
8362CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
8363 unsigned specifierLen) {
8364 SourceLocation Start = getLocationOfByte(startSpecifier);
8365 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
8366
8367 // Advance the end SourceLocation by one due to half-open ranges.
8368 End = End.getLocWithOffset(1);
8369
8370 return CharSourceRange::getCharRange(Start, End);
8371}
8372
8373SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8374 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8376}
8377
8378void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8379 unsigned specifierLen) {
8380 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8381 getLocationOfByte(startSpecifier),
8382 /*IsStringLocation*/ true,
8383 getSpecifierRange(startSpecifier, specifierLen));
8384}
8385
8386bool CheckFormatHandler::CheckUnsupportedType(
8387 const analyze_format_string::ArgType &AT, const Expr *E,
8388 const char *StartSpecifier, unsigned SpecifierLen) {
8389 if (!AT.isUnsupported())
8390 return false;
8391
8392 EmitFormatDiagnostic(S.PDiag(diag::warn_format_unsupported_type)
8394 E->getExprLoc(), /*IsStringLocation=*/false,
8395 getSpecifierRange(StartSpecifier, SpecifierLen));
8396 return true;
8397}
8398
8399void CheckFormatHandler::HandleInvalidLengthModifier(
8402 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8403 using namespace analyze_format_string;
8404
8405 const LengthModifier &LM = FS.getLengthModifier();
8406 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8407
8408 // See if we know how to fix this length modifier.
8409 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8410 if (FixedLM) {
8411 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8412 getLocationOfByte(LM.getStart()),
8413 /*IsStringLocation*/ true,
8414 getSpecifierRange(startSpecifier, specifierLen));
8415
8416 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8417 << FixedLM->toString()
8418 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8419
8420 } else {
8421 FixItHint Hint;
8422 if (DiagID == diag::warn_format_nonsensical_length)
8423 Hint = FixItHint::CreateRemoval(LMRange);
8424
8425 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8426 getLocationOfByte(LM.getStart()),
8427 /*IsStringLocation*/ true,
8428 getSpecifierRange(startSpecifier, specifierLen), Hint);
8429 }
8430}
8431
8432void CheckFormatHandler::HandleNonStandardLengthModifier(
8434 const char *startSpecifier, unsigned specifierLen) {
8435 using namespace analyze_format_string;
8436
8437 const LengthModifier &LM = FS.getLengthModifier();
8438 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8439
8440 // See if we know how to fix this length modifier.
8441 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8442 if (FixedLM) {
8443 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8444 << LM.toString() << 0,
8445 getLocationOfByte(LM.getStart()),
8446 /*IsStringLocation*/ true,
8447 getSpecifierRange(startSpecifier, specifierLen));
8448
8449 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8450 << FixedLM->toString()
8451 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8452
8453 } else {
8454 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8455 << LM.toString() << 0,
8456 getLocationOfByte(LM.getStart()),
8457 /*IsStringLocation*/ true,
8458 getSpecifierRange(startSpecifier, specifierLen));
8459 }
8460}
8461
8462void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8464 const char *startSpecifier, unsigned specifierLen) {
8465 using namespace analyze_format_string;
8466
8467 // See if we know how to fix this conversion specifier.
8468 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8469 if (FixedCS) {
8470 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8471 << CS.toString() << /*conversion specifier*/ 1,
8472 getLocationOfByte(CS.getStart()),
8473 /*IsStringLocation*/ true,
8474 getSpecifierRange(startSpecifier, specifierLen));
8475
8476 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8477 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8478 << FixedCS->toString()
8479 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8480 } else {
8481 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8482 << CS.toString() << /*conversion specifier*/ 1,
8483 getLocationOfByte(CS.getStart()),
8484 /*IsStringLocation*/ true,
8485 getSpecifierRange(startSpecifier, specifierLen));
8486 }
8487}
8488
8489void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8490 if (!S.getDiagnostics().isIgnored(
8491 diag::warn_format_non_standard_positional_arg, SourceLocation()))
8492 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8493 getLocationOfByte(startPos),
8494 /*IsStringLocation*/ true,
8495 getSpecifierRange(startPos, posLen));
8496}
8497
8498void CheckFormatHandler::HandleInvalidPosition(
8499 const char *startSpecifier, unsigned specifierLen,
8501 if (!S.getDiagnostics().isIgnored(
8502 diag::warn_format_invalid_positional_specifier, SourceLocation()))
8503 EmitFormatDiagnostic(
8504 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8505 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true,
8506 getSpecifierRange(startSpecifier, specifierLen));
8507}
8508
8509void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8510 unsigned posLen) {
8511 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier,
8512 SourceLocation()))
8513 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8514 getLocationOfByte(startPos),
8515 /*IsStringLocation*/ true,
8516 getSpecifierRange(startPos, posLen));
8517}
8518
8519void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8520 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8521 // The presence of a null character is likely an error.
8522 EmitFormatDiagnostic(
8523 S.PDiag(diag::warn_printf_format_string_contains_null_char),
8524 getLocationOfByte(nullCharacter), /*IsStringLocation*/ true,
8525 getFormatStringRange());
8526 }
8527}
8528
8529// Note that this may return NULL if there was an error parsing or building
8530// one of the argument expressions.
8531const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8532 return Args[FirstDataArg + i];
8533}
8534
8535void CheckFormatHandler::DoneProcessing() {
8536 // Does the number of data arguments exceed the number of
8537 // format conversions in the format string?
8538 if (HasFormatArguments()) {
8539 // Find any arguments that weren't covered.
8540 CoveredArgs.flip();
8541 signed notCoveredArg = CoveredArgs.find_first();
8542 if (notCoveredArg >= 0) {
8543 assert((unsigned)notCoveredArg < NumDataArgs);
8544 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8545 } else {
8546 UncoveredArg.setAllCovered();
8547 }
8548 }
8549}
8550
8551void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8552 const Expr *ArgExpr) {
8553 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8554
8555 if (!ArgExpr)
8556 return;
8557
8558 SourceLocation Loc = ArgExpr->getBeginLoc();
8559
8560 if (S.getSourceManager().isInSystemMacro(Loc))
8561 return;
8562
8563 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8564 for (auto E : DiagnosticExprs)
8565 PDiag << E->getSourceRange();
8566
8567 CheckFormatHandler::EmitFormatDiagnostic(
8568 S, IsFunctionCall, DiagnosticExprs[0], PDiag, Loc,
8569 /*IsStringLocation*/ false, DiagnosticExprs[0]->getSourceRange());
8570}
8571
8572bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8573 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8574 unsigned specifierLen, const char *csStart, unsigned csLen) {
8575 bool keepGoing = true;
8576 if (argIndex < NumDataArgs) {
8577 // Consider the argument coverered, even though the specifier doesn't
8578 // make sense.
8579 CoveredArgs.set(argIndex);
8580 } else {
8581 // If argIndex exceeds the number of data arguments we
8582 // don't issue a warning because that is just a cascade of warnings (and
8583 // they may have intended '%%' anyway). We don't want to continue processing
8584 // the format string after this point, however, as we will like just get
8585 // gibberish when trying to match arguments.
8586 keepGoing = false;
8587 }
8588
8589 StringRef Specifier(csStart, csLen);
8590
8591 // If the specifier in non-printable, it could be the first byte of a UTF-8
8592 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8593 // hex value.
8594 std::string CodePointStr;
8595 if (!llvm::sys::locale::isPrint(*csStart)) {
8596 llvm::UTF32 CodePoint;
8597 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8598 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8599 llvm::ConversionResult Result =
8600 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8601
8602 if (Result != llvm::conversionOK) {
8603 unsigned char FirstChar = *csStart;
8604 CodePoint = (llvm::UTF32)FirstChar;
8605 }
8606
8607 llvm::raw_string_ostream OS(CodePointStr);
8608 if (CodePoint < 256)
8609 OS << "\\x" << llvm::format("%02x", CodePoint);
8610 else if (CodePoint <= 0xFFFF)
8611 OS << "\\u" << llvm::format("%04x", CodePoint);
8612 else
8613 OS << "\\U" << llvm::format("%08x", CodePoint);
8614 Specifier = CodePointStr;
8615 }
8616
8617 EmitFormatDiagnostic(
8618 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8619 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8620
8621 return keepGoing;
8622}
8623
8624void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8625 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8626 EmitFormatDiagnostic(
8627 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), Loc,
8628 /*isStringLoc*/ true, getSpecifierRange(startSpec, specifierLen));
8629}
8630
8631bool CheckFormatHandler::CheckNumArgs(
8634 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8635
8636 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8637 PartialDiagnostic PDiag =
8639 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8640 << (argIndex + 1) << NumDataArgs)
8641 : S.PDiag(diag::warn_printf_insufficient_data_args);
8642 EmitFormatDiagnostic(PDiag, getLocationOfByte(CS.getStart()),
8643 /*IsStringLocation*/ true,
8644 getSpecifierRange(startSpecifier, specifierLen));
8645
8646 // Since more arguments than conversion tokens are given, by extension
8647 // all arguments are covered, so mark this as so.
8648 UncoveredArg.setAllCovered();
8649 return false;
8650 }
8651 return true;
8652}
8653
8654template <typename Range>
8655void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8656 SourceLocation Loc,
8657 bool IsStringLocation,
8658 Range StringRange,
8659 ArrayRef<FixItHint> FixIt) {
8660 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8661 IsStringLocation, StringRange, FixIt);
8662}
8663
8664/// If the format string is not within the function call, emit a note
8665/// so that the function call and string are in diagnostic messages.
8666///
8667/// \param InFunctionCall if true, the format string is within the function
8668/// call and only one diagnostic message will be produced. Otherwise, an
8669/// extra note will be emitted pointing to location of the format string.
8670///
8671/// \param ArgumentExpr the expression that is passed as the format string
8672/// argument in the function call. Used for getting locations when two
8673/// diagnostics are emitted.
8674///
8675/// \param PDiag the callee should already have provided any strings for the
8676/// diagnostic message. This function only adds locations and fixits
8677/// to diagnostics.
8678///
8679/// \param Loc primary location for diagnostic. If two diagnostics are
8680/// required, one will be at Loc and a new SourceLocation will be created for
8681/// the other one.
8682///
8683/// \param IsStringLocation if true, Loc points to the format string should be
8684/// used for the note. Otherwise, Loc points to the argument list and will
8685/// be used with PDiag.
8686///
8687/// \param StringRange some or all of the string to highlight. This is
8688/// templated so it can accept either a CharSourceRange or a SourceRange.
8689///
8690/// \param FixIt optional fix it hint for the format string.
8691template <typename Range>
8692void CheckFormatHandler::EmitFormatDiagnostic(
8693 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8694 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8695 Range StringRange, ArrayRef<FixItHint> FixIt) {
8696 if (InFunctionCall) {
8697 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8698 D << StringRange;
8699 D << FixIt;
8700 } else {
8701 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8702 << ArgumentExpr->getSourceRange();
8703
8705 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8706 diag::note_format_string_defined);
8707
8708 Note << StringRange;
8709 Note << FixIt;
8710 }
8711}
8712
8713//===--- CHECK: Printf format string checking -----------------------------===//
8714
8715namespace {
8716
8717class CheckPrintfHandler : public CheckFormatHandler {
8718public:
8719 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8720 const Expr *origFormatExpr, const FormatStringType type,
8721 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8722 const char *beg, Sema::FormatArgumentPassingKind APK,
8723 ArrayRef<const Expr *> Args, unsigned formatIdx,
8724 bool inFunctionCall, VariadicCallType CallType,
8725 llvm::SmallBitVector &CheckedVarArgs,
8726 UncoveredArgHandler &UncoveredArg)
8727 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8728 numDataArgs, beg, APK, Args, formatIdx,
8729 inFunctionCall, CallType, CheckedVarArgs,
8730 UncoveredArg) {}
8731
8732 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8733
8734 /// Returns true if '%@' specifiers are allowed in the format string.
8735 bool allowsObjCArg() const {
8736 return FSType == FormatStringType::NSString ||
8737 FSType == FormatStringType::OSLog ||
8738 FSType == FormatStringType::OSTrace;
8739 }
8740
8741 bool HandleInvalidPrintfConversionSpecifier(
8742 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8743 unsigned specifierLen) override;
8744
8745 void handleInvalidMaskType(StringRef MaskType) override;
8746
8747 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8748 const char *startSpecifier, unsigned specifierLen,
8749 const TargetInfo &Target) override;
8750 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8751 const char *StartSpecifier, unsigned SpecifierLen,
8752 const Expr *E);
8753
8754 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8755 unsigned k, const char *startSpecifier,
8756 unsigned specifierLen);
8757 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8758 const analyze_printf::OptionalAmount &Amt,
8759 unsigned type, const char *startSpecifier,
8760 unsigned specifierLen);
8761 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8762 const analyze_printf::OptionalFlag &flag,
8763 const char *startSpecifier, unsigned specifierLen);
8764 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8765 const analyze_printf::OptionalFlag &ignoredFlag,
8766 const analyze_printf::OptionalFlag &flag,
8767 const char *startSpecifier, unsigned specifierLen);
8768 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8769
8770 void HandleEmptyObjCModifierFlag(const char *startFlag,
8771 unsigned flagLen) override;
8772
8773 void HandleInvalidObjCModifierFlag(const char *startFlag,
8774 unsigned flagLen) override;
8775
8776 void
8777 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8778 const char *flagsEnd,
8779 const char *conversionPosition) override;
8780};
8781
8782/// Keeps around the information needed to verify that two specifiers are
8783/// compatible.
8784class EquatableFormatArgument {
8785public:
8786 enum SpecifierSensitivity : unsigned {
8787 SS_None,
8788 SS_Private,
8789 SS_Public,
8790 SS_Sensitive
8791 };
8792
8793 enum FormatArgumentRole : unsigned {
8794 FAR_Data,
8795 FAR_FieldWidth,
8796 FAR_Precision,
8797 FAR_Auxiliary, // FreeBSD kernel %b and %D
8798 };
8799
8800private:
8801 analyze_format_string::ArgType ArgType;
8802 analyze_format_string::LengthModifier LengthMod;
8803 StringRef SpecifierLetter;
8804 CharSourceRange Range;
8805 SourceLocation ElementLoc;
8806 FormatArgumentRole Role : 2;
8807 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8808 unsigned Position : 14;
8809 unsigned ModifierFor : 14; // not set for FAR_Data
8810
8811 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8812 bool InFunctionCall) const;
8813
8814public:
8815 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8816 analyze_format_string::LengthModifier LengthMod,
8817 StringRef SpecifierLetter,
8818 analyze_format_string::ArgType ArgType,
8819 FormatArgumentRole Role,
8820 SpecifierSensitivity Sensitivity, unsigned Position,
8821 unsigned ModifierFor)
8822 : ArgType(ArgType), LengthMod(LengthMod),
8823 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8824 Role(Role), Sensitivity(Sensitivity), Position(Position),
8825 ModifierFor(ModifierFor) {}
8826
8827 unsigned getPosition() const { return Position; }
8828 SourceLocation getSourceLocation() const { return ElementLoc; }
8829 CharSourceRange getSourceRange() const { return Range; }
8830 analyze_format_string::LengthModifier getLengthModifier() const {
8831 return LengthMod;
8832 }
8833 void setModifierFor(unsigned V) { ModifierFor = V; }
8834
8835 std::string buildFormatSpecifier() const {
8836 std::string result;
8837 llvm::raw_string_ostream(result)
8838 << getLengthModifier().toString() << SpecifierLetter;
8839 return result;
8840 }
8841
8842 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8843 const Expr *FmtExpr, bool InFunctionCall) const;
8844};
8845
8846/// Turns format strings into lists of EquatableSpecifier objects.
8847class DecomposePrintfHandler : public CheckPrintfHandler {
8848 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8849 bool HadError;
8850
8851 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8852 const Expr *origFormatExpr,
8853 const FormatStringType type, unsigned firstDataArg,
8854 unsigned numDataArgs, bool isObjC, const char *beg,
8856 ArrayRef<const Expr *> Args, unsigned formatIdx,
8857 bool inFunctionCall, VariadicCallType CallType,
8858 llvm::SmallBitVector &CheckedVarArgs,
8859 UncoveredArgHandler &UncoveredArg,
8860 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8861 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8862 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8863 inFunctionCall, CallType, CheckedVarArgs,
8864 UncoveredArg),
8865 Specs(Specs), HadError(false) {}
8866
8867public:
8868 static bool
8869 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8870 FormatStringType type, bool IsObjC, bool InFunctionCall,
8871 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8872
8873 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8874 const char *startSpecifier,
8875 unsigned specifierLen,
8876 const TargetInfo &Target) override;
8877};
8878
8879} // namespace
8880
8881bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8882 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8883 unsigned specifierLen) {
8886
8887 return HandleInvalidConversionSpecifier(
8888 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
8889 specifierLen, CS.getStart(), CS.getLength());
8890}
8891
8892void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8893 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8894}
8895
8896// Error out if struct or complex type argments are passed to os_log.
8898 QualType T) {
8899 if (FSType != FormatStringType::OSLog)
8900 return false;
8901 return T->isRecordType() || T->isComplexType();
8902}
8903
8904bool CheckPrintfHandler::HandleAmount(
8905 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8906 const char *startSpecifier, unsigned specifierLen) {
8907 if (Amt.hasDataArgument()) {
8908 if (HasFormatArguments()) {
8909 unsigned argIndex = Amt.getArgIndex();
8910 if (argIndex >= NumDataArgs) {
8911 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8912 << k,
8913 getLocationOfByte(Amt.getStart()),
8914 /*IsStringLocation*/ true,
8915 getSpecifierRange(startSpecifier, specifierLen));
8916 // Don't do any more checking. We will just emit
8917 // spurious errors.
8918 return false;
8919 }
8920
8921 // Type check the data argument. It should be an 'int'.
8922 // Although not in conformance with C99, we also allow the argument to be
8923 // an 'unsigned int' as that is a reasonably safe case. GCC also
8924 // doesn't emit a warning for that case.
8925 CoveredArgs.set(argIndex);
8926 const Expr *Arg = getDataArg(argIndex);
8927 if (!Arg)
8928 return false;
8929
8930 QualType T = Arg->getType();
8931
8932 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8933 assert(AT.isValid());
8934
8935 if (!AT.matchesType(S.Context, T)) {
8936 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8937 ? diag::err_printf_asterisk_wrong_type
8938 : diag::warn_printf_asterisk_wrong_type;
8939 EmitFormatDiagnostic(S.PDiag(DiagID)
8941 << T << Arg->getSourceRange(),
8942 getLocationOfByte(Amt.getStart()),
8943 /*IsStringLocation*/ true,
8944 getSpecifierRange(startSpecifier, specifierLen));
8945 // Don't do any more checking. We will just emit
8946 // spurious errors.
8947 return false;
8948 }
8949 }
8950 }
8951 return true;
8952}
8953
8954void CheckPrintfHandler::HandleInvalidAmount(
8956 const analyze_printf::OptionalAmount &Amt, unsigned type,
8957 const char *startSpecifier, unsigned specifierLen) {
8960
8961 FixItHint fixit =
8964 getSpecifierRange(Amt.getStart(), Amt.getConstantLength()))
8965 : FixItHint();
8966
8967 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8968 << type << CS.toString(),
8969 getLocationOfByte(Amt.getStart()),
8970 /*IsStringLocation*/ true,
8971 getSpecifierRange(startSpecifier, specifierLen), fixit);
8972}
8973
8974void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8975 const analyze_printf::OptionalFlag &flag,
8976 const char *startSpecifier,
8977 unsigned specifierLen) {
8978 // Warn about pointless flag with a fixit removal.
8981 EmitFormatDiagnostic(
8982 S.PDiag(diag::warn_printf_nonsensical_flag)
8983 << flag.toString() << CS.toString(),
8984 getLocationOfByte(flag.getPosition()),
8985 /*IsStringLocation*/ true,
8986 getSpecifierRange(startSpecifier, specifierLen),
8987 FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1)));
8988}
8989
8990void CheckPrintfHandler::HandleIgnoredFlag(
8992 const analyze_printf::OptionalFlag &ignoredFlag,
8993 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
8994 unsigned specifierLen) {
8995 // Warn about ignored flag with a fixit removal.
8996 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8997 << ignoredFlag.toString() << flag.toString(),
8998 getLocationOfByte(ignoredFlag.getPosition()),
8999 /*IsStringLocation*/ true,
9000 getSpecifierRange(startSpecifier, specifierLen),
9002 getSpecifierRange(ignoredFlag.getPosition(), 1)));
9003}
9004
9005void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
9006 unsigned flagLen) {
9007 // Warn about an empty flag.
9008 EmitFormatDiagnostic(
9009 S.PDiag(diag::warn_printf_empty_objc_flag), getLocationOfByte(startFlag),
9010 /*IsStringLocation*/ true, getSpecifierRange(startFlag, flagLen));
9011}
9012
9013void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
9014 unsigned flagLen) {
9015 // Warn about an invalid flag.
9016 auto Range = getSpecifierRange(startFlag, flagLen);
9017 StringRef flag(startFlag, flagLen);
9018 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9019 getLocationOfByte(startFlag),
9020 /*IsStringLocation*/ true, Range,
9022}
9023
9024void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9025 const char *flagsStart, const char *flagsEnd,
9026 const char *conversionPosition) {
9027 // Warn about using '[...]' without a '@' conversion.
9028 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9029 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9030 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
9031 getLocationOfByte(conversionPosition),
9032 /*IsStringLocation*/ true, Range,
9034}
9035
9036void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
9037 const Expr *FmtExpr,
9038 bool InFunctionCall) const {
9039 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
9040 ElementLoc, true, Range);
9041}
9042
9043bool EquatableFormatArgument::VerifyCompatible(
9044 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
9045 bool InFunctionCall) const {
9047 if (Role != Other.Role) {
9048 // diagnose and stop
9049 EmitDiagnostic(
9050 S, S.PDiag(diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
9051 FmtExpr, InFunctionCall);
9052 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
9053 return false;
9054 }
9055
9056 if (Role != FAR_Data) {
9057 if (ModifierFor != Other.ModifierFor) {
9058 // diagnose and stop
9059 EmitDiagnostic(S,
9060 S.PDiag(diag::warn_format_cmp_modifierfor_mismatch)
9061 << (ModifierFor + 1) << (Other.ModifierFor + 1),
9062 FmtExpr, InFunctionCall);
9063 S.Diag(Other.ElementLoc, diag::note_format_cmp_with) << 0 << Other.Range;
9064 return false;
9065 }
9066 return true;
9067 }
9068
9069 bool HadError = false;
9070 if (Sensitivity != Other.Sensitivity) {
9071 // diagnose and continue
9072 EmitDiagnostic(S,
9073 S.PDiag(diag::warn_format_cmp_sensitivity_mismatch)
9074 << Sensitivity << Other.Sensitivity,
9075 FmtExpr, InFunctionCall);
9076 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
9077 << 0 << Other.Range;
9078 }
9079
9080 switch (ArgType.matchesArgType(S.Context, Other.ArgType)) {
9081 case MK::Match:
9082 break;
9083
9084 case MK::MatchPromotion:
9085 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
9086 // MatchPromotion is treated as a failure by format_matches.
9087 case MK::NoMatch:
9088 case MK::NoMatchTypeConfusion:
9089 case MK::NoMatchPromotionTypeConfusion:
9090 EmitDiagnostic(S,
9091 S.PDiag(diag::warn_format_cmp_specifier_mismatch)
9092 << buildFormatSpecifier()
9093 << Other.buildFormatSpecifier(),
9094 FmtExpr, InFunctionCall);
9095 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
9096 << 0 << Other.Range;
9097 break;
9098
9099 case MK::NoMatchPedantic:
9100 EmitDiagnostic(S,
9101 S.PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
9102 << buildFormatSpecifier()
9103 << Other.buildFormatSpecifier(),
9104 FmtExpr, InFunctionCall);
9105 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
9106 << 0 << Other.Range;
9107 break;
9108
9109 case MK::NoMatchSignedness:
9110 EmitDiagnostic(S,
9111 S.PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
9112 << buildFormatSpecifier()
9113 << Other.buildFormatSpecifier(),
9114 FmtExpr, InFunctionCall);
9115 HadError = S.Diag(Other.ElementLoc, diag::note_format_cmp_with)
9116 << 0 << Other.Range;
9117 break;
9118 }
9119 return !HadError;
9120}
9121
9122bool DecomposePrintfHandler::GetSpecifiers(
9123 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
9124 FormatStringType Type, bool IsObjC, bool InFunctionCall,
9126 StringRef Data = FSL->getString();
9127 const char *Str = Data.data();
9128 llvm::SmallBitVector BV;
9129 UncoveredArgHandler UA;
9130 const Expr *PrintfArgs[] = {FSL->getFormatString()};
9131 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
9132 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
9133 InFunctionCall, VariadicCallType::DoesNotApply, BV,
9134 UA, Args);
9135
9137 H, Str, Str + Data.size(), S.getLangOpts(), S.Context.getTargetInfo(),
9139 H.DoneProcessing();
9140 if (H.HadError)
9141 return false;
9142
9143 llvm::stable_sort(Args, [](const EquatableFormatArgument &A,
9144 const EquatableFormatArgument &B) {
9145 return A.getPosition() < B.getPosition();
9146 });
9147 return true;
9148}
9149
9150bool DecomposePrintfHandler::HandlePrintfSpecifier(
9151 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9152 unsigned specifierLen, const TargetInfo &Target) {
9153 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
9154 specifierLen, Target)) {
9155 HadError = true;
9156 return false;
9157 }
9158
9159 // Do not add any specifiers to the list for %%. This is possibly incorrect
9160 // if using a precision/width with a data argument, but that combination is
9161 // meaningless and we wouldn't know which format to attach the
9162 // precision/width to.
9163 const auto &CS = FS.getConversionSpecifier();
9165 return true;
9166
9167 // have to patch these to have the right ModifierFor if they are used
9168 const unsigned Unset = ~0;
9169 unsigned FieldWidthIndex = Unset;
9170 unsigned PrecisionIndex = Unset;
9171
9172 // field width?
9173 const auto &FieldWidth = FS.getFieldWidth();
9174 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
9175 FieldWidthIndex = Specs.size();
9176 Specs.emplace_back(
9177 getSpecifierRange(startSpecifier, specifierLen),
9178 getLocationOfByte(FieldWidth.getStart()),
9179 analyze_format_string::LengthModifier(), FieldWidth.getCharacters(),
9180 FieldWidth.getArgType(S.Context),
9181 EquatableFormatArgument::FAR_FieldWidth,
9182 EquatableFormatArgument::SS_None,
9183 FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
9184 : FieldWidthIndex,
9185 0);
9186 }
9187 // precision?
9188 const auto &Precision = FS.getPrecision();
9189 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
9190 PrecisionIndex = Specs.size();
9191 Specs.emplace_back(
9192 getSpecifierRange(startSpecifier, specifierLen),
9193 getLocationOfByte(Precision.getStart()),
9194 analyze_format_string::LengthModifier(), Precision.getCharacters(),
9195 Precision.getArgType(S.Context), EquatableFormatArgument::FAR_Precision,
9196 EquatableFormatArgument::SS_None,
9197 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
9198 : PrecisionIndex,
9199 0);
9200 }
9201
9202 // this specifier
9203 unsigned SpecIndex =
9204 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
9205 if (FieldWidthIndex != Unset)
9206 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
9207 if (PrecisionIndex != Unset)
9208 Specs[PrecisionIndex].setModifierFor(SpecIndex);
9209
9210 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
9211 if (FS.isPrivate())
9212 Sensitivity = EquatableFormatArgument::SS_Private;
9213 else if (FS.isPublic())
9214 Sensitivity = EquatableFormatArgument::SS_Public;
9215 else if (FS.isSensitive())
9216 Sensitivity = EquatableFormatArgument::SS_Sensitive;
9217 else
9218 Sensitivity = EquatableFormatArgument::SS_None;
9219
9220 Specs.emplace_back(
9221 getSpecifierRange(startSpecifier, specifierLen),
9222 getLocationOfByte(CS.getStart()), FS.getLengthModifier(),
9223 CS.getCharacters(), FS.getArgType(S.Context, isObjCContext()),
9224 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
9225
9226 // auxiliary argument?
9229 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
9230 getLocationOfByte(CS.getStart()),
9232 CS.getCharacters(),
9234 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
9235 SpecIndex + 1, SpecIndex);
9236 }
9237 return true;
9238}
9239
9240// Determines if the specified is a C++ class or struct containing
9241// a member with the specified name and kind (e.g. a CXXMethodDecl named
9242// "c_str()").
9243template<typename MemberKind>
9245CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9246 auto *RD = Ty->getAsCXXRecordDecl();
9248
9249 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
9250 return Results;
9251
9252 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9254 R.suppressDiagnostics();
9255
9256 // We just need to include all members of the right kind turned up by the
9257 // filter, at this point.
9258 if (S.LookupQualifiedName(R, RD))
9259 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9260 NamedDecl *decl = (*I)->getUnderlyingDecl();
9261 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9262 Results.insert(FK);
9263 }
9264 return Results;
9265}
9266
9267/// Check if we could call '.c_str()' on an object.
9268///
9269/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9270/// allow the call, or if it would be ambiguous).
9272 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9273
9274 MethodSet Results =
9275 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
9276 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9277 MI != ME; ++MI)
9278 if ((*MI)->getMinRequiredArguments() == 0)
9279 return true;
9280 return false;
9281}
9282
9283// Check if a (w)string was passed when a (w)char* was needed, and offer a
9284// better diagnostic if so. AT is assumed to be valid.
9285// Returns true when a c_str() conversion method is found.
9286bool CheckPrintfHandler::checkForCStrMembers(
9287 const analyze_printf::ArgType &AT, const Expr *E) {
9288 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9289
9290 MethodSet Results =
9292
9293 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9294 MI != ME; ++MI) {
9295 const CXXMethodDecl *Method = *MI;
9296 if (Method->getMinRequiredArguments() == 0 &&
9297 AT.matchesType(S.Context, Method->getReturnType())) {
9298 // FIXME: Suggest parens if the expression needs them.
9300 S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
9301 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
9302 return true;
9303 }
9304 }
9305
9306 return false;
9307}
9308
9309bool CheckPrintfHandler::HandlePrintfSpecifier(
9310 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9311 unsigned specifierLen, const TargetInfo &Target) {
9312 using namespace analyze_format_string;
9313 using namespace analyze_printf;
9314
9315 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9316
9317 if (FS.consumesDataArgument()) {
9318 if (atFirstArg) {
9319 atFirstArg = false;
9320 usesPositionalArgs = FS.usesPositionalArg();
9321 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9322 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9323 startSpecifier, specifierLen);
9324 return false;
9325 }
9326 }
9327
9328 // First check if the field width, precision, and conversion specifier
9329 // have matching data arguments.
9330 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, startSpecifier,
9331 specifierLen)) {
9332 return false;
9333 }
9334
9335 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, startSpecifier,
9336 specifierLen)) {
9337 return false;
9338 }
9339
9340 if (!CS.consumesDataArgument()) {
9341 // FIXME: Technically specifying a precision or field width here
9342 // makes no sense. Worth issuing a warning at some point.
9343 return true;
9344 }
9345
9346 // Consume the argument.
9347 unsigned argIndex = FS.getArgIndex();
9348 if (argIndex < NumDataArgs) {
9349 // The check to see if the argIndex is valid will come later.
9350 // We set the bit here because we may exit early from this
9351 // function if we encounter some other error.
9352 CoveredArgs.set(argIndex);
9353 }
9354
9355 // FreeBSD kernel extensions.
9356 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9357 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9358 // We need at least two arguments.
9359 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9360 return false;
9361
9362 if (HasFormatArguments()) {
9363 // Claim the second argument.
9364 CoveredArgs.set(argIndex + 1);
9365
9366 // Type check the first argument (int for %b, pointer for %D)
9367 const Expr *Ex = getDataArg(argIndex);
9368 const analyze_printf::ArgType &AT =
9369 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
9370 ? ArgType(S.Context.IntTy)
9371 : ArgType::CPointerTy;
9372 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9373 EmitFormatDiagnostic(
9374 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9375 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9376 << false << Ex->getSourceRange(),
9377 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9378 getSpecifierRange(startSpecifier, specifierLen));
9379
9380 // Type check the second argument (char * for both %b and %D)
9381 Ex = getDataArg(argIndex + 1);
9383 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9384 EmitFormatDiagnostic(
9385 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9386 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9387 << false << Ex->getSourceRange(),
9388 Ex->getBeginLoc(), /*IsStringLocation*/ false,
9389 getSpecifierRange(startSpecifier, specifierLen));
9390 }
9391 return true;
9392 }
9393
9394 // Check for using an Objective-C specific conversion specifier
9395 // in a non-ObjC literal.
9396 if (!allowsObjCArg() && CS.isObjCArg()) {
9397 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9398 specifierLen);
9399 }
9400
9401 // %P can only be used with os_log.
9402 if (FSType != FormatStringType::OSLog &&
9403 CS.getKind() == ConversionSpecifier::PArg) {
9404 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9405 specifierLen);
9406 }
9407
9408 // %n is not allowed with os_log.
9409 if (FSType == FormatStringType::OSLog &&
9410 CS.getKind() == ConversionSpecifier::nArg) {
9411 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9412 getLocationOfByte(CS.getStart()),
9413 /*IsStringLocation*/ false,
9414 getSpecifierRange(startSpecifier, specifierLen));
9415
9416 return true;
9417 }
9418
9419 // Only scalars are allowed for os_trace.
9420 if (FSType == FormatStringType::OSTrace &&
9421 (CS.getKind() == ConversionSpecifier::PArg ||
9422 CS.getKind() == ConversionSpecifier::sArg ||
9423 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9424 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9425 specifierLen);
9426 }
9427
9428 // Check for use of public/private annotation outside of os_log().
9429 if (FSType != FormatStringType::OSLog) {
9430 if (FS.isPublic().isSet()) {
9431 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9432 << "public",
9433 getLocationOfByte(FS.isPublic().getPosition()),
9434 /*IsStringLocation*/ false,
9435 getSpecifierRange(startSpecifier, specifierLen));
9436 }
9437 if (FS.isPrivate().isSet()) {
9438 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9439 << "private",
9440 getLocationOfByte(FS.isPrivate().getPosition()),
9441 /*IsStringLocation*/ false,
9442 getSpecifierRange(startSpecifier, specifierLen));
9443 }
9444 }
9445
9446 const llvm::Triple &Triple = Target.getTriple();
9447 if (CS.getKind() == ConversionSpecifier::nArg &&
9448 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9449 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported),
9450 getLocationOfByte(CS.getStart()),
9451 /*IsStringLocation*/ false,
9452 getSpecifierRange(startSpecifier, specifierLen));
9453 }
9454
9455 // Check for invalid use of field width
9456 if (!FS.hasValidFieldWidth()) {
9457 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9458 startSpecifier, specifierLen);
9459 }
9460
9461 // Check for invalid use of precision
9462 if (!FS.hasValidPrecision()) {
9463 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9464 startSpecifier, specifierLen);
9465 }
9466
9467 // Precision is mandatory for %P specifier.
9468 if (CS.getKind() == ConversionSpecifier::PArg &&
9470 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9471 getLocationOfByte(startSpecifier),
9472 /*IsStringLocation*/ false,
9473 getSpecifierRange(startSpecifier, specifierLen));
9474 }
9475
9476 // Check each flag does not conflict with any other component.
9478 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9479 if (!FS.hasValidLeadingZeros())
9480 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9481 if (!FS.hasValidPlusPrefix())
9482 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9483 if (!FS.hasValidSpacePrefix())
9484 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9485 if (!FS.hasValidAlternativeForm())
9486 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9487 if (!FS.hasValidLeftJustified())
9488 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9489
9490 // Check that flags are not ignored by another flag
9491 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9492 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9493 startSpecifier, specifierLen);
9494 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9495 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9496 startSpecifier, specifierLen);
9497
9498 // Check the length modifier is valid with the given conversion specifier.
9500 S.getLangOpts()))
9501 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9502 diag::warn_format_nonsensical_length);
9503 else if (!FS.hasStandardLengthModifier())
9504 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9506 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9507 diag::warn_format_non_standard_conversion_spec);
9508
9510 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9511
9512 // The remaining checks depend on the data arguments.
9513 if (!HasFormatArguments())
9514 return true;
9515
9516 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9517 return false;
9518
9519 const Expr *Arg = getDataArg(argIndex);
9520 if (!Arg)
9521 return true;
9522
9523 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9524}
9525
9526static bool requiresParensToAddCast(const Expr *E) {
9527 // FIXME: We should have a general way to reason about operator
9528 // precedence and whether parens are actually needed here.
9529 // Take care of a few common cases where they aren't.
9530 const Expr *Inside = E->IgnoreImpCasts();
9531 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9532 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9533
9534 switch (Inside->getStmtClass()) {
9535 case Stmt::ArraySubscriptExprClass:
9536 case Stmt::CallExprClass:
9537 case Stmt::CharacterLiteralClass:
9538 case Stmt::CXXBoolLiteralExprClass:
9539 case Stmt::DeclRefExprClass:
9540 case Stmt::FloatingLiteralClass:
9541 case Stmt::IntegerLiteralClass:
9542 case Stmt::MemberExprClass:
9543 case Stmt::ObjCArrayLiteralClass:
9544 case Stmt::ObjCBoolLiteralExprClass:
9545 case Stmt::ObjCBoxedExprClass:
9546 case Stmt::ObjCDictionaryLiteralClass:
9547 case Stmt::ObjCEncodeExprClass:
9548 case Stmt::ObjCIvarRefExprClass:
9549 case Stmt::ObjCMessageExprClass:
9550 case Stmt::ObjCPropertyRefExprClass:
9551 case Stmt::ObjCStringLiteralClass:
9552 case Stmt::ObjCSubscriptRefExprClass:
9553 case Stmt::ParenExprClass:
9554 case Stmt::StringLiteralClass:
9555 case Stmt::UnaryOperatorClass:
9556 return false;
9557 default:
9558 return true;
9559 }
9560}
9561
9562static std::pair<QualType, StringRef>
9563shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9564 const Expr *E) {
9565 // Use a 'while' to peel off layers of typedefs.
9566 QualType TyTy = IntendedTy;
9567 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9568 StringRef Name = UserTy->getDecl()->getName();
9569 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9570 .Case("CFIndex", Context.getNSIntegerType())
9571 .Case("NSInteger", Context.getNSIntegerType())
9572 .Case("NSUInteger", Context.getNSUIntegerType())
9573 .Case("SInt32", Context.IntTy)
9574 .Case("UInt32", Context.UnsignedIntTy)
9575 .Default(QualType());
9576
9577 if (!CastTy.isNull())
9578 return std::make_pair(CastTy, Name);
9579
9580 TyTy = UserTy->desugar();
9581 }
9582
9583 // Strip parens if necessary.
9584 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9585 return shouldNotPrintDirectly(Context, PE->getSubExpr()->getType(),
9586 PE->getSubExpr());
9587
9588 // If this is a conditional expression, then its result type is constructed
9589 // via usual arithmetic conversions and thus there might be no necessary
9590 // typedef sugar there. Recurse to operands to check for NSInteger &
9591 // Co. usage condition.
9592 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9593 QualType TrueTy, FalseTy;
9594 StringRef TrueName, FalseName;
9595
9596 std::tie(TrueTy, TrueName) = shouldNotPrintDirectly(
9597 Context, CO->getTrueExpr()->getType(), CO->getTrueExpr());
9598 std::tie(FalseTy, FalseName) = shouldNotPrintDirectly(
9599 Context, CO->getFalseExpr()->getType(), CO->getFalseExpr());
9600
9601 if (TrueTy == FalseTy)
9602 return std::make_pair(TrueTy, TrueName);
9603 else if (TrueTy.isNull())
9604 return std::make_pair(FalseTy, FalseName);
9605 else if (FalseTy.isNull())
9606 return std::make_pair(TrueTy, TrueName);
9607 }
9608
9609 return std::make_pair(QualType(), StringRef());
9610}
9611
9612/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9613/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9614/// type do not count.
9616 const ImplicitCastExpr *ICE) {
9617 QualType From = ICE->getSubExpr()->getType();
9618 QualType To = ICE->getType();
9619 // It's an integer promotion if the destination type is the promoted
9620 // source type.
9621 if (ICE->getCastKind() == CK_IntegralCast &&
9623 S.Context.getPromotedIntegerType(From) == To)
9624 return true;
9625 // Look through vector types, since we do default argument promotion for
9626 // those in OpenCL.
9627 if (const auto *VecTy = From->getAs<ExtVectorType>())
9628 From = VecTy->getElementType();
9629 if (const auto *VecTy = To->getAs<ExtVectorType>())
9630 To = VecTy->getElementType();
9631 // It's a floating promotion if the source type is a lower rank.
9632 return ICE->getCastKind() == CK_FloatingCast &&
9633 S.Context.getFloatingTypeOrder(From, To) < 0;
9634}
9635
9638 DiagnosticsEngine &Diags, SourceLocation Loc) {
9640 if (Diags.isIgnored(
9641 diag::warn_format_conversion_argument_type_mismatch_signedness,
9642 Loc) ||
9643 Diags.isIgnored(
9644 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9645 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9647 }
9648 }
9649 return Match;
9650}
9651
9652bool CheckPrintfHandler::checkFormatExpr(
9653 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9654 unsigned SpecifierLen, const Expr *E) {
9655 using namespace analyze_format_string;
9656 using namespace analyze_printf;
9657
9658 // Now type check the data expression that matches the
9659 // format specifier.
9660 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9661 if (!AT.isValid())
9662 return true;
9663
9664 QualType ExprTy = E->getType();
9665 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9666 ExprTy = TET->getUnderlyingExpr()->getType();
9667 }
9668
9669 if (const OverflowBehaviorType *OBT =
9670 dyn_cast<OverflowBehaviorType>(ExprTy.getCanonicalType()))
9671 ExprTy = OBT->getUnderlyingType();
9672
9673 // When using the format attribute in C++, you can receive a function or an
9674 // array that will necessarily decay to a pointer when passed to the final
9675 // format consumer. Apply decay before type comparison.
9676 if (ExprTy->canDecayToPointerType())
9677 ExprTy = S.Context.getDecayedType(ExprTy);
9678
9679 // Diagnose attempts to print a boolean value as a character. Unlike other
9680 // -Wformat diagnostics, this is fine from a type perspective, but it still
9681 // doesn't make sense.
9684 const CharSourceRange &CSR =
9685 getSpecifierRange(StartSpecifier, SpecifierLen);
9686 SmallString<4> FSString;
9687 llvm::raw_svector_ostream os(FSString);
9688 FS.toString(os);
9689 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9690 << FSString,
9691 E->getExprLoc(), false, CSR);
9692 return true;
9693 }
9694
9695 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9696 // dumping raw class data (like is-a pointer), not actual data.
9698 ExprTy->isObjCObjectPointerType()) {
9699 const CharSourceRange &CSR =
9700 getSpecifierRange(StartSpecifier, SpecifierLen);
9701 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer),
9702 E->getExprLoc(), false, CSR);
9703 return true;
9704 }
9705
9706 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9707 return true;
9708
9709 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9711 ArgType::MatchKind OrigMatch = Match;
9712
9714 if (Match == ArgType::Match)
9715 return true;
9716
9717 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9718 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9719
9720 // Look through argument promotions for our error message's reported type.
9721 // This includes the integral and floating promotions, but excludes array
9722 // and function pointer decay (seeing that an argument intended to be a
9723 // string has type 'char [6]' is probably more confusing than 'char *') and
9724 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9725 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9726 if (isArithmeticArgumentPromotion(S, ICE)) {
9727 E = ICE->getSubExpr();
9728 ExprTy = E->getType();
9729
9730 // Check if we didn't match because of an implicit cast from a 'char'
9731 // or 'short' to an 'int'. This is done because printf is a varargs
9732 // function.
9733 if (ICE->getType() == S.Context.IntTy ||
9734 ICE->getType() == S.Context.UnsignedIntTy) {
9735 // All further checking is done on the subexpression
9736 ImplicitMatch = AT.matchesType(S.Context, ExprTy);
9737 if (OrigMatch == ArgType::NoMatchSignedness &&
9738 ImplicitMatch != ArgType::NoMatchSignedness)
9739 // If the original match was a signedness match this match on the
9740 // implicit cast type also need to be signedness match otherwise we
9741 // might introduce new unexpected warnings from -Wformat-signedness.
9742 return true;
9743 ImplicitMatch = handleFormatSignedness(
9744 ImplicitMatch, S.getDiagnostics(), E->getExprLoc());
9745 if (ImplicitMatch == ArgType::Match)
9746 return true;
9747 }
9748 }
9749 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9750 // Special case for 'a', which has type 'int' in C.
9751 // Note, however, that we do /not/ want to treat multibyte constants like
9752 // 'MooV' as characters! This form is deprecated but still exists. In
9753 // addition, don't treat expressions as of type 'char' if one byte length
9754 // modifier is provided.
9755 if (ExprTy == S.Context.IntTy &&
9757 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) {
9758 ExprTy = S.Context.CharTy;
9759 // To improve check results, we consider a character literal in C
9760 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9761 // more likely a type confusion situation, so we will suggest to
9762 // use '%hhd' instead by discarding the MatchPromotion.
9763 if (Match == ArgType::MatchPromotion)
9765 }
9766 }
9767 if (Match == ArgType::MatchPromotion) {
9768 // WG14 N2562 only clarified promotions in *printf
9769 // For NSLog in ObjC, just preserve -Wformat behavior
9770 if (!S.getLangOpts().ObjC &&
9771 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9772 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9773 return true;
9775 }
9776 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9777 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9778 Match = ImplicitMatch;
9779 assert(Match != ArgType::MatchPromotion);
9780
9781 // Look through unscoped enums to their underlying type.
9782 bool IsEnum = false;
9783 bool IsScopedEnum = false;
9784 QualType IntendedTy = ExprTy;
9785 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9786 IntendedTy = ED->getIntegerType();
9787 if (!ED->isScoped()) {
9788 ExprTy = IntendedTy;
9789 // This controls whether we're talking about the underlying type or not,
9790 // which we only want to do when it's an unscoped enum.
9791 IsEnum = true;
9792 } else {
9793 IsScopedEnum = true;
9794 }
9795 }
9796
9797 // %C in an Objective-C context prints a unichar, not a wchar_t.
9798 // If the argument is an integer of some kind, believe the %C and suggest
9799 // a cast instead of changing the conversion specifier.
9800 if (isObjCContext() &&
9802 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9803 !ExprTy->isCharType()) {
9804 // 'unichar' is defined as a typedef of unsigned short, but we should
9805 // prefer using the typedef if it is visible.
9806 IntendedTy = S.Context.UnsignedShortTy;
9807
9808 // While we are here, check if the value is an IntegerLiteral that happens
9809 // to be within the valid range.
9810 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9811 const llvm::APInt &V = IL->getValue();
9812 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9813 return true;
9814 }
9815
9816 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9818 if (S.LookupName(Result, S.getCurScope())) {
9819 NamedDecl *ND = Result.getFoundDecl();
9820 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9821 if (TD->getUnderlyingType() == IntendedTy)
9822 IntendedTy =
9824 /*Qualifier=*/std::nullopt, TD);
9825 }
9826 }
9827 }
9828
9829 // Special-case some of Darwin's platform-independence types by suggesting
9830 // casts to primitive types that are known to be large enough.
9831 bool ShouldNotPrintDirectly = false;
9832 StringRef CastTyName;
9833 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9834 QualType CastTy;
9835 std::tie(CastTy, CastTyName) =
9836 shouldNotPrintDirectly(S.Context, IntendedTy, E);
9837 if (!CastTy.isNull()) {
9838 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9839 // (long in ASTContext). Only complain to pedants or when they're the
9840 // underlying type of a scoped enum (which always needs a cast).
9841 if (!IsScopedEnum &&
9842 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9843 (AT.isSizeT() || AT.isPtrdiffT()) &&
9844 AT.matchesType(S.Context, CastTy))
9846 IntendedTy = CastTy;
9847 ShouldNotPrintDirectly = true;
9848 }
9849 }
9850
9851 // We may be able to offer a FixItHint if it is a supported type.
9852 PrintfSpecifier fixedFS = FS;
9853 bool Success =
9854 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9855
9856 if (Success) {
9857 // Get the fix string from the fixed format specifier
9858 SmallString<16> buf;
9859 llvm::raw_svector_ostream os(buf);
9860 fixedFS.toString(os);
9861
9862 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9863
9864 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9865 unsigned Diag;
9866 switch (Match) {
9867 case ArgType::Match:
9870 llvm_unreachable("expected non-matching");
9872 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9873 break;
9875 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9876 break;
9878 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9879 break;
9880 case ArgType::NoMatch:
9881 Diag = diag::warn_format_conversion_argument_type_mismatch;
9882 break;
9883 }
9884
9885 // In this case, the specifier is wrong and should be changed to match
9886 // the argument.
9887 EmitFormatDiagnostic(S.PDiag(Diag)
9889 << IntendedTy << IsEnum << E->getSourceRange(),
9890 E->getBeginLoc(),
9891 /*IsStringLocation*/ false, SpecRange,
9892 FixItHint::CreateReplacement(SpecRange, os.str()));
9893 } else {
9894 // The canonical type for formatting this value is different from the
9895 // actual type of the expression. (This occurs, for example, with Darwin's
9896 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9897 // should be printed as 'long' for 64-bit compatibility.)
9898 // Rather than emitting a normal format/argument mismatch, we want to
9899 // add a cast to the recommended type (and correct the format string
9900 // if necessary). We should also do so for scoped enumerations.
9901 SmallString<16> CastBuf;
9902 llvm::raw_svector_ostream CastFix(CastBuf);
9903 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9904 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9905 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9906
9908 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy);
9909 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(),
9910 E->getExprLoc());
9911 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9912 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9913
9914 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9915 // If there's already a cast present, just replace it.
9916 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9917 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9918
9919 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9920 // If the expression has high enough precedence,
9921 // just write the C-style cast.
9922 Hints.push_back(
9923 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9924 } else {
9925 // Otherwise, add parens around the expression as well as the cast.
9926 CastFix << "(";
9927 Hints.push_back(
9928 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9929
9930 // We don't use getLocForEndOfToken because it returns invalid source
9931 // locations for macro expansions (by design).
9935 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9936 }
9937
9938 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9939 // The expression has a type that should not be printed directly.
9940 // We extract the name from the typedef because we don't want to show
9941 // the underlying type in the diagnostic.
9942 StringRef Name;
9943 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9944 Name = TypedefTy->getDecl()->getName();
9945 else
9946 Name = CastTyName;
9947 unsigned Diag = Match == ArgType::NoMatchPedantic
9948 ? diag::warn_format_argument_needs_cast_pedantic
9949 : diag::warn_format_argument_needs_cast;
9950 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9951 << E->getSourceRange(),
9952 E->getBeginLoc(), /*IsStringLocation=*/false,
9953 SpecRange, Hints);
9954 } else {
9955 // In this case, the expression could be printed using a different
9956 // specifier, but we've decided that the specifier is probably correct
9957 // and we should cast instead. Just use the normal warning message.
9958
9959 unsigned Diag =
9960 IsScopedEnum
9961 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9962 : diag::warn_format_conversion_argument_type_mismatch;
9963
9964 EmitFormatDiagnostic(
9965 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9966 << IsEnum << E->getSourceRange(),
9967 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9968 }
9969 }
9970 } else {
9971 const CharSourceRange &CSR =
9972 getSpecifierRange(StartSpecifier, SpecifierLen);
9973 // Since the warning for passing non-POD types to variadic functions
9974 // was deferred until now, we emit a warning for non-POD
9975 // arguments here.
9976 bool EmitTypeMismatch = false;
9977 // Record and complex type arguments cannot be code generated for os_log
9978 // and would crash CodeGen, so they are rejected with a hard error emitted
9979 // after the switch below.
9980 bool EmitOSLogError = false;
9981 switch (S.isValidVarArgType(ExprTy)) {
9982 case VarArgKind::Valid:
9984 unsigned Diag;
9985 switch (Match) {
9986 case ArgType::Match:
9989 llvm_unreachable("expected non-matching");
9991 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9992 break;
9994 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9995 break;
9997 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9998 break;
9999 case ArgType::NoMatch:
10000 EmitOSLogError = isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy);
10001 Diag = diag::warn_format_conversion_argument_type_mismatch;
10002 break;
10003 }
10004
10005 if (!EmitOSLogError)
10006 EmitFormatDiagnostic(
10007 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
10008 << IsEnum << CSR << E->getSourceRange(),
10009 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
10010 break;
10011 }
10014 if (CallType == VariadicCallType::DoesNotApply) {
10015 EmitTypeMismatch = true;
10016 } else if (isInvalidOSLogArgTypeForCodeGen(FSType, ExprTy)) {
10017 // Emit a hard error rather than the -Wnon-pod-varargs warning, which
10018 // does not stop compilation.
10019 EmitOSLogError = true;
10020 } else {
10021 EmitFormatDiagnostic(
10022 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
10023 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
10024 << AT.getRepresentativeTypeName(S.Context) << CSR
10025 << E->getSourceRange(),
10026 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
10027 checkForCStrMembers(AT, E);
10028 }
10029 break;
10030
10032 if (CallType == VariadicCallType::DoesNotApply)
10033 EmitTypeMismatch = true;
10034 else if (ExprTy->isObjCObjectType())
10035 EmitFormatDiagnostic(
10036 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
10037 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
10038 << AT.getRepresentativeTypeName(S.Context) << CSR
10039 << E->getSourceRange(),
10040 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
10041 else
10042 // FIXME: If this is an initializer list, suggest removing the braces
10043 // or inserting a cast to the target type.
10044 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
10045 << isa<InitListExpr>(E) << ExprTy << CallType
10047 break;
10048 }
10049
10050 if (EmitOSLogError)
10051 EmitFormatDiagnostic(
10052 S.PDiag(diag::err_format_conversion_argument_type_mismatch)
10053 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
10054 << CSR << E->getSourceRange(),
10055 E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
10056
10057 if (EmitTypeMismatch) {
10058 // The function is not variadic, so we do not generate warnings about
10059 // being allowed to pass that object as a variadic argument. Instead,
10060 // since there are inherently no printf specifiers for types which cannot
10061 // be passed as variadic arguments, emit a plain old specifier mismatch
10062 // argument.
10063 EmitFormatDiagnostic(
10064 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
10065 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false
10066 << E->getSourceRange(),
10067 E->getBeginLoc(), false, CSR);
10068 }
10069
10070 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
10071 "format string specifier index out of range");
10072 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
10073 }
10074
10075 return true;
10076}
10077
10078//===--- CHECK: Scanf format string checking ------------------------------===//
10079
10080namespace {
10081
10082class CheckScanfHandler : public CheckFormatHandler {
10083public:
10084 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
10085 const Expr *origFormatExpr, FormatStringType type,
10086 unsigned firstDataArg, unsigned numDataArgs,
10087 const char *beg, Sema::FormatArgumentPassingKind APK,
10088 ArrayRef<const Expr *> Args, unsigned formatIdx,
10089 bool inFunctionCall, VariadicCallType CallType,
10090 llvm::SmallBitVector &CheckedVarArgs,
10091 UncoveredArgHandler &UncoveredArg)
10092 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
10093 numDataArgs, beg, APK, Args, formatIdx,
10094 inFunctionCall, CallType, CheckedVarArgs,
10095 UncoveredArg) {}
10096
10097 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10098 const char *startSpecifier,
10099 unsigned specifierLen) override;
10100
10101 bool
10102 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10103 const char *startSpecifier,
10104 unsigned specifierLen) override;
10105
10106 void HandleIncompleteScanList(const char *start, const char *end) override;
10107};
10108
10109} // namespace
10110
10111void CheckScanfHandler::HandleIncompleteScanList(const char *start,
10112 const char *end) {
10113 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
10114 getLocationOfByte(end), /*IsStringLocation*/ true,
10115 getSpecifierRange(start, end - start));
10116}
10117
10118bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
10119 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
10120 unsigned specifierLen) {
10123
10124 return HandleInvalidConversionSpecifier(
10125 FS.getArgIndex(), getLocationOfByte(CS.getStart()), startSpecifier,
10126 specifierLen, CS.getStart(), CS.getLength());
10127}
10128
10129bool CheckScanfHandler::HandleScanfSpecifier(
10130 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
10131 unsigned specifierLen) {
10132 using namespace analyze_scanf;
10133 using namespace analyze_format_string;
10134
10135 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
10136
10137 // Handle case where '%' and '*' don't consume an argument. These shouldn't
10138 // be used to decide if we are using positional arguments consistently.
10139 if (FS.consumesDataArgument()) {
10140 if (atFirstArg) {
10141 atFirstArg = false;
10142 usesPositionalArgs = FS.usesPositionalArg();
10143 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
10144 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
10145 startSpecifier, specifierLen);
10146 return false;
10147 }
10148 }
10149
10150 // Check if the field with is non-zero.
10151 const OptionalAmount &Amt = FS.getFieldWidth();
10153 if (Amt.getConstantAmount() == 0) {
10154 const CharSourceRange &R =
10155 getSpecifierRange(Amt.getStart(), Amt.getConstantLength());
10156 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
10157 getLocationOfByte(Amt.getStart()),
10158 /*IsStringLocation*/ true, R,
10160 }
10161 }
10162
10163 if (!FS.consumesDataArgument()) {
10164 // FIXME: Technically specifying a precision or field width here
10165 // makes no sense. Worth issuing a warning at some point.
10166 return true;
10167 }
10168
10169 // Consume the argument.
10170 unsigned argIndex = FS.getArgIndex();
10171 if (argIndex < NumDataArgs) {
10172 // The check to see if the argIndex is valid will come later.
10173 // We set the bit here because we may exit early from this
10174 // function if we encounter some other error.
10175 CoveredArgs.set(argIndex);
10176 }
10177
10178 // Check the length modifier is valid with the given conversion specifier.
10180 S.getLangOpts()))
10181 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10182 diag::warn_format_nonsensical_length);
10183 else if (!FS.hasStandardLengthModifier())
10184 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10186 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10187 diag::warn_format_non_standard_conversion_spec);
10188
10190 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10191
10192 // The remaining checks depend on the data arguments.
10193 if (!HasFormatArguments())
10194 return true;
10195
10196 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10197 return false;
10198
10199 // Check that the argument type matches the format specifier.
10200 const Expr *Ex = getDataArg(argIndex);
10201 if (!Ex)
10202 return true;
10203
10205
10206 if (!AT.isValid()) {
10207 return true;
10208 }
10209
10210 if (CheckUnsupportedType(AT, Ex, startSpecifier, specifierLen))
10211 return true;
10212
10214 AT.matchesType(S.Context, Ex->getType());
10217 return true;
10220
10221 ScanfSpecifier fixedFS = FS;
10222 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
10223 S.getLangOpts(), S.Context);
10224
10225 unsigned Diag =
10226 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10227 : Signedness
10228 ? diag::warn_format_conversion_argument_type_mismatch_signedness
10229 : diag::warn_format_conversion_argument_type_mismatch;
10230
10231 if (Success) {
10232 // Get the fix string from the fixed format specifier.
10233 SmallString<128> buf;
10234 llvm::raw_svector_ostream os(buf);
10235 fixedFS.toString(os);
10236
10237 EmitFormatDiagnostic(
10239 << Ex->getType() << false << Ex->getSourceRange(),
10240 Ex->getBeginLoc(),
10241 /*IsStringLocation*/ false,
10242 getSpecifierRange(startSpecifier, specifierLen),
10244 getSpecifierRange(startSpecifier, specifierLen), os.str()));
10245 } else {
10246 EmitFormatDiagnostic(S.PDiag(Diag)
10248 << Ex->getType() << false << Ex->getSourceRange(),
10249 Ex->getBeginLoc(),
10250 /*IsStringLocation*/ false,
10251 getSpecifierRange(startSpecifier, specifierLen));
10252 }
10253
10254 return true;
10255}
10256
10257static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
10259 const StringLiteral *Fmt,
10261 const Expr *FmtExpr, bool InFunctionCall) {
10262 bool HadError = false;
10263 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
10264 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
10265 while (FmtIter < FmtEnd && RefIter < RefEnd) {
10266 // In positional-style format strings, the same specifier can appear
10267 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
10268 // are sorted by getPosition(), and we process each range of equal
10269 // getPosition() values as one group.
10270 // RefArgs are taken from a string literal that was given to
10271 // attribute(format_matches), and if we got this far, we have already
10272 // verified that if it has positional specifiers that appear in multiple
10273 // locations, then they are all mutually compatible. What's left for us to
10274 // do is verify that all specifiers with the same position in FmtArgs are
10275 // compatible with the RefArgs specifiers. We check each specifier from
10276 // FmtArgs against the first member of the RefArgs group.
10277 for (; FmtIter < FmtEnd; ++FmtIter) {
10278 // Clang does not diagnose missing format specifiers in positional-style
10279 // strings (TODO: which it probably should do, as it is UB to skip over a
10280 // format argument). Skip specifiers if needed.
10281 if (FmtIter->getPosition() < RefIter->getPosition())
10282 continue;
10283
10284 // Delimits a new getPosition() value.
10285 if (FmtIter->getPosition() > RefIter->getPosition())
10286 break;
10287
10288 HadError |=
10289 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
10290 }
10291
10292 // Jump RefIter to the start of the next group.
10293 RefIter = std::find_if(RefIter + 1, RefEnd, [=](const auto &Arg) {
10294 return Arg.getPosition() != RefIter->getPosition();
10295 });
10296 }
10297
10298 if (FmtIter < FmtEnd) {
10299 CheckFormatHandler::EmitFormatDiagnostic(
10300 S, InFunctionCall, FmtExpr,
10301 S.PDiag(diag::warn_format_cmp_specifier_arity) << 1,
10302 FmtExpr->getBeginLoc(), false, FmtIter->getSourceRange());
10303 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with) << 1;
10304 } else if (RefIter < RefEnd) {
10305 CheckFormatHandler::EmitFormatDiagnostic(
10306 S, InFunctionCall, FmtExpr,
10307 S.PDiag(diag::warn_format_cmp_specifier_arity) << 0,
10308 FmtExpr->getBeginLoc(), false, Fmt->getSourceRange());
10309 HadError = S.Diag(Ref->getBeginLoc(), diag::note_format_cmp_with)
10310 << 1 << RefIter->getSourceRange();
10311 }
10312 return !HadError;
10313}
10314
10316 Sema &S, const FormatStringLiteral *FExpr,
10317 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
10319 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
10320 bool inFunctionCall, VariadicCallType CallType,
10321 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10322 bool IgnoreStringsWithoutSpecifiers) {
10323 // CHECK: is the format string a wide literal?
10324 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10325 CheckFormatHandler::EmitFormatDiagnostic(
10326 S, inFunctionCall, Args[format_idx],
10327 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10328 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10329 return;
10330 }
10331
10332 // Str - The format string. NOTE: this is NOT null-terminated!
10333 StringRef StrRef = FExpr->getString();
10334 const char *Str = StrRef.data();
10335 // Account for cases where the string literal is truncated in a declaration.
10336 const ConstantArrayType *T =
10337 S.Context.getAsConstantArrayType(FExpr->getType());
10338 assert(T && "String literal not of constant array type!");
10339 size_t TypeSize = T->getZExtSize();
10340 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10341 const unsigned numDataArgs = Args.size() - firstDataArg;
10342
10343 if (IgnoreStringsWithoutSpecifiers &&
10345 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10346 return;
10347
10348 // Emit a warning if the string literal is truncated and does not contain an
10349 // embedded null character.
10350 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
10351 CheckFormatHandler::EmitFormatDiagnostic(
10352 S, inFunctionCall, Args[format_idx],
10353 S.PDiag(diag::warn_printf_format_string_not_null_terminated),
10354 FExpr->getBeginLoc(),
10355 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
10356 return;
10357 }
10358
10359 // CHECK: empty format string?
10360 if (StrLen == 0 && numDataArgs > 0) {
10361 CheckFormatHandler::EmitFormatDiagnostic(
10362 S, inFunctionCall, Args[format_idx],
10363 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10364 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
10365 return;
10366 }
10367
10372 bool IsObjC =
10374 if (ReferenceFormatString == nullptr) {
10375 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10376 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10377 inFunctionCall, CallType, CheckedVarArgs,
10378 UncoveredArg);
10379
10381 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(),
10384 H.DoneProcessing();
10385 } else {
10387 Type, ReferenceFormatString, FExpr->getFormatString(),
10388 inFunctionCall ? nullptr : Args[format_idx]);
10389 }
10390 } else if (Type == FormatStringType::Scanf) {
10391 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10392 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10393 CallType, CheckedVarArgs, UncoveredArg);
10394
10396 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
10397 H.DoneProcessing();
10398 } // TODO: handle other formats
10399}
10400
10402 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
10403 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
10408 return true;
10409
10410 bool IsObjC =
10413 FormatStringLiteral RefLit = AuthoritativeFormatString;
10414 FormatStringLiteral TestLit = TestedFormatString;
10415 const Expr *Arg;
10416 bool DiagAtStringLiteral;
10417 if (FunctionCallArg) {
10418 Arg = FunctionCallArg;
10419 DiagAtStringLiteral = false;
10420 } else {
10421 Arg = TestedFormatString;
10422 DiagAtStringLiteral = true;
10423 }
10424 if (DecomposePrintfHandler::GetSpecifiers(*this, &RefLit,
10425 AuthoritativeFormatString, Type,
10426 IsObjC, true, RefArgs) &&
10427 DecomposePrintfHandler::GetSpecifiers(*this, &TestLit, Arg, Type, IsObjC,
10428 DiagAtStringLiteral, FmtArgs)) {
10429 return CompareFormatSpecifiers(*this, AuthoritativeFormatString, RefArgs,
10430 TestedFormatString, FmtArgs, Arg,
10431 DiagAtStringLiteral);
10432 }
10433 return false;
10434}
10435
10437 const StringLiteral *Str) {
10442 return true;
10443
10444 FormatStringLiteral RefLit = Str;
10446 bool IsObjC =
10448 if (!DecomposePrintfHandler::GetSpecifiers(*this, &RefLit, Str, Type, IsObjC,
10449 true, Args))
10450 return false;
10451
10452 // Group arguments by getPosition() value, and check that each member of the
10453 // group is compatible with the first member. This verifies that when
10454 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10455 // are mutually compatible. As an optimization, don't test the first member
10456 // against itself.
10457 bool HadError = false;
10458 auto Iter = Args.begin();
10459 auto End = Args.end();
10460 while (Iter != End) {
10461 const auto &FirstInGroup = *Iter;
10462 for (++Iter;
10463 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10464 ++Iter) {
10465 HadError |= !Iter->VerifyCompatible(*this, FirstInGroup, Str, true);
10466 }
10467 }
10468 return !HadError;
10469}
10470
10472 // Str - The format string. NOTE: this is NOT null-terminated!
10473 StringRef StrRef = FExpr->getString();
10474 const char *Str = StrRef.data();
10475 // Account for cases where the string literal is truncated in a declaration.
10476 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
10477 assert(T && "String literal not of constant array type!");
10478 size_t TypeSize = T->getZExtSize();
10479 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
10481 Str, Str + StrLen, getLangOpts(), Context.getTargetInfo());
10482}
10483
10484//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10485
10486// Returns the related absolute value function that is larger, of 0 if one
10487// does not exist.
10488static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10489 switch (AbsFunction) {
10490 default:
10491 return 0;
10492
10493 case Builtin::BI__builtin_abs:
10494 return Builtin::BI__builtin_labs;
10495 case Builtin::BI__builtin_labs:
10496 return Builtin::BI__builtin_llabs;
10497 case Builtin::BI__builtin_llabs:
10498 return 0;
10499
10500 case Builtin::BI__builtin_fabsf:
10501 return Builtin::BI__builtin_fabs;
10502 case Builtin::BI__builtin_fabs:
10503 return Builtin::BI__builtin_fabsl;
10504 case Builtin::BI__builtin_fabsl:
10505 return 0;
10506
10507 case Builtin::BI__builtin_cabsf:
10508 return Builtin::BI__builtin_cabs;
10509 case Builtin::BI__builtin_cabs:
10510 return Builtin::BI__builtin_cabsl;
10511 case Builtin::BI__builtin_cabsl:
10512 return 0;
10513
10514 case Builtin::BIabs:
10515 return Builtin::BIlabs;
10516 case Builtin::BIlabs:
10517 return Builtin::BIllabs;
10518 case Builtin::BIllabs:
10519 return 0;
10520
10521 case Builtin::BIfabsf:
10522 return Builtin::BIfabs;
10523 case Builtin::BIfabs:
10524 return Builtin::BIfabsl;
10525 case Builtin::BIfabsl:
10526 return 0;
10527
10528 case Builtin::BIcabsf:
10529 return Builtin::BIcabs;
10530 case Builtin::BIcabs:
10531 return Builtin::BIcabsl;
10532 case Builtin::BIcabsl:
10533 return 0;
10534 }
10535}
10536
10537// Returns the argument type of the absolute value function.
10539 unsigned AbsType) {
10540 if (AbsType == 0)
10541 return QualType();
10542
10544 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
10546 return QualType();
10547
10549 if (!FT)
10550 return QualType();
10551
10552 if (FT->getNumParams() != 1)
10553 return QualType();
10554
10555 return FT->getParamType(0);
10556}
10557
10558// Returns the best absolute value function, or zero, based on type and
10559// current absolute value function.
10560static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10561 unsigned AbsFunctionKind) {
10562 unsigned BestKind = 0;
10563 uint64_t ArgSize = Context.getTypeSize(ArgType);
10564 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10565 Kind = getLargerAbsoluteValueFunction(Kind)) {
10566 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
10567 if (Context.getTypeSize(ParamType) >= ArgSize) {
10568 if (BestKind == 0)
10569 BestKind = Kind;
10570 else if (Context.hasSameType(ParamType, ArgType)) {
10571 BestKind = Kind;
10572 break;
10573 }
10574 }
10575 }
10576 return BestKind;
10577}
10578
10584
10586 if (T->isIntegralOrEnumerationType())
10587 return AVK_Integer;
10588 if (T->isRealFloatingType())
10589 return AVK_Floating;
10590 if (T->isAnyComplexType())
10591 return AVK_Complex;
10592
10593 llvm_unreachable("Type not integer, floating, or complex");
10594}
10595
10596// Changes the absolute value function to a different type. Preserves whether
10597// the function is a builtin.
10598static unsigned changeAbsFunction(unsigned AbsKind,
10599 AbsoluteValueKind ValueKind) {
10600 switch (ValueKind) {
10601 case AVK_Integer:
10602 switch (AbsKind) {
10603 default:
10604 return 0;
10605 case Builtin::BI__builtin_fabsf:
10606 case Builtin::BI__builtin_fabs:
10607 case Builtin::BI__builtin_fabsl:
10608 case Builtin::BI__builtin_cabsf:
10609 case Builtin::BI__builtin_cabs:
10610 case Builtin::BI__builtin_cabsl:
10611 return Builtin::BI__builtin_abs;
10612 case Builtin::BIfabsf:
10613 case Builtin::BIfabs:
10614 case Builtin::BIfabsl:
10615 case Builtin::BIcabsf:
10616 case Builtin::BIcabs:
10617 case Builtin::BIcabsl:
10618 return Builtin::BIabs;
10619 }
10620 case AVK_Floating:
10621 switch (AbsKind) {
10622 default:
10623 return 0;
10624 case Builtin::BI__builtin_abs:
10625 case Builtin::BI__builtin_labs:
10626 case Builtin::BI__builtin_llabs:
10627 case Builtin::BI__builtin_cabsf:
10628 case Builtin::BI__builtin_cabs:
10629 case Builtin::BI__builtin_cabsl:
10630 return Builtin::BI__builtin_fabsf;
10631 case Builtin::BIabs:
10632 case Builtin::BIlabs:
10633 case Builtin::BIllabs:
10634 case Builtin::BIcabsf:
10635 case Builtin::BIcabs:
10636 case Builtin::BIcabsl:
10637 return Builtin::BIfabsf;
10638 }
10639 case AVK_Complex:
10640 switch (AbsKind) {
10641 default:
10642 return 0;
10643 case Builtin::BI__builtin_abs:
10644 case Builtin::BI__builtin_labs:
10645 case Builtin::BI__builtin_llabs:
10646 case Builtin::BI__builtin_fabsf:
10647 case Builtin::BI__builtin_fabs:
10648 case Builtin::BI__builtin_fabsl:
10649 return Builtin::BI__builtin_cabsf;
10650 case Builtin::BIabs:
10651 case Builtin::BIlabs:
10652 case Builtin::BIllabs:
10653 case Builtin::BIfabsf:
10654 case Builtin::BIfabs:
10655 case Builtin::BIfabsl:
10656 return Builtin::BIcabsf;
10657 }
10658 }
10659 llvm_unreachable("Unable to convert function");
10660}
10661
10662static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10663 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10664 if (!FnInfo)
10665 return 0;
10666
10667 switch (FDecl->getBuiltinID()) {
10668 default:
10669 return 0;
10670 case Builtin::BI__builtin_abs:
10671 case Builtin::BI__builtin_fabs:
10672 case Builtin::BI__builtin_fabsf:
10673 case Builtin::BI__builtin_fabsl:
10674 case Builtin::BI__builtin_labs:
10675 case Builtin::BI__builtin_llabs:
10676 case Builtin::BI__builtin_cabs:
10677 case Builtin::BI__builtin_cabsf:
10678 case Builtin::BI__builtin_cabsl:
10679 case Builtin::BIabs:
10680 case Builtin::BIlabs:
10681 case Builtin::BIllabs:
10682 case Builtin::BIfabs:
10683 case Builtin::BIfabsf:
10684 case Builtin::BIfabsl:
10685 case Builtin::BIcabs:
10686 case Builtin::BIcabsf:
10687 case Builtin::BIcabsl:
10688 return FDecl->getBuiltinID();
10689 }
10690 llvm_unreachable("Unknown Builtin type");
10691}
10692
10693// If the replacement is valid, emit a note with replacement function.
10694// Additionally, suggest including the proper header if not already included.
10696 unsigned AbsKind, QualType ArgType) {
10697 bool EmitHeaderHint = true;
10698 const char *HeaderName = nullptr;
10699 std::string FunctionName;
10700 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10701 FunctionName = "std::abs";
10702 if (ArgType->isIntegralOrEnumerationType()) {
10703 HeaderName = "cstdlib";
10704 } else if (ArgType->isRealFloatingType()) {
10705 HeaderName = "cmath";
10706 } else {
10707 llvm_unreachable("Invalid Type");
10708 }
10709
10710 // Lookup all std::abs
10711 if (NamespaceDecl *Std = S.getStdNamespace()) {
10712 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10713 R.suppressDiagnostics();
10714 S.LookupQualifiedName(R, Std);
10715
10716 for (const auto *I : R) {
10717 const FunctionDecl *FDecl = nullptr;
10718 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10719 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10720 } else {
10721 FDecl = dyn_cast<FunctionDecl>(I);
10722 }
10723 if (!FDecl)
10724 continue;
10725
10726 // Found std::abs(), check that they are the right ones.
10727 if (FDecl->getNumParams() != 1)
10728 continue;
10729
10730 // Check that the parameter type can handle the argument.
10731 QualType ParamType = FDecl->getParamDecl(0)->getType();
10732 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10733 S.Context.getTypeSize(ArgType) <=
10734 S.Context.getTypeSize(ParamType)) {
10735 // Found a function, don't need the header hint.
10736 EmitHeaderHint = false;
10737 break;
10738 }
10739 }
10740 }
10741 } else {
10742 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10743 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10744
10745 if (HeaderName) {
10746 DeclarationName DN(&S.Context.Idents.get(FunctionName));
10747 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10748 R.suppressDiagnostics();
10749 S.LookupName(R, S.getCurScope());
10750
10751 if (R.isSingleResult()) {
10752 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10753 if (FD && FD->getBuiltinID() == AbsKind) {
10754 EmitHeaderHint = false;
10755 } else {
10756 return;
10757 }
10758 } else if (!R.empty()) {
10759 return;
10760 }
10761 }
10762 }
10763
10764 S.Diag(Loc, diag::note_replace_abs_function)
10765 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10766
10767 if (!HeaderName)
10768 return;
10769
10770 if (!EmitHeaderHint)
10771 return;
10772
10773 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10774 << FunctionName;
10775}
10776
10777template <std::size_t StrLen>
10778static bool IsStdFunction(const FunctionDecl *FDecl,
10779 const char (&Str)[StrLen]) {
10780 if (!FDecl)
10781 return false;
10782 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10783 return false;
10784 if (!FDecl->isInStdNamespace())
10785 return false;
10786
10787 return true;
10788}
10789
10790enum class MathCheck { NaN, Inf };
10791static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10792 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10793 return llvm::is_contained(names, calleeName);
10794 };
10795
10796 switch (Check) {
10797 case MathCheck::NaN:
10798 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10799 "__builtin_nanf16", "__builtin_nanf128"});
10800 case MathCheck::Inf:
10801 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10802 "__builtin_inff16", "__builtin_inff128"});
10803 }
10804 llvm_unreachable("unknown MathCheck");
10805}
10806
10807static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10808 if (FDecl->getName() != "infinity")
10809 return false;
10810
10811 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10812 const CXXRecordDecl *RDecl = MDecl->getParent();
10813 if (RDecl->getName() != "numeric_limits")
10814 return false;
10815
10816 if (const NamespaceDecl *NSDecl =
10817 dyn_cast<NamespaceDecl>(RDecl->getDeclContext()))
10818 return NSDecl->isStdNamespace();
10819 }
10820
10821 return false;
10822}
10823
10824void Sema::CheckInfNaNFunction(const CallExpr *Call,
10825 const FunctionDecl *FDecl) {
10826 if (!FDecl->getIdentifier())
10827 return;
10828
10829 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts());
10830 if (FPO.getNoHonorNaNs() &&
10831 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") ||
10833 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10834 << 1 << 0 << Call->getSourceRange();
10835 return;
10836 }
10837
10838 if (FPO.getNoHonorInfs() &&
10839 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") ||
10840 IsInfinityFunction(FDecl) ||
10842 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10843 << 0 << 0 << Call->getSourceRange();
10844 }
10845}
10846
10847void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10848 const FunctionDecl *FDecl) {
10849 if (Call->getNumArgs() != 1)
10850 return;
10851
10852 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10853 bool IsStdAbs = IsStdFunction(FDecl, "abs");
10854 if (AbsKind == 0 && !IsStdAbs)
10855 return;
10856
10857 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10858 QualType ParamType = Call->getArg(0)->getType();
10859
10860 // Unsigned types cannot be negative. Suggest removing the absolute value
10861 // function call.
10862 if (ArgType->isUnsignedIntegerType()) {
10863 std::string FunctionName =
10864 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10865 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10866 Diag(Call->getExprLoc(), diag::note_remove_abs)
10867 << FunctionName
10868 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10869 return;
10870 }
10871
10872 // Taking the absolute value of a pointer is very suspicious, they probably
10873 // wanted to index into an array, dereference a pointer, call a function, etc.
10874 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10875 unsigned DiagType = 0;
10876 if (ArgType->isFunctionType())
10877 DiagType = 1;
10878 else if (ArgType->isArrayType())
10879 DiagType = 2;
10880
10881 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10882 return;
10883 }
10884
10885 // std::abs has overloads which prevent most of the absolute value problems
10886 // from occurring.
10887 if (IsStdAbs)
10888 return;
10889
10890 // Prevent reaching unreachable code in getAbsoluteValueKind for unsupported
10891 // types.
10892 if (!ArgType->isIntegralOrEnumerationType() &&
10893 !ArgType->isRealFloatingType() && !ArgType->isAnyComplexType())
10894 return;
10895
10896 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10897 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10898
10899 // The argument and parameter are the same kind. Check if they are the right
10900 // size.
10901 if (ArgValueKind == ParamValueKind) {
10902 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10903 return;
10904
10905 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10906 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10907 << FDecl << ArgType << ParamType;
10908
10909 if (NewAbsKind == 0)
10910 return;
10911
10912 emitReplacement(*this, Call->getExprLoc(),
10913 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10914 return;
10915 }
10916
10917 // ArgValueKind != ParamValueKind
10918 // The wrong type of absolute value function was used. Attempt to find the
10919 // proper one.
10920 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10921 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10922 if (NewAbsKind == 0)
10923 return;
10924
10925 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10926 << FDecl << ParamValueKind << ArgValueKind;
10927
10928 emitReplacement(*this, Call->getExprLoc(),
10929 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10930}
10931
10932//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10933void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10934 const FunctionDecl *FDecl) {
10935 if (!Call || !FDecl) return;
10936
10937 // Ignore template specializations and macros.
10938 if (inTemplateInstantiation()) return;
10939 if (Call->getExprLoc().isMacroID()) return;
10940
10941 // Only care about the one template argument, two function parameter std::max
10942 if (Call->getNumArgs() != 2) return;
10943 if (!IsStdFunction(FDecl, "max")) return;
10944 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10945 if (!ArgList) return;
10946 if (ArgList->size() != 1) return;
10947
10948 // Check that template type argument is unsigned integer.
10949 const auto& TA = ArgList->get(0);
10950 if (TA.getKind() != TemplateArgument::Type) return;
10951 QualType ArgType = TA.getAsType();
10952 if (!ArgType->isUnsignedIntegerType()) return;
10953
10954 // See if either argument is a literal zero.
10955 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10956 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10957 if (!MTE) return false;
10958 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10959 if (!Num) return false;
10960 if (Num->getValue() != 0) return false;
10961 return true;
10962 };
10963
10964 const Expr *FirstArg = Call->getArg(0);
10965 const Expr *SecondArg = Call->getArg(1);
10966 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10967 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10968
10969 // Only warn when exactly one argument is zero.
10970 if (IsFirstArgZero == IsSecondArgZero) return;
10971
10972 SourceRange FirstRange = FirstArg->getSourceRange();
10973 SourceRange SecondRange = SecondArg->getSourceRange();
10974
10975 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10976
10977 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10978 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10979
10980 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10981 SourceRange RemovalRange;
10982 if (IsFirstArgZero) {
10983 RemovalRange = SourceRange(FirstRange.getBegin(),
10984 SecondRange.getBegin().getLocWithOffset(-1));
10985 } else {
10986 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10987 SecondRange.getEnd());
10988 }
10989
10990 Diag(Call->getExprLoc(), diag::note_remove_max_call)
10991 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10992 << FixItHint::CreateRemoval(RemovalRange);
10993}
10994
10995//===--- CHECK: Standard memory functions ---------------------------------===//
10996
10997/// Takes the expression passed to the size_t parameter of functions
10998/// such as memcmp, strncat, etc and warns if it's a comparison.
10999///
11000/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
11002 const IdentifierInfo *FnName,
11003 SourceLocation FnLoc,
11004 SourceLocation RParenLoc) {
11005 const auto *Size = dyn_cast<BinaryOperator>(E);
11006 if (!Size)
11007 return false;
11008
11009 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
11010 if (!Size->isComparisonOp() && !Size->isLogicalOp())
11011 return false;
11012
11013 SourceRange SizeRange = Size->getSourceRange();
11014 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
11015 << SizeRange << FnName;
11016 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
11017 << FnName
11019 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
11020 << FixItHint::CreateRemoval(RParenLoc);
11021 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
11022 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
11024 ")");
11025
11026 return true;
11027}
11028
11029/// Determine whether the given type is or contains a dynamic class type
11030/// (e.g., whether it has a vtable).
11032 bool &IsContained) {
11033 // Look through array types while ignoring qualifiers.
11034 const Type *Ty = T->getBaseElementTypeUnsafe();
11035 IsContained = false;
11036
11037 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
11038 RD = RD ? RD->getDefinition() : nullptr;
11039 if (!RD || RD->isInvalidDecl())
11040 return nullptr;
11041
11042 if (RD->isDynamicClass())
11043 return RD;
11044
11045 // Check all the fields. If any bases were dynamic, the class is dynamic.
11046 // It's impossible for a class to transitively contain itself by value, so
11047 // infinite recursion is impossible.
11048 for (auto *FD : RD->fields()) {
11049 bool SubContained;
11050 if (const CXXRecordDecl *ContainedRD =
11051 getContainedDynamicClass(FD->getType(), SubContained)) {
11052 IsContained = true;
11053 return ContainedRD;
11054 }
11055 }
11056
11057 return nullptr;
11058}
11059
11061 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
11062 if (Unary->getKind() == UETT_SizeOf)
11063 return Unary;
11064 return nullptr;
11065}
11066
11067/// If E is a sizeof expression, returns its argument expression,
11068/// otherwise returns NULL.
11069static const Expr *getSizeOfExprArg(const Expr *E) {
11071 if (!SizeOf->isArgumentType())
11072 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
11073 return nullptr;
11074}
11075
11076/// If E is a sizeof expression, returns its argument type.
11079 return SizeOf->getTypeOfArgument();
11080 return QualType();
11081}
11082
11083namespace {
11084
11085struct SearchNonTrivialToInitializeField
11086 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
11087 using Super =
11088 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
11089
11090 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
11091
11092 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
11093 SourceLocation SL) {
11094 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
11095 asDerived().visitArray(PDIK, AT, SL);
11096 return;
11097 }
11098
11099 Super::visitWithKind(PDIK, FT, SL);
11100 }
11101
11102 void visitARCStrong(QualType FT, SourceLocation SL) {
11103 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
11104 }
11105 void visitARCWeak(QualType FT, SourceLocation SL) {
11106 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
11107 }
11108 void visitStruct(QualType FT, SourceLocation SL) {
11109 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
11110 visit(FD->getType(), FD->getLocation());
11111 }
11112 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
11113 const ArrayType *AT, SourceLocation SL) {
11114 visit(getContext().getBaseElementType(AT), SL);
11115 }
11116 void visitTrivial(QualType FT, SourceLocation SL) {}
11117
11118 static void diag(QualType RT, const Expr *E, Sema &S) {
11119 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
11120 }
11121
11122 ASTContext &getContext() { return S.getASTContext(); }
11123
11124 const Expr *E;
11125 Sema &S;
11126};
11127
11128struct SearchNonTrivialToCopyField
11129 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
11130 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
11131
11132 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
11133
11134 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
11135 SourceLocation SL) {
11136 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
11137 asDerived().visitArray(PCK, AT, SL);
11138 return;
11139 }
11140
11141 Super::visitWithKind(PCK, FT, SL);
11142 }
11143
11144 void visitARCStrong(QualType FT, SourceLocation SL) {
11145 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
11146 }
11147 void visitARCWeak(QualType FT, SourceLocation SL) {
11148 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
11149 }
11150 void visitPtrAuth(QualType FT, SourceLocation SL) {
11151 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
11152 }
11153 void visitStruct(QualType FT, SourceLocation SL) {
11154 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
11155 visit(FD->getType(), FD->getLocation());
11156 }
11157 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
11158 SourceLocation SL) {
11159 visit(getContext().getBaseElementType(AT), SL);
11160 }
11161 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
11162 SourceLocation SL) {}
11163 void visitTrivial(QualType FT, SourceLocation SL) {}
11164 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
11165
11166 static void diag(QualType RT, const Expr *E, Sema &S) {
11167 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
11168 }
11169
11170 ASTContext &getContext() { return S.getASTContext(); }
11171
11172 const Expr *E;
11173 Sema &S;
11174};
11175
11176}
11177
11178/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
11179static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
11180 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
11181
11182 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
11183 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
11184 return false;
11185
11186 return doesExprLikelyComputeSize(BO->getLHS()) ||
11187 doesExprLikelyComputeSize(BO->getRHS());
11188 }
11189
11190 return getAsSizeOfExpr(SizeofExpr) != nullptr;
11191}
11192
11193/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
11194///
11195/// \code
11196/// #define MACRO 0
11197/// foo(MACRO);
11198/// foo(0);
11199/// \endcode
11200///
11201/// This should return true for the first call to foo, but not for the second
11202/// (regardless of whether foo is a macro or function).
11204 SourceLocation CallLoc,
11205 SourceLocation ArgLoc) {
11206 if (!CallLoc.isMacroID())
11207 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
11208
11209 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
11211}
11212
11213/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
11214/// last two arguments transposed.
11215static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
11216 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
11217 return;
11218
11219 const Expr *SizeArg =
11220 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
11221
11222 auto isLiteralZero = [](const Expr *E) {
11223 return (isa<IntegerLiteral>(E) &&
11224 cast<IntegerLiteral>(E)->getValue() == 0) ||
11226 cast<CharacterLiteral>(E)->getValue() == 0);
11227 };
11228
11229 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
11230 SourceLocation CallLoc = Call->getRParenLoc();
11232 if (isLiteralZero(SizeArg) &&
11233 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
11234
11235 SourceLocation DiagLoc = SizeArg->getExprLoc();
11236
11237 // Some platforms #define bzero to __builtin_memset. See if this is the
11238 // case, and if so, emit a better diagnostic.
11239 if (BId == Builtin::BIbzero ||
11241 CallLoc, SM, S.getLangOpts()) == "bzero")) {
11242 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
11243 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
11244 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
11245 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
11246 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
11247 }
11248 return;
11249 }
11250
11251 // If the second argument to a memset is a sizeof expression and the third
11252 // isn't, this is also likely an error. This should catch
11253 // 'memset(buf, sizeof(buf), 0xff)'.
11254 if (BId == Builtin::BImemset &&
11255 doesExprLikelyComputeSize(Call->getArg(1)) &&
11256 !doesExprLikelyComputeSize(Call->getArg(2))) {
11257 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
11258 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
11259 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
11260 return;
11261 }
11262}
11263
11264void Sema::CheckMemaccessArguments(const CallExpr *Call,
11265 unsigned BId,
11266 IdentifierInfo *FnName) {
11267 assert(BId != 0);
11268
11269 // It is possible to have a non-standard definition of memset. Validate
11270 // we have enough arguments, and if not, abort further checking.
11271 unsigned ExpectedNumArgs =
11272 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11273 if (Call->getNumArgs() < ExpectedNumArgs)
11274 return;
11275
11276 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11277 BId == Builtin::BIstrndup ? 1 : 2);
11278 unsigned LenArg =
11279 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11280 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
11281
11282 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
11283 Call->getBeginLoc(), Call->getRParenLoc()))
11284 return;
11285
11286 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11287 CheckMemaccessSize(*this, BId, Call);
11288
11289 // We have special checking when the length is a sizeof expression.
11290 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
11291
11292 // Although widely used, 'bzero' is not a standard function. Be more strict
11293 // with the argument types before allowing diagnostics and only allow the
11294 // form bzero(ptr, sizeof(...)).
11295 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
11296 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11297 return;
11298
11299 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11300 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
11301 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
11302
11303 QualType DestTy = Dest->getType();
11304 QualType PointeeTy;
11305 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11306 PointeeTy = DestPtrTy->getPointeeType();
11307
11308 // Never warn about void type pointers. This can be used to suppress
11309 // false positives.
11310 if (PointeeTy->isVoidType())
11311 continue;
11312
11313 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11314 // actually comparing the expressions for equality. Because computing the
11315 // expression IDs can be expensive, we only do this if the diagnostic is
11316 // enabled.
11317 if (CheckSizeofMemaccessArgument(LenExpr, Dest, FnName))
11318 break;
11319
11320 // Also check for cases where the sizeof argument is the exact same
11321 // type as the memory argument, and where it points to a user-defined
11322 // record type.
11323 if (SizeOfArgTy != QualType()) {
11324 if (PointeeTy->isRecordType() &&
11325 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
11326 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
11327 PDiag(diag::warn_sizeof_pointer_type_memaccess)
11328 << FnName << SizeOfArgTy << ArgIdx
11329 << PointeeTy << Dest->getSourceRange()
11330 << LenExpr->getSourceRange());
11331 break;
11332 }
11333 }
11334 } else if (DestTy->isArrayType()) {
11335 PointeeTy = DestTy;
11336 }
11337
11338 if (PointeeTy == QualType())
11339 continue;
11340
11341 // Always complain about dynamic classes.
11342 bool IsContained;
11343 if (const CXXRecordDecl *ContainedRD =
11344 getContainedDynamicClass(PointeeTy, IsContained)) {
11345
11346 unsigned OperationType = 0;
11347 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11348 // "overwritten" if we're warning about the destination for any call
11349 // but memcmp; otherwise a verb appropriate to the call.
11350 if (ArgIdx != 0 || IsCmp) {
11351 if (BId == Builtin::BImemcpy)
11352 OperationType = 1;
11353 else if(BId == Builtin::BImemmove)
11354 OperationType = 2;
11355 else if (IsCmp)
11356 OperationType = 3;
11357 }
11358
11359 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11360 PDiag(diag::warn_dyn_class_memaccess)
11361 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11362 << IsContained << ContainedRD << OperationType
11363 << Call->getCallee()->getSourceRange());
11364 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11365 BId != Builtin::BImemset)
11367 Dest->getExprLoc(), Dest,
11368 PDiag(diag::warn_arc_object_memaccess)
11369 << ArgIdx << FnName << PointeeTy
11370 << Call->getCallee()->getSourceRange());
11371 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
11372
11373 // FIXME: Do not consider incomplete types even though they may be
11374 // completed later. GCC does not diagnose such code, but we may want to
11375 // consider diagnosing it in the future, perhaps under a different, but
11376 // related, diagnostic group.
11377 bool NonTriviallyCopyableCXXRecord =
11378 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
11379 !PointeeTy.isTriviallyCopyableType(Context);
11380
11381 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11383 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11384 PDiag(diag::warn_cstruct_memaccess)
11385 << ArgIdx << FnName << PointeeTy << 0);
11386 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
11387 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11388 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11389 // FIXME: Limiting this warning to dest argument until we decide
11390 // whether it's valid for source argument too.
11391 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11392 PDiag(diag::warn_cxxstruct_memaccess)
11393 << FnName << PointeeTy);
11394 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11396 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11397 PDiag(diag::warn_cstruct_memaccess)
11398 << ArgIdx << FnName << PointeeTy << 1);
11399 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
11400 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11401 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11402 // FIXME: Limiting this warning to dest argument until we decide
11403 // whether it's valid for source argument too.
11404 DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
11405 PDiag(diag::warn_cxxstruct_memaccess)
11406 << FnName << PointeeTy);
11407 } else {
11408 continue;
11409 }
11410 } else
11411 continue;
11412
11414 Dest->getExprLoc(), Dest,
11415 PDiag(diag::note_bad_memaccess_silence)
11416 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
11417 break;
11418 }
11419}
11420
11421bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
11422 IdentifierInfo *FnName) {
11423 llvm::FoldingSetNodeID SizeOfArgID;
11424 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
11425 if (!SizeOfArg)
11426 return false;
11427 // Computing this warning is expensive, so we only do so if the warning is
11428 // enabled.
11429 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
11430 SizeOfArg->getExprLoc()))
11431 return false;
11432 QualType DestTy = Dest->getType();
11433 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
11434 if (!DestPtrTy)
11435 return false;
11436
11437 QualType PointeeTy = DestPtrTy->getPointeeType();
11438
11439 if (SizeOfArgID == llvm::FoldingSetNodeID())
11440 SizeOfArg->Profile(SizeOfArgID, Context, true);
11441
11442 llvm::FoldingSetNodeID DestID;
11443 Dest->Profile(DestID, Context, true);
11444 if (DestID == SizeOfArgID) {
11445 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11446 // over sizeof(src) as well.
11447 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11448 StringRef ReadableName = FnName->getName();
11449
11450 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest);
11451 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11452 ActionIdx = 1; // If its an address-of operator, just remove it.
11453 if (!PointeeTy->isIncompleteType() &&
11454 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
11455 ActionIdx = 2; // If the pointee's size is sizeof(char),
11456 // suggest an explicit length.
11457
11458 // If the function is defined as a builtin macro, do not show macro
11459 // expansion.
11460 SourceLocation SL = SizeOfArg->getExprLoc();
11461 SourceRange DSR = Dest->getSourceRange();
11462 SourceRange SSR = SizeOfArg->getSourceRange();
11463 SourceManager &SM = getSourceManager();
11464
11465 if (SM.isMacroArgExpansion(SL)) {
11466 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
11467 SL = SM.getSpellingLoc(SL);
11468 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
11469 SM.getSpellingLoc(DSR.getEnd()));
11470 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
11471 SM.getSpellingLoc(SSR.getEnd()));
11472 }
11473
11474 DiagRuntimeBehavior(SL, SizeOfArg,
11475 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11476 << ReadableName << PointeeTy << DestTy << DSR
11477 << SSR);
11478 DiagRuntimeBehavior(SL, SizeOfArg,
11479 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11480 << ActionIdx << SSR);
11481 return true;
11482 }
11483 return false;
11484}
11485
11486// A little helper routine: ignore addition and subtraction of integer literals.
11487// This intentionally does not ignore all integer constant expressions because
11488// we don't want to remove sizeof().
11489static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11490 Ex = Ex->IgnoreParenCasts();
11491
11492 while (true) {
11493 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
11494 if (!BO || !BO->isAdditiveOp())
11495 break;
11496
11497 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11498 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11499
11500 if (isa<IntegerLiteral>(RHS))
11501 Ex = LHS;
11502 else if (isa<IntegerLiteral>(LHS))
11503 Ex = RHS;
11504 else
11505 break;
11506 }
11507
11508 return Ex;
11509}
11510
11512 ASTContext &Context) {
11513 // Only handle constant-sized or VLAs, but not flexible members.
11514 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
11515 // Only issue the FIXIT for arrays of size > 1.
11516 if (CAT->getZExtSize() <= 1)
11517 return false;
11518 } else if (!Ty->isVariableArrayType()) {
11519 return false;
11520 }
11521 return true;
11522}
11523
11524void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11525 IdentifierInfo *FnName) {
11526
11527 // Don't crash if the user has the wrong number of arguments
11528 unsigned NumArgs = Call->getNumArgs();
11529 if ((NumArgs != 3) && (NumArgs != 4))
11530 return;
11531
11532 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
11533 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
11534 const Expr *CompareWithSrc = nullptr;
11535
11536 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
11537 Call->getBeginLoc(), Call->getRParenLoc()))
11538 return;
11539
11540 // Look for 'strlcpy(dst, x, sizeof(x))'
11541 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
11542 CompareWithSrc = Ex;
11543 else {
11544 // Look for 'strlcpy(dst, x, strlen(x))'
11545 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11546 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11547 SizeCall->getNumArgs() == 1)
11548 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
11549 }
11550 }
11551
11552 if (!CompareWithSrc)
11553 return;
11554
11555 // Determine if the argument to sizeof/strlen is equal to the source
11556 // argument. In principle there's all kinds of things you could do
11557 // here, for instance creating an == expression and evaluating it with
11558 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11559 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11560 if (!SrcArgDRE)
11561 return;
11562
11563 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11564 if (!CompareWithSrcDRE ||
11565 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11566 return;
11567
11568 const Expr *OriginalSizeArg = Call->getArg(2);
11569 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11570 << OriginalSizeArg->getSourceRange() << FnName;
11571
11572 // Output a FIXIT hint if the destination is an array (rather than a
11573 // pointer to an array). This could be enhanced to handle some
11574 // pointers if we know the actual size, like if DstArg is 'array+2'
11575 // we could say 'sizeof(array)-2'.
11576 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
11578 return;
11579
11580 SmallString<128> sizeString;
11581 llvm::raw_svector_ostream OS(sizeString);
11582 OS << "sizeof(";
11583 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11584 OS << ")";
11585
11586 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
11587 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
11588 OS.str());
11589}
11590
11591/// Check if two expressions refer to the same declaration.
11592static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11593 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11594 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11595 return D1->getDecl() == D2->getDecl();
11596 return false;
11597}
11598
11599static const Expr *getStrlenExprArg(const Expr *E) {
11600 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11601 const FunctionDecl *FD = CE->getDirectCallee();
11602 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11603 return nullptr;
11604 return CE->getArg(0)->IgnoreParenCasts();
11605 }
11606 return nullptr;
11607}
11608
11609void Sema::CheckStrncatArguments(const CallExpr *CE,
11610 const IdentifierInfo *FnName) {
11611 // Don't crash if the user has the wrong number of arguments.
11612 if (CE->getNumArgs() < 3)
11613 return;
11614 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
11615 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
11616 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
11617
11618 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
11619 CE->getRParenLoc()))
11620 return;
11621
11622 // Identify common expressions, which are wrongly used as the size argument
11623 // to strncat and may lead to buffer overflows.
11624 unsigned PatternType = 0;
11625 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
11626 // - sizeof(dst)
11627 if (referToTheSameDecl(SizeOfArg, DstArg))
11628 PatternType = 1;
11629 // - sizeof(src)
11630 else if (referToTheSameDecl(SizeOfArg, SrcArg))
11631 PatternType = 2;
11632 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11633 if (BE->getOpcode() == BO_Sub) {
11634 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11635 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11636 // - sizeof(dst) - strlen(dst)
11637 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
11639 PatternType = 1;
11640 // - sizeof(src) - (anything)
11641 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
11642 PatternType = 2;
11643 }
11644 }
11645
11646 if (PatternType == 0)
11647 return;
11648
11649 // Generate the diagnostic.
11650 SourceLocation SL = LenArg->getBeginLoc();
11651 SourceRange SR = LenArg->getSourceRange();
11652 SourceManager &SM = getSourceManager();
11653
11654 // If the function is defined as a builtin macro, do not show macro expansion.
11655 if (SM.isMacroArgExpansion(SL)) {
11656 SL = SM.getSpellingLoc(SL);
11657 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
11658 SM.getSpellingLoc(SR.getEnd()));
11659 }
11660
11661 // Check if the destination is an array (rather than a pointer to an array).
11662 QualType DstTy = DstArg->getType();
11663 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
11664 Context);
11665 if (!isKnownSizeArray) {
11666 if (PatternType == 1)
11667 Diag(SL, diag::warn_strncat_wrong_size) << SR;
11668 else
11669 Diag(SL, diag::warn_strncat_src_size) << SR;
11670 return;
11671 }
11672
11673 if (PatternType == 1)
11674 Diag(SL, diag::warn_strncat_large_size) << SR;
11675 else
11676 Diag(SL, diag::warn_strncat_src_size) << SR;
11677
11678 SmallString<128> sizeString;
11679 llvm::raw_svector_ostream OS(sizeString);
11680 OS << "sizeof(";
11681 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11682 OS << ") - ";
11683 OS << "strlen(";
11684 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
11685 OS << ") - 1";
11686
11687 Diag(SL, diag::note_strncat_wrong_size)
11688 << FixItHint::CreateReplacement(SR, OS.str());
11689}
11690
11691namespace {
11692void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11693 const UnaryOperator *UnaryExpr, const Decl *D) {
11695 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
11696 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
11697 return;
11698 }
11699}
11700
11701void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11702 const UnaryOperator *UnaryExpr) {
11703 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
11704 const Decl *D = Lvalue->getDecl();
11705 if (const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11706 if (!DD->getType()->isReferenceType())
11707 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11708 }
11709 }
11710
11711 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
11712 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11713 Lvalue->getMemberDecl());
11714}
11715
11716void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11717 const UnaryOperator *UnaryExpr) {
11718 const auto *Lambda = dyn_cast<LambdaExpr>(
11720 if (!Lambda)
11721 return;
11722
11723 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11724 << CalleeName << 2 /*object: lambda expression*/;
11725}
11726
11727void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11728 const DeclRefExpr *Lvalue) {
11729 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11730 if (Var == nullptr)
11731 return;
11732
11733 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11734 << CalleeName << 0 /*object: */ << Var;
11735}
11736
11737void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11738 const CastExpr *Cast) {
11739 SmallString<128> SizeString;
11740 llvm::raw_svector_ostream OS(SizeString);
11741
11742 clang::CastKind Kind = Cast->getCastKind();
11743 if (Kind == clang::CK_BitCast &&
11744 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11745 return;
11746 if (Kind == clang::CK_IntegralToPointer &&
11748 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11749 return;
11750
11751 switch (Cast->getCastKind()) {
11752 case clang::CK_BitCast:
11753 case clang::CK_IntegralToPointer:
11754 case clang::CK_FunctionToPointerDecay:
11755 OS << '\'';
11756 Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11757 OS << '\'';
11758 break;
11759 default:
11760 return;
11761 }
11762
11763 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11764 << CalleeName << 0 /*object: */ << OS.str();
11765}
11766} // namespace
11767
11768void Sema::CheckFreeArguments(const CallExpr *E) {
11769 const std::string CalleeName =
11770 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11771
11772 { // Prefer something that doesn't involve a cast to make things simpler.
11773 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11774 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11775 switch (UnaryExpr->getOpcode()) {
11776 case UnaryOperator::Opcode::UO_AddrOf:
11777 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11778 case UnaryOperator::Opcode::UO_Plus:
11779 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11780 default:
11781 break;
11782 }
11783
11784 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11785 if (Lvalue->getType()->isArrayType())
11786 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11787
11788 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11789 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11790 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11791 return;
11792 }
11793
11794 if (isa<BlockExpr>(Arg)) {
11795 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11796 << CalleeName << 1 /*object: block*/;
11797 return;
11798 }
11799 }
11800 // Maybe the cast was important, check after the other cases.
11801 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11802 return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11803}
11804
11805void
11806Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11807 SourceLocation ReturnLoc,
11808 bool isObjCMethod,
11809 const AttrVec *Attrs,
11810 const FunctionDecl *FD) {
11811 // Check if the return value is null but should not be.
11812 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11813 (!isObjCMethod && isNonNullType(lhsType))) &&
11814 CheckNonNullExpr(*this, RetValExp))
11815 Diag(ReturnLoc, diag::warn_null_ret)
11816 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11817
11818 // C++11 [basic.stc.dynamic.allocation]p4:
11819 // If an allocation function declared with a non-throwing
11820 // exception-specification fails to allocate storage, it shall return
11821 // a null pointer. Any other allocation function that fails to allocate
11822 // storage shall indicate failure only by throwing an exception [...]
11823 if (FD) {
11825 if (Op == OO_New || Op == OO_Array_New) {
11826 const FunctionProtoType *Proto
11827 = FD->getType()->castAs<FunctionProtoType>();
11828 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11829 CheckNonNullExpr(*this, RetValExp))
11830 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11831 << FD << getLangOpts().CPlusPlus11;
11832 }
11833 }
11834
11835 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11836 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11837 }
11838
11839 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11840 // here prevent the user from using a PPC MMA type as trailing return type.
11841 if (Context.getTargetInfo().getTriple().isPPC64())
11842 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11843}
11844
11846 const Expr *RHS, BinaryOperatorKind Opcode) {
11847 if (!BinaryOperator::isEqualityOp(Opcode))
11848 return;
11849
11850 // Match and capture subexpressions such as "(float) X == 0.1".
11851 const FloatingLiteral *FPLiteral;
11852 const CastExpr *FPCast;
11853 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11854 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11855 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11856 return FPLiteral && FPCast;
11857 };
11858
11859 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11860 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11861 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11862 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11863 TargetTy->isFloatingPoint()) {
11864 bool Lossy;
11865 llvm::APFloat TargetC = FPLiteral->getValue();
11866 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)),
11867 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11868 if (Lossy) {
11869 // If the literal cannot be represented in the source type, then a
11870 // check for == is always false and check for != is always true.
11871 Diag(Loc, diag::warn_float_compare_literal)
11872 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11873 << LHS->getSourceRange() << RHS->getSourceRange();
11874 return;
11875 }
11876 }
11877 }
11878
11879 // Match a more general floating-point equality comparison (-Wfloat-equal).
11880 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11881 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11882
11883 // Special case: check for x == x (which is OK).
11884 // Do not emit warnings for such cases.
11885 if (const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11886 if (const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11887 if (DRL->getDecl() == DRR->getDecl())
11888 return;
11889
11890 // Special case: check for comparisons against literals that can be exactly
11891 // represented by APFloat. In such cases, do not emit a warning. This
11892 // is a heuristic: often comparison against such literals are used to
11893 // detect if a value in a variable has not changed. This clearly can
11894 // lead to false negatives.
11895 if (const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11896 if (FLL->isExact())
11897 return;
11898 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11899 if (FLR->isExact())
11900 return;
11901
11902 // Check for comparisons with builtin types.
11903 if (const auto *CL = dyn_cast<CallExpr>(LeftExprSansParen);
11904 CL && CL->getBuiltinCallee())
11905 return;
11906
11907 if (const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11908 CR && CR->getBuiltinCallee())
11909 return;
11910
11911 // Emit the diagnostic.
11912 Diag(Loc, diag::warn_floatingpoint_eq)
11913 << LHS->getSourceRange() << RHS->getSourceRange();
11914}
11915
11916//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11917//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11918
11919namespace {
11920
11921/// Structure recording the 'active' range of an integer-valued
11922/// expression.
11923struct IntRange {
11924 /// The number of bits active in the int. Note that this includes exactly one
11925 /// sign bit if !NonNegative.
11926 unsigned Width;
11927
11928 /// True if the int is known not to have negative values. If so, all leading
11929 /// bits before Width are known zero, otherwise they are known to be the
11930 /// same as the MSB within Width.
11931 bool NonNegative;
11932
11933 IntRange(unsigned Width, bool NonNegative)
11934 : Width(Width), NonNegative(NonNegative) {}
11935
11936 /// Number of bits excluding the sign bit.
11937 unsigned valueBits() const {
11938 return NonNegative ? Width : Width - 1;
11939 }
11940
11941 /// Returns the range of the bool type.
11942 static IntRange forBoolType() {
11943 return IntRange(1, true);
11944 }
11945
11946 /// Returns the range of an opaque value of the given integral type.
11947 static IntRange forValueOfType(ASTContext &C, QualType T) {
11948 return forValueOfCanonicalType(C,
11950 }
11951
11952 /// Returns the range of an opaque value of a canonical integral type.
11953 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11954 assert(T->isCanonicalUnqualified());
11955
11956 if (const auto *VT = dyn_cast<VectorType>(T))
11957 T = VT->getElementType().getTypePtr();
11958 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
11959 T = MT->getElementType().getTypePtr();
11960 if (const auto *CT = dyn_cast<ComplexType>(T))
11961 T = CT->getElementType().getTypePtr();
11962 if (const auto *AT = dyn_cast<AtomicType>(T))
11963 T = AT->getValueType().getTypePtr();
11964 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
11965 T = OBT->getUnderlyingType().getTypePtr();
11966
11967 if (!C.getLangOpts().CPlusPlus) {
11968 // For enum types in C code, use the underlying datatype.
11969 if (const auto *ED = T->getAsEnumDecl())
11970 T = ED->getIntegerType().getDesugaredType(C).getTypePtr();
11971 } else if (auto *Enum = T->getAsEnumDecl()) {
11972 // For enum types in C++, use the known bit width of the enumerators.
11973 // In C++11, enums can have a fixed underlying type. Use this type to
11974 // compute the range.
11975 if (Enum->isFixed()) {
11976 return IntRange(C.getIntWidth(QualType(T, 0)),
11977 !Enum->getIntegerType()->isSignedIntegerType());
11978 }
11979
11980 unsigned NumPositive = Enum->getNumPositiveBits();
11981 unsigned NumNegative = Enum->getNumNegativeBits();
11982
11983 if (NumNegative == 0)
11984 return IntRange(NumPositive, true/*NonNegative*/);
11985 else
11986 return IntRange(std::max(NumPositive + 1, NumNegative),
11987 false/*NonNegative*/);
11988 }
11989
11990 if (const auto *EIT = dyn_cast<BitIntType>(T))
11991 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11992
11993 const BuiltinType *BT = cast<BuiltinType>(T);
11994 assert(BT->isInteger());
11995
11996 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11997 }
11998
11999 /// Returns the "target" range of a canonical integral type, i.e.
12000 /// the range of values expressible in the type.
12001 ///
12002 /// This matches forValueOfCanonicalType except that enums have the
12003 /// full range of their type, not the range of their enumerators.
12004 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
12005 assert(T->isCanonicalUnqualified());
12006
12007 if (const VectorType *VT = dyn_cast<VectorType>(T))
12008 T = VT->getElementType().getTypePtr();
12009 if (const auto *MT = dyn_cast<ConstantMatrixType>(T))
12010 T = MT->getElementType().getTypePtr();
12011 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
12012 T = CT->getElementType().getTypePtr();
12013 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
12014 T = AT->getValueType().getTypePtr();
12015 if (const auto *ED = T->getAsEnumDecl())
12016 T = C.getCanonicalType(ED->getIntegerType()).getTypePtr();
12017 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(T))
12018 T = OBT->getUnderlyingType().getTypePtr();
12019
12020 if (const auto *EIT = dyn_cast<BitIntType>(T))
12021 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
12022
12023 const BuiltinType *BT = cast<BuiltinType>(T);
12024 assert(BT->isInteger());
12025
12026 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
12027 }
12028
12029 /// Returns the supremum of two ranges: i.e. their conservative merge.
12030 static IntRange join(IntRange L, IntRange R) {
12031 bool Unsigned = L.NonNegative && R.NonNegative;
12032 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
12033 L.NonNegative && R.NonNegative);
12034 }
12035
12036 /// Return the range of a bitwise-AND of the two ranges.
12037 static IntRange bit_and(IntRange L, IntRange R) {
12038 unsigned Bits = std::max(L.Width, R.Width);
12039 bool NonNegative = false;
12040 if (L.NonNegative) {
12041 Bits = std::min(Bits, L.Width);
12042 NonNegative = true;
12043 }
12044 if (R.NonNegative) {
12045 Bits = std::min(Bits, R.Width);
12046 NonNegative = true;
12047 }
12048 return IntRange(Bits, NonNegative);
12049 }
12050
12051 /// Return the range of a sum of the two ranges.
12052 static IntRange sum(IntRange L, IntRange R) {
12053 bool Unsigned = L.NonNegative && R.NonNegative;
12054 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
12055 Unsigned);
12056 }
12057
12058 /// Return the range of a difference of the two ranges.
12059 static IntRange difference(IntRange L, IntRange R) {
12060 // We need a 1-bit-wider range if:
12061 // 1) LHS can be negative: least value can be reduced.
12062 // 2) RHS can be negative: greatest value can be increased.
12063 bool CanWiden = !L.NonNegative || !R.NonNegative;
12064 bool Unsigned = L.NonNegative && R.Width == 0;
12065 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
12066 !Unsigned,
12067 Unsigned);
12068 }
12069
12070 /// Return the range of a product of the two ranges.
12071 static IntRange product(IntRange L, IntRange R) {
12072 // If both LHS and RHS can be negative, we can form
12073 // -2^L * -2^R = 2^(L + R)
12074 // which requires L + R + 1 value bits to represent.
12075 bool CanWiden = !L.NonNegative && !R.NonNegative;
12076 bool Unsigned = L.NonNegative && R.NonNegative;
12077 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
12078 Unsigned);
12079 }
12080
12081 /// Return the range of a remainder operation between the two ranges.
12082 static IntRange rem(IntRange L, IntRange R) {
12083 // The result of a remainder can't be larger than the result of
12084 // either side. The sign of the result is the sign of the LHS.
12085 bool Unsigned = L.NonNegative;
12086 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
12087 Unsigned);
12088 }
12089};
12090
12091} // namespace
12092
12093static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
12094 if (value.isSigned() && value.isNegative())
12095 return IntRange(value.getSignificantBits(), false);
12096
12097 if (value.getBitWidth() > MaxWidth)
12098 value = value.trunc(MaxWidth);
12099
12100 // isNonNegative() just checks the sign bit without considering
12101 // signedness.
12102 return IntRange(value.getActiveBits(), true);
12103}
12104
12105static std::optional<IntRange> GetValueRange(APValue &result, QualType Ty,
12106 unsigned MaxWidth) {
12107 if (result.isInt())
12108 return GetValueRange(result.getInt(), MaxWidth);
12109
12110 if (result.isVector()) {
12111 std::optional<IntRange> R =
12112 GetValueRange(result.getVectorElt(0), Ty, MaxWidth);
12113 if (!R)
12114 return std::nullopt;
12115 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
12116 std::optional<IntRange> El =
12117 GetValueRange(result.getVectorElt(i), Ty, MaxWidth);
12118 if (!El)
12119 return std::nullopt;
12120 R = IntRange::join(*R, *El);
12121 }
12122 return R;
12123 }
12124
12125 if (result.isComplexInt()) {
12126 IntRange R = GetValueRange(result.getComplexIntReal(), MaxWidth);
12127 IntRange I = GetValueRange(result.getComplexIntImag(), MaxWidth);
12128 return IntRange::join(R, I);
12129 }
12130
12131 // This can happen with lossless casts to intptr_t of "based" lvalues.
12132 // Assume it might use arbitrary bits.
12133 // FIXME: The only reason we need to pass the type in here is to get
12134 // the sign right on this one case. It would be nice if APValue
12135 // preserved this.
12136 if (result.isLValue() || result.isAddrLabelDiff())
12137 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
12138
12139 // Unsupported APValue kinds (e.g. floating) have no integer range.
12140 return std::nullopt;
12141}
12142
12143static QualType GetExprType(const Expr *E) {
12144 QualType Ty = E->getType();
12145 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
12146 Ty = AtomicRHS->getValueType();
12147 return Ty;
12148}
12149
12150/// Attempts to estimate an approximate range for the given integer expression.
12151/// Returns a range if successful, otherwise it returns \c std::nullopt if a
12152/// reliable estimation cannot be determined.
12153///
12154/// \param MaxWidth The width to which the value will be truncated.
12155/// \param InConstantContext If \c true, interpret the expression within a
12156/// constant context.
12157/// \param Approximate If \c true, provide a likely range of values by assuming
12158/// that arithmetic on narrower types remains within those types.
12159/// If \c false, return a range that includes all possible values
12160/// resulting from the expression.
12161/// \returns A range of values that the expression might take, or
12162/// std::nullopt if a reliable estimation cannot be determined.
12163static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12164 unsigned MaxWidth,
12165 bool InConstantContext,
12166 bool Approximate) {
12167 E = E->IgnoreParens();
12168
12169 // Try a full evaluation first.
12170 Expr::EvalResult result;
12171 if (E->EvaluateAsRValue(result, C, InConstantContext))
12172 return GetValueRange(result.Val, GetExprType(E), MaxWidth);
12173
12174 // I think we only want to look through implicit casts here; if the
12175 // user has an explicit widening cast, we should treat the value as
12176 // being of the new, wider type.
12177 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
12178 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
12179 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
12180 Approximate);
12181
12182 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
12183
12184 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
12185 CE->getCastKind() == CK_BooleanToSignedIntegral;
12186
12187 // Assume that non-integer casts can span the full range of the type.
12188 if (!isIntegerCast)
12189 return OutputTypeRange;
12190
12191 std::optional<IntRange> SubRange = TryGetExprRange(
12192 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
12193 InConstantContext, Approximate);
12194 if (!SubRange)
12195 return std::nullopt;
12196
12197 // Bail out if the subexpr's range is as wide as the cast type.
12198 if (SubRange->Width >= OutputTypeRange.Width)
12199 return OutputTypeRange;
12200
12201 // Otherwise, we take the smaller width, and we're non-negative if
12202 // either the output type or the subexpr is.
12203 return IntRange(SubRange->Width,
12204 SubRange->NonNegative || OutputTypeRange.NonNegative);
12205 }
12206
12207 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12208 // If we can fold the condition, just take that operand.
12209 bool CondResult;
12210 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
12211 return TryGetExprRange(
12212 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
12213 InConstantContext, Approximate);
12214
12215 // Otherwise, conservatively merge.
12216 // TryGetExprRange requires an integer expression, but a throw expression
12217 // results in a void type.
12218 Expr *TrueExpr = CO->getTrueExpr();
12219 if (TrueExpr->getType()->isVoidType())
12220 return std::nullopt;
12221
12222 std::optional<IntRange> L =
12223 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate);
12224 if (!L)
12225 return std::nullopt;
12226
12227 Expr *FalseExpr = CO->getFalseExpr();
12228 if (FalseExpr->getType()->isVoidType())
12229 return std::nullopt;
12230
12231 std::optional<IntRange> R =
12232 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate);
12233 if (!R)
12234 return std::nullopt;
12235
12236 return IntRange::join(*L, *R);
12237 }
12238
12239 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12240 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
12241
12242 switch (BO->getOpcode()) {
12243 case BO_Cmp:
12244 llvm_unreachable("builtin <=> should have class type");
12245
12246 // Boolean-valued operations are single-bit and positive.
12247 case BO_LAnd:
12248 case BO_LOr:
12249 case BO_LT:
12250 case BO_GT:
12251 case BO_LE:
12252 case BO_GE:
12253 case BO_EQ:
12254 case BO_NE:
12255 return IntRange::forBoolType();
12256
12257 // The type of the assignments is the type of the LHS, so the RHS
12258 // is not necessarily the same type.
12259 case BO_MulAssign:
12260 case BO_DivAssign:
12261 case BO_RemAssign:
12262 case BO_AddAssign:
12263 case BO_SubAssign:
12264 case BO_XorAssign:
12265 case BO_OrAssign:
12266 // TODO: bitfields?
12267 return IntRange::forValueOfType(C, GetExprType(E));
12268
12269 // Simple assignments just pass through the RHS, which will have
12270 // been coerced to the LHS type.
12271 case BO_Assign:
12272 // TODO: bitfields?
12273 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12274 Approximate);
12275
12276 // Operations with opaque sources are black-listed.
12277 case BO_PtrMemD:
12278 case BO_PtrMemI:
12279 return IntRange::forValueOfType(C, GetExprType(E));
12280
12281 // Bitwise-and uses the *infinum* of the two source ranges.
12282 case BO_And:
12283 case BO_AndAssign:
12284 Combine = IntRange::bit_and;
12285 break;
12286
12287 // Left shift gets black-listed based on a judgement call.
12288 case BO_Shl:
12289 // ...except that we want to treat '1 << (blah)' as logically
12290 // positive. It's an important idiom.
12291 if (IntegerLiteral *I
12292 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
12293 if (I->getValue() == 1) {
12294 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
12295 return IntRange(R.Width, /*NonNegative*/ true);
12296 }
12297 }
12298 [[fallthrough]];
12299
12300 case BO_ShlAssign:
12301 return IntRange::forValueOfType(C, GetExprType(E));
12302
12303 // Right shift by a constant can narrow its left argument.
12304 case BO_Shr:
12305 case BO_ShrAssign: {
12306 std::optional<IntRange> L = TryGetExprRange(
12307 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
12308 if (!L)
12309 return std::nullopt;
12310
12311 // If the shift amount is a positive constant, drop the width by
12312 // that much.
12313 if (std::optional<llvm::APSInt> shift =
12314 BO->getRHS()->getIntegerConstantExpr(C)) {
12315 if (shift->isNonNegative()) {
12316 if (shift->uge(L->Width))
12317 L->Width = (L->NonNegative ? 0 : 1);
12318 else
12319 L->Width -= shift->getZExtValue();
12320 }
12321 }
12322
12323 return L;
12324 }
12325
12326 // Comma acts as its right operand.
12327 case BO_Comma:
12328 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
12329 Approximate);
12330
12331 case BO_Add:
12332 if (!Approximate)
12333 Combine = IntRange::sum;
12334 break;
12335
12336 case BO_Sub:
12337 if (BO->getLHS()->getType()->isPointerType())
12338 return IntRange::forValueOfType(C, GetExprType(E));
12339 if (!Approximate)
12340 Combine = IntRange::difference;
12341 break;
12342
12343 case BO_Mul:
12344 if (!Approximate)
12345 Combine = IntRange::product;
12346 break;
12347
12348 // The width of a division result is mostly determined by the size
12349 // of the LHS.
12350 case BO_Div: {
12351 // Don't 'pre-truncate' the operands.
12352 unsigned opWidth = C.getIntWidth(GetExprType(E));
12353 std::optional<IntRange> L = TryGetExprRange(
12354 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
12355 if (!L)
12356 return std::nullopt;
12357
12358 // If the divisor is constant, use that.
12359 if (std::optional<llvm::APSInt> divisor =
12360 BO->getRHS()->getIntegerConstantExpr(C)) {
12361 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12362 if (log2 >= L->Width)
12363 L->Width = (L->NonNegative ? 0 : 1);
12364 else
12365 L->Width = std::min(L->Width - log2, MaxWidth);
12366 return L;
12367 }
12368
12369 // Otherwise, just use the LHS's width.
12370 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12371 // could be -1.
12372 std::optional<IntRange> R = TryGetExprRange(
12373 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
12374 if (!R)
12375 return std::nullopt;
12376
12377 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12378 }
12379
12380 case BO_Rem:
12381 Combine = IntRange::rem;
12382 break;
12383
12384 // The default behavior is okay for these.
12385 case BO_Xor:
12386 case BO_Or:
12387 break;
12388 }
12389
12390 // Combine the two ranges, but limit the result to the type in which we
12391 // performed the computation.
12392 QualType T = GetExprType(E);
12393 unsigned opWidth = C.getIntWidth(T);
12394 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth,
12395 InConstantContext, Approximate);
12396 if (!L)
12397 return std::nullopt;
12398
12399 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth,
12400 InConstantContext, Approximate);
12401 if (!R)
12402 return std::nullopt;
12403
12404 IntRange C = Combine(*L, *R);
12405 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12406 C.Width = std::min(C.Width, MaxWidth);
12407 return C;
12408 }
12409
12410 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
12411 switch (UO->getOpcode()) {
12412 // Boolean-valued operations are white-listed.
12413 case UO_LNot:
12414 return IntRange::forBoolType();
12415
12416 // Operations with opaque sources are black-listed.
12417 case UO_Deref:
12418 case UO_AddrOf: // should be impossible
12419 return IntRange::forValueOfType(C, GetExprType(E));
12420
12421 case UO_Minus: {
12422 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12423 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12424 Approximate);
12425 }
12426
12427 std::optional<IntRange> SubRange = TryGetExprRange(
12428 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12429
12430 if (!SubRange)
12431 return std::nullopt;
12432
12433 // If the range was previously non-negative, we need an extra bit for the
12434 // sign bit. Otherwise, we need an extra bit because the negation of the
12435 // most-negative value is one bit wider than that value.
12436 return IntRange(std::min(SubRange->Width + 1, MaxWidth), false);
12437 }
12438
12439 case UO_Not: {
12440 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12441 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12442 Approximate);
12443 }
12444
12445 std::optional<IntRange> SubRange = TryGetExprRange(
12446 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12447
12448 if (!SubRange)
12449 return std::nullopt;
12450
12451 // The width increments by 1 if the sub-expression cannot be negative
12452 // since it now can be.
12453 return IntRange(
12454 std::min(SubRange->Width + (int)SubRange->NonNegative, MaxWidth),
12455 false);
12456 }
12457
12458 default:
12459 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
12460 Approximate);
12461 }
12462 }
12463
12464 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12465 // The source expression is null for the OpaqueValueExpr that stands in for
12466 // a non-type template argument of pointer or reference type; fall back to
12467 // the range of the type in that case.
12468 if (const Expr *SourceExpr = OVE->getSourceExpr())
12469 return TryGetExprRange(C, SourceExpr, MaxWidth, InConstantContext,
12470 Approximate);
12471 }
12472
12473 if (const auto *BitField = E->getSourceBitField())
12474 return IntRange(BitField->getBitWidthValue(),
12475 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12476
12477 if (GetExprType(E)->isVoidType())
12478 return std::nullopt;
12479
12480 return IntRange::forValueOfType(C, GetExprType(E));
12481}
12482
12483static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12484 bool InConstantContext,
12485 bool Approximate) {
12486 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
12487 Approximate);
12488}
12489
12490/// Checks whether the given value, which currently has the given
12491/// source semantics, has the same value when coerced through the
12492/// target semantics.
12493static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12494 const llvm::fltSemantics &Src,
12495 const llvm::fltSemantics &Tgt) {
12496 llvm::APFloat truncated = value;
12497
12498 bool ignored;
12499 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12500 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12501
12502 return truncated.bitwiseIsEqual(value);
12503}
12504
12505/// Checks whether the given value, which currently has the given
12506/// source semantics, has the same value when coerced through the
12507/// target semantics.
12508///
12509/// The value might be a vector of floats (or a complex number).
12510static bool IsSameFloatAfterCast(const APValue &value,
12511 const llvm::fltSemantics &Src,
12512 const llvm::fltSemantics &Tgt) {
12513 if (value.isFloat())
12514 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
12515
12516 if (value.isVector()) {
12517 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12518 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
12519 return false;
12520 return true;
12521 }
12522
12523 if (value.isMatrix()) {
12524 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12525 if (!IsSameFloatAfterCast(value.getMatrixElt(i), Src, Tgt))
12526 return false;
12527 return true;
12528 }
12529
12530 assert(value.isComplexFloat());
12531 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
12532 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
12533}
12534
12535static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12536 bool IsListInit = false);
12537
12538static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12539 // Suppress cases where we are comparing against an enum constant.
12540 if (const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
12541 if (isa<EnumConstantDecl>(DR->getDecl()))
12542 return true;
12543
12544 // Suppress cases where the value is expanded from a macro, unless that macro
12545 // is how a language represents a boolean literal. This is the case in both C
12546 // and Objective-C.
12547 SourceLocation BeginLoc = E->getBeginLoc();
12548 if (BeginLoc.isMacroID()) {
12549 StringRef MacroName = Lexer::getImmediateMacroName(
12550 BeginLoc, S.getSourceManager(), S.getLangOpts());
12551 return MacroName != "YES" && MacroName != "NO" &&
12552 MacroName != "true" && MacroName != "false";
12553 }
12554
12555 return false;
12556}
12557
12558static bool isKnownToHaveUnsignedValue(const Expr *E) {
12559 return E->getType()->isIntegerType() &&
12560 (!E->getType()->isSignedIntegerType() ||
12562}
12563
12564namespace {
12565/// The promoted range of values of a type. In general this has the
12566/// following structure:
12567///
12568/// |-----------| . . . |-----------|
12569/// ^ ^ ^ ^
12570/// Min HoleMin HoleMax Max
12571///
12572/// ... where there is only a hole if a signed type is promoted to unsigned
12573/// (in which case Min and Max are the smallest and largest representable
12574/// values).
12575struct PromotedRange {
12576 // Min, or HoleMax if there is a hole.
12577 llvm::APSInt PromotedMin;
12578 // Max, or HoleMin if there is a hole.
12579 llvm::APSInt PromotedMax;
12580
12581 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12582 if (R.Width == 0)
12583 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12584 else if (R.Width >= BitWidth && !Unsigned) {
12585 // Promotion made the type *narrower*. This happens when promoting
12586 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12587 // Treat all values of 'signed int' as being in range for now.
12588 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
12589 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
12590 } else {
12591 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
12592 .extOrTrunc(BitWidth);
12593 PromotedMin.setIsUnsigned(Unsigned);
12594
12595 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
12596 .extOrTrunc(BitWidth);
12597 PromotedMax.setIsUnsigned(Unsigned);
12598 }
12599 }
12600
12601 // Determine whether this range is contiguous (has no hole).
12602 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12603
12604 // Where a constant value is within the range.
12605 enum ComparisonResult {
12606 LT = 0x1,
12607 LE = 0x2,
12608 GT = 0x4,
12609 GE = 0x8,
12610 EQ = 0x10,
12611 NE = 0x20,
12612 InRangeFlag = 0x40,
12613
12614 Less = LE | LT | NE,
12615 Min = LE | InRangeFlag,
12616 InRange = InRangeFlag,
12617 Max = GE | InRangeFlag,
12618 Greater = GE | GT | NE,
12619
12620 OnlyValue = LE | GE | EQ | InRangeFlag,
12621 InHole = NE
12622 };
12623
12624 ComparisonResult compare(const llvm::APSInt &Value) const {
12625 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12626 Value.isUnsigned() == PromotedMin.isUnsigned());
12627 if (!isContiguous()) {
12628 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12629 if (Value.isMinValue()) return Min;
12630 if (Value.isMaxValue()) return Max;
12631 if (Value >= PromotedMin) return InRange;
12632 if (Value <= PromotedMax) return InRange;
12633 return InHole;
12634 }
12635
12636 switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
12637 case -1: return Less;
12638 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12639 case 1:
12640 switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
12641 case -1: return InRange;
12642 case 0: return Max;
12643 case 1: return Greater;
12644 }
12645 }
12646
12647 llvm_unreachable("impossible compare result");
12648 }
12649
12650 static std::optional<StringRef>
12651 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12652 if (Op == BO_Cmp) {
12653 ComparisonResult LTFlag = LT, GTFlag = GT;
12654 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12655
12656 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12657 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12658 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12659 return std::nullopt;
12660 }
12661
12662 ComparisonResult TrueFlag, FalseFlag;
12663 if (Op == BO_EQ) {
12664 TrueFlag = EQ;
12665 FalseFlag = NE;
12666 } else if (Op == BO_NE) {
12667 TrueFlag = NE;
12668 FalseFlag = EQ;
12669 } else {
12670 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12671 TrueFlag = LT;
12672 FalseFlag = GE;
12673 } else {
12674 TrueFlag = GT;
12675 FalseFlag = LE;
12676 }
12677 if (Op == BO_GE || Op == BO_LE)
12678 std::swap(TrueFlag, FalseFlag);
12679 }
12680 if (R & TrueFlag)
12681 return StringRef("true");
12682 if (R & FalseFlag)
12683 return StringRef("false");
12684 return std::nullopt;
12685 }
12686};
12687}
12688
12689static bool HasEnumType(const Expr *E) {
12690 // Strip off implicit integral promotions.
12691 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12692 if (ICE->getCastKind() != CK_IntegralCast &&
12693 ICE->getCastKind() != CK_NoOp)
12694 break;
12695 E = ICE->getSubExpr();
12696 }
12697
12698 return E->getType()->isEnumeralType();
12699}
12700
12702 // The values of this enumeration are used in the diagnostics
12703 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12704 enum ConstantValueKind {
12705 Miscellaneous = 0,
12706 LiteralTrue,
12707 LiteralFalse
12708 };
12709 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
12710 return BL->getValue() ? ConstantValueKind::LiteralTrue
12711 : ConstantValueKind::LiteralFalse;
12712 return ConstantValueKind::Miscellaneous;
12713}
12714
12717 const llvm::APSInt &Value,
12718 bool RhsConstant) {
12720 return false;
12721
12722 Expr *OriginalOther = Other;
12723
12724 Constant = Constant->IgnoreParenImpCasts();
12725 Other = Other->IgnoreParenImpCasts();
12726
12727 // Suppress warnings on tautological comparisons between values of the same
12728 // enumeration type. There are only two ways we could warn on this:
12729 // - If the constant is outside the range of representable values of
12730 // the enumeration. In such a case, we should warn about the cast
12731 // to enumeration type, not about the comparison.
12732 // - If the constant is the maximum / minimum in-range value. For an
12733 // enumeratin type, such comparisons can be meaningful and useful.
12734 if (Constant->getType()->isEnumeralType() &&
12735 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
12736 return false;
12737
12738 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12739 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false);
12740 if (!OtherValueRange)
12741 return false;
12742
12743 QualType OtherT = Other->getType();
12744 if (const auto *AT = OtherT->getAs<AtomicType>())
12745 OtherT = AT->getValueType();
12746 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
12747
12748 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12749 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12750 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12751 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) &&
12752 OtherT->isSpecificBuiltinType(BuiltinType::SChar);
12753
12754 // Whether we're treating Other as being a bool because of the form of
12755 // expression despite it having another type (typically 'int' in C).
12756 bool OtherIsBooleanDespiteType =
12757 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12758 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12759 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12760
12761 // Check if all values in the range of possible values of this expression
12762 // lead to the same comparison outcome.
12763 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12764 Value.isUnsigned());
12765 auto Cmp = OtherPromotedValueRange.compare(Value);
12766 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
12767 if (!Result)
12768 return false;
12769
12770 // Also consider the range determined by the type alone. This allows us to
12771 // classify the warning under the proper diagnostic group.
12772 bool TautologicalTypeCompare = false;
12773 {
12774 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12775 Value.isUnsigned());
12776 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12777 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
12778 RhsConstant)) {
12779 TautologicalTypeCompare = true;
12780 Cmp = TypeCmp;
12782 }
12783 }
12784
12785 // Don't warn if the non-constant operand actually always evaluates to the
12786 // same value.
12787 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12788 return false;
12789
12790 // Suppress the diagnostic for an in-range comparison if the constant comes
12791 // from a macro or enumerator. We don't want to diagnose
12792 //
12793 // some_long_value <= INT_MAX
12794 //
12795 // when sizeof(int) == sizeof(long).
12796 bool InRange = Cmp & PromotedRange::InRangeFlag;
12797 if (InRange && IsEnumConstOrFromMacro(S, Constant))
12798 return false;
12799
12800 // A comparison of an unsigned bit-field against 0 is really a type problem,
12801 // even though at the type level the bit-field might promote to 'signed int'.
12802 if (Other->refersToBitField() && InRange && Value == 0 &&
12803 Other->getType()->isUnsignedIntegerOrEnumerationType())
12804 TautologicalTypeCompare = true;
12805
12806 // If this is a comparison to an enum constant, include that
12807 // constant in the diagnostic.
12808 const EnumConstantDecl *ED = nullptr;
12809 if (const auto *DR = dyn_cast<DeclRefExpr>(Constant))
12810 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12811
12812 // Should be enough for uint128 (39 decimal digits)
12813 SmallString<64> PrettySourceValue;
12814 llvm::raw_svector_ostream OS(PrettySourceValue);
12815 if (ED) {
12816 OS << '\'' << *ED << "' (" << Value << ")";
12817 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12818 Constant->IgnoreParenImpCasts())) {
12819 OS << (BL->getValue() ? "YES" : "NO");
12820 } else {
12821 OS << Value;
12822 }
12823
12824 if (!TautologicalTypeCompare) {
12825 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
12826 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12827 << E->getOpcodeStr() << OS.str() << *Result
12828 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12829 return true;
12830 }
12831
12832 if (IsObjCSignedCharBool) {
12834 S.PDiag(diag::warn_tautological_compare_objc_bool)
12835 << OS.str() << *Result);
12836 return true;
12837 }
12838
12839 // FIXME: We use a somewhat different formatting for the in-range cases and
12840 // cases involving boolean values for historical reasons. We should pick a
12841 // consistent way of presenting these diagnostics.
12842 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12843
12845 E->getOperatorLoc(), E,
12846 S.PDiag(!InRange ? diag::warn_out_of_range_compare
12847 : diag::warn_tautological_bool_compare)
12848 << OS.str() << classifyConstantValue(Constant) << OtherT
12849 << OtherIsBooleanDespiteType << *Result
12850 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12851 } else {
12852 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12853 unsigned Diag =
12854 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12855 ? (HasEnumType(OriginalOther)
12856 ? diag::warn_unsigned_enum_always_true_comparison
12857 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12858 : diag::warn_unsigned_always_true_comparison)
12859 : diag::warn_tautological_constant_compare;
12860
12861 S.Diag(E->getOperatorLoc(), Diag)
12862 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12863 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12864 }
12865
12866 return true;
12867}
12868
12869/// Analyze the operands of the given comparison. Implements the
12870/// fallback case from AnalyzeComparison.
12875
12876/// Implements -Wsign-compare.
12877///
12878/// \param E the binary operator to check for warnings
12880 // The type the comparison is being performed in.
12881 QualType T = E->getLHS()->getType();
12882
12883 // Only analyze comparison operators where both sides have been converted to
12884 // the same type.
12886 return AnalyzeImpConvsInComparison(S, E);
12887
12888 // Don't analyze value-dependent comparisons directly.
12889 if (E->isValueDependent())
12890 return AnalyzeImpConvsInComparison(S, E);
12891
12892 Expr *LHS = E->getLHS();
12893 Expr *RHS = E->getRHS();
12894
12895 if (T->isIntegralType(S.Context)) {
12896 std::optional<llvm::APSInt> RHSValue =
12898 std::optional<llvm::APSInt> LHSValue =
12900
12901 // We don't care about expressions whose result is a constant.
12902 if (RHSValue && LHSValue)
12903 return AnalyzeImpConvsInComparison(S, E);
12904
12905 // We only care about expressions where just one side is literal
12906 if ((bool)RHSValue ^ (bool)LHSValue) {
12907 // Is the constant on the RHS or LHS?
12908 const bool RhsConstant = (bool)RHSValue;
12909 Expr *Const = RhsConstant ? RHS : LHS;
12910 Expr *Other = RhsConstant ? LHS : RHS;
12911 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12912
12913 // Check whether an integer constant comparison results in a value
12914 // of 'true' or 'false'.
12915 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12916 return AnalyzeImpConvsInComparison(S, E);
12917 }
12918 }
12919
12920 if (!T->hasUnsignedIntegerRepresentation()) {
12921 // We don't do anything special if this isn't an unsigned integral
12922 // comparison: we're only interested in integral comparisons, and
12923 // signed comparisons only happen in cases we don't care to warn about.
12924 return AnalyzeImpConvsInComparison(S, E);
12925 }
12926
12927 LHS = LHS->IgnoreParenImpCasts();
12928 RHS = RHS->IgnoreParenImpCasts();
12929
12930 if (!S.getLangOpts().CPlusPlus) {
12931 // Avoid warning about comparison of integers with different signs when
12932 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12933 // the type of `E`.
12934 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12935 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12936 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12937 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12938 }
12939
12940 // Check to see if one of the (unmodified) operands is of different
12941 // signedness.
12942 Expr *signedOperand, *unsignedOperand;
12944 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12945 "unsigned comparison between two signed integer expressions?");
12946 signedOperand = LHS;
12947 unsignedOperand = RHS;
12948 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12949 signedOperand = RHS;
12950 unsignedOperand = LHS;
12951 } else {
12952 return AnalyzeImpConvsInComparison(S, E);
12953 }
12954
12955 // Otherwise, calculate the effective range of the signed operand.
12956 std::optional<IntRange> signedRange =
12958 /*Approximate=*/true);
12959 if (!signedRange)
12960 return;
12961
12962 // Go ahead and analyze implicit conversions in the operands. Note
12963 // that we skip the implicit conversions on both sides.
12966
12967 // If the signed range is non-negative, -Wsign-compare won't fire.
12968 if (signedRange->NonNegative)
12969 return;
12970
12971 // For (in)equality comparisons, if the unsigned operand is a
12972 // constant which cannot collide with a overflowed signed operand,
12973 // then reinterpreting the signed operand as unsigned will not
12974 // change the result of the comparison.
12975 if (E->isEqualityOp()) {
12976 unsigned comparisonWidth = S.Context.getIntWidth(T);
12977 std::optional<IntRange> unsignedRange = TryGetExprRange(
12978 S.Context, unsignedOperand, S.isConstantEvaluatedContext(),
12979 /*Approximate=*/true);
12980 if (!unsignedRange)
12981 return;
12982
12983 // We should never be unable to prove that the unsigned operand is
12984 // non-negative.
12985 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12986
12987 if (unsignedRange->Width < comparisonWidth)
12988 return;
12989 }
12990
12992 S.PDiag(diag::warn_mixed_sign_comparison)
12993 << LHS->getType() << RHS->getType()
12994 << LHS->getSourceRange() << RHS->getSourceRange());
12995}
12996
12997/// Analyzes an attempt to assign the given value to a bitfield.
12998///
12999/// Returns true if there was something fishy about the attempt.
13001 SourceLocation InitLoc) {
13002 assert(Bitfield->isBitField());
13003 if (Bitfield->isInvalidDecl())
13004 return false;
13005
13006 // White-list bool bitfields.
13007 QualType BitfieldType = Bitfield->getType();
13008 if (BitfieldType->isBooleanType())
13009 return false;
13010
13011 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
13012 // If the underlying enum type was not explicitly specified as an unsigned
13013 // type and the enum contain only positive values, MSVC++ will cause an
13014 // inconsistency by storing this as a signed type.
13015 if (S.getLangOpts().CPlusPlus11 &&
13016 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
13017 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
13018 BitfieldEnumDecl->getNumNegativeBits() == 0) {
13019 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
13020 << BitfieldEnumDecl;
13021 }
13022 }
13023
13024 // Ignore value- or type-dependent expressions.
13025 if (Bitfield->getBitWidth()->isValueDependent() ||
13026 Bitfield->getBitWidth()->isTypeDependent() ||
13027 Init->isValueDependent() ||
13028 Init->isTypeDependent())
13029 return false;
13030
13031 Expr *OriginalInit = Init->IgnoreParenImpCasts();
13032 unsigned FieldWidth = Bitfield->getBitWidthValue();
13033
13035 if (!OriginalInit->EvaluateAsInt(Result, S.Context,
13037 // The RHS is not constant. If the RHS has an enum type, make sure the
13038 // bitfield is wide enough to hold all the values of the enum without
13039 // truncation.
13040 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
13041 const PreferredTypeAttr *PTAttr = nullptr;
13042 if (!ED) {
13043 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
13044 if (PTAttr)
13045 ED = PTAttr->getType()->getAsEnumDecl();
13046 }
13047 if (ED) {
13048 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
13049
13050 // Enum types are implicitly signed on Windows, so check if there are any
13051 // negative enumerators to see if the enum was intended to be signed or
13052 // not.
13053 bool SignedEnum = ED->getNumNegativeBits() > 0;
13054
13055 // Check for surprising sign changes when assigning enum values to a
13056 // bitfield of different signedness. If the bitfield is signed and we
13057 // have exactly the right number of bits to store this unsigned enum,
13058 // suggest changing the enum to an unsigned type. This typically happens
13059 // on Windows where unfixed enums always use an underlying type of 'int'.
13060 unsigned DiagID = 0;
13061 if (SignedEnum && !SignedBitfield) {
13062 DiagID =
13063 PTAttr == nullptr
13064 ? diag::warn_unsigned_bitfield_assigned_signed_enum
13065 : diag::
13066 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
13067 } else if (SignedBitfield && !SignedEnum &&
13068 ED->getNumPositiveBits() == FieldWidth) {
13069 DiagID =
13070 PTAttr == nullptr
13071 ? diag::warn_signed_bitfield_enum_conversion
13072 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
13073 }
13074 if (DiagID) {
13075 S.Diag(InitLoc, DiagID) << Bitfield << ED;
13076 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
13077 SourceRange TypeRange =
13078 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
13079 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
13080 << SignedEnum << TypeRange;
13081 if (PTAttr)
13082 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
13083 << ED;
13084 }
13085
13086 // Compute the required bitwidth. If the enum has negative values, we need
13087 // one more bit than the normal number of positive bits to represent the
13088 // sign bit.
13089 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
13090 ED->getNumNegativeBits())
13091 : ED->getNumPositiveBits();
13092
13093 // Check the bitwidth.
13094 if (BitsNeeded > FieldWidth) {
13095 Expr *WidthExpr = Bitfield->getBitWidth();
13096 auto DiagID =
13097 PTAttr == nullptr
13098 ? diag::warn_bitfield_too_small_for_enum
13099 : diag::warn_preferred_type_bitfield_too_small_for_enum;
13100 S.Diag(InitLoc, DiagID) << Bitfield << ED;
13101 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
13102 << BitsNeeded << ED << WidthExpr->getSourceRange();
13103 if (PTAttr)
13104 S.Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
13105 << ED;
13106 }
13107 }
13108
13109 return false;
13110 }
13111
13112 llvm::APSInt Value = Result.Val.getInt();
13113
13114 unsigned OriginalWidth = Value.getBitWidth();
13115
13116 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
13117 // false positives where the user is demonstrating they intend to use the
13118 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
13119 // to a one-bit bit-field to see if the value came from a macro named 'true'.
13120 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
13121 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
13122 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
13123 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
13124 S.findMacroSpelling(MaybeMacroLoc, "true"))
13125 return false;
13126 }
13127
13128 if (!Value.isSigned() || Value.isNegative())
13129 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
13130 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
13131 OriginalWidth = Value.getSignificantBits();
13132
13133 if (OriginalWidth <= FieldWidth)
13134 return false;
13135
13136 // Compute the value which the bitfield will contain.
13137 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
13138 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
13139
13140 // Check whether the stored value is equal to the original value.
13141 TruncatedValue = TruncatedValue.extend(OriginalWidth);
13142 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
13143 return false;
13144
13145 std::string PrettyValue = toString(Value, 10);
13146 std::string PrettyTrunc = toString(TruncatedValue, 10);
13147
13148 S.Diag(InitLoc, OneAssignedToOneBitBitfield
13149 ? diag::warn_impcast_single_bit_bitield_precision_constant
13150 : diag::warn_impcast_bitfield_precision_constant)
13151 << PrettyValue << PrettyTrunc << OriginalInit->getType()
13152 << Init->getSourceRange();
13153
13154 return true;
13155}
13156
13157/// Analyze the given simple or compound assignment for warning-worthy
13158/// operations.
13160 // Just recurse on the LHS.
13162
13163 // We want to recurse on the RHS as normal unless we're assigning to
13164 // a bitfield.
13165 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
13166 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
13167 E->getOperatorLoc())) {
13168 // Recurse, ignoring any implicit conversions on the RHS.
13170 E->getOperatorLoc());
13171 }
13172 }
13173
13174 // Set context flag for overflow behavior type assignment analysis, use RAII
13175 // pattern to handle nested assignments.
13176 llvm::SaveAndRestore OBTAssignmentContext(
13178
13180
13181 // Diagnose implicitly sequentially-consistent atomic assignment.
13182 if (E->getLHS()->getType()->isAtomicType())
13183 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13184}
13185
13186/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13187static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
13188 QualType T, SourceLocation CContext, unsigned diag,
13189 bool PruneControlFlow = false) {
13190 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
13191 // address space annotations isn't really useful. The warnings aren't because
13192 // you're converting a `private int` to `unsigned int`, it is because you're
13193 // conerting `int` to `unsigned int`.
13194 if (SourceType.hasAddressSpace())
13195 SourceType = S.getASTContext().removeAddrSpaceQualType(SourceType);
13196 if (T.hasAddressSpace())
13198 if (PruneControlFlow) {
13200 S.PDiag(diag)
13201 << SourceType << T << E->getSourceRange()
13202 << SourceRange(CContext));
13203 return;
13204 }
13205 S.Diag(E->getExprLoc(), diag)
13206 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
13207}
13208
13209/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13210static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
13211 SourceLocation CContext, unsigned diag,
13212 bool PruneControlFlow = false) {
13213 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, PruneControlFlow);
13214}
13215
13216/// Diagnose an implicit cast from a floating point value to an integer value.
13217static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
13218 SourceLocation CContext) {
13219 bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
13220 bool PruneWarnings = S.inTemplateInstantiation();
13221
13222 const Expr *InnerE = E->IgnoreParenImpCasts();
13223 // We also want to warn on, e.g., "int i = -1.234"
13224 if (const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
13225 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
13226 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
13227
13228 bool IsLiteral = isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
13229
13230 llvm::APFloat Value(0.0);
13231 bool IsConstant =
13233 if (!IsConstant) {
13234 if (S.ObjC().isSignedCharBool(T)) {
13236 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
13237 << E->getType());
13238 }
13239
13240 return DiagnoseImpCast(S, E, T, CContext,
13241 diag::warn_impcast_float_integer, PruneWarnings);
13242 }
13243
13244 bool isExact = false;
13245
13246 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
13247 T->hasUnsignedIntegerRepresentation());
13248 llvm::APFloat::opStatus Result = Value.convertToInteger(
13249 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
13250
13251 // FIXME: Force the precision of the source value down so we don't print
13252 // digits which are usually useless (we don't really care here if we
13253 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
13254 // would automatically print the shortest representation, but it's a bit
13255 // tricky to implement.
13256 SmallString<16> PrettySourceValue;
13257 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
13258 precision = (precision * 59 + 195) / 196;
13259 Value.toString(PrettySourceValue, precision);
13260
13261 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) {
13263 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
13264 << PrettySourceValue);
13265 }
13266
13267 if (Result == llvm::APFloat::opOK && isExact) {
13268 if (IsLiteral) return;
13269 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
13270 PruneWarnings);
13271 }
13272
13273 // Conversion of a floating-point value to a non-bool integer where the
13274 // integral part cannot be represented by the integer type is undefined.
13275 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
13276 return DiagnoseImpCast(
13277 S, E, T, CContext,
13278 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13279 : diag::warn_impcast_float_to_integer_out_of_range,
13280 PruneWarnings);
13281
13282 unsigned DiagID = 0;
13283 if (IsLiteral) {
13284 // Warn on floating point literal to integer.
13285 DiagID = diag::warn_impcast_literal_float_to_integer;
13286 } else if (IntegerValue == 0) {
13287 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
13288 return DiagnoseImpCast(S, E, T, CContext,
13289 diag::warn_impcast_float_integer, PruneWarnings);
13290 }
13291 // Warn on non-zero to zero conversion.
13292 DiagID = diag::warn_impcast_float_to_integer_zero;
13293 } else {
13294 if (IntegerValue.isUnsigned()) {
13295 if (!IntegerValue.isMaxValue()) {
13296 return DiagnoseImpCast(S, E, T, CContext,
13297 diag::warn_impcast_float_integer, PruneWarnings);
13298 }
13299 } else { // IntegerValue.isSigned()
13300 if (!IntegerValue.isMaxSignedValue() &&
13301 !IntegerValue.isMinSignedValue()) {
13302 return DiagnoseImpCast(S, E, T, CContext,
13303 diag::warn_impcast_float_integer, PruneWarnings);
13304 }
13305 }
13306 // Warn on evaluatable floating point expression to integer conversion.
13307 DiagID = diag::warn_impcast_float_to_integer;
13308 }
13309
13310 SmallString<16> PrettyTargetValue;
13311 if (IsBool)
13312 PrettyTargetValue = Value.isZero() ? "false" : "true";
13313 else
13314 IntegerValue.toString(PrettyTargetValue);
13315
13316 if (PruneWarnings) {
13318 S.PDiag(DiagID)
13319 << E->getType() << T.getUnqualifiedType()
13320 << PrettySourceValue << PrettyTargetValue
13321 << E->getSourceRange() << SourceRange(CContext));
13322 } else {
13323 S.Diag(E->getExprLoc(), DiagID)
13324 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
13325 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
13326 }
13327}
13328
13329/// Analyze the given compound assignment for the possible losing of
13330/// floating-point precision.
13332 assert(isa<CompoundAssignOperator>(E) &&
13333 "Must be compound assignment operation");
13334 // Recurse on the LHS and RHS in here
13337
13338 if (E->getLHS()->getType()->isAtomicType())
13339 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
13340
13341 // Now check the outermost expression
13342 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13343 const auto *RBT = cast<CompoundAssignOperator>(E)
13344 ->getComputationResultType()
13345 ->getAs<BuiltinType>();
13346
13347 // The below checks assume source is floating point.
13348 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13349
13350 // If source is floating point but target is an integer.
13351 if (ResultBT->isInteger())
13352 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
13353 E->getExprLoc(), diag::warn_impcast_float_integer);
13354
13355 if (!ResultBT->isFloatingPoint())
13356 return;
13357
13358 // If both source and target are floating points, warn about losing precision.
13360 QualType(ResultBT, 0), QualType(RBT, 0));
13361 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
13362 // warn about dropping FP rank.
13363 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
13364 diag::warn_impcast_float_result_precision);
13365}
13366
13367static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13368 IntRange Range) {
13369 if (!Range.Width) return "0";
13370
13371 llvm::APSInt ValueInRange = Value;
13372 ValueInRange.setIsSigned(!Range.NonNegative);
13373 ValueInRange = ValueInRange.trunc(Range.Width);
13374 return toString(ValueInRange, 10);
13375}
13376
13377static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
13378 bool ToBool) {
13379 if (!isa<ImplicitCastExpr>(Ex))
13380 return false;
13381
13382 const Expr *InnerE = Ex->IgnoreParenImpCasts();
13384 const Type *Source =
13386 if (Target->isDependentType())
13387 return false;
13388
13389 const auto *FloatCandidateBT =
13390 dyn_cast<BuiltinType>(ToBool ? Source : Target);
13391 const Type *BoolCandidateType = ToBool ? Target : Source;
13392
13393 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
13394 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13395}
13396
13397static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
13398 SourceLocation CC) {
13399 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
13400 const Expr *CurrA = TheCall->getArg(I);
13401 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
13402 continue;
13403
13404 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
13405 S, TheCall->getArg(I - 1), false));
13406 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
13407 S, TheCall->getArg(I + 1), false));
13408 if (IsSwapped) {
13409 // Warn on this floating-point to bool conversion.
13411 CurrA->getType(), CC,
13412 diag::warn_impcast_floating_point_to_bool);
13413 }
13414 }
13415}
13416
13418 SourceLocation CC) {
13419 // Don't warn on functions which have return type nullptr_t.
13420 if (isa<CallExpr>(E))
13421 return;
13422
13423 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13424 const Expr *NewE = E->IgnoreParenImpCasts();
13425 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE);
13426 bool HasNullPtrType = NewE->getType()->isNullPtrType();
13427 if (!IsGNUNullExpr && !HasNullPtrType)
13428 return;
13429
13430 // Return if target type is a safe conversion.
13431 if (T->isAnyPointerType() || T->isBlockPointerType() ||
13432 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13433 return;
13434
13435 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
13436 E->getExprLoc()))
13437 return;
13438
13440
13441 // Venture through the macro stacks to get to the source of macro arguments.
13442 // The new location is a better location than the complete location that was
13443 // passed in.
13444 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13446
13447 // __null is usually wrapped in a macro. Go up a macro if that is the case.
13448 if (IsGNUNullExpr && Loc.isMacroID()) {
13449 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13450 Loc, S.SourceMgr, S.getLangOpts());
13451 if (MacroName == "NULL")
13453 }
13454
13455 // Only warn if the null and context location are in the same macro expansion.
13456 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
13457 return;
13458
13459 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
13460 << HasNullPtrType << T << SourceRange(CC)
13463}
13464
13465// Helper function to filter out cases for constant width constant conversion.
13466// Don't warn on unsigned char array initialization or for non-decimal
13467// values.
13469 SourceLocation CC) {
13470 // If initializing from a constant, and the constant starts with '0',
13471 // then it is a binary, octal, or hexadecimal. Allow these constants
13472 // to fill all the bits, even if there is a sign change.
13473 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
13474 const char FirstLiteralCharacter =
13475 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
13476 if (FirstLiteralCharacter == '0')
13477 return false;
13478 }
13479
13480 // If the CC location points to a '{' and the type is an unsigned char
13481 // type, assume it is an array initialization.
13482 if (T->isCharType() && !T->isSignedIntegerType() && CC.isValid()) {
13483 const char FirstContextCharacter =
13485 if (FirstContextCharacter == '{')
13486 return false;
13487 }
13488
13489 return true;
13490}
13491
13493 const auto *IL = dyn_cast<IntegerLiteral>(E);
13494 if (!IL) {
13495 if (auto *UO = dyn_cast<UnaryOperator>(E)) {
13496 if (UO->getOpcode() == UO_Minus)
13497 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13498 }
13499 }
13500
13501 return IL;
13502}
13503
13505 E = E->IgnoreParenImpCasts();
13506 SourceLocation ExprLoc = E->getExprLoc();
13507
13508 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
13509 BinaryOperator::Opcode Opc = BO->getOpcode();
13511 // Do not diagnose unsigned shifts.
13512 if (Opc == BO_Shl) {
13513 const auto *LHS = getIntegerLiteral(BO->getLHS());
13514 const auto *RHS = getIntegerLiteral(BO->getRHS());
13515 if (LHS && LHS->getValue() == 0)
13516 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13517 else if (!E->isValueDependent() && LHS && RHS &&
13518 RHS->getValue().isNonNegative() &&
13520 S.Diag(ExprLoc, diag::warn_left_shift_always)
13521 << (Result.Val.getInt() != 0);
13522 else if (E->getType()->isSignedIntegerType())
13523 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
13526 ") != 0");
13527 }
13528 }
13529
13530 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13531 const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
13532 const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
13533 if (!LHS || !RHS)
13534 return;
13535 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13536 (RHS->getValue() == 0 || RHS->getValue() == 1))
13537 // Do not diagnose common idioms.
13538 return;
13539 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13540 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13541 }
13542}
13543
13545 const Type *Target, Expr *E,
13546 QualType T,
13547 SourceLocation CC) {
13548 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13549 Source != Target);
13550
13551 // Lone surrogates have a distinct representation in UTF-32.
13552 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13553 // so don't warn on such conversion.
13554 if (Source->isChar16Type() && Target->isChar32Type())
13555 return;
13556
13560 llvm::APSInt Value(32);
13561 Value = Result.Val.getInt();
13562 bool IsASCII = Value <= 0x7F;
13563 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13564 bool ConversionPreservesSemantics =
13565 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13566
13567 if (!ConversionPreservesSemantics) {
13568 auto IsSingleCodeUnitCP = [](const QualType &T,
13569 const llvm::APSInt &Value) {
13570 if (T->isChar8Type())
13571 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13572 if (T->isChar16Type())
13573 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13574 assert(T->isChar32Type());
13575 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13576 };
13577
13578 S.Diag(CC, diag::warn_impcast_unicode_char_type_constant)
13579 << E->getType() << T
13580 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13581 << FormatUTFCodeUnitAsCodepoint(Value.getExtValue(), E->getType());
13582 }
13583 } else {
13584 bool LosesPrecision = S.getASTContext().getIntWidth(E->getType()) >
13586 DiagnoseImpCast(S, E, T, CC,
13587 LosesPrecision ? diag::warn_impcast_unicode_precision
13588 : diag::warn_impcast_unicode_char_type);
13589 }
13590}
13591
13593 From = Context.getCanonicalType(From);
13594 To = Context.getCanonicalType(To);
13595 QualType MaybePointee = From->getPointeeType();
13596 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13597 From = MaybePointee;
13598 MaybePointee = To->getPointeeType();
13599 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13600 To = MaybePointee;
13601
13602 if (const auto *FromFn = From->getAs<FunctionType>()) {
13603 if (const auto *ToFn = To->getAs<FunctionType>()) {
13604 if (FromFn->getCFIUncheckedCalleeAttr() &&
13605 !ToFn->getCFIUncheckedCalleeAttr())
13606 return true;
13607 }
13608 }
13609 return false;
13610}
13611
13613 bool *ICContext, bool IsListInit) {
13614 if (E->isTypeDependent() || E->isValueDependent()) return;
13615
13616 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
13617 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13618 if (Source == Target) return;
13619 if (Target->isDependentType()) return;
13620
13621 // If the conversion context location is invalid don't complain. We also
13622 // don't want to emit a warning if the issue occurs from the expansion of
13623 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13624 // delay this check as long as possible. Once we detect we are in that
13625 // scenario, we just return.
13626 if (CC.isInvalid())
13627 return;
13628
13629 if (Source->isAtomicType())
13630 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
13631
13632 // Diagnose implicit casts to bool.
13633 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13634 if (isa<StringLiteral>(E))
13635 // Warn on string literal to bool. Checks for string literals in logical
13636 // and expressions, for instance, assert(0 && "error here"), are
13637 // prevented by a check in AnalyzeImplicitConversions().
13638 return DiagnoseImpCast(*this, E, T, CC,
13639 diag::warn_impcast_string_literal_to_bool);
13642 // This covers the literal expressions that evaluate to Objective-C
13643 // objects.
13644 return DiagnoseImpCast(*this, E, T, CC,
13645 diag::warn_impcast_objective_c_literal_to_bool);
13646 }
13647 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13648 // Warn on pointer to bool conversion that is always true.
13650 SourceRange(CC));
13651 }
13652 }
13653
13655
13656 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13657 // is a typedef for signed char (macOS), then that constant value has to be 1
13658 // or 0.
13659 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) {
13662 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13664 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13665 << toString(Result.Val.getInt(), 10));
13666 }
13667 return;
13668 }
13669 }
13670
13671 // Check implicit casts from Objective-C collection literals to specialized
13672 // collection types, e.g., NSArray<NSString *> *.
13673 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13674 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral);
13675 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13676 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral);
13677
13678 // Strip complex types.
13679 if (isa<ComplexType>(Source)) {
13680 if (!isa<ComplexType>(Target)) {
13681 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
13682 return;
13683
13684 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13685 return DiagnoseImpCast(*this, E, T, CC,
13686 diag::err_impcast_incompatible_type);
13687 }
13688
13689 return DiagnoseImpCast(*this, E, T, CC,
13691 ? diag::err_impcast_complex_scalar
13692 : diag::warn_impcast_complex_scalar);
13693 }
13694
13695 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
13696 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
13697 }
13698
13699 // Strip vector types.
13700 if (isa<VectorType>(Source)) {
13701 if (Target->isSveVLSBuiltinType() &&
13702 (ARM().areCompatibleSveTypes(QualType(Target, 0),
13703 QualType(Source, 0)) ||
13704 ARM().areLaxCompatibleSveTypes(QualType(Target, 0),
13705 QualType(Source, 0))))
13706 return;
13707
13708 if (Target->isRVVVLSBuiltinType() &&
13709 (Context.areCompatibleRVVTypes(QualType(Target, 0),
13710 QualType(Source, 0)) ||
13711 Context.areLaxCompatibleRVVTypes(QualType(Target, 0),
13712 QualType(Source, 0))))
13713 return;
13714
13715 if (!isa<VectorType>(Target)) {
13716 if (SourceMgr.isInSystemMacro(CC))
13717 return;
13718 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar);
13719 }
13720 if (getLangOpts().HLSL &&
13721 Target->castAs<VectorType>()->getNumElements() <
13722 Source->castAs<VectorType>()->getNumElements()) {
13723 // Diagnose vector truncation but don't return. We may also want to
13724 // diagnose an element conversion.
13725 DiagnoseImpCast(*this, E, T, CC,
13726 diag::warn_hlsl_impcast_vector_truncation);
13727 }
13728
13729 // If the vector cast is cast between two vectors of the same size, it is
13730 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13731 if (!getLangOpts().HLSL &&
13732 Context.getTypeSize(Source) == Context.getTypeSize(Target))
13733 return;
13734
13735 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
13736 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
13737 }
13738 if (const auto *VecTy = dyn_cast<VectorType>(Target))
13739 Target = VecTy->getElementType().getTypePtr();
13740
13741 // Strip matrix types.
13742 if (isa<ConstantMatrixType>(Source)) {
13743 if (Target->isScalarType())
13744 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_matrix_scalar);
13745
13748 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13749 // Diagnose Matrix truncation but don't return. We may also want to
13750 // diagnose an element conversion.
13751 DiagnoseImpCast(*this, E, T, CC,
13752 diag::warn_hlsl_impcast_matrix_truncation);
13753 }
13754
13755 Source = cast<ConstantMatrixType>(Source)->getElementType().getTypePtr();
13756 Target = cast<ConstantMatrixType>(Target)->getElementType().getTypePtr();
13757 }
13758 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Target))
13759 Target = MatTy->getElementType().getTypePtr();
13760
13761 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13762 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
13763
13764 // Strip SVE vector types
13765 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13766 // Need the original target type for vector type checks
13767 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13768 // Handle conversion from scalable to fixed when msve-vector-bits is
13769 // specified
13770 if (ARM().areCompatibleSveTypes(QualType(OriginalTarget, 0),
13771 QualType(Source, 0)) ||
13772 ARM().areLaxCompatibleSveTypes(QualType(OriginalTarget, 0),
13773 QualType(Source, 0)))
13774 return;
13775
13776 // If the vector cast is cast between two vectors of the same size, it is
13777 // a bitcast, not a conversion.
13778 if (Context.getTypeSize(Source) == Context.getTypeSize(Target))
13779 return;
13780
13781 Source = SourceBT->getSveEltType(Context).getTypePtr();
13782 }
13783
13784 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13785 Target = TargetBT->getSveEltType(Context).getTypePtr();
13786
13787 // Nothing to diagnose if stripping the wrappers left identical element types
13788 // (e.g. a scalar splatted to a vector of its own type).
13789 if (Source == Target)
13790 return;
13791
13792 // If the source is floating point...
13793 if (SourceBT && SourceBT->isFloatingPoint()) {
13794 // ...and the target is floating point...
13795 if (TargetBT && TargetBT->isFloatingPoint()) {
13796 // ...then warn if we're dropping FP rank.
13797
13799 QualType(SourceBT, 0), QualType(TargetBT, 0));
13800 if (Order > 0) {
13801 // Don't warn about float constants that are precisely
13802 // representable in the target type.
13803 Expr::EvalResult result;
13804 if (E->EvaluateAsRValue(result, Context)) {
13805 // Value might be a float, a float vector, or a float complex.
13807 result.Val,
13808 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
13809 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
13810 return;
13811 }
13812
13813 if (SourceMgr.isInSystemMacro(CC))
13814 return;
13815
13816 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision);
13817 }
13818 // ... or possibly if we're increasing rank, too
13819 else if (Order < 0) {
13820 if (SourceMgr.isInSystemMacro(CC))
13821 return;
13822
13823 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion);
13824 }
13825 return;
13826 }
13827
13828 // If the target is integral, always warn.
13829 if (TargetBT && TargetBT->isInteger()) {
13830 if (SourceMgr.isInSystemMacro(CC))
13831 return;
13832
13833 DiagnoseFloatingImpCast(*this, E, T, CC);
13834 }
13835
13836 // Detect the case where a call result is converted from floating-point to
13837 // to bool, and the final argument to the call is converted from bool, to
13838 // discover this typo:
13839 //
13840 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13841 //
13842 // FIXME: This is an incredibly special case; is there some more general
13843 // way to detect this class of misplaced-parentheses bug?
13844 if (Target->isBooleanType() && isa<CallExpr>(E)) {
13845 // Check last argument of function call to see if it is an
13846 // implicit cast from a type matching the type the result
13847 // is being cast to.
13848 CallExpr *CEx = cast<CallExpr>(E);
13849 if (unsigned NumArgs = CEx->getNumArgs()) {
13850 Expr *LastA = CEx->getArg(NumArgs - 1);
13851 Expr *InnerE = LastA->IgnoreParenImpCasts();
13852 if (isa<ImplicitCastExpr>(LastA) &&
13853 InnerE->getType()->isBooleanType()) {
13854 // Warn on this floating-point to bool conversion
13855 DiagnoseImpCast(*this, E, T, CC,
13856 diag::warn_impcast_floating_point_to_bool);
13857 }
13858 }
13859 }
13860 return;
13861 }
13862
13863 // Valid casts involving fixed point types should be accounted for here.
13864 if (Source->isFixedPointType()) {
13865 if (Target->isUnsaturatedFixedPointType()) {
13869 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13870 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T);
13871 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T);
13872 if (Value > MaxVal || Value < MinVal) {
13874 PDiag(diag::warn_impcast_fixed_point_range)
13875 << Value.toString() << T
13876 << E->getSourceRange()
13877 << clang::SourceRange(CC));
13878 return;
13879 }
13880 }
13881 } else if (Target->isIntegerType()) {
13885 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13886
13887 bool Overflowed;
13888 llvm::APSInt IntResult = FXResult.convertToInt(
13889 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(),
13890 &Overflowed);
13891
13892 if (Overflowed) {
13894 PDiag(diag::warn_impcast_fixed_point_range)
13895 << FXResult.toString() << T
13896 << E->getSourceRange()
13897 << clang::SourceRange(CC));
13898 return;
13899 }
13900 }
13901 }
13902 } else if (Target->isUnsaturatedFixedPointType()) {
13903 if (Source->isIntegerType()) {
13907 llvm::APSInt Value = Result.Val.getInt();
13908
13909 bool Overflowed;
13910 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13911 Value, Context.getFixedPointSemantics(T), &Overflowed);
13912
13913 if (Overflowed) {
13915 PDiag(diag::warn_impcast_fixed_point_range)
13916 << toString(Value, /*Radix=*/10) << T
13917 << E->getSourceRange()
13918 << clang::SourceRange(CC));
13919 return;
13920 }
13921 }
13922 }
13923 }
13924
13925 // If we are casting an integer type to a floating point type without
13926 // initialization-list syntax, we might lose accuracy if the floating
13927 // point type has a narrower significand than the integer type.
13928 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13929 TargetBT->isFloatingType() && !IsListInit) {
13930 // Determine the number of precision bits in the source integer type.
13931 std::optional<IntRange> SourceRange =
13933 /*Approximate=*/true);
13934 if (!SourceRange)
13935 return;
13936 unsigned int SourcePrecision = SourceRange->Width;
13937
13938 // Determine the number of precision bits in the
13939 // target floating point type.
13940 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13941 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13942
13943 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13944 SourcePrecision > TargetPrecision) {
13945
13946 if (std::optional<llvm::APSInt> SourceInt =
13948 // If the source integer is a constant, convert it to the target
13949 // floating point type. Issue a warning if the value changes
13950 // during the whole conversion.
13951 llvm::APFloat TargetFloatValue(
13952 Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13953 llvm::APFloat::opStatus ConversionStatus =
13954 TargetFloatValue.convertFromAPInt(
13955 *SourceInt, SourceBT->isSignedInteger(),
13956 llvm::APFloat::rmNearestTiesToEven);
13957
13958 if (ConversionStatus != llvm::APFloat::opOK) {
13959 SmallString<32> PrettySourceValue;
13960 SourceInt->toString(PrettySourceValue, 10);
13961 SmallString<32> PrettyTargetValue;
13962 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13963
13965 E->getExprLoc(), E,
13966 PDiag(diag::warn_impcast_integer_float_precision_constant)
13967 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13968 << E->getSourceRange() << clang::SourceRange(CC));
13969 }
13970 } else {
13971 // Otherwise, the implicit conversion may lose precision.
13972 DiagnoseImpCast(*this, E, T, CC,
13973 diag::warn_impcast_integer_float_precision);
13974 }
13975 }
13976 }
13977
13978 DiagnoseNullConversion(*this, E, T, CC);
13979
13981
13982 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13983 DiagnoseMixedUnicodeImplicitConversion(*this, Source, Target, E, T, CC);
13984 return;
13985 }
13986
13987 if (Target->isBooleanType())
13988 DiagnoseIntInBoolContext(*this, E);
13989
13991 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
13992 << QualType(Source, 0) << QualType(Target, 0);
13993 }
13994
13995 if (!Source->isIntegerType() || !Target->isIntegerType())
13996 return;
13997
13998 // TODO: remove this early return once the false positives for constant->bool
13999 // in templates, macros, etc, are reduced or removed.
14000 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
14001 return;
14002
14003 if (ObjC().isSignedCharBool(T) && !Source->isCharType() &&
14004 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
14006 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
14007 << E->getType());
14008 }
14009 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
14010 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true);
14011 if (!LikelySourceRange)
14012 return;
14013
14014 IntRange SourceTypeRange =
14015 IntRange::forTargetOfCanonicalType(Context, Source);
14016 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target);
14017
14018 if (LikelySourceRange->Width > TargetRange.Width) {
14019 // Check if target is a wrapping OBT - if so, don't warn about constant
14020 // conversion as this type may be used intentionally with implicit
14021 // truncation, especially during assignments.
14022 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14023 if (TargetOBT->isWrapKind()) {
14024 return;
14025 }
14026 }
14027
14028 // Check if source expression has an explicit __ob_wrap cast because if so,
14029 // wrapping was explicitly requested and we shouldn't warn
14030 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
14031 if (SourceOBT->isWrapKind()) {
14032 return;
14033 }
14034 }
14035
14036 // If the source is a constant, use a default-on diagnostic.
14037 // TODO: this should happen for bitfield stores, too.
14041 llvm::APSInt Value(32);
14042 Value = Result.Val.getInt();
14043
14044 if (SourceMgr.isInSystemMacro(CC))
14045 return;
14046
14047 std::string PrettySourceValue = toString(Value, 10);
14048 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
14049
14051 PDiag(diag::warn_impcast_integer_precision_constant)
14052 << PrettySourceValue << PrettyTargetValue
14053 << E->getType() << T << E->getSourceRange()
14054 << SourceRange(CC));
14055 return;
14056 }
14057
14058 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
14059 if (SourceMgr.isInSystemMacro(CC))
14060 return;
14061
14062 if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
14063 if (UO->getOpcode() == UO_Minus)
14064 return DiagnoseImpCast(
14065 *this, E, T, CC, diag::warn_impcast_integer_precision_on_negation);
14066 }
14067
14068 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64)
14069 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32,
14070 /* pruneControlFlow */ true);
14071 return DiagnoseImpCast(*this, E, T, CC,
14072 diag::warn_impcast_integer_precision);
14073 }
14074
14075 if (TargetRange.Width > SourceTypeRange.Width) {
14076 if (auto *UO = dyn_cast<UnaryOperator>(E))
14077 if (UO->getOpcode() == UO_Minus)
14078 if (Source->isUnsignedIntegerType()) {
14079 if (Target->isUnsignedIntegerType())
14080 return DiagnoseImpCast(*this, E, T, CC,
14081 diag::warn_impcast_high_order_zero_bits);
14082 if (Target->isSignedIntegerType())
14083 return DiagnoseImpCast(*this, E, T, CC,
14084 diag::warn_impcast_nonnegative_result);
14085 }
14086 }
14087
14088 if (TargetRange.Width == LikelySourceRange->Width &&
14089 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
14090 Source->isSignedIntegerType()) {
14091 // Warn when doing a signed to signed conversion, warn if the positive
14092 // source value is exactly the width of the target type, which will
14093 // cause a negative value to be stored.
14094
14097 !SourceMgr.isInSystemMacro(CC)) {
14098 llvm::APSInt Value = Result.Val.getInt();
14099 if (isSameWidthConstantConversion(*this, E, T, CC)) {
14100 std::string PrettySourceValue = toString(Value, 10);
14101 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
14102
14103 Diag(E->getExprLoc(),
14104 PDiag(diag::warn_impcast_integer_precision_constant)
14105 << PrettySourceValue << PrettyTargetValue << E->getType() << T
14106 << E->getSourceRange() << SourceRange(CC));
14107 return;
14108 }
14109 }
14110
14111 // Fall through for non-constants to give a sign conversion warning.
14112 }
14113
14114 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) &&
14115 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
14116 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
14117 LikelySourceRange->Width == TargetRange.Width))) {
14118 if (SourceMgr.isInSystemMacro(CC))
14119 return;
14120
14121 if (SourceBT && SourceBT->isInteger() && TargetBT &&
14122 TargetBT->isInteger() &&
14123 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
14124 return;
14125 }
14126
14127 unsigned DiagID = diag::warn_impcast_integer_sign;
14128
14129 // Traditionally, gcc has warned about this under -Wsign-compare.
14130 // We also want to warn about it in -Wconversion.
14131 // So if -Wconversion is off, use a completely identical diagnostic
14132 // in the sign-compare group.
14133 // The conditional-checking code will
14134 if (ICContext) {
14135 DiagID = diag::warn_impcast_integer_sign_conditional;
14136 *ICContext = true;
14137 }
14138
14139 DiagnoseImpCast(*this, E, T, CC, DiagID);
14140 }
14141
14142 // If we're implicitly converting from an integer into an enumeration, that
14143 // is valid in C but invalid in C++.
14144 QualType SourceType = E->getEnumCoercedType(Context);
14145 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
14146 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Target))
14147 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_int_to_enum);
14148
14149 // Diagnose conversions between different enumeration types.
14150 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
14151 // type, to give us better diagnostics.
14152 Source = Context.getCanonicalType(SourceType).getTypePtr();
14153
14154 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
14155 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
14156 if (SourceEnum->getDecl()->hasNameForLinkage() &&
14157 TargetEnum->getDecl()->hasNameForLinkage() &&
14158 SourceEnum != TargetEnum) {
14159 if (SourceMgr.isInSystemMacro(CC))
14160 return;
14161
14162 return DiagnoseImpCast(*this, E, SourceType, T, CC,
14163 diag::warn_impcast_different_enum_types);
14164 }
14165}
14166
14169
14171 SourceLocation CC, bool &ICContext) {
14172 E = E->IgnoreParenImpCasts();
14173 // Diagnose incomplete type for second or third operand in C.
14174 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
14175 S.RequireCompleteExprType(E, diag::err_incomplete_type);
14176
14177 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
14178 return CheckConditionalOperator(S, CO, CC, T);
14179
14181 if (E->getType() != T)
14182 return S.CheckImplicitConversion(E, T, CC, &ICContext);
14183}
14184
14188
14189 Expr *TrueExpr = E->getTrueExpr();
14190 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
14191 TrueExpr = BCO->getCommon();
14192
14193 bool Suspicious = false;
14194 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
14195 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
14196
14197 if (T->isBooleanType())
14199
14200 // If -Wconversion would have warned about either of the candidates
14201 // for a signedness conversion to the context type...
14202 if (!Suspicious) return;
14203
14204 // ...but it's currently ignored...
14205 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
14206 return;
14207
14208 // ...then check whether it would have warned about either of the
14209 // candidates for a signedness conversion to the condition type.
14210 if (E->getType() == T) return;
14211
14212 Suspicious = false;
14213 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC,
14214 &Suspicious);
14215 if (!Suspicious)
14217 E->getType(), CC, &Suspicious);
14218}
14219
14220/// Check conversion of given expression to boolean.
14221/// Input argument E is a logical expression.
14223 // Run the bool-like conversion checks only for C since there bools are
14224 // still not used as the return type from "boolean" operators or as the input
14225 // type for conditional operators.
14226 if (S.getLangOpts().CPlusPlus)
14227 return;
14229 return;
14231}
14232
14233namespace {
14234struct AnalyzeImplicitConversionsWorkItem {
14235 Expr *E;
14236 SourceLocation CC;
14237 bool IsListInit;
14238};
14239}
14240
14242 Sema &S, Expr *E, QualType T, SourceLocation CC,
14243 bool ExtraCheckForImplicitConversion,
14245 E = E->IgnoreParenImpCasts();
14246 WorkList.push_back({E, CC, false});
14247
14248 if (ExtraCheckForImplicitConversion && E->getType() != T)
14249 S.CheckImplicitConversion(E, T, CC);
14250}
14251
14252/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
14253/// that should be visited are added to WorkList.
14255 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
14257 Expr *OrigE = Item.E;
14258 SourceLocation CC = Item.CC;
14259
14260 QualType T = OrigE->getType();
14261 Expr *E = OrigE->IgnoreParenImpCasts();
14262
14263 // Propagate whether we are in a C++ list initialization expression.
14264 // If so, we do not issue warnings for implicit int-float conversion
14265 // precision loss, because C++11 narrowing already handles it.
14266 //
14267 // HLSL's initialization lists are special, so they shouldn't observe the C++
14268 // behavior here.
14269 bool IsListInit =
14270 Item.IsListInit || (isa<InitListExpr>(OrigE) &&
14271 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
14272
14273 if (E->isTypeDependent() || E->isValueDependent())
14274 return;
14275
14276 Expr *SourceExpr = E;
14277 // Examine, but don't traverse into the source expression of an
14278 // OpaqueValueExpr, since it may have multiple parents and we don't want to
14279 // emit duplicate diagnostics. Its fine to examine the form or attempt to
14280 // evaluate it in the context of checking the specific conversion to T though.
14281 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
14282 if (auto *Src = OVE->getSourceExpr())
14283 SourceExpr = Src;
14284
14285 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
14286 if (UO->getOpcode() == UO_Not &&
14287 UO->getSubExpr()->isKnownToHaveBooleanValue())
14288 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
14289 << OrigE->getSourceRange() << T->isBooleanType()
14290 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
14291
14292 if (auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
14293 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14294 BO->getLHS()->isKnownToHaveBooleanValue() &&
14295 BO->getRHS()->isKnownToHaveBooleanValue() &&
14296 BO->getLHS()->HasSideEffects(S.Context) &&
14297 BO->getRHS()->HasSideEffects(S.Context)) {
14299 const LangOptions &LO = S.getLangOpts();
14300 SourceLocation BLoc = BO->getOperatorLoc();
14301 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO);
14302 StringRef SR = clang::Lexer::getSourceText(
14303 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO);
14304 // To reduce false positives, only issue the diagnostic if the operator
14305 // is explicitly spelled as a punctuator. This suppresses the diagnostic
14306 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
14307 // in C, along with other macro spellings the user might invent.
14308 if (SR.str() == "&" || SR.str() == "|") {
14309
14310 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
14311 << (BO->getOpcode() == BO_And ? "&" : "|")
14312 << OrigE->getSourceRange()
14314 BO->getOperatorLoc(),
14315 (BO->getOpcode() == BO_And ? "&&" : "||"));
14316 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
14317 }
14318 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
14319 /// Analyze the given comma operator. The basic idea behind the analysis
14320 /// is to analyze the left and right operands slightly differently. The
14321 /// left operand needs to check whether the operand itself has an implicit
14322 /// conversion, but not whether the left operand induces an implicit
14323 /// conversion for the entire comma expression itself. This is similar to
14324 /// how CheckConditionalOperand behaves; it's as-if the correct operand
14325 /// were directly used for the implicit conversion check.
14326 CheckCommaOperand(S, BO->getLHS(), T, BO->getOperatorLoc(),
14327 /*ExtraCheckForImplicitConversion=*/false, WorkList);
14328 CheckCommaOperand(S, BO->getRHS(), T, BO->getOperatorLoc(),
14329 /*ExtraCheckForImplicitConversion=*/true, WorkList);
14330 return;
14331 }
14332 }
14333
14334 // For conditional operators, we analyze the arguments as if they
14335 // were being fed directly into the output.
14336 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
14337 CheckConditionalOperator(S, CO, CC, T);
14338 return;
14339 }
14340
14341 // Check implicit argument conversions for function calls.
14342 if (const auto *Call = dyn_cast<CallExpr>(SourceExpr))
14344
14345 // Go ahead and check any implicit conversions we might have skipped.
14346 // The non-canonical typecheck is just an optimization;
14347 // CheckImplicitConversion will filter out dead implicit conversions.
14348 if (SourceExpr->getType() != T)
14349 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit);
14350
14351 // Now continue drilling into this expression.
14352
14353 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
14354 // The bound subexpressions in a PseudoObjectExpr are not reachable
14355 // as transitive children.
14356 // FIXME: Use a more uniform representation for this.
14357 for (auto *SE : POE->semantics())
14358 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
14359 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
14360 }
14361
14362 // Skip past explicit casts.
14363 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
14364 E = CE->getSubExpr();
14365 // In the special case of a C++ function-style cast with braces,
14366 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
14367 // initializer. This InitListExpr basically belongs to the cast itself, so
14368 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
14370 if (auto *InitListE = dyn_cast<InitListExpr>(E)) {
14371 if (InitListE->getNumInits() == 1) {
14372 E = InitListE->getInit(0);
14373 }
14374 }
14375 }
14376 E = E->IgnoreParenImpCasts();
14377 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14378 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
14379 WorkList.push_back({E, CC, IsListInit});
14380 return;
14381 }
14382
14383 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
14384 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
14385 // The base expression is only used to initialize the parameter for
14386 // arguments to `inout` parameters, so we only traverse down the base
14387 // expression for `inout` cases.
14388 if (OutArgE->isInOut())
14389 WorkList.push_back(
14390 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
14391 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
14392 return;
14393 }
14394
14395 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
14396 // Do a somewhat different check with comparison operators.
14397 if (BO->isComparisonOp())
14398 return AnalyzeComparison(S, BO);
14399
14400 // And with simple assignments.
14401 if (BO->getOpcode() == BO_Assign)
14402 return AnalyzeAssignment(S, BO);
14403 // And with compound assignments.
14404 if (BO->isAssignmentOp())
14405 return AnalyzeCompoundAssignment(S, BO);
14406 }
14407
14408 // These break the otherwise-useful invariant below. Fortunately,
14409 // we don't really need to recurse into them, because any internal
14410 // expressions should have been analyzed already when they were
14411 // built into statements.
14412 if (isa<StmtExpr>(E)) return;
14413
14414 // Don't descend into unevaluated contexts.
14415 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
14416
14417 // Now just recurse over the expression's children.
14418 CC = E->getExprLoc();
14419 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
14420 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14421 for (Stmt *SubStmt : E->children()) {
14422 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
14423 if (!ChildExpr)
14424 continue;
14425
14426 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
14427 if (ChildExpr == CSE->getOperand())
14428 // Do not recurse over a CoroutineSuspendExpr's operand.
14429 // The operand is also a subexpression of getCommonExpr(), and
14430 // recursing into it directly would produce duplicate diagnostics.
14431 continue;
14432
14433 if (IsLogicalAndOperator &&
14435 // Ignore checking string literals that are in logical and operators.
14436 // This is a common pattern for asserts.
14437 continue;
14438 WorkList.push_back({ChildExpr, CC, IsListInit});
14439 }
14440
14441 if (BO && BO->isLogicalOp()) {
14442 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14443 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14444 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14445
14446 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14447 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
14448 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
14449 }
14450
14451 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
14452 if (U->getOpcode() == UO_LNot) {
14453 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
14454 } else if (U->getOpcode() != UO_AddrOf) {
14455 if (U->getSubExpr()->getType()->isAtomicType())
14456 S.Diag(U->getSubExpr()->getBeginLoc(),
14457 diag::warn_atomic_implicit_seq_cst);
14458 }
14459 }
14460}
14461
14462/// AnalyzeImplicitConversions - Find and report any interesting
14463/// implicit conversions in the given expression. There are a couple
14464/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14466 bool IsListInit/*= false*/) {
14468 WorkList.push_back({OrigE, CC, IsListInit});
14469 while (!WorkList.empty())
14470 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
14471}
14472
14473// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14474// Returns true when emitting a warning about taking the address of a reference.
14475static bool CheckForReference(Sema &SemaRef, const Expr *E,
14476 const PartialDiagnostic &PD) {
14477 E = E->IgnoreParenImpCasts();
14478
14479 const FunctionDecl *FD = nullptr;
14480
14481 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14482 if (!DRE->getDecl()->getType()->isReferenceType())
14483 return false;
14484 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14485 if (!M->getMemberDecl()->getType()->isReferenceType())
14486 return false;
14487 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
14488 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
14489 return false;
14490 FD = Call->getDirectCallee();
14491 } else {
14492 return false;
14493 }
14494
14495 SemaRef.Diag(E->getExprLoc(), PD);
14496
14497 // If possible, point to location of function.
14498 if (FD) {
14499 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
14500 }
14501
14502 return true;
14503}
14504
14505// Returns true if the SourceLocation is expanded from any macro body.
14506// Returns false if the SourceLocation is invalid, is from not in a macro
14507// expansion, or is from expanded from a top-level macro argument.
14508static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
14509 if (Loc.isInvalid())
14510 return false;
14511
14512 while (Loc.isMacroID()) {
14513 if (SM.isMacroBodyExpansion(Loc))
14514 return true;
14515 Loc = SM.getImmediateMacroCallerLoc(Loc);
14516 }
14517
14518 return false;
14519}
14520
14523 bool IsEqual, SourceRange Range) {
14524 if (!E)
14525 return;
14526
14527 // Don't warn inside macros.
14528 if (E->getExprLoc().isMacroID()) {
14529 const SourceManager &SM = getSourceManager();
14530 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
14531 IsInAnyMacroBody(SM, Range.getBegin()))
14532 return;
14533 }
14534 E = E->IgnoreImpCasts();
14535
14536 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14537
14538 if (isa<CXXThisExpr>(E)) {
14539 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14540 : diag::warn_this_bool_conversion;
14541 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14542 return;
14543 }
14544
14545 bool IsAddressOf = false;
14546
14547 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) {
14548 if (UO->getOpcode() != UO_AddrOf)
14549 return;
14550 IsAddressOf = true;
14551 E = UO->getSubExpr();
14552 }
14553
14554 if (IsAddressOf) {
14555 unsigned DiagID = IsCompare
14556 ? diag::warn_address_of_reference_null_compare
14557 : diag::warn_address_of_reference_bool_conversion;
14558 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14559 << IsEqual;
14560 if (CheckForReference(*this, E, PD)) {
14561 return;
14562 }
14563 }
14564
14565 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14566 bool IsParam = isa<NonNullAttr>(NonnullAttr);
14567 std::string Str;
14568 llvm::raw_string_ostream S(Str);
14569 E->printPretty(S, nullptr, getPrintingPolicy());
14570 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14571 : diag::warn_cast_nonnull_to_bool;
14572 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
14573 << E->getSourceRange() << Range << IsEqual;
14574 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
14575 };
14576
14577 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14578 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
14579 if (auto *Callee = Call->getDirectCallee()) {
14580 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14581 ComplainAboutNonnullParamOrCall(A);
14582 return;
14583 }
14584 }
14585 }
14586
14587 // Complain if we are converting a lambda expression to a boolean value
14588 // outside of instantiation.
14589 if (!inTemplateInstantiation()) {
14590 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
14591 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14592 MRecordDecl && MRecordDecl->isLambda()) {
14593 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool)
14594 << /*LambdaPointerConversionOperatorType=*/3
14595 << MRecordDecl->getSourceRange() << Range << IsEqual;
14596 return;
14597 }
14598 }
14599 }
14600
14601 // Expect to find a single Decl. Skip anything more complicated.
14602 ValueDecl *D = nullptr;
14603 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
14604 D = R->getDecl();
14605 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14606 D = M->getMemberDecl();
14607 }
14608
14609 // Weak Decls can be null.
14610 if (!D || D->isWeak())
14611 return;
14612
14613 // Check for parameter decl with nonnull attribute
14614 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14615 if (getCurFunction() &&
14616 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
14617 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14618 ComplainAboutNonnullParamOrCall(A);
14619 return;
14620 }
14621
14622 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14623 // Skip function template not specialized yet.
14625 return;
14626 auto ParamIter = llvm::find(FD->parameters(), PV);
14627 assert(ParamIter != FD->param_end());
14628 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
14629
14630 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14631 if (!NonNull->args_size()) {
14632 ComplainAboutNonnullParamOrCall(NonNull);
14633 return;
14634 }
14635
14636 for (const ParamIdx &ArgNo : NonNull->args()) {
14637 if (ArgNo.getASTIndex() == ParamNo) {
14638 ComplainAboutNonnullParamOrCall(NonNull);
14639 return;
14640 }
14641 }
14642 }
14643 }
14644 }
14645 }
14646
14647 QualType T = D->getType();
14648 // A reference to a function is never null either; look through it.
14649 const bool IsFunctionReference =
14650 T->isReferenceType() && T->getPointeeType()->isFunctionType();
14651 if (IsFunctionReference)
14652 T = T->getPointeeType();
14653 const bool IsArray = T->isArrayType();
14654 const bool IsFunction = T->isFunctionType();
14655
14656 // Address of function is used to silence the function warning.
14657 if (IsAddressOf && IsFunction) {
14658 return;
14659 }
14660
14661 // Found nothing.
14662 if (!IsAddressOf && !IsFunction && !IsArray)
14663 return;
14664
14665 // Pretty print the expression for the diagnostic.
14666 std::string Str;
14667 llvm::raw_string_ostream S(Str);
14668 E->printPretty(S, nullptr, getPrintingPolicy());
14669
14670 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14671 : diag::warn_impcast_pointer_to_bool;
14672 enum {
14673 AddressOf,
14674 FunctionPointer,
14675 ArrayPointer
14676 } DiagType;
14677 if (IsAddressOf)
14678 DiagType = AddressOf;
14679 else if (IsFunction)
14680 DiagType = FunctionPointer;
14681 else if (IsArray)
14682 DiagType = ArrayPointer;
14683 else
14684 llvm_unreachable("Could not determine diagnostic.");
14685 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14686 << Range << IsEqual;
14687
14688 // The fix-it notes below only apply to a bare function name, not a reference.
14689 if (!IsFunction || IsFunctionReference)
14690 return;
14691
14692 // Suggest '&' to silence the function warning.
14693 Diag(E->getExprLoc(), diag::note_function_warning_silence)
14695
14696 // Check to see if '()' fixit should be emitted.
14697 QualType ReturnType;
14698 UnresolvedSet<4> NonTemplateOverloads;
14699 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
14700 if (ReturnType.isNull())
14701 return;
14702
14703 if (IsCompare) {
14704 // There are two cases here. If there is null constant, the only suggest
14705 // for a pointer return type. If the null is 0, then suggest if the return
14706 // type is a pointer or an integer type.
14707 if (!ReturnType->isPointerType()) {
14708 if (NullKind == Expr::NPCK_ZeroExpression ||
14709 NullKind == Expr::NPCK_ZeroLiteral) {
14710 if (!ReturnType->isIntegerType())
14711 return;
14712 } else {
14713 return;
14714 }
14715 }
14716 } else { // !IsCompare
14717 // For function to bool, only suggest if the function pointer has bool
14718 // return type.
14719 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
14720 return;
14721 }
14722 Diag(E->getExprLoc(), diag::note_function_to_function_call)
14724}
14725
14727 SourceLocation CC) {
14728 QualType Source = E->getType();
14729 QualType Target = T;
14730
14731 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14732 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14733 // Overflow behavior type is being stripped - issue warning
14734 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14735 Target->isUnsignedIntegerType()) {
14736 // For unsigned wrap to unsigned conversions, use pedantic version
14737 unsigned DiagId =
14739 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14740 : diag::warn_impcast_overflow_behavior_pedantic;
14741 DiagnoseImpCast(*this, E, T, CC, DiagId);
14742 } else {
14743 unsigned DiagId = InOverflowBehaviorAssignmentContext
14744 ? diag::warn_impcast_overflow_behavior_assignment
14745 : diag::warn_impcast_overflow_behavior;
14746 DiagnoseImpCast(*this, E, T, CC, DiagId);
14747 }
14748 }
14749 }
14750
14751 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14752 if (TargetOBT->isWrapKind()) {
14753 return true;
14754 }
14755 }
14756
14757 return false;
14758}
14759
14760void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14761 // Don't diagnose in unevaluated contexts.
14763 return;
14764
14765 // Don't diagnose for value- or type-dependent expressions.
14766 if (E->isTypeDependent() || E->isValueDependent())
14767 return;
14768
14769 // Check for array bounds violations in cases where the check isn't triggered
14770 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14771 // ArraySubscriptExpr is on the RHS of a variable initialization.
14772 CheckArrayAccess(E);
14773
14774 // This is not the right CC for (e.g.) a variable initialization.
14775 AnalyzeImplicitConversions(*this, E, CC);
14776}
14777
14778void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14779 ::CheckBoolLikeConversion(*this, E, CC);
14780}
14781
14782void Sema::CheckForIntOverflow (const Expr *E) {
14783 // Use a work list to deal with nested struct initializers.
14784 SmallVector<const Expr *, 2> Exprs(1, E);
14785
14786 do {
14787 const Expr *OriginalE = Exprs.pop_back_val();
14788 const Expr *E = OriginalE->IgnoreParenCasts();
14789
14790 if (isa<BinaryOperator>(E) ||
14791 (isa<UnaryOperator>(E) && cast<UnaryOperator>(E)->canOverflow())) {
14793 continue;
14794 }
14795
14796 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
14797 Exprs.append(InitList->inits().begin(), InitList->inits().end());
14798 else if (isa<ObjCBoxedExpr>(OriginalE))
14800 else if (const auto *Call = dyn_cast<CallExpr>(E))
14801 Exprs.append(Call->arg_begin(), Call->arg_end());
14802 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E))
14803 Exprs.append(Message->arg_begin(), Message->arg_end());
14804 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
14805 Exprs.append(Construct->arg_begin(), Construct->arg_end());
14806 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
14807 Exprs.push_back(Temporary->getSubExpr());
14808 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E))
14809 Exprs.push_back(Array->getIdx());
14810 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
14811 Exprs.push_back(Compound->getInitializer());
14812 else if (const auto *New = dyn_cast<CXXNewExpr>(E);
14813 New && New->isArray()) {
14814 if (auto ArraySize = New->getArraySize())
14815 Exprs.push_back(*ArraySize);
14816 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
14817 Exprs.push_back(MTE->getSubExpr());
14818 } while (!Exprs.empty());
14819}
14820
14821namespace {
14822
14823/// Visitor for expressions which looks for unsequenced operations on the
14824/// same object.
14825class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14826 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14827
14828 /// A tree of sequenced regions within an expression. Two regions are
14829 /// unsequenced if one is an ancestor or a descendent of the other. When we
14830 /// finish processing an expression with sequencing, such as a comma
14831 /// expression, we fold its tree nodes into its parent, since they are
14832 /// unsequenced with respect to nodes we will visit later.
14833 class SequenceTree {
14834 struct Value {
14835 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14836 unsigned Parent : 31;
14837 LLVM_PREFERRED_TYPE(bool)
14838 unsigned Merged : 1;
14839 };
14840 SmallVector<Value, 8> Values;
14841
14842 public:
14843 /// A region within an expression which may be sequenced with respect
14844 /// to some other region.
14845 class Seq {
14846 friend class SequenceTree;
14847
14848 unsigned Index;
14849
14850 explicit Seq(unsigned N) : Index(N) {}
14851
14852 public:
14853 Seq() : Index(0) {}
14854 };
14855
14856 SequenceTree() { Values.push_back(Value(0)); }
14857 Seq root() const { return Seq(0); }
14858
14859 /// Create a new sequence of operations, which is an unsequenced
14860 /// subset of \p Parent. This sequence of operations is sequenced with
14861 /// respect to other children of \p Parent.
14862 Seq allocate(Seq Parent) {
14863 Values.push_back(Value(Parent.Index));
14864 return Seq(Values.size() - 1);
14865 }
14866
14867 /// Merge a sequence of operations into its parent.
14868 void merge(Seq S) {
14869 Values[S.Index].Merged = true;
14870 }
14871
14872 /// Determine whether two operations are unsequenced. This operation
14873 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14874 /// should have been merged into its parent as appropriate.
14875 bool isUnsequenced(Seq Cur, Seq Old) {
14876 unsigned C = representative(Cur.Index);
14877 unsigned Target = representative(Old.Index);
14878 while (C >= Target) {
14879 if (C == Target)
14880 return true;
14881 C = Values[C].Parent;
14882 }
14883 return false;
14884 }
14885
14886 private:
14887 /// Pick a representative for a sequence.
14888 unsigned representative(unsigned K) {
14889 if (Values[K].Merged)
14890 // Perform path compression as we go.
14891 return Values[K].Parent = representative(Values[K].Parent);
14892 return K;
14893 }
14894 };
14895
14896 /// An object for which we can track unsequenced uses.
14897 using Object = const NamedDecl *;
14898
14899 /// Different flavors of object usage which we track. We only track the
14900 /// least-sequenced usage of each kind.
14901 enum UsageKind {
14902 /// A read of an object. Multiple unsequenced reads are OK.
14903 UK_Use,
14904
14905 /// A modification of an object which is sequenced before the value
14906 /// computation of the expression, such as ++n in C++.
14907 UK_ModAsValue,
14908
14909 /// A modification of an object which is not sequenced before the value
14910 /// computation of the expression, such as n++.
14911 UK_ModAsSideEffect,
14912
14913 UK_Count = UK_ModAsSideEffect + 1
14914 };
14915
14916 /// Bundle together a sequencing region and the expression corresponding
14917 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14918 struct Usage {
14919 const Expr *UsageExpr = nullptr;
14920 SequenceTree::Seq Seq;
14921
14922 Usage() = default;
14923 };
14924
14925 struct UsageInfo {
14926 Usage Uses[UK_Count];
14927
14928 /// Have we issued a diagnostic for this object already?
14929 bool Diagnosed = false;
14930
14931 UsageInfo();
14932 };
14933 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14934
14935 Sema &SemaRef;
14936
14937 /// Sequenced regions within the expression.
14938 SequenceTree Tree;
14939
14940 /// Declaration modifications and references which we have seen.
14941 UsageInfoMap UsageMap;
14942
14943 /// The region we are currently within.
14944 SequenceTree::Seq Region;
14945
14946 /// Filled in with declarations which were modified as a side-effect
14947 /// (that is, post-increment operations).
14948 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14949
14950 /// Expressions to check later. We defer checking these to reduce
14951 /// stack usage.
14952 SmallVectorImpl<const Expr *> &WorkList;
14953
14954 /// RAII object wrapping the visitation of a sequenced subexpression of an
14955 /// expression. At the end of this process, the side-effects of the evaluation
14956 /// become sequenced with respect to the value computation of the result, so
14957 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14958 /// UK_ModAsValue.
14959 struct SequencedSubexpression {
14960 SequencedSubexpression(SequenceChecker &Self)
14961 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14962 Self.ModAsSideEffect = &ModAsSideEffect;
14963 }
14964
14965 ~SequencedSubexpression() {
14966 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
14967 // Add a new usage with usage kind UK_ModAsValue, and then restore
14968 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14969 // the previous one was empty).
14970 UsageInfo &UI = Self.UsageMap[M.first];
14971 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14972 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
14973 SideEffectUsage = M.second;
14974 }
14975 Self.ModAsSideEffect = OldModAsSideEffect;
14976 }
14977
14978 SequenceChecker &Self;
14979 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14980 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14981 };
14982
14983 /// RAII object wrapping the visitation of a subexpression which we might
14984 /// choose to evaluate as a constant. If any subexpression is evaluated and
14985 /// found to be non-constant, this allows us to suppress the evaluation of
14986 /// the outer expression.
14987 class EvaluationTracker {
14988 public:
14989 EvaluationTracker(SequenceChecker &Self)
14990 : Self(Self), Prev(Self.EvalTracker) {
14991 Self.EvalTracker = this;
14992 }
14993
14994 ~EvaluationTracker() {
14995 Self.EvalTracker = Prev;
14996 if (Prev)
14997 Prev->EvalOK &= EvalOK;
14998 }
14999
15000 bool evaluate(const Expr *E, bool &Result) {
15001 if (!EvalOK || E->isValueDependent())
15002 return false;
15003 EvalOK = E->EvaluateAsBooleanCondition(
15004 Result, Self.SemaRef.Context,
15005 Self.SemaRef.isConstantEvaluatedContext());
15006 return EvalOK;
15007 }
15008
15009 private:
15010 SequenceChecker &Self;
15011 EvaluationTracker *Prev;
15012 bool EvalOK = true;
15013 } *EvalTracker = nullptr;
15014
15015 /// Find the object which is produced by the specified expression,
15016 /// if any.
15017 Object getObject(const Expr *E, bool Mod) const {
15018 E = E->IgnoreParenCasts();
15019 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
15020 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
15021 return getObject(UO->getSubExpr(), Mod);
15022 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
15023 if (BO->getOpcode() == BO_Comma)
15024 return getObject(BO->getRHS(), Mod);
15025 if (Mod && BO->isAssignmentOp())
15026 return getObject(BO->getLHS(), Mod);
15027 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15028 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
15029 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
15030 return ME->getMemberDecl();
15031 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
15032 // FIXME: If this is a reference, map through to its value.
15033 return DRE->getDecl();
15034 return nullptr;
15035 }
15036
15037 /// Note that an object \p O was modified or used by an expression
15038 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
15039 /// the object \p O as obtained via the \p UsageMap.
15040 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
15041 // Get the old usage for the given object and usage kind.
15042 Usage &U = UI.Uses[UK];
15043 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
15044 // If we have a modification as side effect and are in a sequenced
15045 // subexpression, save the old Usage so that we can restore it later
15046 // in SequencedSubexpression::~SequencedSubexpression.
15047 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
15048 ModAsSideEffect->push_back(std::make_pair(O, U));
15049 // Then record the new usage with the current sequencing region.
15050 U.UsageExpr = UsageExpr;
15051 U.Seq = Region;
15052 }
15053 }
15054
15055 /// Check whether a modification or use of an object \p O in an expression
15056 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
15057 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
15058 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
15059 /// usage and false we are checking for a mod-use unsequenced usage.
15060 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
15061 UsageKind OtherKind, bool IsModMod) {
15062 if (UI.Diagnosed)
15063 return;
15064
15065 const Usage &U = UI.Uses[OtherKind];
15066 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
15067 return;
15068
15069 const Expr *Mod = U.UsageExpr;
15070 const Expr *ModOrUse = UsageExpr;
15071 if (OtherKind == UK_Use)
15072 std::swap(Mod, ModOrUse);
15073
15074 SemaRef.DiagRuntimeBehavior(
15075 Mod->getExprLoc(), {Mod, ModOrUse},
15076 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
15077 : diag::warn_unsequenced_mod_use)
15078 << O << SourceRange(ModOrUse->getExprLoc()));
15079 UI.Diagnosed = true;
15080 }
15081
15082 // A note on note{Pre, Post}{Use, Mod}:
15083 //
15084 // (It helps to follow the algorithm with an expression such as
15085 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
15086 // operations before C++17 and both are well-defined in C++17).
15087 //
15088 // When visiting a node which uses/modify an object we first call notePreUse
15089 // or notePreMod before visiting its sub-expression(s). At this point the
15090 // children of the current node have not yet been visited and so the eventual
15091 // uses/modifications resulting from the children of the current node have not
15092 // been recorded yet.
15093 //
15094 // We then visit the children of the current node. After that notePostUse or
15095 // notePostMod is called. These will 1) detect an unsequenced modification
15096 // as side effect (as in "k++ + k") and 2) add a new usage with the
15097 // appropriate usage kind.
15098 //
15099 // We also have to be careful that some operation sequences modification as
15100 // side effect as well (for example: || or ,). To account for this we wrap
15101 // the visitation of such a sub-expression (for example: the LHS of || or ,)
15102 // with SequencedSubexpression. SequencedSubexpression is an RAII object
15103 // which record usages which are modifications as side effect, and then
15104 // downgrade them (or more accurately restore the previous usage which was a
15105 // modification as side effect) when exiting the scope of the sequenced
15106 // subexpression.
15107
15108 void notePreUse(Object O, const Expr *UseExpr) {
15109 UsageInfo &UI = UsageMap[O];
15110 // Uses conflict with other modifications.
15111 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
15112 }
15113
15114 void notePostUse(Object O, const Expr *UseExpr) {
15115 UsageInfo &UI = UsageMap[O];
15116 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
15117 /*IsModMod=*/false);
15118 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
15119 }
15120
15121 void notePreMod(Object O, const Expr *ModExpr) {
15122 UsageInfo &UI = UsageMap[O];
15123 // Modifications conflict with other modifications and with uses.
15124 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
15125 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
15126 }
15127
15128 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
15129 UsageInfo &UI = UsageMap[O];
15130 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
15131 /*IsModMod=*/true);
15132 addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
15133 }
15134
15135public:
15136 SequenceChecker(Sema &S, const Expr *E,
15137 SmallVectorImpl<const Expr *> &WorkList)
15138 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
15139 Visit(E);
15140 // Silence a -Wunused-private-field since WorkList is now unused.
15141 // TODO: Evaluate if it can be used, and if not remove it.
15142 (void)this->WorkList;
15143 }
15144
15145 void VisitStmt(const Stmt *S) {
15146 // Skip all statements which aren't expressions for now.
15147 }
15148
15149 void VisitExpr(const Expr *E) {
15150 // By default, just recurse to evaluated subexpressions.
15151 Base::VisitStmt(E);
15152 }
15153
15154 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
15155 for (auto *Sub : CSE->children()) {
15156 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
15157 if (!ChildExpr)
15158 continue;
15159
15160 if (ChildExpr == CSE->getOperand())
15161 // Do not recurse over a CoroutineSuspendExpr's operand.
15162 // The operand is also a subexpression of getCommonExpr(), and
15163 // recursing into it directly could confuse object management
15164 // for the sake of sequence tracking.
15165 continue;
15166
15167 Visit(Sub);
15168 }
15169 }
15170
15171 void VisitCastExpr(const CastExpr *E) {
15172 Object O = Object();
15173 if (E->getCastKind() == CK_LValueToRValue)
15174 O = getObject(E->getSubExpr(), false);
15175
15176 if (O)
15177 notePreUse(O, E);
15178 VisitExpr(E);
15179 if (O)
15180 notePostUse(O, E);
15181 }
15182
15183 void VisitSequencedExpressions(const Expr *SequencedBefore,
15184 const Expr *SequencedAfter) {
15185 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
15186 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
15187 SequenceTree::Seq OldRegion = Region;
15188
15189 {
15190 SequencedSubexpression SeqBefore(*this);
15191 Region = BeforeRegion;
15192 Visit(SequencedBefore);
15193 }
15194
15195 Region = AfterRegion;
15196 Visit(SequencedAfter);
15197
15198 Region = OldRegion;
15199
15200 Tree.merge(BeforeRegion);
15201 Tree.merge(AfterRegion);
15202 }
15203
15204 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
15205 // C++17 [expr.sub]p1:
15206 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
15207 // expression E1 is sequenced before the expression E2.
15208 if (SemaRef.getLangOpts().CPlusPlus17)
15209 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
15210 else {
15211 Visit(ASE->getLHS());
15212 Visit(ASE->getRHS());
15213 }
15214 }
15215
15216 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15217 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15218 void VisitBinPtrMem(const BinaryOperator *BO) {
15219 // C++17 [expr.mptr.oper]p4:
15220 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
15221 // the expression E1 is sequenced before the expression E2.
15222 if (SemaRef.getLangOpts().CPlusPlus17)
15223 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15224 else {
15225 Visit(BO->getLHS());
15226 Visit(BO->getRHS());
15227 }
15228 }
15229
15230 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15231 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15232 void VisitBinShlShr(const BinaryOperator *BO) {
15233 // C++17 [expr.shift]p4:
15234 // The expression E1 is sequenced before the expression E2.
15235 if (SemaRef.getLangOpts().CPlusPlus17)
15236 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15237 else {
15238 Visit(BO->getLHS());
15239 Visit(BO->getRHS());
15240 }
15241 }
15242
15243 void VisitBinComma(const BinaryOperator *BO) {
15244 // C++11 [expr.comma]p1:
15245 // Every value computation and side effect associated with the left
15246 // expression is sequenced before every value computation and side
15247 // effect associated with the right expression.
15248 VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
15249 }
15250
15251 void VisitBinAssign(const BinaryOperator *BO) {
15252 SequenceTree::Seq RHSRegion;
15253 SequenceTree::Seq LHSRegion;
15254 if (SemaRef.getLangOpts().CPlusPlus17) {
15255 RHSRegion = Tree.allocate(Region);
15256 LHSRegion = Tree.allocate(Region);
15257 } else {
15258 RHSRegion = Region;
15259 LHSRegion = Region;
15260 }
15261 SequenceTree::Seq OldRegion = Region;
15262
15263 // C++11 [expr.ass]p1:
15264 // [...] the assignment is sequenced after the value computation
15265 // of the right and left operands, [...]
15266 //
15267 // so check it before inspecting the operands and update the
15268 // map afterwards.
15269 Object O = getObject(BO->getLHS(), /*Mod=*/true);
15270 if (O)
15271 notePreMod(O, BO);
15272
15273 if (SemaRef.getLangOpts().CPlusPlus17) {
15274 // C++17 [expr.ass]p1:
15275 // [...] The right operand is sequenced before the left operand. [...]
15276 {
15277 SequencedSubexpression SeqBefore(*this);
15278 Region = RHSRegion;
15279 Visit(BO->getRHS());
15280 }
15281
15282 Region = LHSRegion;
15283 Visit(BO->getLHS());
15284
15285 if (O && isa<CompoundAssignOperator>(BO))
15286 notePostUse(O, BO);
15287
15288 } else {
15289 // C++11 does not specify any sequencing between the LHS and RHS.
15290 Region = LHSRegion;
15291 Visit(BO->getLHS());
15292
15293 if (O && isa<CompoundAssignOperator>(BO))
15294 notePostUse(O, BO);
15295
15296 Region = RHSRegion;
15297 Visit(BO->getRHS());
15298 }
15299
15300 // C++11 [expr.ass]p1:
15301 // the assignment is sequenced [...] before the value computation of the
15302 // assignment expression.
15303 // C11 6.5.16/3 has no such rule.
15304 Region = OldRegion;
15305 if (O)
15306 notePostMod(O, BO,
15307 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15308 : UK_ModAsSideEffect);
15309 if (SemaRef.getLangOpts().CPlusPlus17) {
15310 Tree.merge(RHSRegion);
15311 Tree.merge(LHSRegion);
15312 }
15313 }
15314
15315 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
15316 VisitBinAssign(CAO);
15317 }
15318
15319 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15320 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15321 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
15322 Object O = getObject(UO->getSubExpr(), true);
15323 if (!O)
15324 return VisitExpr(UO);
15325
15326 notePreMod(O, UO);
15327 Visit(UO->getSubExpr());
15328 // C++11 [expr.pre.incr]p1:
15329 // the expression ++x is equivalent to x+=1
15330 notePostMod(O, UO,
15331 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15332 : UK_ModAsSideEffect);
15333 }
15334
15335 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15336 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15337 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
15338 Object O = getObject(UO->getSubExpr(), true);
15339 if (!O)
15340 return VisitExpr(UO);
15341
15342 notePreMod(O, UO);
15343 Visit(UO->getSubExpr());
15344 notePostMod(O, UO, UK_ModAsSideEffect);
15345 }
15346
15347 void VisitBinLOr(const BinaryOperator *BO) {
15348 // C++11 [expr.log.or]p2:
15349 // If the second expression is evaluated, every value computation and
15350 // side effect associated with the first expression is sequenced before
15351 // every value computation and side effect associated with the
15352 // second expression.
15353 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15354 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15355 SequenceTree::Seq OldRegion = Region;
15356
15357 EvaluationTracker Eval(*this);
15358 {
15359 SequencedSubexpression Sequenced(*this);
15360 Region = LHSRegion;
15361 Visit(BO->getLHS());
15362 }
15363
15364 // C++11 [expr.log.or]p1:
15365 // [...] the second operand is not evaluated if the first operand
15366 // evaluates to true.
15367 bool EvalResult = false;
15368 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15369 bool ShouldVisitRHS = !EvalOK || !EvalResult;
15370 if (ShouldVisitRHS) {
15371 Region = RHSRegion;
15372 Visit(BO->getRHS());
15373 }
15374
15375 Region = OldRegion;
15376 Tree.merge(LHSRegion);
15377 Tree.merge(RHSRegion);
15378 }
15379
15380 void VisitBinLAnd(const BinaryOperator *BO) {
15381 // C++11 [expr.log.and]p2:
15382 // If the second expression is evaluated, every value computation and
15383 // side effect associated with the first expression is sequenced before
15384 // every value computation and side effect associated with the
15385 // second expression.
15386 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15387 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15388 SequenceTree::Seq OldRegion = Region;
15389
15390 EvaluationTracker Eval(*this);
15391 {
15392 SequencedSubexpression Sequenced(*this);
15393 Region = LHSRegion;
15394 Visit(BO->getLHS());
15395 }
15396
15397 // C++11 [expr.log.and]p1:
15398 // [...] the second operand is not evaluated if the first operand is false.
15399 bool EvalResult = false;
15400 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
15401 bool ShouldVisitRHS = !EvalOK || EvalResult;
15402 if (ShouldVisitRHS) {
15403 Region = RHSRegion;
15404 Visit(BO->getRHS());
15405 }
15406
15407 Region = OldRegion;
15408 Tree.merge(LHSRegion);
15409 Tree.merge(RHSRegion);
15410 }
15411
15412 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15413 // C++11 [expr.cond]p1:
15414 // [...] Every value computation and side effect associated with the first
15415 // expression is sequenced before every value computation and side effect
15416 // associated with the second or third expression.
15417 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
15418
15419 // No sequencing is specified between the true and false expression.
15420 // However since exactly one of both is going to be evaluated we can
15421 // consider them to be sequenced. This is needed to avoid warning on
15422 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15423 // both the true and false expressions because we can't evaluate x.
15424 // This will still allow us to detect an expression like (pre C++17)
15425 // "(x ? y += 1 : y += 2) = y".
15426 //
15427 // We don't wrap the visitation of the true and false expression with
15428 // SequencedSubexpression because we don't want to downgrade modifications
15429 // as side effect in the true and false expressions after the visition
15430 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15431 // not warn between the two "y++", but we should warn between the "y++"
15432 // and the "y".
15433 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
15434 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
15435 SequenceTree::Seq OldRegion = Region;
15436
15437 EvaluationTracker Eval(*this);
15438 {
15439 SequencedSubexpression Sequenced(*this);
15440 Region = ConditionRegion;
15441 Visit(CO->getCond());
15442 }
15443
15444 // C++11 [expr.cond]p1:
15445 // [...] The first expression is contextually converted to bool (Clause 4).
15446 // It is evaluated and if it is true, the result of the conditional
15447 // expression is the value of the second expression, otherwise that of the
15448 // third expression. Only one of the second and third expressions is
15449 // evaluated. [...]
15450 bool EvalResult = false;
15451 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
15452 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15453 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15454 if (ShouldVisitTrueExpr) {
15455 Region = TrueRegion;
15456 Visit(CO->getTrueExpr());
15457 }
15458 if (ShouldVisitFalseExpr) {
15459 Region = FalseRegion;
15460 Visit(CO->getFalseExpr());
15461 }
15462
15463 Region = OldRegion;
15464 Tree.merge(ConditionRegion);
15465 Tree.merge(TrueRegion);
15466 Tree.merge(FalseRegion);
15467 }
15468
15469 void VisitCallExpr(const CallExpr *CE) {
15470 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15471
15472 if (CE->isUnevaluatedBuiltinCall(Context))
15473 return;
15474
15475 // C++11 [intro.execution]p15:
15476 // When calling a function [...], every value computation and side effect
15477 // associated with any argument expression, or with the postfix expression
15478 // designating the called function, is sequenced before execution of every
15479 // expression or statement in the body of the function [and thus before
15480 // the value computation of its result].
15481 SequencedSubexpression Sequenced(*this);
15482 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
15483 // C++17 [expr.call]p5
15484 // The postfix-expression is sequenced before each expression in the
15485 // expression-list and any default argument. [...]
15486 SequenceTree::Seq CalleeRegion;
15487 SequenceTree::Seq OtherRegion;
15488 if (SemaRef.getLangOpts().CPlusPlus17) {
15489 CalleeRegion = Tree.allocate(Region);
15490 OtherRegion = Tree.allocate(Region);
15491 } else {
15492 CalleeRegion = Region;
15493 OtherRegion = Region;
15494 }
15495 SequenceTree::Seq OldRegion = Region;
15496
15497 // Visit the callee expression first.
15498 Region = CalleeRegion;
15499 if (SemaRef.getLangOpts().CPlusPlus17) {
15500 SequencedSubexpression Sequenced(*this);
15501 Visit(CE->getCallee());
15502 } else {
15503 Visit(CE->getCallee());
15504 }
15505
15506 // Then visit the argument expressions.
15507 Region = OtherRegion;
15508 for (const Expr *Argument : CE->arguments())
15509 Visit(Argument);
15510
15511 Region = OldRegion;
15512 if (SemaRef.getLangOpts().CPlusPlus17) {
15513 Tree.merge(CalleeRegion);
15514 Tree.merge(OtherRegion);
15515 }
15516 });
15517 }
15518
15519 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15520 // C++17 [over.match.oper]p2:
15521 // [...] the operator notation is first transformed to the equivalent
15522 // function-call notation as summarized in Table 12 (where @ denotes one
15523 // of the operators covered in the specified subclause). However, the
15524 // operands are sequenced in the order prescribed for the built-in
15525 // operator (Clause 8).
15526 //
15527 // From the above only overloaded binary operators and overloaded call
15528 // operators have sequencing rules in C++17 that we need to handle
15529 // separately.
15530 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15531 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15532 return VisitCallExpr(CXXOCE);
15533
15534 enum {
15535 NoSequencing,
15536 LHSBeforeRHS,
15537 RHSBeforeLHS,
15538 LHSBeforeRest
15539 } SequencingKind;
15540 switch (CXXOCE->getOperator()) {
15541 case OO_Equal:
15542 case OO_PlusEqual:
15543 case OO_MinusEqual:
15544 case OO_StarEqual:
15545 case OO_SlashEqual:
15546 case OO_PercentEqual:
15547 case OO_CaretEqual:
15548 case OO_AmpEqual:
15549 case OO_PipeEqual:
15550 case OO_LessLessEqual:
15551 case OO_GreaterGreaterEqual:
15552 SequencingKind = RHSBeforeLHS;
15553 break;
15554
15555 case OO_LessLess:
15556 case OO_GreaterGreater:
15557 case OO_AmpAmp:
15558 case OO_PipePipe:
15559 case OO_Comma:
15560 case OO_ArrowStar:
15561 case OO_Subscript:
15562 SequencingKind = LHSBeforeRHS;
15563 break;
15564
15565 case OO_Call:
15566 SequencingKind = LHSBeforeRest;
15567 break;
15568
15569 default:
15570 SequencingKind = NoSequencing;
15571 break;
15572 }
15573
15574 if (SequencingKind == NoSequencing)
15575 return VisitCallExpr(CXXOCE);
15576
15577 // This is a call, so all subexpressions are sequenced before the result.
15578 SequencedSubexpression Sequenced(*this);
15579
15580 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
15581 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15582 "Should only get there with C++17 and above!");
15583 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15584 "Should only get there with an overloaded binary operator"
15585 " or an overloaded call operator!");
15586
15587 if (SequencingKind == LHSBeforeRest) {
15588 assert(CXXOCE->getOperator() == OO_Call &&
15589 "We should only have an overloaded call operator here!");
15590
15591 // This is very similar to VisitCallExpr, except that we only have the
15592 // C++17 case. The postfix-expression is the first argument of the
15593 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15594 // are in the following arguments.
15595 //
15596 // Note that we intentionally do not visit the callee expression since
15597 // it is just a decayed reference to a function.
15598 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
15599 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
15600 SequenceTree::Seq OldRegion = Region;
15601
15602 assert(CXXOCE->getNumArgs() >= 1 &&
15603 "An overloaded call operator must have at least one argument"
15604 " for the postfix-expression!");
15605 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15606 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15607 CXXOCE->getNumArgs() - 1);
15608
15609 // Visit the postfix-expression first.
15610 {
15611 Region = PostfixExprRegion;
15612 SequencedSubexpression Sequenced(*this);
15613 Visit(PostfixExpr);
15614 }
15615
15616 // Then visit the argument expressions.
15617 Region = ArgsRegion;
15618 for (const Expr *Arg : Args)
15619 Visit(Arg);
15620
15621 Region = OldRegion;
15622 Tree.merge(PostfixExprRegion);
15623 Tree.merge(ArgsRegion);
15624 } else {
15625 assert(CXXOCE->getNumArgs() == 2 &&
15626 "Should only have two arguments here!");
15627 assert((SequencingKind == LHSBeforeRHS ||
15628 SequencingKind == RHSBeforeLHS) &&
15629 "Unexpected sequencing kind!");
15630
15631 // We do not visit the callee expression since it is just a decayed
15632 // reference to a function.
15633 const Expr *E1 = CXXOCE->getArg(0);
15634 const Expr *E2 = CXXOCE->getArg(1);
15635 if (SequencingKind == RHSBeforeLHS)
15636 std::swap(E1, E2);
15637
15638 return VisitSequencedExpressions(E1, E2);
15639 }
15640 });
15641 }
15642
15643 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15644 // This is a call, so all subexpressions are sequenced before the result.
15645 SequencedSubexpression Sequenced(*this);
15646
15647 if (!CCE->isListInitialization())
15648 return VisitExpr(CCE);
15649
15650 // In C++11, list initializations are sequenced.
15651 SequenceExpressionsInOrder(
15652 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15653 }
15654
15655 void VisitInitListExpr(const InitListExpr *ILE) {
15656 if (!SemaRef.getLangOpts().CPlusPlus11)
15657 return VisitExpr(ILE);
15658
15659 // In C++11, list initializations are sequenced.
15660 SequenceExpressionsInOrder(ILE->inits());
15661 }
15662
15663 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15664 // C++20 parenthesized list initializations are sequenced. See C++20
15665 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15666 SequenceExpressionsInOrder(PLIE->getInitExprs());
15667 }
15668
15669private:
15670 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15672 SequenceTree::Seq Parent = Region;
15673 for (const Expr *E : ExpressionList) {
15674 if (!E)
15675 continue;
15676 Region = Tree.allocate(Parent);
15677 Elts.push_back(Region);
15678 Visit(E);
15679 }
15680
15681 // Forget that the initializers are sequenced.
15682 Region = Parent;
15683 for (unsigned I = 0; I < Elts.size(); ++I)
15684 Tree.merge(Elts[I]);
15685 }
15686};
15687
15688SequenceChecker::UsageInfo::UsageInfo() = default;
15689
15690} // namespace
15691
15692void Sema::CheckUnsequencedOperations(const Expr *E) {
15693 SmallVector<const Expr *, 8> WorkList;
15694 WorkList.push_back(E);
15695 while (!WorkList.empty()) {
15696 const Expr *Item = WorkList.pop_back_val();
15697 SequenceChecker(*this, Item, WorkList);
15698 }
15699}
15700
15701void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15702 bool IsConstexpr) {
15703 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15704 IsConstexpr || isa<ConstantExpr>(E));
15705 CheckImplicitConversions(E, CheckLoc);
15706 if (!E->isInstantiationDependent())
15707 CheckUnsequencedOperations(E);
15708 if (!IsConstexpr && !E->isValueDependent() && !isa<ConstantExpr>(E))
15709 CheckForIntOverflow(E);
15710}
15711
15712void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15713 FieldDecl *BitField,
15714 Expr *Init) {
15715 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
15716}
15717
15719 SourceLocation Loc) {
15720 if (!PType->isVariablyModifiedType())
15721 return;
15722 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15723 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
15724 return;
15725 }
15726 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15727 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
15728 return;
15729 }
15730 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15731 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
15732 return;
15733 }
15734
15735 const ArrayType *AT = S.Context.getAsArrayType(PType);
15736 if (!AT)
15737 return;
15738
15741 return;
15742 }
15743
15744 S.Diag(Loc, diag::err_array_star_in_function_definition);
15745}
15746
15748 bool CheckParameterNames) {
15749 bool HasInvalidParm = false;
15750 for (ParmVarDecl *Param : Parameters) {
15751 assert(Param && "null in a parameter list");
15752 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15753 // function declarator that is part of a function definition of
15754 // that function shall not have incomplete type.
15755 //
15756 // C++23 [dcl.fct.def.general]/p2
15757 // The type of a parameter [...] for a function definition
15758 // shall not be a (possibly cv-qualified) class type that is incomplete
15759 // or abstract within the function body unless the function is deleted.
15760 if (!Param->isInvalidDecl() &&
15761 (RequireCompleteType(Param->getLocation(), Param->getType(),
15762 diag::err_typecheck_decl_incomplete_type) ||
15763 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(),
15764 diag::err_abstract_type_in_decl,
15766 Param->setInvalidDecl();
15767 HasInvalidParm = true;
15768 }
15769
15770 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15771 // declaration of each parameter shall include an identifier.
15772 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15773 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15774 // Diagnose this as an extension in C17 and earlier.
15775 if (!getLangOpts().C23)
15776 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
15777 }
15778
15779 // C99 6.7.5.3p12:
15780 // If the function declarator is not part of a definition of that
15781 // function, parameters may have incomplete type and may use the [*]
15782 // notation in their sequences of declarator specifiers to specify
15783 // variable length array types.
15784 QualType PType = Param->getOriginalType();
15785 // FIXME: This diagnostic should point the '[*]' if source-location
15786 // information is added for it.
15787 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
15788
15789 // If the parameter is a c++ class type and it has to be destructed in the
15790 // callee function, declare the destructor so that it can be called by the
15791 // callee function. Do not perform any direct access check on the dtor here.
15792 if (!Param->isInvalidDecl()) {
15793 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15794 if (!ClassDecl->isInvalidDecl() &&
15795 !ClassDecl->hasIrrelevantDestructor() &&
15796 !ClassDecl->isDependentContext() &&
15797 ClassDecl->isParamDestroyedInCallee()) {
15799 MarkFunctionReferenced(Param->getLocation(), Destructor);
15800 DiagnoseUseOfDecl(Destructor, Param->getLocation());
15801 }
15802 }
15803 }
15804
15805 // Parameters with the pass_object_size attribute only need to be marked
15806 // constant at function definitions. Because we lack information about
15807 // whether we're on a declaration or definition when we're instantiating the
15808 // attribute, we need to check for constness here.
15809 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15810 if (!Param->getType().isConstQualified())
15811 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15812 << Attr->getSpelling() << 1;
15813
15814 // Check for parameter names shadowing fields from the class.
15815 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15816 // The owning context for the parameter should be the function, but we
15817 // want to see if this function's declaration context is a record.
15818 DeclContext *DC = Param->getDeclContext();
15819 if (DC && DC->isFunctionOrMethod()) {
15820 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
15821 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15822 RD, /*DeclIsField*/ false);
15823 }
15824 }
15825
15826 if (!Param->isInvalidDecl() &&
15827 Param->getOriginalType()->isWebAssemblyTableType()) {
15828 Param->setInvalidDecl();
15829 HasInvalidParm = true;
15830 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
15831 }
15832 }
15833
15834 return HasInvalidParm;
15835}
15836
15837std::optional<std::pair<
15839 *E,
15841 &Ctx);
15842
15843/// Compute the alignment and offset of the base class object given the
15844/// derived-to-base cast expression and the alignment and offset of the derived
15845/// class object.
15846static std::pair<CharUnits, CharUnits>
15848 CharUnits BaseAlignment, CharUnits Offset,
15849 ASTContext &Ctx) {
15850 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15851 ++PathI) {
15852 const CXXBaseSpecifier *Base = *PathI;
15853 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15854 if (Base->isVirtual()) {
15855 // The complete object may have a lower alignment than the non-virtual
15856 // alignment of the base, in which case the base may be misaligned. Choose
15857 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15858 // conservative lower bound of the complete object alignment.
15859 CharUnits NonVirtualAlignment =
15861 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15862 Offset = CharUnits::Zero();
15863 } else {
15864 const ASTRecordLayout &RL =
15865 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
15866 Offset += RL.getBaseClassOffset(BaseDecl);
15867 }
15868 DerivedType = Base->getType();
15869 }
15870
15871 return std::make_pair(BaseAlignment, Offset);
15872}
15873
15874/// Compute the alignment and offset of a binary additive operator.
15875static std::optional<std::pair<CharUnits, CharUnits>>
15877 bool IsSub, ASTContext &Ctx) {
15878 QualType PointeeType = PtrE->getType()->getPointeeType();
15879
15880 if (!PointeeType->isConstantSizeType())
15881 return std::nullopt;
15882
15883 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
15884
15885 if (!P)
15886 return std::nullopt;
15887
15888 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
15889 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15890 CharUnits Offset = EltSize * IdxRes->getExtValue();
15891 if (IsSub)
15892 Offset = -Offset;
15893 return std::make_pair(P->first, P->second + Offset);
15894 }
15895
15896 // If the integer expression isn't a constant expression, compute the lower
15897 // bound of the alignment using the alignment and offset of the pointer
15898 // expression and the element size.
15899 return std::make_pair(
15900 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15901 CharUnits::Zero());
15902}
15903
15904/// This helper function takes an lvalue expression and returns the alignment of
15905/// a VarDecl and a constant offset from the VarDecl.
15906std::optional<std::pair<
15907 CharUnits,
15909 ASTContext &Ctx) {
15910 E = E->IgnoreParens();
15911 switch (E->getStmtClass()) {
15912 default:
15913 break;
15914 case Stmt::CStyleCastExprClass:
15915 case Stmt::CXXStaticCastExprClass:
15916 case Stmt::ImplicitCastExprClass: {
15917 auto *CE = cast<CastExpr>(E);
15918 const Expr *From = CE->getSubExpr();
15919 switch (CE->getCastKind()) {
15920 default:
15921 break;
15922 case CK_NoOp:
15923 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15924 case CK_UncheckedDerivedToBase:
15925 case CK_DerivedToBase: {
15926 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
15927 if (!P)
15928 break;
15929 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
15930 P->second, Ctx);
15931 }
15932 }
15933 break;
15934 }
15935 case Stmt::ArraySubscriptExprClass: {
15936 auto *ASE = cast<ArraySubscriptExpr>(E);
15938 false, Ctx);
15939 }
15940 case Stmt::DeclRefExprClass: {
15941 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
15942 // FIXME: If VD is captured by copy or is an escaping __block variable,
15943 // use the alignment of VD's type.
15944 if (!VD->getType()->isReferenceType()) {
15945 // Dependent alignment cannot be resolved -> bail out.
15946 if (VD->hasDependentAlignment())
15947 break;
15948 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
15949 }
15950 if (VD->hasInit())
15951 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
15952 }
15953 break;
15954 }
15955 case Stmt::MemberExprClass: {
15956 auto *ME = cast<MemberExpr>(E);
15957 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
15958 if (!FD || FD->getType()->isReferenceType() ||
15960 break;
15961 std::optional<std::pair<CharUnits, CharUnits>> P;
15962 if (ME->isArrow())
15963 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
15964 else
15965 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
15966 if (!P)
15967 break;
15968 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
15969 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
15970 return std::make_pair(P->first,
15971 P->second + CharUnits::fromQuantity(Offset));
15972 }
15973 case Stmt::UnaryOperatorClass: {
15974 auto *UO = cast<UnaryOperator>(E);
15975 switch (UO->getOpcode()) {
15976 default:
15977 break;
15978 case UO_Deref:
15980 }
15981 break;
15982 }
15983 case Stmt::BinaryOperatorClass: {
15984 auto *BO = cast<BinaryOperator>(E);
15985 auto Opcode = BO->getOpcode();
15986 switch (Opcode) {
15987 default:
15988 break;
15989 case BO_Comma:
15991 }
15992 break;
15993 }
15994 }
15995 return std::nullopt;
15996}
15997
15998/// This helper function takes a pointer expression and returns the alignment of
15999/// a VarDecl and a constant offset from the VarDecl.
16000std::optional<std::pair<
16002 *E,
16004 &Ctx) {
16005 E = E->IgnoreParens();
16006 switch (E->getStmtClass()) {
16007 default:
16008 break;
16009 case Stmt::CStyleCastExprClass:
16010 case Stmt::CXXStaticCastExprClass:
16011 case Stmt::ImplicitCastExprClass: {
16012 auto *CE = cast<CastExpr>(E);
16013 const Expr *From = CE->getSubExpr();
16014 switch (CE->getCastKind()) {
16015 default:
16016 break;
16017 case CK_NoOp:
16018 return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
16019 case CK_ArrayToPointerDecay:
16020 return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
16021 case CK_UncheckedDerivedToBase:
16022 case CK_DerivedToBase: {
16023 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
16024 if (!P)
16025 break;
16027 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
16028 }
16029 }
16030 break;
16031 }
16032 case Stmt::CXXThisExprClass: {
16033 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
16035 return std::make_pair(Alignment, CharUnits::Zero());
16036 }
16037 case Stmt::UnaryOperatorClass: {
16038 auto *UO = cast<UnaryOperator>(E);
16039 if (UO->getOpcode() == UO_AddrOf)
16041 break;
16042 }
16043 case Stmt::BinaryOperatorClass: {
16044 auto *BO = cast<BinaryOperator>(E);
16045 auto Opcode = BO->getOpcode();
16046 switch (Opcode) {
16047 default:
16048 break;
16049 case BO_Add:
16050 case BO_Sub: {
16051 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
16052 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
16053 std::swap(LHS, RHS);
16054 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
16055 Ctx);
16056 }
16057 case BO_Comma:
16058 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
16059 }
16060 break;
16061 }
16062 }
16063 return std::nullopt;
16064}
16065
16067 // See if we can compute the alignment of a VarDecl and an offset from it.
16068 std::optional<std::pair<CharUnits, CharUnits>> P =
16070
16071 if (P)
16072 return P->first.alignmentAtOffset(P->second);
16073
16074 // If that failed, return the type's alignment.
16076}
16077
16079 // This is actually a lot of work to potentially be doing on every
16080 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
16081 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
16082 return;
16083
16084 // Ignore dependent types.
16085 if (T->isDependentType() || Op->getType()->isDependentType())
16086 return;
16087
16088 // Require that the destination be a pointer type.
16089 const PointerType *DestPtr = T->getAs<PointerType>();
16090 if (!DestPtr) return;
16091
16092 // If the destination has alignment 1, we're done.
16093 QualType DestPointee = DestPtr->getPointeeType();
16094 if (DestPointee->isIncompleteType()) return;
16095 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
16096 if (DestAlign.isOne()) return;
16097
16098 // Require that the source be a pointer type.
16099 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
16100 if (!SrcPtr) return;
16101 QualType SrcPointee = SrcPtr->getPointeeType();
16102
16103 // Explicitly allow casts from cv void*. We already implicitly
16104 // allowed casts to cv void*, since they have alignment 1.
16105 // Also allow casts involving incomplete types, which implicitly
16106 // includes 'void'.
16107 if (SrcPointee->isIncompleteType()) return;
16108
16109 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
16110
16111 if (SrcAlign >= DestAlign) return;
16112
16113 Diag(TRange.getBegin(), diag::warn_cast_align)
16114 << Op->getType() << T
16115 << static_cast<unsigned>(SrcAlign.getQuantity())
16116 << static_cast<unsigned>(DestAlign.getQuantity())
16117 << TRange << Op->getSourceRange();
16118}
16119
16120void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
16121 const ArraySubscriptExpr *ASE,
16122 bool AllowOnePastEnd, bool IndexNegated) {
16123 // Already diagnosed by the constant evaluator.
16125 return;
16126
16127 IndexExpr = IndexExpr->IgnoreParenImpCasts();
16128 if (IndexExpr->isValueDependent())
16129 return;
16130
16131 const Type *EffectiveType =
16133 BaseExpr = BaseExpr->IgnoreParenCasts();
16134 const ConstantArrayType *ArrayTy =
16135 Context.getAsConstantArrayType(BaseExpr->getType());
16136
16138 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
16139
16140 const Type *BaseType =
16141 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
16142 bool IsUnboundedArray =
16143 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
16144 Context, StrictFlexArraysLevel,
16145 /*IgnoreTemplateOrMacroSubstitution=*/true);
16146 if (EffectiveType->isDependentType() ||
16147 (!IsUnboundedArray && BaseType->isDependentType()))
16148 return;
16149
16151 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
16152 return;
16153
16154 llvm::APSInt index = Result.Val.getInt();
16155 if (IndexNegated) {
16156 index.setIsUnsigned(false);
16157 index = -index;
16158 }
16159
16160 if (IsUnboundedArray) {
16161 if (EffectiveType->isFunctionType())
16162 return;
16163 if (index.isUnsigned() || !index.isNegative()) {
16164 const auto &ASTC = getASTContext();
16165 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
16166 EffectiveType->getCanonicalTypeInternal().getAddressSpace());
16167 if (index.getBitWidth() < AddrBits)
16168 index = index.zext(AddrBits);
16169 std::optional<CharUnits> ElemCharUnits =
16170 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
16171 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
16172 // pointer) bounds-checking isn't meaningful.
16173 if (!ElemCharUnits || ElemCharUnits->isZero())
16174 return;
16175 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
16176 // If index has more active bits than address space, we already know
16177 // we have a bounds violation to warn about. Otherwise, compute
16178 // address of (index + 1)th element, and warn about bounds violation
16179 // only if that address exceeds address space.
16180 if (index.getActiveBits() <= AddrBits) {
16181 bool Overflow;
16182 llvm::APInt Product(index);
16183 Product += 1;
16184 Product = Product.umul_ov(ElemBytes, Overflow);
16185 if (!Overflow && Product.getActiveBits() <= AddrBits)
16186 return;
16187 }
16188
16189 // Need to compute max possible elements in address space, since that
16190 // is included in diag message.
16191 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
16192 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
16193 MaxElems += 1;
16194 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
16195 MaxElems = MaxElems.udiv(ElemBytes);
16196
16197 unsigned DiagID =
16198 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
16199 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
16200
16201 // Diag message shows element size in bits and in "bytes" (platform-
16202 // dependent CharUnits)
16203 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16204 PDiag(DiagID) << index << AddrBits
16205 << (unsigned)ASTC.toBits(*ElemCharUnits)
16206 << ElemBytes << MaxElems
16207 << MaxElems.getZExtValue()
16208 << IndexExpr->getSourceRange());
16209
16210 const NamedDecl *ND = nullptr;
16211 // Try harder to find a NamedDecl to point at in the note.
16212 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16213 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16214 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16215 ND = DRE->getDecl();
16216 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16217 ND = ME->getMemberDecl();
16218
16219 if (ND)
16220 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
16221 PDiag(diag::note_array_declared_here) << ND);
16222 }
16223 return;
16224 }
16225
16226 if (index.isUnsigned() || !index.isNegative()) {
16227 // It is possible that the type of the base expression after
16228 // IgnoreParenCasts is incomplete, even though the type of the base
16229 // expression before IgnoreParenCasts is complete (see PR39746 for an
16230 // example). In this case we have no information about whether the array
16231 // access exceeds the array bounds. However we can still diagnose an array
16232 // access which precedes the array bounds.
16233 if (BaseType->isIncompleteType())
16234 return;
16235
16236 llvm::APInt size = ArrayTy->getSize();
16237
16238 if (BaseType != EffectiveType) {
16239 // Make sure we're comparing apples to apples when comparing index to
16240 // size.
16241 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
16242 uint64_t array_typesize = Context.getTypeSize(BaseType);
16243
16244 // Handle ptrarith_typesize being zero, such as when casting to void*.
16245 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
16246 if (!ptrarith_typesize)
16247 ptrarith_typesize = Context.getCharWidth();
16248
16249 if (ptrarith_typesize != array_typesize) {
16250 // There's a cast to a different size type involved.
16251 uint64_t ratio = array_typesize / ptrarith_typesize;
16252
16253 // TODO: Be smarter about handling cases where array_typesize is not a
16254 // multiple of ptrarith_typesize.
16255 if (ptrarith_typesize * ratio == array_typesize)
16256 size *= llvm::APInt(size.getBitWidth(), ratio);
16257 }
16258 }
16259
16260 if (size.getBitWidth() > index.getBitWidth())
16261 index = index.zext(size.getBitWidth());
16262 else if (size.getBitWidth() < index.getBitWidth())
16263 size = size.zext(index.getBitWidth());
16264
16265 // For array subscripting the index must be less than size, but for pointer
16266 // arithmetic also allow the index (offset) to be equal to size since
16267 // computing the next address after the end of the array is legal and
16268 // commonly done e.g. in C++ iterators and range-based for loops.
16269 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
16270 return;
16271
16272 // Suppress the warning if the subscript expression (as identified by the
16273 // ']' location) and the index expression are both from macro expansions
16274 // within a system header.
16275 if (ASE) {
16276 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
16277 ASE->getRBracketLoc());
16278 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
16279 SourceLocation IndexLoc =
16280 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
16281 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
16282 return;
16283 }
16284 }
16285
16286 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
16287 : diag::warn_ptr_arith_exceeds_bounds;
16288 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
16289 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
16290
16291 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16292 PDiag(DiagID)
16293 << index << ArrayTy->desugar() << CastMsg
16294 << CastMsgTy << IndexExpr->getSourceRange());
16295 } else {
16296 unsigned DiagID = diag::warn_array_index_precedes_bounds;
16297 if (!ASE) {
16298 DiagID = diag::warn_ptr_arith_precedes_bounds;
16299 if (index.isNegative()) index = -index;
16300 }
16301
16302 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
16303 PDiag(DiagID) << index << IndexExpr->getSourceRange());
16304 }
16305
16306 const NamedDecl *ND = nullptr;
16307 // Try harder to find a NamedDecl to point at in the note.
16308 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16309 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16310 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16311 ND = DRE->getDecl();
16312 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16313 ND = ME->getMemberDecl();
16314
16315 if (ND)
16316 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
16317 PDiag(diag::note_array_declared_here) << ND);
16318}
16319
16320void Sema::CheckArrayAccess(const Expr *expr) {
16321 int AllowOnePastEnd = 0;
16322 while (expr) {
16323 expr = expr->IgnoreParenImpCasts();
16324 switch (expr->getStmtClass()) {
16325 case Stmt::ArraySubscriptExprClass: {
16326 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
16327 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
16328 AllowOnePastEnd > 0);
16329 expr = ASE->getBase();
16330 break;
16331 }
16332 case Stmt::MemberExprClass: {
16333 expr = cast<MemberExpr>(expr)->getBase();
16334 break;
16335 }
16336 case Stmt::CXXMemberCallExprClass: {
16337 expr = cast<CXXMemberCallExpr>(expr)->getImplicitObjectArgument();
16338 break;
16339 }
16340 case Stmt::ArraySectionExprClass: {
16341 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr);
16342 // FIXME: We should probably be checking all of the elements to the
16343 // 'length' here as well.
16344 if (ASE->getLowerBound())
16345 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
16346 /*ASE=*/nullptr, AllowOnePastEnd > 0);
16347 return;
16348 }
16349 case Stmt::UnaryOperatorClass: {
16350 // Only unwrap the * and & unary operators
16351 const UnaryOperator *UO = cast<UnaryOperator>(expr);
16352 expr = UO->getSubExpr();
16353 switch (UO->getOpcode()) {
16354 case UO_AddrOf:
16355 AllowOnePastEnd++;
16356 break;
16357 case UO_Deref:
16358 AllowOnePastEnd--;
16359 break;
16360 default:
16361 return;
16362 }
16363 break;
16364 }
16365 case Stmt::ConditionalOperatorClass: {
16366 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
16367 if (const Expr *lhs = cond->getLHS())
16368 CheckArrayAccess(lhs);
16369 if (const Expr *rhs = cond->getRHS())
16370 CheckArrayAccess(rhs);
16371 return;
16372 }
16373 case Stmt::CXXOperatorCallExprClass: {
16374 const auto *OCE = cast<CXXOperatorCallExpr>(expr);
16375 for (const auto *Arg : OCE->arguments())
16376 CheckArrayAccess(Arg);
16377 return;
16378 }
16379 default:
16380 return;
16381 }
16382 }
16383}
16384
16386 Expr *RHS, bool isProperty) {
16387 // Check if RHS is an Objective-C object literal, which also can get
16388 // immediately zapped in a weak reference. Note that we explicitly
16389 // allow ObjCStringLiterals, since those are designed to never really die.
16390 RHS = RHS->IgnoreParenImpCasts();
16391
16392 // This enum needs to match with the 'select' in
16393 // warn_objc_arc_literal_assign (off-by-1).
16395 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
16396 return false;
16397
16398 S.Diag(Loc, diag::warn_arc_literal_assign)
16399 << (unsigned) Kind
16400 << (isProperty ? 0 : 1)
16401 << RHS->getSourceRange();
16402
16403 return true;
16404}
16405
16408 Expr *RHS, bool isProperty) {
16409 // Strip off any implicit cast added to get to the one ARC-specific.
16410 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16411 if (cast->getCastKind() == CK_ARCConsumeObject) {
16412 S.Diag(Loc, diag::warn_arc_retained_assign)
16414 << (isProperty ? 0 : 1)
16415 << RHS->getSourceRange();
16416 return true;
16417 }
16418 RHS = cast->getSubExpr();
16419 }
16420
16421 if (LT == Qualifiers::OCL_Weak &&
16422 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16423 return true;
16424
16425 return false;
16426}
16427
16429 QualType LHS, Expr *RHS) {
16431
16433 return false;
16434
16435 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
16436 return true;
16437
16438 return false;
16439}
16440
16442 Expr *LHS, Expr *RHS) {
16443 QualType LHSType;
16444 // PropertyRef on LHS type need be directly obtained from
16445 // its declaration as it has a PseudoType.
16447 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
16448 if (PRE && !PRE->isImplicitProperty()) {
16449 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16450 if (PD)
16451 LHSType = PD->getType();
16452 }
16453
16454 if (LHSType.isNull())
16455 LHSType = LHS->getType();
16456
16458
16459 if (LT == Qualifiers::OCL_Weak) {
16460 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16462 }
16463
16464 if (checkUnsafeAssigns(Loc, LHSType, RHS))
16465 return;
16466
16467 // FIXME. Check for other life times.
16468 if (LT != Qualifiers::OCL_None)
16469 return;
16470
16471 if (PRE) {
16472 if (PRE->isImplicitProperty())
16473 return;
16474 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16475 if (!PD)
16476 return;
16477
16478 unsigned Attributes = PD->getPropertyAttributes();
16479 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16480 // when 'assign' attribute was not explicitly specified
16481 // by user, ignore it and rely on property type itself
16482 // for lifetime info.
16483 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16484 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16485 LHSType->isObjCRetainableType())
16486 return;
16487
16488 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
16489 if (cast->getCastKind() == CK_ARCConsumeObject) {
16490 Diag(Loc, diag::warn_arc_retained_property_assign)
16491 << RHS->getSourceRange();
16492 return;
16493 }
16494 RHS = cast->getSubExpr();
16495 }
16496 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16497 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
16498 return;
16499 }
16500 }
16501}
16502
16503//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16504
16505static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16506 SourceLocation StmtLoc,
16507 const NullStmt *Body) {
16508 // Do not warn if the body is a macro that expands to nothing, e.g:
16509 //
16510 // #define CALL(x)
16511 // if (condition)
16512 // CALL(0);
16513 if (Body->hasLeadingEmptyMacro())
16514 return false;
16515
16516 // Get line numbers of statement and body.
16517 bool StmtLineInvalid;
16518 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16519 &StmtLineInvalid);
16520 if (StmtLineInvalid)
16521 return false;
16522
16523 bool BodyLineInvalid;
16524 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
16525 &BodyLineInvalid);
16526 if (BodyLineInvalid)
16527 return false;
16528
16529 // Warn if null statement and body are on the same line.
16530 if (StmtLine != BodyLine)
16531 return false;
16532
16533 return true;
16534}
16535
16537 const Stmt *Body,
16538 unsigned DiagID) {
16539 // Since this is a syntactic check, don't emit diagnostic for template
16540 // instantiations, this just adds noise.
16542 return;
16543
16544 // The body should be a null statement.
16545 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16546 if (!NBody)
16547 return;
16548
16549 // Do the usual checks.
16550 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16551 return;
16552
16553 Diag(NBody->getSemiLoc(), DiagID);
16554 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16555}
16556
16558 const Stmt *PossibleBody) {
16559 assert(!CurrentInstantiationScope); // Ensured by caller
16560
16561 SourceLocation StmtLoc;
16562 const Stmt *Body;
16563 unsigned DiagID;
16564 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16565 StmtLoc = FS->getRParenLoc();
16566 Body = FS->getBody();
16567 DiagID = diag::warn_empty_for_body;
16568 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16569 StmtLoc = WS->getRParenLoc();
16570 Body = WS->getBody();
16571 DiagID = diag::warn_empty_while_body;
16572 } else
16573 return; // Neither `for' nor `while'.
16574
16575 // The body should be a null statement.
16576 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16577 if (!NBody)
16578 return;
16579
16580 // Skip expensive checks if diagnostic is disabled.
16581 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
16582 return;
16583
16584 // Do the usual checks.
16585 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
16586 return;
16587
16588 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16589 // noise level low, emit diagnostics only if for/while is followed by a
16590 // CompoundStmt, e.g.:
16591 // for (int i = 0; i < n; i++);
16592 // {
16593 // a(i);
16594 // }
16595 // or if for/while is followed by a statement with more indentation
16596 // than for/while itself:
16597 // for (int i = 0; i < n; i++);
16598 // a(i);
16599 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
16600 if (!ProbableTypo) {
16601 bool BodyColInvalid;
16602 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16603 PossibleBody->getBeginLoc(), &BodyColInvalid);
16604 if (BodyColInvalid)
16605 return;
16606
16607 bool StmtColInvalid;
16608 unsigned StmtCol =
16609 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
16610 if (StmtColInvalid)
16611 return;
16612
16613 if (BodyCol > StmtCol)
16614 ProbableTypo = true;
16615 }
16616
16617 if (ProbableTypo) {
16618 Diag(NBody->getSemiLoc(), DiagID);
16619 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16620 }
16621}
16622
16623//===--- CHECK: Warn on self move with std::move. -------------------------===//
16624
16625void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16626 SourceLocation OpLoc) {
16627 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16628 return;
16629
16631 return;
16632
16633 // Strip parens and casts away.
16634 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16635 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16636
16637 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16638 // which we can treat as an inlined std::move
16639 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr);
16640 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16641 RHSExpr = CE->getArg(0);
16642 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
16643 CXXSCE && CXXSCE->isXValue())
16644 RHSExpr = CXXSCE->getSubExpr();
16645 else
16646 return;
16647
16648 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16649 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16650
16651 // Two DeclRefExpr's, check that the decls are the same.
16652 if (LHSDeclRef && RHSDeclRef) {
16653 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16654 return;
16655 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16656 RHSDeclRef->getDecl()->getCanonicalDecl())
16657 return;
16658
16659 auto D = Diag(OpLoc, diag::warn_self_move)
16660 << LHSExpr->getType() << LHSExpr->getSourceRange()
16661 << RHSExpr->getSourceRange();
16662 if (const FieldDecl *F =
16664 D << 1 << F
16665 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
16666 else
16667 D << 0;
16668 return;
16669 }
16670
16671 // Member variables require a different approach to check for self moves.
16672 // MemberExpr's are the same if every nested MemberExpr refers to the same
16673 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16674 // the base Expr's are CXXThisExpr's.
16675 const Expr *LHSBase = LHSExpr;
16676 const Expr *RHSBase = RHSExpr;
16677 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16678 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16679 if (!LHSME || !RHSME)
16680 return;
16681
16682 while (LHSME && RHSME) {
16683 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16684 RHSME->getMemberDecl()->getCanonicalDecl())
16685 return;
16686
16687 LHSBase = LHSME->getBase();
16688 RHSBase = RHSME->getBase();
16689 LHSME = dyn_cast<MemberExpr>(LHSBase);
16690 RHSME = dyn_cast<MemberExpr>(RHSBase);
16691 }
16692
16693 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16694 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16695 if (LHSDeclRef && RHSDeclRef) {
16696 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16697 return;
16698 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16699 RHSDeclRef->getDecl()->getCanonicalDecl())
16700 return;
16701
16702 Diag(OpLoc, diag::warn_self_move)
16703 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16704 << RHSExpr->getSourceRange();
16705 return;
16706 }
16707
16708 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16709 Diag(OpLoc, diag::warn_self_move)
16710 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16711 << RHSExpr->getSourceRange();
16712}
16713
16714//===--- Layout compatibility ----------------------------------------------//
16715
16716static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16717
16718/// Check if two enumeration types are layout-compatible.
16719static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16720 const EnumDecl *ED2) {
16721 // C++11 [dcl.enum] p8:
16722 // Two enumeration types are layout-compatible if they have the same
16723 // underlying type.
16724 return ED1->isComplete() && ED2->isComplete() &&
16725 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16726}
16727
16728/// Check if two fields are layout-compatible.
16729/// Can be used on union members, which are exempt from alignment requirement
16730/// of common initial sequence.
16731static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16732 const FieldDecl *Field2,
16733 bool AreUnionMembers = false) {
16734#ifndef NDEBUG
16735 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16736 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16737 assert(((Field1Parent->isStructureOrClassType() &&
16738 Field2Parent->isStructureOrClassType()) ||
16739 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16740 "Can't evaluate layout compatibility between a struct field and a "
16741 "union field.");
16742 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16743 (AreUnionMembers && Field1Parent->isUnionType())) &&
16744 "AreUnionMembers should be 'true' for union fields (only).");
16745#endif
16746
16747 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16748 return false;
16749
16750 if (Field1->isBitField() != Field2->isBitField())
16751 return false;
16752
16753 if (Field1->isBitField()) {
16754 // Make sure that the bit-fields are the same length.
16755 unsigned Bits1 = Field1->getBitWidthValue();
16756 unsigned Bits2 = Field2->getBitWidthValue();
16757
16758 if (Bits1 != Bits2)
16759 return false;
16760 }
16761
16762 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16763 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16764 return false;
16765
16766 if (!AreUnionMembers &&
16767 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16768 return false;
16769
16770 return true;
16771}
16772
16773/// Check if two standard-layout structs are layout-compatible.
16774/// (C++11 [class.mem] p17)
16775static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16776 const RecordDecl *RD2) {
16777 // Get to the class where the fields are declared
16778 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
16779 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16780
16781 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
16782 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16783
16784 // Check the fields.
16785 return llvm::equal(RD1->fields(), RD2->fields(),
16786 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16787 return isLayoutCompatible(C, F1, F2);
16788 });
16789}
16790
16791/// Check if two standard-layout unions are layout-compatible.
16792/// (C++11 [class.mem] p18)
16793static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16794 const RecordDecl *RD2) {
16795 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16796 RD2->fields());
16797
16798 for (auto *Field1 : RD1->fields()) {
16799 auto It = llvm::find_if(UnmatchedFields, [&](const FieldDecl *Field2) {
16800 return isLayoutCompatible(C, Field1, Field2, /*IsUnionMember=*/true);
16801 });
16802 if (It == UnmatchedFields.end())
16803 return false;
16804 [[maybe_unused]] bool Result = UnmatchedFields.erase(*It);
16805 assert(Result);
16806 }
16807
16808 return UnmatchedFields.empty();
16809}
16810
16811static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16812 const RecordDecl *RD2) {
16813 if (RD1->isUnion() != RD2->isUnion())
16814 return false;
16815
16816 if (RD1->isUnion())
16817 return isLayoutCompatibleUnion(C, RD1, RD2);
16818 else
16819 return isLayoutCompatibleStruct(C, RD1, RD2);
16820}
16821
16822/// Check if two types are layout-compatible in C++11 sense.
16823static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16824 if (T1.isNull() || T2.isNull())
16825 return false;
16826
16827 // C++20 [basic.types] p11:
16828 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16829 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16830 // or layout-compatible standard-layout class types (11.4).
16833
16834 if (C.hasSameType(T1, T2))
16835 return true;
16836
16837 const Type::TypeClass TC1 = T1->getTypeClass();
16838 const Type::TypeClass TC2 = T2->getTypeClass();
16839
16840 if (TC1 != TC2)
16841 return false;
16842
16843 if (TC1 == Type::Enum)
16844 return isLayoutCompatible(C, T1->castAsEnumDecl(), T2->castAsEnumDecl());
16845 if (TC1 == Type::Record) {
16846 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16847 return false;
16848
16850 T2->castAsRecordDecl());
16851 }
16852
16853 return false;
16854}
16855
16857 return isLayoutCompatible(getASTContext(), T1, T2);
16858}
16859
16860//===-------------- Pointer interconvertibility ----------------------------//
16861
16863 const TypeSourceInfo *Derived) {
16864 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16865 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16866
16867 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16868 getASTContext().hasSameType(BaseT, DerivedT))
16869 return true;
16870
16871 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT))
16872 return false;
16873
16874 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16875 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16876 return true;
16877
16878 return false;
16879}
16880
16881//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16882
16883/// Given a type tag expression find the type tag itself.
16884///
16885/// \param TypeExpr Type tag expression, as it appears in user's code.
16886///
16887/// \param VD Declaration of an identifier that appears in a type tag.
16888///
16889/// \param MagicValue Type tag magic value.
16890///
16891/// \param isConstantEvaluated whether the evalaution should be performed in
16892
16893/// constant context.
16894static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16895 const ValueDecl **VD, uint64_t *MagicValue,
16896 bool isConstantEvaluated) {
16897 while(true) {
16898 if (!TypeExpr)
16899 return false;
16900
16901 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16902
16903 switch (TypeExpr->getStmtClass()) {
16904 case Stmt::UnaryOperatorClass: {
16905 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16906 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16907 TypeExpr = UO->getSubExpr();
16908 continue;
16909 }
16910 return false;
16911 }
16912
16913 case Stmt::DeclRefExprClass: {
16914 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16915 *VD = DRE->getDecl();
16916 return true;
16917 }
16918
16919 case Stmt::IntegerLiteralClass: {
16920 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16921 llvm::APInt MagicValueAPInt = IL->getValue();
16922 if (MagicValueAPInt.getActiveBits() <= 64) {
16923 *MagicValue = MagicValueAPInt.getZExtValue();
16924 return true;
16925 } else
16926 return false;
16927 }
16928
16929 case Stmt::BinaryConditionalOperatorClass:
16930 case Stmt::ConditionalOperatorClass: {
16931 const AbstractConditionalOperator *ACO =
16933 bool Result;
16934 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16935 isConstantEvaluated)) {
16936 if (Result)
16937 TypeExpr = ACO->getTrueExpr();
16938 else
16939 TypeExpr = ACO->getFalseExpr();
16940 continue;
16941 }
16942 return false;
16943 }
16944
16945 case Stmt::BinaryOperatorClass: {
16946 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16947 if (BO->getOpcode() == BO_Comma) {
16948 TypeExpr = BO->getRHS();
16949 continue;
16950 }
16951 return false;
16952 }
16953
16954 default:
16955 return false;
16956 }
16957 }
16958}
16959
16960/// Retrieve the C type corresponding to type tag TypeExpr.
16961///
16962/// \param TypeExpr Expression that specifies a type tag.
16963///
16964/// \param MagicValues Registered magic values.
16965///
16966/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16967/// kind.
16968///
16969/// \param TypeInfo Information about the corresponding C type.
16970///
16971/// \param isConstantEvaluated whether the evalaution should be performed in
16972/// constant context.
16973///
16974/// \returns true if the corresponding C type was found.
16976 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16977 const ASTContext &Ctx,
16978 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16979 *MagicValues,
16980 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16981 bool isConstantEvaluated) {
16982 FoundWrongKind = false;
16983
16984 // Variable declaration that has type_tag_for_datatype attribute.
16985 const ValueDecl *VD = nullptr;
16986
16987 uint64_t MagicValue;
16988
16989 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16990 return false;
16991
16992 if (VD) {
16993 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16994 if (I->getArgumentKind() != ArgumentKind) {
16995 FoundWrongKind = true;
16996 return false;
16997 }
16998 TypeInfo.Type = I->getMatchingCType();
16999 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
17000 TypeInfo.MustBeNull = I->getMustBeNull();
17001 return true;
17002 }
17003 return false;
17004 }
17005
17006 if (!MagicValues)
17007 return false;
17008
17009 llvm::DenseMap<Sema::TypeTagMagicValue,
17011 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
17012 if (I == MagicValues->end())
17013 return false;
17014
17015 TypeInfo = I->second;
17016 return true;
17017}
17018
17020 uint64_t MagicValue, QualType Type,
17021 bool LayoutCompatible,
17022 bool MustBeNull) {
17023 if (!TypeTagForDatatypeMagicValues)
17024 TypeTagForDatatypeMagicValues.reset(
17025 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
17026
17027 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
17028 (*TypeTagForDatatypeMagicValues)[Magic] =
17029 TypeTagData(Type, LayoutCompatible, MustBeNull);
17030}
17031
17032static bool IsSameCharType(QualType T1, QualType T2) {
17033 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
17034 if (!BT1)
17035 return false;
17036
17037 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
17038 if (!BT2)
17039 return false;
17040
17041 BuiltinType::Kind T1Kind = BT1->getKind();
17042 BuiltinType::Kind T2Kind = BT2->getKind();
17043
17044 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
17045 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
17046 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
17047 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
17048}
17049
17050void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
17051 const ArrayRef<const Expr *> ExprArgs,
17052 SourceLocation CallSiteLoc) {
17053 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
17054 bool IsPointerAttr = Attr->getIsPointer();
17055
17056 // Retrieve the argument representing the 'type_tag'.
17057 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
17058 if (TypeTagIdxAST >= ExprArgs.size()) {
17059 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
17060 << 0 << Attr->getTypeTagIdx().getSourceIndex();
17061 return;
17062 }
17063 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
17064 bool FoundWrongKind;
17065 TypeTagData TypeInfo;
17066 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
17067 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
17068 TypeInfo, isConstantEvaluatedContext())) {
17069 if (FoundWrongKind)
17070 Diag(TypeTagExpr->getExprLoc(),
17071 diag::warn_type_tag_for_datatype_wrong_kind)
17072 << TypeTagExpr->getSourceRange();
17073 return;
17074 }
17075
17076 // Retrieve the argument representing the 'arg_idx'.
17077 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
17078 if (ArgumentIdxAST >= ExprArgs.size()) {
17079 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
17080 << 1 << Attr->getArgumentIdx().getSourceIndex();
17081 return;
17082 }
17083 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
17084 if (IsPointerAttr) {
17085 // Skip implicit cast of pointer to `void *' (as a function argument).
17086 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
17087 if (ICE->getType()->isVoidPointerType() &&
17088 ICE->getCastKind() == CK_BitCast)
17089 ArgumentExpr = ICE->getSubExpr();
17090 }
17091 QualType ArgumentType = ArgumentExpr->getType();
17092
17093 // Passing a `void*' pointer shouldn't trigger a warning.
17094 if (IsPointerAttr && ArgumentType->isVoidPointerType())
17095 return;
17096
17097 if (TypeInfo.MustBeNull) {
17098 // Type tag with matching void type requires a null pointer.
17099 if (!ArgumentExpr->isNullPointerConstant(Context,
17101 Diag(ArgumentExpr->getExprLoc(),
17102 diag::warn_type_safety_null_pointer_required)
17103 << ArgumentKind->getName()
17104 << ArgumentExpr->getSourceRange()
17105 << TypeTagExpr->getSourceRange();
17106 }
17107 return;
17108 }
17109
17110 QualType RequiredType = TypeInfo.Type;
17111 if (IsPointerAttr)
17112 RequiredType = Context.getPointerType(RequiredType);
17113
17114 bool mismatch = false;
17115 if (!TypeInfo.LayoutCompatible) {
17116 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
17117
17118 // C++11 [basic.fundamental] p1:
17119 // Plain char, signed char, and unsigned char are three distinct types.
17120 //
17121 // But we treat plain `char' as equivalent to `signed char' or `unsigned
17122 // char' depending on the current char signedness mode.
17123 if (mismatch)
17124 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
17125 RequiredType->getPointeeType())) ||
17126 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
17127 mismatch = false;
17128 } else
17129 if (IsPointerAttr)
17130 mismatch = !isLayoutCompatible(Context,
17131 ArgumentType->getPointeeType(),
17132 RequiredType->getPointeeType());
17133 else
17134 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
17135
17136 if (mismatch)
17137 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
17138 << ArgumentType << ArgumentKind
17139 << TypeInfo.LayoutCompatible << RequiredType
17140 << ArgumentExpr->getSourceRange()
17141 << TypeTagExpr->getSourceRange();
17142}
17143
17144void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
17145 CharUnits Alignment) {
17146 currentEvaluationContext().MisalignedMembers.emplace_back(E, RD, MD,
17147 Alignment);
17148}
17149
17151 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
17152 const NamedDecl *ND = m.RD;
17153 if (ND->getName().empty()) {
17154 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
17155 ND = TD;
17156 }
17157 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
17158 << m.MD << ND << m.E->getSourceRange();
17159 }
17161}
17162
17164 E = E->IgnoreParens();
17165 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
17166 return;
17167 if (isa<UnaryOperator>(E) &&
17168 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
17169 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
17170 if (isa<MemberExpr>(Op)) {
17171 auto &MisalignedMembersForExpr =
17173 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
17174 if (MA != MisalignedMembersForExpr.end() &&
17175 (T->isDependentType() || T->isIntegerType() ||
17176 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
17177 Context.getTypeAlignInChars(
17178 T->getPointeeType()) <= MA->Alignment))))
17179 MisalignedMembersForExpr.erase(MA);
17180 }
17181 }
17182}
17183
17185 Expr *E,
17186 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
17187 Action) {
17188 const auto *ME = dyn_cast<MemberExpr>(E);
17189 if (!ME)
17190 return;
17191
17192 // No need to check expressions with an __unaligned-qualified type.
17193 if (E->getType().getQualifiers().hasUnaligned())
17194 return;
17195
17196 // For a chain of MemberExpr like "a.b.c.d" this list
17197 // will keep FieldDecl's like [d, c, b].
17198 SmallVector<FieldDecl *, 4> ReverseMemberChain;
17199 const MemberExpr *TopME = nullptr;
17200 bool AnyIsPacked = false;
17201 do {
17202 QualType BaseType = ME->getBase()->getType();
17203 if (BaseType->isDependentType())
17204 return;
17205 if (ME->isArrow())
17206 BaseType = BaseType->getPointeeType();
17207 auto *RD = BaseType->castAsRecordDecl();
17208 if (RD->isInvalidDecl())
17209 return;
17210
17211 ValueDecl *MD = ME->getMemberDecl();
17212 auto *FD = dyn_cast<FieldDecl>(MD);
17213 // We do not care about non-data members.
17214 if (!FD || FD->isInvalidDecl())
17215 return;
17216
17217 AnyIsPacked =
17218 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17219 ReverseMemberChain.push_back(FD);
17220
17221 TopME = ME;
17222 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
17223 } while (ME);
17224 assert(TopME && "We did not compute a topmost MemberExpr!");
17225
17226 // Not the scope of this diagnostic.
17227 if (!AnyIsPacked)
17228 return;
17229
17230 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17231 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
17232 // TODO: The innermost base of the member expression may be too complicated.
17233 // For now, just disregard these cases. This is left for future
17234 // improvement.
17235 if (!DRE && !isa<CXXThisExpr>(TopBase))
17236 return;
17237
17238 // Alignment expected by the whole expression.
17239 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
17240
17241 // No need to do anything else with this case.
17242 if (ExpectedAlignment.isOne())
17243 return;
17244
17245 // Synthesize offset of the whole access.
17246 CharUnits Offset;
17247 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
17248 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
17249
17250 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17251 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17252 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
17253
17254 // The base expression of the innermost MemberExpr may give
17255 // stronger guarantees than the class containing the member.
17256 if (DRE && !TopME->isArrow()) {
17257 const ValueDecl *VD = DRE->getDecl();
17258 if (!VD->getType()->isReferenceType())
17259 CompleteObjectAlignment =
17260 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
17261 }
17262
17263 // Check if the synthesized offset fulfills the alignment.
17264 if (!Offset.isMultipleOf(ExpectedAlignment) ||
17265 // It may fulfill the offset it but the effective alignment may still be
17266 // lower than the expected expression alignment.
17267 CompleteObjectAlignment < ExpectedAlignment) {
17268 // If this happens, we want to determine a sensible culprit of this.
17269 // Intuitively, watching the chain of member expressions from right to
17270 // left, we start with the required alignment (as required by the field
17271 // type) but some packed attribute in that chain has reduced the alignment.
17272 // It may happen that another packed structure increases it again. But if
17273 // we are here such increase has not been enough. So pointing the first
17274 // FieldDecl that either is packed or else its RecordDecl is,
17275 // seems reasonable.
17276 FieldDecl *FD = nullptr;
17277 CharUnits Alignment;
17278 for (FieldDecl *FDI : ReverseMemberChain) {
17279 if (FDI->hasAttr<PackedAttr>() ||
17280 FDI->getParent()->hasAttr<PackedAttr>()) {
17281 FD = FDI;
17282 Alignment = std::min(Context.getTypeAlignInChars(FD->getType()),
17283 Context.getTypeAlignInChars(
17284 Context.getCanonicalTagType(FD->getParent())));
17285 break;
17286 }
17287 }
17288 assert(FD && "We did not find a packed FieldDecl!");
17289 Action(E, FD->getParent(), FD, Alignment);
17290 }
17291}
17292
17293void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17294 using namespace std::placeholders;
17295
17297 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
17298 _2, _3, _4));
17299}
17300
17302 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17303 if (checkArgCount(TheCall, 1))
17304 return true;
17305
17306 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0));
17307 if (A.isInvalid())
17308 return true;
17309
17310 TheCall->setArg(0, A.get());
17311 QualType TyA = A.get()->getType();
17312
17313 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA,
17314 ArgTyRestr, 1))
17315 return true;
17316
17317 TheCall->setType(TyA);
17318 return false;
17319}
17320
17321bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
17322 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17323 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
17324 TheCall->setType(*Res);
17325 return false;
17326 }
17327 return true;
17328}
17329
17331 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
17332 if (!Res)
17333 return true;
17334
17335 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
17336 TheCall->setType(VecTy0->getElementType());
17337 else
17338 TheCall->setType(*Res);
17339
17340 return false;
17341}
17342
17344 SourceLocation Loc) {
17346 R = RHS->getEnumCoercedType(S.Context);
17347 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
17349 return S.Diag(Loc, diag::err_conv_mixed_enum_types)
17350 << LHS->getSourceRange() << RHS->getSourceRange()
17351 << /*Arithmetic Between*/ 0 << L << R;
17352 }
17353 return false;
17354}
17355
17356/// Check if all arguments have the same type. If the types don't match, emit an
17357/// error message and return true. Otherwise return false.
17358///
17359/// For scalars we directly compare their unqualified types. But even if we
17360/// compare unqualified vector types, a difference in qualifiers in the element
17361/// types can make the vector types be considered not equal. For example,
17362/// vector of 4 'const float' values vs vector of 4 'float' values.
17363/// So we compare unqualified types of their elements and number of elements.
17365 ArrayRef<Expr *> Args) {
17366 assert(!Args.empty() && "Should have at least one argument.");
17367
17368 Expr *Arg0 = Args.front();
17369 QualType Ty0 = Arg0->getType();
17370
17371 auto EmitError = [&](Expr *ArgI) {
17372 SemaRef.Diag(Arg0->getBeginLoc(),
17373 diag::err_typecheck_call_different_arg_types)
17374 << Arg0->getType() << ArgI->getType();
17375 };
17376
17377 // Compare scalar types.
17378 if (!Ty0->isVectorType()) {
17379 for (Expr *ArgI : Args.drop_front())
17380 if (!SemaRef.Context.hasSameUnqualifiedType(Ty0, ArgI->getType())) {
17381 EmitError(ArgI);
17382 return true;
17383 }
17384
17385 return false;
17386 }
17387
17388 // Compare vector types.
17389 const auto *Vec0 = Ty0->castAs<VectorType>();
17390 for (Expr *ArgI : Args.drop_front()) {
17391 const auto *VecI = ArgI->getType()->getAs<VectorType>();
17392 if (!VecI ||
17393 !SemaRef.Context.hasSameUnqualifiedType(Vec0->getElementType(),
17394 VecI->getElementType()) ||
17395 Vec0->getNumElements() != VecI->getNumElements()) {
17396 EmitError(ArgI);
17397 return true;
17398 }
17399 }
17400
17401 return false;
17402}
17403
17404std::optional<QualType>
17406 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17407 if (checkArgCount(TheCall, 2))
17408 return std::nullopt;
17409
17411 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc()))
17412 return std::nullopt;
17413
17414 Expr *Args[2];
17415 for (int I = 0; I < 2; ++I) {
17416 ExprResult Converted =
17417 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17418 if (Converted.isInvalid())
17419 return std::nullopt;
17420 Args[I] = Converted.get();
17421 }
17422
17423 SourceLocation LocA = Args[0]->getBeginLoc();
17424 QualType TyA = Args[0]->getType();
17425
17426 if (checkMathBuiltinElementType(*this, LocA, TyA, ArgTyRestr, 1))
17427 return std::nullopt;
17428
17429 if (checkBuiltinVectorMathArgTypes(*this, Args))
17430 return std::nullopt;
17431
17432 TheCall->setArg(0, Args[0]);
17433 TheCall->setArg(1, Args[1]);
17434 return TyA;
17435}
17436
17438 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17439 if (checkArgCount(TheCall, 3))
17440 return true;
17441
17442 SourceLocation Loc = TheCall->getExprLoc();
17443 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0),
17444 TheCall->getArg(1), Loc) ||
17445 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1),
17446 TheCall->getArg(2), Loc))
17447 return true;
17448
17449 Expr *Args[3];
17450 for (int I = 0; I < 3; ++I) {
17451 ExprResult Converted =
17452 BuiltinVectorMathConversions(*this, TheCall->getArg(I));
17453 if (Converted.isInvalid())
17454 return true;
17455 Args[I] = Converted.get();
17456 }
17457
17458 int ArgOrdinal = 1;
17459 for (Expr *Arg : Args) {
17460 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(),
17461 ArgTyRestr, ArgOrdinal++))
17462 return true;
17463 }
17464
17465 if (checkBuiltinVectorMathArgTypes(*this, Args))
17466 return true;
17467
17468 for (int I = 0; I < 3; ++I)
17469 TheCall->setArg(I, Args[I]);
17470
17471 TheCall->setType(Args[0]->getType());
17472 return false;
17473}
17474
17475bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17476 if (checkArgCount(TheCall, 1))
17477 return true;
17478
17479 ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
17480 if (A.isInvalid())
17481 return true;
17482
17483 TheCall->setArg(0, A.get());
17484 return false;
17485}
17486
17487bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17488 if (checkArgCount(TheCall, 1))
17489 return true;
17490
17491 ExprResult Arg = TheCall->getArg(0);
17492 QualType TyArg = Arg.get()->getType();
17493
17494 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17495 return Diag(TheCall->getArg(0)->getBeginLoc(),
17496 diag::err_builtin_invalid_arg_type)
17497 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17498
17499 TheCall->setType(TyArg);
17500 return false;
17501}
17502
17503ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17504 ExprResult CallResult) {
17505 if (checkArgCount(TheCall, 1))
17506 return ExprError();
17507
17508 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
17509 if (MatrixArg.isInvalid())
17510 return MatrixArg;
17511 Expr *Matrix = MatrixArg.get();
17512
17513 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17514 if (!MType) {
17515 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17516 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17517 << Matrix->getType();
17518 return ExprError();
17519 }
17520
17521 // Create returned matrix type by swapping rows and columns of the argument
17522 // matrix type.
17523 QualType ResultType = Context.getConstantMatrixType(
17524 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17525
17526 // Change the return type to the type of the returned matrix.
17527 TheCall->setType(ResultType);
17528
17529 // Update call argument to use the possibly converted matrix argument.
17530 TheCall->setArg(0, Matrix);
17531 return CallResult;
17532}
17533
17534// Get and verify the matrix dimensions.
17535static std::optional<unsigned>
17537 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(S.Context);
17538 if (!Value) {
17539 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
17540 << Name;
17541 return {};
17542 }
17543 uint64_t Dim = Value->getZExtValue();
17544 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17545 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
17546 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17547 return {};
17548 }
17549 return Dim;
17550}
17551
17552ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17553 ExprResult CallResult) {
17554 if (!getLangOpts().MatrixTypes) {
17555 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17556 return ExprError();
17557 }
17558
17559 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17561 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17562 << /*column*/ 1 << /*load*/ 0;
17563 return ExprError();
17564 }
17565
17566 if (checkArgCount(TheCall, 4))
17567 return ExprError();
17568
17569 unsigned PtrArgIdx = 0;
17570 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17571 Expr *RowsExpr = TheCall->getArg(1);
17572 Expr *ColumnsExpr = TheCall->getArg(2);
17573 Expr *StrideExpr = TheCall->getArg(3);
17574
17575 bool ArgError = false;
17576
17577 // Check pointer argument.
17578 {
17580 if (PtrConv.isInvalid())
17581 return PtrConv;
17582 PtrExpr = PtrConv.get();
17583 TheCall->setArg(0, PtrExpr);
17584 if (PtrExpr->isTypeDependent()) {
17585 TheCall->setType(Context.DependentTy);
17586 return TheCall;
17587 }
17588 }
17589
17590 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17591 QualType ElementTy;
17592 if (!PtrTy) {
17593 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17594 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17595 << PtrExpr->getType();
17596 ArgError = true;
17597 } else {
17598 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17599
17601 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17602 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17603 << /* no fp */ 0 << PtrExpr->getType();
17604 ArgError = true;
17605 }
17606 }
17607
17608 // Apply default Lvalue conversions and convert the expression to size_t.
17609 auto ApplyArgumentConversions = [this](Expr *E) {
17611 if (Conv.isInvalid())
17612 return Conv;
17613
17614 return tryConvertExprToType(Conv.get(), Context.getSizeType());
17615 };
17616
17617 // Apply conversion to row and column expressions.
17618 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17619 if (!RowsConv.isInvalid()) {
17620 RowsExpr = RowsConv.get();
17621 TheCall->setArg(1, RowsExpr);
17622 } else
17623 RowsExpr = nullptr;
17624
17625 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17626 if (!ColumnsConv.isInvalid()) {
17627 ColumnsExpr = ColumnsConv.get();
17628 TheCall->setArg(2, ColumnsExpr);
17629 } else
17630 ColumnsExpr = nullptr;
17631
17632 // If any part of the result matrix type is still pending, just use
17633 // Context.DependentTy, until all parts are resolved.
17634 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17635 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17636 TheCall->setType(Context.DependentTy);
17637 return CallResult;
17638 }
17639
17640 // Check row and column dimensions.
17641 std::optional<unsigned> MaybeRows;
17642 if (RowsExpr)
17643 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
17644
17645 std::optional<unsigned> MaybeColumns;
17646 if (ColumnsExpr)
17647 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
17648
17649 // Check stride argument.
17650 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17651 if (StrideConv.isInvalid())
17652 return ExprError();
17653 StrideExpr = StrideConv.get();
17654 TheCall->setArg(3, StrideExpr);
17655
17656 if (MaybeRows) {
17657 if (std::optional<llvm::APSInt> Value =
17658 StrideExpr->getIntegerConstantExpr(Context)) {
17659 uint64_t Stride = Value->getZExtValue();
17660 if (Stride < *MaybeRows) {
17661 Diag(StrideExpr->getBeginLoc(),
17662 diag::err_builtin_matrix_stride_too_small);
17663 ArgError = true;
17664 }
17665 }
17666 }
17667
17668 if (ArgError || !MaybeRows || !MaybeColumns)
17669 return ExprError();
17670
17671 TheCall->setType(
17672 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17673 return CallResult;
17674}
17675
17676ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17677 ExprResult CallResult) {
17678 if (!getLangOpts().MatrixTypes) {
17679 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
17680 return ExprError();
17681 }
17682
17683 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17685 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17686 << /*column*/ 1 << /*store*/ 1;
17687 return ExprError();
17688 }
17689
17690 if (checkArgCount(TheCall, 3))
17691 return ExprError();
17692
17693 unsigned PtrArgIdx = 1;
17694 Expr *MatrixExpr = TheCall->getArg(0);
17695 Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
17696 Expr *StrideExpr = TheCall->getArg(2);
17697
17698 bool ArgError = false;
17699
17700 {
17701 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
17702 if (MatrixConv.isInvalid())
17703 return MatrixConv;
17704 MatrixExpr = MatrixConv.get();
17705 TheCall->setArg(0, MatrixExpr);
17706 }
17707 if (MatrixExpr->isTypeDependent()) {
17708 TheCall->setType(Context.DependentTy);
17709 return TheCall;
17710 }
17711
17712 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17713 if (!MatrixTy) {
17714 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17715 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17716 ArgError = true;
17717 }
17718
17719 {
17721 if (PtrConv.isInvalid())
17722 return PtrConv;
17723 PtrExpr = PtrConv.get();
17724 TheCall->setArg(1, PtrExpr);
17725 if (PtrExpr->isTypeDependent()) {
17726 TheCall->setType(Context.DependentTy);
17727 return TheCall;
17728 }
17729 }
17730
17731 // Check pointer argument.
17732 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17733 if (!PtrTy) {
17734 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
17735 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17736 << PtrExpr->getType();
17737 ArgError = true;
17738 } else {
17739 QualType ElementTy = PtrTy->getPointeeType();
17740 if (ElementTy.isConstQualified()) {
17741 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17742 ArgError = true;
17743 }
17744 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17745 if (MatrixTy &&
17746 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17747 Diag(PtrExpr->getBeginLoc(),
17748 diag::err_builtin_matrix_pointer_arg_mismatch)
17749 << ElementTy << MatrixTy->getElementType();
17750 ArgError = true;
17751 }
17752 }
17753
17754 // Apply default Lvalue conversions and convert the stride expression to
17755 // size_t.
17756 {
17757 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
17758 if (StrideConv.isInvalid())
17759 return StrideConv;
17760
17761 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
17762 if (StrideConv.isInvalid())
17763 return StrideConv;
17764 StrideExpr = StrideConv.get();
17765 TheCall->setArg(2, StrideExpr);
17766 }
17767
17768 // Check stride argument.
17769 if (MatrixTy) {
17770 if (std::optional<llvm::APSInt> Value =
17771 StrideExpr->getIntegerConstantExpr(Context)) {
17772 uint64_t Stride = Value->getZExtValue();
17773 if (Stride < MatrixTy->getNumRows()) {
17774 Diag(StrideExpr->getBeginLoc(),
17775 diag::err_builtin_matrix_stride_too_small);
17776 ArgError = true;
17777 }
17778 }
17779 }
17780
17781 if (ArgError)
17782 return ExprError();
17783
17784 return CallResult;
17785}
17786
17788 const NamedDecl *Callee) {
17789 // This warning does not make sense in code that has no runtime behavior.
17791 return;
17792
17793 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17794
17795 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17796 return;
17797
17798 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17799 // all TCBs the callee is a part of.
17800 llvm::StringSet<> CalleeTCBs;
17801 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17802 CalleeTCBs.insert(A->getTCBName());
17803 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17804 CalleeTCBs.insert(A->getTCBName());
17805
17806 // Go through the TCBs the caller is a part of and emit warnings if Caller
17807 // is in a TCB that the Callee is not.
17808 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17809 StringRef CallerTCB = A->getTCBName();
17810 if (CalleeTCBs.count(CallerTCB) == 0) {
17811 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17812 << Callee << CallerTCB;
17813 }
17814 }
17815}
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 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:158
APSInt & getInt()
Definition APValue.h:573
bool isVector() const
Definition APValue.h:555
APSInt & getComplexIntImag()
Definition APValue.h:611
bool isComplexInt() const
Definition APValue.h:552
bool isFloat() const
Definition APValue.h:550
bool isComplexFloat() const
Definition APValue.h:553
APValue & getVectorElt(unsigned I)
Definition APValue.h:647
unsigned getVectorLength() const
Definition APValue.h:655
bool isLValue() const
Definition APValue.h:554
bool isInt() const
Definition APValue.h:549
APValue & getMatrixElt(unsigned Idx)
Definition APValue.h:671
APSInt & getComplexIntReal()
Definition APValue.h:603
APFloat & getComplexFloatImag()
Definition APValue.h:627
APFloat & getComplexFloatReal()
Definition APValue.h:619
APFloat & getFloat()
Definition APValue.h:587
bool isMatrix() const
Definition APValue.h:556
unsigned getMatrixNumElements() const
Definition APValue.h:668
bool isAddrLabelDiff() const
Definition APValue.h:561
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
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:852
Builtin::Context & BuiltinInfo
Definition ASTContext.h:854
const LangOptions & getLangOpts() const
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
CanQualType OverloadTy
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:905
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:971
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:4422
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4600
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4606
SourceLocation getQuestionLoc() const
Definition Expr.h:4449
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4612
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:7383
Expr * getLowerBound()
Get lower bound of array section.
Definition Expr.h:7387
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2790
SourceLocation getRBracketLoc() const
Definition Expr.h:2838
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2819
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3834
QualType getElementType() const
Definition TypeBase.h:3832
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition Expr.h:7014
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
Definition Expr.h:7163
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:7145
Attr - This represents one attribute.
Definition Attr.h:47
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:4107
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4240
Expr * getLHS() const
Definition Expr.h:4157
SourceLocation getOperatorLoc() const
Definition Expr.h:4149
SourceLocation getExprLoc() const
Definition Expr.h:4148
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2170
Expr * getRHS() const
Definition Expr.h:4159
static bool isAdditiveOp(Opcode Opc)
Definition Expr.h:4193
Opcode getOpcode() const
Definition Expr.h:4152
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4204
BinaryOperatorKind Opcode
Definition Expr.h:4112
Pointer to a block type.
Definition TypeBase.h:3653
This class is used for builtin types like 'int'.
Definition TypeBase.h:3245
bool isInteger() const
Definition TypeBase.h:3312
bool isFloatingPoint() const
Definition TypeBase.h:3324
bool isSignedInteger() const
Definition TypeBase.h:3316
bool isUnsignedInteger() const
Definition TypeBase.h:3320
Kind getKind() const
Definition TypeBase.h:3299
llvm::SmallString< 64 > 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:385
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:4038
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Definition ExprCXX.h:1635
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1693
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2977
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:86
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprCXX.h:159
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Definition ExprCXX.h:116
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5195
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5235
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:1235
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:549
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1224
bool isDynamicClass() const
Definition DeclCXX.h:575
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:77
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
SourceLocation getBeginLoc() const
Definition Expr.h:3346
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3229
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition Expr.cpp:1624
arg_iterator arg_begin()
Definition Expr.h:3269
arg_iterator arg_end()
Definition Expr.h:3272
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
bool isCallToStdMove() const
Definition Expr.cpp:3682
Expr * getCallee()
Definition Expr.h:3159
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3203
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Definition Expr.h:3305
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3206
arg_range arguments()
Definition Expr.h:3264
SourceLocation getEndLoc() const
Definition Expr.h:3365
SourceLocation getRParenLoc() const
Definition Expr.h:3343
Decl * getCalleeDecl()
Definition Expr.h:3189
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:1629
void setCallee(Expr *F)
Definition Expr.h:3161
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition Expr.h:3248
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:3745
path_iterator path_begin()
Definition Expr.h:3815
CastKind getCastKind() const
Definition Expr.h:3789
path_iterator path_end()
Definition Expr.h:3816
Expr * getSubExpr()
Definition Expr.h:3795
Represents a byte-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
bool isOne() const
Test whether the quantity equals one.
Definition CharUnits.h:104
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
ConditionalOperator - The ?
Definition Expr.h:4460
Expr * getLHS() const
Definition Expr.h:4494
Expr * getRHS() const
Definition Expr.h:4495
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
QualType desugar() const
Definition TypeBase.h:3959
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3914
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:4622
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
Definition TypeBase.h:4649
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:5731
Expr * getOperand() const
Definition ExprCXX.h:5378
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:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2121
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2418
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2176
DeclContext * getEnclosingNonExpansionStatementContext()
Retrieve the innermost enclosing context that doesn't belong to an expansion statement.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
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:498
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1408
ValueDecl * getDecl()
Definition Expr.h:1383
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1513
SourceLocation getBeginLoc() const
Definition Expr.h:1394
SourceLocation getLocation() const
Definition Expr.h:1391
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:444
T * getAttr() const
Definition DeclBase.h:582
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:597
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:568
SourceLocation getLocation() const
Definition DeclBase.h:448
DeclContext * getDeclContext()
Definition DeclBase.h:457
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:440
bool hasAttr() const
Definition DeclBase.h:586
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:436
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
Definition Decl.cpp:2005
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:811
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:241
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:992
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3574
Represents an enum.
Definition Decl.h:4162
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4394
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4335
This represents one expression.
Definition Expr.h:114
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:3156
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:703
@ SE_NoSideEffects
Strictly evaluate the expression.
Definition Expr.h:700
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
void setType(QualType t)
Definition Expr.h:147
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:449
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
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:3129
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3117
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:248
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:3125
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:286
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4271
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:876
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:880
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:456
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:3113
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3121
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:3728
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:225
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:3109
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:847
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:856
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:859
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:849
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:4110
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:466
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:469
QualType getType() const
Definition Expr.h:146
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:528
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:4497
Represents a member of a struct/union/class.
Definition Decl.h:3311
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3414
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4843
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3547
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3427
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
llvm::APFloat getValue() const
Definition Expr.h:1711
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2899
Represents a function declaration or definition.
Definition Decl.h:2071
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
Definition Decl.cpp:4638
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2944
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3824
param_iterator param_end()
Definition Decl.h:2930
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3932
QualType getReturnType() const
Definition Decl.h:2992
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2917
param_iterator param_begin()
Definition Decl.h:2929
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3139
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4393
bool isStatic() const
Definition Decl.h:3076
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4208
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4194
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3888
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
unsigned getNumParams() const
Definition TypeBase.h:5826
QualType getParamType(unsigned i) const
Definition TypeBase.h:5828
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5952
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5837
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition TypeBase.h:5947
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5833
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:5053
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:5049
QualType getReturnType() const
Definition TypeBase.h:5084
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:3922
Describes an C or C++ initializer list.
Definition Expr.h:5377
ArrayRef< Expr * > inits() const
Definition Expr.h:5441
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:985
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:4567
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4593
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3510
bool isArrow() const
Definition Expr.h:3617
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
This represents a decl that may have a name.
Definition Decl.h:276
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1209
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition Decl.cpp:1945
Represent a C++ namespace.
Definition Decl.h:594
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition Stmt.h:1714
bool hasLeadingEmptyMacro() const
Definition Stmt.h:1728
SourceLocation getSemiLoc() const
Definition Stmt.h:1725
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:280
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2251
Represents a parameter to a function.
Definition Decl.h:1832
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:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6890
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5238
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8662
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition Type.cpp:3092
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:8578
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
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:8630
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
void removeLocalVolatile()
Definition TypeBase.h:8694
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1195
void removeLocalConst()
Definition TypeBase.h:8686
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8651
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8699
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1841
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8624
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:4476
bool hasFlexibleArrayMember() const
Definition Decl.h:4509
bool isNonTrivialToPrimitiveCopy() const
Definition Decl.h:4562
field_range fields() const
Definition Decl.h:4679
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Definition Decl.h:4554
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:1191
@ 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:1273
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:574
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10492
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Definition Sema.h:10497
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:862
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:1473
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:13294
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1164
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:2890
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9501
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9509
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9546
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:7076
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:2106
SemaHexagon & Hexagon()
Definition Sema.h:1513
SemaSYCL & SYCL()
Definition Sema.h:1583
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:1779
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:848
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
SemaX86 & X86()
Definition Sema.h:1603
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:1331
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:229
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:931
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:1543
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
Definition Sema.h:1398
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:769
ASTContext & getASTContext() const
Definition Sema.h:934
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:774
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
Definition Sema.h:2739
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:1235
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:2846
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:927
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:1488
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:1503
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:1329
static const uint64_t MaximumAlignment
Definition Sema.h:1258
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:967
SemaHLSL & HLSL()
Definition Sema.h:1508
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
SemaMIPS & MIPS()
Definition Sema.h:1528
SemaRISCV & RISCV()
Definition Sema.h:1573
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
bool convertArgumentToType(Expr *&Value, QualType Ty)
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:2912
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7112
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1791
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:1366
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:2819
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
Definition Sema.h:15719
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:2476
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:649
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:1471
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:1553
FormatArgumentPassingKind
Definition Sema.h:2749
@ FAPK_Elsewhere
Definition Sema.h:2753
@ FAPK_Fixed
Definition Sema.h:2750
@ FAPK_Variadic
Definition Sema.h:2751
@ FAPK_VAList
Definition Sema.h:2752
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:8337
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:14213
SourceManager & getSourceManager() const
Definition Sema.h:932
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:2741
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:1563
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:1290
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:1593
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:1334
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:798
DiagnosticsEngine & Diags
Definition Sema.h:1333
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:1538
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:643
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:6429
SemaSPIRV & SPIRV()
Definition Sema.h:1578
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:1518
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6564
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:1598
SemaARM & ARM()
Definition Sema.h:1478
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:4712
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:1504
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:1844
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2042
bool isUTF8() const
Definition Expr.h:1979
bool isWide() const
Definition Expr.h:1978
bool isPascal() const
Definition Expr.h:1983
unsigned getLength() const
Definition Expr.h:1969
StringLiteralKind getKind() const
Definition Expr.h:1973
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:1336
bool isUTF32() const
Definition Expr.h:1981
unsigned getByteLength() const
Definition Expr.h:1967
StringRef getString() const
Definition Expr.h:1912
bool isUTF16() const
Definition Expr.h:1980
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.h:2043
bool isOrdinary() const
Definition Expr.h:1977
unsigned getCharByteWidth() const
Definition Expr.h:1971
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition Decl.h:3989
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3969
bool isUnion() const
Definition Decl.h:4079
Exposes information about the current target.
Definition TargetInfo.h:228
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:396
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:6458
A container of type source information.
Definition TypeBase.h:8549
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:8560
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isBlockPointerType() const
Definition TypeBase.h:8835
bool isVoidType() const
Definition TypeBase.h:9200
bool isBooleanType() const
Definition TypeBase.h:9341
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2415
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9391
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:920
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2392
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition Type.cpp:2483
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2299
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:9371
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:845
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2645
bool isArrayType() const
Definition TypeBase.h:8914
bool isFunctionPointerType() const
Definition TypeBase.h:8882
bool isPointerType() const
Definition TypeBase.h:8815
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isReferenceType() const
Definition TypeBase.h:8839
bool isEnumeralType() const
Definition TypeBase.h:8946
bool isScalarType() const
Definition TypeBase.h:9310
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:2080
bool isVariableArrayType() const
Definition TypeBase.h:8926
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2829
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9326
bool isExtVectorType() const
Definition TypeBase.h:8958
bool isExtVectorBoolType() const
Definition TypeBase.h:8962
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2866
bool isBitIntType() const
Definition TypeBase.h:9090
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9169
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8938
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8950
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2436
QualType getCanonicalTypeInternal() const
Definition TypeBase.h:3200
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2779
bool isMemberPointerType() const
Definition TypeBase.h:8896
bool isAtomicType() const
Definition TypeBase.h:9007
bool isFunctionProtoType() const
Definition TypeBase.h:2665
bool isMatrixType() const
Definition TypeBase.h:8978
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition Type.cpp:3334
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:2881
bool isUnscopedEnumerationType() const
Definition Type.cpp:2312
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9484
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9347
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:2655
bool isFunctionType() const
Definition TypeBase.h:8811
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2525
bool isStructureOrClassType() const
Definition Type.cpp:839
bool isVectorType() const
Definition TypeBase.h:8954
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2533
bool isFloatingType() const
Definition Type.cpp:2517
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:2460
bool isAnyPointerType() const
Definition TypeBase.h:8823
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:9431
bool isNullPtrType() const
Definition TypeBase.h:9241
bool isRecordType() const
Definition TypeBase.h:8942
bool isObjCRetainableType() const
Definition Type.cpp:5609
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2791
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5325
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Definition Type.cpp:2854
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3713
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2694
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2431
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1110
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1198
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3429
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5678
Represents a variable declaration or definition.
Definition Decl.h:934
Represents a GCC generic vector type.
Definition TypeBase.h:4398
unsigned getNumElements() const
Definition TypeBase.h:4413
QualType getElementType() const
Definition TypeBase.h:4412
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2708
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:240
@ 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:1520
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1505
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1498
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1512
bool Cast(InterpState &S, CodePtr OpPC)
Definition Interp.h:2858
bool EQ(InterpState &S, CodePtr OpPC)
Definition Interp.h:1451
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1527
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:823
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:506
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
Definition Sema.h:656
@ Comparison
A comparison.
Definition Sema.h:660
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:352
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:153
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:155
PointerAuthDiscArgKind
Definition Sema.h:587
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:128
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:261
@ 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:685
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:150
ExprResult ExprError()
Definition Ownership.h:265
LangAS
Defines the address space values used by the address space qualifier of QualType.
FormatStringType
Definition Sema.h:492
CastKind
CastKind - The kind of operation required for a conversion.
unsigned getFunctionOrMethodNumParams(const Decl *D, bool IncludeThis=false)
getFunctionOrMethodNumParams - Return number of function or method parameters, optionally including t...
Definition Attr.h:66
BuiltinCountedByRefKind
Definition Sema.h:514
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:164
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:136
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
for(const auto &A :T->param_types())
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
Definition IgnoreExpr.h:144
StringLiteralKind
Definition Expr.h:1808
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
@ CC_Win64
Definition Specifiers.h:289
@ CC_X86_64SysV
Definition Specifiers.h:290
@ Generic
not a target-specific vector type
Definition TypeBase.h:4234
U cast(CodeGen::Address addr)
Definition Address.h:327
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6167
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6160
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1787
unsigned long uint64_t
__builtin_bitreverse32 uint32_t __builtin_riscv_aaddu_u32 __builtin_riscv_asubu_u32 __builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t uint32_t uint32_t __builtin_riscv_mhacc_i32 __builtin_riscv_mhaccu_u32 __builtin_riscv_mhaccsu_i32 __builtin_riscv_mulq_i32 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:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
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:651
Extra information about a function prototype.
Definition TypeBase.h:5633
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:13476
unsigned NumCallArgs
The number of expressions in CallArgs.
Definition Sema.h:13502
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
Definition Sema.h:13492
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13440
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.
Definition Sema.h:6970
FormatArgumentPassingKind ArgPassingKind
Definition Sema.h:2761
#define log2(__x)
Definition tgmath.h:970