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"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTDiagnostic.h"
18#include "clang/AST/Attr.h"
19#include "clang/AST/AttrIterator.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"
25#include "clang/AST/DeclarationName.h"
26#include "clang/AST/EvaluatedExprVisitor.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
30#include "clang/AST/FormatString.h"
31#include "clang/AST/IgnoreExpr.h"
32#include "clang/AST/NSAPI.h"
33#include "clang/AST/NonTrivialTypeVisitor.h"
34#include "clang/AST/OperationKinds.h"
35#include "clang/AST/RecordLayout.h"
36#include "clang/AST/Stmt.h"
37#include "clang/AST/TemplateBase.h"
38#include "clang/AST/TemplateName.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeBase.h"
41#include "clang/AST/TypeLoc.h"
42#include "clang/AST/UnresolvedSet.h"
43#include "clang/Basic/AddressSpaces.h"
44#include "clang/Basic/BuiltinTraits.h"
45#include "clang/Basic/Diagnostic.h"
46#include "clang/Basic/DiagnosticSema.h"
47#include "clang/Basic/IdentifierTable.h"
48#include "clang/Basic/LLVM.h"
49#include "clang/Basic/LangOptions.h"
50#include "clang/Basic/OpenCLOptions.h"
51#include "clang/Basic/OperatorKinds.h"
52#include "clang/Basic/PartialDiagnostic.h"
53#include "clang/Basic/SourceLocation.h"
54#include "clang/Basic/SourceManager.h"
55#include "clang/Basic/Specifiers.h"
56#include "clang/Basic/SyncScope.h"
57#include "clang/Basic/TargetInfo.h"
58#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
59#include "clang/Sema/Initialization.h"
60#include "clang/Sema/Lookup.h"
61#include "clang/Sema/Ownership.h"
62#include "clang/Sema/Scope.h"
63#include "clang/Sema/ScopeInfo.h"
64#include "clang/Sema/Sema.h"
65#include "clang/Sema/SemaAMDGPU.h"
66#include "clang/Sema/SemaARM.h"
67#include "clang/Sema/SemaBPF.h"
68#include "clang/Sema/SemaDirectX.h"
69#include "clang/Sema/SemaHLSL.h"
70#include "clang/Sema/SemaHexagon.h"
71#include "clang/Sema/SemaLoongArch.h"
72#include "clang/Sema/SemaMIPS.h"
73#include "clang/Sema/SemaNVPTX.h"
74#include "clang/Sema/SemaObjC.h"
75#include "clang/Sema/SemaOpenCL.h"
76#include "clang/Sema/SemaPPC.h"
77#include "clang/Sema/SemaRISCV.h"
78#include "clang/Sema/SemaSPIRV.h"
79#include "clang/Sema/SemaSYCL.h"
80#include "clang/Sema/SemaSystemZ.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
125SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
126 unsigned ByteNo) const {
127 return SL->getLocationOfByte(ByteNo, SM: getSourceManager(), Features: LangOpts,
128 Target: Context.getTargetInfo());
129}
130
131static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
132 Sema::FormatArgumentPassingKind B) {
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(Loc: Call->getEndLoc(), DiagID: 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(Loc: Call->getEndLoc(), DiagID: 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, MinArgCount: DesiredArgCount))
167 return true;
168 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
169
170 // Highlight all the excess arguments.
171 SourceRange Range(Call->getArg(Arg: DesiredArgCount)->getBeginLoc(),
172 Call->getArg(Arg: ArgCount - 1)->getEndLoc());
173
174 return Diag(Loc: Range.getBegin(), DiagID: diag::err_typecheck_call_too_many_args)
175 << 0 /*function call*/ << DesiredArgCount << ArgCount
176 << /*is non object*/ 0 << Range;
177}
178
179static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S) {
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(Ctx&: 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(c: '$') != std::string::npos)
192 DiagMsgKind = 1;
193
194 if (DiagMsgKind >= 0) {
195 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_verbose_trap_arg)
196 << DiagMsgKind << Arg->getSourceRange();
197 HasError = true;
198 }
199 }
200
201 return !HasError;
202}
203
204bool Sema::convertArgumentToType(Expr *&Value, QualType Ty) {
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
209 InitializedEntity::InitializeParameter(Context, Type: Ty, Consumed: false);
210 ExprResult Result =
211 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Value);
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(Call: TheCall, DesiredArgCount: 2))
222 return true;
223
224 // First argument should be an integer.
225 Expr *ValArg = TheCall->getArg(Arg: 0);
226 QualType Ty = ValArg->getType();
227 if (!Ty->isIntegerType()) {
228 S.Diag(Loc: ValArg->getBeginLoc(), DiagID: 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(Arg: 1)->IgnoreParenCasts();
235 StringLiteral *Literal = dyn_cast<StringLiteral>(Val: StrArg);
236 if (!Literal || !Literal->isOrdinary()) {
237 S.Diag(Loc: StrArg->getBeginLoc(), DiagID: 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(Loc: TheCall->getEndLoc(), DiagID: 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>(Val: Arg->IgnoreParenCasts());
258 if (!Literal || !Literal->isWide()) {
259 S.Diag(Loc: Arg->getBeginLoc(), DiagID: 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(Call: TheCall, DesiredArgCount: 1))
272 return true;
273
274 ExprResult Arg(TheCall->getArg(Arg: 0));
275 QualType ResultType = S.CheckAddressOfOperand(Operand&: Arg, OpLoc: TheCall->getBeginLoc());
276 if (ResultType.isNull())
277 return true;
278
279 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
280 TheCall->setType(ResultType);
281 return false;
282}
283
284/// Check that the argument to __builtin_function_start is a function.
285static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
286 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
287 return true;
288
289 if (TheCall->getArg(Arg: 0)->containsErrors())
290 return true;
291
292 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
293 if (Arg.isInvalid())
294 return true;
295
296 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
297 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
298 Val: Arg.get()->getAsBuiltinConstantDeclRef(Context: S.getASTContext()));
299
300 if (!FD) {
301 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_function_start_invalid_type)
302 << TheCall->getSourceRange();
303 return true;
304 }
305
306 return !S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
307 Loc: TheCall->getBeginLoc());
308}
309
310/// Check the number of arguments and set the result type to
311/// the argument type.
312static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
313 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
314 return true;
315
316 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
317 return false;
318}
319
320/// Check that the value argument for __builtin_is_aligned(value, alignment) and
321/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
322/// type (but not a function pointer) and that the alignment is a power-of-two.
323static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
324 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
325 return true;
326
327 clang::Expr *Source = TheCall->getArg(Arg: 0);
328 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
329
330 auto IsValidIntegerType = [](QualType Ty) {
331 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
332 };
333 QualType SrcTy = Source->getType();
334 // We should also be able to use it with arrays (but not functions!).
335 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
336 SrcTy = S.Context.getDecayedType(T: SrcTy);
337 }
338 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
339 SrcTy->isFunctionPointerType()) {
340 S.Diag(Loc: Source->getExprLoc(), DiagID: diag::err_typecheck_expect_scalar_operand)
341 << SrcTy;
342 if (SrcTy->isFloatingType())
343 S.Diag(Loc: Source->getExprLoc(), DiagID: diag::note_alignment_invalid_type);
344 else if (SrcTy->isMemberPointerType())
345 S.Diag(Loc: Source->getExprLoc(), DiagID: diag::note_alignment_invalid_member_pointer);
346 else if (SrcTy->isFunctionPointerType())
347 S.Diag(Loc: Source->getExprLoc(),
348 DiagID: diag::note_alignment_invalid_function_pointer);
349 return true;
350 }
351
352 clang::Expr *AlignOp = TheCall->getArg(Arg: 1);
353 if (!IsValidIntegerType(AlignOp->getType())) {
354 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_typecheck_expect_int)
355 << AlignOp->getType();
356 return true;
357 }
358 Expr::EvalResult AlignResult;
359 unsigned MaxAlignmentBits = S.Context.getIntWidth(T: SrcTy) - 1;
360 // We can't check validity of alignment if it is value dependent.
361 if (!AlignOp->isValueDependent() &&
362 AlignOp->EvaluateAsInt(Result&: AlignResult, Ctx: S.Context,
363 AllowSideEffects: Expr::SE_AllowSideEffects)) {
364 llvm::APSInt AlignValue = AlignResult.Val.getInt();
365 llvm::APSInt MaxValue(
366 llvm::APInt::getOneBitSet(numBits: MaxAlignmentBits + 1, BitNo: MaxAlignmentBits));
367 if (AlignValue < 1) {
368 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_too_small) << 1;
369 return true;
370 }
371 if (llvm::APSInt::compareValues(I1: AlignValue, I2: MaxValue) > 0) {
372 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_too_big)
373 << toString(I: MaxValue, Radix: 10);
374 return true;
375 }
376 if (!AlignValue.isPowerOf2()) {
377 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_not_power_of_two);
378 return true;
379 }
380 if (AlignValue == 1) {
381 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::warn_alignment_builtin_useless)
382 << IsBooleanAlignBuiltin;
383 }
384 }
385
386 ExprResult SrcArg = S.PerformCopyInitialization(
387 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Type: SrcTy, Consumed: false),
388 EqualLoc: SourceLocation(), Init: Source);
389 if (SrcArg.isInvalid())
390 return true;
391 TheCall->setArg(Arg: 0, ArgExpr: SrcArg.get());
392 ExprResult AlignArg =
393 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
394 Context&: S.Context, Type: AlignOp->getType(), Consumed: false),
395 EqualLoc: SourceLocation(), Init: AlignOp);
396 if (AlignArg.isInvalid())
397 return true;
398 TheCall->setArg(Arg: 1, ArgExpr: AlignArg.get());
399 // For align_up/align_down, the return type is the same as the (potentially
400 // decayed) argument type including qualifiers. For is_aligned(), the result
401 // is always bool.
402 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
403 return false;
404}
405
406static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
407 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
408 return true;
409
410 std::pair<unsigned, const char *> Builtins[] = {
411 { Builtin::BI__builtin_add_overflow, "ckd_add" },
412 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
413 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
414 };
415
416 bool CkdOperation = llvm::any_of(Range&: Builtins, P: [&](const std::pair<unsigned,
417 const char *> &P) {
418 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
419 Lexer::getImmediateMacroName(Loc: TheCall->getExprLoc(),
420 SM: S.getSourceManager(), LangOpts: S.getLangOpts()) == P.second;
421 });
422
423 auto ValidCkdIntType = [](QualType QT) {
424 // A valid checked integer type is an integer type other than a plain char,
425 // bool, a bit-precise type, or an enumeration type.
426 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
427 return (BT->getKind() >= BuiltinType::Short &&
428 BT->getKind() <= BuiltinType::Int128) || (
429 BT->getKind() >= BuiltinType::UShort &&
430 BT->getKind() <= BuiltinType::UInt128) ||
431 BT->getKind() == BuiltinType::UChar ||
432 BT->getKind() == BuiltinType::SChar;
433 return false;
434 };
435
436 // First two arguments should be integers.
437 for (unsigned I = 0; I < 2; ++I) {
438 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: I));
439 if (Arg.isInvalid()) return true;
440 TheCall->setArg(Arg: I, ArgExpr: Arg.get());
441
442 QualType Ty = Arg.get()->getType();
443 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
444 if (!IsValid) {
445 S.Diag(Loc: Arg.get()->getBeginLoc(), DiagID: diag::err_overflow_builtin_must_be_int)
446 << CkdOperation << Ty << Arg.get()->getSourceRange();
447 return true;
448 }
449 }
450
451 // Third argument should be a pointer to a non-const integer.
452 // IRGen correctly handles volatile, restrict, and address spaces, and
453 // the other qualifiers aren't possible.
454 {
455 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 2));
456 if (Arg.isInvalid()) return true;
457 TheCall->setArg(Arg: 2, ArgExpr: Arg.get());
458
459 QualType Ty = Arg.get()->getType();
460 const auto *PtrTy = Ty->getAs<PointerType>();
461 if (!PtrTy ||
462 !PtrTy->getPointeeType()->isIntegerType() ||
463 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
464 PtrTy->getPointeeType().isConstQualified()) {
465 S.Diag(Loc: Arg.get()->getBeginLoc(),
466 DiagID: diag::err_overflow_builtin_must_be_ptr_int)
467 << CkdOperation << Ty << Arg.get()->getSourceRange();
468 return true;
469 }
470 }
471
472 // Disallow signed bit-precise integer args larger than 128 bits to mul
473 // function until we improve backend support.
474 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
475 for (unsigned I = 0; I < 3; ++I) {
476 const auto Arg = TheCall->getArg(Arg: I);
477 // Third argument will be a pointer.
478 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
479 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
480 S.getASTContext().getIntWidth(T: Ty) > 128)
481 return S.Diag(Loc: Arg->getBeginLoc(),
482 DiagID: diag::err_overflow_builtin_bit_int_max_size)
483 << 128;
484 }
485 }
486
487 return false;
488}
489
490namespace {
491struct BuiltinDumpStructGenerator {
492 Sema &S;
493 CallExpr *TheCall;
494 SourceLocation Loc = TheCall->getBeginLoc();
495 SmallVector<Expr *, 32> Actions;
496 DiagnosticErrorTrap ErrorTracker;
497 PrintingPolicy Policy;
498
499 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
500 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
501 Policy(S.Context.getPrintingPolicy()) {
502 Policy.AnonymousTagNameStyle =
503 llvm::to_underlying(E: PrintingPolicy::AnonymousTagMode::Plain);
504 }
505
506 Expr *makeOpaqueValueExpr(Expr *Inner) {
507 auto *OVE = new (S.Context)
508 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
509 Inner->getObjectKind(), Inner);
510 Actions.push_back(Elt: OVE);
511 return OVE;
512 }
513
514 Expr *getStringLiteral(llvm::StringRef Str) {
515 Expr *Lit = S.Context.getPredefinedStringLiteralFromCache(Key: Str);
516 // Wrap the literal in parentheses to attach a source location.
517 return new (S.Context) ParenExpr(Loc, Loc, Lit);
518 }
519
520 bool callPrintFunction(llvm::StringRef Format,
521 llvm::ArrayRef<Expr *> Exprs = {}) {
522 SmallVector<Expr *, 8> Args;
523 assert(TheCall->getNumArgs() >= 2);
524 Args.reserve(N: (TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
525 Args.assign(in_start: TheCall->arg_begin() + 2, in_end: TheCall->arg_end());
526 Args.push_back(Elt: getStringLiteral(Str: Format));
527 llvm::append_range(C&: Args, R&: Exprs);
528
529 // Register a note to explain why we're performing the call.
530 Sema::CodeSynthesisContext Ctx;
531 Ctx.Kind = Sema::CodeSynthesisContext::BuildingBuiltinDumpStructCall;
532 Ctx.PointOfInstantiation = Loc;
533 Ctx.CallArgs = Args.data();
534 Ctx.NumCallArgs = Args.size();
535 S.pushCodeSynthesisContext(Ctx);
536
537 ExprResult RealCall =
538 S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: TheCall->getArg(Arg: 1),
539 LParenLoc: TheCall->getBeginLoc(), ArgExprs: Args, RParenLoc: TheCall->getRParenLoc());
540
541 S.popCodeSynthesisContext();
542 if (!RealCall.isInvalid())
543 Actions.push_back(Elt: RealCall.get());
544 // Bail out if we've hit any unrecoverable errors, even if we managed
545 // to build the call.
546 return RealCall.isInvalid() || ErrorTracker.hasUnrecoverableErrorOccurred();
547 }
548
549 Expr *getIndentString(unsigned Depth) {
550 if (!Depth)
551 return nullptr;
552
553 llvm::SmallString<32> Indent;
554 Indent.resize(N: Depth * Policy.Indentation, NV: ' ');
555 return getStringLiteral(Str: Indent);
556 }
557
558 Expr *getTypeString(QualType T) {
559 return getStringLiteral(Str: T.getAsString(Policy));
560 }
561
562 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
563 llvm::raw_svector_ostream OS(Str);
564
565 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
566 // than trying to print a single character.
567 if (auto *BT = T->getAs<BuiltinType>()) {
568 switch (BT->getKind()) {
569 case BuiltinType::Bool:
570 OS << "%d";
571 return true;
572 case BuiltinType::Char_U:
573 case BuiltinType::UChar:
574 OS << "%hhu";
575 return true;
576 case BuiltinType::Char_S:
577 case BuiltinType::SChar:
578 OS << "%hhd";
579 return true;
580 default:
581 break;
582 }
583 }
584
585 analyze_printf::PrintfSpecifier Specifier;
586 if (Specifier.fixType(QT: T, LangOpt: S.getLangOpts(), Ctx&: S.Context, /*IsObjCLiteral=*/false)) {
587 // We were able to guess how to format this.
588 if (Specifier.getConversionSpecifier().getKind() ==
589 analyze_printf::PrintfConversionSpecifier::sArg) {
590 // Wrap double-quotes around a '%s' specifier and limit its maximum
591 // length. Ideally we'd also somehow escape special characters in the
592 // contents but printf doesn't support that.
593 // FIXME: '%s' formatting is not safe in general.
594 OS << '"';
595 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
596 Specifier.toString(os&: OS);
597 OS << '"';
598 // FIXME: It would be nice to include a '...' if the string doesn't fit
599 // in the length limit.
600 } else {
601 Specifier.toString(os&: OS);
602 }
603 return true;
604 }
605
606 if (T->isPointerType()) {
607 // Format all pointers with '%p'.
608 OS << "%p";
609 return true;
610 }
611
612 return false;
613 }
614
615 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
616 Expr *IndentLit = getIndentString(Depth);
617 Expr *TypeLit = getTypeString(T: S.Context.getCanonicalTagType(TD: RD));
618 if (IndentLit ? callPrintFunction(Format: "%s%s", Exprs: {IndentLit, TypeLit})
619 : callPrintFunction(Format: "%s", Exprs: {TypeLit}))
620 return true;
621
622 return dumpRecordValue(RD, E, RecordIndent: IndentLit, Depth);
623 }
624
625 // Dump a record value. E should be a pointer or lvalue referring to an RD.
626 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
627 unsigned Depth) {
628 // FIXME: Decide what to do if RD is a union. At least we should probably
629 // turn off printing `const char*` members with `%s`, because that is very
630 // likely to crash if that's not the active member. Whatever we decide, we
631 // should document it.
632
633 // Build an OpaqueValueExpr so we can refer to E more than once without
634 // triggering re-evaluation.
635 Expr *RecordArg = makeOpaqueValueExpr(Inner: E);
636 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
637
638 if (callPrintFunction(Format: " {\n"))
639 return true;
640
641 // Dump each base class, regardless of whether they're aggregates.
642 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
643 for (const auto &Base : CXXRD->bases()) {
644 QualType BaseType =
645 RecordArgIsPtr ? S.Context.getPointerType(T: Base.getType())
646 : S.Context.getLValueReferenceType(T: Base.getType());
647 ExprResult BasePtr = S.BuildCStyleCastExpr(
648 LParenLoc: Loc, Ty: S.Context.getTrivialTypeSourceInfo(T: BaseType, Loc), RParenLoc: Loc,
649 Op: RecordArg);
650 if (BasePtr.isInvalid() ||
651 dumpUnnamedRecord(RD: Base.getType()->getAsRecordDecl(), E: BasePtr.get(),
652 Depth: Depth + 1))
653 return true;
654 }
655 }
656
657 Expr *FieldIndentArg = getIndentString(Depth: Depth + 1);
658
659 // Dump each field.
660 for (auto *D : RD->decls()) {
661 auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D);
662 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(Val: D);
663 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
664 continue;
665
666 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
667 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
668 getTypeString(T: FD->getType()),
669 getStringLiteral(Str: FD->getName())};
670
671 if (FD->isBitField()) {
672 Format += ": %zu ";
673 QualType SizeT = S.Context.getSizeType();
674 llvm::APInt BitWidth(S.Context.getIntWidth(T: SizeT),
675 FD->getBitWidthValue());
676 Args.push_back(Elt: IntegerLiteral::Create(C: S.Context, V: BitWidth, type: SizeT, l: Loc));
677 }
678
679 Format += "=";
680
681 ExprResult Field =
682 IFD ? S.BuildAnonymousStructUnionMemberReference(
683 SS: CXXScopeSpec(), nameLoc: Loc, indirectField: IFD,
684 FoundDecl: DeclAccessPair::make(D: IFD, AS: AS_public), baseObjectExpr: RecordArg, opLoc: Loc)
685 : S.BuildFieldReferenceExpr(
686 BaseExpr: RecordArg, IsArrow: RecordArgIsPtr, OpLoc: Loc, SS: CXXScopeSpec(), Field: FD,
687 FoundDecl: DeclAccessPair::make(D: FD, AS: AS_public),
688 MemberNameInfo: DeclarationNameInfo(FD->getDeclName(), Loc));
689 if (Field.isInvalid())
690 return true;
691
692 auto *InnerRD = FD->getType()->getAsRecordDecl();
693 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(Val: InnerRD);
694 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
695 // Recursively print the values of members of aggregate record type.
696 if (callPrintFunction(Format, Exprs: Args) ||
697 dumpRecordValue(RD: InnerRD, E: Field.get(), RecordIndent: FieldIndentArg, Depth: Depth + 1))
698 return true;
699 } else {
700 Format += " ";
701 if (appendFormatSpecifier(T: FD->getType(), Str&: Format)) {
702 // We know how to print this field.
703 Args.push_back(Elt: Field.get());
704 } else {
705 // We don't know how to print this field. Print out its address
706 // with a format specifier that a smart tool will be able to
707 // recognize and treat specially.
708 Format += "*%p";
709 ExprResult FieldAddr =
710 S.BuildUnaryOp(S: nullptr, OpLoc: Loc, Opc: UO_AddrOf, Input: Field.get());
711 if (FieldAddr.isInvalid())
712 return true;
713 Args.push_back(Elt: FieldAddr.get());
714 }
715 Format += "\n";
716 if (callPrintFunction(Format, Exprs: Args))
717 return true;
718 }
719 }
720
721 return RecordIndent ? callPrintFunction(Format: "%s}\n", Exprs: RecordIndent)
722 : callPrintFunction(Format: "}\n");
723 }
724
725 Expr *buildWrapper() {
726 auto *Wrapper = PseudoObjectExpr::Create(Context: S.Context, syntactic: TheCall, semantic: Actions,
727 resultIndex: PseudoObjectExpr::NoResult);
728 TheCall->setType(Wrapper->getType());
729 TheCall->setValueKind(Wrapper->getValueKind());
730 return Wrapper;
731 }
732};
733} // namespace
734
735static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall) {
736 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 2))
737 return ExprError();
738
739 ExprResult PtrArgResult = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
740 if (PtrArgResult.isInvalid())
741 return ExprError();
742 TheCall->setArg(Arg: 0, ArgExpr: PtrArgResult.get());
743
744 // First argument should be a pointer to a struct.
745 QualType PtrArgType = PtrArgResult.get()->getType();
746 if (!PtrArgType->isPointerType() ||
747 !PtrArgType->getPointeeType()->isRecordType()) {
748 S.Diag(Loc: PtrArgResult.get()->getBeginLoc(),
749 DiagID: diag::err_expected_struct_pointer_argument)
750 << 1 << TheCall->getDirectCallee() << PtrArgType;
751 return ExprError();
752 }
753 QualType Pointee = PtrArgType->getPointeeType();
754 const RecordDecl *RD = Pointee->getAsRecordDecl();
755 // Try to instantiate the class template as appropriate; otherwise, access to
756 // its data() may lead to a crash.
757 if (S.RequireCompleteType(Loc: PtrArgResult.get()->getBeginLoc(), T: Pointee,
758 DiagID: diag::err_incomplete_type))
759 return ExprError();
760 // Second argument is a callable, but we can't fully validate it until we try
761 // calling it.
762 QualType FnArgType = TheCall->getArg(Arg: 1)->getType();
763 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
764 !FnArgType->isBlockPointerType() &&
765 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
766 auto *BT = FnArgType->getAs<BuiltinType>();
767 switch (BT ? BT->getKind() : BuiltinType::Void) {
768 case BuiltinType::Dependent:
769 case BuiltinType::Overload:
770 case BuiltinType::BoundMember:
771 case BuiltinType::PseudoObject:
772 case BuiltinType::UnknownAny:
773 case BuiltinType::BuiltinFn:
774 // This might be a callable.
775 break;
776
777 default:
778 S.Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
779 DiagID: diag::err_expected_callable_argument)
780 << 2 << TheCall->getDirectCallee() << FnArgType;
781 return ExprError();
782 }
783 }
784
785 BuiltinDumpStructGenerator Generator(S, TheCall);
786
787 // Wrap parentheses around the given pointer. This is not necessary for
788 // correct code generation, but it means that when we pretty-print the call
789 // arguments in our diagnostics we will produce '(&s)->n' instead of the
790 // incorrect '&s->n'.
791 Expr *PtrArg = PtrArgResult.get();
792 PtrArg = new (S.Context)
793 ParenExpr(PtrArg->getBeginLoc(),
794 S.getLocForEndOfToken(Loc: PtrArg->getEndLoc()), PtrArg);
795 if (Generator.dumpUnnamedRecord(RD, E: PtrArg, Depth: 0))
796 return ExprError();
797
798 return Generator.buildWrapper();
799}
800
801static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
802 if (S.checkArgCount(Call: BuiltinCall, DesiredArgCount: 2))
803 return true;
804
805 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
806 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
807 Expr *Call = BuiltinCall->getArg(Arg: 0);
808 Expr *Chain = BuiltinCall->getArg(Arg: 1);
809
810 if (Call->getStmtClass() != Stmt::CallExprClass) {
811 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_not_call)
812 << Call->getSourceRange();
813 return true;
814 }
815
816 auto CE = cast<CallExpr>(Val: Call);
817 if (CE->getCallee()->getType()->isBlockPointerType()) {
818 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_block_call)
819 << Call->getSourceRange();
820 return true;
821 }
822
823 const Decl *TargetDecl = CE->getCalleeDecl();
824 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: TargetDecl))
825 if (FD->getBuiltinID()) {
826 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_builtin_call)
827 << Call->getSourceRange();
828 return true;
829 }
830
831 if (isa<CXXPseudoDestructorExpr>(Val: CE->getCallee()->IgnoreParens())) {
832 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_pdtor_call)
833 << Call->getSourceRange();
834 return true;
835 }
836
837 ExprResult ChainResult = S.UsualUnaryConversions(E: Chain);
838 if (ChainResult.isInvalid())
839 return true;
840 if (!ChainResult.get()->getType()->isPointerType()) {
841 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_second_argument_to_cwsc_not_pointer)
842 << Chain->getSourceRange();
843 return true;
844 }
845
846 QualType ReturnTy = CE->getCallReturnType(Ctx: S.Context);
847 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
848 QualType BuiltinTy = S.Context.getFunctionType(
849 ResultTy: ReturnTy, Args: ArgTys, EPI: FunctionProtoType::ExtProtoInfo());
850 QualType BuiltinPtrTy = S.Context.getPointerType(T: BuiltinTy);
851
852 Builtin =
853 S.ImpCastExprToType(E: Builtin, Type: BuiltinPtrTy, CK: CK_BuiltinFnToFnPtr).get();
854
855 BuiltinCall->setType(CE->getType());
856 BuiltinCall->setValueKind(CE->getValueKind());
857 BuiltinCall->setObjectKind(CE->getObjectKind());
858 BuiltinCall->setCallee(Builtin);
859 BuiltinCall->setArg(Arg: 1, ArgExpr: ChainResult.get());
860
861 return false;
862}
863
864namespace {
865
866class ScanfDiagnosticFormatHandler
867 : public analyze_format_string::FormatStringHandler {
868 // Accepts the argument index (relative to the first destination index) of the
869 // argument whose size we want.
870 using ComputeSizeFunction =
871 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
872
873 // Accepts the argument index (relative to the first destination index), the
874 // destination size, and the source size).
875 using DiagnoseFunction =
876 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
877
878 ComputeSizeFunction ComputeSizeArgument;
879 DiagnoseFunction Diagnose;
880
881public:
882 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
883 DiagnoseFunction Diagnose)
884 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
885
886 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
887 const char *StartSpecifier,
888 unsigned specifierLen) override {
889 if (!FS.consumesDataArgument())
890 return true;
891
892 unsigned NulByte = 0;
893 switch ((FS.getConversionSpecifier().getKind())) {
894 default:
895 return true;
896 case analyze_format_string::ConversionSpecifier::sArg:
897 case analyze_format_string::ConversionSpecifier::ScanListArg:
898 NulByte = 1;
899 break;
900 case analyze_format_string::ConversionSpecifier::cArg:
901 break;
902 }
903
904 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
905 if (FW.getHowSpecified() !=
906 analyze_format_string::OptionalAmount::HowSpecified::Constant)
907 return true;
908
909 unsigned SourceSize = FW.getConstantAmount() + NulByte;
910
911 std::optional<llvm::APSInt> DestSizeAPS =
912 ComputeSizeArgument(FS.getArgIndex());
913 if (!DestSizeAPS)
914 return true;
915
916 unsigned DestSize = DestSizeAPS->getZExtValue();
917
918 if (DestSize < SourceSize)
919 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
920
921 return true;
922 }
923};
924
925class EstimateSizeFormatHandler
926 : public analyze_format_string::FormatStringHandler {
927 size_t Size;
928 /// Whether the format string contains Linux kernel's format specifier
929 /// extension.
930 bool IsKernelCompatible = true;
931
932public:
933 EstimateSizeFormatHandler(StringRef Format)
934 : Size(std::min(a: Format.find(C: 0), b: Format.size()) +
935 1 /* null byte always written by sprintf */) {}
936
937 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
938 const char *, unsigned SpecifierLen,
939 const TargetInfo &) override {
940
941 const size_t FieldWidth = computeFieldWidth(FS);
942 const size_t Precision = computePrecision(FS);
943
944 // The actual format.
945 switch (FS.getConversionSpecifier().getKind()) {
946 // Just a char.
947 case analyze_format_string::ConversionSpecifier::cArg:
948 case analyze_format_string::ConversionSpecifier::CArg:
949 Size += std::max(a: FieldWidth, b: (size_t)1);
950 break;
951 // Just an integer.
952 case analyze_format_string::ConversionSpecifier::dArg:
953 case analyze_format_string::ConversionSpecifier::DArg:
954 case analyze_format_string::ConversionSpecifier::iArg:
955 case analyze_format_string::ConversionSpecifier::oArg:
956 case analyze_format_string::ConversionSpecifier::OArg:
957 case analyze_format_string::ConversionSpecifier::uArg:
958 case analyze_format_string::ConversionSpecifier::UArg:
959 case analyze_format_string::ConversionSpecifier::xArg:
960 case analyze_format_string::ConversionSpecifier::XArg:
961 Size += std::max(a: FieldWidth, b: Precision);
962 break;
963
964 // %g style conversion switches between %f or %e style dynamically.
965 // %g removes trailing zeros, and does not print decimal point if there are
966 // no digits that follow it. Thus %g can print a single digit.
967 // FIXME: If it is alternative form:
968 // For g and G conversions, trailing zeros are not removed from the result.
969 case analyze_format_string::ConversionSpecifier::gArg:
970 case analyze_format_string::ConversionSpecifier::GArg:
971 Size += 1;
972 break;
973
974 // Floating point number in the form '[+]ddd.ddd'.
975 case analyze_format_string::ConversionSpecifier::fArg:
976 case analyze_format_string::ConversionSpecifier::FArg:
977 Size += std::max(a: FieldWidth, b: 1 /* integer part */ +
978 (Precision ? 1 + Precision
979 : 0) /* period + decimal */);
980 break;
981
982 // Floating point number in the form '[-]d.ddde[+-]dd'.
983 case analyze_format_string::ConversionSpecifier::eArg:
984 case analyze_format_string::ConversionSpecifier::EArg:
985 Size +=
986 std::max(a: FieldWidth,
987 b: 1 /* integer part */ +
988 (Precision ? 1 + Precision : 0) /* period + decimal */ +
989 1 /* e or E letter */ + 2 /* exponent */);
990 break;
991
992 // Floating point number in the form '[-]0xh.hhhhp±dd'.
993 case analyze_format_string::ConversionSpecifier::aArg:
994 case analyze_format_string::ConversionSpecifier::AArg:
995 Size +=
996 std::max(a: FieldWidth,
997 b: 2 /* 0x */ + 1 /* integer part */ +
998 (Precision ? 1 + Precision : 0) /* period + decimal */ +
999 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
1000 break;
1001
1002 // Just a string.
1003 case analyze_format_string::ConversionSpecifier::sArg:
1004 case analyze_format_string::ConversionSpecifier::SArg:
1005 Size += FieldWidth;
1006 break;
1007
1008 // Just a pointer in the form '0xddd'.
1009 case analyze_format_string::ConversionSpecifier::pArg:
1010 // Linux kernel has its own extesion for `%p` specifier.
1011 // Kernel Document:
1012 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1013 IsKernelCompatible = false;
1014 Size += std::max(a: FieldWidth, b: 2 /* leading 0x */ + Precision);
1015 break;
1016
1017 // A plain percent.
1018 case analyze_format_string::ConversionSpecifier::PercentArg:
1019 Size += 1;
1020 break;
1021
1022 default:
1023 break;
1024 }
1025
1026 // If field width is specified, the sign/space is already accounted for
1027 // within the field width, so no additional size is needed.
1028 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1029 Size += 1;
1030
1031 if (FS.hasAlternativeForm()) {
1032 switch (FS.getConversionSpecifier().getKind()) {
1033 // For o conversion, it increases the precision, if and only if necessary,
1034 // to force the first digit of the result to be a zero
1035 // (if the value and precision are both 0, a single 0 is printed)
1036 case analyze_format_string::ConversionSpecifier::oArg:
1037 // For b conversion, a nonzero result has 0b prefixed to it.
1038 case analyze_format_string::ConversionSpecifier::bArg:
1039 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1040 // it.
1041 case analyze_format_string::ConversionSpecifier::xArg:
1042 case analyze_format_string::ConversionSpecifier::XArg:
1043 // Note: even when the prefix is added, if
1044 // (prefix_width <= FieldWidth - formatted_length) holds,
1045 // the prefix does not increase the format
1046 // size. e.g.(("%#3x", 0xf) is "0xf")
1047
1048 // If the result is zero, o, b, x, X adds nothing.
1049 break;
1050 // For a, A, e, E, f, F, g, and G conversions,
1051 // the result of converting a floating-point number always contains a
1052 // decimal-point
1053 case analyze_format_string::ConversionSpecifier::aArg:
1054 case analyze_format_string::ConversionSpecifier::AArg:
1055 case analyze_format_string::ConversionSpecifier::eArg:
1056 case analyze_format_string::ConversionSpecifier::EArg:
1057 case analyze_format_string::ConversionSpecifier::fArg:
1058 case analyze_format_string::ConversionSpecifier::FArg:
1059 case analyze_format_string::ConversionSpecifier::gArg:
1060 case analyze_format_string::ConversionSpecifier::GArg:
1061 Size += (Precision ? 0 : 1);
1062 break;
1063 // For other conversions, the behavior is undefined.
1064 default:
1065 break;
1066 }
1067 }
1068 assert(SpecifierLen <= Size && "no underflow");
1069 Size -= SpecifierLen;
1070 return true;
1071 }
1072
1073 size_t getSizeLowerBound() const { return Size; }
1074 bool isKernelCompatible() const { return IsKernelCompatible; }
1075
1076private:
1077 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1078 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1079 size_t FieldWidth = 0;
1080 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
1081 FieldWidth = FW.getConstantAmount();
1082 return FieldWidth;
1083 }
1084
1085 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1086 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1087 size_t Precision = 0;
1088
1089 // See man 3 printf for default precision value based on the specifier.
1090 switch (FW.getHowSpecified()) {
1091 case analyze_format_string::OptionalAmount::NotSpecified:
1092 switch (FS.getConversionSpecifier().getKind()) {
1093 default:
1094 break;
1095 case analyze_format_string::ConversionSpecifier::dArg: // %d
1096 case analyze_format_string::ConversionSpecifier::DArg: // %D
1097 case analyze_format_string::ConversionSpecifier::iArg: // %i
1098 Precision = 1;
1099 break;
1100 case analyze_format_string::ConversionSpecifier::oArg: // %d
1101 case analyze_format_string::ConversionSpecifier::OArg: // %D
1102 case analyze_format_string::ConversionSpecifier::uArg: // %d
1103 case analyze_format_string::ConversionSpecifier::UArg: // %D
1104 case analyze_format_string::ConversionSpecifier::xArg: // %d
1105 case analyze_format_string::ConversionSpecifier::XArg: // %D
1106 Precision = 1;
1107 break;
1108 case analyze_format_string::ConversionSpecifier::fArg: // %f
1109 case analyze_format_string::ConversionSpecifier::FArg: // %F
1110 case analyze_format_string::ConversionSpecifier::eArg: // %e
1111 case analyze_format_string::ConversionSpecifier::EArg: // %E
1112 case analyze_format_string::ConversionSpecifier::gArg: // %g
1113 case analyze_format_string::ConversionSpecifier::GArg: // %G
1114 Precision = 6;
1115 break;
1116 case analyze_format_string::ConversionSpecifier::pArg: // %d
1117 Precision = 1;
1118 break;
1119 }
1120 break;
1121 case analyze_format_string::OptionalAmount::Constant:
1122 Precision = FW.getConstantAmount();
1123 break;
1124 default:
1125 break;
1126 }
1127 return Precision;
1128 }
1129};
1130
1131} // namespace
1132
1133static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1134 StringRef &FormatStrRef, size_t &StrLen,
1135 ASTContext &Context) {
1136 if (const auto *Format = dyn_cast<StringLiteral>(Val: FormatExpr);
1137 Format && (Format->isOrdinary() || Format->isUTF8())) {
1138 FormatStrRef = Format->getString();
1139 const ConstantArrayType *T =
1140 Context.getAsConstantArrayType(T: Format->getType());
1141 assert(T && "String literal not of constant array type!");
1142 size_t TypeSize = T->getZExtSize();
1143 // In case there's a null byte somewhere.
1144 StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: FormatStrRef.find(C: 0));
1145 return true;
1146 }
1147 return false;
1148}
1149
1150namespace {
1151/// Helper class for buffer overflow/overread checking in fortified functions.
1152class FortifiedBufferChecker {
1153public:
1154 FortifiedBufferChecker(Sema &S, FunctionDecl *FD, CallExpr *TheCall)
1155 : S(S), TheCall(TheCall), FD(FD),
1156 DABAttr(FD ? FD->getAttr<DiagnoseAsBuiltinAttr>() : nullptr) {
1157 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1158 SizeTypeWidth = TI.getTypeWidth(T: TI.getSizeType());
1159 }
1160
1161 std::optional<unsigned> TranslateIndex(unsigned Index) {
1162 // If we refer to a diagnose_as_builtin attribute, we need to change the
1163 // argument index to refer to the arguments of the called function. Unless
1164 // the index is out of bounds, which presumably means it's a variadic
1165 // function.
1166 unsigned NewIndex = Index;
1167 if (DABAttr) {
1168 unsigned DABIndices = DABAttr->argIndices_size();
1169 NewIndex = Index < DABIndices ? DABAttr->argIndices_begin()[Index]
1170 : Index - DABIndices + FD->getNumParams();
1171 }
1172 if (NewIndex >= TheCall->getNumArgs())
1173 return std::nullopt;
1174 return NewIndex;
1175 }
1176
1177 /// Evaluate the argument at Index as an integer constant while preserving
1178 /// its signedness, or return std::nullopt if it cannot be evaluated.
1179 std::optional<llvm::APSInt> EvaluateIntegerArgument(unsigned Index) {
1180 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1181 if (!IndexOptional)
1182 return std::nullopt;
1183 Expr::EvalResult Result;
1184 Expr *Arg = TheCall->getArg(Arg: *IndexOptional);
1185 if (!Arg->EvaluateAsInt(Result, Ctx: S.getASTContext()))
1186 return std::nullopt;
1187
1188 return Result.Val.getInt();
1189 }
1190
1191 std::optional<llvm::APSInt>
1192 ComputeExplicitObjectSizeArgument(unsigned Index) {
1193 std::optional<llvm::APSInt> Integer = EvaluateIntegerArgument(Index);
1194 if (!Integer)
1195 return std::nullopt;
1196 *Integer = Integer->extOrTrunc(width: SizeTypeWidth);
1197 Integer->setIsUnsigned(true);
1198 return Integer;
1199 }
1200
1201 std::optional<llvm::APSInt> ComputeSizeArgument(unsigned Index) {
1202 // If the parameter has a pass_object_size attribute, then we should use its
1203 // (potentially) more strict checking mode. Otherwise, conservatively assume
1204 // type 0.
1205 int BOSType = 0;
1206 // This check can fail for variadic functions.
1207 if (Index < FD->getNumParams()) {
1208 if (const auto *POS =
1209 FD->getParamDecl(i: Index)->getAttr<PassObjectSizeAttr>())
1210 BOSType = POS->getType();
1211 }
1212
1213 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1214 if (!IndexOptional)
1215 return std::nullopt;
1216
1217 const Expr *ObjArg = TheCall->getArg(Arg: *IndexOptional);
1218 if (std::optional<uint64_t> ObjSize =
1219 ObjArg->tryEvaluateObjectSize(Ctx: S.getASTContext(), Type: BOSType)) {
1220 // Get the object size in the target's size_t width.
1221 return llvm::APSInt::getUnsigned(X: *ObjSize).extOrTrunc(width: SizeTypeWidth);
1222 }
1223 return std::nullopt;
1224 }
1225
1226 std::optional<llvm::APSInt>
1227 ComputeExplicitObjectSizeArgumentProduct(unsigned LIndex, unsigned RIndex) {
1228 auto L = ComputeExplicitObjectSizeArgument(Index: LIndex);
1229 auto R = ComputeExplicitObjectSizeArgument(Index: RIndex);
1230 if (!L || !R)
1231 return std::nullopt;
1232
1233 unsigned W =
1234 2 * std::max(l: {L->getBitWidth(), R->getBitWidth(), SizeTypeWidth});
1235
1236 llvm::APSInt LE = L->extOrTrunc(width: W);
1237 llvm::APSInt RE = R->extOrTrunc(width: W);
1238
1239 return LE * RE;
1240 }
1241
1242 std::optional<llvm::APSInt> ComputeStrLenArgument(unsigned Index) {
1243 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1244 if (!IndexOptional)
1245 return std::nullopt;
1246 unsigned NewIndex = *IndexOptional;
1247
1248 const Expr *ObjArg = TheCall->getArg(Arg: NewIndex);
1249
1250 if (std::optional<uint64_t> Result =
1251 ObjArg->tryEvaluateStrLen(Ctx: S.getASTContext())) {
1252 // Add 1 for null byte.
1253 return llvm::APSInt::getUnsigned(X: *Result + 1).extOrTrunc(width: SizeTypeWidth);
1254 }
1255 return std::nullopt;
1256 }
1257
1258 unsigned getSizeTypeWidth() const { return SizeTypeWidth; }
1259
1260 unsigned getBuiltinID() const {
1261 const FunctionDecl *UseDecl = FD;
1262 if (DABAttr) {
1263 UseDecl = DABAttr->getFunction();
1264 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1265 }
1266 return UseDecl->getBuiltinID(/*ConsiderWrappers=*/ConsiderWrapperFunctions: true);
1267 }
1268
1269 /// Return function name after stripping __builtin_ and _chk affixes.
1270 std::string getFunctionName() const {
1271 unsigned ID = getBuiltinID();
1272 if (!ID) {
1273 // Use callee name directly if not a builtin.
1274 const FunctionDecl *Callee = TheCall->getDirectCallee();
1275 assert(Callee && "expected callee");
1276 return Callee->getName().str();
1277 }
1278 std::string Name = S.getASTContext().BuiltinInfo.getName(ID);
1279 StringRef Ref = Name;
1280 // Strip __builtin___*_chk or __builtin_ prefix.
1281 if (!(Ref.consume_front(Prefix: "__builtin___") && Ref.consume_back(Suffix: "_chk")))
1282 Ref.consume_front(Prefix: "__builtin_");
1283 assert(!Ref.empty() && "expected non-empty function name");
1284 return Ref.str();
1285 }
1286
1287 /// Check for source buffer overread in memory functions.
1288 void checkSourceOverread(unsigned SrcArgIdx, unsigned SizeArgIdx) {
1289 if (S.isConstantEvaluatedContext())
1290 return;
1291
1292 const Expr *SrcArg = TheCall->getArg(Arg: SrcArgIdx);
1293 const Expr *SizeArg = TheCall->getArg(Arg: SizeArgIdx);
1294 if (SrcArg->isInstantiationDependent() ||
1295 SizeArg->isInstantiationDependent())
1296 return;
1297
1298 std::optional<llvm::APSInt> CopyLen =
1299 ComputeExplicitObjectSizeArgument(Index: SizeArgIdx);
1300 std::optional<llvm::APSInt> SrcBufSize = ComputeSizeArgument(Index: SrcArgIdx);
1301
1302 if (!CopyLen || !SrcBufSize)
1303 return;
1304
1305 // Warn only if copy length exceeds source buffer size.
1306 if (llvm::APSInt::compareValues(I1: *CopyLen, I2: *SrcBufSize) <= 0)
1307 return;
1308
1309 S.DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1310 PD: S.PDiag(DiagID: diag::warn_stringop_overread)
1311 << getFunctionName() << CopyLen->getZExtValue()
1312 << SrcBufSize->getZExtValue());
1313 }
1314
1315private:
1316 Sema &S;
1317 CallExpr *TheCall;
1318 FunctionDecl *FD;
1319 const DiagnoseAsBuiltinAttr *DABAttr;
1320 unsigned SizeTypeWidth;
1321};
1322} // anonymous namespace
1323
1324void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1325 CallExpr *TheCall) {
1326 if (TheCall->isInstantiationDependent() || isConstantEvaluatedContext())
1327 return;
1328
1329 FortifiedBufferChecker Checker(*this, FD, TheCall);
1330
1331 unsigned BuiltinID = Checker.getBuiltinID();
1332 if (!BuiltinID)
1333 return;
1334
1335 unsigned SizeTypeWidth = Checker.getSizeTypeWidth();
1336
1337 std::optional<llvm::APSInt> AccessSize;
1338 std::optional<llvm::APSInt> BufferSize;
1339 unsigned DiagID = 0;
1340
1341 switch (BuiltinID) {
1342 default:
1343 return;
1344 case Builtin::BI__builtin_strcat:
1345 case Builtin::BIstrcat:
1346 case Builtin::BI__builtin_stpcpy:
1347 case Builtin::BIstpcpy:
1348 case Builtin::BI__builtin_strcpy:
1349 case Builtin::BIstrcpy: {
1350 DiagID = diag::warn_fortify_strlen_overflow;
1351 AccessSize = Checker.ComputeStrLenArgument(Index: 1);
1352 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1353 break;
1354 }
1355
1356 case Builtin::BI__builtin___strcat_chk:
1357 case Builtin::BI__builtin___stpcpy_chk:
1358 case Builtin::BI__builtin___strcpy_chk: {
1359 DiagID = diag::warn_fortify_strlen_overflow;
1360 AccessSize = Checker.ComputeStrLenArgument(Index: 1);
1361 BufferSize = Checker.ComputeExplicitObjectSizeArgument(Index: 2);
1362 break;
1363 }
1364
1365 case Builtin::BIscanf:
1366 case Builtin::BIfscanf:
1367 case Builtin::BIsscanf: {
1368 unsigned FormatIndex = 1;
1369 unsigned DataIndex = 2;
1370 if (BuiltinID == Builtin::BIscanf) {
1371 FormatIndex = 0;
1372 DataIndex = 1;
1373 }
1374
1375 const auto *FormatExpr =
1376 TheCall->getArg(Arg: FormatIndex)->IgnoreParenImpCasts();
1377
1378 StringRef FormatStrRef;
1379 size_t StrLen;
1380 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1381 return;
1382
1383 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1384 unsigned SourceSize) {
1385 DiagID = diag::warn_fortify_scanf_overflow;
1386 unsigned Index = ArgIndex + DataIndex;
1387 std::string FunctionName = Checker.getFunctionName();
1388 DiagRuntimeBehavior(Loc: TheCall->getArg(Arg: Index)->getBeginLoc(), Statement: TheCall,
1389 PD: PDiag(DiagID) << FunctionName << (Index + 1)
1390 << DestSize << SourceSize);
1391 };
1392
1393 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1394 return Checker.ComputeSizeArgument(Index: Index + DataIndex);
1395 };
1396 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1397 const char *FormatBytes = FormatStrRef.data();
1398 analyze_format_string::ParseScanfString(H, beg: FormatBytes,
1399 end: FormatBytes + StrLen, LO: getLangOpts(),
1400 Target: Context.getTargetInfo());
1401
1402 // Unlike the other cases, in this one we have already issued the diagnostic
1403 // here, so no need to continue (because unlike the other cases, here the
1404 // diagnostic refers to the argument number).
1405 return;
1406 }
1407
1408 case Builtin::BIsprintf:
1409 case Builtin::BI__builtin___sprintf_chk: {
1410 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1411 auto *FormatExpr = TheCall->getArg(Arg: FormatIndex)->IgnoreParenImpCasts();
1412
1413 StringRef FormatStrRef;
1414 size_t StrLen;
1415 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1416 EstimateSizeFormatHandler H(FormatStrRef);
1417 const char *FormatBytes = FormatStrRef.data();
1418 if (!analyze_format_string::ParsePrintfString(
1419 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1420 Target: Context.getTargetInfo(), isFreeBSDKPrintf: false)) {
1421 DiagID = H.isKernelCompatible()
1422 ? diag::warn_format_overflow
1423 : diag::warn_format_overflow_non_kprintf;
1424 AccessSize = llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1425 .extOrTrunc(width: SizeTypeWidth);
1426 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1427 BufferSize = Checker.ComputeExplicitObjectSizeArgument(Index: 2);
1428 } else {
1429 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1430 }
1431 break;
1432 }
1433 }
1434 return;
1435 }
1436 case Builtin::BI__builtin___memcpy_chk:
1437 case Builtin::BI__builtin___memmove_chk:
1438 case Builtin::BI__builtin___memset_chk:
1439 case Builtin::BI__builtin___strlcat_chk:
1440 case Builtin::BI__builtin___strlcpy_chk:
1441 case Builtin::BI__builtin___strncat_chk:
1442 case Builtin::BI__builtin___strncpy_chk:
1443 case Builtin::BI__builtin___stpncpy_chk:
1444 case Builtin::BI__builtin___memccpy_chk:
1445 case Builtin::BI__builtin___mempcpy_chk: {
1446 DiagID = diag::warn_builtin_chk_overflow;
1447 AccessSize =
1448 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 2);
1449 BufferSize =
1450 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1451
1452 if (BuiltinID == Builtin::BI__builtin___memcpy_chk ||
1453 BuiltinID == Builtin::BI__builtin___memmove_chk ||
1454 BuiltinID == Builtin::BI__builtin___mempcpy_chk) {
1455 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1456 }
1457 break;
1458 }
1459
1460 case Builtin::BI__builtin___snprintf_chk:
1461 case Builtin::BI__builtin___vsnprintf_chk: {
1462 DiagID = diag::warn_builtin_chk_overflow;
1463 AccessSize = Checker.ComputeExplicitObjectSizeArgument(Index: 1);
1464 BufferSize = Checker.ComputeExplicitObjectSizeArgument(Index: 3);
1465 break;
1466 }
1467
1468 case Builtin::BIstrncat:
1469 case Builtin::BI__builtin_strncat:
1470 case Builtin::BIstrncpy:
1471 case Builtin::BI__builtin_strncpy:
1472 case Builtin::BIstpncpy:
1473 case Builtin::BI__builtin_stpncpy:
1474 case Builtin::BIstrlcat:
1475 case Builtin::BI__builtin_strlcat:
1476 case Builtin::BIstrlcpy:
1477 case Builtin::BI__builtin_strlcpy: {
1478 // Whether these functions overflow depends on the runtime strlen of the
1479 // string, not just the buffer size, so emitting the "always overflow"
1480 // diagnostic isn't quite right. We should still diagnose passing a buffer
1481 // size larger than the destination buffer though; this is a runtime abort
1482 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1483 DiagID = diag::warn_fortify_source_size_mismatch;
1484 AccessSize =
1485 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1486 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1487 break;
1488 }
1489
1490 case Builtin::BIrecv:
1491 case Builtin::BIrecvfrom: {
1492 unsigned ExpectedArgs = BuiltinID == Builtin::BIrecv ? 4 : 6;
1493 if (TheCall->getNumArgs() != ExpectedArgs ||
1494 !TheCall->getArg(Arg: 1)->getType()->isPointerType() ||
1495 !TheCall->getArg(Arg: 2)->getType()->isIntegerType())
1496 return;
1497 DiagID = diag::warn_fortify_source_size_mismatch;
1498 AccessSize = Checker.ComputeExplicitObjectSizeArgument(Index: 2);
1499 BufferSize = Checker.ComputeSizeArgument(Index: 1);
1500 break;
1501 }
1502
1503 case Builtin::BIpoll:
1504 case Builtin::BIppoll:
1505 case Builtin::BIppoll64: {
1506 unsigned ExpectedArgs = BuiltinID == Builtin::BIpoll ? 3 : 4;
1507 if (TheCall->getNumArgs() != ExpectedArgs ||
1508 !TheCall->getArg(Arg: 1)->getType()->isIntegerType())
1509 return;
1510 QualType PointeeTy = TheCall->getArg(Arg: 0)->getType()->getPointeeType();
1511 if (PointeeTy.isNull())
1512 return;
1513 const RecordDecl *RD = PointeeTy->getAsRecordDecl();
1514 if (!RD || !RD->getIdentifier() || RD->getName() != "pollfd")
1515 return;
1516 if (BuiltinID == Builtin::BIpoll) {
1517 if (!TheCall->getArg(Arg: 2)->getType()->isIntegerType())
1518 return;
1519 } else {
1520 QualType TmoPointeeTy = TheCall->getArg(Arg: 2)->getType()->getPointeeType();
1521 if (TmoPointeeTy.isNull())
1522 return;
1523 const RecordDecl *TmoRD = TmoPointeeTy->getAsRecordDecl();
1524 if (!TmoRD || !TmoRD->getIdentifier() || TmoRD->getName() != "timespec" ||
1525 !TheCall->getArg(Arg: 3)->getType()->isPointerType())
1526 return;
1527 }
1528 std::optional<CharUnits> ElemSize =
1529 Context.getTypeSizeInCharsIfKnown(Ty: PointeeTy);
1530 if (!ElemSize)
1531 return;
1532 std::optional<llvm::APSInt> Count =
1533 Checker.ComputeExplicitObjectSizeArgument(Index: 1);
1534 if (!Count)
1535 return;
1536 DiagID = diag::warn_fortify_source_size_mismatch;
1537 unsigned WideWidth = SizeTypeWidth * 2;
1538 AccessSize = Count->extOrTrunc(width: WideWidth) *
1539 llvm::APSInt(llvm::APInt(WideWidth, ElemSize->getQuantity()),
1540 /*isUnsigned=*/true);
1541 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1542 break;
1543 }
1544
1545 case Builtin::BIbzero:
1546 case Builtin::BI__builtin_bzero:
1547 case Builtin::BImemcpy:
1548 case Builtin::BI__builtin_memcpy:
1549 case Builtin::BImemmove:
1550 case Builtin::BI__builtin_memmove:
1551 case Builtin::BImemset:
1552 case Builtin::BI__builtin_memset:
1553 case Builtin::BImempcpy:
1554 case Builtin::BI__builtin_mempcpy: {
1555 DiagID = diag::warn_fortify_source_overflow;
1556 AccessSize =
1557 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1558 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1559
1560 // Buffer overread doesn't make sense for memset/bzero.
1561 if (BuiltinID != Builtin::BImemset &&
1562 BuiltinID != Builtin::BI__builtin_memset &&
1563 BuiltinID != Builtin::BIbzero &&
1564 BuiltinID != Builtin::BI__builtin_bzero) {
1565 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1566 }
1567 break;
1568 }
1569 case Builtin::BIbcopy:
1570 case Builtin::BI__builtin_bcopy: {
1571 DiagID = diag::warn_fortify_source_overflow;
1572 AccessSize =
1573 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1574 BufferSize = Checker.ComputeSizeArgument(Index: 1);
1575 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1576 break;
1577 }
1578 case Builtin::BIfread: {
1579 DiagID = diag::warn_fortify_source_overflow;
1580 AccessSize = Checker.ComputeExplicitObjectSizeArgumentProduct(LIndex: 1, RIndex: 2);
1581 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1582 break;
1583 }
1584 case Builtin::BIfwrite: {
1585 DiagID = diag::warn_fortify_source_overread;
1586 AccessSize = Checker.ComputeExplicitObjectSizeArgumentProduct(LIndex: 1, RIndex: 2);
1587 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1588 break;
1589 }
1590 case Builtin::BIfgets: {
1591 AccessSize = Checker.EvaluateIntegerArgument(Index: 1);
1592
1593 if (AccessSize && AccessSize->isNegative()) {
1594 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1595 PD: PDiag(DiagID: diag::warn_fortify_source_negative_size)
1596 << Checker.getFunctionName());
1597 return;
1598 }
1599
1600 DiagID = diag::warn_fortify_source_size_mismatch;
1601 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1602 break;
1603 }
1604 // memchr(buf, val, size)
1605 case Builtin::BImemchr:
1606 case Builtin::BI__builtin_memchr: {
1607 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1608 return;
1609 }
1610
1611 // memcmp/bcmp(buf0, buf1, size)
1612 // Two checks since each buffer is read
1613 case Builtin::BImemcmp:
1614 case Builtin::BI__builtin_memcmp:
1615 case Builtin::BIbcmp:
1616 case Builtin::BI__builtin_bcmp: {
1617 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1618 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1619 return;
1620 }
1621 case Builtin::BIsnprintf:
1622 case Builtin::BI__builtin_snprintf:
1623 case Builtin::BIvsnprintf:
1624 case Builtin::BI__builtin_vsnprintf: {
1625 DiagID = diag::warn_fortify_source_size_mismatch;
1626 AccessSize = Checker.ComputeExplicitObjectSizeArgument(Index: 1);
1627 const auto *FormatExpr = TheCall->getArg(Arg: 2)->IgnoreParenImpCasts();
1628 StringRef FormatStrRef;
1629 size_t StrLen;
1630 if (AccessSize &&
1631 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1632 EstimateSizeFormatHandler H(FormatStrRef);
1633 const char *FormatBytes = FormatStrRef.data();
1634 if (!analyze_format_string::ParsePrintfString(
1635 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1636 Target: Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1637 llvm::APSInt FormatSize =
1638 llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1639 .extOrTrunc(width: SizeTypeWidth);
1640 if (FormatSize > *AccessSize && *AccessSize != 0) {
1641 unsigned TruncationDiagID =
1642 H.isKernelCompatible() ? diag::warn_format_truncation
1643 : diag::warn_format_truncation_non_kprintf;
1644 SmallString<16> SpecifiedSizeStr;
1645 SmallString<16> FormatSizeStr;
1646 AccessSize->toString(Str&: SpecifiedSizeStr, /*Radix=*/10);
1647 FormatSize.toString(Str&: FormatSizeStr, /*Radix=*/10);
1648 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1649 PD: PDiag(DiagID: TruncationDiagID)
1650 << Checker.getFunctionName()
1651 << SpecifiedSizeStr << FormatSizeStr);
1652 }
1653 }
1654 }
1655 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1656 const Expr *LenArg = TheCall->getArg(Arg: 1)->IgnoreCasts();
1657 const Expr *Dest = TheCall->getArg(Arg: 0)->IgnoreCasts();
1658 IdentifierInfo *FnInfo = FD->getIdentifier();
1659 CheckSizeofMemaccessArgument(SizeOfArg: LenArg, Dest, FnName: FnInfo);
1660 }
1661 }
1662
1663 if (!AccessSize || !BufferSize ||
1664 llvm::APSInt::compareValues(I1: *AccessSize, I2: *BufferSize) <= 0)
1665 return;
1666
1667 std::string FunctionName = Checker.getFunctionName();
1668
1669 SmallString<16> BufferSizeStr;
1670 SmallString<16> AccessSizeStr;
1671 BufferSize->toString(Str&: BufferSizeStr, /*Radix=*/10);
1672 AccessSize->toString(Str&: AccessSizeStr, /*Radix=*/10);
1673 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1674 PD: PDiag(DiagID)
1675 << FunctionName << BufferSizeStr << AccessSizeStr);
1676}
1677
1678void Sema::checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall) {
1679 if (TheCall->isValueDependent() || TheCall->isTypeDependent())
1680 return;
1681
1682 // Recognize the libc function by builtin identity rather than by name and
1683 // system-header origin. umask is a LibBuiltin marked IgnoreSignature, so the
1684 // builtin id is attached to any file-scope, C-linkage declaration of umask
1685 // regardless of the libc's mode_t spelling -- including a hand-written
1686 // forward declaration without <sys/stat.h>. A static/local lookalike or a
1687 // C++ (non-extern-"C") declaration keeps a zero builtin id and is ignored.
1688 if (FD->getBuiltinID() != Builtin::BIumask)
1689 return;
1690
1691 // umask(mode_t): warn when the constant-evaluated argument has bits set
1692 // outside the file-permission mask (0777). Those bits are ignored.
1693 if (TheCall->getNumArgs() != 1)
1694 return;
1695 Expr *Arg = TheCall->getArg(Arg: 0);
1696 if (!Arg->getType()->isIntegerType())
1697 return;
1698 Expr::EvalResult R;
1699 if (!Arg->EvaluateAsInt(Result&: R, Ctx: getASTContext()))
1700 return;
1701 // Operate on the raw two's-complement bit pattern so that negative literals
1702 // (which convert to large unsigned mode_t values) are caught.
1703 llvm::APInt RawValue = R.Val.getInt();
1704 llvm::APInt Mask(RawValue.getBitWidth(), 0777);
1705 llvm::APInt Extra = RawValue & ~Mask;
1706 if (Extra == 0)
1707 return;
1708 SmallString<16> ExtraStr;
1709 Extra.toString(Str&: ExtraStr, /*Radix=*/8, /*Signed=*/false);
1710 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fortify_umask_unused_bits)
1711 << ExtraStr;
1712}
1713
1714static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1715 Scope::ScopeFlags NeededScopeFlags,
1716 unsigned DiagID) {
1717 // Scopes aren't available during instantiation. Fortunately, builtin
1718 // functions cannot be template args so they cannot be formed through template
1719 // instantiation. Therefore checking once during the parse is sufficient.
1720 if (SemaRef.inTemplateInstantiation())
1721 return false;
1722
1723 Scope *S = SemaRef.getCurScope();
1724 while (S && !S->isSEHExceptScope())
1725 S = S->getParent();
1726 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1727 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
1728 SemaRef.Diag(Loc: TheCall->getExprLoc(), DiagID)
1729 << DRE->getDecl()->getIdentifier();
1730 return true;
1731 }
1732
1733 return false;
1734}
1735
1736// In OpenCL, __builtin_alloca_* should return a pointer to address space
1737// that corresponds to the stack address space i.e private address space.
1738static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1739 QualType RT = TheCall->getType();
1740 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1741 "__builtin_alloca has invalid address space");
1742
1743 RT = RT->getPointeeType();
1744 RT = S.Context.getAddrSpaceQualType(T: RT, AddressSpace: LangAS::opencl_private);
1745 TheCall->setType(S.Context.getPointerType(T: RT));
1746}
1747
1748static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1749 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 1))
1750 return true;
1751
1752 for (Expr *Arg : TheCall->arguments()) {
1753 // If argument is dependent on a template parameter, we can't resolve now.
1754 if (Arg->isTypeDependent() || Arg->isValueDependent())
1755 continue;
1756 // Reject void types.
1757 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1758 if (ArgTy->isVoidType())
1759 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_param_with_void_type);
1760 }
1761
1762 TheCall->setType(S.Context.getSizeType());
1763 return false;
1764}
1765
1766namespace {
1767enum PointerAuthOpKind {
1768 PAO_Strip,
1769 PAO_Sign,
1770 PAO_Auth,
1771 PAO_SignGeneric,
1772 PAO_Discriminator,
1773 PAO_BlendPointer,
1774 PAO_BlendInteger,
1775 PAO_BlendPC
1776};
1777}
1778
1779bool Sema::checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range) {
1780 if (getLangOpts().PointerAuthIntrinsics)
1781 return false;
1782
1783 Diag(Loc, DiagID: diag::err_ptrauth_disabled) << Range;
1784 return true;
1785}
1786
1787static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1788 return S.checkPointerAuthEnabled(Loc: E->getExprLoc(), Range: E->getSourceRange());
1789}
1790
1791static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1792 // Convert it to type 'int'.
1793 if (S.convertArgumentToType(Value&: Arg, Ty: S.Context.IntTy))
1794 return true;
1795
1796 // Value-dependent expressions are okay; wait for template instantiation.
1797 if (Arg->isValueDependent())
1798 return false;
1799
1800 unsigned KeyValue;
1801 return S.checkConstantPointerAuthKey(keyExpr: Arg, key&: KeyValue);
1802}
1803
1804bool Sema::checkConstantPointerAuthKey(Expr *Arg, unsigned &Result) {
1805 // Attempt to constant-evaluate the expression.
1806 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Ctx: Context);
1807 if (!KeyValue) {
1808 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_expr_not_ice)
1809 << 0 << Arg->getSourceRange();
1810 return true;
1811 }
1812
1813 // Ask the target to validate the key parameter.
1814 if (!Context.getTargetInfo().validatePointerAuthKey(value: *KeyValue)) {
1815 llvm::SmallString<32> Value;
1816 {
1817 llvm::raw_svector_ostream Str(Value);
1818 Str << *KeyValue;
1819 }
1820
1821 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_invalid_key)
1822 << Value << Arg->getSourceRange();
1823 return true;
1824 }
1825
1826 Result = KeyValue->getZExtValue();
1827 return false;
1828}
1829
1830bool Sema::checkPointerAuthDiscriminatorArg(Expr *Arg,
1831 PointerAuthDiscArgKind Kind,
1832 unsigned &IntVal) {
1833 if (!Arg) {
1834 IntVal = 0;
1835 return true;
1836 }
1837
1838 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
1839 if (!Result) {
1840 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_arg_not_ice);
1841 return false;
1842 }
1843
1844 unsigned Max;
1845 bool IsAddrDiscArg = false;
1846
1847 switch (Kind) {
1848 case PointerAuthDiscArgKind::Addr:
1849 Max = 1;
1850 IsAddrDiscArg = true;
1851 break;
1852 case PointerAuthDiscArgKind::Extra:
1853 Max = PointerAuthQualifier::MaxDiscriminator;
1854 break;
1855 };
1856
1857 if (*Result < 0 || *Result > Max) {
1858 if (IsAddrDiscArg)
1859 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_address_discrimination_invalid)
1860 << Result->getExtValue();
1861 else
1862 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_extra_discriminator_invalid)
1863 << Result->getExtValue() << Max;
1864
1865 return false;
1866 };
1867
1868 IntVal = Result->getZExtValue();
1869 return true;
1870}
1871
1872static std::pair<const ValueDecl *, CharUnits>
1873findConstantBaseAndOffset(Sema &S, Expr *E) {
1874 // Must evaluate as a pointer.
1875 Expr::EvalResult Result;
1876 if (!E->EvaluateAsRValue(Result, Ctx: S.Context) || !Result.Val.isLValue())
1877 return {nullptr, CharUnits()};
1878
1879 const auto *BaseDecl =
1880 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1881 if (!BaseDecl)
1882 return {nullptr, CharUnits()};
1883
1884 return {BaseDecl, Result.Val.getLValueOffset()};
1885}
1886
1887static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1888 bool RequireConstant = false) {
1889 if (Arg->hasPlaceholderType()) {
1890 ExprResult R = S.CheckPlaceholderExpr(E: Arg);
1891 if (R.isInvalid())
1892 return true;
1893 Arg = R.get();
1894 }
1895
1896 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1897 return OpKind != PAO_BlendInteger;
1898 };
1899 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1900 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1901 OpKind == PAO_SignGeneric || OpKind == PAO_BlendPC;
1902 };
1903
1904 // Require the value to have the right range of type.
1905 QualType ExpectedTy;
1906 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1907 ExpectedTy = Arg->getType().getUnqualifiedType();
1908 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1909 ExpectedTy = S.Context.VoidPtrTy;
1910 } else if (AllowsInteger(OpKind) &&
1911 Arg->getType()->isIntegralOrUnscopedEnumerationType()) {
1912 ExpectedTy = S.Context.getUIntPtrType();
1913
1914 } else {
1915 // Diagnose the failures.
1916 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_value_bad_type)
1917 << unsigned(OpKind == PAO_Discriminator ? 1
1918 : OpKind == PAO_BlendPointer ? 2
1919 : OpKind == PAO_BlendInteger ? 3
1920 : OpKind == PAO_BlendPC ? 4
1921 : 0)
1922 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1923 << Arg->getType() << Arg->getSourceRange();
1924 return true;
1925 }
1926
1927 // Convert to that type. This should just be an lvalue-to-rvalue
1928 // conversion.
1929 if (S.convertArgumentToType(Value&: Arg, Ty: ExpectedTy))
1930 return true;
1931
1932 if (!RequireConstant) {
1933 // Warn about null pointers for non-generic sign and auth operations.
1934 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1935 Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNull)) {
1936 S.Diag(Loc: Arg->getExprLoc(), DiagID: OpKind == PAO_Sign
1937 ? diag::warn_ptrauth_sign_null_pointer
1938 : diag::warn_ptrauth_auth_null_pointer)
1939 << Arg->getSourceRange();
1940 }
1941
1942 return false;
1943 }
1944
1945 // Perform special checking on the arguments to ptrauth_sign_constant.
1946
1947 // The main argument.
1948 if (OpKind == PAO_Sign) {
1949 // Require the value we're signing to have a special form.
1950 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Arg);
1951 bool Invalid;
1952
1953 // Must be rooted in a declaration reference.
1954 if (!BaseDecl)
1955 Invalid = true;
1956
1957 // If it's a function declaration, we can't have an offset.
1958 else if (isa<FunctionDecl>(Val: BaseDecl))
1959 Invalid = !Offset.isZero();
1960
1961 // Otherwise we're fine.
1962 else
1963 Invalid = false;
1964
1965 if (Invalid)
1966 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_pointer);
1967 return Invalid;
1968 }
1969
1970 // The discriminator argument.
1971 assert(OpKind == PAO_Discriminator);
1972
1973 // Must be a pointer or integer or blend thereof.
1974 Expr *Pointer = nullptr;
1975 Expr *Integer = nullptr;
1976 if (auto *Call = dyn_cast<CallExpr>(Val: Arg->IgnoreParens())) {
1977 if (Call->getBuiltinCallee() ==
1978 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1979 Pointer = Call->getArg(Arg: 0);
1980 Integer = Call->getArg(Arg: 1);
1981 }
1982 }
1983 if (!Pointer && !Integer) {
1984 if (Arg->getType()->isPointerType())
1985 Pointer = Arg;
1986 else
1987 Integer = Arg;
1988 }
1989
1990 // Check the pointer.
1991 bool Invalid = false;
1992 if (Pointer) {
1993 assert(Pointer->getType()->isPointerType());
1994
1995 // TODO: if we're initializing a global, check that the address is
1996 // somehow related to what we're initializing. This probably will
1997 // never really be feasible and we'll have to catch it at link-time.
1998 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Pointer);
1999 if (!BaseDecl || !isa<VarDecl>(Val: BaseDecl))
2000 Invalid = true;
2001 }
2002
2003 // Check the integer.
2004 if (Integer) {
2005 assert(Integer->getType()->isIntegerType());
2006 if (!Integer->isEvaluatable(Ctx: S.Context))
2007 Invalid = true;
2008 }
2009
2010 if (Invalid)
2011 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_discriminator);
2012 return Invalid;
2013}
2014
2015static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call) {
2016 if (S.checkArgCount(Call, DesiredArgCount: 2))
2017 return ExprError();
2018 if (checkPointerAuthEnabled(S, E: Call))
2019 return ExprError();
2020 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Strip) ||
2021 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]))
2022 return ExprError();
2023
2024 Call->setType(Call->getArgs()[0]->getType());
2025 return Call;
2026}
2027
2028static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call) {
2029 if (S.checkArgCount(Call, DesiredArgCount: 2))
2030 return ExprError();
2031 if (checkPointerAuthEnabled(S, E: Call))
2032 return ExprError();
2033 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_BlendPointer) ||
2034 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_BlendInteger))
2035 return ExprError();
2036
2037 Call->setType(S.Context.getUIntPtrType());
2038 return Call;
2039}
2040
2041static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call) {
2042 if (S.checkArgCount(Call, DesiredArgCount: 2))
2043 return ExprError();
2044 if (checkPointerAuthEnabled(S, E: Call))
2045 return ExprError();
2046 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_SignGeneric) ||
2047 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_Discriminator))
2048 return ExprError();
2049
2050 Call->setType(S.Context.getUIntPtrType());
2051 return Call;
2052}
2053
2054static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call,
2055 PointerAuthOpKind OpKind,
2056 bool RequireConstant) {
2057 if (S.checkArgCount(Call, DesiredArgCount: 3))
2058 return ExprError();
2059 if (checkPointerAuthEnabled(S, E: Call))
2060 return ExprError();
2061 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind, RequireConstant) ||
2062 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
2063 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator,
2064 RequireConstant))
2065 return ExprError();
2066
2067 Call->setType(Call->getArgs()[0]->getType());
2068 return Call;
2069}
2070
2071static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call) {
2072 if (S.checkArgCount(Call, DesiredArgCount: 5))
2073 return ExprError();
2074 if (checkPointerAuthEnabled(S, E: Call))
2075 return ExprError();
2076 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
2077 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
2078 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
2079 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
2080 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator))
2081 return ExprError();
2082
2083 Call->setType(Call->getArgs()[0]->getType());
2084 return Call;
2085}
2086
2087static ExprResult PointerAuthAuthWithPCAndResign(Sema &S, CallExpr *Call) {
2088 if (S.checkArgCount(Call, DesiredArgCount: 6))
2089 return ExprError();
2090 if (checkPointerAuthEnabled(S, E: Call))
2091 return ExprError();
2092 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
2093 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
2094 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
2095 checkPointerAuthValue(S, Arg&: Call->getArgs()[3], OpKind: PAO_BlendPC) ||
2096 checkPointerAuthKey(S, Arg&: Call->getArgs()[4]) ||
2097 checkPointerAuthValue(S, Arg&: Call->getArgs()[5], OpKind: PAO_Discriminator))
2098 return ExprError();
2099
2100 // Validate that the oldKey is IA or IB, not DA or DB.
2101 // This enforces the constraint that auth_with_pc_and_resign only supports
2102 // IA/IB keys for authentication, as only those keys support the PC-based
2103 // signing instructions (paciasppc/pacibsppc).
2104 unsigned OldKey = 0;
2105 if (!S.checkConstantPointerAuthKey(Arg: Call->getArgs()[1], Result&: OldKey)) {
2106 using AK = PointerAuthSchema::ARM8_3Key;
2107 if (OldKey != static_cast<unsigned>(AK::ASIA) &&
2108 OldKey != static_cast<unsigned>(AK::ASIB)) {
2109 S.Diag(Loc: Call->getArgs()[1]->getExprLoc(),
2110 DiagID: diag::err_ptrauth_auth_with_pc_and_resign_invalid_key)
2111 << OldKey << Call->getArgs()[1]->getSourceRange();
2112 return ExprError();
2113 }
2114 }
2115
2116 Call->setType(Call->getArgs()[0]->getType());
2117 return Call;
2118}
2119
2120static ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call) {
2121 if (S.checkArgCount(Call, DesiredArgCount: 6))
2122 return ExprError();
2123 if (checkPointerAuthEnabled(S, E: Call))
2124 return ExprError();
2125 const Expr *AddendExpr = Call->getArg(Arg: 5);
2126 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(Ctx: S.Context);
2127 if (!AddendIsConstInt) {
2128 const Expr *Arg = Call->getArg(Arg: 5)->IgnoreParenImpCasts();
2129 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreParenCasts());
2130 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
2131 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_constant_integer_last_arg_type)
2132 << FDecl->getDeclName() << Arg->getSourceRange();
2133 }
2134 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
2135 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
2136 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
2137 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
2138 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator) ||
2139 !AddendIsConstInt)
2140 return ExprError();
2141
2142 Call->setType(Call->getArgs()[0]->getType());
2143 return Call;
2144}
2145
2146static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call) {
2147 if (checkPointerAuthEnabled(S, E: Call))
2148 return ExprError();
2149
2150 // We've already performed normal call type-checking.
2151 const Expr *Arg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
2152
2153 // Operand must be an ordinary or UTF-8 string literal.
2154 const auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
2155 if (!Literal || Literal->getCharByteWidth() != 1) {
2156 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_string_not_literal)
2157 << (Literal ? 1 : 0) << Arg->getSourceRange();
2158 return ExprError();
2159 }
2160
2161 return Call;
2162}
2163
2164static ExprResult GetVTablePointer(Sema &S, CallExpr *Call) {
2165 if (S.checkArgCount(Call, DesiredArgCount: 1))
2166 return ExprError();
2167 Expr *FirstArg = Call->getArg(Arg: 0);
2168 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(E: FirstArg);
2169 if (FirstValue.isInvalid())
2170 return ExprError();
2171 Call->setArg(Arg: 0, ArgExpr: FirstValue.get());
2172 QualType FirstArgType = FirstArg->getType();
2173 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
2174 FirstArgType = S.Context.getDecayedType(T: FirstArgType);
2175
2176 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
2177 if (!FirstArgRecord) {
2178 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
2179 << /*isPolymorphic=*/0 << FirstArgType;
2180 return ExprError();
2181 }
2182 if (S.RequireCompleteType(
2183 Loc: FirstArg->getBeginLoc(), T: FirstArgType->getPointeeType(),
2184 DiagID: diag::err_get_vtable_pointer_requires_complete_type)) {
2185 return ExprError();
2186 }
2187
2188 if (!FirstArgRecord->isPolymorphic()) {
2189 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
2190 << /*isPolymorphic=*/1 << FirstArgRecord;
2191 return ExprError();
2192 }
2193 QualType ReturnType = S.Context.getPointerType(T: S.Context.VoidTy.withConst());
2194 Call->setType(ReturnType);
2195 return Call;
2196}
2197
2198static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) {
2199 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2200 return ExprError();
2201
2202 // Compute __builtin_launder's parameter type from the argument.
2203 // The parameter type is:
2204 // * The type of the argument if it's not an array or function type,
2205 // Otherwise,
2206 // * The decayed argument type.
2207 QualType ParamTy = [&]() {
2208 QualType ArgTy = TheCall->getArg(Arg: 0)->getType();
2209 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
2210 return S.Context.getPointerType(T: Ty->getElementType());
2211 if (ArgTy->isFunctionType()) {
2212 return S.Context.getPointerType(T: ArgTy);
2213 }
2214 return ArgTy;
2215 }();
2216
2217 TheCall->setType(ParamTy);
2218
2219 auto DiagSelect = [&]() -> std::optional<unsigned> {
2220 if (!ParamTy->isPointerType())
2221 return 0;
2222 if (ParamTy->isFunctionPointerType())
2223 return 1;
2224 if (ParamTy->isVoidPointerType())
2225 return 2;
2226 return std::optional<unsigned>{};
2227 }();
2228 if (DiagSelect) {
2229 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_launder_invalid_arg)
2230 << *DiagSelect << TheCall->getSourceRange();
2231 return ExprError();
2232 }
2233
2234 // We either have an incomplete class type, or we have a class template
2235 // whose instantiation has not been forced. Example:
2236 //
2237 // template <class T> struct Foo { T value; };
2238 // Foo<int> *p = nullptr;
2239 // auto *d = __builtin_launder(p);
2240 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T: ParamTy->getPointeeType(),
2241 DiagID: diag::err_incomplete_type))
2242 return ExprError();
2243
2244 assert(ParamTy->getPointeeType()->isObjectType() &&
2245 "Unhandled non-object pointer case");
2246
2247 InitializedEntity Entity =
2248 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ParamTy, Consumed: false);
2249 ExprResult Arg =
2250 S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: TheCall->getArg(Arg: 0));
2251 if (Arg.isInvalid())
2252 return ExprError();
2253 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
2254
2255 return TheCall;
2256}
2257
2258static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall) {
2259 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2260 return ExprError();
2261
2262 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
2263 if (Arg.isInvalid())
2264 return ExprError();
2265 QualType ParamTy = Arg.get()->getType();
2266 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
2267 TheCall->setType(S.Context.BoolTy);
2268
2269 // Only accept pointers to objects as arguments, which should have object
2270 // pointer or void pointer types.
2271 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2272 // LWG4138: Function pointer types not allowed
2273 if (PT->getPointeeType()->isFunctionType()) {
2274 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2275 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2276 << 1;
2277 return ExprError();
2278 }
2279 // Disallow VLAs too since those shouldn't be able to
2280 // be a template parameter for `std::is_within_lifetime`
2281 if (PT->getPointeeType()->isVariableArrayType()) {
2282 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(), DiagID: diag::err_vla_unsupported)
2283 << 1 << "__builtin_is_within_lifetime";
2284 return ExprError();
2285 }
2286 } else {
2287 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2288 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2289 << 0;
2290 return ExprError();
2291 }
2292 return TheCall;
2293}
2294
2295static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall) {
2296 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2297 return ExprError();
2298
2299 QualType Dest = TheCall->getArg(Arg: 0)->getType();
2300 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2301 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2302 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2303 << /*a pointer*/ 0;
2304 return ExprError();
2305 }
2306
2307 QualType T = Dest->getPointeeType();
2308 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T,
2309 DiagID: diag::err_incomplete_type))
2310 return ExprError();
2311
2312 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2313 T->isIncompleteArrayType()) {
2314 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2315 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2316 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2317 return ExprError();
2318 }
2319
2320 TheCall->setType(Dest);
2321
2322 QualType Src = TheCall->getArg(Arg: 1)->getType();
2323 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2324 S.Diag(Loc: TheCall->getArg(Arg: 1)->getExprLoc(),
2325 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2326 << /*the same*/ 3;
2327 return ExprError();
2328 }
2329
2330 Expr *SizeExpr = TheCall->getArg(Arg: 2);
2331 ExprResult Size = S.DefaultLvalueConversion(E: SizeExpr);
2332 if (Size.isInvalid())
2333 return ExprError();
2334
2335 Size = S.tryConvertExprToType(E: Size.get(), Ty: S.getASTContext().getSizeType());
2336 if (Size.isInvalid())
2337 return ExprError();
2338 SizeExpr = Size.get();
2339 TheCall->setArg(Arg: 2, ArgExpr: SizeExpr);
2340
2341 return TheCall;
2342}
2343
2344// Emit an error and return true if the current object format type is in the
2345// list of unsupported types.
2346static bool CheckBuiltinTargetNotInUnsupported(
2347 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2348 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2349 llvm::Triple::ObjectFormatType CurObjFormat =
2350 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2351 if (llvm::is_contained(Range&: UnsupportedObjectFormatTypes, Element: CurObjFormat)) {
2352 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2353 << TheCall->getSourceRange();
2354 return true;
2355 }
2356 return false;
2357}
2358
2359// Emit an error and return true if the current architecture is not in the list
2360// of supported architectures.
2361static bool
2362CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall,
2363 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2364 llvm::Triple::ArchType CurArch =
2365 S.getASTContext().getTargetInfo().getTriple().getArch();
2366 if (llvm::is_contained(Range&: SupportedArchs, Element: CurArch))
2367 return false;
2368 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2369 << TheCall->getSourceRange();
2370 return true;
2371}
2372
2373static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2374 SourceLocation CallSiteLoc);
2375
2376bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2377 CallExpr *TheCall) {
2378 switch (TI.getTriple().getArch()) {
2379 default:
2380 // Some builtins don't require additional checking, so just consider these
2381 // acceptable.
2382 return false;
2383 case llvm::Triple::arm:
2384 case llvm::Triple::armeb:
2385 case llvm::Triple::thumb:
2386 case llvm::Triple::thumbeb:
2387 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2388 case llvm::Triple::aarch64:
2389 case llvm::Triple::aarch64_32:
2390 case llvm::Triple::aarch64_be:
2391 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2392 case llvm::Triple::bpfeb:
2393 case llvm::Triple::bpfel:
2394 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2395 case llvm::Triple::dxil:
2396 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2397 case llvm::Triple::hexagon:
2398 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2399 case llvm::Triple::mips:
2400 case llvm::Triple::mipsel:
2401 case llvm::Triple::mips64:
2402 case llvm::Triple::mips64el:
2403 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2404 case llvm::Triple::spirv:
2405 case llvm::Triple::spirv32:
2406 case llvm::Triple::spirv64:
2407 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2408 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2409 return false;
2410 case llvm::Triple::systemz:
2411 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2412 case llvm::Triple::x86:
2413 case llvm::Triple::x86_64:
2414 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2415 case llvm::Triple::ppc:
2416 case llvm::Triple::ppcle:
2417 case llvm::Triple::ppc64:
2418 case llvm::Triple::ppc64le:
2419 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2420 case llvm::Triple::amdgpu:
2421 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(TI, BuiltinID, TheCall);
2422 case llvm::Triple::riscv32:
2423 case llvm::Triple::riscv64:
2424 case llvm::Triple::riscv32be:
2425 case llvm::Triple::riscv64be:
2426 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2427 case llvm::Triple::loongarch32:
2428 case llvm::Triple::loongarch64:
2429 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2430 TheCall);
2431 case llvm::Triple::wasm32:
2432 case llvm::Triple::wasm64:
2433 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2434 case llvm::Triple::nvptx:
2435 case llvm::Triple::nvptx64:
2436 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2437 }
2438}
2439
2440static bool isValidMathElementType(QualType T) {
2441 return T->isDependentType() ||
2442 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2443}
2444
2445// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2446// not a valid type, emit an error message and return true. Otherwise return
2447// false.
2448static bool
2449checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy,
2450 Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr,
2451 int ArgOrdinal) {
2452 clang::QualType EltTy =
2453 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2454 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2455 : ArgTy;
2456
2457 switch (ArgTyRestr) {
2458 case Sema::EltwiseBuiltinArgTyRestriction::None:
2459 if (!ArgTy->getAs<VectorType>() && !ArgTy->getAs<MatrixType>() &&
2460 !isValidMathElementType(T: ArgTy)) {
2461 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2462 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2463 << ArgTy;
2464 }
2465 break;
2466 case Sema::EltwiseBuiltinArgTyRestriction::FloatTy:
2467 if (!EltTy->isRealFloatingType()) {
2468 // FIXME: make diagnostic's wording correct for matrices
2469 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2470 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2471 << /* floating-point */ 1 << ArgTy;
2472 }
2473 break;
2474 case Sema::EltwiseBuiltinArgTyRestriction::IntegerTy:
2475 if (!EltTy->isIntegerType()) {
2476 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2477 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2478 << /* no fp */ 0 << ArgTy;
2479 }
2480 break;
2481 case Sema::EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy:
2482 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2483 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2484 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2485 << /* or fp */ 1 << ArgTy;
2486 }
2487 break;
2488 }
2489
2490 return false;
2491}
2492
2493/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2494/// This checks that the target supports the builtin and that the string
2495/// argument is constant and valid.
2496static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2497 const TargetInfo *AuxTI, unsigned BuiltinID) {
2498 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2499 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2500 "Expecting __builtin_cpu_...");
2501
2502 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2503 const TargetInfo *TheTI = &TI;
2504 auto SupportsBI = [=](const TargetInfo *TInfo) {
2505 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2506 (!IsCPUSupports && TInfo->supportsCpuIs()));
2507 };
2508 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2509 TheTI = AuxTI;
2510
2511 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2512 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2513 return S.Diag(Loc: TheCall->getBeginLoc(),
2514 DiagID: TI.getTriple().isOSAIX()
2515 ? diag::err_builtin_aix_os_unsupported
2516 : diag::err_builtin_target_unsupported)
2517 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2518
2519 Expr *Arg = TheCall->getArg(Arg: 0)->IgnoreParenImpCasts();
2520 // Check if the argument is a string literal.
2521 if (!isa<StringLiteral>(Val: Arg))
2522 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
2523 << Arg->getSourceRange();
2524
2525 // Check the contents of the string.
2526 StringRef Feature = cast<StringLiteral>(Val: Arg)->getString();
2527 if (IsCPUSupports && !TheTI->validateCpuSupports(Name: Feature)) {
2528 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_invalid_cpu_supports)
2529 << Arg->getSourceRange();
2530 return false;
2531 }
2532 if (!IsCPUSupports && !TheTI->validateCpuIs(Name: Feature))
2533 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_cpu_is)
2534 << Arg->getSourceRange();
2535 return false;
2536}
2537
2538/// Checks that __builtin_bswapg was called with a single argument, which is an
2539/// unsigned integer, and overrides the return value type to the integer type.
2540static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2541 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2542 return true;
2543 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2544 if (ArgRes.isInvalid())
2545 return true;
2546
2547 Expr *Arg = ArgRes.get();
2548 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2549 if (Arg->isTypeDependent())
2550 return false;
2551
2552 QualType ArgTy = Arg->getType();
2553
2554 if (!ArgTy->isIntegerType()) {
2555 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2556 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2557 << ArgTy;
2558 return true;
2559 }
2560 if (const auto *BT = dyn_cast<BitIntType>(Val&: ArgTy)) {
2561 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2562 BT->getNumBits() != 1) {
2563 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_bswapg_invalid_bit_width)
2564 << ArgTy << BT->getNumBits();
2565 return true;
2566 }
2567 }
2568 TheCall->setType(ArgTy);
2569 return false;
2570}
2571
2572/// Checks that __builtin_bitreverseg was called with a single argument, which
2573/// is an integer
2574static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2575 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2576 return true;
2577 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2578 if (ArgRes.isInvalid())
2579 return true;
2580
2581 Expr *Arg = ArgRes.get();
2582 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2583 if (Arg->isTypeDependent())
2584 return false;
2585
2586 QualType ArgTy = Arg->getType();
2587
2588 if (!ArgTy->isIntegerType()) {
2589 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2590 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2591 << ArgTy;
2592 return true;
2593 }
2594 TheCall->setType(ArgTy);
2595 return false;
2596}
2597
2598/// Checks that __builtin_popcountg was called with a single argument, which is
2599/// an unsigned integer.
2600static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2601 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2602 return true;
2603
2604 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2605 if (ArgRes.isInvalid())
2606 return true;
2607
2608 Expr *Arg = ArgRes.get();
2609 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2610
2611 QualType ArgTy = Arg->getType();
2612
2613 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2614 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2615 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2616 << ArgTy;
2617 return true;
2618 }
2619 return false;
2620}
2621
2622/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2623/// argument and return either int, bool, or the argument type.
2624static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2625 QualType ReturnType) {
2626 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2627 return true;
2628
2629 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2630 if (ArgRes.isInvalid())
2631 return true;
2632
2633 Expr *Arg = ArgRes.get();
2634 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2635
2636 QualType ArgTy = Arg->getType();
2637 // C23 stdbit.h functions do not permit bool or enumeration types.
2638 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2639 return S.Diag(Loc: Arg->getBeginLoc(),
2640 DiagID: diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2641 << 1 /*1st argument*/ << ArgTy;
2642 if (!ArgTy->isUnsignedIntegerType())
2643 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_stdc_invalid_arg_type)
2644 << 1 /*1st argument*/ << ArgTy;
2645
2646 // For builtins returning unsigned int, verify the argument's bit width fits.
2647 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2648 // produce a count that overflows the return type.
2649 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2650 uint64_t ArgWidth = S.Context.getIntWidth(T: ArgTy);
2651 uint64_t ReturnTypeWidth = S.Context.getIntWidth(T: S.Context.UnsignedIntTy);
2652 if (!llvm::isUIntN(N: ReturnTypeWidth, x: ArgWidth))
2653 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_stdc_result_overflow)
2654 << ArgTy;
2655 }
2656
2657 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2658 return false;
2659}
2660
2661/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2662/// an unsigned integer, and an optional second argument, which is promoted to
2663/// an 'int'.
2664static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2665 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
2666 return true;
2667
2668 ExprResult Arg0Res = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2669 if (Arg0Res.isInvalid())
2670 return true;
2671
2672 Expr *Arg0 = Arg0Res.get();
2673 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2674
2675 QualType Arg0Ty = Arg0->getType();
2676
2677 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2678 S.Diag(Loc: Arg0->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2679 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2680 << Arg0Ty;
2681 return true;
2682 }
2683
2684 if (TheCall->getNumArgs() > 1) {
2685 ExprResult Arg1Res = S.UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
2686 if (Arg1Res.isInvalid())
2687 return true;
2688
2689 Expr *Arg1 = Arg1Res.get();
2690 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2691
2692 QualType Arg1Ty = Arg1->getType();
2693
2694 if (!Arg1Ty->isSpecificBuiltinType(K: BuiltinType::Int)) {
2695 S.Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2696 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2697 return true;
2698 }
2699 }
2700
2701 return false;
2702}
2703
2704class RotateIntegerConverter : public Sema::ContextualImplicitConverter {
2705 unsigned ArgIndex;
2706 bool OnlyUnsigned;
2707
2708 Sema::SemaDiagnosticBuilder emitError(Sema &S, SourceLocation Loc,
2709 QualType T) {
2710 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2711 << ArgIndex << /*scalar*/ 1
2712 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2713 << /*no fp*/ 0 << T;
2714 }
2715
2716public:
2717 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2718 : ContextualImplicitConverter(/*Suppress=*/false,
2719 /*SuppressConversion=*/true),
2720 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2721
2722 bool match(QualType T) override {
2723 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2724 }
2725
2726 Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2727 QualType T) override {
2728 return emitError(S, Loc, T);
2729 }
2730
2731 Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2732 QualType T) override {
2733 return emitError(S, Loc, T);
2734 }
2735
2736 Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2737 QualType T,
2738 QualType ConvTy) override {
2739 return emitError(S, Loc, T);
2740 }
2741
2742 Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2743 QualType ConvTy) override {
2744 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2745 }
2746
2747 Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2748 QualType T) override {
2749 return emitError(S, Loc, T);
2750 }
2751
2752 Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2753 QualType ConvTy) override {
2754 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2755 }
2756
2757 Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2758 QualType T,
2759 QualType ConvTy) override {
2760 llvm_unreachable("conversion functions are permitted");
2761 }
2762};
2763
2764/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2765/// arguments, that the first argument is an unsigned integer type, and that
2766/// the second argument is an integer type.
2767static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2768 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
2769 return true;
2770
2771 // First argument (value to rotate) must be unsigned integer type.
2772 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2773 ExprResult Arg0Res = S.PerformContextualImplicitConversion(
2774 Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), FromE: TheCall->getArg(Arg: 0), Converter&: Arg0Converter);
2775 if (Arg0Res.isInvalid())
2776 return true;
2777
2778 Expr *Arg0 = Arg0Res.get();
2779 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2780
2781 QualType Arg0Ty = Arg0->getType();
2782 if (!Arg0Ty->isUnsignedIntegerType())
2783 return true;
2784
2785 // Second argument (rotation count) must be integer type.
2786 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2787 ExprResult Arg1Res = S.PerformContextualImplicitConversion(
2788 Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), FromE: TheCall->getArg(Arg: 1), Converter&: Arg1Converter);
2789 if (Arg1Res.isInvalid())
2790 return true;
2791
2792 Expr *Arg1 = Arg1Res.get();
2793 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2794
2795 QualType Arg1Ty = Arg1->getType();
2796 if (!Arg1Ty->isIntegerType())
2797 return true;
2798
2799 TheCall->setType(Arg0Ty);
2800 return false;
2801}
2802
2803static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2804 unsigned Pos, bool AllowConst,
2805 bool AllowAS) {
2806 QualType MaskTy = MaskArg->getType();
2807 if (!MaskTy->isExtVectorBoolType())
2808 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2809 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2810 << MaskTy;
2811
2812 QualType PtrTy = PtrArg->getType();
2813 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2814 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2815 << Pos << "scalar pointer";
2816
2817 QualType PointeeTy = PtrTy->getPointeeType();
2818 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2819 (!AllowConst && PointeeTy.isConstQualified()) ||
2820 (!AllowAS && PointeeTy.hasAddressSpace())) {
2821 QualType Target =
2822 S.Context.getPointerType(T: PointeeTy.getAtomicUnqualifiedType());
2823 return S.Diag(Loc: PtrArg->getExprLoc(),
2824 DiagID: diag::err_typecheck_convert_incompatible)
2825 << PtrTy << Target << /*different qualifiers=*/5
2826 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2827 << PtrTy << Target;
2828 }
2829 return false;
2830}
2831
2832static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2833 bool TypeDependent = false;
2834 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2835 ExprResult Converted =
2836 S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg));
2837 if (Converted.isInvalid())
2838 return true;
2839 TheCall->setArg(Arg, ArgExpr: Converted.get());
2840 TypeDependent |= Converted.get()->isTypeDependent();
2841 }
2842
2843 if (TypeDependent)
2844 TheCall->setType(S.Context.DependentTy);
2845 return false;
2846}
2847
2848static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall) {
2849 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
2850 return ExprError();
2851
2852 if (ConvertMaskedBuiltinArgs(S, TheCall))
2853 return ExprError();
2854
2855 Expr *MaskArg = TheCall->getArg(Arg: 0);
2856 Expr *PtrArg = TheCall->getArg(Arg: 1);
2857 if (TheCall->isTypeDependent())
2858 return TheCall;
2859
2860 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 2, /*AllowConst=*/true,
2861 AllowAS: TheCall->getBuiltinCallee() ==
2862 Builtin::BI__builtin_masked_load))
2863 return ExprError();
2864
2865 QualType MaskTy = MaskArg->getType();
2866 QualType PtrTy = PtrArg->getType();
2867 QualType PointeeTy = PtrTy->getPointeeType();
2868 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2869
2870 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2871 NumElts: MaskVecTy->getNumElements());
2872 if (TheCall->getNumArgs() == 3) {
2873 Expr *PassThruArg = TheCall->getArg(Arg: 2);
2874 QualType PassThruTy = PassThruArg->getType();
2875 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2876 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2877 << /* third argument */ 3 << RetTy;
2878 }
2879
2880 TheCall->setType(RetTy);
2881 return TheCall;
2882}
2883
2884static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall) {
2885 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2886 return ExprError();
2887
2888 if (ConvertMaskedBuiltinArgs(S, TheCall))
2889 return ExprError();
2890
2891 Expr *MaskArg = TheCall->getArg(Arg: 0);
2892 Expr *ValArg = TheCall->getArg(Arg: 1);
2893 Expr *PtrArg = TheCall->getArg(Arg: 2);
2894 if (TheCall->isTypeDependent())
2895 return TheCall;
2896
2897 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/false,
2898 AllowAS: TheCall->getBuiltinCallee() ==
2899 Builtin::BI__builtin_masked_store))
2900 return ExprError();
2901
2902 QualType MaskTy = MaskArg->getType();
2903 QualType PtrTy = PtrArg->getType();
2904 QualType ValTy = ValArg->getType();
2905 if (!ValTy->isVectorType())
2906 return ExprError(
2907 S.Diag(Loc: ValArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2908 << 2 << "vector");
2909
2910 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2911 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2912
2913 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2914 return ExprError(
2915 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2916 << S.getASTContext().BuiltinInfo.getQuotedName(
2917 ID: TheCall->getBuiltinCallee())
2918 << MaskTy << ValTy);
2919 }
2920
2921 if (!S.Context.hasSameType(T1: ValVecTy->getElementType().getUnqualifiedType(),
2922 T2: PtrTy->getPointeeType().getUnqualifiedType()))
2923 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
2924 DiagID: diag::err_vec_builtin_incompatible_vector)
2925 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2926 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
2927 TheCall->getArg(Arg: 1)->getEndLoc()));
2928
2929 TheCall->setType(S.Context.VoidTy);
2930 return TheCall;
2931}
2932
2933static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall) {
2934 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 3, MaxArgCount: 4))
2935 return ExprError();
2936
2937 if (ConvertMaskedBuiltinArgs(S, TheCall))
2938 return ExprError();
2939
2940 Expr *MaskArg = TheCall->getArg(Arg: 0);
2941 Expr *IdxArg = TheCall->getArg(Arg: 1);
2942 Expr *PtrArg = TheCall->getArg(Arg: 2);
2943 if (TheCall->isTypeDependent())
2944 return TheCall;
2945
2946 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/true,
2947 /*AllowAS=*/true))
2948 return ExprError();
2949
2950 QualType IdxTy = IdxArg->getType();
2951 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2952 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2953 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2954 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2955 << IdxTy;
2956
2957 QualType MaskTy = MaskArg->getType();
2958 QualType PtrTy = PtrArg->getType();
2959 QualType PointeeTy = PtrTy->getPointeeType();
2960 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2961 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2962 return ExprError(
2963 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2964 << S.getASTContext().BuiltinInfo.getQuotedName(
2965 ID: TheCall->getBuiltinCallee())
2966 << MaskTy << IdxTy);
2967
2968 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2969 NumElts: MaskVecTy->getNumElements());
2970 if (TheCall->getNumArgs() == 4) {
2971 Expr *PassThruArg = TheCall->getArg(Arg: 3);
2972 QualType PassThruTy = PassThruArg->getType();
2973 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2974 return S.Diag(Loc: PassThruArg->getExprLoc(),
2975 DiagID: diag::err_vec_masked_load_store_ptr)
2976 << /* fourth argument */ 4 << RetTy;
2977 }
2978
2979 TheCall->setType(RetTy);
2980 return TheCall;
2981}
2982
2983static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall) {
2984 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 4))
2985 return ExprError();
2986
2987 if (ConvertMaskedBuiltinArgs(S, TheCall))
2988 return ExprError();
2989
2990 Expr *MaskArg = TheCall->getArg(Arg: 0);
2991 Expr *IdxArg = TheCall->getArg(Arg: 1);
2992 Expr *ValArg = TheCall->getArg(Arg: 2);
2993 Expr *PtrArg = TheCall->getArg(Arg: 3);
2994 if (TheCall->isTypeDependent())
2995 return TheCall;
2996
2997 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 4, /*AllowConst=*/false,
2998 /*AllowAS=*/true))
2999 return ExprError();
3000
3001 QualType IdxTy = IdxArg->getType();
3002 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
3003 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
3004 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3005 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
3006 << IdxTy;
3007
3008 QualType ValTy = ValArg->getType();
3009 QualType MaskTy = MaskArg->getType();
3010 QualType PtrTy = PtrArg->getType();
3011
3012 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
3013 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
3014 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
3015 return ExprError(
3016 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
3017 << S.getASTContext().BuiltinInfo.getQuotedName(
3018 ID: TheCall->getBuiltinCallee())
3019 << MaskTy << IdxTy);
3020 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
3021 return ExprError(
3022 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
3023 << S.getASTContext().BuiltinInfo.getQuotedName(
3024 ID: TheCall->getBuiltinCallee())
3025 << MaskTy << ValTy);
3026
3027 if (!S.Context.hasSameType(T1: ValVecTy->getElementType().getUnqualifiedType(),
3028 T2: PtrTy->getPointeeType().getUnqualifiedType()))
3029 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
3030 DiagID: diag::err_vec_builtin_incompatible_vector)
3031 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
3032 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
3033 TheCall->getArg(Arg: 1)->getEndLoc()));
3034
3035 TheCall->setType(S.Context.VoidTy);
3036 return TheCall;
3037}
3038
3039static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall) {
3040 SourceLocation Loc = TheCall->getBeginLoc();
3041 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
3042 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
3043
3044 if (Args.size() == 0) {
3045 S.Diag(Loc: TheCall->getBeginLoc(),
3046 DiagID: diag::err_typecheck_call_too_few_args_at_least)
3047 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
3048 << /*is_non_object=*/0 << TheCall->getSourceRange();
3049 return ExprError();
3050 }
3051
3052 QualType FuncT = Args[0]->getType();
3053
3054 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
3055 if (Args.size() < 2) {
3056 S.Diag(Loc: TheCall->getBeginLoc(),
3057 DiagID: diag::err_typecheck_call_too_few_args_at_least)
3058 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
3059 << /*is_non_object=*/0 << TheCall->getSourceRange();
3060 return ExprError();
3061 }
3062
3063 const Type *MemPtrClass = MPT->getQualifier().getAsType();
3064 QualType ObjectT = Args[1]->getType();
3065
3066 if (MPT->isMemberDataPointer() && S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
3067 return ExprError();
3068
3069 ExprResult ObjectArg = [&]() -> ExprResult {
3070 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
3071 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
3072 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
3073 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
3074 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
3075 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
3076 if (S.Context.hasSameType(T1: QualType(MemPtrClass, 0),
3077 T2: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc)) ||
3078 S.BuiltinIsBaseOf(RhsTLoc: Args[1]->getBeginLoc(), LhsT: QualType(MemPtrClass, 0),
3079 RhsT: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc))) {
3080 return Args[1];
3081 }
3082
3083 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
3084 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
3085 // reference_wrapper;
3086 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
3087 if (RD->isInStdNamespace() &&
3088 RD->getDeclName().getAsString() == "reference_wrapper") {
3089 CXXScopeSpec SS;
3090 IdentifierInfo *GetName = &S.Context.Idents.get(Name: "get");
3091 UnqualifiedId GetID;
3092 GetID.setIdentifier(Id: GetName, IdLoc: Loc);
3093
3094 ExprResult MemExpr = S.ActOnMemberAccessExpr(
3095 S: S.getCurScope(), Base: Args[1], OpLoc: Loc, OpKind: tok::period, SS,
3096 /*TemplateKWLoc=*/SourceLocation(), Member&: GetID, ObjCImpDecl: nullptr);
3097
3098 if (MemExpr.isInvalid())
3099 return ExprError();
3100
3101 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemExpr.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
3102 }
3103 }
3104
3105 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
3106 // class T and t1 does not satisfy the previous two items;
3107
3108 return S.ActOnUnaryOp(S: S.getCurScope(), OpLoc: Loc, Op: tok::star, Input: Args[1]);
3109 }();
3110
3111 if (ObjectArg.isInvalid())
3112 return ExprError();
3113
3114 ExprResult BinOp = S.ActOnBinOp(S: S.getCurScope(), TokLoc: TheCall->getBeginLoc(),
3115 Kind: tok::periodstar, LHSExpr: ObjectArg.get(), RHSExpr: Args[0]);
3116 if (BinOp.isInvalid())
3117 return ExprError();
3118
3119 if (MPT->isMemberDataPointer())
3120 return BinOp;
3121
3122 // Give the synthesized expression a valid source range for diagnostics.
3123 auto *MemCall = new (S.Context)
3124 ParenExpr(TheCall->getBeginLoc(), TheCall->getRParenLoc(), BinOp.get());
3125
3126 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemCall, LParenLoc: TheCall->getBeginLoc(),
3127 ArgExprs: Args.drop_front(N: 2), RParenLoc: TheCall->getRParenLoc());
3128 }
3129 return S.ActOnCallExpr(S: S.getCurScope(), Fn: Args.front(), LParenLoc: TheCall->getBeginLoc(),
3130 ArgExprs: Args.drop_front(), RParenLoc: TheCall->getRParenLoc());
3131}
3132
3133// Performs a similar job to Sema::UsualUnaryConversions, but without any
3134// implicit promotion of integral/enumeration types.
3135static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E) {
3136 // First, convert to an r-value.
3137 ExprResult Res = S.DefaultFunctionArrayLvalueConversion(E);
3138 if (Res.isInvalid())
3139 return ExprError();
3140
3141 // Promote floating-point types.
3142 return S.UsualUnaryFPConversions(E: Res.get());
3143}
3144
3145static QualType getVectorElementType(ASTContext &Context, QualType VecTy) {
3146 if (const auto *TyA = VecTy->getAs<VectorType>())
3147 return TyA->getElementType();
3148 if (VecTy->isSizelessVectorType())
3149 return VecTy->getSizelessVectorEltType(Ctx: Context);
3150 return QualType();
3151}
3152
3153ExprResult
3154Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3155 CallExpr *TheCall) {
3156 ExprResult TheCallResult(TheCall);
3157
3158 // Find out if any arguments are required to be integer constant expressions.
3159 unsigned ICEArguments = 0;
3160 ASTContext::GetBuiltinTypeError Error;
3161 Context.GetBuiltinType(ID: BuiltinID, Error, IntegerConstantArgs: &ICEArguments);
3162 if (Error != ASTContext::GE_None)
3163 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
3164
3165 // If any arguments are required to be ICE's, check and diagnose.
3166 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
3167 // Skip arguments not required to be ICE's.
3168 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
3169
3170 llvm::APSInt Result;
3171 // If we don't have enough arguments, continue so we can issue better
3172 // diagnostic in checkArgCount(...)
3173 if (ArgNo < TheCall->getNumArgs() &&
3174 BuiltinConstantArg(TheCall, ArgNum: ArgNo, Result))
3175 return true;
3176 ICEArguments &= ~(1 << ArgNo);
3177 }
3178
3179 FPOptions FPO;
3180 switch (BuiltinID) {
3181 case Builtin::BI__builtin___get_unsafe_stack_start:
3182 case Builtin::BI__builtin___get_unsafe_stack_bottom:
3183 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3184 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3185 << "__safestack_get_unsafe_stack_bottom";
3186 break;
3187 case Builtin::BI__builtin___get_unsafe_stack_top:
3188 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3189 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3190 << "__safestack_get_unsafe_stack_top";
3191 break;
3192 case Builtin::BI__builtin___get_unsafe_stack_ptr:
3193 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3194 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3195 << "__safestack_get_unsafe_stack_ptr";
3196 break;
3197 case Builtin::BI__builtin_cpu_supports:
3198 case Builtin::BI__builtin_cpu_is:
3199 if (BuiltinCpu(S&: *this, TI: Context.getTargetInfo(), TheCall,
3200 AuxTI: Context.getAuxTargetInfo(), BuiltinID))
3201 return ExprError();
3202 break;
3203 case Builtin::BI__builtin_cpu_init:
3204 if (!Context.getTargetInfo().supportsCpuInit()) {
3205 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
3206 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
3207 return ExprError();
3208 }
3209 break;
3210 case Builtin::BI__builtin___CFStringMakeConstantString:
3211 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
3212 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
3213 if (CheckBuiltinTargetNotInUnsupported(
3214 S&: *this, BuiltinID, TheCall,
3215 UnsupportedObjectFormatTypes: {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
3216 return ExprError();
3217 assert(TheCall->getNumArgs() == 1 &&
3218 "Wrong # arguments to builtin CFStringMakeConstantString");
3219 if (ObjC().CheckObjCString(Arg: TheCall->getArg(Arg: 0)))
3220 return ExprError();
3221 break;
3222 case Builtin::BI__builtin_ms_va_start:
3223 case Builtin::BI__builtin_zos_va_start:
3224 case Builtin::BI__builtin_stdarg_start:
3225 case Builtin::BI__builtin_va_start:
3226 case Builtin::BI__builtin_c23_va_start:
3227 if (BuiltinVAStart(BuiltinID, TheCall))
3228 return ExprError();
3229 break;
3230 case Builtin::BI__va_start: {
3231 switch (Context.getTargetInfo().getTriple().getArch()) {
3232 case llvm::Triple::aarch64:
3233 case llvm::Triple::arm:
3234 case llvm::Triple::thumb:
3235 if (BuiltinVAStartARMMicrosoft(Call: TheCall))
3236 return ExprError();
3237 break;
3238 default:
3239 if (BuiltinVAStart(BuiltinID, TheCall))
3240 return ExprError();
3241 break;
3242 }
3243 break;
3244 }
3245
3246 // The acquire, release, and no fence variants are ARM and AArch64 only.
3247 case Builtin::BI_interlockedbittestandset_acq:
3248 case Builtin::BI_interlockedbittestandset_rel:
3249 case Builtin::BI_interlockedbittestandset_nf:
3250 case Builtin::BI_interlockedbittestandreset_acq:
3251 case Builtin::BI_interlockedbittestandreset_rel:
3252 case Builtin::BI_interlockedbittestandreset_nf:
3253 if (CheckBuiltinTargetInSupported(
3254 S&: *this, TheCall,
3255 SupportedArchs: {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
3256 return ExprError();
3257 break;
3258
3259 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
3260 case Builtin::BI_bittest64:
3261 case Builtin::BI_bittestandcomplement64:
3262 case Builtin::BI_bittestandreset64:
3263 case Builtin::BI_bittestandset64:
3264 case Builtin::BI_interlockedbittestandreset64:
3265 case Builtin::BI_interlockedbittestandset64:
3266 if (CheckBuiltinTargetInSupported(
3267 S&: *this, TheCall,
3268 SupportedArchs: {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3269 llvm::Triple::aarch64, llvm::Triple::amdgpu}))
3270 return ExprError();
3271 break;
3272
3273 // The 64-bit acquire, release, and no fence variants are AArch64 only.
3274 case Builtin::BI_interlockedbittestandreset64_acq:
3275 case Builtin::BI_interlockedbittestandreset64_rel:
3276 case Builtin::BI_interlockedbittestandreset64_nf:
3277 case Builtin::BI_interlockedbittestandset64_acq:
3278 case Builtin::BI_interlockedbittestandset64_rel:
3279 case Builtin::BI_interlockedbittestandset64_nf:
3280 if (CheckBuiltinTargetInSupported(S&: *this, TheCall, SupportedArchs: {llvm::Triple::aarch64}))
3281 return ExprError();
3282 break;
3283
3284 case Builtin::BI__builtin_set_flt_rounds:
3285 if (CheckBuiltinTargetInSupported(
3286 S&: *this, TheCall,
3287 SupportedArchs: {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3288 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgpu,
3289 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3290 llvm::Triple::ppc64le}))
3291 return ExprError();
3292 break;
3293
3294 case Builtin::BI__builtin_isgreater:
3295 case Builtin::BI__builtin_isgreaterequal:
3296 case Builtin::BI__builtin_isless:
3297 case Builtin::BI__builtin_islessequal:
3298 case Builtin::BI__builtin_islessgreater:
3299 case Builtin::BI__builtin_isunordered:
3300 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3301 return ExprError();
3302 break;
3303 case Builtin::BI__builtin_fpclassify:
3304 if (BuiltinFPClassification(TheCall, NumArgs: 6, BuiltinID))
3305 return ExprError();
3306 break;
3307 case Builtin::BI__builtin_isfpclass:
3308 if (BuiltinFPClassification(TheCall, NumArgs: 2, BuiltinID))
3309 return ExprError();
3310 break;
3311 case Builtin::BI__builtin_isfinite:
3312 case Builtin::BI__builtin_isinf:
3313 case Builtin::BI__builtin_isinf_sign:
3314 case Builtin::BI__builtin_isnan:
3315 case Builtin::BI__builtin_issignaling:
3316 case Builtin::BI__builtin_isnormal:
3317 case Builtin::BI__builtin_issubnormal:
3318 case Builtin::BI__builtin_iszero:
3319 case Builtin::BI__builtin_signbit:
3320 case Builtin::BI__builtin_signbitf:
3321 case Builtin::BI__builtin_signbitl:
3322 if (BuiltinFPClassification(TheCall, NumArgs: 1, BuiltinID))
3323 return ExprError();
3324 break;
3325 case Builtin::BI__builtin_shufflevector:
3326 return BuiltinShuffleVector(TheCall);
3327 // TheCall will be freed by the smart pointer here, but that's fine, since
3328 // BuiltinShuffleVector guts it, but then doesn't release it.
3329 case Builtin::BI__builtin_masked_load:
3330 case Builtin::BI__builtin_masked_expand_load:
3331 return BuiltinMaskedLoad(S&: *this, TheCall);
3332 case Builtin::BI__builtin_masked_store:
3333 case Builtin::BI__builtin_masked_compress_store:
3334 return BuiltinMaskedStore(S&: *this, TheCall);
3335 case Builtin::BI__builtin_masked_gather:
3336 return BuiltinMaskedGather(S&: *this, TheCall);
3337 case Builtin::BI__builtin_masked_scatter:
3338 return BuiltinMaskedScatter(S&: *this, TheCall);
3339 case Builtin::BI__builtin_invoke:
3340 return BuiltinInvoke(S&: *this, TheCall);
3341 case Builtin::BI__builtin_prefetch:
3342 if (BuiltinPrefetch(TheCall))
3343 return ExprError();
3344 break;
3345 case Builtin::BI__builtin_alloca_with_align:
3346 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3347 if (BuiltinAllocaWithAlign(TheCall))
3348 return ExprError();
3349 [[fallthrough]];
3350 case Builtin::BI__builtin_alloca:
3351 case Builtin::BI__builtin_alloca_uninitialized:
3352 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca)
3353 << TheCall->getDirectCallee();
3354 if (getLangOpts().OpenCL) {
3355 builtinAllocaAddrSpace(S&: *this, TheCall);
3356 }
3357 break;
3358 case Builtin::BI__builtin_infer_alloc_token:
3359 if (checkBuiltinInferAllocToken(S&: *this, TheCall))
3360 return ExprError();
3361 break;
3362 case Builtin::BI__arithmetic_fence:
3363 if (BuiltinArithmeticFence(TheCall))
3364 return ExprError();
3365 break;
3366 case Builtin::BI__assume:
3367 case Builtin::BI__builtin_assume:
3368 if (BuiltinAssume(TheCall))
3369 return ExprError();
3370 break;
3371 case Builtin::BI__builtin_assume_aligned:
3372 if (BuiltinAssumeAligned(TheCall))
3373 return ExprError();
3374 break;
3375 case Builtin::BI__builtin_dynamic_object_size:
3376 case Builtin::BI__builtin_object_size:
3377 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: 3))
3378 return ExprError();
3379 break;
3380 case Builtin::BI__builtin_longjmp:
3381 if (BuiltinLongjmp(TheCall))
3382 return ExprError();
3383 break;
3384 case Builtin::BI__builtin_setjmp:
3385 if (BuiltinSetjmp(TheCall))
3386 return ExprError();
3387 break;
3388 case Builtin::BI__builtin_complex:
3389 if (BuiltinComplex(TheCall))
3390 return ExprError();
3391 break;
3392 case Builtin::BI__builtin_classify_type:
3393 case Builtin::BI__builtin_constant_p: {
3394 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3395 return true;
3396 ExprResult Arg = DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
3397 if (Arg.isInvalid()) return true;
3398 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
3399 TheCall->setType(Context.IntTy);
3400 break;
3401 }
3402 case Builtin::BI__builtin_launder:
3403 return BuiltinLaunder(S&: *this, TheCall);
3404 case Builtin::BI__builtin_is_within_lifetime:
3405 return BuiltinIsWithinLifetime(S&: *this, TheCall);
3406 case Builtin::BI__builtin_trivially_relocate:
3407 return BuiltinTriviallyRelocate(S&: *this, TheCall);
3408 case Builtin::BI__builtin_clear_padding: {
3409 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3410 return ExprError();
3411
3412 const Expr *PtrArg = TheCall->getArg(Arg: 0);
3413 const QualType PtrArgType = PtrArg->getType();
3414 if (!PtrArgType->isPointerType()) {
3415 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
3416 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3417 << "pointer";
3418 return ExprError();
3419 }
3420 QualType PointeeType = PtrArgType->getPointeeType();
3421 if (PointeeType.isConstQualified()) {
3422 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_typecheck_assign_const)
3423 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3424 return ExprError();
3425 }
3426 if (RequireCompleteType(Loc: PtrArg->getBeginLoc(), T: PointeeType,
3427 DiagID: diag::err_typecheck_decl_incomplete_type))
3428 return ExprError();
3429
3430 // For non trivially copyable types, we try to match gcc's behaviour.
3431 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3432 // object, either a local variable or a function parameter passed by value
3433 auto IsAddrOfDeclExpr = [&]() {
3434 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Ctx: Context);
3435 const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: Inner);
3436 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3437 return false;
3438
3439 const Expr *Operand =
3440 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Ctx: Context);
3441 const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: Operand);
3442 if (!DeclRef)
3443 return false;
3444
3445 const auto *VarDecl = dyn_cast<::clang::VarDecl>(Val: DeclRef->getDecl());
3446 if (!VarDecl || VarDecl->getType()->isReferenceType())
3447 return false;
3448
3449 // matching GCC behaviour
3450 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3451 QualType VarQType = VarDecl->getType();
3452 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3453 Context.hasSameUnqualifiedType(T1: PointeeType, T2: VarQType);
3454 };
3455
3456 if (!PointeeType.isTriviallyCopyableType(Context) &&
3457 !PointeeType->isAtomicType() // _Atomic is not copyable
3458 && !IsAddrOfDeclExpr()) {
3459 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_clear_padding_needs_trivial_copy)
3460 << PtrArg->getType() << PtrArg->getSourceRange();
3461 return ExprError();
3462 }
3463
3464 if (auto *Record = PointeeType->getAsRecordDecl();
3465 Record && Record->hasFlexibleArrayMember()) {
3466 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_clear_padding_no_flexible_array)
3467 << PointeeType << PtrArg->getSourceRange();
3468 return ExprError();
3469 }
3470
3471 break;
3472 }
3473 case Builtin::BI__sync_fetch_and_add:
3474 case Builtin::BI__sync_fetch_and_add_1:
3475 case Builtin::BI__sync_fetch_and_add_2:
3476 case Builtin::BI__sync_fetch_and_add_4:
3477 case Builtin::BI__sync_fetch_and_add_8:
3478 case Builtin::BI__sync_fetch_and_add_16:
3479 case Builtin::BI__sync_fetch_and_sub:
3480 case Builtin::BI__sync_fetch_and_sub_1:
3481 case Builtin::BI__sync_fetch_and_sub_2:
3482 case Builtin::BI__sync_fetch_and_sub_4:
3483 case Builtin::BI__sync_fetch_and_sub_8:
3484 case Builtin::BI__sync_fetch_and_sub_16:
3485 case Builtin::BI__sync_fetch_and_or:
3486 case Builtin::BI__sync_fetch_and_or_1:
3487 case Builtin::BI__sync_fetch_and_or_2:
3488 case Builtin::BI__sync_fetch_and_or_4:
3489 case Builtin::BI__sync_fetch_and_or_8:
3490 case Builtin::BI__sync_fetch_and_or_16:
3491 case Builtin::BI__sync_fetch_and_and:
3492 case Builtin::BI__sync_fetch_and_and_1:
3493 case Builtin::BI__sync_fetch_and_and_2:
3494 case Builtin::BI__sync_fetch_and_and_4:
3495 case Builtin::BI__sync_fetch_and_and_8:
3496 case Builtin::BI__sync_fetch_and_and_16:
3497 case Builtin::BI__sync_fetch_and_xor:
3498 case Builtin::BI__sync_fetch_and_xor_1:
3499 case Builtin::BI__sync_fetch_and_xor_2:
3500 case Builtin::BI__sync_fetch_and_xor_4:
3501 case Builtin::BI__sync_fetch_and_xor_8:
3502 case Builtin::BI__sync_fetch_and_xor_16:
3503 case Builtin::BI__sync_fetch_and_nand:
3504 case Builtin::BI__sync_fetch_and_nand_1:
3505 case Builtin::BI__sync_fetch_and_nand_2:
3506 case Builtin::BI__sync_fetch_and_nand_4:
3507 case Builtin::BI__sync_fetch_and_nand_8:
3508 case Builtin::BI__sync_fetch_and_nand_16:
3509 case Builtin::BI__sync_add_and_fetch:
3510 case Builtin::BI__sync_add_and_fetch_1:
3511 case Builtin::BI__sync_add_and_fetch_2:
3512 case Builtin::BI__sync_add_and_fetch_4:
3513 case Builtin::BI__sync_add_and_fetch_8:
3514 case Builtin::BI__sync_add_and_fetch_16:
3515 case Builtin::BI__sync_sub_and_fetch:
3516 case Builtin::BI__sync_sub_and_fetch_1:
3517 case Builtin::BI__sync_sub_and_fetch_2:
3518 case Builtin::BI__sync_sub_and_fetch_4:
3519 case Builtin::BI__sync_sub_and_fetch_8:
3520 case Builtin::BI__sync_sub_and_fetch_16:
3521 case Builtin::BI__sync_and_and_fetch:
3522 case Builtin::BI__sync_and_and_fetch_1:
3523 case Builtin::BI__sync_and_and_fetch_2:
3524 case Builtin::BI__sync_and_and_fetch_4:
3525 case Builtin::BI__sync_and_and_fetch_8:
3526 case Builtin::BI__sync_and_and_fetch_16:
3527 case Builtin::BI__sync_or_and_fetch:
3528 case Builtin::BI__sync_or_and_fetch_1:
3529 case Builtin::BI__sync_or_and_fetch_2:
3530 case Builtin::BI__sync_or_and_fetch_4:
3531 case Builtin::BI__sync_or_and_fetch_8:
3532 case Builtin::BI__sync_or_and_fetch_16:
3533 case Builtin::BI__sync_xor_and_fetch:
3534 case Builtin::BI__sync_xor_and_fetch_1:
3535 case Builtin::BI__sync_xor_and_fetch_2:
3536 case Builtin::BI__sync_xor_and_fetch_4:
3537 case Builtin::BI__sync_xor_and_fetch_8:
3538 case Builtin::BI__sync_xor_and_fetch_16:
3539 case Builtin::BI__sync_nand_and_fetch:
3540 case Builtin::BI__sync_nand_and_fetch_1:
3541 case Builtin::BI__sync_nand_and_fetch_2:
3542 case Builtin::BI__sync_nand_and_fetch_4:
3543 case Builtin::BI__sync_nand_and_fetch_8:
3544 case Builtin::BI__sync_nand_and_fetch_16:
3545 case Builtin::BI__sync_val_compare_and_swap:
3546 case Builtin::BI__sync_val_compare_and_swap_1:
3547 case Builtin::BI__sync_val_compare_and_swap_2:
3548 case Builtin::BI__sync_val_compare_and_swap_4:
3549 case Builtin::BI__sync_val_compare_and_swap_8:
3550 case Builtin::BI__sync_val_compare_and_swap_16:
3551 case Builtin::BI__sync_bool_compare_and_swap:
3552 case Builtin::BI__sync_bool_compare_and_swap_1:
3553 case Builtin::BI__sync_bool_compare_and_swap_2:
3554 case Builtin::BI__sync_bool_compare_and_swap_4:
3555 case Builtin::BI__sync_bool_compare_and_swap_8:
3556 case Builtin::BI__sync_bool_compare_and_swap_16:
3557 case Builtin::BI__sync_lock_test_and_set:
3558 case Builtin::BI__sync_lock_test_and_set_1:
3559 case Builtin::BI__sync_lock_test_and_set_2:
3560 case Builtin::BI__sync_lock_test_and_set_4:
3561 case Builtin::BI__sync_lock_test_and_set_8:
3562 case Builtin::BI__sync_lock_test_and_set_16:
3563 case Builtin::BI__sync_lock_release:
3564 case Builtin::BI__sync_lock_release_1:
3565 case Builtin::BI__sync_lock_release_2:
3566 case Builtin::BI__sync_lock_release_4:
3567 case Builtin::BI__sync_lock_release_8:
3568 case Builtin::BI__sync_lock_release_16:
3569 case Builtin::BI__sync_swap:
3570 case Builtin::BI__sync_swap_1:
3571 case Builtin::BI__sync_swap_2:
3572 case Builtin::BI__sync_swap_4:
3573 case Builtin::BI__sync_swap_8:
3574 case Builtin::BI__sync_swap_16:
3575 return BuiltinAtomicOverloaded(TheCallResult);
3576 case Builtin::BI__sync_synchronize:
3577 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
3578 << TheCall->getCallee()->getSourceRange();
3579 break;
3580 case Builtin::BI__builtin_nontemporal_load:
3581 case Builtin::BI__builtin_nontemporal_store:
3582 return BuiltinNontemporalOverloaded(TheCallResult);
3583 case Builtin::BI__builtin_memcpy_inline: {
3584 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3585 // We warn about copying to or from `nullptr` pointers when `size` is
3586 // greater than 0. When `size` is value dependent we cannot evaluate its
3587 // value so we bail out.
3588 if (SizeOp->isValueDependent())
3589 break;
3590 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero()) {
3591 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3592 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 1), CallSiteLoc: TheCall->getExprLoc());
3593 }
3594 break;
3595 }
3596 case Builtin::BI__builtin_memset_inline: {
3597 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3598 // We warn about filling to `nullptr` pointers when `size` is greater than
3599 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3600 // out.
3601 if (SizeOp->isValueDependent())
3602 break;
3603 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero())
3604 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3605 break;
3606 }
3607#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3608 case Builtin::BI##ID: \
3609 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3610#include "clang/Basic/Builtins.inc"
3611 case Builtin::BI__annotation: {
3612 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3613 if (!TT.isOSWindows() && !TT.isUEFI()) {
3614 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
3615 << TheCall->getSourceRange();
3616 return ExprError();
3617 }
3618 if (BuiltinMSVCAnnotation(S&: *this, TheCall))
3619 return ExprError();
3620 break;
3621 }
3622 case Builtin::BI__builtin_annotation:
3623 if (BuiltinAnnotation(S&: *this, TheCall))
3624 return ExprError();
3625 break;
3626 case Builtin::BI__builtin_addressof:
3627 if (BuiltinAddressof(S&: *this, TheCall))
3628 return ExprError();
3629 break;
3630 case Builtin::BI__builtin_function_start:
3631 if (BuiltinFunctionStart(S&: *this, TheCall))
3632 return ExprError();
3633 break;
3634 case Builtin::BI__builtin_is_aligned:
3635 case Builtin::BI__builtin_align_up:
3636 case Builtin::BI__builtin_align_down:
3637 if (BuiltinAlignment(S&: *this, TheCall, ID: BuiltinID))
3638 return ExprError();
3639 break;
3640 case Builtin::BI__builtin_add_overflow:
3641 case Builtin::BI__builtin_sub_overflow:
3642 case Builtin::BI__builtin_mul_overflow:
3643 if (BuiltinOverflow(S&: *this, TheCall, BuiltinID))
3644 return ExprError();
3645 break;
3646 case Builtin::BI__builtin_operator_new:
3647 case Builtin::BI__builtin_operator_delete: {
3648 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3649 ExprResult Res =
3650 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3651 return Res;
3652 }
3653 case Builtin::BI__builtin_dump_struct:
3654 return BuiltinDumpStruct(S&: *this, TheCall);
3655 case Builtin::BI__builtin_expect_with_probability: {
3656 // We first want to ensure we are called with 3 arguments
3657 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
3658 return ExprError();
3659 // then check probability is constant float in range [0.0, 1.0]
3660 const Expr *ProbArg = TheCall->getArg(Arg: 2);
3661 SmallVector<PartialDiagnosticAt, 8> Notes;
3662 Expr::EvalResult Eval;
3663 Eval.Diag = &Notes;
3664 if ((!ProbArg->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context)) ||
3665 !Eval.Val.isFloat()) {
3666 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_not_constant_float)
3667 << ProbArg->getSourceRange();
3668 for (const PartialDiagnosticAt &PDiag : Notes)
3669 Diag(Loc: PDiag.first, PD: PDiag.second);
3670 return ExprError();
3671 }
3672 llvm::APFloat Probability = Eval.Val.getFloat();
3673 bool LoseInfo = false;
3674 Probability.convert(ToSemantics: llvm::APFloat::IEEEdouble(),
3675 RM: llvm::RoundingMode::Dynamic, losesInfo: &LoseInfo);
3676 if (!(Probability >= llvm::APFloat(0.0) &&
3677 Probability <= llvm::APFloat(1.0))) {
3678 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_out_of_range)
3679 << ProbArg->getSourceRange();
3680 return ExprError();
3681 }
3682 break;
3683 }
3684 case Builtin::BI__builtin_preserve_access_index:
3685 if (BuiltinPreserveAI(S&: *this, TheCall))
3686 return ExprError();
3687 break;
3688 case Builtin::BI__builtin_call_with_static_chain:
3689 if (BuiltinCallWithStaticChain(S&: *this, BuiltinCall: TheCall))
3690 return ExprError();
3691 break;
3692 case Builtin::BI__exception_code:
3693 case Builtin::BI_exception_code:
3694 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHExceptScope,
3695 DiagID: diag::err_seh___except_block))
3696 return ExprError();
3697 break;
3698 case Builtin::BI__exception_info:
3699 case Builtin::BI_exception_info:
3700 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHFilterScope,
3701 DiagID: diag::err_seh___except_filter))
3702 return ExprError();
3703 break;
3704 case Builtin::BI__GetExceptionInfo:
3705 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3706 return ExprError();
3707
3708 if (CheckCXXThrowOperand(
3709 ThrowLoc: TheCall->getBeginLoc(),
3710 ThrowTy: Context.getExceptionObjectType(T: FDecl->getParamDecl(i: 0)->getType()),
3711 E: TheCall))
3712 return ExprError();
3713
3714 TheCall->setType(Context.VoidPtrTy);
3715 break;
3716 case Builtin::BIaddressof:
3717 case Builtin::BI__addressof:
3718 case Builtin::BIforward:
3719 case Builtin::BIforward_like:
3720 case Builtin::BImove:
3721 case Builtin::BImove_if_noexcept:
3722 case Builtin::BIas_const: {
3723 // These are all expected to be of the form
3724 // T &/&&/* f(U &/&&)
3725 // where T and U only differ in qualification.
3726 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3727 return ExprError();
3728 QualType Param = FDecl->getParamDecl(i: 0)->getType();
3729 QualType Result = FDecl->getReturnType();
3730 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3731 BuiltinID == Builtin::BI__addressof;
3732 if (!(Param->isReferenceType() &&
3733 (ReturnsPointer ? Result->isAnyPointerType()
3734 : Result->isReferenceType()) &&
3735 Context.hasSameUnqualifiedType(T1: Param->getPointeeType(),
3736 T2: Result->getPointeeType()))) {
3737 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_move_forward_unsupported)
3738 << FDecl;
3739 return ExprError();
3740 }
3741 break;
3742 }
3743 case Builtin::BI__builtin_ptrauth_strip:
3744 return PointerAuthStrip(S&: *this, Call: TheCall);
3745 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3746 return PointerAuthBlendDiscriminator(S&: *this, Call: TheCall);
3747 case Builtin::BI__builtin_ptrauth_sign_constant:
3748 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3749 /*RequireConstant=*/true);
3750 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3751 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3752 /*RequireConstant=*/false);
3753 case Builtin::BI__builtin_ptrauth_auth:
3754 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Auth,
3755 /*RequireConstant=*/false);
3756 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3757 return PointerAuthSignGenericData(S&: *this, Call: TheCall);
3758 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3759 return PointerAuthAuthAndResign(S&: *this, Call: TheCall);
3760 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
3761 return PointerAuthAuthWithPCAndResign(S&: *this, Call: TheCall);
3762 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3763 return PointerAuthAuthLoadRelativeAndSign(S&: *this, Call: TheCall);
3764 case Builtin::BI__builtin_ptrauth_string_discriminator:
3765 return PointerAuthStringDiscriminator(S&: *this, Call: TheCall);
3766
3767 case Builtin::BI__builtin_get_vtable_pointer:
3768 return GetVTablePointer(S&: *this, Call: TheCall);
3769
3770 // OpenCL v2.0, s6.13.16 - Pipe functions
3771 case Builtin::BIread_pipe:
3772 case Builtin::BIwrite_pipe:
3773 // Since those two functions are declared with var args, we need a semantic
3774 // check for the argument.
3775 if (OpenCL().checkBuiltinRWPipe(Call: TheCall))
3776 return ExprError();
3777 break;
3778 case Builtin::BIreserve_read_pipe:
3779 case Builtin::BIreserve_write_pipe:
3780 case Builtin::BIwork_group_reserve_read_pipe:
3781 case Builtin::BIwork_group_reserve_write_pipe:
3782 if (OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3783 return ExprError();
3784 break;
3785 case Builtin::BIsub_group_reserve_read_pipe:
3786 case Builtin::BIsub_group_reserve_write_pipe:
3787 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3788 OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3789 return ExprError();
3790 break;
3791 case Builtin::BIcommit_read_pipe:
3792 case Builtin::BIcommit_write_pipe:
3793 case Builtin::BIwork_group_commit_read_pipe:
3794 case Builtin::BIwork_group_commit_write_pipe:
3795 if (OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3796 return ExprError();
3797 break;
3798 case Builtin::BIsub_group_commit_read_pipe:
3799 case Builtin::BIsub_group_commit_write_pipe:
3800 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3801 OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3802 return ExprError();
3803 break;
3804 case Builtin::BIget_pipe_num_packets:
3805 case Builtin::BIget_pipe_max_packets:
3806 if (OpenCL().checkBuiltinPipePackets(Call: TheCall))
3807 return ExprError();
3808 break;
3809 case Builtin::BIto_global:
3810 case Builtin::BIto_local:
3811 case Builtin::BIto_private:
3812 if (OpenCL().checkBuiltinToAddr(BuiltinID, Call: TheCall))
3813 return ExprError();
3814 break;
3815 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3816 case Builtin::BIenqueue_kernel:
3817 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3818 return ExprError();
3819 break;
3820 case Builtin::BIget_kernel_work_group_size:
3821 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3822 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3823 return ExprError();
3824 break;
3825 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3826 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3827 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3828 return ExprError();
3829 break;
3830 case Builtin::BI__builtin_os_log_format:
3831 Cleanup.setExprNeedsCleanups(true);
3832 [[fallthrough]];
3833 case Builtin::BI__builtin_os_log_format_buffer_size:
3834 if (BuiltinOSLogFormat(TheCall))
3835 return ExprError();
3836 break;
3837 case Builtin::BI__builtin_frame_address:
3838 case Builtin::BI__builtin_return_address: {
3839 if (BuiltinConstantArgRange(TheCall, ArgNum: 0, Low: 0, High: 0xFFFF))
3840 return ExprError();
3841
3842 // -Wframe-address warning if non-zero passed to builtin
3843 // return/frame address.
3844 Expr::EvalResult Result;
3845 if (!TheCall->getArg(Arg: 0)->isValueDependent() &&
3846 TheCall->getArg(Arg: 0)->EvaluateAsInt(Result, Ctx: getASTContext()) &&
3847 Result.Val.getInt() != 0)
3848 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_frame_address)
3849 << ((BuiltinID == Builtin::BI__builtin_return_address)
3850 ? "__builtin_return_address"
3851 : "__builtin_frame_address")
3852 << TheCall->getSourceRange();
3853 break;
3854 }
3855
3856 case Builtin::BI__builtin_nondeterministic_value: {
3857 if (BuiltinNonDeterministicValue(TheCall))
3858 return ExprError();
3859 break;
3860 }
3861
3862 // __builtin_elementwise_abs restricts the element type to signed integers or
3863 // floating point types only.
3864 case Builtin::BI__builtin_elementwise_abs:
3865 if (PrepareBuiltinElementwiseMathOneArgCall(
3866 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy))
3867 return ExprError();
3868 break;
3869
3870 // These builtins restrict the element type to floating point
3871 // types only.
3872 case Builtin::BI__builtin_elementwise_acos:
3873 case Builtin::BI__builtin_elementwise_asin:
3874 case Builtin::BI__builtin_elementwise_atan:
3875 case Builtin::BI__builtin_elementwise_ceil:
3876 case Builtin::BI__builtin_elementwise_cos:
3877 case Builtin::BI__builtin_elementwise_cosh:
3878 case Builtin::BI__builtin_elementwise_exp:
3879 case Builtin::BI__builtin_elementwise_exp2:
3880 case Builtin::BI__builtin_elementwise_exp10:
3881 case Builtin::BI__builtin_elementwise_floor:
3882 case Builtin::BI__builtin_elementwise_log:
3883 case Builtin::BI__builtin_elementwise_log2:
3884 case Builtin::BI__builtin_elementwise_log10:
3885 case Builtin::BI__builtin_elementwise_roundeven:
3886 case Builtin::BI__builtin_elementwise_round:
3887 case Builtin::BI__builtin_elementwise_rint:
3888 case Builtin::BI__builtin_elementwise_nearbyint:
3889 case Builtin::BI__builtin_elementwise_sin:
3890 case Builtin::BI__builtin_elementwise_sinh:
3891 case Builtin::BI__builtin_elementwise_sqrt:
3892 case Builtin::BI__builtin_elementwise_tan:
3893 case Builtin::BI__builtin_elementwise_tanh:
3894 case Builtin::BI__builtin_elementwise_trunc:
3895 case Builtin::BI__builtin_elementwise_canonicalize:
3896 if (PrepareBuiltinElementwiseMathOneArgCall(
3897 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3898 return ExprError();
3899 break;
3900 case Builtin::BI__builtin_elementwise_fma:
3901 if (BuiltinElementwiseTernaryMath(TheCall))
3902 return ExprError();
3903 break;
3904
3905 case Builtin::BI__builtin_elementwise_ldexp: {
3906 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3907 return ExprError();
3908
3909 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
3910 if (A.isInvalid())
3911 return ExprError();
3912 QualType TyA = A.get()->getType();
3913 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
3914 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1))
3915 return ExprError();
3916
3917 ExprResult Exp = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3918 if (Exp.isInvalid())
3919 return ExprError();
3920 QualType TyExp = Exp.get()->getType();
3921 if (checkMathBuiltinElementType(S&: *this, Loc: Exp.get()->getBeginLoc(), ArgTy: TyExp,
3922 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy,
3923 ArgOrdinal: 2))
3924 return ExprError();
3925
3926 // Check the two arguments are either scalars or vectors of equal length.
3927 const auto *Vec0 = TyA->getAs<VectorType>();
3928 const auto *Vec1 = TyExp->getAs<VectorType>();
3929 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3930 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3931 if (Arg0Length != Arg1Length) {
3932 Diag(Loc: Exp.get()->getBeginLoc(),
3933 DiagID: diag::err_typecheck_vector_lengths_not_equal)
3934 << TyA << TyExp << A.get()->getSourceRange()
3935 << Exp.get()->getSourceRange();
3936 return ExprError();
3937 }
3938
3939 TheCall->setArg(Arg: 0, ArgExpr: A.get());
3940 TheCall->setArg(Arg: 1, ArgExpr: Exp.get());
3941 TheCall->setType(TyA);
3942 break;
3943 }
3944
3945 // These builtins restrict the element type to floating point
3946 // types only, and take in two arguments.
3947 case Builtin::BI__builtin_elementwise_minnum:
3948 case Builtin::BI__builtin_elementwise_maxnum:
3949 case Builtin::BI__builtin_elementwise_minimum:
3950 case Builtin::BI__builtin_elementwise_maximum:
3951 case Builtin::BI__builtin_elementwise_minimumnum:
3952 case Builtin::BI__builtin_elementwise_maximumnum:
3953 case Builtin::BI__builtin_elementwise_atan2:
3954 case Builtin::BI__builtin_elementwise_fmod:
3955 case Builtin::BI__builtin_elementwise_pow:
3956 if (BuiltinElementwiseMath(TheCall,
3957 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3958 return ExprError();
3959 break;
3960 // These builtins restrict the element type to integer
3961 // types only.
3962 case Builtin::BI__builtin_elementwise_add_sat:
3963 case Builtin::BI__builtin_elementwise_sub_sat:
3964 case Builtin::BI__builtin_elementwise_clmul:
3965 case Builtin::BI__builtin_elementwise_pext:
3966 case Builtin::BI__builtin_elementwise_pdep:
3967 if (BuiltinElementwiseMath(TheCall,
3968 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3969 return ExprError();
3970 break;
3971 case Builtin::BI__builtin_elementwise_fshl:
3972 case Builtin::BI__builtin_elementwise_fshr:
3973 if (BuiltinElementwiseTernaryMath(
3974 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3975 return ExprError();
3976 break;
3977 case Builtin::BI__builtin_elementwise_min:
3978 case Builtin::BI__builtin_elementwise_max: {
3979 if (BuiltinElementwiseMath(TheCall))
3980 return ExprError();
3981 Expr *Arg0 = TheCall->getArg(Arg: 0);
3982 Expr *Arg1 = TheCall->getArg(Arg: 1);
3983 QualType Ty0 = Arg0->getType();
3984 QualType Ty1 = Arg1->getType();
3985 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3986 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3987 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3988 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3989 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3990 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin_no_suggestion)
3991 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID);
3992 break;
3993 }
3994 case Builtin::BI__builtin_elementwise_popcount:
3995 case Builtin::BI__builtin_elementwise_bitreverse:
3996 if (PrepareBuiltinElementwiseMathOneArgCall(
3997 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3998 return ExprError();
3999 break;
4000 case Builtin::BI__builtin_elementwise_copysign: {
4001 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
4002 return ExprError();
4003
4004 ExprResult Magnitude = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
4005 ExprResult Sign = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
4006 if (Magnitude.isInvalid() || Sign.isInvalid())
4007 return ExprError();
4008
4009 QualType MagnitudeTy = Magnitude.get()->getType();
4010 QualType SignTy = Sign.get()->getType();
4011 if (checkMathBuiltinElementType(
4012 S&: *this, Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), ArgTy: MagnitudeTy,
4013 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1) ||
4014 checkMathBuiltinElementType(
4015 S&: *this, Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), ArgTy: SignTy,
4016 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 2)) {
4017 return ExprError();
4018 }
4019
4020 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
4021 return Diag(Loc: Sign.get()->getBeginLoc(),
4022 DiagID: diag::err_typecheck_call_different_arg_types)
4023 << MagnitudeTy << SignTy;
4024 }
4025
4026 TheCall->setArg(Arg: 0, ArgExpr: Magnitude.get());
4027 TheCall->setArg(Arg: 1, ArgExpr: Sign.get());
4028 TheCall->setType(Magnitude.get()->getType());
4029 break;
4030 }
4031 case Builtin::BI__builtin_elementwise_clzg:
4032 case Builtin::BI__builtin_elementwise_ctzg:
4033 // These builtins can be unary or binary. Note for empty calls we call the
4034 // unary checker in order to not emit an error that says the function
4035 // expects 2 arguments, which would be misleading.
4036 if (TheCall->getNumArgs() <= 1) {
4037 if (PrepareBuiltinElementwiseMathOneArgCall(
4038 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
4039 return ExprError();
4040 } else if (BuiltinElementwiseMath(
4041 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
4042 return ExprError();
4043 break;
4044 case Builtin::BI__builtin_reduce_max:
4045 case Builtin::BI__builtin_reduce_min: {
4046 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4047 return ExprError();
4048
4049 const Expr *Arg = TheCall->getArg(Arg: 0);
4050 const auto *TyA = Arg->getType()->getAs<VectorType>();
4051
4052 QualType ElTy;
4053 if (TyA)
4054 ElTy = TyA->getElementType();
4055 else if (Arg->getType()->isSizelessVectorType())
4056 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
4057
4058 if (ElTy.isNull()) {
4059 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4060 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
4061 << Arg->getType();
4062 return ExprError();
4063 }
4064
4065 TheCall->setType(ElTy);
4066 break;
4067 }
4068 case Builtin::BI__builtin_reduce_maximum:
4069 case Builtin::BI__builtin_reduce_minimum: {
4070 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4071 return ExprError();
4072
4073 const Expr *Arg = TheCall->getArg(Arg: 0);
4074 const auto *TyA = Arg->getType()->getAs<VectorType>();
4075
4076 QualType ElTy;
4077 if (TyA)
4078 ElTy = TyA->getElementType();
4079 else if (Arg->getType()->isSizelessVectorType())
4080 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
4081
4082 if (ElTy.isNull() || !ElTy->isFloatingType()) {
4083 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4084 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4085 << Arg->getType();
4086 return ExprError();
4087 }
4088
4089 TheCall->setType(ElTy);
4090 break;
4091 }
4092
4093 // These builtins support vectors of integers only.
4094 // TODO: ADD/MUL should support floating-point types.
4095 case Builtin::BI__builtin_reduce_add:
4096 case Builtin::BI__builtin_reduce_mul:
4097 case Builtin::BI__builtin_reduce_xor:
4098 case Builtin::BI__builtin_reduce_or:
4099 case Builtin::BI__builtin_reduce_and: {
4100 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4101 return ExprError();
4102
4103 const Expr *Arg = TheCall->getArg(Arg: 0);
4104
4105 QualType ElTy = getVectorElementType(Context, VecTy: Arg->getType());
4106 if (ElTy.isNull() || !ElTy->isIntegerType()) {
4107 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4108 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
4109 << Arg->getType();
4110 return ExprError();
4111 }
4112
4113 TheCall->setType(ElTy);
4114 break;
4115 }
4116
4117 case Builtin::BI__builtin_reduce_assoc_fadd:
4118 case Builtin::BI__builtin_reduce_in_order_fadd: {
4119 // For in-order reductions require the user to specify the start value.
4120 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
4121 if (InOrder ? checkArgCount(Call: TheCall, DesiredArgCount: 2) : checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
4122 return ExprError();
4123
4124 ExprResult Vec = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
4125 if (Vec.isInvalid())
4126 return ExprError();
4127
4128 TheCall->setArg(Arg: 0, ArgExpr: Vec.get());
4129
4130 QualType ElTy = getVectorElementType(Context, VecTy: Vec.get()->getType());
4131 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
4132 Diag(Loc: Vec.get()->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4133 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4134 << Vec.get()->getType();
4135 return ExprError();
4136 }
4137
4138 if (TheCall->getNumArgs() == 2) {
4139 ExprResult StartValue = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
4140 if (StartValue.isInvalid())
4141 return ExprError();
4142
4143 if (!StartValue.get()->getType()->isRealFloatingType()) {
4144 Diag(Loc: StartValue.get()->getBeginLoc(),
4145 DiagID: diag::err_builtin_invalid_arg_type)
4146 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
4147 << StartValue.get()->getType();
4148 return ExprError();
4149 }
4150 TheCall->setArg(Arg: 1, ArgExpr: StartValue.get());
4151 }
4152
4153 TheCall->setType(ElTy);
4154 break;
4155 }
4156
4157 case Builtin::BI__builtin_matrix_transpose:
4158 return BuiltinMatrixTranspose(TheCall, CallResult: TheCallResult);
4159
4160 case Builtin::BI__builtin_matrix_column_major_load:
4161 return BuiltinMatrixColumnMajorLoad(TheCall, CallResult: TheCallResult);
4162
4163 case Builtin::BI__builtin_matrix_column_major_store:
4164 return BuiltinMatrixColumnMajorStore(TheCall, CallResult: TheCallResult);
4165
4166 case Builtin::BI__builtin_verbose_trap:
4167 if (!checkBuiltinVerboseTrap(Call: TheCall, S&: *this))
4168 return ExprError();
4169 break;
4170
4171 case Builtin::BI__builtin_get_device_side_mangled_name: {
4172 auto Check = [](CallExpr *TheCall) {
4173 if (TheCall->getNumArgs() != 1)
4174 return false;
4175 auto *DRE = dyn_cast<DeclRefExpr>(Val: TheCall->getArg(Arg: 0)->IgnoreImpCasts());
4176 if (!DRE)
4177 return false;
4178 auto *D = DRE->getDecl();
4179 if (!isa<FunctionDecl>(Val: D) && !isa<VarDecl>(Val: D))
4180 return false;
4181 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4182 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
4183 };
4184 if (!Check(TheCall)) {
4185 Diag(Loc: TheCall->getBeginLoc(),
4186 DiagID: diag::err_hip_invalid_args_builtin_mangled_name);
4187 return ExprError();
4188 }
4189 break;
4190 }
4191 case Builtin::BI__builtin_bswapg:
4192 if (BuiltinBswapg(S&: *this, TheCall))
4193 return ExprError();
4194 break;
4195 case Builtin::BI__builtin_bitreverseg:
4196 if (BuiltinBitreverseg(S&: *this, TheCall))
4197 return ExprError();
4198 break;
4199 case Builtin::BI__builtin_popcountg:
4200 if (BuiltinPopcountg(S&: *this, TheCall))
4201 return ExprError();
4202 break;
4203 case Builtin::BI__builtin_clzg:
4204 case Builtin::BI__builtin_ctzg:
4205 if (BuiltinCountZeroBitsGeneric(S&: *this, TheCall))
4206 return ExprError();
4207 break;
4208
4209 case Builtin::BI__builtin_stdc_rotate_left:
4210 case Builtin::BI__builtin_stdc_rotate_right:
4211 if (BuiltinRotateGeneric(S&: *this, TheCall))
4212 return ExprError();
4213 break;
4214
4215 case Builtin::BI__builtin_stdc_memreverse8:
4216 case Builtin::BIstdc_memreverse8:
4217 case Builtin::BIstdc_memreverse8u8:
4218 case Builtin::BIstdc_memreverse8u16:
4219 case Builtin::BIstdc_memreverse8u32:
4220 case Builtin::BIstdc_memreverse8u64:
4221 if (Context.getTargetInfo().getCharWidth() != 8) {
4222 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_requires_char_bit_8)
4223 << TheCall->getDirectCallee()->getName();
4224 return ExprError();
4225 }
4226 break;
4227
4228 case Builtin::BI__builtin_stdc_bit_floor:
4229 case Builtin::BI__builtin_stdc_bit_ceil:
4230 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: QualType()))
4231 return ExprError();
4232 break;
4233 case Builtin::BI__builtin_stdc_has_single_bit:
4234 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: Context.BoolTy))
4235 return ExprError();
4236 break;
4237 case Builtin::BI__builtin_stdc_leading_zeros:
4238 case Builtin::BI__builtin_stdc_leading_ones:
4239 case Builtin::BI__builtin_stdc_trailing_zeros:
4240 case Builtin::BI__builtin_stdc_trailing_ones:
4241 case Builtin::BI__builtin_stdc_first_leading_zero:
4242 case Builtin::BI__builtin_stdc_first_leading_one:
4243 case Builtin::BI__builtin_stdc_first_trailing_zero:
4244 case Builtin::BI__builtin_stdc_first_trailing_one:
4245 case Builtin::BI__builtin_stdc_count_zeros:
4246 case Builtin::BI__builtin_stdc_count_ones:
4247 case Builtin::BI__builtin_stdc_bit_width:
4248 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: Context.UnsignedIntTy))
4249 return ExprError();
4250 break;
4251
4252 case Builtin::BI__builtin_allow_runtime_check: {
4253 Expr *Arg = TheCall->getArg(Arg: 0);
4254 // Check if the argument is a string literal.
4255 if (!isa<StringLiteral>(Val: Arg->IgnoreParenImpCasts())) {
4256 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
4257 << Arg->getSourceRange();
4258 return ExprError();
4259 }
4260 break;
4261 }
4262
4263 case Builtin::BI__builtin_allow_sanitize_check: {
4264 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
4265 return ExprError();
4266
4267 Expr *Arg = TheCall->getArg(Arg: 0);
4268 // Check if the argument is a string literal.
4269 const StringLiteral *SanitizerName =
4270 dyn_cast<StringLiteral>(Val: Arg->IgnoreParenImpCasts());
4271 if (!SanitizerName) {
4272 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
4273 << Arg->getSourceRange();
4274 return ExprError();
4275 }
4276 // Validate the sanitizer name.
4277 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
4278 .Cases(CaseStrings: {"address", "thread", "memory", "hwaddress",
4279 "kernel-address", "kernel-memory", "kernel-hwaddress"},
4280 Value: true)
4281 .Default(Value: false)) {
4282 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_builtin_argument)
4283 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
4284 << Arg->getSourceRange();
4285 return ExprError();
4286 }
4287 break;
4288 }
4289 case Builtin::BI__builtin_counted_by_ref:
4290 if (BuiltinCountedByRef(TheCall))
4291 return ExprError();
4292 break;
4293 }
4294
4295 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4296 return ExprError();
4297
4298 // Since the target specific builtins for each arch overlap, only check those
4299 // of the arch we are compiling for.
4300 if (Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID)) {
4301 if (Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID)) {
4302 assert(Context.getAuxTargetInfo() &&
4303 "Aux Target Builtin, but not an aux target?");
4304
4305 if (CheckTSBuiltinFunctionCall(
4306 TI: *Context.getAuxTargetInfo(),
4307 BuiltinID: Context.BuiltinInfo.getAuxBuiltinID(ID: BuiltinID), TheCall))
4308 return ExprError();
4309 } else {
4310 if (CheckTSBuiltinFunctionCall(TI: Context.getTargetInfo(), BuiltinID,
4311 TheCall))
4312 return ExprError();
4313 }
4314 }
4315
4316 return TheCallResult;
4317}
4318
4319bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4320 llvm::APSInt Result;
4321 // We can't check the value of a dependent argument.
4322 Expr *Arg = TheCall->getArg(Arg: ArgNum);
4323 if (Arg->isTypeDependent() || Arg->isValueDependent())
4324 return false;
4325
4326 // Check constant-ness first.
4327 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4328 return true;
4329
4330 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4331 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4332 return false;
4333
4334 return Diag(Loc: TheCall->getBeginLoc(),
4335 DiagID: diag::err_argument_not_contiguous_bit_field)
4336 << ArgNum << Arg->getSourceRange();
4337}
4338
4339bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4340 unsigned FirstArg, FormatStringInfo *FSI) {
4341 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4342 bool IsVariadic = false;
4343 if (const FunctionType *FnTy = D->getFunctionType())
4344 IsVariadic = cast<FunctionProtoType>(Val: FnTy)->isVariadic();
4345 else if (const auto *BD = dyn_cast<BlockDecl>(Val: D))
4346 IsVariadic = BD->isVariadic();
4347 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D))
4348 IsVariadic = OMD->isVariadic();
4349
4350 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4351 IsVariadic, FSI);
4352}
4353
4354bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4355 bool HasImplicitThisParam, bool IsVariadic,
4356 FormatStringInfo *FSI) {
4357 if (FirstArg == 0)
4358 FSI->ArgPassingKind = FAPK_VAList;
4359 else if (IsVariadic)
4360 FSI->ArgPassingKind = FAPK_Variadic;
4361 else
4362 FSI->ArgPassingKind = FAPK_Fixed;
4363 FSI->FormatIdx = FormatIdx - 1;
4364 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4365
4366 // The way the format attribute works in GCC, the implicit this argument
4367 // of member functions is counted. However, it doesn't appear in our own
4368 // lists, so decrement format_idx in that case.
4369 if (HasImplicitThisParam) {
4370 if(FSI->FormatIdx == 0)
4371 return false;
4372 --FSI->FormatIdx;
4373 if (FSI->FirstDataArg != 0)
4374 --FSI->FirstDataArg;
4375 }
4376 return true;
4377}
4378
4379/// Checks if a the given expression evaluates to null.
4380///
4381/// Returns true if the value evaluates to null.
4382static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4383 // Treat (smart) pointers constructed from nullptr as null, whether we can
4384 // const-evaluate them or not.
4385 // This must happen first: the smart pointer expr might have _Nonnull type!
4386 if (isa<CXXNullPtrLiteralExpr>(
4387 Val: IgnoreExprNodes(E: Expr, Fns&: IgnoreImplicitAsWrittenSingleStep,
4388 Fns&: IgnoreElidableImplicitConstructorSingleStep)))
4389 return true;
4390
4391 // If the expression has non-null type, it doesn't evaluate to null.
4392 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4393 if (*nullability == NullabilityKind::NonNull)
4394 return false;
4395 }
4396
4397 // As a special case, transparent unions initialized with zero are
4398 // considered null for the purposes of the nonnull attribute.
4399 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4400 UT &&
4401 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4402 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Val: Expr))
4403 if (const auto *ILE = dyn_cast<InitListExpr>(Val: CLE->getInitializer()))
4404 Expr = ILE->getInit(Init: 0);
4405 }
4406
4407 bool Result;
4408 return (!Expr->isValueDependent() &&
4409 Expr->EvaluateAsBooleanCondition(Result, Ctx: S.Context) &&
4410 !Result);
4411}
4412
4413static void CheckNonNullArgument(Sema &S,
4414 const Expr *ArgExpr,
4415 SourceLocation CallSiteLoc) {
4416 if (CheckNonNullExpr(S, Expr: ArgExpr))
4417 S.DiagRuntimeBehavior(Loc: CallSiteLoc, Statement: ArgExpr,
4418 PD: S.PDiag(DiagID: diag::warn_null_arg)
4419 << ArgExpr->getSourceRange());
4420}
4421
4422/// Determine whether the given type has a non-null nullability annotation.
4423static bool isNonNullType(QualType type) {
4424 if (auto nullability = type->getNullability())
4425 return *nullability == NullabilityKind::NonNull;
4426
4427 return false;
4428}
4429
4430static void CheckNonNullArguments(Sema &S,
4431 const NamedDecl *FDecl,
4432 const FunctionProtoType *Proto,
4433 ArrayRef<const Expr *> Args,
4434 SourceLocation CallSiteLoc) {
4435 assert((FDecl || Proto) && "Need a function declaration or prototype");
4436
4437 // Already checked by constant evaluator.
4438 if (S.isConstantEvaluatedContext())
4439 return;
4440 // Check the attributes attached to the method/function itself.
4441 llvm::SmallBitVector NonNullArgs;
4442 if (FDecl) {
4443 // Handle the nonnull attribute on the function/method declaration itself.
4444 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4445 if (!NonNull->args_size()) {
4446 // Easy case: all pointer arguments are nonnull.
4447 for (const auto *Arg : Args)
4448 if (S.isValidPointerAttrType(T: Arg->getType()))
4449 CheckNonNullArgument(S, ArgExpr: Arg, CallSiteLoc);
4450 return;
4451 }
4452
4453 for (const ParamIdx &Idx : NonNull->args()) {
4454 unsigned IdxAST = Idx.getASTIndex();
4455 if (IdxAST >= Args.size())
4456 continue;
4457 if (NonNullArgs.empty())
4458 NonNullArgs.resize(N: Args.size());
4459 NonNullArgs.set(IdxAST);
4460 }
4461 }
4462 }
4463
4464 if (FDecl && (isa<FunctionDecl>(Val: FDecl) || isa<ObjCMethodDecl>(Val: FDecl))) {
4465 // Handle the nonnull attribute on the parameters of the
4466 // function/method.
4467 ArrayRef<ParmVarDecl*> parms;
4468 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: FDecl))
4469 parms = FD->parameters();
4470 else
4471 parms = cast<ObjCMethodDecl>(Val: FDecl)->parameters();
4472
4473 unsigned ParamIndex = 0;
4474 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4475 I != E; ++I, ++ParamIndex) {
4476 const ParmVarDecl *PVD = *I;
4477 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(type: PVD->getType())) {
4478 if (NonNullArgs.empty())
4479 NonNullArgs.resize(N: Args.size());
4480
4481 NonNullArgs.set(ParamIndex);
4482 }
4483 }
4484 } else {
4485 // If we have a non-function, non-method declaration but no
4486 // function prototype, try to dig out the function prototype.
4487 if (!Proto) {
4488 if (const ValueDecl *VD = dyn_cast<ValueDecl>(Val: FDecl)) {
4489 QualType type = VD->getType().getNonReferenceType();
4490 if (auto pointerType = type->getAs<PointerType>())
4491 type = pointerType->getPointeeType();
4492 else if (auto blockType = type->getAs<BlockPointerType>())
4493 type = blockType->getPointeeType();
4494 // FIXME: data member pointers?
4495
4496 // Dig out the function prototype, if there is one.
4497 Proto = type->getAs<FunctionProtoType>();
4498 }
4499 }
4500
4501 // Fill in non-null argument information from the nullability
4502 // information on the parameter types (if we have them).
4503 if (Proto) {
4504 unsigned Index = 0;
4505 for (auto paramType : Proto->getParamTypes()) {
4506 if (isNonNullType(type: paramType)) {
4507 if (NonNullArgs.empty())
4508 NonNullArgs.resize(N: Args.size());
4509
4510 NonNullArgs.set(Index);
4511 }
4512
4513 ++Index;
4514 }
4515 }
4516 }
4517
4518 // Check for non-null arguments.
4519 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4520 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4521 if (NonNullArgs[ArgIndex])
4522 CheckNonNullArgument(S, ArgExpr: Args[ArgIndex], CallSiteLoc: Args[ArgIndex]->getExprLoc());
4523 }
4524}
4525
4526void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4527 StringRef ParamName, QualType ArgTy,
4528 QualType ParamTy) {
4529
4530 // If a function accepts a pointer or reference type
4531 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4532 return;
4533
4534 // If the parameter is a pointer type, get the pointee type for the
4535 // argument too. If the parameter is a reference type, don't try to get
4536 // the pointee type for the argument.
4537 if (ParamTy->isPointerType())
4538 ArgTy = ArgTy->getPointeeType();
4539
4540 // Remove reference or pointer
4541 ParamTy = ParamTy->getPointeeType();
4542
4543 // Find expected alignment, and the actual alignment of the passed object.
4544 // getTypeAlignInChars requires complete types
4545 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4546 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4547 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4548 return;
4549
4550 CharUnits ParamAlign = Context.getTypeAlignInChars(T: ParamTy);
4551 CharUnits ArgAlign = Context.getTypeAlignInChars(T: ArgTy);
4552
4553 // If the argument is less aligned than the parameter, there is a
4554 // potential alignment issue.
4555 if (ArgAlign < ParamAlign)
4556 Diag(Loc, DiagID: diag::warn_param_mismatched_alignment)
4557 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4558 << ParamName << (FDecl != nullptr) << FDecl;
4559}
4560
4561void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4562 const Expr *ThisArg,
4563 ArrayRef<const Expr *> Args) {
4564 if (!FD || Args.empty())
4565 return;
4566 auto GetArgAt = [&](int Idx) -> const Expr * {
4567 if (Idx == LifetimeCaptureByAttr::Global ||
4568 Idx == LifetimeCaptureByAttr::Unknown)
4569 return nullptr;
4570 if (IsMemberFunction && Idx == 0)
4571 return ThisArg;
4572 return Args[Idx - IsMemberFunction];
4573 };
4574 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4575 unsigned ArgIdx) {
4576 if (!Attr)
4577 return;
4578
4579 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4580 for (int CapturingParamIdx : Attr->params()) {
4581 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4582 continue;
4583 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4584 // initialization codepath.
4585 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4586 isa<CXXConstructorDecl>(Val: FD))
4587 continue;
4588 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4589 CapturingEntity CE{.Entity: Capturing};
4590 // Ensure that 'Captured' outlives the 'Capturing' entity.
4591 checkCaptureByLifetime(SemaRef&: *this, Entity: CE, Init: Captured);
4592 }
4593 };
4594 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4595 for (const auto *A :
4596 FD->getParamDecl(i: I)->specific_attrs<LifetimeCaptureByAttr>())
4597 HandleCaptureByAttr(A, I + IsMemberFunction);
4598 // Check when the implicit object param is captured.
4599 if (IsMemberFunction) {
4600 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4601 if (!TSI)
4602 return;
4603 AttributedTypeLoc ATL;
4604 for (TypeLoc TL = TSI->getTypeLoc();
4605 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4606 TL = ATL.getModifiedLoc())
4607 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4608 }
4609}
4610
4611void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4612 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4613 bool IsMemberFunction, SourceLocation Loc,
4614 SourceRange Range, VariadicCallType CallType) {
4615
4616 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4617 llvm::any_of(Range&: Args, P: [](const Expr *E) {
4618 return E && E->isInstantiationDependent();
4619 }))
4620 return;
4621
4622 // Printf and scanf checking.
4623 llvm::SmallBitVector CheckedVarArgs;
4624 if (FDecl) {
4625 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4626 // Only create vector if there are format attributes.
4627 CheckedVarArgs.resize(N: Args.size());
4628 CheckFormatString(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4629 CheckedVarArgs);
4630 }
4631
4632 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4633 CheckedVarArgs.resize(N: Args.size());
4634 CheckFormatArguments(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4635 CheckedVarArgs);
4636 }
4637 }
4638
4639 // Refuse POD arguments that weren't caught by the format string
4640 // checks above.
4641 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: FDecl);
4642 if (CallType != VariadicCallType::DoesNotApply &&
4643 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4644 unsigned NumParams = Proto ? Proto->getNumParams()
4645 : isa_and_nonnull<FunctionDecl>(Val: FDecl)
4646 ? cast<FunctionDecl>(Val: FDecl)->getNumParams()
4647 : isa_and_nonnull<ObjCMethodDecl>(Val: FDecl)
4648 ? cast<ObjCMethodDecl>(Val: FDecl)->param_size()
4649 : 0;
4650
4651 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4652 // Args[ArgIdx] can be null in malformed code.
4653 if (const Expr *Arg = Args[ArgIdx]) {
4654 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4655 checkVariadicArgument(E: Arg, CT: CallType);
4656 }
4657 }
4658 }
4659 if (FD)
4660 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4661 if (FDecl || Proto) {
4662 CheckNonNullArguments(S&: *this, FDecl, Proto, Args, CallSiteLoc: Loc);
4663
4664 // Type safety checking.
4665 if (FDecl) {
4666 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4667 CheckArgumentWithTypeTag(Attr: I, ExprArgs: Args, CallSiteLoc: Loc);
4668 }
4669 }
4670
4671 // Check that passed arguments match the alignment of original arguments.
4672 // Try to get the missing prototype from the declaration.
4673 if (!Proto && FDecl) {
4674 const auto *FT = FDecl->getFunctionType();
4675 if (isa_and_nonnull<FunctionProtoType>(Val: FT))
4676 Proto = cast<FunctionProtoType>(Val: FDecl->getFunctionType());
4677 }
4678 if (Proto) {
4679 // For variadic functions, we may have more args than parameters.
4680 // For some K&R functions, we may have less args than parameters.
4681 const auto N = std::min<unsigned>(a: Proto->getNumParams(), b: Args.size());
4682 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4683 bool IsScalableArg = false;
4684 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4685 // Args[ArgIdx] can be null in malformed code.
4686 if (const Expr *Arg = Args[ArgIdx]) {
4687 if (Arg->containsErrors())
4688 continue;
4689
4690 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4691 FDecl->hasLinkage() &&
4692 FDecl->getFormalLinkage() != Linkage::Internal &&
4693 CallType == VariadicCallType::DoesNotApply)
4694 PPC().checkAIXMemberAlignment(Loc: (Arg->getExprLoc()), Arg);
4695
4696 QualType ParamTy = Proto->getParamType(i: ArgIdx);
4697 if (ParamTy->isSizelessVectorType())
4698 IsScalableArg = true;
4699 QualType ArgTy = Arg->getType();
4700 CheckArgAlignment(Loc: Arg->getExprLoc(), FDecl, ParamName: std::to_string(val: ArgIdx + 1),
4701 ArgTy, ParamTy);
4702 }
4703 }
4704
4705 // If the callee has an AArch64 SME attribute to indicate that it is an
4706 // __arm_streaming function, then the caller requires SME to be available.
4707 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
4708 if (ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask) {
4709 if (auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext)) {
4710 llvm::StringMap<bool> CallerFeatureMap;
4711 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, CallerFD);
4712 if (!CallerFeatureMap.contains(Key: "sme"))
4713 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4714 } else if (!Context.getTargetInfo().hasFeature(Feature: "sme")) {
4715 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4716 }
4717 }
4718
4719 // If the call requires a streaming-mode change and has scalable vector
4720 // arguments or return values, then warn the user that the streaming and
4721 // non-streaming vector lengths may be different.
4722 // When both streaming and non-streaming vector lengths are defined and
4723 // mismatched, produce an error.
4724 const auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext);
4725 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4726 (IsScalableArg || IsScalableRet)) {
4727 bool IsCalleeStreaming =
4728 ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
4729 bool IsCalleeStreamingCompatible =
4730 ExtInfo.AArch64SMEAttributes &
4731 FunctionType::SME_PStateSMCompatibleMask;
4732 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(FD: CallerFD);
4733 if (!IsCalleeStreamingCompatible &&
4734 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4735 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4736 const LangOptions &LO = getLangOpts();
4737 unsigned VL = LO.VScaleMin * 128;
4738 unsigned SVL = LO.VScaleStreamingMin * 128;
4739 bool IsVLMismatch = VL && SVL && VL != SVL;
4740
4741 auto EmitDiag = [&](bool IsArg) {
4742 if (IsVLMismatch) {
4743 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4744 // Emit warning for streaming-compatible callers
4745 Diag(Loc, DiagID: diag::warn_sme_streaming_compatible_vl_mismatch)
4746 << IsArg << IsCalleeStreaming << SVL << VL;
4747 else
4748 // Emit error otherwise
4749 Diag(Loc, DiagID: diag::err_sme_streaming_transition_vl_mismatch)
4750 << IsArg << SVL << VL;
4751 } else
4752 Diag(Loc, DiagID: diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4753 << IsArg;
4754 };
4755
4756 if (IsScalableArg)
4757 EmitDiag(true);
4758 if (IsScalableRet)
4759 EmitDiag(false);
4760 }
4761 }
4762
4763 FunctionType::ArmStateValue CalleeArmZAState =
4764 FunctionType::getArmZAState(AttrBits: ExtInfo.AArch64SMEAttributes);
4765 FunctionType::ArmStateValue CalleeArmZT0State =
4766 FunctionType::getArmZT0State(AttrBits: ExtInfo.AArch64SMEAttributes);
4767 if (CalleeArmZAState != FunctionType::ARM_None ||
4768 CalleeArmZT0State != FunctionType::ARM_None) {
4769 bool CallerHasZAState = false;
4770 bool CallerHasZT0State = false;
4771 if (CallerFD) {
4772 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4773 if (Attr && Attr->isNewZA())
4774 CallerHasZAState = true;
4775 if (Attr && Attr->isNewZT0())
4776 CallerHasZT0State = true;
4777 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4778 CallerHasZAState |=
4779 FunctionType::getArmZAState(
4780 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4781 FunctionType::ARM_None;
4782 CallerHasZT0State |=
4783 FunctionType::getArmZT0State(
4784 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4785 FunctionType::ARM_None;
4786 }
4787 }
4788
4789 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4790 Diag(Loc, DiagID: diag::err_sme_za_call_no_za_state);
4791
4792 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4793 Diag(Loc, DiagID: diag::err_sme_zt0_call_no_zt0_state);
4794
4795 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4796 CalleeArmZT0State != FunctionType::ARM_None) {
4797 Diag(Loc, DiagID: diag::err_sme_unimplemented_za_save_restore);
4798 Diag(Loc, DiagID: diag::note_sme_use_preserves_za);
4799 }
4800 }
4801 }
4802
4803 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4804 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4805 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4806 if (!Arg->isValueDependent()) {
4807 Expr::EvalResult Align;
4808 if (Arg->EvaluateAsInt(Result&: Align, Ctx: Context)) {
4809 const llvm::APSInt &I = Align.Val.getInt();
4810 if (!I.isPowerOf2())
4811 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_alignment_not_power_of_two)
4812 << Arg->getSourceRange();
4813
4814 if (I > Sema::MaximumAlignment)
4815 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_assume_aligned_too_great)
4816 << Arg->getSourceRange() << Sema::MaximumAlignment;
4817 }
4818 }
4819 }
4820
4821 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4822 !isUnevaluatedContext())
4823 SYCL().DiagIfDeviceCode(Loc, DiagID: diag::err_variadic_device_fn)
4824 << diag::OffloadLang::SYCL;
4825
4826 if (FD)
4827 diagnoseArgDependentDiagnoseIfAttrs(Function: FD, ThisArg, Args, Loc);
4828}
4829
4830void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4831 if (TemplateDecl *Decl =
4832 AutoT->getTypeConstraintConcept().getAsTemplateDecl()) {
4833 DiagnoseUseOfDecl(D: Decl, Locs: Loc);
4834 }
4835}
4836
4837void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4838 ArrayRef<const Expr *> Args,
4839 const FunctionProtoType *Proto,
4840 SourceLocation Loc) {
4841 VariadicCallType CallType = Proto->isVariadic()
4842 ? VariadicCallType::Constructor
4843 : VariadicCallType::DoesNotApply;
4844
4845 auto *Ctor = cast<CXXConstructorDecl>(Val: FDecl);
4846 CheckArgAlignment(
4847 Loc, FDecl, ParamName: "'this'", ArgTy: Context.getPointerType(T: ThisType),
4848 ParamTy: Context.getPointerType(T: Ctor->getFunctionObjectParameterType()));
4849
4850 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4851 Loc, Range: SourceRange(), CallType);
4852}
4853
4854bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4855 const FunctionProtoType *Proto) {
4856 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(Val: TheCall) &&
4857 isa<CXXMethodDecl>(Val: FDecl);
4858 bool IsMemberFunction = isa<CXXMemberCallExpr>(Val: TheCall) ||
4859 IsMemberOperatorCall;
4860 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4861 Fn: TheCall->getCallee());
4862 Expr** Args = TheCall->getArgs();
4863 unsigned NumArgs = TheCall->getNumArgs();
4864
4865 Expr *ImplicitThis = nullptr;
4866 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4867 // If this is a call to a member operator, hide the first
4868 // argument from checkCall.
4869 // FIXME: Our choice of AST representation here is less than ideal.
4870 ImplicitThis = Args[0];
4871 ++Args;
4872 --NumArgs;
4873 } else if (IsMemberFunction && !FDecl->isStatic() &&
4874 !FDecl->hasCXXExplicitFunctionObjectParameter())
4875 ImplicitThis =
4876 cast<CXXMemberCallExpr>(Val: TheCall)->getImplicitObjectArgument();
4877
4878 if (ImplicitThis) {
4879 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4880 // used.
4881 QualType ThisType = ImplicitThis->getType();
4882 if (!ThisType->isPointerType()) {
4883 assert(!ThisType->isReferenceType());
4884 ThisType = Context.getPointerType(T: ThisType);
4885 }
4886
4887 QualType ThisTypeFromDecl = Context.getPointerType(
4888 T: cast<CXXMethodDecl>(Val: FDecl)->getFunctionObjectParameterType());
4889
4890 CheckArgAlignment(Loc: TheCall->getRParenLoc(), FDecl, ParamName: "'this'", ArgTy: ThisType,
4891 ParamTy: ThisTypeFromDecl);
4892 }
4893
4894 checkCall(FDecl, Proto, ThisArg: ImplicitThis, Args: llvm::ArrayRef(Args, NumArgs),
4895 IsMemberFunction, Loc: TheCall->getRParenLoc(),
4896 Range: TheCall->getCallee()->getSourceRange(), CallType);
4897
4898 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4899 // None of the checks below are needed for functions that don't have
4900 // simple names (e.g., C++ conversion functions).
4901 if (!FnInfo)
4902 return false;
4903
4904 // Enforce TCB except for builtin calls, which are always allowed.
4905 if (FDecl->getBuiltinID() == 0)
4906 CheckTCBEnforcement(CallExprLoc: TheCall->getExprLoc(), Callee: FDecl);
4907
4908 CheckAbsoluteValueFunction(Call: TheCall, FDecl);
4909 CheckMaxUnsignedZero(Call: TheCall, FDecl);
4910 CheckInfNaNFunction(Call: TheCall, FDecl);
4911
4912 if (getLangOpts().ObjC)
4913 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4914
4915 unsigned CMId = FDecl->getMemoryFunctionKind();
4916
4917 // Handle memory setting and copying functions.
4918 switch (CMId) {
4919 case 0:
4920 return false;
4921 case Builtin::BIstrlcpy: // fallthrough
4922 case Builtin::BIstrlcat:
4923 CheckStrlcpycatArguments(Call: TheCall, FnName: FnInfo);
4924 break;
4925 case Builtin::BIstrncat:
4926 CheckStrncatArguments(Call: TheCall, FnName: FnInfo);
4927 break;
4928 case Builtin::BIfree:
4929 CheckFreeArguments(E: TheCall);
4930 break;
4931 default:
4932 CheckMemaccessArguments(Call: TheCall, BId: CMId, FnName: FnInfo);
4933 }
4934
4935 return false;
4936}
4937
4938bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4939 const FunctionProtoType *Proto) {
4940 QualType Ty;
4941 if (const auto *V = dyn_cast<VarDecl>(Val: NDecl))
4942 Ty = V->getType().getNonReferenceType();
4943 else if (const auto *F = dyn_cast<FieldDecl>(Val: NDecl))
4944 Ty = F->getType().getNonReferenceType();
4945 else
4946 return false;
4947
4948 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4949 !Ty->isFunctionProtoType())
4950 return false;
4951
4952 VariadicCallType CallType;
4953 if (!Proto || !Proto->isVariadic()) {
4954 CallType = VariadicCallType::DoesNotApply;
4955 } else if (Ty->isBlockPointerType()) {
4956 CallType = VariadicCallType::Block;
4957 } else { // Ty->isFunctionPointerType()
4958 CallType = VariadicCallType::Function;
4959 }
4960
4961 checkCall(FDecl: NDecl, Proto, /*ThisArg=*/nullptr,
4962 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4963 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4964 Range: TheCall->getCallee()->getSourceRange(), CallType);
4965
4966 return false;
4967}
4968
4969bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4970 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4971 Fn: TheCall->getCallee());
4972 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4973 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4974 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4975 Range: TheCall->getCallee()->getSourceRange(), CallType);
4976
4977 return false;
4978}
4979
4980static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4981 if (!llvm::isValidAtomicOrderingCABI(I: Ordering))
4982 return false;
4983
4984 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4985 switch (Op) {
4986 case AtomicExpr::AO__c11_atomic_init:
4987 case AtomicExpr::AO__opencl_atomic_init:
4988 llvm_unreachable("There is no ordering argument for an init");
4989
4990 case AtomicExpr::AO__c11_atomic_load:
4991 case AtomicExpr::AO__opencl_atomic_load:
4992 case AtomicExpr::AO__hip_atomic_load:
4993 case AtomicExpr::AO__atomic_load_n:
4994 case AtomicExpr::AO__atomic_load:
4995 case AtomicExpr::AO__scoped_atomic_load_n:
4996 case AtomicExpr::AO__scoped_atomic_load:
4997 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4998 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4999
5000 case AtomicExpr::AO__c11_atomic_store:
5001 case AtomicExpr::AO__opencl_atomic_store:
5002 case AtomicExpr::AO__hip_atomic_store:
5003 case AtomicExpr::AO__atomic_store:
5004 case AtomicExpr::AO__atomic_store_n:
5005 case AtomicExpr::AO__scoped_atomic_store:
5006 case AtomicExpr::AO__scoped_atomic_store_n:
5007 case AtomicExpr::AO__atomic_clear:
5008 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5009 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5010 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5011
5012 default:
5013 return true;
5014 }
5015}
5016
5017ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
5018 AtomicExpr::AtomicOp Op) {
5019 CallExpr *TheCall = cast<CallExpr>(Val: TheCallResult.get());
5020 DeclRefExpr *DRE =cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
5021 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5022 return BuildAtomicExpr(CallRange: {TheCall->getBeginLoc(), TheCall->getEndLoc()},
5023 ExprRange: DRE->getSourceRange(), RParenLoc: TheCall->getRParenLoc(), Args,
5024 Op);
5025}
5026
5027/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
5028/// equivalents. Provide a fixit when the scope is a compile-time constant and
5029/// there is a direct mapping from the HIP builtin to a Clang builtin. The
5030/// compare_exchange builtins differ in how they accept the desired value, so
5031/// only a warning (without a fixit) is emitted for those.
5032static void DiagnoseDeprecatedHIPAtomic(Sema &S, SourceRange ExprRange,
5033 MultiExprArg Args,
5034 AtomicExpr::AtomicOp Op) {
5035 StringRef OldName;
5036 StringRef NewName;
5037 bool CanFixIt;
5038
5039 switch (Op) {
5040#define HIP_ATOMIC_FIXABLE(hip, scoped) \
5041 case AtomicExpr::AO__hip_atomic_##hip: \
5042 OldName = "__hip_atomic_" #hip; \
5043 NewName = "__scoped_atomic_" #scoped; \
5044 CanFixIt = true; \
5045 break;
5046 HIP_ATOMIC_FIXABLE(load, load_n)
5047 HIP_ATOMIC_FIXABLE(store, store_n)
5048 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
5049 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
5050 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
5051 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
5052 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
5053 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
5054 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
5055 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
5056#undef HIP_ATOMIC_FIXABLE
5057 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5058 OldName = "__hip_atomic_compare_exchange_weak";
5059 NewName = "__scoped_atomic_compare_exchange";
5060 CanFixIt = false;
5061 break;
5062 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5063 OldName = "__hip_atomic_compare_exchange_strong";
5064 NewName = "__scoped_atomic_compare_exchange";
5065 CanFixIt = false;
5066 break;
5067 default:
5068 llvm_unreachable("unhandled HIP atomic op");
5069 }
5070
5071 auto DB = S.Diag(Loc: ExprRange.getBegin(), DiagID: diag::warn_hip_deprecated_builtin)
5072 << OldName << NewName;
5073 if (!CanFixIt)
5074 return;
5075
5076 DB << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: NewName);
5077
5078 Expr *Scope = Args[Args.size() - 1];
5079 std::optional<llvm::APSInt> ScopeVal =
5080 Scope->getIntegerConstantExpr(Ctx: S.Context);
5081 if (!ScopeVal)
5082 return;
5083
5084 StringRef ScopeName;
5085 switch (ScopeVal->getZExtValue()) {
5086 case AtomicScopeHIPModel::SingleThread:
5087 ScopeName = "__MEMORY_SCOPE_SINGLE";
5088 break;
5089 case AtomicScopeHIPModel::Wavefront:
5090 ScopeName = "__MEMORY_SCOPE_WVFRNT";
5091 break;
5092 case AtomicScopeHIPModel::Workgroup:
5093 ScopeName = "__MEMORY_SCOPE_WRKGRP";
5094 break;
5095 case AtomicScopeHIPModel::Agent:
5096 ScopeName = "__MEMORY_SCOPE_DEVICE";
5097 break;
5098 case AtomicScopeHIPModel::System:
5099 ScopeName = "__MEMORY_SCOPE_SYSTEM";
5100 break;
5101 case AtomicScopeHIPModel::Cluster:
5102 ScopeName = "__MEMORY_SCOPE_CLUSTR";
5103 break;
5104 default:
5105 return;
5106 }
5107
5108 DB << FixItHint::CreateReplacement(
5109 RemoveRange: CharSourceRange::getTokenRange(R: Scope->getSourceRange()), Code: ScopeName);
5110}
5111
5112ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5113 SourceLocation RParenLoc, MultiExprArg Args,
5114 AtomicExpr::AtomicOp Op,
5115 AtomicArgumentOrder ArgOrder) {
5116 // All the non-OpenCL operations take one of the following forms.
5117 // The OpenCL operations take the __c11 forms with one extra argument for
5118 // synchronization scope.
5119 enum {
5120 // C __c11_atomic_init(A *, C)
5121 Init,
5122
5123 // C __c11_atomic_load(A *, int)
5124 Load,
5125
5126 // void __atomic_load(A *, CP, int)
5127 LoadCopy,
5128
5129 // void __atomic_store(A *, CP, int)
5130 Copy,
5131
5132 // C __c11_atomic_add(A *, M, int)
5133 Arithmetic,
5134
5135 // C __atomic_exchange_n(A *, CP, int)
5136 Xchg,
5137
5138 // void __atomic_exchange(A *, C *, CP, int)
5139 GNUXchg,
5140
5141 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5142 C11CmpXchg,
5143
5144 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5145 GNUCmpXchg,
5146
5147 // bool __atomic_test_and_set(A *, int)
5148 TestAndSetByte,
5149
5150 // void __atomic_clear(A *, int)
5151 ClearByte,
5152 } Form = Init;
5153
5154 const unsigned NumForm = ClearByte + 1;
5155 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
5156 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
5157 // where:
5158 // C is an appropriate type,
5159 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5160 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5161 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5162 // the int parameters are for orderings.
5163
5164 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5165 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5166 "need to update code for modified forms");
5167 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
5168 AtomicExpr::AO__atomic_xor_fetch + 1 ==
5169 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
5170 "need to update code for modified C11 atomics");
5171 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
5172 Op <= AtomicExpr::AO__opencl_atomic_store;
5173 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
5174 Op <= AtomicExpr::AO__hip_atomic_store;
5175 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
5176 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
5177 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
5178 Op <= AtomicExpr::AO__c11_atomic_store) ||
5179 IsOpenCL;
5180 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5181 Op == AtomicExpr::AO__atomic_store_n ||
5182 Op == AtomicExpr::AO__atomic_exchange_n ||
5183 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
5184 Op == AtomicExpr::AO__scoped_atomic_load_n ||
5185 Op == AtomicExpr::AO__scoped_atomic_store_n ||
5186 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
5187 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
5188 // Bit mask for extra allowed value types other than integers for atomic
5189 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
5190 // allow floating point.
5191 enum ArithOpExtraValueType {
5192 AOEVT_None = 0,
5193 AOEVT_Pointer = 1,
5194 AOEVT_FP = 2,
5195 AOEVT_Int = 4,
5196 };
5197 unsigned ArithAllows = AOEVT_None;
5198
5199 switch (Op) {
5200 case AtomicExpr::AO__c11_atomic_init:
5201 case AtomicExpr::AO__opencl_atomic_init:
5202 Form = Init;
5203 break;
5204
5205 case AtomicExpr::AO__c11_atomic_load:
5206 case AtomicExpr::AO__opencl_atomic_load:
5207 case AtomicExpr::AO__hip_atomic_load:
5208 case AtomicExpr::AO__atomic_load_n:
5209 case AtomicExpr::AO__scoped_atomic_load_n:
5210 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5211 Form = Load;
5212 break;
5213
5214 case AtomicExpr::AO__atomic_load:
5215 case AtomicExpr::AO__scoped_atomic_load:
5216 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5217 Form = LoadCopy;
5218 break;
5219
5220 case AtomicExpr::AO__c11_atomic_store:
5221 case AtomicExpr::AO__opencl_atomic_store:
5222 case AtomicExpr::AO__hip_atomic_store:
5223 case AtomicExpr::AO__atomic_store:
5224 case AtomicExpr::AO__atomic_store_n:
5225 case AtomicExpr::AO__scoped_atomic_store:
5226 case AtomicExpr::AO__scoped_atomic_store_n:
5227 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5228 Form = Copy;
5229 break;
5230 case AtomicExpr::AO__atomic_fetch_add:
5231 case AtomicExpr::AO__atomic_fetch_sub:
5232 case AtomicExpr::AO__atomic_add_fetch:
5233 case AtomicExpr::AO__atomic_sub_fetch:
5234 case AtomicExpr::AO__scoped_atomic_fetch_add:
5235 case AtomicExpr::AO__scoped_atomic_fetch_sub:
5236 case AtomicExpr::AO__scoped_atomic_add_fetch:
5237 case AtomicExpr::AO__scoped_atomic_sub_fetch:
5238 case AtomicExpr::AO__c11_atomic_fetch_add:
5239 case AtomicExpr::AO__c11_atomic_fetch_sub:
5240 case AtomicExpr::AO__opencl_atomic_fetch_add:
5241 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5242 case AtomicExpr::AO__hip_atomic_fetch_add:
5243 case AtomicExpr::AO__hip_atomic_fetch_sub:
5244 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5245 Form = Arithmetic;
5246 break;
5247 case AtomicExpr::AO__atomic_fetch_fminimum:
5248 case AtomicExpr::AO__atomic_fetch_fmaximum:
5249 case AtomicExpr::AO__atomic_fetch_fminimum_num:
5250 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
5251 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
5252 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
5253 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
5254 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
5255 ArithAllows = AOEVT_FP;
5256 Form = Arithmetic;
5257 break;
5258 case AtomicExpr::AO__atomic_fetch_max:
5259 case AtomicExpr::AO__atomic_fetch_min:
5260 case AtomicExpr::AO__atomic_max_fetch:
5261 case AtomicExpr::AO__atomic_min_fetch:
5262 case AtomicExpr::AO__scoped_atomic_fetch_max:
5263 case AtomicExpr::AO__scoped_atomic_fetch_min:
5264 case AtomicExpr::AO__scoped_atomic_max_fetch:
5265 case AtomicExpr::AO__scoped_atomic_min_fetch:
5266 case AtomicExpr::AO__c11_atomic_fetch_max:
5267 case AtomicExpr::AO__c11_atomic_fetch_min:
5268 case AtomicExpr::AO__opencl_atomic_fetch_max:
5269 case AtomicExpr::AO__opencl_atomic_fetch_min:
5270 case AtomicExpr::AO__hip_atomic_fetch_max:
5271 case AtomicExpr::AO__hip_atomic_fetch_min:
5272 ArithAllows = AOEVT_Int | AOEVT_FP;
5273 Form = Arithmetic;
5274 break;
5275 case AtomicExpr::AO__c11_atomic_fetch_and:
5276 case AtomicExpr::AO__c11_atomic_fetch_or:
5277 case AtomicExpr::AO__c11_atomic_fetch_xor:
5278 case AtomicExpr::AO__hip_atomic_fetch_and:
5279 case AtomicExpr::AO__hip_atomic_fetch_or:
5280 case AtomicExpr::AO__hip_atomic_fetch_xor:
5281 case AtomicExpr::AO__c11_atomic_fetch_nand:
5282 case AtomicExpr::AO__opencl_atomic_fetch_and:
5283 case AtomicExpr::AO__opencl_atomic_fetch_or:
5284 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5285 case AtomicExpr::AO__atomic_fetch_and:
5286 case AtomicExpr::AO__atomic_fetch_or:
5287 case AtomicExpr::AO__atomic_fetch_xor:
5288 case AtomicExpr::AO__atomic_fetch_nand:
5289 case AtomicExpr::AO__atomic_and_fetch:
5290 case AtomicExpr::AO__atomic_or_fetch:
5291 case AtomicExpr::AO__atomic_xor_fetch:
5292 case AtomicExpr::AO__atomic_nand_fetch:
5293 case AtomicExpr::AO__atomic_fetch_uinc:
5294 case AtomicExpr::AO__atomic_fetch_udec:
5295 case AtomicExpr::AO__scoped_atomic_fetch_and:
5296 case AtomicExpr::AO__scoped_atomic_fetch_or:
5297 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5298 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5299 case AtomicExpr::AO__scoped_atomic_and_fetch:
5300 case AtomicExpr::AO__scoped_atomic_or_fetch:
5301 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5302 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5303 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5304 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5305 Form = Arithmetic;
5306 break;
5307
5308 case AtomicExpr::AO__c11_atomic_exchange:
5309 case AtomicExpr::AO__hip_atomic_exchange:
5310 case AtomicExpr::AO__opencl_atomic_exchange:
5311 case AtomicExpr::AO__atomic_exchange_n:
5312 case AtomicExpr::AO__scoped_atomic_exchange_n:
5313 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5314 Form = Xchg;
5315 break;
5316
5317 case AtomicExpr::AO__atomic_exchange:
5318 case AtomicExpr::AO__scoped_atomic_exchange:
5319 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5320 Form = GNUXchg;
5321 break;
5322
5323 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5324 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5325 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5326 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5327 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5328 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5329 Form = C11CmpXchg;
5330 break;
5331
5332 case AtomicExpr::AO__atomic_compare_exchange:
5333 case AtomicExpr::AO__atomic_compare_exchange_n:
5334 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5335 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5336 ArithAllows = AOEVT_Pointer;
5337 Form = GNUCmpXchg;
5338 break;
5339
5340 case AtomicExpr::AO__atomic_test_and_set:
5341 Form = TestAndSetByte;
5342 break;
5343
5344 case AtomicExpr::AO__atomic_clear:
5345 Form = ClearByte;
5346 break;
5347 }
5348
5349 unsigned AdjustedNumArgs = NumArgs[Form];
5350 if ((IsOpenCL || IsHIP || IsScoped) &&
5351 Op != AtomicExpr::AO__opencl_atomic_init)
5352 ++AdjustedNumArgs;
5353 // Check we have the right number of arguments.
5354 if (Args.size() < AdjustedNumArgs) {
5355 Diag(Loc: CallRange.getEnd(), DiagID: diag::err_typecheck_call_too_few_args)
5356 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5357 << /*is non object*/ 0 << ExprRange;
5358 return ExprError();
5359 } else if (Args.size() > AdjustedNumArgs) {
5360 Diag(Loc: Args[AdjustedNumArgs]->getBeginLoc(),
5361 DiagID: diag::err_typecheck_call_too_many_args)
5362 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5363 << /*is non object*/ 0 << ExprRange;
5364 return ExprError();
5365 }
5366
5367 // Inspect the first argument of the atomic operation.
5368 Expr *Ptr = Args[0];
5369 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(E: Ptr);
5370 if (ConvertedPtr.isInvalid())
5371 return ExprError();
5372
5373 Ptr = ConvertedPtr.get();
5374 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5375 if (!pointerType) {
5376 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5377 << Ptr->getType() << 0 << Ptr->getSourceRange();
5378 return ExprError();
5379 }
5380
5381 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5382 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5383 QualType ValType = AtomTy; // 'C'
5384 if (IsC11) {
5385 if (!AtomTy->isAtomicType()) {
5386 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_atomic)
5387 << Ptr->getType() << Ptr->getSourceRange();
5388 return ExprError();
5389 }
5390 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5391 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5392 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_atomic)
5393 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5394 << Ptr->getSourceRange();
5395 return ExprError();
5396 }
5397 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5398 } else if (Form != Load && Form != LoadCopy) {
5399 if (ValType.isConstQualified()) {
5400 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_pointer)
5401 << Ptr->getType() << Ptr->getSourceRange();
5402 return ExprError();
5403 }
5404 }
5405
5406 if (Form != TestAndSetByte && Form != ClearByte) {
5407 // Pointer to object of size zero is not allowed.
5408 if (RequireCompleteType(Loc: Ptr->getBeginLoc(), T: AtomTy,
5409 DiagID: diag::err_incomplete_type))
5410 return ExprError();
5411
5412 if (Context.getTypeInfoInChars(T: AtomTy).Width.isZero()) {
5413 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5414 << Ptr->getType() << 1 << Ptr->getSourceRange();
5415 return ExprError();
5416 }
5417 } else {
5418 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5419 // non-const pointer type, including void* and pointers to incomplete
5420 // structs, but only access the first byte.
5421 AtomTy = Context.CharTy;
5422 AtomTy = AtomTy.withCVRQualifiers(
5423 CVR: pointerType->getPointeeType().getCVRQualifiers());
5424 QualType PointerQT = Context.getPointerType(T: AtomTy);
5425 pointerType = PointerQT->getAs<PointerType>();
5426 Ptr = ImpCastExprToType(E: Ptr, Type: PointerQT, CK: CK_BitCast).get();
5427 ValType = AtomTy;
5428 }
5429
5430 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5431 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5432 Diag(Loc: ExprRange.getBegin(),
5433 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5434 << 0 << Ptr->getType() << Ptr->getSourceRange();
5435 return ExprError();
5436 }
5437
5438 // For an arithmetic operation, the implied arithmetic must be well-formed.
5439 // For _n operations, the value type must also be a valid atomic type.
5440 if (Form == Arithmetic || IsN) {
5441 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5442 // trivial type errors.
5443 auto IsAllowedValueType = [&](QualType ValType,
5444 unsigned AllowedType) -> bool {
5445 bool IsX87LongDouble =
5446 ValType->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
5447 &Context.getTargetInfo().getLongDoubleFormat() ==
5448 &llvm::APFloat::x87DoubleExtended();
5449 if (ValType->isIntegerType())
5450 // Special case: f-prefixed operations (AOEVT_FP exactly) reject
5451 // integers. Explicit AOEVT_Int or other combinations allow integers.
5452 return (AllowedType & AOEVT_Int) || AllowedType != AOEVT_FP;
5453 if (ValType->isPointerType())
5454 return AllowedType & AOEVT_Pointer;
5455 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5456 return false;
5457 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5458 if (IsX87LongDouble)
5459 return false;
5460 return true;
5461 };
5462 if (!IsAllowedValueType(ValType, ArithAllows)) {
5463 auto DID =
5464 ArithAllows == AOEVT_FP
5465 ? diag::err_atomic_op_needs_atomic_fp
5466 : (ArithAllows & AOEVT_FP
5467 ? (ArithAllows & AOEVT_Pointer
5468 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5469 : diag::err_atomic_op_needs_atomic_int_or_fp)
5470 : (ArithAllows & AOEVT_Pointer
5471 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5472 : diag::err_atomic_op_needs_atomic_int));
5473 Diag(Loc: ExprRange.getBegin(), DiagID: DID)
5474 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5475 return ExprError();
5476 }
5477 if (IsC11 && ValType->isPointerType() &&
5478 RequireCompleteType(Loc: Ptr->getBeginLoc(), T: ValType->getPointeeType(),
5479 DiagID: diag::err_incomplete_type)) {
5480 return ExprError();
5481 }
5482 }
5483
5484 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5485 !AtomTy->isScalarType()) {
5486 // For GNU atomics, require a trivially-copyable type. This is not part of
5487 // the GNU atomics specification but we enforce it for consistency with
5488 // other atomics which generally all require a trivially-copyable type. This
5489 // is because atomics just copy bits.
5490 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_trivial_copy)
5491 << Ptr->getType() << Ptr->getSourceRange();
5492 return ExprError();
5493 }
5494
5495 switch (ValType.getObjCLifetime()) {
5496 case Qualifiers::OCL_None:
5497 case Qualifiers::OCL_ExplicitNone:
5498 // okay
5499 break;
5500
5501 case Qualifiers::OCL_Weak:
5502 case Qualifiers::OCL_Strong:
5503 case Qualifiers::OCL_Autoreleasing:
5504 // FIXME: Can this happen? By this point, ValType should be known
5505 // to be trivially copyable.
5506 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_arc_atomic_ownership)
5507 << ValType << Ptr->getSourceRange();
5508 return ExprError();
5509 }
5510
5511 // All atomic operations have an overload which takes a pointer to a volatile
5512 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5513 // into the result or the other operands. Similarly atomic_load takes a
5514 // pointer to a const 'A'.
5515 ValType.removeLocalVolatile();
5516 ValType.removeLocalConst();
5517 QualType ResultType = ValType;
5518 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5519 Form == ClearByte)
5520 ResultType = Context.VoidTy;
5521 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5522 ResultType = Context.BoolTy;
5523
5524 // The type of a parameter passed 'by value'. In the GNU atomics, such
5525 // arguments are actually passed as pointers.
5526 QualType ByValType = ValType; // 'CP'
5527 bool IsPassedByAddress = false;
5528 if (!IsC11 && !IsHIP && !IsN) {
5529 ByValType = Ptr->getType();
5530 IsPassedByAddress = true;
5531 }
5532
5533 SmallVector<Expr *, 5> APIOrderedArgs;
5534 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5535 APIOrderedArgs.push_back(Elt: Args[0]);
5536 switch (Form) {
5537 case Init:
5538 case Load:
5539 APIOrderedArgs.push_back(Elt: Args[1]); // Val1/Order
5540 break;
5541 case LoadCopy:
5542 case Copy:
5543 case Arithmetic:
5544 case Xchg:
5545 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5546 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5547 break;
5548 case GNUXchg:
5549 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5550 APIOrderedArgs.push_back(Elt: Args[3]); // Val2
5551 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5552 break;
5553 case C11CmpXchg:
5554 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5555 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
5556 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5557 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
5558 break;
5559 case GNUCmpXchg:
5560 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5561 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
5562 APIOrderedArgs.push_back(Elt: Args[5]); // Weak
5563 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5564 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
5565 break;
5566 case TestAndSetByte:
5567 case ClearByte:
5568 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5569 break;
5570 }
5571 } else
5572 APIOrderedArgs.append(in_start: Args.begin(), in_end: Args.end());
5573
5574 // The first argument's non-CV pointer type is used to deduce the type of
5575 // subsequent arguments, except for:
5576 // - weak flag (always converted to bool)
5577 // - memory order (always converted to int)
5578 // - scope (always converted to int)
5579 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5580 QualType Ty;
5581 if (i < NumVals[Form] + 1) {
5582 switch (i) {
5583 case 0:
5584 // The first argument is always a pointer. It has a fixed type.
5585 // It is always dereferenced, a nullptr is undefined.
5586 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5587 // Nothing else to do: we already know all we want about this pointer.
5588 continue;
5589 case 1:
5590 // The second argument is the non-atomic operand. For arithmetic, this
5591 // is always passed by value, and for a compare_exchange it is always
5592 // passed by address. For the rest, GNU uses by-address and C11 uses
5593 // by-value.
5594 assert(Form != Load);
5595 if (Form == Arithmetic && ValType->isPointerType())
5596 Ty = Context.getPointerDiffType();
5597 else if (Form == Init || Form == Arithmetic)
5598 Ty = ValType;
5599 else if (Form == Copy || Form == Xchg) {
5600 if (IsPassedByAddress) {
5601 // The value pointer is always dereferenced, a nullptr is undefined.
5602 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i],
5603 CallSiteLoc: ExprRange.getBegin());
5604 }
5605 Ty = ByValType;
5606 } else {
5607 Expr *ValArg = APIOrderedArgs[i];
5608 // The value pointer is always dereferenced, a nullptr is undefined.
5609 CheckNonNullArgument(S&: *this, ArgExpr: ValArg, CallSiteLoc: ExprRange.getBegin());
5610 LangAS AS = LangAS::Default;
5611 // Keep address space of non-atomic pointer type.
5612 if (const PointerType *PtrTy =
5613 ValArg->getType()->getAs<PointerType>()) {
5614 AS = PtrTy->getPointeeType().getAddressSpace();
5615 }
5616 Ty = Context.getPointerType(
5617 T: Context.getAddrSpaceQualType(T: ValType.getUnqualifiedType(), AddressSpace: AS));
5618 }
5619 break;
5620 case 2:
5621 // The third argument to compare_exchange / GNU exchange is the desired
5622 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5623 if (IsPassedByAddress)
5624 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5625 Ty = ByValType;
5626 break;
5627 case 3:
5628 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5629 Ty = Context.BoolTy;
5630 break;
5631 }
5632 } else {
5633 // The order(s) and scope are always converted to int.
5634 Ty = Context.IntTy;
5635 }
5636
5637 InitializedEntity Entity =
5638 InitializedEntity::InitializeParameter(Context, Type: Ty, Consumed: false);
5639 ExprResult Arg = APIOrderedArgs[i];
5640 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5641 if (Arg.isInvalid())
5642 return true;
5643 APIOrderedArgs[i] = Arg.get();
5644 }
5645
5646 // Permute the arguments into a 'consistent' order.
5647 SmallVector<Expr*, 5> SubExprs;
5648 SubExprs.push_back(Elt: Ptr);
5649 switch (Form) {
5650 case Init:
5651 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5652 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5653 break;
5654 case Load:
5655 case TestAndSetByte:
5656 case ClearByte:
5657 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Order
5658 break;
5659 case LoadCopy:
5660 case Copy:
5661 case Arithmetic:
5662 case Xchg:
5663 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Order
5664 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5665 break;
5666 case GNUXchg:
5667 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5668 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5669 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5670 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5671 break;
5672 case C11CmpXchg:
5673 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5674 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5675 SubExprs.push_back(Elt: APIOrderedArgs[4]); // OrderFail
5676 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5677 break;
5678 case GNUCmpXchg:
5679 SubExprs.push_back(Elt: APIOrderedArgs[4]); // Order
5680 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5681 SubExprs.push_back(Elt: APIOrderedArgs[5]); // OrderFail
5682 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5683 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Weak
5684 break;
5685 }
5686
5687 // If the memory orders are constants, check they are valid.
5688 if (SubExprs.size() >= 2 && Form != Init) {
5689 std::optional<llvm::APSInt> Success =
5690 SubExprs[1]->getIntegerConstantExpr(Ctx: Context);
5691 if (Success && !isValidOrderingForOp(Ordering: Success->getSExtValue(), Op)) {
5692 Diag(Loc: SubExprs[1]->getBeginLoc(),
5693 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5694 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5695 << SubExprs[1]->getSourceRange();
5696 }
5697 if (SubExprs.size() >= 5) {
5698 if (std::optional<llvm::APSInt> Failure =
5699 SubExprs[3]->getIntegerConstantExpr(Ctx: Context)) {
5700 if (!llvm::is_contained(
5701 Set: {llvm::AtomicOrderingCABI::relaxed,
5702 llvm::AtomicOrderingCABI::consume,
5703 llvm::AtomicOrderingCABI::acquire,
5704 llvm::AtomicOrderingCABI::seq_cst},
5705 Element: (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5706 Diag(Loc: SubExprs[3]->getBeginLoc(),
5707 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5708 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5709 }
5710 }
5711 }
5712 }
5713
5714 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5715 auto *Scope = Args[Args.size() - 1];
5716 if (std::optional<llvm::APSInt> Result =
5717 Scope->getIntegerConstantExpr(Ctx: Context)) {
5718 if (!ScopeModel->isValid(S: Result->getZExtValue()))
5719 Diag(Loc: Scope->getBeginLoc(), DiagID: diag::err_atomic_op_has_invalid_sync_scope)
5720 << Scope->getSourceRange();
5721 }
5722 SubExprs.push_back(Elt: Scope);
5723 }
5724
5725 if (IsHIP)
5726 DiagnoseDeprecatedHIPAtomic(S&: *this, ExprRange, Args, Op);
5727
5728 AtomicExpr *AE = new (Context)
5729 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5730
5731 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5732 Op == AtomicExpr::AO__c11_atomic_store ||
5733 Op == AtomicExpr::AO__opencl_atomic_load ||
5734 Op == AtomicExpr::AO__hip_atomic_load ||
5735 Op == AtomicExpr::AO__opencl_atomic_store ||
5736 Op == AtomicExpr::AO__hip_atomic_store) &&
5737 Context.AtomicUsesUnsupportedLibcall(E: AE))
5738 Diag(Loc: AE->getBeginLoc(), DiagID: diag::err_atomic_load_store_uses_lib)
5739 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5740 Op == AtomicExpr::AO__opencl_atomic_load ||
5741 Op == AtomicExpr::AO__hip_atomic_load)
5742 ? 0
5743 : 1);
5744
5745 if (ValType->isBitIntType()) {
5746 Diag(Loc: Ptr->getExprLoc(), DiagID: diag::err_atomic_builtin_bit_int_prohibit);
5747 return ExprError();
5748 }
5749
5750 return AE;
5751}
5752
5753/// checkBuiltinArgument - Given a call to a builtin function, perform
5754/// normal type-checking on the given argument, updating the call in
5755/// place. This is useful when a builtin function requires custom
5756/// type-checking for some of its arguments but not necessarily all of
5757/// them.
5758///
5759/// Returns true on error.
5760static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5761 FunctionDecl *Fn = E->getDirectCallee();
5762 assert(Fn && "builtin call without direct callee!");
5763
5764 ParmVarDecl *Param = Fn->getParamDecl(i: ArgIndex);
5765 InitializedEntity Entity =
5766 InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Param);
5767
5768 ExprResult Arg = E->getArg(Arg: ArgIndex);
5769 Arg = S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5770 if (Arg.isInvalid())
5771 return true;
5772
5773 E->setArg(Arg: ArgIndex, ArgExpr: Arg.get());
5774 return false;
5775}
5776
5777ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5778 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5779 Expr *Callee = TheCall->getCallee();
5780 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Callee->IgnoreParenCasts());
5781 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
5782
5783 // Ensure that we have at least one argument to do type inference from.
5784 if (TheCall->getNumArgs() < 1) {
5785 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5786 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5787 << Callee->getSourceRange();
5788 return ExprError();
5789 }
5790
5791 // Inspect the first argument of the atomic builtin. This should always be
5792 // a pointer type, whose element is an integral scalar or pointer type.
5793 // Because it is a pointer type, we don't have to worry about any implicit
5794 // casts here.
5795 // FIXME: We don't allow floating point scalars as input.
5796 Expr *FirstArg = TheCall->getArg(Arg: 0);
5797 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(E: FirstArg);
5798 if (FirstArgResult.isInvalid())
5799 return ExprError();
5800 FirstArg = FirstArgResult.get();
5801 TheCall->setArg(Arg: 0, ArgExpr: FirstArg);
5802
5803 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5804 if (!pointerType) {
5805 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5806 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5807 return ExprError();
5808 }
5809
5810 QualType ValType = pointerType->getPointeeType();
5811 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5812 !ValType->isBlockPointerType()) {
5813 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer_intptr)
5814 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5815 return ExprError();
5816 }
5817 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5818 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5819 Diag(Loc: FirstArg->getBeginLoc(),
5820 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5821 << 1 << ValType << FirstArg->getSourceRange();
5822 return ExprError();
5823 }
5824
5825 if (ValType.isConstQualified()) {
5826 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_cannot_be_const)
5827 << FirstArg->getType() << FirstArg->getSourceRange();
5828 return ExprError();
5829 }
5830
5831 switch (ValType.getObjCLifetime()) {
5832 case Qualifiers::OCL_None:
5833 case Qualifiers::OCL_ExplicitNone:
5834 // okay
5835 break;
5836
5837 case Qualifiers::OCL_Weak:
5838 case Qualifiers::OCL_Strong:
5839 case Qualifiers::OCL_Autoreleasing:
5840 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_arc_atomic_ownership)
5841 << ValType << FirstArg->getSourceRange();
5842
5843 return ExprError();
5844 }
5845
5846 // Strip any qualifiers off ValType.
5847 ValType = ValType.getUnqualifiedType();
5848
5849 // The majority of builtins return a value, but a few have special return
5850 // types, so allow them to override appropriately below.
5851 QualType ResultType = ValType;
5852
5853 // We need to figure out which concrete builtin this maps onto. For example,
5854 // __sync_fetch_and_add with a 2 byte object turns into
5855 // __sync_fetch_and_add_2.
5856#define BUILTIN_ROW(x) \
5857 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5858 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5859
5860 static const unsigned BuiltinIndices[][5] = {
5861 BUILTIN_ROW(__sync_fetch_and_add),
5862 BUILTIN_ROW(__sync_fetch_and_sub),
5863 BUILTIN_ROW(__sync_fetch_and_or),
5864 BUILTIN_ROW(__sync_fetch_and_and),
5865 BUILTIN_ROW(__sync_fetch_and_xor),
5866 BUILTIN_ROW(__sync_fetch_and_nand),
5867
5868 BUILTIN_ROW(__sync_add_and_fetch),
5869 BUILTIN_ROW(__sync_sub_and_fetch),
5870 BUILTIN_ROW(__sync_and_and_fetch),
5871 BUILTIN_ROW(__sync_or_and_fetch),
5872 BUILTIN_ROW(__sync_xor_and_fetch),
5873 BUILTIN_ROW(__sync_nand_and_fetch),
5874
5875 BUILTIN_ROW(__sync_val_compare_and_swap),
5876 BUILTIN_ROW(__sync_bool_compare_and_swap),
5877 BUILTIN_ROW(__sync_lock_test_and_set),
5878 BUILTIN_ROW(__sync_lock_release),
5879 BUILTIN_ROW(__sync_swap)
5880 };
5881#undef BUILTIN_ROW
5882
5883 // Determine the index of the size.
5884 unsigned SizeIndex;
5885 switch (Context.getTypeSizeInChars(T: ValType).getQuantity()) {
5886 case 1: SizeIndex = 0; break;
5887 case 2: SizeIndex = 1; break;
5888 case 4: SizeIndex = 2; break;
5889 case 8: SizeIndex = 3; break;
5890 case 16: SizeIndex = 4; break;
5891 default:
5892 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_pointer_size)
5893 << FirstArg->getType() << FirstArg->getSourceRange();
5894 return ExprError();
5895 }
5896
5897 // Each of these builtins has one pointer argument, followed by some number of
5898 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5899 // that we ignore. Find out which row of BuiltinIndices to read from as well
5900 // as the number of fixed args.
5901 unsigned BuiltinID = FDecl->getBuiltinID();
5902 unsigned BuiltinIndex, NumFixed = 1;
5903 bool WarnAboutSemanticsChange = false;
5904 switch (BuiltinID) {
5905 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5906 case Builtin::BI__sync_fetch_and_add:
5907 case Builtin::BI__sync_fetch_and_add_1:
5908 case Builtin::BI__sync_fetch_and_add_2:
5909 case Builtin::BI__sync_fetch_and_add_4:
5910 case Builtin::BI__sync_fetch_and_add_8:
5911 case Builtin::BI__sync_fetch_and_add_16:
5912 BuiltinIndex = 0;
5913 break;
5914
5915 case Builtin::BI__sync_fetch_and_sub:
5916 case Builtin::BI__sync_fetch_and_sub_1:
5917 case Builtin::BI__sync_fetch_and_sub_2:
5918 case Builtin::BI__sync_fetch_and_sub_4:
5919 case Builtin::BI__sync_fetch_and_sub_8:
5920 case Builtin::BI__sync_fetch_and_sub_16:
5921 BuiltinIndex = 1;
5922 break;
5923
5924 case Builtin::BI__sync_fetch_and_or:
5925 case Builtin::BI__sync_fetch_and_or_1:
5926 case Builtin::BI__sync_fetch_and_or_2:
5927 case Builtin::BI__sync_fetch_and_or_4:
5928 case Builtin::BI__sync_fetch_and_or_8:
5929 case Builtin::BI__sync_fetch_and_or_16:
5930 BuiltinIndex = 2;
5931 break;
5932
5933 case Builtin::BI__sync_fetch_and_and:
5934 case Builtin::BI__sync_fetch_and_and_1:
5935 case Builtin::BI__sync_fetch_and_and_2:
5936 case Builtin::BI__sync_fetch_and_and_4:
5937 case Builtin::BI__sync_fetch_and_and_8:
5938 case Builtin::BI__sync_fetch_and_and_16:
5939 BuiltinIndex = 3;
5940 break;
5941
5942 case Builtin::BI__sync_fetch_and_xor:
5943 case Builtin::BI__sync_fetch_and_xor_1:
5944 case Builtin::BI__sync_fetch_and_xor_2:
5945 case Builtin::BI__sync_fetch_and_xor_4:
5946 case Builtin::BI__sync_fetch_and_xor_8:
5947 case Builtin::BI__sync_fetch_and_xor_16:
5948 BuiltinIndex = 4;
5949 break;
5950
5951 case Builtin::BI__sync_fetch_and_nand:
5952 case Builtin::BI__sync_fetch_and_nand_1:
5953 case Builtin::BI__sync_fetch_and_nand_2:
5954 case Builtin::BI__sync_fetch_and_nand_4:
5955 case Builtin::BI__sync_fetch_and_nand_8:
5956 case Builtin::BI__sync_fetch_and_nand_16:
5957 BuiltinIndex = 5;
5958 WarnAboutSemanticsChange = true;
5959 break;
5960
5961 case Builtin::BI__sync_add_and_fetch:
5962 case Builtin::BI__sync_add_and_fetch_1:
5963 case Builtin::BI__sync_add_and_fetch_2:
5964 case Builtin::BI__sync_add_and_fetch_4:
5965 case Builtin::BI__sync_add_and_fetch_8:
5966 case Builtin::BI__sync_add_and_fetch_16:
5967 BuiltinIndex = 6;
5968 break;
5969
5970 case Builtin::BI__sync_sub_and_fetch:
5971 case Builtin::BI__sync_sub_and_fetch_1:
5972 case Builtin::BI__sync_sub_and_fetch_2:
5973 case Builtin::BI__sync_sub_and_fetch_4:
5974 case Builtin::BI__sync_sub_and_fetch_8:
5975 case Builtin::BI__sync_sub_and_fetch_16:
5976 BuiltinIndex = 7;
5977 break;
5978
5979 case Builtin::BI__sync_and_and_fetch:
5980 case Builtin::BI__sync_and_and_fetch_1:
5981 case Builtin::BI__sync_and_and_fetch_2:
5982 case Builtin::BI__sync_and_and_fetch_4:
5983 case Builtin::BI__sync_and_and_fetch_8:
5984 case Builtin::BI__sync_and_and_fetch_16:
5985 BuiltinIndex = 8;
5986 break;
5987
5988 case Builtin::BI__sync_or_and_fetch:
5989 case Builtin::BI__sync_or_and_fetch_1:
5990 case Builtin::BI__sync_or_and_fetch_2:
5991 case Builtin::BI__sync_or_and_fetch_4:
5992 case Builtin::BI__sync_or_and_fetch_8:
5993 case Builtin::BI__sync_or_and_fetch_16:
5994 BuiltinIndex = 9;
5995 break;
5996
5997 case Builtin::BI__sync_xor_and_fetch:
5998 case Builtin::BI__sync_xor_and_fetch_1:
5999 case Builtin::BI__sync_xor_and_fetch_2:
6000 case Builtin::BI__sync_xor_and_fetch_4:
6001 case Builtin::BI__sync_xor_and_fetch_8:
6002 case Builtin::BI__sync_xor_and_fetch_16:
6003 BuiltinIndex = 10;
6004 break;
6005
6006 case Builtin::BI__sync_nand_and_fetch:
6007 case Builtin::BI__sync_nand_and_fetch_1:
6008 case Builtin::BI__sync_nand_and_fetch_2:
6009 case Builtin::BI__sync_nand_and_fetch_4:
6010 case Builtin::BI__sync_nand_and_fetch_8:
6011 case Builtin::BI__sync_nand_and_fetch_16:
6012 BuiltinIndex = 11;
6013 WarnAboutSemanticsChange = true;
6014 break;
6015
6016 case Builtin::BI__sync_val_compare_and_swap:
6017 case Builtin::BI__sync_val_compare_and_swap_1:
6018 case Builtin::BI__sync_val_compare_and_swap_2:
6019 case Builtin::BI__sync_val_compare_and_swap_4:
6020 case Builtin::BI__sync_val_compare_and_swap_8:
6021 case Builtin::BI__sync_val_compare_and_swap_16:
6022 BuiltinIndex = 12;
6023 NumFixed = 2;
6024 break;
6025
6026 case Builtin::BI__sync_bool_compare_and_swap:
6027 case Builtin::BI__sync_bool_compare_and_swap_1:
6028 case Builtin::BI__sync_bool_compare_and_swap_2:
6029 case Builtin::BI__sync_bool_compare_and_swap_4:
6030 case Builtin::BI__sync_bool_compare_and_swap_8:
6031 case Builtin::BI__sync_bool_compare_and_swap_16:
6032 BuiltinIndex = 13;
6033 NumFixed = 2;
6034 ResultType = Context.BoolTy;
6035 break;
6036
6037 case Builtin::BI__sync_lock_test_and_set:
6038 case Builtin::BI__sync_lock_test_and_set_1:
6039 case Builtin::BI__sync_lock_test_and_set_2:
6040 case Builtin::BI__sync_lock_test_and_set_4:
6041 case Builtin::BI__sync_lock_test_and_set_8:
6042 case Builtin::BI__sync_lock_test_and_set_16:
6043 BuiltinIndex = 14;
6044 break;
6045
6046 case Builtin::BI__sync_lock_release:
6047 case Builtin::BI__sync_lock_release_1:
6048 case Builtin::BI__sync_lock_release_2:
6049 case Builtin::BI__sync_lock_release_4:
6050 case Builtin::BI__sync_lock_release_8:
6051 case Builtin::BI__sync_lock_release_16:
6052 BuiltinIndex = 15;
6053 NumFixed = 0;
6054 ResultType = Context.VoidTy;
6055 break;
6056
6057 case Builtin::BI__sync_swap:
6058 case Builtin::BI__sync_swap_1:
6059 case Builtin::BI__sync_swap_2:
6060 case Builtin::BI__sync_swap_4:
6061 case Builtin::BI__sync_swap_8:
6062 case Builtin::BI__sync_swap_16:
6063 BuiltinIndex = 16;
6064 break;
6065 }
6066
6067 // Now that we know how many fixed arguments we expect, first check that we
6068 // have at least that many.
6069 if (TheCall->getNumArgs() < 1+NumFixed) {
6070 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
6071 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
6072 << Callee->getSourceRange();
6073 return ExprError();
6074 }
6075
6076 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
6077 << Callee->getSourceRange();
6078
6079 if (WarnAboutSemanticsChange) {
6080 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_sync_fetch_and_nand_semantics_change)
6081 << Callee->getSourceRange();
6082 }
6083
6084 // Get the decl for the concrete builtin from this, we can tell what the
6085 // concrete integer type we should convert to is.
6086 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6087 std::string NewBuiltinName = Context.BuiltinInfo.getName(ID: NewBuiltinID);
6088 FunctionDecl *NewBuiltinDecl;
6089 if (NewBuiltinID == BuiltinID)
6090 NewBuiltinDecl = FDecl;
6091 else {
6092 // Perform builtin lookup to avoid redeclaring it.
6093 DeclarationName DN(&Context.Idents.get(Name: NewBuiltinName));
6094 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6095 LookupName(R&: Res, S: TUScope, /*AllowBuiltinCreation=*/true);
6096 assert(Res.getFoundDecl());
6097 NewBuiltinDecl = dyn_cast<FunctionDecl>(Val: Res.getFoundDecl());
6098 if (!NewBuiltinDecl)
6099 return ExprError();
6100 }
6101
6102 // The first argument --- the pointer --- has a fixed type; we
6103 // deduce the types of the rest of the arguments accordingly. Walk
6104 // the remaining arguments, converting them to the deduced value type.
6105 for (unsigned i = 0; i != NumFixed; ++i) {
6106 ExprResult Arg = TheCall->getArg(Arg: i+1);
6107
6108 // GCC does an implicit conversion to the pointer or integer ValType. This
6109 // can fail in some cases (1i -> int**), check for this error case now.
6110 // Initialize the argument.
6111 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6112 Type: ValType, /*consume*/ Consumed: false);
6113 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
6114 if (Arg.isInvalid())
6115 return ExprError();
6116
6117 // Okay, we have something that *can* be converted to the right type. Check
6118 // to see if there is a potentially weird extension going on here. This can
6119 // happen when you do an atomic operation on something like an char* and
6120 // pass in 42. The 42 gets converted to char. This is even more strange
6121 // for things like 45.123 -> char, etc.
6122 // FIXME: Do this check.
6123 TheCall->setArg(Arg: i+1, ArgExpr: Arg.get());
6124 }
6125
6126 // Create a new DeclRefExpr to refer to the new decl.
6127 DeclRefExpr *NewDRE = DeclRefExpr::Create(
6128 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: NewBuiltinDecl,
6129 /*enclosing*/ RefersToEnclosingVariableOrCapture: false, NameLoc: DRE->getLocation(), T: Context.BuiltinFnTy,
6130 VK: DRE->getValueKind(), FoundD: nullptr, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
6131
6132 // Set the callee in the CallExpr.
6133 // FIXME: This loses syntactic information.
6134 QualType CalleePtrTy = Context.getPointerType(T: NewBuiltinDecl->getType());
6135 ExprResult PromotedCall = ImpCastExprToType(E: NewDRE, Type: CalleePtrTy,
6136 CK: CK_BuiltinFnToFnPtr);
6137 TheCall->setCallee(PromotedCall.get());
6138
6139 // Change the result type of the call to match the original value type. This
6140 // is arbitrary, but the codegen for these builtins ins design to handle it
6141 // gracefully.
6142 TheCall->setType(ResultType);
6143
6144 // Prohibit problematic uses of bit-precise integer types with atomic
6145 // builtins. The arguments would have already been converted to the first
6146 // argument's type, so only need to check the first argument.
6147 const auto *BitIntValType = ValType->getAs<BitIntType>();
6148 if (BitIntValType && !llvm::isPowerOf2_64(Value: BitIntValType->getNumBits())) {
6149 Diag(Loc: FirstArg->getExprLoc(), DiagID: diag::err_atomic_builtin_ext_int_size);
6150 return ExprError();
6151 }
6152
6153 return TheCallResult;
6154}
6155
6156ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6157 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6158 DeclRefExpr *DRE =
6159 cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
6160 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
6161 unsigned BuiltinID = FDecl->getBuiltinID();
6162 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6163 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6164 "Unexpected nontemporal load/store builtin!");
6165 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6166 unsigned numArgs = isStore ? 2 : 1;
6167
6168 // Ensure that we have the proper number of arguments.
6169 if (checkArgCount(Call: TheCall, DesiredArgCount: numArgs))
6170 return ExprError();
6171
6172 // Inspect the last argument of the nontemporal builtin. This should always
6173 // be a pointer type, from which we imply the type of the memory access.
6174 // Because it is a pointer type, we don't have to worry about any implicit
6175 // casts here.
6176 Expr *PointerArg = TheCall->getArg(Arg: numArgs - 1);
6177 ExprResult PointerArgResult =
6178 DefaultFunctionArrayLvalueConversion(E: PointerArg);
6179
6180 if (PointerArgResult.isInvalid())
6181 return ExprError();
6182 PointerArg = PointerArgResult.get();
6183 TheCall->setArg(Arg: numArgs - 1, ArgExpr: PointerArg);
6184
6185 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6186 if (!pointerType) {
6187 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_nontemporal_builtin_must_be_pointer)
6188 << PointerArg->getType() << PointerArg->getSourceRange();
6189 return ExprError();
6190 }
6191
6192 QualType ValType = pointerType->getPointeeType();
6193
6194 // Strip any qualifiers off ValType.
6195 ValType = ValType.getUnqualifiedType();
6196 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6197 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6198 !ValType->isVectorType()) {
6199 Diag(Loc: DRE->getBeginLoc(),
6200 DiagID: diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6201 << PointerArg->getType() << PointerArg->getSourceRange();
6202 return ExprError();
6203 }
6204
6205 if (!isStore) {
6206 TheCall->setType(ValType);
6207 return TheCallResult;
6208 }
6209
6210 ExprResult ValArg = TheCall->getArg(Arg: 0);
6211 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6212 Context, Type: ValType, /*consume*/ Consumed: false);
6213 ValArg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: ValArg);
6214 if (ValArg.isInvalid())
6215 return ExprError();
6216
6217 TheCall->setArg(Arg: 0, ArgExpr: ValArg.get());
6218 TheCall->setType(Context.VoidTy);
6219 return TheCallResult;
6220}
6221
6222/// CheckObjCString - Checks that the format string argument to the os_log()
6223/// and os_trace() functions is correct, and converts it to const char *.
6224ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6225 Arg = Arg->IgnoreParenCasts();
6226 auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
6227 if (!Literal) {
6228 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Val: Arg)) {
6229 Literal = ObjcLiteral->getString();
6230 }
6231 }
6232
6233 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
6234 return ExprError(
6235 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_os_log_format_not_string_constant)
6236 << Arg->getSourceRange());
6237 }
6238
6239 ExprResult Result(Literal);
6240 QualType ResultTy = Context.getPointerType(T: Context.CharTy.withConst());
6241 InitializedEntity Entity =
6242 InitializedEntity::InitializeParameter(Context, Type: ResultTy, Consumed: false);
6243 Result = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Result);
6244 return Result;
6245}
6246
6247/// Check that the user is calling the appropriate va_start builtin for the
6248/// target and calling convention.
6249static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6250 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6251 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6252 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6253 TT.getArch() == llvm::Triple::aarch64_32);
6254 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
6255 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6256 if (IsX64 || IsAArch64) {
6257 CallingConv CC = CC_C;
6258 if (const FunctionDecl *FD = S.getCurFunctionDecl())
6259 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6260 if (IsMSVAStart) {
6261 // Don't allow this in System V ABI functions.
6262 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
6263 return S.Diag(Loc: Fn->getBeginLoc(),
6264 DiagID: diag::err_ms_va_start_used_in_sysv_function);
6265 } else {
6266 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6267 // On x64 Windows, don't allow this in System V ABI functions.
6268 // (Yes, that means there's no corresponding way to support variadic
6269 // System V ABI functions on Windows.)
6270 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
6271 (!IsWindowsOrUEFI && CC == CC_Win64))
6272 return S.Diag(Loc: Fn->getBeginLoc(),
6273 DiagID: diag::err_va_start_used_in_wrong_abi_function)
6274 << !IsWindowsOrUEFI;
6275 }
6276 return false;
6277 }
6278
6279 if (IsMSVAStart)
6280 return S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_builtin_x64_aarch64_only);
6281 return false;
6282}
6283
6284static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6285 ParmVarDecl **LastParam = nullptr) {
6286 // Determine whether the current function, block, or obj-c method is variadic
6287 // and get its parameter list.
6288 bool IsVariadic = false;
6289 ArrayRef<ParmVarDecl *> Params;
6290 DeclContext *Caller =
6291 S.CurContext->getEnclosingNonExpansionStatementContext();
6292 if (auto *Block = dyn_cast<BlockDecl>(Val: Caller)) {
6293 IsVariadic = Block->isVariadic();
6294 Params = Block->parameters();
6295 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: Caller)) {
6296 IsVariadic = FD->isVariadic();
6297 Params = FD->parameters();
6298 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Val: Caller)) {
6299 IsVariadic = MD->isVariadic();
6300 // FIXME: This isn't correct for methods (results in bogus warning).
6301 Params = MD->parameters();
6302 } else if (isa<CapturedDecl>(Val: Caller)) {
6303 // We don't support va_start in a CapturedDecl.
6304 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_captured_stmt);
6305 return true;
6306 } else {
6307 // This must be some other declcontext that parses exprs.
6308 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_outside_function);
6309 return true;
6310 }
6311
6312 if (!IsVariadic) {
6313 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_fixed_function);
6314 return true;
6315 }
6316
6317 if (LastParam)
6318 *LastParam = Params.empty() ? nullptr : Params.back();
6319
6320 return false;
6321}
6322
6323bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6324 Expr *Fn = TheCall->getCallee();
6325 if (checkVAStartABI(S&: *this, BuiltinID, Fn))
6326 return true;
6327
6328 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6329 // This builtin requires one argument (the va_list), allows two arguments,
6330 // but diagnoses more than two arguments. e.g.,
6331 // __builtin_c23_va_start(); // error
6332 // __builtin_c23_va_start(list); // ok
6333 // __builtin_c23_va_start(list, param); // ok
6334 // __builtin_c23_va_start(list, anything, anything); // error
6335 // This differs from the GCC behavior in that they accept the last case
6336 // with a warning, but it doesn't seem like a useful behavior to allow.
6337 if (checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
6338 return true;
6339 } else {
6340 // In C23 mode, va_start only needs one argument. However, the builtin still
6341 // requires two arguments (which matches the behavior of the GCC builtin),
6342 // <stdarg.h> passes `0` as the second argument in C23 mode.
6343 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6344 return true;
6345 }
6346
6347 // Type-check the first argument normally.
6348 if (checkBuiltinArgument(S&: *this, E: TheCall, ArgIndex: 0))
6349 return true;
6350
6351 // Check that the current function is variadic, and get its last parameter.
6352 ParmVarDecl *LastParam;
6353 if (checkVAStartIsInVariadicFunction(S&: *this, Fn, LastParam: &LastParam))
6354 return true;
6355
6356 // Verify that the second argument to the builtin is the last non-variadic
6357 // argument of the current function or method. In C23 mode, if the call is
6358 // not to __builtin_c23_va_start, and the second argument is an integer
6359 // constant expression with value 0, then we don't bother with this check.
6360 // For __builtin_c23_va_start, we only perform the check for the second
6361 // argument being the last argument to the current function if there is a
6362 // second argument present.
6363 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6364 TheCall->getNumArgs() < 2) {
6365 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
6366 return false;
6367 }
6368
6369 const Expr *Arg = TheCall->getArg(Arg: 1)->IgnoreParenCasts();
6370 if (std::optional<llvm::APSInt> Val =
6371 TheCall->getArg(Arg: 1)->getIntegerConstantExpr(Ctx: Context);
6372 Val && LangOpts.C23 && *Val == 0 &&
6373 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6374 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
6375 return false;
6376 }
6377
6378 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6379 // next block.
6380 QualType Type;
6381 SourceLocation ParamLoc;
6382 bool IsCRegister = false;
6383 bool SecondArgIsLastNonVariadicArgument = false;
6384 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: Arg)) {
6385 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: DR->getDecl())) {
6386 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6387
6388 Type = PV->getType();
6389 ParamLoc = PV->getLocation();
6390 IsCRegister =
6391 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6392 }
6393 }
6394
6395 if (!SecondArgIsLastNonVariadicArgument)
6396 Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
6397 DiagID: diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6398 else if (IsCRegister || Type->isReferenceType() ||
6399 Type->isSpecificBuiltinType(K: BuiltinType::Float) || [=] {
6400 // Promotable integers are UB, but enumerations need a bit of
6401 // extra checking to see what their promotable type actually is.
6402 if (!Context.isPromotableIntegerType(T: Type))
6403 return false;
6404 const auto *ED = Type->getAsEnumDecl();
6405 if (!ED)
6406 return true;
6407 return !Context.typesAreCompatible(T1: ED->getPromotionType(), T2: Type);
6408 }()) {
6409 unsigned Reason = 0;
6410 if (Type->isReferenceType()) Reason = 1;
6411 else if (IsCRegister) Reason = 2;
6412 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_va_start_type_is_undefined) << Reason;
6413 Diag(Loc: ParamLoc, DiagID: diag::note_parameter_type) << Type;
6414 }
6415
6416 return false;
6417}
6418
6419bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6420 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6421 const LangOptions &LO = getLangOpts();
6422
6423 if (LO.CPlusPlus)
6424 return Arg->getType()
6425 .getCanonicalType()
6426 .getTypePtr()
6427 ->getPointeeType()
6428 .withoutLocalFastQualifiers() == Context.CharTy;
6429
6430 // In C, allow aliasing through `char *`, this is required for AArch64 at
6431 // least.
6432 return true;
6433 };
6434
6435 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6436 // const char *named_addr);
6437
6438 Expr *Func = Call->getCallee();
6439
6440 if (Call->getNumArgs() < 3)
6441 return Diag(Loc: Call->getEndLoc(),
6442 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6443 << 0 /*function call*/ << 3 << Call->getNumArgs()
6444 << /*is non object*/ 0;
6445
6446 // Type-check the first argument normally.
6447 if (checkBuiltinArgument(S&: *this, E: Call, ArgIndex: 0))
6448 return true;
6449
6450 // Check that the current function is variadic.
6451 if (checkVAStartIsInVariadicFunction(S&: *this, Fn: Func))
6452 return true;
6453
6454 // __va_start on Windows does not validate the parameter qualifiers
6455
6456 const Expr *Arg1 = Call->getArg(Arg: 1)->IgnoreParens();
6457 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6458
6459 const Expr *Arg2 = Call->getArg(Arg: 2)->IgnoreParens();
6460 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6461
6462 const QualType &ConstCharPtrTy =
6463 Context.getPointerType(T: Context.CharTy.withConst());
6464 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6465 Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
6466 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6467 << 0 /* qualifier difference */
6468 << 3 /* parameter mismatch */
6469 << 2 << Arg1->getType() << ConstCharPtrTy;
6470
6471 const QualType SizeTy = Context.getSizeType();
6472 if (!Context.hasSameType(
6473 T1: Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers(),
6474 T2: SizeTy))
6475 Diag(Loc: Arg2->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
6476 << Arg2->getType() << SizeTy << 1 /* different class */
6477 << 0 /* qualifier difference */
6478 << 3 /* parameter mismatch */
6479 << 3 << Arg2->getType() << SizeTy;
6480
6481 return false;
6482}
6483
6484bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6485 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6486 return true;
6487
6488 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6489 TheCall->getFPFeaturesInEffect(LO: getLangOpts()).getNoHonorNaNs())
6490 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6491 << 1 << 0 << TheCall->getSourceRange();
6492
6493 ExprResult OrigArg0 = TheCall->getArg(Arg: 0);
6494 ExprResult OrigArg1 = TheCall->getArg(Arg: 1);
6495
6496 // Do standard promotions between the two arguments, returning their common
6497 // type.
6498 QualType Res = UsualArithmeticConversions(
6499 LHS&: OrigArg0, RHS&: OrigArg1, Loc: TheCall->getExprLoc(), ACK: ArithConvKind::Comparison);
6500 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6501 return true;
6502
6503 // Make sure any conversions are pushed back into the call; this is
6504 // type safe since unordered compare builtins are declared as "_Bool
6505 // foo(...)".
6506 TheCall->setArg(Arg: 0, ArgExpr: OrigArg0.get());
6507 TheCall->setArg(Arg: 1, ArgExpr: OrigArg1.get());
6508
6509 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6510 return false;
6511
6512 // If the common type isn't a real floating type, then the arguments were
6513 // invalid for this operation.
6514 if (Res.isNull() || !Res->isRealFloatingType())
6515 return Diag(Loc: OrigArg0.get()->getBeginLoc(),
6516 DiagID: diag::err_typecheck_call_invalid_ordered_compare)
6517 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6518 << SourceRange(OrigArg0.get()->getBeginLoc(),
6519 OrigArg1.get()->getEndLoc());
6520
6521 return false;
6522}
6523
6524bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6525 unsigned BuiltinID) {
6526 if (checkArgCount(Call: TheCall, DesiredArgCount: NumArgs))
6527 return true;
6528
6529 FPOptions FPO = TheCall->getFPFeaturesInEffect(LO: getLangOpts());
6530 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6531 BuiltinID == Builtin::BI__builtin_isinf ||
6532 BuiltinID == Builtin::BI__builtin_isinf_sign))
6533 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6534 << 0 << 0 << TheCall->getSourceRange();
6535
6536 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6537 BuiltinID == Builtin::BI__builtin_isunordered))
6538 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6539 << 1 << 0 << TheCall->getSourceRange();
6540
6541 bool IsFPClass = NumArgs == 2;
6542
6543 // Find out position of floating-point argument.
6544 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6545
6546 // We can count on all parameters preceding the floating-point just being int.
6547 // Try all of those.
6548 for (unsigned i = 0; i < FPArgNo; ++i) {
6549 Expr *Arg = TheCall->getArg(Arg: i);
6550
6551 if (Arg->isTypeDependent())
6552 return false;
6553
6554 ExprResult Res = PerformImplicitConversion(From: Arg, ToType: Context.IntTy,
6555 Action: AssignmentAction::Passing);
6556
6557 if (Res.isInvalid())
6558 return true;
6559 TheCall->setArg(Arg: i, ArgExpr: Res.get());
6560 }
6561
6562 Expr *OrigArg = TheCall->getArg(Arg: FPArgNo);
6563
6564 if (OrigArg->isTypeDependent())
6565 return false;
6566
6567 // We want to leave the type how it is, but do normal L->Rvalue conversions.
6568 ExprResult Res = DefaultFunctionArrayLvalueConversion(E: OrigArg);
6569 if (!Res.isUsable())
6570 return true;
6571 OrigArg = Res.get();
6572
6573 TheCall->setArg(Arg: FPArgNo, ArgExpr: OrigArg);
6574
6575 QualType VectorResultTy;
6576 QualType ElementTy = OrigArg->getType();
6577 // TODO: When all classification function are implemented with is_fpclass,
6578 // vector argument can be supported in all of them.
6579 if (ElementTy->isVectorType() && IsFPClass) {
6580 VectorResultTy = GetSignedVectorType(V: ElementTy);
6581 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6582 }
6583
6584 // This operation requires a non-_Complex floating-point number.
6585 if (!ElementTy->isRealFloatingType())
6586 return Diag(Loc: OrigArg->getBeginLoc(),
6587 DiagID: diag::err_typecheck_call_invalid_unary_fp)
6588 << OrigArg->getType() << OrigArg->getSourceRange();
6589
6590 // __builtin_isfpclass has integer parameter that specify test mask. It is
6591 // passed in (...), so it should be analyzed completely here.
6592 if (IsFPClass) {
6593 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: llvm::fcAllFlags))
6594 return true;
6595
6596 ExprResult MaskRes = PerformImplicitConversion(
6597 From: TheCall->getArg(Arg: NumArgs - 1), ToType: Context.IntTy, Action: AssignmentAction::Passing);
6598 if (!MaskRes.isUsable())
6599 return true;
6600 TheCall->setArg(Arg: NumArgs - 1, ArgExpr: MaskRes.get());
6601 }
6602
6603 // TODO: enable this code to all classification functions.
6604 if (IsFPClass) {
6605 QualType ResultTy;
6606 if (!VectorResultTy.isNull())
6607 ResultTy = VectorResultTy;
6608 else
6609 ResultTy = Context.IntTy;
6610 TheCall->setType(ResultTy);
6611 }
6612
6613 return false;
6614}
6615
6616bool Sema::BuiltinComplex(CallExpr *TheCall) {
6617 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6618 return true;
6619
6620 bool Dependent = false;
6621 for (unsigned I = 0; I != 2; ++I) {
6622 Expr *Arg = TheCall->getArg(Arg: I);
6623 QualType T = Arg->getType();
6624 if (T->isDependentType()) {
6625 Dependent = true;
6626 continue;
6627 }
6628
6629 // Despite supporting _Complex int, GCC requires a real floating point type
6630 // for the operands of __builtin_complex.
6631 if (!T->isRealFloatingType()) {
6632 return Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_typecheck_call_requires_real_fp)
6633 << Arg->getType() << Arg->getSourceRange();
6634 }
6635
6636 ExprResult Converted = DefaultLvalueConversion(E: Arg);
6637 if (Converted.isInvalid())
6638 return true;
6639 TheCall->setArg(Arg: I, ArgExpr: Converted.get());
6640 }
6641
6642 if (Dependent) {
6643 TheCall->setType(Context.DependentTy);
6644 return false;
6645 }
6646
6647 Expr *Real = TheCall->getArg(Arg: 0);
6648 Expr *Imag = TheCall->getArg(Arg: 1);
6649 if (!Context.hasSameType(T1: Real->getType(), T2: Imag->getType())) {
6650 return Diag(Loc: Real->getBeginLoc(),
6651 DiagID: diag::err_typecheck_call_different_arg_types)
6652 << Real->getType() << Imag->getType()
6653 << Real->getSourceRange() << Imag->getSourceRange();
6654 }
6655
6656 TheCall->setType(Context.getComplexType(T: Real->getType()));
6657 return false;
6658}
6659
6660/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6661// This is declared to take (...), so we have to check everything.
6662ExprResult Sema::BuiltinShuffleVector(CallExpr *TheCall) {
6663 unsigned NumArgs = TheCall->getNumArgs();
6664 if (NumArgs < 2)
6665 return ExprError(Diag(Loc: TheCall->getEndLoc(),
6666 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6667 << 0 /*function call*/ << 2 << NumArgs
6668 << /*is non object*/ 0 << TheCall->getSourceRange());
6669
6670 // Determine which of the following types of shufflevector we're checking:
6671 // 1) unary, vector mask: (lhs, mask)
6672 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6673 QualType ResType = TheCall->getArg(Arg: 0)->getType();
6674 unsigned NumElements = 0;
6675
6676 if (!TheCall->getArg(Arg: 0)->isTypeDependent() &&
6677 !TheCall->getArg(Arg: 1)->isTypeDependent()) {
6678 QualType LHSType = TheCall->getArg(Arg: 0)->getType();
6679 QualType RHSType = TheCall->getArg(Arg: 1)->getType();
6680
6681 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6682 return ExprError(
6683 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_builtin_non_vector)
6684 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6685 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6686 TheCall->getArg(Arg: 1)->getEndLoc()));
6687
6688 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6689 unsigned NumResElements = NumArgs - 2;
6690
6691 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6692 // with mask. If so, verify that RHS is an integer vector type with the
6693 // same number of elts as lhs.
6694 if (NumArgs == 2) {
6695 auto *RHSVecType = RHSType->castAs<VectorType>();
6696 if (RHSVecType->getElementType()->isBooleanType() ||
6697 !RHSVecType->getElementType()->isIntegerType()) {
6698 return ExprError(
6699 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
6700 << /* Arg ordinal */ 2 << /*vector of*/ 4 << /*integer*/ 1
6701 << /*no fp*/ 0 << RHSType
6702 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6703 TheCall->getArg(Arg: 1)->getEndLoc()));
6704 }
6705
6706 if (RHSVecType->getNumElements() != NumElements)
6707 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6708 DiagID: diag::err_typecheck_vector_lengths_not_equal)
6709 << LHSType << RHSType << /*isMoreThanTwoArgs*/ false
6710 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
6711 TheCall->getArg(Arg: 1)->getEndLoc()));
6712 } else if (!Context.hasSameUnqualifiedType(T1: LHSType, T2: RHSType)) {
6713 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6714 DiagID: diag::err_vec_builtin_incompatible_vector)
6715 << TheCall->getDirectCallee()
6716 << /*isMoreThanTwoArgs*/ false
6717 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6718 TheCall->getArg(Arg: 1)->getEndLoc()));
6719 } else if (NumElements != NumResElements) {
6720 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6721 ResType = ResType->isExtVectorType()
6722 ? Context.getExtVectorType(VectorType: EltType, NumElts: NumResElements)
6723 : Context.getVectorType(VectorType: EltType, NumElts: NumResElements,
6724 VecKind: VectorKind::Generic);
6725 }
6726 }
6727
6728 for (unsigned I = 2; I != NumArgs; ++I) {
6729 Expr *Arg = TheCall->getArg(Arg: I);
6730 if (Arg->isTypeDependent() || Arg->isValueDependent())
6731 continue;
6732
6733 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
6734 if (!Result)
6735 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6736 DiagID: diag::err_shufflevector_nonconstant_argument)
6737 << Arg->getSourceRange());
6738
6739 // Allow -1 which will be translated to undef in the IR.
6740 if (Result->isSigned() && Result->isAllOnes())
6741 ;
6742 else if (Result->getActiveBits() > 64 ||
6743 Result->getZExtValue() >= NumElements * 2)
6744 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6745 DiagID: diag::err_shufflevector_argument_too_large)
6746 << Arg->getSourceRange());
6747
6748 TheCall->setArg(Arg: I, ArgExpr: ConstantExpr::Create(Context, E: Arg, Result: APValue(*Result)));
6749 }
6750
6751 auto *Result = new (Context) ShuffleVectorExpr(
6752 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6753 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6754
6755 // All moved to Result.
6756 TheCall->shrinkNumArgs(NewNumArgs: 0);
6757 return Result;
6758}
6759
6760ExprResult Sema::ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6761 SourceLocation BuiltinLoc,
6762 SourceLocation RParenLoc) {
6763 ExprValueKind VK = VK_PRValue;
6764 ExprObjectKind OK = OK_Ordinary;
6765 QualType DstTy = TInfo->getType();
6766 QualType SrcTy = E->getType();
6767
6768 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6769 return ExprError(Diag(Loc: BuiltinLoc,
6770 DiagID: diag::err_convertvector_non_vector)
6771 << E->getSourceRange());
6772 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6773 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_builtin_non_vector_type)
6774 << "second"
6775 << "__builtin_convertvector");
6776
6777 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6778 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6779 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6780 if (SrcElts != DstElts)
6781 return ExprError(Diag(Loc: BuiltinLoc,
6782 DiagID: diag::err_convertvector_incompatible_vector)
6783 << E->getSourceRange());
6784 }
6785
6786 return ConvertVectorExpr::Create(C: Context, SrcExpr: E, TI: TInfo, DstType: DstTy, VK, OK, BuiltinLoc,
6787 RParenLoc, FPFeatures: CurFPFeatureOverrides());
6788}
6789
6790bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6791 unsigned NumArgs = TheCall->getNumArgs();
6792
6793 if (NumArgs > 3)
6794 return Diag(Loc: TheCall->getEndLoc(),
6795 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6796 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6797 << TheCall->getSourceRange();
6798
6799 // Argument 0 is checked for us and the remaining arguments must be
6800 // constant integers.
6801 for (unsigned i = 1; i != NumArgs; ++i) {
6802 if (convertArgumentToType(Value&: TheCall->getArgs()[i], Ty: Context.IntTy))
6803 return true;
6804 if (BuiltinConstantArgRange(TheCall, ArgNum: i, Low: 0, High: i == 1 ? 1 : 3))
6805 return true;
6806 }
6807
6808 return false;
6809}
6810
6811bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6812 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6813 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
6814 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6815 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
6816 return true;
6817 Expr *Arg = TheCall->getArg(Arg: 0);
6818 if (Arg->isInstantiationDependent())
6819 return false;
6820
6821 QualType ArgTy = Arg->getType();
6822 if (!ArgTy->hasFloatingRepresentation())
6823 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_expect_flt_or_vector)
6824 << ArgTy;
6825 if (Arg->isLValue()) {
6826 ExprResult FirstArg = DefaultLvalueConversion(E: Arg);
6827 TheCall->setArg(Arg: 0, ArgExpr: FirstArg.get());
6828 }
6829 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
6830 return false;
6831}
6832
6833bool Sema::BuiltinAssume(CallExpr *TheCall) {
6834 Expr *Arg = TheCall->getArg(Arg: 0);
6835 if (Arg->isInstantiationDependent()) return false;
6836
6837 if (Arg->HasSideEffects(Ctx: Context))
6838 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_assume_side_effects)
6839 << Arg->getSourceRange()
6840 << cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getIdentifier();
6841
6842 return false;
6843}
6844
6845bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6846 // The alignment must be a constant integer.
6847 Expr *Arg = TheCall->getArg(Arg: 1);
6848
6849 // We can't check the value of a dependent argument.
6850 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6851 if (const auto *UE =
6852 dyn_cast<UnaryExprOrTypeTraitExpr>(Val: Arg->IgnoreParenImpCasts()))
6853 if (UE->getKind() == UETT_AlignOf ||
6854 UE->getKind() == UETT_PreferredAlignOf)
6855 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca_align_alignof)
6856 << Arg->getSourceRange();
6857
6858 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Ctx: Context);
6859
6860 if (!Result.isPowerOf2())
6861 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6862 << Arg->getSourceRange();
6863
6864 if (Result < Context.getCharWidth())
6865 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_small)
6866 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6867
6868 if (Result > std::numeric_limits<int32_t>::max())
6869 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_big)
6870 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6871 }
6872
6873 return false;
6874}
6875
6876bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6877 if (checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
6878 return true;
6879
6880 unsigned NumArgs = TheCall->getNumArgs();
6881 Expr *FirstArg = TheCall->getArg(Arg: 0);
6882
6883 {
6884 ExprResult FirstArgResult =
6885 DefaultFunctionArrayLvalueConversion(E: FirstArg);
6886 if (!FirstArgResult.get()->getType()->isPointerType()) {
6887 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_assume_aligned_invalid_arg)
6888 << TheCall->getSourceRange();
6889 return true;
6890 }
6891 TheCall->setArg(Arg: 0, ArgExpr: FirstArgResult.get());
6892 }
6893
6894 // The alignment must be a constant integer.
6895 Expr *SecondArg = TheCall->getArg(Arg: 1);
6896
6897 // We can't check the value of a dependent argument.
6898 if (!SecondArg->isValueDependent()) {
6899 llvm::APSInt Result;
6900 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
6901 return true;
6902
6903 if (!Result.isPowerOf2())
6904 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6905 << SecondArg->getSourceRange();
6906
6907 if (Result > Sema::MaximumAlignment)
6908 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_assume_aligned_too_great)
6909 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6910
6911 TheCall->setArg(Arg: 1,
6912 ArgExpr: ConstantExpr::Create(Context, E: SecondArg, Result: APValue(Result)));
6913 }
6914
6915 if (NumArgs > 2) {
6916 Expr *ThirdArg = TheCall->getArg(Arg: 2);
6917 if (convertArgumentToType(Value&: ThirdArg, Ty: Context.getSizeType()))
6918 return true;
6919 TheCall->setArg(Arg: 2, ArgExpr: ThirdArg);
6920 }
6921
6922 return false;
6923}
6924
6925bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6926 unsigned BuiltinID =
6927 cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getBuiltinID();
6928 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6929
6930 unsigned NumArgs = TheCall->getNumArgs();
6931 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6932 if (NumArgs < NumRequiredArgs) {
6933 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args)
6934 << 0 /* function call */ << NumRequiredArgs << NumArgs
6935 << /*is non object*/ 0 << TheCall->getSourceRange();
6936 }
6937 if (NumArgs >= NumRequiredArgs + 0x100) {
6938 return Diag(Loc: TheCall->getEndLoc(),
6939 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6940 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6941 << /*is non object*/ 0 << TheCall->getSourceRange();
6942 }
6943 unsigned i = 0;
6944
6945 // For formatting call, check buffer arg.
6946 if (!IsSizeCall) {
6947 ExprResult Arg(TheCall->getArg(Arg: i));
6948 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6949 Context, Type: Context.VoidPtrTy, Consumed: false);
6950 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
6951 if (Arg.isInvalid())
6952 return true;
6953 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6954 i++;
6955 }
6956
6957 // Check string literal arg.
6958 unsigned FormatIdx = i;
6959 {
6960 ExprResult Arg = CheckOSLogFormatStringArg(Arg: TheCall->getArg(Arg: i));
6961 if (Arg.isInvalid())
6962 return true;
6963 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6964 i++;
6965 }
6966
6967 // Make sure variadic args are scalar.
6968 unsigned FirstDataArg = i;
6969 while (i < NumArgs) {
6970 ExprResult Arg = DefaultVariadicArgumentPromotion(
6971 E: TheCall->getArg(Arg: i), CT: VariadicCallType::Function, FDecl: nullptr);
6972 if (Arg.isInvalid())
6973 return true;
6974 CharUnits ArgSize = Context.getTypeSizeInChars(T: Arg.get()->getType());
6975 if (ArgSize.getQuantity() >= 0x100) {
6976 return Diag(Loc: Arg.get()->getEndLoc(), DiagID: diag::err_os_log_argument_too_big)
6977 << i << (int)ArgSize.getQuantity() << 0xff
6978 << TheCall->getSourceRange();
6979 }
6980 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6981 i++;
6982 }
6983
6984 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6985 // call to avoid duplicate diagnostics.
6986 if (!IsSizeCall) {
6987 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6988 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6989 bool Success = CheckFormatArguments(
6990 Args, FAPK: FAPK_Variadic, ReferenceFormatString: nullptr, format_idx: FormatIdx, firstDataArg: FirstDataArg,
6991 Type: FormatStringType::OSLog, CallType: VariadicCallType::Function,
6992 Loc: TheCall->getBeginLoc(), range: SourceRange(), CheckedVarArgs);
6993 if (!Success)
6994 return true;
6995 }
6996
6997 if (IsSizeCall) {
6998 TheCall->setType(Context.getSizeType());
6999 } else {
7000 TheCall->setType(Context.VoidPtrTy);
7001 }
7002 return false;
7003}
7004
7005bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
7006 llvm::APSInt &Result) {
7007 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7008
7009 if (Arg->isTypeDependent() || Arg->isValueDependent())
7010 return false;
7011
7012 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Ctx: Context);
7013 if (!R) {
7014 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
7015 auto *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
7016 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_constant_integer_arg_type)
7017 << FDecl->getDeclName() << Arg->getSourceRange();
7018 }
7019 Result = *R;
7020
7021 return false;
7022}
7023
7024bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
7025 int High, bool RangeIsError) {
7026 if (isConstantEvaluatedContext())
7027 return false;
7028 llvm::APSInt Result;
7029
7030 // We can't check the value of a dependent argument.
7031 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7032 if (Arg->isTypeDependent() || Arg->isValueDependent())
7033 return false;
7034
7035 // Check constant-ness first.
7036 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7037 return true;
7038
7039 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7040 if (RangeIsError)
7041 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_invalid_range)
7042 << toString(I: Result, Radix: 10) << Low << High << Arg->getSourceRange();
7043 else
7044 // Defer the warning until we know if the code will be emitted so that
7045 // dead code can ignore this.
7046 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
7047 PD: PDiag(DiagID: diag::warn_argument_invalid_range)
7048 << toString(I: Result, Radix: 10) << Low << High
7049 << Arg->getSourceRange());
7050 }
7051
7052 return false;
7053}
7054
7055bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
7056 unsigned Num) {
7057 llvm::APSInt Result;
7058
7059 // We can't check the value of a dependent argument.
7060 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7061 if (Arg->isTypeDependent() || Arg->isValueDependent())
7062 return false;
7063
7064 // Check constant-ness first.
7065 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7066 return true;
7067
7068 if (Result.getSExtValue() % Num != 0)
7069 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_multiple)
7070 << Num << Arg->getSourceRange();
7071
7072 return false;
7073}
7074
7075bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
7076 llvm::APSInt Result;
7077
7078 // We can't check the value of a dependent argument.
7079 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7080 if (Arg->isTypeDependent() || Arg->isValueDependent())
7081 return false;
7082
7083 // Check constant-ness first.
7084 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7085 return true;
7086
7087 if (Result.isPowerOf2())
7088 return false;
7089
7090 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_power_of_2)
7091 << Arg->getSourceRange();
7092}
7093
7094static bool IsShiftedByte(llvm::APSInt Value) {
7095 if (Value.isNegative())
7096 return false;
7097
7098 // Check if it's a shifted byte, by shifting it down
7099 while (true) {
7100 // If the value fits in the bottom byte, the check passes.
7101 if (Value < 0x100)
7102 return true;
7103
7104 // Otherwise, if the value has _any_ bits in the bottom byte, the check
7105 // fails.
7106 if ((Value & 0xFF) != 0)
7107 return false;
7108
7109 // If the bottom 8 bits are all 0, but something above that is nonzero,
7110 // then shifting the value right by 8 bits won't affect whether it's a
7111 // shifted byte or not. So do that, and go round again.
7112 Value >>= 8;
7113 }
7114}
7115
7116bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
7117 unsigned ArgBits) {
7118 llvm::APSInt Result;
7119
7120 // We can't check the value of a dependent argument.
7121 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7122 if (Arg->isTypeDependent() || Arg->isValueDependent())
7123 return false;
7124
7125 // Check constant-ness first.
7126 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7127 return true;
7128
7129 // Truncate to the given size.
7130 Result = Result.getLoBits(numBits: ArgBits);
7131 Result.setIsUnsigned(true);
7132
7133 if (IsShiftedByte(Value: Result))
7134 return false;
7135
7136 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_shifted_byte)
7137 << Arg->getSourceRange();
7138}
7139
7140bool Sema::BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7141 unsigned ArgNum,
7142 unsigned ArgBits) {
7143 llvm::APSInt Result;
7144
7145 // We can't check the value of a dependent argument.
7146 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7147 if (Arg->isTypeDependent() || Arg->isValueDependent())
7148 return false;
7149
7150 // Check constant-ness first.
7151 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7152 return true;
7153
7154 // Truncate to the given size.
7155 Result = Result.getLoBits(numBits: ArgBits);
7156 Result.setIsUnsigned(true);
7157
7158 // Check to see if it's in either of the required forms.
7159 if (IsShiftedByte(Value: Result) ||
7160 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7161 return false;
7162
7163 return Diag(Loc: TheCall->getBeginLoc(),
7164 DiagID: diag::err_argument_not_shifted_byte_or_xxff)
7165 << Arg->getSourceRange();
7166}
7167
7168bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
7169 if (!Context.getTargetInfo().hasSjLjLowering())
7170 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_unsupported)
7171 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7172
7173 Expr *Arg = TheCall->getArg(Arg: 1);
7174 llvm::APSInt Result;
7175
7176 // TODO: This is less than ideal. Overload this to take a value.
7177 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
7178 return true;
7179
7180 if (Result != 1)
7181 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_invalid_val)
7182 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7183
7184 return false;
7185}
7186
7187bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
7188 if (!Context.getTargetInfo().hasSjLjLowering())
7189 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_setjmp_unsupported)
7190 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7191 return false;
7192}
7193
7194bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
7195 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
7196 return true;
7197
7198 ExprResult ArgRes = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
7199 if (ArgRes.isInvalid())
7200 return true;
7201
7202 // For simplicity, we support only limited expressions for the argument.
7203 // Specifically a flexible array member or a pointer with counted_by:
7204 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
7205 // complex casting, which really shouldn't be a huge problem.
7206 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
7207 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
7208 return Diag(Loc: Arg->getBeginLoc(),
7209 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7210 << Arg->getSourceRange();
7211
7212 if (Arg->HasSideEffects(Ctx: Context))
7213 return Diag(Loc: Arg->getBeginLoc(),
7214 DiagID: diag::err_builtin_counted_by_ref_has_side_effects)
7215 << Arg->getSourceRange();
7216
7217 if (const auto *ME = dyn_cast<MemberExpr>(Val: Arg)) {
7218 const auto *CATy =
7219 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
7220
7221 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
7222 // Member has counted_by attribute - return pointer to count field
7223 const auto *MemberDecl = cast<FieldDecl>(Val: ME->getMemberDecl());
7224 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
7225 TheCall->setType(Context.getPointerType(T: CountFD->getType()));
7226 return false;
7227 }
7228 }
7229
7230 // FAMs and pointers without counted_by return void*
7231 QualType MemberTy = ME->getMemberDecl()->getType();
7232 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
7233 return Diag(Loc: Arg->getBeginLoc(),
7234 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7235 << Arg->getSourceRange();
7236 } else {
7237 return Diag(Loc: Arg->getBeginLoc(),
7238 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7239 << Arg->getSourceRange();
7240 }
7241
7242 TheCall->setType(Context.getPointerType(T: Context.VoidTy));
7243 return false;
7244}
7245
7246/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
7247/// It allows leaking and modification of bounds safety information.
7248bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
7249 BuiltinCountedByRefKind K) {
7250 const CallExpr *CE =
7251 E ? dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts()) : nullptr;
7252 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
7253 return false;
7254
7255 switch (K) {
7256 case BuiltinCountedByRefKind::Assignment:
7257 case BuiltinCountedByRefKind::Initializer:
7258 Diag(Loc: E->getExprLoc(),
7259 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7260 << 0 << E->getSourceRange();
7261 break;
7262 case BuiltinCountedByRefKind::FunctionArg:
7263 Diag(Loc: E->getExprLoc(),
7264 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7265 << 1 << E->getSourceRange();
7266 break;
7267 case BuiltinCountedByRefKind::ReturnArg:
7268 Diag(Loc: E->getExprLoc(),
7269 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7270 << 2 << E->getSourceRange();
7271 break;
7272 case BuiltinCountedByRefKind::ArraySubscript:
7273 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
7274 << 0 << E->getSourceRange();
7275 break;
7276 case BuiltinCountedByRefKind::BinaryExpr:
7277 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
7278 << 1 << E->getSourceRange();
7279 break;
7280 }
7281
7282 return true;
7283}
7284
7285namespace {
7286
7287class UncoveredArgHandler {
7288 enum { Unknown = -1, AllCovered = -2 };
7289
7290 signed FirstUncoveredArg = Unknown;
7291 SmallVector<const Expr *, 4> DiagnosticExprs;
7292
7293public:
7294 UncoveredArgHandler() = default;
7295
7296 bool hasUncoveredArg() const {
7297 return (FirstUncoveredArg >= 0);
7298 }
7299
7300 unsigned getUncoveredArg() const {
7301 assert(hasUncoveredArg() && "no uncovered argument");
7302 return FirstUncoveredArg;
7303 }
7304
7305 void setAllCovered() {
7306 // A string has been found with all arguments covered, so clear out
7307 // the diagnostics.
7308 DiagnosticExprs.clear();
7309 FirstUncoveredArg = AllCovered;
7310 }
7311
7312 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7313 assert(NewFirstUncoveredArg >= 0 && "Outside range");
7314
7315 // Don't update if a previous string covers all arguments.
7316 if (FirstUncoveredArg == AllCovered)
7317 return;
7318
7319 // UncoveredArgHandler tracks the highest uncovered argument index
7320 // and with it all the strings that match this index.
7321 if (NewFirstUncoveredArg == FirstUncoveredArg)
7322 DiagnosticExprs.push_back(Elt: StrExpr);
7323 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7324 DiagnosticExprs.clear();
7325 DiagnosticExprs.push_back(Elt: StrExpr);
7326 FirstUncoveredArg = NewFirstUncoveredArg;
7327 }
7328 }
7329
7330 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7331};
7332
7333enum StringLiteralCheckType {
7334 SLCT_NotALiteral,
7335 SLCT_UncheckedLiteral,
7336 SLCT_CheckedLiteral
7337};
7338
7339} // namespace
7340
7341static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7342 BinaryOperatorKind BinOpKind,
7343 bool AddendIsRight) {
7344 unsigned BitWidth = Offset.getBitWidth();
7345 unsigned AddendBitWidth = Addend.getBitWidth();
7346 // There might be negative interim results.
7347 if (Addend.isUnsigned()) {
7348 Addend = Addend.zext(width: ++AddendBitWidth);
7349 Addend.setIsSigned(true);
7350 }
7351 // Adjust the bit width of the APSInts.
7352 if (AddendBitWidth > BitWidth) {
7353 Offset = Offset.sext(width: AddendBitWidth);
7354 BitWidth = AddendBitWidth;
7355 } else if (BitWidth > AddendBitWidth) {
7356 Addend = Addend.sext(width: BitWidth);
7357 }
7358
7359 bool Ov = false;
7360 llvm::APSInt ResOffset = Offset;
7361 if (BinOpKind == BO_Add)
7362 ResOffset = Offset.sadd_ov(RHS: Addend, Overflow&: Ov);
7363 else {
7364 assert(AddendIsRight && BinOpKind == BO_Sub &&
7365 "operator must be add or sub with addend on the right");
7366 ResOffset = Offset.ssub_ov(RHS: Addend, Overflow&: Ov);
7367 }
7368
7369 // We add an offset to a pointer here so we should support an offset as big as
7370 // possible.
7371 if (Ov) {
7372 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7373 "index (intermediate) result too big");
7374 Offset = Offset.sext(width: 2 * BitWidth);
7375 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7376 return;
7377 }
7378
7379 Offset = std::move(ResOffset);
7380}
7381
7382namespace {
7383
7384// This is a wrapper class around StringLiteral to support offsetted string
7385// literals as format strings. It takes the offset into account when returning
7386// the string and its length or the source locations to display notes correctly.
7387class FormatStringLiteral {
7388 const StringLiteral *FExpr;
7389 int64_t Offset;
7390
7391public:
7392 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7393 : FExpr(fexpr), Offset(Offset) {}
7394
7395 const StringLiteral *getFormatString() const { return FExpr; }
7396
7397 StringRef getString() const { return FExpr->getString().drop_front(N: Offset); }
7398
7399 unsigned getByteLength() const {
7400 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7401 }
7402
7403 unsigned getLength() const { return FExpr->getLength() - Offset; }
7404 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7405
7406 StringLiteralKind getKind() const { return FExpr->getKind(); }
7407
7408 QualType getType() const { return FExpr->getType(); }
7409
7410 bool isAscii() const { return FExpr->isOrdinary(); }
7411 bool isWide() const { return FExpr->isWide(); }
7412 bool isUTF8() const { return FExpr->isUTF8(); }
7413 bool isUTF16() const { return FExpr->isUTF16(); }
7414 bool isUTF32() const { return FExpr->isUTF32(); }
7415 bool isPascal() const { return FExpr->isPascal(); }
7416
7417 SourceLocation getLocationOfByte(
7418 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7419 const TargetInfo &Target, unsigned *StartToken = nullptr,
7420 unsigned *StartTokenByteOffset = nullptr) const {
7421 return FExpr->getLocationOfByte(ByteNo: ByteNo + Offset, SM, Features, Target,
7422 StartToken, StartTokenByteOffset);
7423 }
7424
7425 SourceLocation getBeginLoc() const LLVM_READONLY {
7426 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7427 }
7428
7429 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7430};
7431
7432} // namespace
7433
7434static void CheckFormatString(
7435 Sema &S, const FormatStringLiteral *FExpr,
7436 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7437 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
7438 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7439 bool inFunctionCall, VariadicCallType CallType,
7440 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7441 bool IgnoreStringsWithoutSpecifiers);
7442
7443static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7444 const Expr *E);
7445
7446// Determine if an expression is a string literal or constant string.
7447// If this function returns false on the arguments to a function expecting a
7448// format string, we will usually need to emit a warning.
7449// True string literals are then checked by CheckFormatString.
7450static StringLiteralCheckType
7451checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7452 const Expr *E, ArrayRef<const Expr *> Args,
7453 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7454 unsigned firstDataArg, FormatStringType Type,
7455 VariadicCallType CallType, bool InFunctionCall,
7456 llvm::SmallBitVector &CheckedVarArgs,
7457 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7458 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7459 bool IgnoreStringsWithoutSpecifiers = false) {
7460 if (S.isConstantEvaluatedContext())
7461 return SLCT_NotALiteral;
7462tryAgain:
7463 assert(Offset.isSigned() && "invalid offset");
7464
7465 if (E->isTypeDependent() || E->isValueDependent())
7466 return SLCT_NotALiteral;
7467
7468 E = E->IgnoreParenCasts();
7469
7470 if (E->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull))
7471 // Technically -Wformat-nonliteral does not warn about this case.
7472 // The behavior of printf and friends in this case is implementation
7473 // dependent. Ideally if the format string cannot be null then
7474 // it should have a 'nonnull' attribute in the function prototype.
7475 return SLCT_UncheckedLiteral;
7476
7477 switch (E->getStmtClass()) {
7478 case Stmt::InitListExprClass:
7479 // Handle expressions like {"foobar"}.
7480 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E)) {
7481 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7482 format_idx, firstDataArg, Type, CallType,
7483 /*InFunctionCall*/ false, CheckedVarArgs,
7484 UncoveredArg, Offset, CallerFormatParamIdx,
7485 IgnoreStringsWithoutSpecifiers);
7486 }
7487 return SLCT_NotALiteral;
7488 case Stmt::BinaryConditionalOperatorClass:
7489 case Stmt::ConditionalOperatorClass: {
7490 // The expression is a literal if both sub-expressions were, and it was
7491 // completely checked only if both sub-expressions were checked.
7492 const AbstractConditionalOperator *C =
7493 cast<AbstractConditionalOperator>(Val: E);
7494
7495 // Determine whether it is necessary to check both sub-expressions, for
7496 // example, because the condition expression is a constant that can be
7497 // evaluated at compile time.
7498 bool CheckLeft = true, CheckRight = true;
7499
7500 bool Cond;
7501 if (C->getCond()->EvaluateAsBooleanCondition(
7502 Result&: Cond, Ctx: S.getASTContext(), InConstantContext: S.isConstantEvaluatedContext())) {
7503 if (Cond)
7504 CheckRight = false;
7505 else
7506 CheckLeft = false;
7507 }
7508
7509 // We need to maintain the offsets for the right and the left hand side
7510 // separately to check if every possible indexed expression is a valid
7511 // string literal. They might have different offsets for different string
7512 // literals in the end.
7513 StringLiteralCheckType Left;
7514 if (!CheckLeft)
7515 Left = SLCT_UncheckedLiteral;
7516 else {
7517 Left = checkFormatStringExpr(S, ReferenceFormatString, E: C->getTrueExpr(),
7518 Args, APK, format_idx, firstDataArg, Type,
7519 CallType, InFunctionCall, CheckedVarArgs,
7520 UncoveredArg, Offset, CallerFormatParamIdx,
7521 IgnoreStringsWithoutSpecifiers);
7522 if (Left == SLCT_NotALiteral || !CheckRight) {
7523 return Left;
7524 }
7525 }
7526
7527 StringLiteralCheckType Right = checkFormatStringExpr(
7528 S, ReferenceFormatString, E: C->getFalseExpr(), Args, APK, format_idx,
7529 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7530 UncoveredArg, Offset, CallerFormatParamIdx,
7531 IgnoreStringsWithoutSpecifiers);
7532
7533 return (CheckLeft && Left < Right) ? Left : Right;
7534 }
7535
7536 case Stmt::ImplicitCastExprClass:
7537 E = cast<ImplicitCastExpr>(Val: E)->getSubExpr();
7538 goto tryAgain;
7539
7540 case Stmt::OpaqueValueExprClass:
7541 if (const Expr *src = cast<OpaqueValueExpr>(Val: E)->getSourceExpr()) {
7542 E = src;
7543 goto tryAgain;
7544 }
7545 return SLCT_NotALiteral;
7546
7547 case Stmt::PredefinedExprClass:
7548 // While __func__, etc., are technically not string literals, they
7549 // cannot contain format specifiers and thus are not a security
7550 // liability.
7551 return SLCT_UncheckedLiteral;
7552
7553 case Stmt::DeclRefExprClass: {
7554 const DeclRefExpr *DR = cast<DeclRefExpr>(Val: E);
7555
7556 // As an exception, do not flag errors for variables binding to
7557 // const string literals.
7558 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: DR->getDecl())) {
7559 bool isConstant = false;
7560 QualType T = DR->getType();
7561
7562 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7563 isConstant = AT->getElementType().isConstant(Ctx: S.Context);
7564 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7565 isConstant = T.isConstant(Ctx: S.Context) &&
7566 PT->getPointeeType().isConstant(Ctx: S.Context);
7567 } else if (T->isObjCObjectPointerType()) {
7568 // In ObjC, there is usually no "const ObjectPointer" type,
7569 // so don't check if the pointee type is constant.
7570 isConstant = T.isConstant(Ctx: S.Context);
7571 }
7572
7573 if (isConstant) {
7574 if (const Expr *Init = VD->getAnyInitializer()) {
7575 // Look through initializers like const char c[] = { "foo" }
7576 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
7577 if (InitList->isStringLiteralInit())
7578 Init = InitList->getInit(Init: 0)->IgnoreParenImpCasts();
7579 }
7580 return checkFormatStringExpr(
7581 S, ReferenceFormatString, E: Init, Args, APK, format_idx,
7582 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7583 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7584 }
7585 }
7586
7587 // When the format argument is an argument of this function, and this
7588 // function also has the format attribute, there are several interactions
7589 // for which there shouldn't be a warning. For instance, when calling
7590 // v*printf from a function that has the printf format attribute, we
7591 // should not emit a warning about using `fmt`, even though it's not
7592 // constant, because the arguments have already been checked for the
7593 // caller of `logmessage`:
7594 //
7595 // __attribute__((format(printf, 1, 2)))
7596 // void logmessage(char const *fmt, ...) {
7597 // va_list ap;
7598 // va_start(ap, fmt);
7599 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7600 // ...
7601 // }
7602 //
7603 // Another interaction that we need to support is using a format string
7604 // specified by the format_matches attribute:
7605 //
7606 // __attribute__((format_matches(printf, 1, "%s %d")))
7607 // void logmessage(char const *fmt, const char *a, int b) {
7608 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7609 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7610 // ...
7611 // }
7612 //
7613 // Yet another interaction that we need to support is calling a variadic
7614 // format function from a format function that has fixed arguments. For
7615 // instance:
7616 //
7617 // __attribute__((format(printf, 1, 2)))
7618 // void logstring(char const *fmt, char const *str) {
7619 // printf(fmt, str); /* do not emit a warning about "fmt" */
7620 // }
7621 //
7622 // Same (and perhaps more relatably) for the variadic template case:
7623 //
7624 // template<typename... Args>
7625 // __attribute__((format(printf, 1, 2)))
7626 // void log(const char *fmt, Args&&... args) {
7627 // printf(fmt, forward<Args>(args)...);
7628 // /* do not emit a warning about "fmt" */
7629 // }
7630 //
7631 // Due to implementation difficulty, we only check the format, not the
7632 // format arguments, in all cases.
7633 //
7634 if (const auto *PV = dyn_cast<ParmVarDecl>(Val: VD)) {
7635 if (CallerFormatParamIdx)
7636 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7637 if (const auto *D = dyn_cast<Decl>(Val: PV->getDeclContext())) {
7638 for (const auto *PVFormatMatches :
7639 D->specific_attrs<FormatMatchesAttr>()) {
7640 Sema::FormatStringInfo CalleeFSI;
7641 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormatMatches->getFormatIdx(),
7642 FirstArg: 0, FSI: &CalleeFSI))
7643 continue;
7644 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7645 // If using the wrong type of format string, emit a diagnostic
7646 // here and stop checking to avoid irrelevant diagnostics.
7647 if (Type != S.GetFormatStringType(Format: PVFormatMatches)) {
7648 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7649 DiagID: diag::warn_format_string_type_incompatible)
7650 << PVFormatMatches->getType()->getName()
7651 << S.GetFormatStringTypeName(FST: Type);
7652 if (!InFunctionCall) {
7653 S.Diag(Loc: PVFormatMatches->getFormatString()->getBeginLoc(),
7654 DiagID: diag::note_format_string_defined);
7655 }
7656 return SLCT_UncheckedLiteral;
7657 }
7658 return checkFormatStringExpr(
7659 S, ReferenceFormatString, E: PVFormatMatches->getFormatString(),
7660 Args, APK, format_idx, firstDataArg, Type, CallType,
7661 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7662 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7663 }
7664 }
7665
7666 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7667 Sema::FormatStringInfo CallerFSI;
7668 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormat->getFormatIdx(),
7669 FirstArg: PVFormat->getFirstArg(), FSI: &CallerFSI))
7670 continue;
7671 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7672 // We also check if the formats are compatible.
7673 // We can't pass a 'scanf' string to a 'printf' function.
7674 if (Type != S.GetFormatStringType(Format: PVFormat)) {
7675 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7676 DiagID: diag::warn_format_string_type_incompatible)
7677 << PVFormat->getType()->getName()
7678 << S.GetFormatStringTypeName(FST: Type);
7679 if (!InFunctionCall) {
7680 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_format_string_defined);
7681 }
7682 return SLCT_UncheckedLiteral;
7683 }
7684 // Lastly, check that argument passing kinds transition in a
7685 // way that makes sense:
7686 // from a caller with FAPK_VAList, allow FAPK_VAList
7687 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7688 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7689 // from a caller with FAPK_Variadic, allow FAPK_VAList
7690 switch (combineFAPK(A: CallerFSI.ArgPassingKind, B: APK)) {
7691 case combineFAPK(A: Sema::FAPK_VAList, B: Sema::FAPK_VAList):
7692 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Fixed):
7693 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Variadic):
7694 case combineFAPK(A: Sema::FAPK_Variadic, B: Sema::FAPK_VAList):
7695 return SLCT_UncheckedLiteral;
7696 }
7697 }
7698 }
7699 }
7700 }
7701 }
7702
7703 return SLCT_NotALiteral;
7704 }
7705
7706 case Stmt::CallExprClass:
7707 case Stmt::CXXMemberCallExprClass: {
7708 const CallExpr *CE = cast<CallExpr>(Val: E);
7709 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Val: CE->getCalleeDecl())) {
7710 bool IsFirst = true;
7711 StringLiteralCheckType CommonResult;
7712 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7713 const Expr *Arg = CE->getArg(Arg: FA->getFormatIdx().getASTIndex());
7714 StringLiteralCheckType Result = checkFormatStringExpr(
7715 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7716 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7717 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7718 if (IsFirst) {
7719 CommonResult = Result;
7720 IsFirst = false;
7721 }
7722 }
7723 if (!IsFirst)
7724 return CommonResult;
7725
7726 if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) {
7727 unsigned BuiltinID = FD->getBuiltinID();
7728 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7729 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7730 const Expr *Arg = CE->getArg(Arg: 0);
7731 return checkFormatStringExpr(
7732 S, ReferenceFormatString, E: Arg, Args, APK, format_idx,
7733 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7734 UncoveredArg, Offset, CallerFormatParamIdx,
7735 IgnoreStringsWithoutSpecifiers);
7736 }
7737 }
7738 }
7739 if (const Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E))
7740 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7741 format_idx, firstDataArg, Type, CallType,
7742 /*InFunctionCall*/ false, CheckedVarArgs,
7743 UncoveredArg, Offset, CallerFormatParamIdx,
7744 IgnoreStringsWithoutSpecifiers);
7745 return SLCT_NotALiteral;
7746 }
7747 case Stmt::ObjCMessageExprClass: {
7748 const auto *ME = cast<ObjCMessageExpr>(Val: E);
7749 if (const auto *MD = ME->getMethodDecl()) {
7750 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7751 // As a special case heuristic, if we're using the method -[NSBundle
7752 // localizedStringForKey:value:table:], ignore any key strings that lack
7753 // format specifiers. The idea is that if the key doesn't have any
7754 // format specifiers then its probably just a key to map to the
7755 // localized strings. If it does have format specifiers though, then its
7756 // likely that the text of the key is the format string in the
7757 // programmer's language, and should be checked.
7758 const ObjCInterfaceDecl *IFace;
7759 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7760 IFace->getIdentifier()->isStr(Str: "NSBundle") &&
7761 MD->getSelector().isKeywordSelector(
7762 Names: {"localizedStringForKey", "value", "table"})) {
7763 IgnoreStringsWithoutSpecifiers = true;
7764 }
7765
7766 const Expr *Arg = ME->getArg(Arg: FA->getFormatIdx().getASTIndex());
7767 return checkFormatStringExpr(
7768 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7769 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7770 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7771 }
7772 }
7773
7774 return SLCT_NotALiteral;
7775 }
7776 case Stmt::ObjCStringLiteralClass:
7777 case Stmt::StringLiteralClass: {
7778 const StringLiteral *StrE = nullptr;
7779
7780 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(Val: E))
7781 StrE = ObjCFExpr->getString();
7782 else
7783 StrE = cast<StringLiteral>(Val: E);
7784
7785 if (StrE) {
7786 if (Offset.isNegative() || Offset > StrE->getLength()) {
7787 // TODO: It would be better to have an explicit warning for out of
7788 // bounds literals.
7789 return SLCT_NotALiteral;
7790 }
7791 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(width: 64).getSExtValue());
7792 CheckFormatString(S, FExpr: &FStr, ReferenceFormatString, OrigFormatExpr: E, Args, APK,
7793 format_idx, firstDataArg, Type, inFunctionCall: InFunctionCall,
7794 CallType, CheckedVarArgs, UncoveredArg,
7795 IgnoreStringsWithoutSpecifiers);
7796 return SLCT_CheckedLiteral;
7797 }
7798
7799 return SLCT_NotALiteral;
7800 }
7801 case Stmt::BinaryOperatorClass: {
7802 const BinaryOperator *BinOp = cast<BinaryOperator>(Val: E);
7803
7804 // A string literal + an int offset is still a string literal.
7805 if (BinOp->isAdditiveOp()) {
7806 Expr::EvalResult LResult, RResult;
7807
7808 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7809 Result&: LResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7810 InConstantContext: S.isConstantEvaluatedContext());
7811 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7812 Result&: RResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7813 InConstantContext: S.isConstantEvaluatedContext());
7814
7815 if (LIsInt != RIsInt) {
7816 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7817
7818 if (LIsInt) {
7819 if (BinOpKind == BO_Add) {
7820 sumOffsets(Offset, Addend: LResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7821 E = BinOp->getRHS();
7822 goto tryAgain;
7823 }
7824 } else {
7825 sumOffsets(Offset, Addend: RResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7826 E = BinOp->getLHS();
7827 goto tryAgain;
7828 }
7829 }
7830 }
7831
7832 return SLCT_NotALiteral;
7833 }
7834 case Stmt::UnaryOperatorClass: {
7835 const UnaryOperator *UnaOp = cast<UnaryOperator>(Val: E);
7836 auto ASE = dyn_cast<ArraySubscriptExpr>(Val: UnaOp->getSubExpr());
7837 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7838 Expr::EvalResult IndexResult;
7839 if (ASE->getRHS()->EvaluateAsInt(Result&: IndexResult, Ctx: S.Context,
7840 AllowSideEffects: Expr::SE_NoSideEffects,
7841 InConstantContext: S.isConstantEvaluatedContext())) {
7842 sumOffsets(Offset, Addend: IndexResult.Val.getInt(), BinOpKind: BO_Add,
7843 /*RHS is int*/ AddendIsRight: true);
7844 E = ASE->getBase();
7845 goto tryAgain;
7846 }
7847 }
7848
7849 return SLCT_NotALiteral;
7850 }
7851
7852 default:
7853 return SLCT_NotALiteral;
7854 }
7855}
7856
7857// If this expression can be evaluated at compile-time,
7858// check if the result is a StringLiteral and return it
7859// otherwise return nullptr
7860static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7861 const Expr *E) {
7862 Expr::EvalResult Result;
7863 if (E->EvaluateAsRValue(Result, Ctx: Context) && Result.Val.isLValue()) {
7864 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7865 if (isa_and_nonnull<StringLiteral>(Val: LVE))
7866 return LVE;
7867 }
7868 return nullptr;
7869}
7870
7871StringRef Sema::GetFormatStringTypeName(FormatStringType FST) {
7872 switch (FST) {
7873 case FormatStringType::Scanf:
7874 return "scanf";
7875 case FormatStringType::Printf:
7876 return "printf";
7877 case FormatStringType::NSString:
7878 return "NSString";
7879 case FormatStringType::Strftime:
7880 return "strftime";
7881 case FormatStringType::Strfmon:
7882 return "strfmon";
7883 case FormatStringType::Kprintf:
7884 return "kprintf";
7885 case FormatStringType::FreeBSDKPrintf:
7886 return "freebsd_kprintf";
7887 case FormatStringType::OSLog:
7888 return "os_log";
7889 default:
7890 return "<unknown>";
7891 }
7892}
7893
7894FormatStringType Sema::GetFormatStringType(StringRef Flavor) {
7895 return llvm::StringSwitch<FormatStringType>(Flavor)
7896 .Cases(CaseStrings: {"gnu_scanf", "scanf"}, Value: FormatStringType::Scanf)
7897 .Cases(CaseStrings: {"gnu_printf", "printf", "printf0", "syslog"},
7898 Value: FormatStringType::Printf)
7899 .Cases(CaseStrings: {"NSString", "CFString"}, Value: FormatStringType::NSString)
7900 .Cases(CaseStrings: {"gnu_strftime", "strftime"}, Value: FormatStringType::Strftime)
7901 .Cases(CaseStrings: {"gnu_strfmon", "strfmon"}, Value: FormatStringType::Strfmon)
7902 .Cases(CaseStrings: {"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7903 Value: FormatStringType::Kprintf)
7904 .Case(S: "freebsd_kprintf", Value: FormatStringType::FreeBSDKPrintf)
7905 .Case(S: "os_trace", Value: FormatStringType::OSLog)
7906 .Case(S: "os_log", Value: FormatStringType::OSLog)
7907 .Default(Value: FormatStringType::Unknown);
7908}
7909
7910FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7911 return GetFormatStringType(Flavor: Format->getType()->getName());
7912}
7913
7914FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7915 return GetFormatStringType(Flavor: Format->getType()->getName());
7916}
7917
7918bool Sema::CheckFormatArguments(const FormatAttr *Format,
7919 ArrayRef<const Expr *> Args, bool IsCXXMember,
7920 VariadicCallType CallType, SourceLocation Loc,
7921 SourceRange Range,
7922 llvm::SmallBitVector &CheckedVarArgs) {
7923 FormatStringInfo FSI;
7924 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: Format->getFirstArg(),
7925 HasImplicitThisParam: IsCXXMember,
7926 IsVariadic: CallType != VariadicCallType::DoesNotApply, FSI: &FSI))
7927 return CheckFormatArguments(
7928 Args, FAPK: FSI.ArgPassingKind, ReferenceFormatString: nullptr, format_idx: FSI.FormatIdx, firstDataArg: FSI.FirstDataArg,
7929 Type: GetFormatStringType(Format), CallType, Loc, range: Range, CheckedVarArgs);
7930 return false;
7931}
7932
7933bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7934 ArrayRef<const Expr *> Args, bool IsCXXMember,
7935 VariadicCallType CallType, SourceLocation Loc,
7936 SourceRange Range,
7937 llvm::SmallBitVector &CheckedVarArgs) {
7938 FormatStringInfo FSI;
7939 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: 0, HasImplicitThisParam: IsCXXMember, IsVariadic: false,
7940 FSI: &FSI)) {
7941 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7942 return CheckFormatArguments(Args, FAPK: FSI.ArgPassingKind,
7943 ReferenceFormatString: Format->getFormatString(), format_idx: FSI.FormatIdx,
7944 firstDataArg: FSI.FirstDataArg, Type: GetFormatStringType(Format),
7945 CallType, Loc, range: Range, CheckedVarArgs);
7946 }
7947 return false;
7948}
7949
7950static bool CheckMissingFormatAttribute(
7951 Sema *S, ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
7952 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7953 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7954 SourceLocation Loc) {
7955 if (S->getDiagnostics().isIgnored(DiagID: diag::warn_missing_format_attribute, Loc))
7956 return false;
7957
7958 DeclContext *DC = S->CurContext->getEnclosingNonExpansionStatementContext();
7959 if (!isa<ObjCMethodDecl>(Val: DC) && !isa<FunctionDecl>(Val: DC) && !isa<BlockDecl>(Val: DC))
7960 return false;
7961 Decl *Caller = cast<Decl>(Val: DC)->getCanonicalDecl();
7962
7963 unsigned NumCallerParams = getFunctionOrMethodNumParams(D: Caller);
7964
7965 // Find the offset to convert between attribute and parameter indexes.
7966 unsigned CallerArgumentIndexOffset =
7967 hasImplicitObjectParameter(D: Caller) ? 2 : 1;
7968
7969 unsigned FirstArgumentIndex = -1;
7970 switch (APK) {
7971 case Sema::FormatArgumentPassingKind::FAPK_Fixed:
7972 case Sema::FormatArgumentPassingKind::FAPK_Variadic: {
7973 // As an extension, clang allows the format attribute on non-variadic
7974 // functions.
7975 // Caller must have fixed arguments to pass them to a fixed or variadic
7976 // function. Try to match caller and callee arguments. If successful, then
7977 // emit a diag with the caller idx, otherwise we can't determine the callee
7978 // arguments.
7979 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7980 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7981 // There aren't enough arguments in the caller to pass to callee.
7982 return false;
7983 }
7984 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7985 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7986 const auto *Arg =
7987 dyn_cast<DeclRefExpr>(Val: Args[CalleeIdx]->IgnoreParenCasts());
7988 if (!Arg)
7989 return false;
7990 const auto *Param = dyn_cast<ParmVarDecl>(Val: Arg->getDecl());
7991 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7992 return false;
7993 }
7994 FirstArgumentIndex =
7995 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7996 break;
7997 }
7998 case Sema::FormatArgumentPassingKind::FAPK_VAList:
7999 // Caller arguments are either variadic or a va_list.
8000 FirstArgumentIndex = isFunctionOrMethodVariadic(D: Caller)
8001 ? (NumCallerParams + CallerArgumentIndexOffset)
8002 : 0;
8003 break;
8004 case Sema::FormatArgumentPassingKind::FAPK_Elsewhere:
8005 // The callee has a format_matches attribute. We will emit that instead.
8006 if (!ReferenceFormatString)
8007 return false;
8008 break;
8009 }
8010
8011 // Emit the diagnostic and fixit.
8012 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
8013 StringRef FormatTypeName = S->GetFormatStringTypeName(FST: FormatType);
8014 NamedDecl *ND = dyn_cast<NamedDecl>(Val: Caller);
8015 do {
8016 std::string Attr, Fixit;
8017 llvm::raw_string_ostream AttrOS(Attr);
8018 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
8019 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
8020 << FirstArgumentIndex << ")";
8021 } else {
8022 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
8023 << ", \"";
8024 AttrOS.write_escaped(Str: ReferenceFormatString->getString());
8025 AttrOS << "\")";
8026 }
8027 AttrOS.flush();
8028 auto DB = S->Diag(Loc, DiagID: diag::warn_missing_format_attribute) << Attr;
8029 if (ND)
8030 DB << ND;
8031 else
8032 DB << "block";
8033
8034 // Blocks don't provide a correct end loc, so skip emitting a fixit.
8035 if (isa<BlockDecl>(Val: Caller))
8036 break;
8037
8038 SourceLocation SL;
8039 llvm::raw_string_ostream IS(Fixit);
8040 // The attribute goes at the start of the declaration in C/C++ functions
8041 // and methods, but after the declaration for Objective-C methods.
8042 if (isa<ObjCMethodDecl>(Val: Caller)) {
8043 IS << ' ';
8044 SL = Caller->getEndLoc();
8045 }
8046 const LangOptions &LO = S->getLangOpts();
8047 if (LO.C23 || LO.CPlusPlus11)
8048 IS << "[[gnu::" << Attr << "]]";
8049 else if (LO.ObjC || LO.GNUMode)
8050 IS << "__attribute__((" << Attr << "))";
8051 else
8052 break;
8053 if (!isa<ObjCMethodDecl>(Val: Caller)) {
8054 IS << ' ';
8055 SL = Caller->getBeginLoc();
8056 }
8057 IS.flush();
8058
8059 DB << FixItHint::CreateInsertion(InsertionLoc: SL, Code: Fixit);
8060 } while (false);
8061
8062 // Add implicit format or format_matches attribute.
8063 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
8064 Caller->addAttr(A: FormatAttr::CreateImplicit(
8065 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
8066 FormatIdx: FormatStringIndex, FirstArg: FirstArgumentIndex));
8067 } else {
8068 Caller->addAttr(A: FormatMatchesAttr::CreateImplicit(
8069 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
8070 FormatIdx: FormatStringIndex, ExpectedFormat: ReferenceFormatString));
8071 }
8072
8073 {
8074 auto DB = S->Diag(Loc: Caller->getLocation(), DiagID: diag::note_entity_declared_at);
8075 if (ND)
8076 DB << ND;
8077 else
8078 DB << "block";
8079 }
8080 return true;
8081}
8082
8083bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8084 Sema::FormatArgumentPassingKind APK,
8085 StringLiteral *ReferenceFormatString,
8086 unsigned format_idx, unsigned firstDataArg,
8087 FormatStringType Type,
8088 VariadicCallType CallType, SourceLocation Loc,
8089 SourceRange Range,
8090 llvm::SmallBitVector &CheckedVarArgs) {
8091 // CHECK: printf/scanf-like function is called with no format string.
8092 if (format_idx >= Args.size()) {
8093 Diag(Loc, DiagID: diag::warn_missing_format_string) << Range;
8094 return false;
8095 }
8096
8097 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8098
8099 // CHECK: format string is not a string literal.
8100 //
8101 // Dynamically generated format strings are difficult to
8102 // automatically vet at compile time. Requiring that format strings
8103 // are string literals: (1) permits the checking of format strings by
8104 // the compiler and thereby (2) can practically remove the source of
8105 // many format string exploits.
8106
8107 // Format string can be either ObjC string (e.g. @"%d") or
8108 // C string (e.g. "%d")
8109 // ObjC string uses the same format specifiers as C string, so we can use
8110 // the same format string checking logic for both ObjC and C strings.
8111 UncoveredArgHandler UncoveredArg;
8112 std::optional<unsigned> CallerParamIdx;
8113 StringLiteralCheckType CT = checkFormatStringExpr(
8114 S&: *this, ReferenceFormatString, E: OrigFormatExpr, Args, APK, format_idx,
8115 firstDataArg, Type, CallType,
8116 /*IsFunctionCall*/ InFunctionCall: true, CheckedVarArgs, UncoveredArg,
8117 /*no string offset*/ Offset: llvm::APSInt(64, false) = 0, CallerFormatParamIdx: &CallerParamIdx);
8118
8119 // Generate a diagnostic where an uncovered argument is detected.
8120 if (UncoveredArg.hasUncoveredArg()) {
8121 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8122 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8123 UncoveredArg.Diagnose(S&: *this, /*IsFunctionCall*/true, ArgExpr: Args[ArgIdx]);
8124 }
8125
8126 if (CT != SLCT_NotALiteral)
8127 // Literal format string found, check done!
8128 return CT == SLCT_CheckedLiteral;
8129
8130 // Do not emit diag when the string param is a macro expansion and the
8131 // format is either NSString or CFString. This is a hack to prevent
8132 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8133 // which are usually used in place of NS and CF string literals.
8134 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8135 if (Type == FormatStringType::NSString &&
8136 SourceMgr.isInSystemMacro(loc: FormatLoc))
8137 return false;
8138
8139 if (CallerParamIdx && CheckMissingFormatAttribute(
8140 S: this, Args, APK, ReferenceFormatString, FormatIdx: format_idx,
8141 FirstDataArg: firstDataArg, FormatType: Type, CallerParamIdx: *CallerParamIdx, Loc))
8142 return false;
8143
8144 // Strftime is particular as it always uses a single 'time' argument,
8145 // so it is safe to pass a non-literal string.
8146 if (Type == FormatStringType::Strftime)
8147 return false;
8148
8149 // If there are no arguments specified, warn with -Wformat-security, otherwise
8150 // warn only with -Wformat-nonliteral.
8151 if (Args.size() == firstDataArg) {
8152 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral_noargs)
8153 << OrigFormatExpr->getSourceRange();
8154 switch (Type) {
8155 default:
8156 break;
8157 case FormatStringType::Kprintf:
8158 case FormatStringType::FreeBSDKPrintf:
8159 case FormatStringType::Printf:
8160 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
8161 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "\"%s\", ");
8162 break;
8163 case FormatStringType::NSString:
8164 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
8165 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "@\"%@\", ");
8166 break;
8167 }
8168 } else {
8169 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral)
8170 << OrigFormatExpr->getSourceRange();
8171 }
8172 return false;
8173}
8174
8175namespace {
8176
8177class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8178protected:
8179 Sema &S;
8180 const FormatStringLiteral *FExpr;
8181 const Expr *OrigFormatExpr;
8182 const FormatStringType FSType;
8183 const unsigned FirstDataArg;
8184 const unsigned NumDataArgs;
8185 const char *Beg; // Start of format string.
8186 const Sema::FormatArgumentPassingKind ArgPassingKind;
8187 ArrayRef<const Expr *> Args;
8188 unsigned FormatIdx;
8189 llvm::SmallBitVector CoveredArgs;
8190 bool usesPositionalArgs = false;
8191 bool atFirstArg = true;
8192 bool inFunctionCall;
8193 VariadicCallType CallType;
8194 llvm::SmallBitVector &CheckedVarArgs;
8195 UncoveredArgHandler &UncoveredArg;
8196
8197public:
8198 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8199 const Expr *origFormatExpr, const FormatStringType type,
8200 unsigned firstDataArg, unsigned numDataArgs,
8201 const char *beg, Sema::FormatArgumentPassingKind APK,
8202 ArrayRef<const Expr *> Args, unsigned formatIdx,
8203 bool inFunctionCall, VariadicCallType callType,
8204 llvm::SmallBitVector &CheckedVarArgs,
8205 UncoveredArgHandler &UncoveredArg)
8206 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8207 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8208 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
8209 inFunctionCall(inFunctionCall), CallType(callType),
8210 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8211 CoveredArgs.resize(N: numDataArgs);
8212 CoveredArgs.reset();
8213 }
8214
8215 bool HasFormatArguments() const {
8216 return ArgPassingKind == Sema::FAPK_Fixed ||
8217 ArgPassingKind == Sema::FAPK_Variadic;
8218 }
8219
8220 void DoneProcessing();
8221
8222 void HandleIncompleteSpecifier(const char *startSpecifier,
8223 unsigned specifierLen) override;
8224
8225 void HandleInvalidLengthModifier(
8226 const analyze_format_string::FormatSpecifier &FS,
8227 const analyze_format_string::ConversionSpecifier &CS,
8228 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
8229
8230 void HandleNonStandardLengthModifier(
8231 const analyze_format_string::FormatSpecifier &FS,
8232 const char *startSpecifier, unsigned specifierLen);
8233
8234 void HandleNonStandardConversionSpecifier(
8235 const analyze_format_string::ConversionSpecifier &CS,
8236 const char *startSpecifier, unsigned specifierLen);
8237
8238 void HandlePosition(const char *startPos, unsigned posLen) override;
8239
8240 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
8241 analyze_format_string::PositionContext p) override;
8242
8243 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8244
8245 void HandleNullChar(const char *nullCharacter) override;
8246
8247 template <typename Range>
8248 static void
8249 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8250 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8251 bool IsStringLocation, Range StringRange,
8252 ArrayRef<FixItHint> Fixit = {});
8253
8254protected:
8255 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8256 const char *startSpec,
8257 unsigned specifierLen,
8258 const char *csStart, unsigned csLen);
8259
8260 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8261 const char *startSpec,
8262 unsigned specifierLen);
8263
8264 SourceRange getFormatStringRange();
8265 CharSourceRange getSpecifierRange(const char *startSpecifier,
8266 unsigned specifierLen);
8267 SourceLocation getLocationOfByte(const char *x);
8268
8269 const Expr *getDataArg(unsigned i) const;
8270
8271 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8272 const analyze_format_string::ConversionSpecifier &CS,
8273 const char *startSpecifier, unsigned specifierLen,
8274 unsigned argIndex);
8275
8276 bool CheckUnsupportedType(const analyze_format_string::ArgType &AT,
8277 const Expr *E, const char *startSpecifier,
8278 unsigned specifierLen);
8279
8280 template <typename Range>
8281 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8282 bool IsStringLocation, Range StringRange,
8283 ArrayRef<FixItHint> Fixit = {});
8284};
8285
8286} // namespace
8287
8288SourceRange CheckFormatHandler::getFormatStringRange() {
8289 return OrigFormatExpr->getSourceRange();
8290}
8291
8292CharSourceRange
8293CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
8294 unsigned specifierLen) {
8295 SourceLocation Start = getLocationOfByte(x: startSpecifier);
8296 SourceLocation End = getLocationOfByte(x: startSpecifier + specifierLen - 1);
8297
8298 // Advance the end SourceLocation by one due to half-open ranges.
8299 End = End.getLocWithOffset(Offset: 1);
8300
8301 return CharSourceRange::getCharRange(B: Start, E: End);
8302}
8303
8304SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8305 return FExpr->getLocationOfByte(ByteNo: x - Beg, SM: S.getSourceManager(),
8306 Features: S.getLangOpts(), Target: S.Context.getTargetInfo());
8307}
8308
8309void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8310 unsigned specifierLen) {
8311 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_incomplete_specifier),
8312 Loc: getLocationOfByte(x: startSpecifier),
8313 /*IsStringLocation*/ true,
8314 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8315}
8316
8317bool CheckFormatHandler::CheckUnsupportedType(
8318 const analyze_format_string::ArgType &AT, const Expr *E,
8319 const char *StartSpecifier, unsigned SpecifierLen) {
8320 if (!AT.isUnsupported())
8321 return false;
8322
8323 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_unsupported_type)
8324 << AT.getRepresentativeTypeName(C&: S.Context),
8325 Loc: E->getExprLoc(), /*IsStringLocation=*/false,
8326 StringRange: getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen));
8327 return true;
8328}
8329
8330void CheckFormatHandler::HandleInvalidLengthModifier(
8331 const analyze_format_string::FormatSpecifier &FS,
8332 const analyze_format_string::ConversionSpecifier &CS,
8333 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8334 using namespace analyze_format_string;
8335
8336 const LengthModifier &LM = FS.getLengthModifier();
8337 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
8338
8339 // See if we know how to fix this length modifier.
8340 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8341 if (FixedLM) {
8342 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
8343 Loc: getLocationOfByte(x: LM.getStart()),
8344 /*IsStringLocation*/ true,
8345 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8346
8347 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
8348 << FixedLM->toString()
8349 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
8350
8351 } else {
8352 FixItHint Hint;
8353 if (DiagID == diag::warn_format_nonsensical_length)
8354 Hint = FixItHint::CreateRemoval(RemoveRange: LMRange);
8355
8356 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
8357 Loc: getLocationOfByte(x: LM.getStart()),
8358 /*IsStringLocation*/ true,
8359 StringRange: getSpecifierRange(startSpecifier, specifierLen), FixIt: Hint);
8360 }
8361}
8362
8363void CheckFormatHandler::HandleNonStandardLengthModifier(
8364 const analyze_format_string::FormatSpecifier &FS,
8365 const char *startSpecifier, unsigned specifierLen) {
8366 using namespace analyze_format_string;
8367
8368 const LengthModifier &LM = FS.getLengthModifier();
8369 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
8370
8371 // See if we know how to fix this length modifier.
8372 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8373 if (FixedLM) {
8374 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8375 << LM.toString() << 0,
8376 Loc: getLocationOfByte(x: LM.getStart()),
8377 /*IsStringLocation*/ true,
8378 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8379
8380 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
8381 << FixedLM->toString()
8382 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
8383
8384 } else {
8385 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8386 << LM.toString() << 0,
8387 Loc: getLocationOfByte(x: LM.getStart()),
8388 /*IsStringLocation*/ true,
8389 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8390 }
8391}
8392
8393void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8394 const analyze_format_string::ConversionSpecifier &CS,
8395 const char *startSpecifier, unsigned specifierLen) {
8396 using namespace analyze_format_string;
8397
8398 // See if we know how to fix this conversion specifier.
8399 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8400 if (FixedCS) {
8401 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8402 << CS.toString() << /*conversion specifier*/ 1,
8403 Loc: getLocationOfByte(x: CS.getStart()),
8404 /*IsStringLocation*/ true,
8405 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8406
8407 CharSourceRange CSRange = getSpecifierRange(startSpecifier: CS.getStart(), specifierLen: CS.getLength());
8408 S.Diag(Loc: getLocationOfByte(x: CS.getStart()), DiagID: diag::note_format_fix_specifier)
8409 << FixedCS->toString()
8410 << FixItHint::CreateReplacement(RemoveRange: CSRange, Code: FixedCS->toString());
8411 } else {
8412 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8413 << CS.toString() << /*conversion specifier*/ 1,
8414 Loc: getLocationOfByte(x: CS.getStart()),
8415 /*IsStringLocation*/ true,
8416 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8417 }
8418}
8419
8420void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8421 if (!S.getDiagnostics().isIgnored(
8422 DiagID: diag::warn_format_non_standard_positional_arg, Loc: SourceLocation()))
8423 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard_positional_arg),
8424 Loc: getLocationOfByte(x: startPos),
8425 /*IsStringLocation*/ true,
8426 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
8427}
8428
8429void CheckFormatHandler::HandleInvalidPosition(
8430 const char *startSpecifier, unsigned specifierLen,
8431 analyze_format_string::PositionContext p) {
8432 if (!S.getDiagnostics().isIgnored(
8433 DiagID: diag::warn_format_invalid_positional_specifier, Loc: SourceLocation()))
8434 EmitFormatDiagnostic(
8435 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8436 Loc: getLocationOfByte(x: startSpecifier), /*IsStringLocation*/ true,
8437 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8438}
8439
8440void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8441 unsigned posLen) {
8442 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_format_zero_positional_specifier,
8443 Loc: SourceLocation()))
8444 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_zero_positional_specifier),
8445 Loc: getLocationOfByte(x: startPos),
8446 /*IsStringLocation*/ true,
8447 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
8448}
8449
8450void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8451 if (!isa<ObjCStringLiteral>(Val: OrigFormatExpr)) {
8452 // The presence of a null character is likely an error.
8453 EmitFormatDiagnostic(
8454 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_contains_null_char),
8455 Loc: getLocationOfByte(x: nullCharacter), /*IsStringLocation*/ true,
8456 StringRange: getFormatStringRange());
8457 }
8458}
8459
8460// Note that this may return NULL if there was an error parsing or building
8461// one of the argument expressions.
8462const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8463 return Args[FirstDataArg + i];
8464}
8465
8466void CheckFormatHandler::DoneProcessing() {
8467 // Does the number of data arguments exceed the number of
8468 // format conversions in the format string?
8469 if (HasFormatArguments()) {
8470 // Find any arguments that weren't covered.
8471 CoveredArgs.flip();
8472 signed notCoveredArg = CoveredArgs.find_first();
8473 if (notCoveredArg >= 0) {
8474 assert((unsigned)notCoveredArg < NumDataArgs);
8475 UncoveredArg.Update(NewFirstUncoveredArg: notCoveredArg, StrExpr: OrigFormatExpr);
8476 } else {
8477 UncoveredArg.setAllCovered();
8478 }
8479 }
8480}
8481
8482void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8483 const Expr *ArgExpr) {
8484 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8485
8486 if (!ArgExpr)
8487 return;
8488
8489 SourceLocation Loc = ArgExpr->getBeginLoc();
8490
8491 if (S.getSourceManager().isInSystemMacro(loc: Loc))
8492 return;
8493
8494 PartialDiagnostic PDiag = S.PDiag(DiagID: diag::warn_printf_data_arg_not_used);
8495 for (auto E : DiagnosticExprs)
8496 PDiag << E->getSourceRange();
8497
8498 CheckFormatHandler::EmitFormatDiagnostic(
8499 S, InFunctionCall: IsFunctionCall, ArgumentExpr: DiagnosticExprs[0], PDiag, Loc,
8500 /*IsStringLocation*/ false, StringRange: DiagnosticExprs[0]->getSourceRange());
8501}
8502
8503bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8504 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8505 unsigned specifierLen, const char *csStart, unsigned csLen) {
8506 bool keepGoing = true;
8507 if (argIndex < NumDataArgs) {
8508 // Consider the argument coverered, even though the specifier doesn't
8509 // make sense.
8510 CoveredArgs.set(argIndex);
8511 } else {
8512 // If argIndex exceeds the number of data arguments we
8513 // don't issue a warning because that is just a cascade of warnings (and
8514 // they may have intended '%%' anyway). We don't want to continue processing
8515 // the format string after this point, however, as we will like just get
8516 // gibberish when trying to match arguments.
8517 keepGoing = false;
8518 }
8519
8520 StringRef Specifier(csStart, csLen);
8521
8522 // If the specifier in non-printable, it could be the first byte of a UTF-8
8523 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8524 // hex value.
8525 std::string CodePointStr;
8526 if (!llvm::sys::locale::isPrint(c: *csStart)) {
8527 llvm::UTF32 CodePoint;
8528 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8529 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8530 llvm::ConversionResult Result =
8531 llvm::convertUTF8Sequence(source: B, sourceEnd: E, target: &CodePoint, flags: llvm::strictConversion);
8532
8533 if (Result != llvm::conversionOK) {
8534 unsigned char FirstChar = *csStart;
8535 CodePoint = (llvm::UTF32)FirstChar;
8536 }
8537
8538 llvm::raw_string_ostream OS(CodePointStr);
8539 if (CodePoint < 256)
8540 OS << "\\x" << llvm::format(Fmt: "%02x", Vals: CodePoint);
8541 else if (CodePoint <= 0xFFFF)
8542 OS << "\\u" << llvm::format(Fmt: "%04x", Vals: CodePoint);
8543 else
8544 OS << "\\U" << llvm::format(Fmt: "%08x", Vals: CodePoint);
8545 Specifier = CodePointStr;
8546 }
8547
8548 EmitFormatDiagnostic(
8549 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_conversion) << Specifier, Loc,
8550 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
8551
8552 return keepGoing;
8553}
8554
8555void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8556 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8557 EmitFormatDiagnostic(
8558 PDiag: S.PDiag(DiagID: diag::warn_format_mix_positional_nonpositional_args), Loc,
8559 /*isStringLoc*/ IsStringLocation: true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
8560}
8561
8562bool CheckFormatHandler::CheckNumArgs(
8563 const analyze_format_string::FormatSpecifier &FS,
8564 const analyze_format_string::ConversionSpecifier &CS,
8565 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8566
8567 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8568 PartialDiagnostic PDiag =
8569 FS.usesPositionalArg()
8570 ? (S.PDiag(DiagID: diag::warn_printf_positional_arg_exceeds_data_args)
8571 << (argIndex + 1) << NumDataArgs)
8572 : S.PDiag(DiagID: diag::warn_printf_insufficient_data_args);
8573 EmitFormatDiagnostic(PDiag, Loc: getLocationOfByte(x: CS.getStart()),
8574 /*IsStringLocation*/ true,
8575 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8576
8577 // Since more arguments than conversion tokens are given, by extension
8578 // all arguments are covered, so mark this as so.
8579 UncoveredArg.setAllCovered();
8580 return false;
8581 }
8582 return true;
8583}
8584
8585template <typename Range>
8586void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8587 SourceLocation Loc,
8588 bool IsStringLocation,
8589 Range StringRange,
8590 ArrayRef<FixItHint> FixIt) {
8591 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8592 IsStringLocation, StringRange, FixIt);
8593}
8594
8595/// If the format string is not within the function call, emit a note
8596/// so that the function call and string are in diagnostic messages.
8597///
8598/// \param InFunctionCall if true, the format string is within the function
8599/// call and only one diagnostic message will be produced. Otherwise, an
8600/// extra note will be emitted pointing to location of the format string.
8601///
8602/// \param ArgumentExpr the expression that is passed as the format string
8603/// argument in the function call. Used for getting locations when two
8604/// diagnostics are emitted.
8605///
8606/// \param PDiag the callee should already have provided any strings for the
8607/// diagnostic message. This function only adds locations and fixits
8608/// to diagnostics.
8609///
8610/// \param Loc primary location for diagnostic. If two diagnostics are
8611/// required, one will be at Loc and a new SourceLocation will be created for
8612/// the other one.
8613///
8614/// \param IsStringLocation if true, Loc points to the format string should be
8615/// used for the note. Otherwise, Loc points to the argument list and will
8616/// be used with PDiag.
8617///
8618/// \param StringRange some or all of the string to highlight. This is
8619/// templated so it can accept either a CharSourceRange or a SourceRange.
8620///
8621/// \param FixIt optional fix it hint for the format string.
8622template <typename Range>
8623void CheckFormatHandler::EmitFormatDiagnostic(
8624 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8625 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8626 Range StringRange, ArrayRef<FixItHint> FixIt) {
8627 if (InFunctionCall) {
8628 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PD: PDiag);
8629 D << StringRange;
8630 D << FixIt;
8631 } else {
8632 S.Diag(Loc: IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PD: PDiag)
8633 << ArgumentExpr->getSourceRange();
8634
8635 const Sema::SemaDiagnosticBuilder &Note =
8636 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8637 diag::note_format_string_defined);
8638
8639 Note << StringRange;
8640 Note << FixIt;
8641 }
8642}
8643
8644//===--- CHECK: Printf format string checking -----------------------------===//
8645
8646namespace {
8647
8648class CheckPrintfHandler : public CheckFormatHandler {
8649public:
8650 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8651 const Expr *origFormatExpr, const FormatStringType type,
8652 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8653 const char *beg, Sema::FormatArgumentPassingKind APK,
8654 ArrayRef<const Expr *> Args, unsigned formatIdx,
8655 bool inFunctionCall, VariadicCallType CallType,
8656 llvm::SmallBitVector &CheckedVarArgs,
8657 UncoveredArgHandler &UncoveredArg)
8658 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8659 numDataArgs, beg, APK, Args, formatIdx,
8660 inFunctionCall, CallType, CheckedVarArgs,
8661 UncoveredArg) {}
8662
8663 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8664
8665 /// Returns true if '%@' specifiers are allowed in the format string.
8666 bool allowsObjCArg() const {
8667 return FSType == FormatStringType::NSString ||
8668 FSType == FormatStringType::OSLog ||
8669 FSType == FormatStringType::OSTrace;
8670 }
8671
8672 bool HandleInvalidPrintfConversionSpecifier(
8673 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8674 unsigned specifierLen) override;
8675
8676 void handleInvalidMaskType(StringRef MaskType) override;
8677
8678 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8679 const char *startSpecifier, unsigned specifierLen,
8680 const TargetInfo &Target) override;
8681 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8682 const char *StartSpecifier, unsigned SpecifierLen,
8683 const Expr *E);
8684
8685 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8686 unsigned k, const char *startSpecifier,
8687 unsigned specifierLen);
8688 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8689 const analyze_printf::OptionalAmount &Amt,
8690 unsigned type, const char *startSpecifier,
8691 unsigned specifierLen);
8692 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8693 const analyze_printf::OptionalFlag &flag,
8694 const char *startSpecifier, unsigned specifierLen);
8695 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8696 const analyze_printf::OptionalFlag &ignoredFlag,
8697 const analyze_printf::OptionalFlag &flag,
8698 const char *startSpecifier, unsigned specifierLen);
8699 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8700
8701 void HandleEmptyObjCModifierFlag(const char *startFlag,
8702 unsigned flagLen) override;
8703
8704 void HandleInvalidObjCModifierFlag(const char *startFlag,
8705 unsigned flagLen) override;
8706
8707 void
8708 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8709 const char *flagsEnd,
8710 const char *conversionPosition) override;
8711};
8712
8713/// Keeps around the information needed to verify that two specifiers are
8714/// compatible.
8715class EquatableFormatArgument {
8716public:
8717 enum SpecifierSensitivity : unsigned {
8718 SS_None,
8719 SS_Private,
8720 SS_Public,
8721 SS_Sensitive
8722 };
8723
8724 enum FormatArgumentRole : unsigned {
8725 FAR_Data,
8726 FAR_FieldWidth,
8727 FAR_Precision,
8728 FAR_Auxiliary, // FreeBSD kernel %b and %D
8729 };
8730
8731private:
8732 analyze_format_string::ArgType ArgType;
8733 analyze_format_string::LengthModifier LengthMod;
8734 StringRef SpecifierLetter;
8735 CharSourceRange Range;
8736 SourceLocation ElementLoc;
8737 FormatArgumentRole Role : 2;
8738 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8739 unsigned Position : 14;
8740 unsigned ModifierFor : 14; // not set for FAR_Data
8741
8742 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8743 bool InFunctionCall) const;
8744
8745public:
8746 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8747 analyze_format_string::LengthModifier LengthMod,
8748 StringRef SpecifierLetter,
8749 analyze_format_string::ArgType ArgType,
8750 FormatArgumentRole Role,
8751 SpecifierSensitivity Sensitivity, unsigned Position,
8752 unsigned ModifierFor)
8753 : ArgType(ArgType), LengthMod(LengthMod),
8754 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8755 Role(Role), Sensitivity(Sensitivity), Position(Position),
8756 ModifierFor(ModifierFor) {}
8757
8758 unsigned getPosition() const { return Position; }
8759 SourceLocation getSourceLocation() const { return ElementLoc; }
8760 CharSourceRange getSourceRange() const { return Range; }
8761 analyze_format_string::LengthModifier getLengthModifier() const {
8762 return LengthMod;
8763 }
8764 void setModifierFor(unsigned V) { ModifierFor = V; }
8765
8766 std::string buildFormatSpecifier() const {
8767 std::string result;
8768 llvm::raw_string_ostream(result)
8769 << getLengthModifier().toString() << SpecifierLetter;
8770 return result;
8771 }
8772
8773 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8774 const Expr *FmtExpr, bool InFunctionCall) const;
8775};
8776
8777/// Turns format strings into lists of EquatableSpecifier objects.
8778class DecomposePrintfHandler : public CheckPrintfHandler {
8779 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8780 bool HadError;
8781
8782 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8783 const Expr *origFormatExpr,
8784 const FormatStringType type, unsigned firstDataArg,
8785 unsigned numDataArgs, bool isObjC, const char *beg,
8786 Sema::FormatArgumentPassingKind APK,
8787 ArrayRef<const Expr *> Args, unsigned formatIdx,
8788 bool inFunctionCall, VariadicCallType CallType,
8789 llvm::SmallBitVector &CheckedVarArgs,
8790 UncoveredArgHandler &UncoveredArg,
8791 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8792 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8793 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8794 inFunctionCall, CallType, CheckedVarArgs,
8795 UncoveredArg),
8796 Specs(Specs), HadError(false) {}
8797
8798public:
8799 static bool
8800 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8801 FormatStringType type, bool IsObjC, bool InFunctionCall,
8802 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8803
8804 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8805 const char *startSpecifier,
8806 unsigned specifierLen,
8807 const TargetInfo &Target) override;
8808};
8809
8810} // namespace
8811
8812bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8813 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8814 unsigned specifierLen) {
8815 const analyze_printf::PrintfConversionSpecifier &CS =
8816 FS.getConversionSpecifier();
8817
8818 return HandleInvalidConversionSpecifier(
8819 argIndex: FS.getArgIndex(), Loc: getLocationOfByte(x: CS.getStart()), startSpec: startSpecifier,
8820 specifierLen, csStart: CS.getStart(), csLen: CS.getLength());
8821}
8822
8823void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8824 S.Diag(Loc: getLocationOfByte(x: MaskType.data()), DiagID: diag::err_invalid_mask_type_size);
8825}
8826
8827// Error out if struct or complex type argments are passed to os_log.
8828static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType,
8829 QualType T) {
8830 if (FSType != FormatStringType::OSLog)
8831 return false;
8832 return T->isRecordType() || T->isComplexType();
8833}
8834
8835bool CheckPrintfHandler::HandleAmount(
8836 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8837 const char *startSpecifier, unsigned specifierLen) {
8838 if (Amt.hasDataArgument()) {
8839 if (HasFormatArguments()) {
8840 unsigned argIndex = Amt.getArgIndex();
8841 if (argIndex >= NumDataArgs) {
8842 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_asterisk_missing_arg)
8843 << k,
8844 Loc: getLocationOfByte(x: Amt.getStart()),
8845 /*IsStringLocation*/ true,
8846 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8847 // Don't do any more checking. We will just emit
8848 // spurious errors.
8849 return false;
8850 }
8851
8852 // Type check the data argument. It should be an 'int'.
8853 // Although not in conformance with C99, we also allow the argument to be
8854 // an 'unsigned int' as that is a reasonably safe case. GCC also
8855 // doesn't emit a warning for that case.
8856 CoveredArgs.set(argIndex);
8857 const Expr *Arg = getDataArg(i: argIndex);
8858 if (!Arg)
8859 return false;
8860
8861 QualType T = Arg->getType();
8862
8863 const analyze_printf::ArgType &AT = Amt.getArgType(Ctx&: S.Context);
8864 assert(AT.isValid());
8865
8866 if (!AT.matchesType(C&: S.Context, argTy: T)) {
8867 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8868 ? diag::err_printf_asterisk_wrong_type
8869 : diag::warn_printf_asterisk_wrong_type;
8870 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID)
8871 << k << AT.getRepresentativeTypeName(C&: S.Context)
8872 << T << Arg->getSourceRange(),
8873 Loc: getLocationOfByte(x: Amt.getStart()),
8874 /*IsStringLocation*/ true,
8875 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8876 // Don't do any more checking. We will just emit
8877 // spurious errors.
8878 return false;
8879 }
8880 }
8881 }
8882 return true;
8883}
8884
8885void CheckPrintfHandler::HandleInvalidAmount(
8886 const analyze_printf::PrintfSpecifier &FS,
8887 const analyze_printf::OptionalAmount &Amt, unsigned type,
8888 const char *startSpecifier, unsigned specifierLen) {
8889 const analyze_printf::PrintfConversionSpecifier &CS =
8890 FS.getConversionSpecifier();
8891
8892 FixItHint fixit =
8893 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8894 ? FixItHint::CreateRemoval(
8895 RemoveRange: getSpecifierRange(startSpecifier: Amt.getStart(), specifierLen: Amt.getConstantLength()))
8896 : FixItHint();
8897
8898 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_optional_amount)
8899 << type << CS.toString(),
8900 Loc: getLocationOfByte(x: Amt.getStart()),
8901 /*IsStringLocation*/ true,
8902 StringRange: getSpecifierRange(startSpecifier, specifierLen), FixIt: fixit);
8903}
8904
8905void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8906 const analyze_printf::OptionalFlag &flag,
8907 const char *startSpecifier,
8908 unsigned specifierLen) {
8909 // Warn about pointless flag with a fixit removal.
8910 const analyze_printf::PrintfConversionSpecifier &CS =
8911 FS.getConversionSpecifier();
8912 EmitFormatDiagnostic(
8913 PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_flag)
8914 << flag.toString() << CS.toString(),
8915 Loc: getLocationOfByte(x: flag.getPosition()),
8916 /*IsStringLocation*/ true,
8917 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8918 FixIt: FixItHint::CreateRemoval(RemoveRange: getSpecifierRange(startSpecifier: flag.getPosition(), specifierLen: 1)));
8919}
8920
8921void CheckPrintfHandler::HandleIgnoredFlag(
8922 const analyze_printf::PrintfSpecifier &FS,
8923 const analyze_printf::OptionalFlag &ignoredFlag,
8924 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
8925 unsigned specifierLen) {
8926 // Warn about ignored flag with a fixit removal.
8927 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_ignored_flag)
8928 << ignoredFlag.toString() << flag.toString(),
8929 Loc: getLocationOfByte(x: ignoredFlag.getPosition()),
8930 /*IsStringLocation*/ true,
8931 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8932 FixIt: FixItHint::CreateRemoval(
8933 RemoveRange: getSpecifierRange(startSpecifier: ignoredFlag.getPosition(), specifierLen: 1)));
8934}
8935
8936void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8937 unsigned flagLen) {
8938 // Warn about an empty flag.
8939 EmitFormatDiagnostic(
8940 PDiag: S.PDiag(DiagID: diag::warn_printf_empty_objc_flag), Loc: getLocationOfByte(x: startFlag),
8941 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen));
8942}
8943
8944void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8945 unsigned flagLen) {
8946 // Warn about an invalid flag.
8947 auto Range = getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen);
8948 StringRef flag(startFlag, flagLen);
8949 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_invalid_objc_flag) << flag,
8950 Loc: getLocationOfByte(x: startFlag),
8951 /*IsStringLocation*/ true, StringRange: Range,
8952 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8953}
8954
8955void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8956 const char *flagsStart, const char *flagsEnd,
8957 const char *conversionPosition) {
8958 // Warn about using '[...]' without a '@' conversion.
8959 auto Range = getSpecifierRange(startSpecifier: flagsStart, specifierLen: flagsEnd - flagsStart + 1);
8960 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8961 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag) << StringRef(conversionPosition, 1),
8962 Loc: getLocationOfByte(x: conversionPosition),
8963 /*IsStringLocation*/ true, StringRange: Range,
8964 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8965}
8966
8967void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8968 const Expr *FmtExpr,
8969 bool InFunctionCall) const {
8970 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, ArgumentExpr: FmtExpr, PDiag,
8971 Loc: ElementLoc, IsStringLocation: true, StringRange: Range);
8972}
8973
8974bool EquatableFormatArgument::VerifyCompatible(
8975 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8976 bool InFunctionCall) const {
8977 using MK = analyze_format_string::ArgType::MatchKind;
8978 if (Role != Other.Role) {
8979 // diagnose and stop
8980 EmitDiagnostic(
8981 S, PDiag: S.PDiag(DiagID: diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8982 FmtExpr, InFunctionCall);
8983 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8984 return false;
8985 }
8986
8987 if (Role != FAR_Data) {
8988 if (ModifierFor != Other.ModifierFor) {
8989 // diagnose and stop
8990 EmitDiagnostic(S,
8991 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_modifierfor_mismatch)
8992 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8993 FmtExpr, InFunctionCall);
8994 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8995 return false;
8996 }
8997 return true;
8998 }
8999
9000 bool HadError = false;
9001 if (Sensitivity != Other.Sensitivity) {
9002 // diagnose and continue
9003 EmitDiagnostic(S,
9004 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_sensitivity_mismatch)
9005 << Sensitivity << Other.Sensitivity,
9006 FmtExpr, InFunctionCall);
9007 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
9008 << 0 << Other.Range;
9009 }
9010
9011 switch (ArgType.matchesArgType(C&: S.Context, other: Other.ArgType)) {
9012 case MK::Match:
9013 break;
9014
9015 case MK::MatchPromotion:
9016 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
9017 // MatchPromotion is treated as a failure by format_matches.
9018 case MK::NoMatch:
9019 case MK::NoMatchTypeConfusion:
9020 case MK::NoMatchPromotionTypeConfusion:
9021 EmitDiagnostic(S,
9022 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch)
9023 << buildFormatSpecifier()
9024 << Other.buildFormatSpecifier(),
9025 FmtExpr, InFunctionCall);
9026 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
9027 << 0 << Other.Range;
9028 break;
9029
9030 case MK::NoMatchPedantic:
9031 EmitDiagnostic(S,
9032 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch_pedantic)
9033 << buildFormatSpecifier()
9034 << Other.buildFormatSpecifier(),
9035 FmtExpr, InFunctionCall);
9036 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
9037 << 0 << Other.Range;
9038 break;
9039
9040 case MK::NoMatchSignedness:
9041 EmitDiagnostic(S,
9042 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_sign_mismatch)
9043 << buildFormatSpecifier()
9044 << Other.buildFormatSpecifier(),
9045 FmtExpr, InFunctionCall);
9046 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
9047 << 0 << Other.Range;
9048 break;
9049 }
9050 return !HadError;
9051}
9052
9053bool DecomposePrintfHandler::GetSpecifiers(
9054 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
9055 FormatStringType Type, bool IsObjC, bool InFunctionCall,
9056 llvm::SmallVectorImpl<EquatableFormatArgument> &Args) {
9057 StringRef Data = FSL->getString();
9058 const char *Str = Data.data();
9059 llvm::SmallBitVector BV;
9060 UncoveredArgHandler UA;
9061 const Expr *PrintfArgs[] = {FSL->getFormatString()};
9062 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
9063 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
9064 InFunctionCall, VariadicCallType::DoesNotApply, BV,
9065 UA, Args);
9066
9067 if (!analyze_format_string::ParsePrintfString(
9068 H, beg: Str, end: Str + Data.size(), LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
9069 isFreeBSDKPrintf: Type == FormatStringType::FreeBSDKPrintf))
9070 H.DoneProcessing();
9071 if (H.HadError)
9072 return false;
9073
9074 llvm::stable_sort(Range&: Args, C: [](const EquatableFormatArgument &A,
9075 const EquatableFormatArgument &B) {
9076 return A.getPosition() < B.getPosition();
9077 });
9078 return true;
9079}
9080
9081bool DecomposePrintfHandler::HandlePrintfSpecifier(
9082 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9083 unsigned specifierLen, const TargetInfo &Target) {
9084 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
9085 specifierLen, Target)) {
9086 HadError = true;
9087 return false;
9088 }
9089
9090 // Do not add any specifiers to the list for %%. This is possibly incorrect
9091 // if using a precision/width with a data argument, but that combination is
9092 // meaningless and we wouldn't know which format to attach the
9093 // precision/width to.
9094 const auto &CS = FS.getConversionSpecifier();
9095 if (CS.getKind() == analyze_format_string::ConversionSpecifier::PercentArg)
9096 return true;
9097
9098 // have to patch these to have the right ModifierFor if they are used
9099 const unsigned Unset = ~0;
9100 unsigned FieldWidthIndex = Unset;
9101 unsigned PrecisionIndex = Unset;
9102
9103 // field width?
9104 const auto &FieldWidth = FS.getFieldWidth();
9105 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
9106 FieldWidthIndex = Specs.size();
9107 Specs.emplace_back(
9108 Args: getSpecifierRange(startSpecifier, specifierLen),
9109 Args: getLocationOfByte(x: FieldWidth.getStart()),
9110 Args: analyze_format_string::LengthModifier(), Args: FieldWidth.getCharacters(),
9111 Args: FieldWidth.getArgType(Ctx&: S.Context),
9112 Args: EquatableFormatArgument::FAR_FieldWidth,
9113 Args: EquatableFormatArgument::SS_None,
9114 Args: FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
9115 : FieldWidthIndex,
9116 Args: 0);
9117 }
9118 // precision?
9119 const auto &Precision = FS.getPrecision();
9120 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
9121 PrecisionIndex = Specs.size();
9122 Specs.emplace_back(
9123 Args: getSpecifierRange(startSpecifier, specifierLen),
9124 Args: getLocationOfByte(x: Precision.getStart()),
9125 Args: analyze_format_string::LengthModifier(), Args: Precision.getCharacters(),
9126 Args: Precision.getArgType(Ctx&: S.Context), Args: EquatableFormatArgument::FAR_Precision,
9127 Args: EquatableFormatArgument::SS_None,
9128 Args: Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
9129 : PrecisionIndex,
9130 Args: 0);
9131 }
9132
9133 // this specifier
9134 unsigned SpecIndex =
9135 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
9136 if (FieldWidthIndex != Unset)
9137 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
9138 if (PrecisionIndex != Unset)
9139 Specs[PrecisionIndex].setModifierFor(SpecIndex);
9140
9141 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
9142 if (FS.isPrivate())
9143 Sensitivity = EquatableFormatArgument::SS_Private;
9144 else if (FS.isPublic())
9145 Sensitivity = EquatableFormatArgument::SS_Public;
9146 else if (FS.isSensitive())
9147 Sensitivity = EquatableFormatArgument::SS_Sensitive;
9148 else
9149 Sensitivity = EquatableFormatArgument::SS_None;
9150
9151 Specs.emplace_back(
9152 Args: getSpecifierRange(startSpecifier, specifierLen),
9153 Args: getLocationOfByte(x: CS.getStart()), Args: FS.getLengthModifier(),
9154 Args: CS.getCharacters(), Args: FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext()),
9155 Args: EquatableFormatArgument::FAR_Data, Args&: Sensitivity, Args&: SpecIndex, Args: 0);
9156
9157 // auxiliary argument?
9158 if (CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDbArg ||
9159 CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDDArg) {
9160 Specs.emplace_back(Args: getSpecifierRange(startSpecifier, specifierLen),
9161 Args: getLocationOfByte(x: CS.getStart()),
9162 Args: analyze_format_string::LengthModifier(),
9163 Args: CS.getCharacters(),
9164 Args: analyze_format_string::ArgType::CStrTy,
9165 Args: EquatableFormatArgument::FAR_Auxiliary, Args&: Sensitivity,
9166 Args: SpecIndex + 1, Args&: SpecIndex);
9167 }
9168 return true;
9169}
9170
9171// Determines if the specified is a C++ class or struct containing
9172// a member with the specified name and kind (e.g. a CXXMethodDecl named
9173// "c_str()").
9174template<typename MemberKind>
9175static llvm::SmallPtrSet<MemberKind*, 1>
9176CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9177 auto *RD = Ty->getAsCXXRecordDecl();
9178 llvm::SmallPtrSet<MemberKind*, 1> Results;
9179
9180 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
9181 return Results;
9182
9183 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9184 Sema::LookupMemberName);
9185 R.suppressDiagnostics();
9186
9187 // We just need to include all members of the right kind turned up by the
9188 // filter, at this point.
9189 if (S.LookupQualifiedName(R, LookupCtx: RD))
9190 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9191 NamedDecl *decl = (*I)->getUnderlyingDecl();
9192 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9193 Results.insert(FK);
9194 }
9195 return Results;
9196}
9197
9198/// Check if we could call '.c_str()' on an object.
9199///
9200/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9201/// allow the call, or if it would be ambiguous).
9202bool Sema::hasCStrMethod(const Expr *E) {
9203 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9204
9205 MethodSet Results =
9206 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S&: *this, Ty: E->getType());
9207 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9208 MI != ME; ++MI)
9209 if ((*MI)->getMinRequiredArguments() == 0)
9210 return true;
9211 return false;
9212}
9213
9214// Check if a (w)string was passed when a (w)char* was needed, and offer a
9215// better diagnostic if so. AT is assumed to be valid.
9216// Returns true when a c_str() conversion method is found.
9217bool CheckPrintfHandler::checkForCStrMembers(
9218 const analyze_printf::ArgType &AT, const Expr *E) {
9219 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9220
9221 MethodSet Results =
9222 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S, Ty: E->getType());
9223
9224 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9225 MI != ME; ++MI) {
9226 const CXXMethodDecl *Method = *MI;
9227 if (Method->getMinRequiredArguments() == 0 &&
9228 AT.matchesType(C&: S.Context, argTy: Method->getReturnType())) {
9229 // FIXME: Suggest parens if the expression needs them.
9230 SourceLocation EndLoc = S.getLocForEndOfToken(Loc: E->getEndLoc());
9231 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_printf_c_str)
9232 << "c_str()" << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ".c_str()");
9233 return true;
9234 }
9235 }
9236
9237 return false;
9238}
9239
9240bool CheckPrintfHandler::HandlePrintfSpecifier(
9241 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9242 unsigned specifierLen, const TargetInfo &Target) {
9243 using namespace analyze_format_string;
9244 using namespace analyze_printf;
9245
9246 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9247
9248 if (FS.consumesDataArgument()) {
9249 if (atFirstArg) {
9250 atFirstArg = false;
9251 usesPositionalArgs = FS.usesPositionalArg();
9252 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9253 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
9254 startSpec: startSpecifier, specifierLen);
9255 return false;
9256 }
9257 }
9258
9259 // First check if the field width, precision, and conversion specifier
9260 // have matching data arguments.
9261 if (!HandleAmount(Amt: FS.getFieldWidth(), /* field width */ k: 0, startSpecifier,
9262 specifierLen)) {
9263 return false;
9264 }
9265
9266 if (!HandleAmount(Amt: FS.getPrecision(), /* precision */ k: 1, startSpecifier,
9267 specifierLen)) {
9268 return false;
9269 }
9270
9271 if (!CS.consumesDataArgument()) {
9272 // FIXME: Technically specifying a precision or field width here
9273 // makes no sense. Worth issuing a warning at some point.
9274 return true;
9275 }
9276
9277 // Consume the argument.
9278 unsigned argIndex = FS.getArgIndex();
9279 if (argIndex < NumDataArgs) {
9280 // The check to see if the argIndex is valid will come later.
9281 // We set the bit here because we may exit early from this
9282 // function if we encounter some other error.
9283 CoveredArgs.set(argIndex);
9284 }
9285
9286 // FreeBSD kernel extensions.
9287 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9288 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9289 // We need at least two arguments.
9290 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex: argIndex + 1))
9291 return false;
9292
9293 if (HasFormatArguments()) {
9294 // Claim the second argument.
9295 CoveredArgs.set(argIndex + 1);
9296
9297 // Type check the first argument (int for %b, pointer for %D)
9298 const Expr *Ex = getDataArg(i: argIndex);
9299 const analyze_printf::ArgType &AT =
9300 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
9301 ? ArgType(S.Context.IntTy)
9302 : ArgType::CPointerTy;
9303 if (AT.isValid() && !AT.matchesType(C&: S.Context, argTy: Ex->getType()))
9304 EmitFormatDiagnostic(
9305 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9306 << AT.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
9307 << false << Ex->getSourceRange(),
9308 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
9309 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9310
9311 // Type check the second argument (char * for both %b and %D)
9312 Ex = getDataArg(i: argIndex + 1);
9313 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9314 if (AT2.isValid() && !AT2.matchesType(C&: S.Context, argTy: Ex->getType()))
9315 EmitFormatDiagnostic(
9316 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9317 << AT2.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
9318 << false << Ex->getSourceRange(),
9319 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
9320 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9321 }
9322 return true;
9323 }
9324
9325 // Check for using an Objective-C specific conversion specifier
9326 // in a non-ObjC literal.
9327 if (!allowsObjCArg() && CS.isObjCArg()) {
9328 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9329 specifierLen);
9330 }
9331
9332 // %P can only be used with os_log.
9333 if (FSType != FormatStringType::OSLog &&
9334 CS.getKind() == ConversionSpecifier::PArg) {
9335 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9336 specifierLen);
9337 }
9338
9339 // %n is not allowed with os_log.
9340 if (FSType == FormatStringType::OSLog &&
9341 CS.getKind() == ConversionSpecifier::nArg) {
9342 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_os_log_format_narg),
9343 Loc: getLocationOfByte(x: CS.getStart()),
9344 /*IsStringLocation*/ false,
9345 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9346
9347 return true;
9348 }
9349
9350 // Only scalars are allowed for os_trace.
9351 if (FSType == FormatStringType::OSTrace &&
9352 (CS.getKind() == ConversionSpecifier::PArg ||
9353 CS.getKind() == ConversionSpecifier::sArg ||
9354 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9355 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9356 specifierLen);
9357 }
9358
9359 // Check for use of public/private annotation outside of os_log().
9360 if (FSType != FormatStringType::OSLog) {
9361 if (FS.isPublic().isSet()) {
9362 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
9363 << "public",
9364 Loc: getLocationOfByte(x: FS.isPublic().getPosition()),
9365 /*IsStringLocation*/ false,
9366 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9367 }
9368 if (FS.isPrivate().isSet()) {
9369 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
9370 << "private",
9371 Loc: getLocationOfByte(x: FS.isPrivate().getPosition()),
9372 /*IsStringLocation*/ false,
9373 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9374 }
9375 }
9376
9377 const llvm::Triple &Triple = Target.getTriple();
9378 if (CS.getKind() == ConversionSpecifier::nArg &&
9379 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9380 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_narg_not_supported),
9381 Loc: getLocationOfByte(x: CS.getStart()),
9382 /*IsStringLocation*/ false,
9383 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9384 }
9385
9386 // Check for invalid use of field width
9387 if (!FS.hasValidFieldWidth()) {
9388 HandleInvalidAmount(FS, Amt: FS.getFieldWidth(), /* field width */ type: 0,
9389 startSpecifier, specifierLen);
9390 }
9391
9392 // Check for invalid use of precision
9393 if (!FS.hasValidPrecision()) {
9394 HandleInvalidAmount(FS, Amt: FS.getPrecision(), /* precision */ type: 1,
9395 startSpecifier, specifierLen);
9396 }
9397
9398 // Precision is mandatory for %P specifier.
9399 if (CS.getKind() == ConversionSpecifier::PArg &&
9400 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9401 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_no_precision),
9402 Loc: getLocationOfByte(x: startSpecifier),
9403 /*IsStringLocation*/ false,
9404 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9405 }
9406
9407 // Check each flag does not conflict with any other component.
9408 if (!FS.hasValidThousandsGroupingPrefix())
9409 HandleFlag(FS, flag: FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9410 if (!FS.hasValidLeadingZeros())
9411 HandleFlag(FS, flag: FS.hasLeadingZeros(), startSpecifier, specifierLen);
9412 if (!FS.hasValidPlusPrefix())
9413 HandleFlag(FS, flag: FS.hasPlusPrefix(), startSpecifier, specifierLen);
9414 if (!FS.hasValidSpacePrefix())
9415 HandleFlag(FS, flag: FS.hasSpacePrefix(), startSpecifier, specifierLen);
9416 if (!FS.hasValidAlternativeForm())
9417 HandleFlag(FS, flag: FS.hasAlternativeForm(), startSpecifier, specifierLen);
9418 if (!FS.hasValidLeftJustified())
9419 HandleFlag(FS, flag: FS.isLeftJustified(), startSpecifier, specifierLen);
9420
9421 // Check that flags are not ignored by another flag
9422 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9423 HandleIgnoredFlag(FS, ignoredFlag: FS.hasSpacePrefix(), flag: FS.hasPlusPrefix(),
9424 startSpecifier, specifierLen);
9425 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9426 HandleIgnoredFlag(FS, ignoredFlag: FS.hasLeadingZeros(), flag: FS.isLeftJustified(),
9427 startSpecifier, specifierLen);
9428
9429 // Check the length modifier is valid with the given conversion specifier.
9430 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
9431 LO: S.getLangOpts()))
9432 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9433 DiagID: diag::warn_format_nonsensical_length);
9434 else if (!FS.hasStandardLengthModifier())
9435 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9436 else if (!FS.hasStandardLengthConversionCombination())
9437 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9438 DiagID: diag::warn_format_non_standard_conversion_spec);
9439
9440 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
9441 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9442
9443 // The remaining checks depend on the data arguments.
9444 if (!HasFormatArguments())
9445 return true;
9446
9447 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9448 return false;
9449
9450 const Expr *Arg = getDataArg(i: argIndex);
9451 if (!Arg)
9452 return true;
9453
9454 return checkFormatExpr(FS, StartSpecifier: startSpecifier, SpecifierLen: specifierLen, E: Arg);
9455}
9456
9457static bool requiresParensToAddCast(const Expr *E) {
9458 // FIXME: We should have a general way to reason about operator
9459 // precedence and whether parens are actually needed here.
9460 // Take care of a few common cases where they aren't.
9461 const Expr *Inside = E->IgnoreImpCasts();
9462 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: Inside))
9463 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9464
9465 switch (Inside->getStmtClass()) {
9466 case Stmt::ArraySubscriptExprClass:
9467 case Stmt::CallExprClass:
9468 case Stmt::CharacterLiteralClass:
9469 case Stmt::CXXBoolLiteralExprClass:
9470 case Stmt::DeclRefExprClass:
9471 case Stmt::FloatingLiteralClass:
9472 case Stmt::IntegerLiteralClass:
9473 case Stmt::MemberExprClass:
9474 case Stmt::ObjCArrayLiteralClass:
9475 case Stmt::ObjCBoolLiteralExprClass:
9476 case Stmt::ObjCBoxedExprClass:
9477 case Stmt::ObjCDictionaryLiteralClass:
9478 case Stmt::ObjCEncodeExprClass:
9479 case Stmt::ObjCIvarRefExprClass:
9480 case Stmt::ObjCMessageExprClass:
9481 case Stmt::ObjCPropertyRefExprClass:
9482 case Stmt::ObjCStringLiteralClass:
9483 case Stmt::ObjCSubscriptRefExprClass:
9484 case Stmt::ParenExprClass:
9485 case Stmt::StringLiteralClass:
9486 case Stmt::UnaryOperatorClass:
9487 return false;
9488 default:
9489 return true;
9490 }
9491}
9492
9493static std::pair<QualType, StringRef>
9494shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9495 const Expr *E) {
9496 // Use a 'while' to peel off layers of typedefs.
9497 QualType TyTy = IntendedTy;
9498 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9499 StringRef Name = UserTy->getDecl()->getName();
9500 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9501 .Case(S: "CFIndex", Value: Context.getNSIntegerType())
9502 .Case(S: "NSInteger", Value: Context.getNSIntegerType())
9503 .Case(S: "NSUInteger", Value: Context.getNSUIntegerType())
9504 .Case(S: "SInt32", Value: Context.IntTy)
9505 .Case(S: "UInt32", Value: Context.UnsignedIntTy)
9506 .Default(Value: QualType());
9507
9508 if (!CastTy.isNull())
9509 return std::make_pair(x&: CastTy, y&: Name);
9510
9511 TyTy = UserTy->desugar();
9512 }
9513
9514 // Strip parens if necessary.
9515 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Val: E))
9516 return shouldNotPrintDirectly(Context, IntendedTy: PE->getSubExpr()->getType(),
9517 E: PE->getSubExpr());
9518
9519 // If this is a conditional expression, then its result type is constructed
9520 // via usual arithmetic conversions and thus there might be no necessary
9521 // typedef sugar there. Recurse to operands to check for NSInteger &
9522 // Co. usage condition.
9523 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
9524 QualType TrueTy, FalseTy;
9525 StringRef TrueName, FalseName;
9526
9527 std::tie(args&: TrueTy, args&: TrueName) = shouldNotPrintDirectly(
9528 Context, IntendedTy: CO->getTrueExpr()->getType(), E: CO->getTrueExpr());
9529 std::tie(args&: FalseTy, args&: FalseName) = shouldNotPrintDirectly(
9530 Context, IntendedTy: CO->getFalseExpr()->getType(), E: CO->getFalseExpr());
9531
9532 if (TrueTy == FalseTy)
9533 return std::make_pair(x&: TrueTy, y&: TrueName);
9534 else if (TrueTy.isNull())
9535 return std::make_pair(x&: FalseTy, y&: FalseName);
9536 else if (FalseTy.isNull())
9537 return std::make_pair(x&: TrueTy, y&: TrueName);
9538 }
9539
9540 return std::make_pair(x: QualType(), y: StringRef());
9541}
9542
9543/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9544/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9545/// type do not count.
9546static bool isArithmeticArgumentPromotion(Sema &S,
9547 const ImplicitCastExpr *ICE) {
9548 QualType From = ICE->getSubExpr()->getType();
9549 QualType To = ICE->getType();
9550 // It's an integer promotion if the destination type is the promoted
9551 // source type.
9552 if (ICE->getCastKind() == CK_IntegralCast &&
9553 S.Context.isPromotableIntegerType(T: From) &&
9554 S.Context.getPromotedIntegerType(PromotableType: From) == To)
9555 return true;
9556 // Look through vector types, since we do default argument promotion for
9557 // those in OpenCL.
9558 if (const auto *VecTy = From->getAs<ExtVectorType>())
9559 From = VecTy->getElementType();
9560 if (const auto *VecTy = To->getAs<ExtVectorType>())
9561 To = VecTy->getElementType();
9562 // It's a floating promotion if the source type is a lower rank.
9563 return ICE->getCastKind() == CK_FloatingCast &&
9564 S.Context.getFloatingTypeOrder(LHS: From, RHS: To) < 0;
9565}
9566
9567static analyze_format_string::ArgType::MatchKind
9568handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match,
9569 DiagnosticsEngine &Diags, SourceLocation Loc) {
9570 if (Match == analyze_format_string::ArgType::NoMatchSignedness) {
9571 if (Diags.isIgnored(
9572 DiagID: diag::warn_format_conversion_argument_type_mismatch_signedness,
9573 Loc) ||
9574 Diags.isIgnored(
9575 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9576 DiagID: diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9577 return analyze_format_string::ArgType::Match;
9578 }
9579 }
9580 return Match;
9581}
9582
9583bool CheckPrintfHandler::checkFormatExpr(
9584 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9585 unsigned SpecifierLen, const Expr *E) {
9586 using namespace analyze_format_string;
9587 using namespace analyze_printf;
9588
9589 // Now type check the data expression that matches the
9590 // format specifier.
9591 const analyze_printf::ArgType &AT = FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9592 if (!AT.isValid())
9593 return true;
9594
9595 QualType ExprTy = E->getType();
9596 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(Val&: ExprTy)) {
9597 ExprTy = TET->getUnderlyingExpr()->getType();
9598 }
9599
9600 if (const OverflowBehaviorType *OBT =
9601 dyn_cast<OverflowBehaviorType>(Val: ExprTy.getCanonicalType()))
9602 ExprTy = OBT->getUnderlyingType();
9603
9604 // When using the format attribute in C++, you can receive a function or an
9605 // array that will necessarily decay to a pointer when passed to the final
9606 // format consumer. Apply decay before type comparison.
9607 if (ExprTy->canDecayToPointerType())
9608 ExprTy = S.Context.getDecayedType(T: ExprTy);
9609
9610 // Diagnose attempts to print a boolean value as a character. Unlike other
9611 // -Wformat diagnostics, this is fine from a type perspective, but it still
9612 // doesn't make sense.
9613 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9614 E->isKnownToHaveBooleanValue()) {
9615 const CharSourceRange &CSR =
9616 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9617 SmallString<4> FSString;
9618 llvm::raw_svector_ostream os(FSString);
9619 FS.toString(os);
9620 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_bool_as_character)
9621 << FSString,
9622 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9623 return true;
9624 }
9625
9626 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9627 // dumping raw class data (like is-a pointer), not actual data.
9628 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
9629 ExprTy->isObjCObjectPointerType()) {
9630 const CharSourceRange &CSR =
9631 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9632 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_with_objc_pointer),
9633 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9634 return true;
9635 }
9636
9637 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9638 return true;
9639
9640 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9641 ArgType::MatchKind Match = AT.matchesType(C&: S.Context, argTy: ExprTy);
9642 ArgType::MatchKind OrigMatch = Match;
9643
9644 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9645 if (Match == ArgType::Match)
9646 return true;
9647
9648 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9649 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9650
9651 // Look through argument promotions for our error message's reported type.
9652 // This includes the integral and floating promotions, but excludes array
9653 // and function pointer decay (seeing that an argument intended to be a
9654 // string has type 'char [6]' is probably more confusing than 'char *') and
9655 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9656 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
9657 if (isArithmeticArgumentPromotion(S, ICE)) {
9658 E = ICE->getSubExpr();
9659 ExprTy = E->getType();
9660
9661 // Check if we didn't match because of an implicit cast from a 'char'
9662 // or 'short' to an 'int'. This is done because printf is a varargs
9663 // function.
9664 if (ICE->getType() == S.Context.IntTy ||
9665 ICE->getType() == S.Context.UnsignedIntTy) {
9666 // All further checking is done on the subexpression
9667 ImplicitMatch = AT.matchesType(C&: S.Context, argTy: ExprTy);
9668 if (OrigMatch == ArgType::NoMatchSignedness &&
9669 ImplicitMatch != ArgType::NoMatchSignedness)
9670 // If the original match was a signedness match this match on the
9671 // implicit cast type also need to be signedness match otherwise we
9672 // might introduce new unexpected warnings from -Wformat-signedness.
9673 return true;
9674 ImplicitMatch = handleFormatSignedness(
9675 Match: ImplicitMatch, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9676 if (ImplicitMatch == ArgType::Match)
9677 return true;
9678 }
9679 }
9680 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(Val: E)) {
9681 // Special case for 'a', which has type 'int' in C.
9682 // Note, however, that we do /not/ want to treat multibyte constants like
9683 // 'MooV' as characters! This form is deprecated but still exists. In
9684 // addition, don't treat expressions as of type 'char' if one byte length
9685 // modifier is provided.
9686 if (ExprTy == S.Context.IntTy &&
9687 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9688 if (llvm::isUIntN(N: S.Context.getCharWidth(), x: CL->getValue())) {
9689 ExprTy = S.Context.CharTy;
9690 // To improve check results, we consider a character literal in C
9691 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9692 // more likely a type confusion situation, so we will suggest to
9693 // use '%hhd' instead by discarding the MatchPromotion.
9694 if (Match == ArgType::MatchPromotion)
9695 Match = ArgType::NoMatch;
9696 }
9697 }
9698 if (Match == ArgType::MatchPromotion) {
9699 // WG14 N2562 only clarified promotions in *printf
9700 // For NSLog in ObjC, just preserve -Wformat behavior
9701 if (!S.getLangOpts().ObjC &&
9702 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9703 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9704 return true;
9705 Match = ArgType::NoMatch;
9706 }
9707 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9708 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9709 Match = ImplicitMatch;
9710 assert(Match != ArgType::MatchPromotion);
9711
9712 // Look through unscoped enums to their underlying type.
9713 bool IsEnum = false;
9714 bool IsScopedEnum = false;
9715 QualType IntendedTy = ExprTy;
9716 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9717 IntendedTy = ED->getIntegerType();
9718 if (!ED->isScoped()) {
9719 ExprTy = IntendedTy;
9720 // This controls whether we're talking about the underlying type or not,
9721 // which we only want to do when it's an unscoped enum.
9722 IsEnum = true;
9723 } else {
9724 IsScopedEnum = true;
9725 }
9726 }
9727
9728 // %C in an Objective-C context prints a unichar, not a wchar_t.
9729 // If the argument is an integer of some kind, believe the %C and suggest
9730 // a cast instead of changing the conversion specifier.
9731 if (isObjCContext() &&
9732 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9733 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9734 !ExprTy->isCharType()) {
9735 // 'unichar' is defined as a typedef of unsigned short, but we should
9736 // prefer using the typedef if it is visible.
9737 IntendedTy = S.Context.UnsignedShortTy;
9738
9739 // While we are here, check if the value is an IntegerLiteral that happens
9740 // to be within the valid range.
9741 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: E)) {
9742 const llvm::APInt &V = IL->getValue();
9743 if (V.getActiveBits() <= S.Context.getTypeSize(T: IntendedTy))
9744 return true;
9745 }
9746
9747 LookupResult Result(S, &S.Context.Idents.get(Name: "unichar"), E->getBeginLoc(),
9748 Sema::LookupOrdinaryName);
9749 if (S.LookupName(R&: Result, S: S.getCurScope())) {
9750 NamedDecl *ND = Result.getFoundDecl();
9751 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: ND))
9752 if (TD->getUnderlyingType() == IntendedTy)
9753 IntendedTy =
9754 S.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
9755 /*Qualifier=*/std::nullopt, Decl: TD);
9756 }
9757 }
9758 }
9759
9760 // Special-case some of Darwin's platform-independence types by suggesting
9761 // casts to primitive types that are known to be large enough.
9762 bool ShouldNotPrintDirectly = false;
9763 StringRef CastTyName;
9764 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9765 QualType CastTy;
9766 std::tie(args&: CastTy, args&: CastTyName) =
9767 shouldNotPrintDirectly(Context: S.Context, IntendedTy, E);
9768 if (!CastTy.isNull()) {
9769 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9770 // (long in ASTContext). Only complain to pedants or when they're the
9771 // underlying type of a scoped enum (which always needs a cast).
9772 if (!IsScopedEnum &&
9773 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9774 (AT.isSizeT() || AT.isPtrdiffT()) &&
9775 AT.matchesType(C&: S.Context, argTy: CastTy))
9776 Match = ArgType::NoMatchPedantic;
9777 IntendedTy = CastTy;
9778 ShouldNotPrintDirectly = true;
9779 }
9780 }
9781
9782 // We may be able to offer a FixItHint if it is a supported type.
9783 PrintfSpecifier fixedFS = FS;
9784 bool Success =
9785 fixedFS.fixType(QT: IntendedTy, LangOpt: S.getLangOpts(), Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9786
9787 if (Success) {
9788 // Get the fix string from the fixed format specifier
9789 SmallString<16> buf;
9790 llvm::raw_svector_ostream os(buf);
9791 fixedFS.toString(os);
9792
9793 CharSourceRange SpecRange = getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9794
9795 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9796 unsigned Diag;
9797 switch (Match) {
9798 case ArgType::Match:
9799 case ArgType::MatchPromotion:
9800 case ArgType::NoMatchPromotionTypeConfusion:
9801 llvm_unreachable("expected non-matching");
9802 case ArgType::NoMatchSignedness:
9803 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9804 break;
9805 case ArgType::NoMatchPedantic:
9806 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9807 break;
9808 case ArgType::NoMatchTypeConfusion:
9809 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9810 break;
9811 case ArgType::NoMatch:
9812 Diag = diag::warn_format_conversion_argument_type_mismatch;
9813 break;
9814 }
9815
9816 // In this case, the specifier is wrong and should be changed to match
9817 // the argument.
9818 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
9819 << AT.getRepresentativeTypeName(C&: S.Context)
9820 << IntendedTy << IsEnum << E->getSourceRange(),
9821 Loc: E->getBeginLoc(),
9822 /*IsStringLocation*/ false, StringRange: SpecRange,
9823 FixIt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9824 } else {
9825 // The canonical type for formatting this value is different from the
9826 // actual type of the expression. (This occurs, for example, with Darwin's
9827 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9828 // should be printed as 'long' for 64-bit compatibility.)
9829 // Rather than emitting a normal format/argument mismatch, we want to
9830 // add a cast to the recommended type (and correct the format string
9831 // if necessary). We should also do so for scoped enumerations.
9832 SmallString<16> CastBuf;
9833 llvm::raw_svector_ostream CastFix(CastBuf);
9834 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9835 IntendedTy.print(OS&: CastFix, Policy: S.Context.getPrintingPolicy());
9836 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9837
9838 SmallVector<FixItHint, 4> Hints;
9839 ArgType::MatchKind IntendedMatch = AT.matchesType(C&: S.Context, argTy: IntendedTy);
9840 IntendedMatch = handleFormatSignedness(Match: IntendedMatch, Diags&: S.getDiagnostics(),
9841 Loc: E->getExprLoc());
9842 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9843 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9844
9845 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(Val: E)) {
9846 // If there's already a cast present, just replace it.
9847 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9848 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: CastRange, Code: CastFix.str()));
9849
9850 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9851 // If the expression has high enough precedence,
9852 // just write the C-style cast.
9853 Hints.push_back(
9854 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9855 } else {
9856 // Otherwise, add parens around the expression as well as the cast.
9857 CastFix << "(";
9858 Hints.push_back(
9859 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9860
9861 // We don't use getLocForEndOfToken because it returns invalid source
9862 // locations for macro expansions (by design).
9863 SourceLocation EndLoc = S.SourceMgr.getSpellingLoc(Loc: E->getEndLoc());
9864 SourceLocation After = EndLoc.getLocWithOffset(
9865 Offset: Lexer::MeasureTokenLength(Loc: EndLoc, SM: S.SourceMgr, LangOpts: S.LangOpts));
9866 Hints.push_back(Elt: FixItHint::CreateInsertion(InsertionLoc: After, Code: ")"));
9867 }
9868
9869 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9870 // The expression has a type that should not be printed directly.
9871 // We extract the name from the typedef because we don't want to show
9872 // the underlying type in the diagnostic.
9873 StringRef Name;
9874 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9875 Name = TypedefTy->getDecl()->getName();
9876 else
9877 Name = CastTyName;
9878 unsigned Diag = Match == ArgType::NoMatchPedantic
9879 ? diag::warn_format_argument_needs_cast_pedantic
9880 : diag::warn_format_argument_needs_cast;
9881 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag) << Name << IntendedTy << IsEnum
9882 << E->getSourceRange(),
9883 Loc: E->getBeginLoc(), /*IsStringLocation=*/false,
9884 StringRange: SpecRange, FixIt: Hints);
9885 } else {
9886 // In this case, the expression could be printed using a different
9887 // specifier, but we've decided that the specifier is probably correct
9888 // and we should cast instead. Just use the normal warning message.
9889
9890 unsigned Diag =
9891 IsScopedEnum
9892 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9893 : diag::warn_format_conversion_argument_type_mismatch;
9894
9895 EmitFormatDiagnostic(
9896 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9897 << IsEnum << E->getSourceRange(),
9898 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: SpecRange, FixIt: Hints);
9899 }
9900 }
9901 } else {
9902 const CharSourceRange &CSR =
9903 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9904 // Since the warning for passing non-POD types to variadic functions
9905 // was deferred until now, we emit a warning for non-POD
9906 // arguments here.
9907 bool EmitTypeMismatch = false;
9908 // Record and complex type arguments cannot be code generated for os_log
9909 // and would crash CodeGen, so they are rejected with a hard error emitted
9910 // after the switch below.
9911 bool EmitOSLogError = false;
9912 switch (S.isValidVarArgType(Ty: ExprTy)) {
9913 case VarArgKind::Valid:
9914 case VarArgKind::ValidInCXX11: {
9915 unsigned Diag;
9916 switch (Match) {
9917 case ArgType::Match:
9918 case ArgType::MatchPromotion:
9919 case ArgType::NoMatchPromotionTypeConfusion:
9920 llvm_unreachable("expected non-matching");
9921 case ArgType::NoMatchSignedness:
9922 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9923 break;
9924 case ArgType::NoMatchPedantic:
9925 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9926 break;
9927 case ArgType::NoMatchTypeConfusion:
9928 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9929 break;
9930 case ArgType::NoMatch:
9931 EmitOSLogError = isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy);
9932 Diag = diag::warn_format_conversion_argument_type_mismatch;
9933 break;
9934 }
9935
9936 if (!EmitOSLogError)
9937 EmitFormatDiagnostic(
9938 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9939 << IsEnum << CSR << E->getSourceRange(),
9940 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9941 break;
9942 }
9943 case VarArgKind::Undefined:
9944 case VarArgKind::MSVCUndefined:
9945 if (CallType == VariadicCallType::DoesNotApply) {
9946 EmitTypeMismatch = true;
9947 } else if (isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy)) {
9948 // Emit a hard error rather than the -Wnon-pod-varargs warning, which
9949 // does not stop compilation.
9950 EmitOSLogError = true;
9951 } else {
9952 EmitFormatDiagnostic(
9953 PDiag: S.PDiag(DiagID: diag::warn_non_pod_vararg_with_format_string)
9954 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9955 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9956 << E->getSourceRange(),
9957 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9958 checkForCStrMembers(AT, E);
9959 }
9960 break;
9961
9962 case VarArgKind::Invalid:
9963 if (CallType == VariadicCallType::DoesNotApply)
9964 EmitTypeMismatch = true;
9965 else if (ExprTy->isObjCObjectType())
9966 EmitFormatDiagnostic(
9967 PDiag: S.PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg_format)
9968 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9969 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9970 << E->getSourceRange(),
9971 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9972 else
9973 // FIXME: If this is an initializer list, suggest removing the braces
9974 // or inserting a cast to the target type.
9975 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg_format)
9976 << isa<InitListExpr>(Val: E) << ExprTy << CallType
9977 << AT.getRepresentativeTypeName(C&: S.Context) << E->getSourceRange();
9978 break;
9979 }
9980
9981 if (EmitOSLogError)
9982 EmitFormatDiagnostic(
9983 PDiag: S.PDiag(DiagID: diag::err_format_conversion_argument_type_mismatch)
9984 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << IsEnum
9985 << CSR << E->getSourceRange(),
9986 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9987
9988 if (EmitTypeMismatch) {
9989 // The function is not variadic, so we do not generate warnings about
9990 // being allowed to pass that object as a variadic argument. Instead,
9991 // since there are inherently no printf specifiers for types which cannot
9992 // be passed as variadic arguments, emit a plain old specifier mismatch
9993 // argument.
9994 EmitFormatDiagnostic(
9995 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9996 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << false
9997 << E->getSourceRange(),
9998 Loc: E->getBeginLoc(), IsStringLocation: false, StringRange: CSR);
9999 }
10000
10001 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
10002 "format string specifier index out of range");
10003 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
10004 }
10005
10006 return true;
10007}
10008
10009//===--- CHECK: Scanf format string checking ------------------------------===//
10010
10011namespace {
10012
10013class CheckScanfHandler : public CheckFormatHandler {
10014public:
10015 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
10016 const Expr *origFormatExpr, FormatStringType type,
10017 unsigned firstDataArg, unsigned numDataArgs,
10018 const char *beg, Sema::FormatArgumentPassingKind APK,
10019 ArrayRef<const Expr *> Args, unsigned formatIdx,
10020 bool inFunctionCall, VariadicCallType CallType,
10021 llvm::SmallBitVector &CheckedVarArgs,
10022 UncoveredArgHandler &UncoveredArg)
10023 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
10024 numDataArgs, beg, APK, Args, formatIdx,
10025 inFunctionCall, CallType, CheckedVarArgs,
10026 UncoveredArg) {}
10027
10028 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10029 const char *startSpecifier,
10030 unsigned specifierLen) override;
10031
10032 bool
10033 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10034 const char *startSpecifier,
10035 unsigned specifierLen) override;
10036
10037 void HandleIncompleteScanList(const char *start, const char *end) override;
10038};
10039
10040} // namespace
10041
10042void CheckScanfHandler::HandleIncompleteScanList(const char *start,
10043 const char *end) {
10044 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_scanlist_incomplete),
10045 Loc: getLocationOfByte(x: end), /*IsStringLocation*/ true,
10046 StringRange: getSpecifierRange(startSpecifier: start, specifierLen: end - start));
10047}
10048
10049bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
10050 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
10051 unsigned specifierLen) {
10052 const analyze_scanf::ScanfConversionSpecifier &CS =
10053 FS.getConversionSpecifier();
10054
10055 return HandleInvalidConversionSpecifier(
10056 argIndex: FS.getArgIndex(), Loc: getLocationOfByte(x: CS.getStart()), startSpec: startSpecifier,
10057 specifierLen, csStart: CS.getStart(), csLen: CS.getLength());
10058}
10059
10060bool CheckScanfHandler::HandleScanfSpecifier(
10061 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
10062 unsigned specifierLen) {
10063 using namespace analyze_scanf;
10064 using namespace analyze_format_string;
10065
10066 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
10067
10068 // Handle case where '%' and '*' don't consume an argument. These shouldn't
10069 // be used to decide if we are using positional arguments consistently.
10070 if (FS.consumesDataArgument()) {
10071 if (atFirstArg) {
10072 atFirstArg = false;
10073 usesPositionalArgs = FS.usesPositionalArg();
10074 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
10075 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
10076 startSpec: startSpecifier, specifierLen);
10077 return false;
10078 }
10079 }
10080
10081 // Check if the field with is non-zero.
10082 const OptionalAmount &Amt = FS.getFieldWidth();
10083 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
10084 if (Amt.getConstantAmount() == 0) {
10085 const CharSourceRange &R =
10086 getSpecifierRange(startSpecifier: Amt.getStart(), specifierLen: Amt.getConstantLength());
10087 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_nonzero_width),
10088 Loc: getLocationOfByte(x: Amt.getStart()),
10089 /*IsStringLocation*/ true, StringRange: R,
10090 FixIt: FixItHint::CreateRemoval(RemoveRange: R));
10091 }
10092 }
10093
10094 if (!FS.consumesDataArgument()) {
10095 // FIXME: Technically specifying a precision or field width here
10096 // makes no sense. Worth issuing a warning at some point.
10097 return true;
10098 }
10099
10100 // Consume the argument.
10101 unsigned argIndex = FS.getArgIndex();
10102 if (argIndex < NumDataArgs) {
10103 // The check to see if the argIndex is valid will come later.
10104 // We set the bit here because we may exit early from this
10105 // function if we encounter some other error.
10106 CoveredArgs.set(argIndex);
10107 }
10108
10109 // Check the length modifier is valid with the given conversion specifier.
10110 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
10111 LO: S.getLangOpts()))
10112 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10113 DiagID: diag::warn_format_nonsensical_length);
10114 else if (!FS.hasStandardLengthModifier())
10115 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10116 else if (!FS.hasStandardLengthConversionCombination())
10117 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10118 DiagID: diag::warn_format_non_standard_conversion_spec);
10119
10120 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
10121 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10122
10123 // The remaining checks depend on the data arguments.
10124 if (!HasFormatArguments())
10125 return true;
10126
10127 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10128 return false;
10129
10130 // Check that the argument type matches the format specifier.
10131 const Expr *Ex = getDataArg(i: argIndex);
10132 if (!Ex)
10133 return true;
10134
10135 const analyze_format_string::ArgType &AT = FS.getArgType(Ctx&: S.Context);
10136
10137 if (!AT.isValid()) {
10138 return true;
10139 }
10140
10141 if (CheckUnsupportedType(AT, E: Ex, StartSpecifier: startSpecifier, SpecifierLen: specifierLen))
10142 return true;
10143
10144 analyze_format_string::ArgType::MatchKind Match =
10145 AT.matchesType(C&: S.Context, argTy: Ex->getType());
10146 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: Ex->getExprLoc());
10147 if (Match == analyze_format_string::ArgType::Match)
10148 return true;
10149 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
10150 bool Signedness = Match == analyze_format_string::ArgType::NoMatchSignedness;
10151
10152 ScanfSpecifier fixedFS = FS;
10153 bool Success = fixedFS.fixType(QT: Ex->getType(), RawQT: Ex->IgnoreImpCasts()->getType(),
10154 LangOpt: S.getLangOpts(), Ctx&: S.Context);
10155
10156 unsigned Diag =
10157 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10158 : Signedness
10159 ? diag::warn_format_conversion_argument_type_mismatch_signedness
10160 : diag::warn_format_conversion_argument_type_mismatch;
10161
10162 if (Success) {
10163 // Get the fix string from the fixed format specifier.
10164 SmallString<128> buf;
10165 llvm::raw_svector_ostream os(buf);
10166 fixedFS.toString(os);
10167
10168 EmitFormatDiagnostic(
10169 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context)
10170 << Ex->getType() << false << Ex->getSourceRange(),
10171 Loc: Ex->getBeginLoc(),
10172 /*IsStringLocation*/ false,
10173 StringRange: getSpecifierRange(startSpecifier, specifierLen),
10174 FixIt: FixItHint::CreateReplacement(
10175 RemoveRange: getSpecifierRange(startSpecifier, specifierLen), Code: os.str()));
10176 } else {
10177 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
10178 << AT.getRepresentativeTypeName(C&: S.Context)
10179 << Ex->getType() << false << Ex->getSourceRange(),
10180 Loc: Ex->getBeginLoc(),
10181 /*IsStringLocation*/ false,
10182 StringRange: getSpecifierRange(startSpecifier, specifierLen));
10183 }
10184
10185 return true;
10186}
10187
10188static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
10189 ArrayRef<EquatableFormatArgument> RefArgs,
10190 const StringLiteral *Fmt,
10191 ArrayRef<EquatableFormatArgument> FmtArgs,
10192 const Expr *FmtExpr, bool InFunctionCall) {
10193 bool HadError = false;
10194 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
10195 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
10196 while (FmtIter < FmtEnd && RefIter < RefEnd) {
10197 // In positional-style format strings, the same specifier can appear
10198 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
10199 // are sorted by getPosition(), and we process each range of equal
10200 // getPosition() values as one group.
10201 // RefArgs are taken from a string literal that was given to
10202 // attribute(format_matches), and if we got this far, we have already
10203 // verified that if it has positional specifiers that appear in multiple
10204 // locations, then they are all mutually compatible. What's left for us to
10205 // do is verify that all specifiers with the same position in FmtArgs are
10206 // compatible with the RefArgs specifiers. We check each specifier from
10207 // FmtArgs against the first member of the RefArgs group.
10208 for (; FmtIter < FmtEnd; ++FmtIter) {
10209 // Clang does not diagnose missing format specifiers in positional-style
10210 // strings (TODO: which it probably should do, as it is UB to skip over a
10211 // format argument). Skip specifiers if needed.
10212 if (FmtIter->getPosition() < RefIter->getPosition())
10213 continue;
10214
10215 // Delimits a new getPosition() value.
10216 if (FmtIter->getPosition() > RefIter->getPosition())
10217 break;
10218
10219 HadError |=
10220 !FmtIter->VerifyCompatible(S, Other: *RefIter, FmtExpr, InFunctionCall);
10221 }
10222
10223 // Jump RefIter to the start of the next group.
10224 RefIter = std::find_if(first: RefIter + 1, last: RefEnd, pred: [=](const auto &Arg) {
10225 return Arg.getPosition() != RefIter->getPosition();
10226 });
10227 }
10228
10229 if (FmtIter < FmtEnd) {
10230 CheckFormatHandler::EmitFormatDiagnostic(
10231 S, InFunctionCall, ArgumentExpr: FmtExpr,
10232 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 1,
10233 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: FmtIter->getSourceRange());
10234 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with) << 1;
10235 } else if (RefIter < RefEnd) {
10236 CheckFormatHandler::EmitFormatDiagnostic(
10237 S, InFunctionCall, ArgumentExpr: FmtExpr,
10238 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 0,
10239 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: Fmt->getSourceRange());
10240 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with)
10241 << 1 << RefIter->getSourceRange();
10242 }
10243 return !HadError;
10244}
10245
10246static void CheckFormatString(
10247 Sema &S, const FormatStringLiteral *FExpr,
10248 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
10249 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
10250 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
10251 bool inFunctionCall, VariadicCallType CallType,
10252 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10253 bool IgnoreStringsWithoutSpecifiers) {
10254 // CHECK: is the format string a wide literal?
10255 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10256 CheckFormatHandler::EmitFormatDiagnostic(
10257 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10258 PDiag: S.PDiag(DiagID: diag::warn_format_string_is_wide_literal), Loc: FExpr->getBeginLoc(),
10259 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
10260 return;
10261 }
10262
10263 // Str - The format string. NOTE: this is NOT null-terminated!
10264 StringRef StrRef = FExpr->getString();
10265 const char *Str = StrRef.data();
10266 // Account for cases where the string literal is truncated in a declaration.
10267 const ConstantArrayType *T =
10268 S.Context.getAsConstantArrayType(T: FExpr->getType());
10269 assert(T && "String literal not of constant array type!");
10270 size_t TypeSize = T->getZExtSize();
10271 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
10272 const unsigned numDataArgs = Args.size() - firstDataArg;
10273
10274 if (IgnoreStringsWithoutSpecifiers &&
10275 !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10276 Begin: Str, End: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
10277 return;
10278
10279 // Emit a warning if the string literal is truncated and does not contain an
10280 // embedded null character.
10281 if (TypeSize <= StrRef.size() && !StrRef.substr(Start: 0, N: TypeSize).contains(C: '\0')) {
10282 CheckFormatHandler::EmitFormatDiagnostic(
10283 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10284 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_not_null_terminated),
10285 Loc: FExpr->getBeginLoc(),
10286 /*IsStringLocation=*/true, StringRange: OrigFormatExpr->getSourceRange());
10287 return;
10288 }
10289
10290 // CHECK: empty format string?
10291 if (StrLen == 0 && numDataArgs > 0) {
10292 CheckFormatHandler::EmitFormatDiagnostic(
10293 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10294 PDiag: S.PDiag(DiagID: diag::warn_empty_format_string), Loc: FExpr->getBeginLoc(),
10295 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
10296 return;
10297 }
10298
10299 if (Type == FormatStringType::Printf || Type == FormatStringType::NSString ||
10300 Type == FormatStringType::Kprintf ||
10301 Type == FormatStringType::FreeBSDKPrintf ||
10302 Type == FormatStringType::OSLog || Type == FormatStringType::OSTrace) {
10303 bool IsObjC =
10304 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10305 if (ReferenceFormatString == nullptr) {
10306 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10307 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10308 inFunctionCall, CallType, CheckedVarArgs,
10309 UncoveredArg);
10310
10311 if (!analyze_format_string::ParsePrintfString(
10312 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
10313 isFreeBSDKPrintf: Type == FormatStringType::Kprintf ||
10314 Type == FormatStringType::FreeBSDKPrintf))
10315 H.DoneProcessing();
10316 } else {
10317 S.CheckFormatStringsCompatible(
10318 FST: Type, AuthoritativeFormatString: ReferenceFormatString, TestedFormatString: FExpr->getFormatString(),
10319 FunctionCallArg: inFunctionCall ? nullptr : Args[format_idx]);
10320 }
10321 } else if (Type == FormatStringType::Scanf) {
10322 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10323 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10324 CallType, CheckedVarArgs, UncoveredArg);
10325
10326 if (!analyze_format_string::ParseScanfString(
10327 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
10328 H.DoneProcessing();
10329 } // TODO: handle other formats
10330}
10331
10332bool Sema::CheckFormatStringsCompatible(
10333 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
10334 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
10335 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
10336 Type != FormatStringType::Kprintf &&
10337 Type != FormatStringType::FreeBSDKPrintf &&
10338 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
10339 return true;
10340
10341 bool IsObjC =
10342 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10343 llvm::SmallVector<EquatableFormatArgument, 9> RefArgs, FmtArgs;
10344 FormatStringLiteral RefLit = AuthoritativeFormatString;
10345 FormatStringLiteral TestLit = TestedFormatString;
10346 const Expr *Arg;
10347 bool DiagAtStringLiteral;
10348 if (FunctionCallArg) {
10349 Arg = FunctionCallArg;
10350 DiagAtStringLiteral = false;
10351 } else {
10352 Arg = TestedFormatString;
10353 DiagAtStringLiteral = true;
10354 }
10355 if (DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit,
10356 FmtExpr: AuthoritativeFormatString, Type,
10357 IsObjC, InFunctionCall: true, Args&: RefArgs) &&
10358 DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &TestLit, FmtExpr: Arg, Type, IsObjC,
10359 InFunctionCall: DiagAtStringLiteral, Args&: FmtArgs)) {
10360 return CompareFormatSpecifiers(S&: *this, Ref: AuthoritativeFormatString, RefArgs,
10361 Fmt: TestedFormatString, FmtArgs, FmtExpr: Arg,
10362 InFunctionCall: DiagAtStringLiteral);
10363 }
10364 return false;
10365}
10366
10367bool Sema::ValidateFormatString(FormatStringType Type,
10368 const StringLiteral *Str) {
10369 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
10370 Type != FormatStringType::Kprintf &&
10371 Type != FormatStringType::FreeBSDKPrintf &&
10372 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
10373 return true;
10374
10375 FormatStringLiteral RefLit = Str;
10376 llvm::SmallVector<EquatableFormatArgument, 9> Args;
10377 bool IsObjC =
10378 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10379 if (!DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit, FmtExpr: Str, Type, IsObjC,
10380 InFunctionCall: true, Args))
10381 return false;
10382
10383 // Group arguments by getPosition() value, and check that each member of the
10384 // group is compatible with the first member. This verifies that when
10385 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10386 // are mutually compatible. As an optimization, don't test the first member
10387 // against itself.
10388 bool HadError = false;
10389 auto Iter = Args.begin();
10390 auto End = Args.end();
10391 while (Iter != End) {
10392 const auto &FirstInGroup = *Iter;
10393 for (++Iter;
10394 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10395 ++Iter) {
10396 HadError |= !Iter->VerifyCompatible(S&: *this, Other: FirstInGroup, FmtExpr: Str, InFunctionCall: true);
10397 }
10398 }
10399 return !HadError;
10400}
10401
10402bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10403 // Str - The format string. NOTE: this is NOT null-terminated!
10404 StringRef StrRef = FExpr->getString();
10405 const char *Str = StrRef.data();
10406 // Account for cases where the string literal is truncated in a declaration.
10407 const ConstantArrayType *T = Context.getAsConstantArrayType(T: FExpr->getType());
10408 assert(T && "String literal not of constant array type!");
10409 size_t TypeSize = T->getZExtSize();
10410 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
10411 return analyze_format_string::ParseFormatStringHasSArg(
10412 beg: Str, end: Str + StrLen, LO: getLangOpts(), Target: Context.getTargetInfo());
10413}
10414
10415//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10416
10417// Returns the related absolute value function that is larger, of 0 if one
10418// does not exist.
10419static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10420 switch (AbsFunction) {
10421 default:
10422 return 0;
10423
10424 case Builtin::BI__builtin_abs:
10425 return Builtin::BI__builtin_labs;
10426 case Builtin::BI__builtin_labs:
10427 return Builtin::BI__builtin_llabs;
10428 case Builtin::BI__builtin_llabs:
10429 return 0;
10430
10431 case Builtin::BI__builtin_fabsf:
10432 return Builtin::BI__builtin_fabs;
10433 case Builtin::BI__builtin_fabs:
10434 return Builtin::BI__builtin_fabsl;
10435 case Builtin::BI__builtin_fabsl:
10436 return 0;
10437
10438 case Builtin::BI__builtin_cabsf:
10439 return Builtin::BI__builtin_cabs;
10440 case Builtin::BI__builtin_cabs:
10441 return Builtin::BI__builtin_cabsl;
10442 case Builtin::BI__builtin_cabsl:
10443 return 0;
10444
10445 case Builtin::BIabs:
10446 return Builtin::BIlabs;
10447 case Builtin::BIlabs:
10448 return Builtin::BIllabs;
10449 case Builtin::BIllabs:
10450 return 0;
10451
10452 case Builtin::BIfabsf:
10453 return Builtin::BIfabs;
10454 case Builtin::BIfabs:
10455 return Builtin::BIfabsl;
10456 case Builtin::BIfabsl:
10457 return 0;
10458
10459 case Builtin::BIcabsf:
10460 return Builtin::BIcabs;
10461 case Builtin::BIcabs:
10462 return Builtin::BIcabsl;
10463 case Builtin::BIcabsl:
10464 return 0;
10465 }
10466}
10467
10468// Returns the argument type of the absolute value function.
10469static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10470 unsigned AbsType) {
10471 if (AbsType == 0)
10472 return QualType();
10473
10474 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10475 QualType BuiltinType = Context.GetBuiltinType(ID: AbsType, Error);
10476 if (Error != ASTContext::GE_None)
10477 return QualType();
10478
10479 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10480 if (!FT)
10481 return QualType();
10482
10483 if (FT->getNumParams() != 1)
10484 return QualType();
10485
10486 return FT->getParamType(i: 0);
10487}
10488
10489// Returns the best absolute value function, or zero, based on type and
10490// current absolute value function.
10491static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10492 unsigned AbsFunctionKind) {
10493 unsigned BestKind = 0;
10494 uint64_t ArgSize = Context.getTypeSize(T: ArgType);
10495 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10496 Kind = getLargerAbsoluteValueFunction(AbsFunction: Kind)) {
10497 QualType ParamType = getAbsoluteValueArgumentType(Context, AbsType: Kind);
10498 if (Context.getTypeSize(T: ParamType) >= ArgSize) {
10499 if (BestKind == 0)
10500 BestKind = Kind;
10501 else if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
10502 BestKind = Kind;
10503 break;
10504 }
10505 }
10506 }
10507 return BestKind;
10508}
10509
10510enum AbsoluteValueKind {
10511 AVK_Integer,
10512 AVK_Floating,
10513 AVK_Complex
10514};
10515
10516static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10517 if (T->isIntegralOrEnumerationType())
10518 return AVK_Integer;
10519 if (T->isRealFloatingType())
10520 return AVK_Floating;
10521 if (T->isAnyComplexType())
10522 return AVK_Complex;
10523
10524 llvm_unreachable("Type not integer, floating, or complex");
10525}
10526
10527// Changes the absolute value function to a different type. Preserves whether
10528// the function is a builtin.
10529static unsigned changeAbsFunction(unsigned AbsKind,
10530 AbsoluteValueKind ValueKind) {
10531 switch (ValueKind) {
10532 case AVK_Integer:
10533 switch (AbsKind) {
10534 default:
10535 return 0;
10536 case Builtin::BI__builtin_fabsf:
10537 case Builtin::BI__builtin_fabs:
10538 case Builtin::BI__builtin_fabsl:
10539 case Builtin::BI__builtin_cabsf:
10540 case Builtin::BI__builtin_cabs:
10541 case Builtin::BI__builtin_cabsl:
10542 return Builtin::BI__builtin_abs;
10543 case Builtin::BIfabsf:
10544 case Builtin::BIfabs:
10545 case Builtin::BIfabsl:
10546 case Builtin::BIcabsf:
10547 case Builtin::BIcabs:
10548 case Builtin::BIcabsl:
10549 return Builtin::BIabs;
10550 }
10551 case AVK_Floating:
10552 switch (AbsKind) {
10553 default:
10554 return 0;
10555 case Builtin::BI__builtin_abs:
10556 case Builtin::BI__builtin_labs:
10557 case Builtin::BI__builtin_llabs:
10558 case Builtin::BI__builtin_cabsf:
10559 case Builtin::BI__builtin_cabs:
10560 case Builtin::BI__builtin_cabsl:
10561 return Builtin::BI__builtin_fabsf;
10562 case Builtin::BIabs:
10563 case Builtin::BIlabs:
10564 case Builtin::BIllabs:
10565 case Builtin::BIcabsf:
10566 case Builtin::BIcabs:
10567 case Builtin::BIcabsl:
10568 return Builtin::BIfabsf;
10569 }
10570 case AVK_Complex:
10571 switch (AbsKind) {
10572 default:
10573 return 0;
10574 case Builtin::BI__builtin_abs:
10575 case Builtin::BI__builtin_labs:
10576 case Builtin::BI__builtin_llabs:
10577 case Builtin::BI__builtin_fabsf:
10578 case Builtin::BI__builtin_fabs:
10579 case Builtin::BI__builtin_fabsl:
10580 return Builtin::BI__builtin_cabsf;
10581 case Builtin::BIabs:
10582 case Builtin::BIlabs:
10583 case Builtin::BIllabs:
10584 case Builtin::BIfabsf:
10585 case Builtin::BIfabs:
10586 case Builtin::BIfabsl:
10587 return Builtin::BIcabsf;
10588 }
10589 }
10590 llvm_unreachable("Unable to convert function");
10591}
10592
10593static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10594 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10595 if (!FnInfo)
10596 return 0;
10597
10598 switch (FDecl->getBuiltinID()) {
10599 default:
10600 return 0;
10601 case Builtin::BI__builtin_abs:
10602 case Builtin::BI__builtin_fabs:
10603 case Builtin::BI__builtin_fabsf:
10604 case Builtin::BI__builtin_fabsl:
10605 case Builtin::BI__builtin_labs:
10606 case Builtin::BI__builtin_llabs:
10607 case Builtin::BI__builtin_cabs:
10608 case Builtin::BI__builtin_cabsf:
10609 case Builtin::BI__builtin_cabsl:
10610 case Builtin::BIabs:
10611 case Builtin::BIlabs:
10612 case Builtin::BIllabs:
10613 case Builtin::BIfabs:
10614 case Builtin::BIfabsf:
10615 case Builtin::BIfabsl:
10616 case Builtin::BIcabs:
10617 case Builtin::BIcabsf:
10618 case Builtin::BIcabsl:
10619 return FDecl->getBuiltinID();
10620 }
10621 llvm_unreachable("Unknown Builtin type");
10622}
10623
10624// If the replacement is valid, emit a note with replacement function.
10625// Additionally, suggest including the proper header if not already included.
10626static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10627 unsigned AbsKind, QualType ArgType) {
10628 bool EmitHeaderHint = true;
10629 const char *HeaderName = nullptr;
10630 std::string FunctionName;
10631 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10632 FunctionName = "std::abs";
10633 if (ArgType->isIntegralOrEnumerationType()) {
10634 HeaderName = "cstdlib";
10635 } else if (ArgType->isRealFloatingType()) {
10636 HeaderName = "cmath";
10637 } else {
10638 llvm_unreachable("Invalid Type");
10639 }
10640
10641 // Lookup all std::abs
10642 if (NamespaceDecl *Std = S.getStdNamespace()) {
10643 LookupResult R(S, &S.Context.Idents.get(Name: "abs"), Loc, Sema::LookupAnyName);
10644 R.suppressDiagnostics();
10645 S.LookupQualifiedName(R, LookupCtx: Std);
10646
10647 for (const auto *I : R) {
10648 const FunctionDecl *FDecl = nullptr;
10649 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(Val: I)) {
10650 FDecl = dyn_cast<FunctionDecl>(Val: UsingD->getTargetDecl());
10651 } else {
10652 FDecl = dyn_cast<FunctionDecl>(Val: I);
10653 }
10654 if (!FDecl)
10655 continue;
10656
10657 // Found std::abs(), check that they are the right ones.
10658 if (FDecl->getNumParams() != 1)
10659 continue;
10660
10661 // Check that the parameter type can handle the argument.
10662 QualType ParamType = FDecl->getParamDecl(i: 0)->getType();
10663 if (getAbsoluteValueKind(T: ArgType) == getAbsoluteValueKind(T: ParamType) &&
10664 S.Context.getTypeSize(T: ArgType) <=
10665 S.Context.getTypeSize(T: ParamType)) {
10666 // Found a function, don't need the header hint.
10667 EmitHeaderHint = false;
10668 break;
10669 }
10670 }
10671 }
10672 } else {
10673 FunctionName = S.Context.BuiltinInfo.getName(ID: AbsKind);
10674 HeaderName = S.Context.BuiltinInfo.getHeaderName(ID: AbsKind);
10675
10676 if (HeaderName) {
10677 DeclarationName DN(&S.Context.Idents.get(Name: FunctionName));
10678 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10679 R.suppressDiagnostics();
10680 S.LookupName(R, S: S.getCurScope());
10681
10682 if (R.isSingleResult()) {
10683 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
10684 if (FD && FD->getBuiltinID() == AbsKind) {
10685 EmitHeaderHint = false;
10686 } else {
10687 return;
10688 }
10689 } else if (!R.empty()) {
10690 return;
10691 }
10692 }
10693 }
10694
10695 S.Diag(Loc, DiagID: diag::note_replace_abs_function)
10696 << FunctionName << FixItHint::CreateReplacement(RemoveRange: Range, Code: FunctionName);
10697
10698 if (!HeaderName)
10699 return;
10700
10701 if (!EmitHeaderHint)
10702 return;
10703
10704 S.Diag(Loc, DiagID: diag::note_include_header_or_declare) << HeaderName
10705 << FunctionName;
10706}
10707
10708template <std::size_t StrLen>
10709static bool IsStdFunction(const FunctionDecl *FDecl,
10710 const char (&Str)[StrLen]) {
10711 if (!FDecl)
10712 return false;
10713 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10714 return false;
10715 if (!FDecl->isInStdNamespace())
10716 return false;
10717
10718 return true;
10719}
10720
10721enum class MathCheck { NaN, Inf };
10722static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10723 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10724 return llvm::is_contained(Set: names, Element: calleeName);
10725 };
10726
10727 switch (Check) {
10728 case MathCheck::NaN:
10729 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10730 "__builtin_nanf16", "__builtin_nanf128"});
10731 case MathCheck::Inf:
10732 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10733 "__builtin_inff16", "__builtin_inff128"});
10734 }
10735 llvm_unreachable("unknown MathCheck");
10736}
10737
10738static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10739 if (FDecl->getName() != "infinity")
10740 return false;
10741
10742 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(Val: FDecl)) {
10743 const CXXRecordDecl *RDecl = MDecl->getParent();
10744 if (RDecl->getName() != "numeric_limits")
10745 return false;
10746
10747 if (const NamespaceDecl *NSDecl =
10748 dyn_cast<NamespaceDecl>(Val: RDecl->getDeclContext()))
10749 return NSDecl->isStdNamespace();
10750 }
10751
10752 return false;
10753}
10754
10755void Sema::CheckInfNaNFunction(const CallExpr *Call,
10756 const FunctionDecl *FDecl) {
10757 if (!FDecl->getIdentifier())
10758 return;
10759
10760 FPOptions FPO = Call->getFPFeaturesInEffect(LO: getLangOpts());
10761 if (FPO.getNoHonorNaNs() &&
10762 (IsStdFunction(FDecl, Str: "isnan") || IsStdFunction(FDecl, Str: "isunordered") ||
10763 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::NaN))) {
10764 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10765 << 1 << 0 << Call->getSourceRange();
10766 return;
10767 }
10768
10769 if (FPO.getNoHonorInfs() &&
10770 (IsStdFunction(FDecl, Str: "isinf") || IsStdFunction(FDecl, Str: "isfinite") ||
10771 IsInfinityFunction(FDecl) ||
10772 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::Inf))) {
10773 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10774 << 0 << 0 << Call->getSourceRange();
10775 }
10776}
10777
10778void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10779 const FunctionDecl *FDecl) {
10780 if (Call->getNumArgs() != 1)
10781 return;
10782
10783 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10784 bool IsStdAbs = IsStdFunction(FDecl, Str: "abs");
10785 if (AbsKind == 0 && !IsStdAbs)
10786 return;
10787
10788 QualType ArgType = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
10789 QualType ParamType = Call->getArg(Arg: 0)->getType();
10790
10791 // Unsigned types cannot be negative. Suggest removing the absolute value
10792 // function call.
10793 if (ArgType->isUnsignedIntegerType()) {
10794 std::string FunctionName =
10795 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(ID: AbsKind);
10796 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_unsigned_abs) << ArgType << ParamType;
10797 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_abs)
10798 << FunctionName
10799 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange());
10800 return;
10801 }
10802
10803 // Taking the absolute value of a pointer is very suspicious, they probably
10804 // wanted to index into an array, dereference a pointer, call a function, etc.
10805 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10806 unsigned DiagType = 0;
10807 if (ArgType->isFunctionType())
10808 DiagType = 1;
10809 else if (ArgType->isArrayType())
10810 DiagType = 2;
10811
10812 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_pointer_abs) << DiagType << ArgType;
10813 return;
10814 }
10815
10816 // std::abs has overloads which prevent most of the absolute value problems
10817 // from occurring.
10818 if (IsStdAbs)
10819 return;
10820
10821 // Prevent reaching unreachable code in getAbsoluteValueKind for unsupported
10822 // types.
10823 if (!ArgType->isIntegralOrEnumerationType() &&
10824 !ArgType->isRealFloatingType() && !ArgType->isAnyComplexType())
10825 return;
10826
10827 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(T: ArgType);
10828 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(T: ParamType);
10829
10830 // The argument and parameter are the same kind. Check if they are the right
10831 // size.
10832 if (ArgValueKind == ParamValueKind) {
10833 if (Context.getTypeSize(T: ArgType) <= Context.getTypeSize(T: ParamType))
10834 return;
10835
10836 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: AbsKind);
10837 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_abs_too_small)
10838 << FDecl << ArgType << ParamType;
10839
10840 if (NewAbsKind == 0)
10841 return;
10842
10843 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10844 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10845 return;
10846 }
10847
10848 // ArgValueKind != ParamValueKind
10849 // The wrong type of absolute value function was used. Attempt to find the
10850 // proper one.
10851 unsigned NewAbsKind = changeAbsFunction(AbsKind, ValueKind: ArgValueKind);
10852 NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: NewAbsKind);
10853 if (NewAbsKind == 0)
10854 return;
10855
10856 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_wrong_absolute_value_type)
10857 << FDecl << ParamValueKind << ArgValueKind;
10858
10859 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10860 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10861}
10862
10863//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10864void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10865 const FunctionDecl *FDecl) {
10866 if (!Call || !FDecl) return;
10867
10868 // Ignore template specializations and macros.
10869 if (inTemplateInstantiation()) return;
10870 if (Call->getExprLoc().isMacroID()) return;
10871
10872 // Only care about the one template argument, two function parameter std::max
10873 if (Call->getNumArgs() != 2) return;
10874 if (!IsStdFunction(FDecl, Str: "max")) return;
10875 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10876 if (!ArgList) return;
10877 if (ArgList->size() != 1) return;
10878
10879 // Check that template type argument is unsigned integer.
10880 const auto& TA = ArgList->get(Idx: 0);
10881 if (TA.getKind() != TemplateArgument::Type) return;
10882 QualType ArgType = TA.getAsType();
10883 if (!ArgType->isUnsignedIntegerType()) return;
10884
10885 // See if either argument is a literal zero.
10886 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10887 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E);
10888 if (!MTE) return false;
10889 const auto *Num = dyn_cast<IntegerLiteral>(Val: MTE->getSubExpr());
10890 if (!Num) return false;
10891 if (Num->getValue() != 0) return false;
10892 return true;
10893 };
10894
10895 const Expr *FirstArg = Call->getArg(Arg: 0);
10896 const Expr *SecondArg = Call->getArg(Arg: 1);
10897 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10898 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10899
10900 // Only warn when exactly one argument is zero.
10901 if (IsFirstArgZero == IsSecondArgZero) return;
10902
10903 SourceRange FirstRange = FirstArg->getSourceRange();
10904 SourceRange SecondRange = SecondArg->getSourceRange();
10905
10906 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10907
10908 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_max_unsigned_zero)
10909 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10910
10911 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10912 SourceRange RemovalRange;
10913 if (IsFirstArgZero) {
10914 RemovalRange = SourceRange(FirstRange.getBegin(),
10915 SecondRange.getBegin().getLocWithOffset(Offset: -1));
10916 } else {
10917 RemovalRange = SourceRange(getLocForEndOfToken(Loc: FirstRange.getEnd()),
10918 SecondRange.getEnd());
10919 }
10920
10921 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_max_call)
10922 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange())
10923 << FixItHint::CreateRemoval(RemoveRange: RemovalRange);
10924}
10925
10926//===--- CHECK: Standard memory functions ---------------------------------===//
10927
10928/// Takes the expression passed to the size_t parameter of functions
10929/// such as memcmp, strncat, etc and warns if it's a comparison.
10930///
10931/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10932static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10933 const IdentifierInfo *FnName,
10934 SourceLocation FnLoc,
10935 SourceLocation RParenLoc) {
10936 const auto *Size = dyn_cast<BinaryOperator>(Val: E);
10937 if (!Size)
10938 return false;
10939
10940 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10941 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10942 return false;
10943
10944 SourceRange SizeRange = Size->getSourceRange();
10945 S.Diag(Loc: Size->getOperatorLoc(), DiagID: diag::warn_memsize_comparison)
10946 << SizeRange << FnName;
10947 S.Diag(Loc: FnLoc, DiagID: diag::note_memsize_comparison_paren)
10948 << FnName
10949 << FixItHint::CreateInsertion(
10950 InsertionLoc: S.getLocForEndOfToken(Loc: Size->getLHS()->getEndLoc()), Code: ")")
10951 << FixItHint::CreateRemoval(RemoveRange: RParenLoc);
10952 S.Diag(Loc: SizeRange.getBegin(), DiagID: diag::note_memsize_comparison_cast_silence)
10953 << FixItHint::CreateInsertion(InsertionLoc: SizeRange.getBegin(), Code: "(size_t)(")
10954 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: SizeRange.getEnd()),
10955 Code: ")");
10956
10957 return true;
10958}
10959
10960/// Determine whether the given type is or contains a dynamic class type
10961/// (e.g., whether it has a vtable).
10962static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10963 bool &IsContained) {
10964 // Look through array types while ignoring qualifiers.
10965 const Type *Ty = T->getBaseElementTypeUnsafe();
10966 IsContained = false;
10967
10968 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10969 RD = RD ? RD->getDefinition() : nullptr;
10970 if (!RD || RD->isInvalidDecl())
10971 return nullptr;
10972
10973 if (RD->isDynamicClass())
10974 return RD;
10975
10976 // Check all the fields. If any bases were dynamic, the class is dynamic.
10977 // It's impossible for a class to transitively contain itself by value, so
10978 // infinite recursion is impossible.
10979 for (auto *FD : RD->fields()) {
10980 bool SubContained;
10981 if (const CXXRecordDecl *ContainedRD =
10982 getContainedDynamicClass(T: FD->getType(), IsContained&: SubContained)) {
10983 IsContained = true;
10984 return ContainedRD;
10985 }
10986 }
10987
10988 return nullptr;
10989}
10990
10991static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10992 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: E))
10993 if (Unary->getKind() == UETT_SizeOf)
10994 return Unary;
10995 return nullptr;
10996}
10997
10998/// If E is a sizeof expression, returns its argument expression,
10999/// otherwise returns NULL.
11000static const Expr *getSizeOfExprArg(const Expr *E) {
11001 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
11002 if (!SizeOf->isArgumentType())
11003 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
11004 return nullptr;
11005}
11006
11007/// If E is a sizeof expression, returns its argument type.
11008static QualType getSizeOfArgType(const Expr *E) {
11009 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
11010 return SizeOf->getTypeOfArgument();
11011 return QualType();
11012}
11013
11014namespace {
11015
11016struct SearchNonTrivialToInitializeField
11017 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
11018 using Super =
11019 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
11020
11021 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
11022
11023 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
11024 SourceLocation SL) {
11025 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
11026 asDerived().visitArray(PDIK, AT, SL);
11027 return;
11028 }
11029
11030 Super::visitWithKind(PDIK, FT, Args&: SL);
11031 }
11032
11033 void visitARCStrong(QualType FT, SourceLocation SL) {
11034 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
11035 }
11036 void visitARCWeak(QualType FT, SourceLocation SL) {
11037 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
11038 }
11039 void visitStruct(QualType FT, SourceLocation SL) {
11040 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
11041 visit(FT: FD->getType(), Args: FD->getLocation());
11042 }
11043 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
11044 const ArrayType *AT, SourceLocation SL) {
11045 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
11046 }
11047 void visitTrivial(QualType FT, SourceLocation SL) {}
11048
11049 static void diag(QualType RT, const Expr *E, Sema &S) {
11050 SearchNonTrivialToInitializeField(E, S).visitStruct(FT: RT, SL: SourceLocation());
11051 }
11052
11053 ASTContext &getContext() { return S.getASTContext(); }
11054
11055 const Expr *E;
11056 Sema &S;
11057};
11058
11059struct SearchNonTrivialToCopyField
11060 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
11061 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
11062
11063 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
11064
11065 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
11066 SourceLocation SL) {
11067 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
11068 asDerived().visitArray(PCK, AT, SL);
11069 return;
11070 }
11071
11072 Super::visitWithKind(PCK, FT, Args&: SL);
11073 }
11074
11075 void visitARCStrong(QualType FT, SourceLocation SL) {
11076 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
11077 }
11078 void visitARCWeak(QualType FT, SourceLocation SL) {
11079 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
11080 }
11081 void visitPtrAuth(QualType FT, SourceLocation SL) {
11082 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
11083 }
11084 void visitStruct(QualType FT, SourceLocation SL) {
11085 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
11086 visit(FT: FD->getType(), Args: FD->getLocation());
11087 }
11088 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
11089 SourceLocation SL) {
11090 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
11091 }
11092 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
11093 SourceLocation SL) {}
11094 void visitTrivial(QualType FT, SourceLocation SL) {}
11095 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
11096
11097 static void diag(QualType RT, const Expr *E, Sema &S) {
11098 SearchNonTrivialToCopyField(E, S).visitStruct(FT: RT, SL: SourceLocation());
11099 }
11100
11101 ASTContext &getContext() { return S.getASTContext(); }
11102
11103 const Expr *E;
11104 Sema &S;
11105};
11106
11107}
11108
11109/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
11110static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
11111 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
11112
11113 if (const auto *BO = dyn_cast<BinaryOperator>(Val: SizeofExpr)) {
11114 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
11115 return false;
11116
11117 return doesExprLikelyComputeSize(SizeofExpr: BO->getLHS()) ||
11118 doesExprLikelyComputeSize(SizeofExpr: BO->getRHS());
11119 }
11120
11121 return getAsSizeOfExpr(E: SizeofExpr) != nullptr;
11122}
11123
11124/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
11125///
11126/// \code
11127/// #define MACRO 0
11128/// foo(MACRO);
11129/// foo(0);
11130/// \endcode
11131///
11132/// This should return true for the first call to foo, but not for the second
11133/// (regardless of whether foo is a macro or function).
11134static bool isArgumentExpandedFromMacro(SourceManager &SM,
11135 SourceLocation CallLoc,
11136 SourceLocation ArgLoc) {
11137 if (!CallLoc.isMacroID())
11138 return SM.getFileID(SpellingLoc: CallLoc) != SM.getFileID(SpellingLoc: ArgLoc);
11139
11140 return SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: CallLoc)) !=
11141 SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: ArgLoc));
11142}
11143
11144/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
11145/// last two arguments transposed.
11146static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
11147 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
11148 return;
11149
11150 const Expr *SizeArg =
11151 Call->getArg(Arg: BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
11152
11153 auto isLiteralZero = [](const Expr *E) {
11154 return (isa<IntegerLiteral>(Val: E) &&
11155 cast<IntegerLiteral>(Val: E)->getValue() == 0) ||
11156 (isa<CharacterLiteral>(Val: E) &&
11157 cast<CharacterLiteral>(Val: E)->getValue() == 0);
11158 };
11159
11160 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
11161 SourceLocation CallLoc = Call->getRParenLoc();
11162 SourceManager &SM = S.getSourceManager();
11163 if (isLiteralZero(SizeArg) &&
11164 !isArgumentExpandedFromMacro(SM, CallLoc, ArgLoc: SizeArg->getExprLoc())) {
11165
11166 SourceLocation DiagLoc = SizeArg->getExprLoc();
11167
11168 // Some platforms #define bzero to __builtin_memset. See if this is the
11169 // case, and if so, emit a better diagnostic.
11170 if (BId == Builtin::BIbzero ||
11171 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
11172 Loc: CallLoc, SM, LangOpts: S.getLangOpts()) == "bzero")) {
11173 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_bzero_size);
11174 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_bzero_size_silence);
11175 } else if (!isLiteralZero(Call->getArg(Arg: 1)->IgnoreImpCasts())) {
11176 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 0;
11177 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 0;
11178 }
11179 return;
11180 }
11181
11182 // If the second argument to a memset is a sizeof expression and the third
11183 // isn't, this is also likely an error. This should catch
11184 // 'memset(buf, sizeof(buf), 0xff)'.
11185 if (BId == Builtin::BImemset &&
11186 doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 1)) &&
11187 !doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 2))) {
11188 SourceLocation DiagLoc = Call->getArg(Arg: 1)->getExprLoc();
11189 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 1;
11190 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 1;
11191 return;
11192 }
11193}
11194
11195void Sema::CheckMemaccessArguments(const CallExpr *Call,
11196 unsigned BId,
11197 IdentifierInfo *FnName) {
11198 assert(BId != 0);
11199
11200 // It is possible to have a non-standard definition of memset. Validate
11201 // we have enough arguments, and if not, abort further checking.
11202 unsigned ExpectedNumArgs =
11203 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11204 if (Call->getNumArgs() < ExpectedNumArgs)
11205 return;
11206
11207 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11208 BId == Builtin::BIstrndup ? 1 : 2);
11209 unsigned LenArg =
11210 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11211 const Expr *LenExpr = Call->getArg(Arg: LenArg)->IgnoreParenImpCasts();
11212
11213 if (CheckMemorySizeofForComparison(S&: *this, E: LenExpr, FnName,
11214 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
11215 return;
11216
11217 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11218 CheckMemaccessSize(S&: *this, BId, Call);
11219
11220 // We have special checking when the length is a sizeof expression.
11221 QualType SizeOfArgTy = getSizeOfArgType(E: LenExpr);
11222
11223 // Although widely used, 'bzero' is not a standard function. Be more strict
11224 // with the argument types before allowing diagnostics and only allow the
11225 // form bzero(ptr, sizeof(...)).
11226 QualType FirstArgTy = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
11227 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11228 return;
11229
11230 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11231 const Expr *Dest = Call->getArg(Arg: ArgIdx)->IgnoreParenImpCasts();
11232 SourceRange ArgRange = Call->getArg(Arg: ArgIdx)->getSourceRange();
11233
11234 QualType DestTy = Dest->getType();
11235 QualType PointeeTy;
11236 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11237 PointeeTy = DestPtrTy->getPointeeType();
11238
11239 // Never warn about void type pointers. This can be used to suppress
11240 // false positives.
11241 if (PointeeTy->isVoidType())
11242 continue;
11243
11244 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11245 // actually comparing the expressions for equality. Because computing the
11246 // expression IDs can be expensive, we only do this if the diagnostic is
11247 // enabled.
11248 if (CheckSizeofMemaccessArgument(SizeOfArg: LenExpr, Dest, FnName))
11249 break;
11250
11251 // Also check for cases where the sizeof argument is the exact same
11252 // type as the memory argument, and where it points to a user-defined
11253 // record type.
11254 if (SizeOfArgTy != QualType()) {
11255 if (PointeeTy->isRecordType() &&
11256 Context.typesAreCompatible(T1: SizeOfArgTy, T2: DestTy)) {
11257 DiagRuntimeBehavior(Loc: LenExpr->getExprLoc(), Statement: Dest,
11258 PD: PDiag(DiagID: diag::warn_sizeof_pointer_type_memaccess)
11259 << FnName << SizeOfArgTy << ArgIdx
11260 << PointeeTy << Dest->getSourceRange()
11261 << LenExpr->getSourceRange());
11262 break;
11263 }
11264 }
11265 } else if (DestTy->isArrayType()) {
11266 PointeeTy = DestTy;
11267 }
11268
11269 if (PointeeTy == QualType())
11270 continue;
11271
11272 // Always complain about dynamic classes.
11273 bool IsContained;
11274 if (const CXXRecordDecl *ContainedRD =
11275 getContainedDynamicClass(T: PointeeTy, IsContained)) {
11276
11277 unsigned OperationType = 0;
11278 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11279 // "overwritten" if we're warning about the destination for any call
11280 // but memcmp; otherwise a verb appropriate to the call.
11281 if (ArgIdx != 0 || IsCmp) {
11282 if (BId == Builtin::BImemcpy)
11283 OperationType = 1;
11284 else if(BId == Builtin::BImemmove)
11285 OperationType = 2;
11286 else if (IsCmp)
11287 OperationType = 3;
11288 }
11289
11290 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11291 PD: PDiag(DiagID: diag::warn_dyn_class_memaccess)
11292 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11293 << IsContained << ContainedRD << OperationType
11294 << Call->getCallee()->getSourceRange());
11295 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11296 BId != Builtin::BImemset)
11297 DiagRuntimeBehavior(
11298 Loc: Dest->getExprLoc(), Statement: Dest,
11299 PD: PDiag(DiagID: diag::warn_arc_object_memaccess)
11300 << ArgIdx << FnName << PointeeTy
11301 << Call->getCallee()->getSourceRange());
11302 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
11303
11304 // FIXME: Do not consider incomplete types even though they may be
11305 // completed later. GCC does not diagnose such code, but we may want to
11306 // consider diagnosing it in the future, perhaps under a different, but
11307 // related, diagnostic group.
11308 bool NonTriviallyCopyableCXXRecord =
11309 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
11310 !PointeeTy.isTriviallyCopyableType(Context);
11311
11312 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11313 RD->isNonTrivialToPrimitiveDefaultInitialize()) {
11314 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11315 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
11316 << ArgIdx << FnName << PointeeTy << 0);
11317 SearchNonTrivialToInitializeField::diag(RT: PointeeTy, E: Dest, S&: *this);
11318 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11319 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11320 // FIXME: Limiting this warning to dest argument until we decide
11321 // whether it's valid for source argument too.
11322 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11323 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
11324 << FnName << PointeeTy);
11325 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11326 RD->isNonTrivialToPrimitiveCopy()) {
11327 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11328 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
11329 << ArgIdx << FnName << PointeeTy << 1);
11330 SearchNonTrivialToCopyField::diag(RT: PointeeTy, E: Dest, S&: *this);
11331 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11332 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11333 // FIXME: Limiting this warning to dest argument until we decide
11334 // whether it's valid for source argument too.
11335 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11336 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
11337 << FnName << PointeeTy);
11338 } else {
11339 continue;
11340 }
11341 } else
11342 continue;
11343
11344 DiagRuntimeBehavior(
11345 Loc: Dest->getExprLoc(), Statement: Dest,
11346 PD: PDiag(DiagID: diag::note_bad_memaccess_silence)
11347 << FixItHint::CreateInsertion(InsertionLoc: ArgRange.getBegin(), Code: "(void*)"));
11348 break;
11349 }
11350}
11351
11352bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
11353 IdentifierInfo *FnName) {
11354 llvm::FoldingSetNodeID SizeOfArgID;
11355 const Expr *SizeOfArg = getSizeOfExprArg(E: LenExpr);
11356 if (!SizeOfArg)
11357 return false;
11358 // Computing this warning is expensive, so we only do so if the warning is
11359 // enabled.
11360 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess,
11361 Loc: SizeOfArg->getExprLoc()))
11362 return false;
11363 QualType DestTy = Dest->getType();
11364 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
11365 if (!DestPtrTy)
11366 return false;
11367
11368 QualType PointeeTy = DestPtrTy->getPointeeType();
11369
11370 if (SizeOfArgID == llvm::FoldingSetNodeID())
11371 SizeOfArg->Profile(ID&: SizeOfArgID, Context, Canonical: true);
11372
11373 llvm::FoldingSetNodeID DestID;
11374 Dest->Profile(ID&: DestID, Context, Canonical: true);
11375 if (DestID == SizeOfArgID) {
11376 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11377 // over sizeof(src) as well.
11378 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11379 StringRef ReadableName = FnName->getName();
11380
11381 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Val: Dest);
11382 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11383 ActionIdx = 1; // If its an address-of operator, just remove it.
11384 if (!PointeeTy->isIncompleteType() &&
11385 (Context.getTypeSize(T: PointeeTy) == Context.getCharWidth()))
11386 ActionIdx = 2; // If the pointee's size is sizeof(char),
11387 // suggest an explicit length.
11388
11389 // If the function is defined as a builtin macro, do not show macro
11390 // expansion.
11391 SourceLocation SL = SizeOfArg->getExprLoc();
11392 SourceRange DSR = Dest->getSourceRange();
11393 SourceRange SSR = SizeOfArg->getSourceRange();
11394 SourceManager &SM = getSourceManager();
11395
11396 if (SM.isMacroArgExpansion(Loc: SL)) {
11397 ReadableName = Lexer::getImmediateMacroName(Loc: SL, SM, LangOpts);
11398 SL = SM.getSpellingLoc(Loc: SL);
11399 DSR = SourceRange(SM.getSpellingLoc(Loc: DSR.getBegin()),
11400 SM.getSpellingLoc(Loc: DSR.getEnd()));
11401 SSR = SourceRange(SM.getSpellingLoc(Loc: SSR.getBegin()),
11402 SM.getSpellingLoc(Loc: SSR.getEnd()));
11403 }
11404
11405 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
11406 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess)
11407 << ReadableName << PointeeTy << DestTy << DSR
11408 << SSR);
11409 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
11410 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess_note)
11411 << ActionIdx << SSR);
11412 return true;
11413 }
11414 return false;
11415}
11416
11417// A little helper routine: ignore addition and subtraction of integer literals.
11418// This intentionally does not ignore all integer constant expressions because
11419// we don't want to remove sizeof().
11420static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11421 Ex = Ex->IgnoreParenCasts();
11422
11423 while (true) {
11424 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Val: Ex);
11425 if (!BO || !BO->isAdditiveOp())
11426 break;
11427
11428 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11429 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11430
11431 if (isa<IntegerLiteral>(Val: RHS))
11432 Ex = LHS;
11433 else if (isa<IntegerLiteral>(Val: LHS))
11434 Ex = RHS;
11435 else
11436 break;
11437 }
11438
11439 return Ex;
11440}
11441
11442static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11443 ASTContext &Context) {
11444 // Only handle constant-sized or VLAs, but not flexible members.
11445 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T: Ty)) {
11446 // Only issue the FIXIT for arrays of size > 1.
11447 if (CAT->getZExtSize() <= 1)
11448 return false;
11449 } else if (!Ty->isVariableArrayType()) {
11450 return false;
11451 }
11452 return true;
11453}
11454
11455void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11456 IdentifierInfo *FnName) {
11457
11458 // Don't crash if the user has the wrong number of arguments
11459 unsigned NumArgs = Call->getNumArgs();
11460 if ((NumArgs != 3) && (NumArgs != 4))
11461 return;
11462
11463 const Expr *SrcArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 1), Ctx&: Context);
11464 const Expr *SizeArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 2), Ctx&: Context);
11465 const Expr *CompareWithSrc = nullptr;
11466
11467 if (CheckMemorySizeofForComparison(S&: *this, E: SizeArg, FnName,
11468 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
11469 return;
11470
11471 // Look for 'strlcpy(dst, x, sizeof(x))'
11472 if (const Expr *Ex = getSizeOfExprArg(E: SizeArg))
11473 CompareWithSrc = Ex;
11474 else {
11475 // Look for 'strlcpy(dst, x, strlen(x))'
11476 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(Val: SizeArg)) {
11477 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11478 SizeCall->getNumArgs() == 1)
11479 CompareWithSrc = ignoreLiteralAdditions(Ex: SizeCall->getArg(Arg: 0), Ctx&: Context);
11480 }
11481 }
11482
11483 if (!CompareWithSrc)
11484 return;
11485
11486 // Determine if the argument to sizeof/strlen is equal to the source
11487 // argument. In principle there's all kinds of things you could do
11488 // here, for instance creating an == expression and evaluating it with
11489 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11490 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(Val: SrcArg);
11491 if (!SrcArgDRE)
11492 return;
11493
11494 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(Val: CompareWithSrc);
11495 if (!CompareWithSrcDRE ||
11496 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11497 return;
11498
11499 const Expr *OriginalSizeArg = Call->getArg(Arg: 2);
11500 Diag(Loc: CompareWithSrcDRE->getBeginLoc(), DiagID: diag::warn_strlcpycat_wrong_size)
11501 << OriginalSizeArg->getSourceRange() << FnName;
11502
11503 // Output a FIXIT hint if the destination is an array (rather than a
11504 // pointer to an array). This could be enhanced to handle some
11505 // pointers if we know the actual size, like if DstArg is 'array+2'
11506 // we could say 'sizeof(array)-2'.
11507 const Expr *DstArg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
11508 if (!isConstantSizeArrayWithMoreThanOneElement(Ty: DstArg->getType(), Context))
11509 return;
11510
11511 SmallString<128> sizeString;
11512 llvm::raw_svector_ostream OS(sizeString);
11513 OS << "sizeof(";
11514 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11515 OS << ")";
11516
11517 Diag(Loc: OriginalSizeArg->getBeginLoc(), DiagID: diag::note_strlcpycat_wrong_size)
11518 << FixItHint::CreateReplacement(RemoveRange: OriginalSizeArg->getSourceRange(),
11519 Code: OS.str());
11520}
11521
11522/// Check if two expressions refer to the same declaration.
11523static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11524 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(Val: E1))
11525 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(Val: E2))
11526 return D1->getDecl() == D2->getDecl();
11527 return false;
11528}
11529
11530static const Expr *getStrlenExprArg(const Expr *E) {
11531 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
11532 const FunctionDecl *FD = CE->getDirectCallee();
11533 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11534 return nullptr;
11535 return CE->getArg(Arg: 0)->IgnoreParenCasts();
11536 }
11537 return nullptr;
11538}
11539
11540void Sema::CheckStrncatArguments(const CallExpr *CE,
11541 const IdentifierInfo *FnName) {
11542 // Don't crash if the user has the wrong number of arguments.
11543 if (CE->getNumArgs() < 3)
11544 return;
11545 const Expr *DstArg = CE->getArg(Arg: 0)->IgnoreParenCasts();
11546 const Expr *SrcArg = CE->getArg(Arg: 1)->IgnoreParenCasts();
11547 const Expr *LenArg = CE->getArg(Arg: 2)->IgnoreParenCasts();
11548
11549 if (CheckMemorySizeofForComparison(S&: *this, E: LenArg, FnName, FnLoc: CE->getBeginLoc(),
11550 RParenLoc: CE->getRParenLoc()))
11551 return;
11552
11553 // Identify common expressions, which are wrongly used as the size argument
11554 // to strncat and may lead to buffer overflows.
11555 unsigned PatternType = 0;
11556 if (const Expr *SizeOfArg = getSizeOfExprArg(E: LenArg)) {
11557 // - sizeof(dst)
11558 if (referToTheSameDecl(E1: SizeOfArg, E2: DstArg))
11559 PatternType = 1;
11560 // - sizeof(src)
11561 else if (referToTheSameDecl(E1: SizeOfArg, E2: SrcArg))
11562 PatternType = 2;
11563 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Val: LenArg)) {
11564 if (BE->getOpcode() == BO_Sub) {
11565 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11566 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11567 // - sizeof(dst) - strlen(dst)
11568 if (referToTheSameDecl(E1: DstArg, E2: getSizeOfExprArg(E: L)) &&
11569 referToTheSameDecl(E1: DstArg, E2: getStrlenExprArg(E: R)))
11570 PatternType = 1;
11571 // - sizeof(src) - (anything)
11572 else if (referToTheSameDecl(E1: SrcArg, E2: getSizeOfExprArg(E: L)))
11573 PatternType = 2;
11574 }
11575 }
11576
11577 if (PatternType == 0)
11578 return;
11579
11580 // Generate the diagnostic.
11581 SourceLocation SL = LenArg->getBeginLoc();
11582 SourceRange SR = LenArg->getSourceRange();
11583 SourceManager &SM = getSourceManager();
11584
11585 // If the function is defined as a builtin macro, do not show macro expansion.
11586 if (SM.isMacroArgExpansion(Loc: SL)) {
11587 SL = SM.getSpellingLoc(Loc: SL);
11588 SR = SourceRange(SM.getSpellingLoc(Loc: SR.getBegin()),
11589 SM.getSpellingLoc(Loc: SR.getEnd()));
11590 }
11591
11592 // Check if the destination is an array (rather than a pointer to an array).
11593 QualType DstTy = DstArg->getType();
11594 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(Ty: DstTy,
11595 Context);
11596 if (!isKnownSizeArray) {
11597 if (PatternType == 1)
11598 Diag(Loc: SL, DiagID: diag::warn_strncat_wrong_size) << SR;
11599 else
11600 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11601 return;
11602 }
11603
11604 if (PatternType == 1)
11605 Diag(Loc: SL, DiagID: diag::warn_strncat_large_size) << SR;
11606 else
11607 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11608
11609 SmallString<128> sizeString;
11610 llvm::raw_svector_ostream OS(sizeString);
11611 OS << "sizeof(";
11612 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11613 OS << ") - ";
11614 OS << "strlen(";
11615 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11616 OS << ") - 1";
11617
11618 Diag(Loc: SL, DiagID: diag::note_strncat_wrong_size)
11619 << FixItHint::CreateReplacement(RemoveRange: SR, Code: OS.str());
11620}
11621
11622namespace {
11623void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11624 const UnaryOperator *UnaryExpr, const Decl *D) {
11625 if (isa<FieldDecl, FunctionDecl, VarDecl>(Val: D)) {
11626 S.Diag(Loc: UnaryExpr->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11627 << CalleeName << 0 /*object: */ << cast<NamedDecl>(Val: D);
11628 return;
11629 }
11630}
11631
11632void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11633 const UnaryOperator *UnaryExpr) {
11634 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: UnaryExpr->getSubExpr())) {
11635 const Decl *D = Lvalue->getDecl();
11636 if (const auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
11637 if (!DD->getType()->isReferenceType())
11638 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11639 }
11640 }
11641
11642 if (const auto *Lvalue = dyn_cast<MemberExpr>(Val: UnaryExpr->getSubExpr()))
11643 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11644 D: Lvalue->getMemberDecl());
11645}
11646
11647void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11648 const UnaryOperator *UnaryExpr) {
11649 const auto *Lambda = dyn_cast<LambdaExpr>(
11650 Val: UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11651 if (!Lambda)
11652 return;
11653
11654 S.Diag(Loc: Lambda->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11655 << CalleeName << 2 /*object: lambda expression*/;
11656}
11657
11658void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11659 const DeclRefExpr *Lvalue) {
11660 const auto *Var = dyn_cast<VarDecl>(Val: Lvalue->getDecl());
11661 if (Var == nullptr)
11662 return;
11663
11664 S.Diag(Loc: Lvalue->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11665 << CalleeName << 0 /*object: */ << Var;
11666}
11667
11668void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11669 const CastExpr *Cast) {
11670 SmallString<128> SizeString;
11671 llvm::raw_svector_ostream OS(SizeString);
11672
11673 clang::CastKind Kind = Cast->getCastKind();
11674 if (Kind == clang::CK_BitCast &&
11675 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11676 return;
11677 if (Kind == clang::CK_IntegralToPointer &&
11678 !isa<IntegerLiteral>(
11679 Val: Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11680 return;
11681
11682 switch (Cast->getCastKind()) {
11683 case clang::CK_BitCast:
11684 case clang::CK_IntegralToPointer:
11685 case clang::CK_FunctionToPointerDecay:
11686 OS << '\'';
11687 Cast->printPretty(OS, Helper: nullptr, Policy: S.getPrintingPolicy());
11688 OS << '\'';
11689 break;
11690 default:
11691 return;
11692 }
11693
11694 S.Diag(Loc: Cast->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11695 << CalleeName << 0 /*object: */ << OS.str();
11696}
11697} // namespace
11698
11699void Sema::CheckFreeArguments(const CallExpr *E) {
11700 const std::string CalleeName =
11701 cast<FunctionDecl>(Val: E->getCalleeDecl())->getQualifiedNameAsString();
11702
11703 { // Prefer something that doesn't involve a cast to make things simpler.
11704 const Expr *Arg = E->getArg(Arg: 0)->IgnoreParenCasts();
11705 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Val: Arg))
11706 switch (UnaryExpr->getOpcode()) {
11707 case UnaryOperator::Opcode::UO_AddrOf:
11708 return CheckFreeArgumentsAddressof(S&: *this, CalleeName, UnaryExpr);
11709 case UnaryOperator::Opcode::UO_Plus:
11710 return CheckFreeArgumentsPlus(S&: *this, CalleeName, UnaryExpr);
11711 default:
11712 break;
11713 }
11714
11715 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: Arg))
11716 if (Lvalue->getType()->isArrayType())
11717 return CheckFreeArgumentsStackArray(S&: *this, CalleeName, Lvalue);
11718
11719 if (const auto *Label = dyn_cast<AddrLabelExpr>(Val: Arg)) {
11720 Diag(Loc: Label->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11721 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11722 return;
11723 }
11724
11725 if (isa<BlockExpr>(Val: Arg)) {
11726 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11727 << CalleeName << 1 /*object: block*/;
11728 return;
11729 }
11730 }
11731 // Maybe the cast was important, check after the other cases.
11732 if (const auto *Cast = dyn_cast<CastExpr>(Val: E->getArg(Arg: 0)))
11733 return CheckFreeArgumentsCast(S&: *this, CalleeName, Cast);
11734}
11735
11736void
11737Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11738 SourceLocation ReturnLoc,
11739 bool isObjCMethod,
11740 const AttrVec *Attrs,
11741 const FunctionDecl *FD) {
11742 // Check if the return value is null but should not be.
11743 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(container: *Attrs)) ||
11744 (!isObjCMethod && isNonNullType(type: lhsType))) &&
11745 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11746 Diag(Loc: ReturnLoc, DiagID: diag::warn_null_ret)
11747 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11748
11749 // C++11 [basic.stc.dynamic.allocation]p4:
11750 // If an allocation function declared with a non-throwing
11751 // exception-specification fails to allocate storage, it shall return
11752 // a null pointer. Any other allocation function that fails to allocate
11753 // storage shall indicate failure only by throwing an exception [...]
11754 if (FD) {
11755 OverloadedOperatorKind Op = FD->getOverloadedOperator();
11756 if (Op == OO_New || Op == OO_Array_New) {
11757 const FunctionProtoType *Proto
11758 = FD->getType()->castAs<FunctionProtoType>();
11759 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11760 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11761 Diag(Loc: ReturnLoc, DiagID: diag::warn_operator_new_returns_null)
11762 << FD << getLangOpts().CPlusPlus11;
11763 }
11764 }
11765
11766 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11767 Diag(Loc: ReturnLoc, DiagID: diag::err_wasm_table_art) << 1;
11768 }
11769
11770 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11771 // here prevent the user from using a PPC MMA type as trailing return type.
11772 if (Context.getTargetInfo().getTriple().isPPC64())
11773 PPC().CheckPPCMMAType(Type: RetValExp->getType(), TypeLoc: ReturnLoc);
11774}
11775
11776void Sema::CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
11777 const Expr *RHS, BinaryOperatorKind Opcode) {
11778 if (!BinaryOperator::isEqualityOp(Opc: Opcode))
11779 return;
11780
11781 // Match and capture subexpressions such as "(float) X == 0.1".
11782 const FloatingLiteral *FPLiteral;
11783 const CastExpr *FPCast;
11784 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11785 FPLiteral = dyn_cast<FloatingLiteral>(Val: L->IgnoreParens());
11786 FPCast = dyn_cast<CastExpr>(Val: R->IgnoreParens());
11787 return FPLiteral && FPCast;
11788 };
11789
11790 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11791 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11792 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11793 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11794 TargetTy->isFloatingPoint()) {
11795 bool Lossy;
11796 llvm::APFloat TargetC = FPLiteral->getValue();
11797 TargetC.convert(ToSemantics: Context.getFloatTypeSemantics(T: QualType(SourceTy, 0)),
11798 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Lossy);
11799 if (Lossy) {
11800 // If the literal cannot be represented in the source type, then a
11801 // check for == is always false and check for != is always true.
11802 Diag(Loc, DiagID: diag::warn_float_compare_literal)
11803 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11804 << LHS->getSourceRange() << RHS->getSourceRange();
11805 return;
11806 }
11807 }
11808 }
11809
11810 // Match a more general floating-point equality comparison (-Wfloat-equal).
11811 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11812 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11813
11814 // Special case: check for x == x (which is OK).
11815 // Do not emit warnings for such cases.
11816 if (const auto *DRL = dyn_cast<DeclRefExpr>(Val: LeftExprSansParen))
11817 if (const auto *DRR = dyn_cast<DeclRefExpr>(Val: RightExprSansParen))
11818 if (DRL->getDecl() == DRR->getDecl())
11819 return;
11820
11821 // Special case: check for comparisons against literals that can be exactly
11822 // represented by APFloat. In such cases, do not emit a warning. This
11823 // is a heuristic: often comparison against such literals are used to
11824 // detect if a value in a variable has not changed. This clearly can
11825 // lead to false negatives.
11826 if (const auto *FLL = dyn_cast<FloatingLiteral>(Val: LeftExprSansParen)) {
11827 if (FLL->isExact())
11828 return;
11829 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(Val: RightExprSansParen))
11830 if (FLR->isExact())
11831 return;
11832
11833 // Check for comparisons with builtin types.
11834 if (const auto *CL = dyn_cast<CallExpr>(Val: LeftExprSansParen);
11835 CL && CL->getBuiltinCallee())
11836 return;
11837
11838 if (const auto *CR = dyn_cast<CallExpr>(Val: RightExprSansParen);
11839 CR && CR->getBuiltinCallee())
11840 return;
11841
11842 // Emit the diagnostic.
11843 Diag(Loc, DiagID: diag::warn_floatingpoint_eq)
11844 << LHS->getSourceRange() << RHS->getSourceRange();
11845}
11846
11847//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11848//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11849
11850namespace {
11851
11852/// Structure recording the 'active' range of an integer-valued
11853/// expression.
11854struct IntRange {
11855 /// The number of bits active in the int. Note that this includes exactly one
11856 /// sign bit if !NonNegative.
11857 unsigned Width;
11858
11859 /// True if the int is known not to have negative values. If so, all leading
11860 /// bits before Width are known zero, otherwise they are known to be the
11861 /// same as the MSB within Width.
11862 bool NonNegative;
11863
11864 IntRange(unsigned Width, bool NonNegative)
11865 : Width(Width), NonNegative(NonNegative) {}
11866
11867 /// Number of bits excluding the sign bit.
11868 unsigned valueBits() const {
11869 return NonNegative ? Width : Width - 1;
11870 }
11871
11872 /// Returns the range of the bool type.
11873 static IntRange forBoolType() {
11874 return IntRange(1, true);
11875 }
11876
11877 /// Returns the range of an opaque value of the given integral type.
11878 static IntRange forValueOfType(ASTContext &C, QualType T) {
11879 return forValueOfCanonicalType(C,
11880 T: T->getCanonicalTypeInternal().getTypePtr());
11881 }
11882
11883 /// Returns the range of an opaque value of a canonical integral type.
11884 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11885 assert(T->isCanonicalUnqualified());
11886
11887 if (const auto *VT = dyn_cast<VectorType>(Val: T))
11888 T = VT->getElementType().getTypePtr();
11889 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
11890 T = MT->getElementType().getTypePtr();
11891 if (const auto *CT = dyn_cast<ComplexType>(Val: T))
11892 T = CT->getElementType().getTypePtr();
11893 if (const auto *AT = dyn_cast<AtomicType>(Val: T))
11894 T = AT->getValueType().getTypePtr();
11895 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11896 T = OBT->getUnderlyingType().getTypePtr();
11897
11898 if (!C.getLangOpts().CPlusPlus) {
11899 // For enum types in C code, use the underlying datatype.
11900 if (const auto *ED = T->getAsEnumDecl())
11901 T = ED->getIntegerType().getDesugaredType(Context: C).getTypePtr();
11902 } else if (auto *Enum = T->getAsEnumDecl()) {
11903 // For enum types in C++, use the known bit width of the enumerators.
11904 // In C++11, enums can have a fixed underlying type. Use this type to
11905 // compute the range.
11906 if (Enum->isFixed()) {
11907 return IntRange(C.getIntWidth(T: QualType(T, 0)),
11908 !Enum->getIntegerType()->isSignedIntegerType());
11909 }
11910
11911 unsigned NumPositive = Enum->getNumPositiveBits();
11912 unsigned NumNegative = Enum->getNumNegativeBits();
11913
11914 if (NumNegative == 0)
11915 return IntRange(NumPositive, true/*NonNegative*/);
11916 else
11917 return IntRange(std::max(a: NumPositive + 1, b: NumNegative),
11918 false/*NonNegative*/);
11919 }
11920
11921 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11922 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11923
11924 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11925 assert(BT->isInteger());
11926
11927 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11928 }
11929
11930 /// Returns the "target" range of a canonical integral type, i.e.
11931 /// the range of values expressible in the type.
11932 ///
11933 /// This matches forValueOfCanonicalType except that enums have the
11934 /// full range of their type, not the range of their enumerators.
11935 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11936 assert(T->isCanonicalUnqualified());
11937
11938 if (const VectorType *VT = dyn_cast<VectorType>(Val: T))
11939 T = VT->getElementType().getTypePtr();
11940 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
11941 T = MT->getElementType().getTypePtr();
11942 if (const ComplexType *CT = dyn_cast<ComplexType>(Val: T))
11943 T = CT->getElementType().getTypePtr();
11944 if (const AtomicType *AT = dyn_cast<AtomicType>(Val: T))
11945 T = AT->getValueType().getTypePtr();
11946 if (const auto *ED = T->getAsEnumDecl())
11947 T = C.getCanonicalType(T: ED->getIntegerType()).getTypePtr();
11948 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11949 T = OBT->getUnderlyingType().getTypePtr();
11950
11951 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11952 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11953
11954 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11955 assert(BT->isInteger());
11956
11957 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11958 }
11959
11960 /// Returns the supremum of two ranges: i.e. their conservative merge.
11961 static IntRange join(IntRange L, IntRange R) {
11962 bool Unsigned = L.NonNegative && R.NonNegative;
11963 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
11964 L.NonNegative && R.NonNegative);
11965 }
11966
11967 /// Return the range of a bitwise-AND of the two ranges.
11968 static IntRange bit_and(IntRange L, IntRange R) {
11969 unsigned Bits = std::max(a: L.Width, b: R.Width);
11970 bool NonNegative = false;
11971 if (L.NonNegative) {
11972 Bits = std::min(a: Bits, b: L.Width);
11973 NonNegative = true;
11974 }
11975 if (R.NonNegative) {
11976 Bits = std::min(a: Bits, b: R.Width);
11977 NonNegative = true;
11978 }
11979 return IntRange(Bits, NonNegative);
11980 }
11981
11982 /// Return the range of a sum of the two ranges.
11983 static IntRange sum(IntRange L, IntRange R) {
11984 bool Unsigned = L.NonNegative && R.NonNegative;
11985 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + 1 + !Unsigned,
11986 Unsigned);
11987 }
11988
11989 /// Return the range of a difference of the two ranges.
11990 static IntRange difference(IntRange L, IntRange R) {
11991 // We need a 1-bit-wider range if:
11992 // 1) LHS can be negative: least value can be reduced.
11993 // 2) RHS can be negative: greatest value can be increased.
11994 bool CanWiden = !L.NonNegative || !R.NonNegative;
11995 bool Unsigned = L.NonNegative && R.Width == 0;
11996 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + CanWiden +
11997 !Unsigned,
11998 Unsigned);
11999 }
12000
12001 /// Return the range of a product of the two ranges.
12002 static IntRange product(IntRange L, IntRange R) {
12003 // If both LHS and RHS can be negative, we can form
12004 // -2^L * -2^R = 2^(L + R)
12005 // which requires L + R + 1 value bits to represent.
12006 bool CanWiden = !L.NonNegative && !R.NonNegative;
12007 bool Unsigned = L.NonNegative && R.NonNegative;
12008 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
12009 Unsigned);
12010 }
12011
12012 /// Return the range of a remainder operation between the two ranges.
12013 static IntRange rem(IntRange L, IntRange R) {
12014 // The result of a remainder can't be larger than the result of
12015 // either side. The sign of the result is the sign of the LHS.
12016 bool Unsigned = L.NonNegative;
12017 return IntRange(std::min(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
12018 Unsigned);
12019 }
12020};
12021
12022} // namespace
12023
12024static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
12025 if (value.isSigned() && value.isNegative())
12026 return IntRange(value.getSignificantBits(), false);
12027
12028 if (value.getBitWidth() > MaxWidth)
12029 value = value.trunc(width: MaxWidth);
12030
12031 // isNonNegative() just checks the sign bit without considering
12032 // signedness.
12033 return IntRange(value.getActiveBits(), true);
12034}
12035
12036static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
12037 if (result.isInt())
12038 return GetValueRange(value&: result.getInt(), MaxWidth);
12039
12040 if (result.isVector()) {
12041 IntRange R = GetValueRange(result&: result.getVectorElt(I: 0), Ty, MaxWidth);
12042 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
12043 IntRange El = GetValueRange(result&: result.getVectorElt(I: i), Ty, MaxWidth);
12044 R = IntRange::join(L: R, R: El);
12045 }
12046 return R;
12047 }
12048
12049 if (result.isComplexInt()) {
12050 IntRange R = GetValueRange(value&: result.getComplexIntReal(), MaxWidth);
12051 IntRange I = GetValueRange(value&: result.getComplexIntImag(), MaxWidth);
12052 return IntRange::join(L: R, R: I);
12053 }
12054
12055 // This can happen with lossless casts to intptr_t of "based" lvalues.
12056 // Assume it might use arbitrary bits.
12057 // FIXME: The only reason we need to pass the type in here is to get
12058 // the sign right on this one case. It would be nice if APValue
12059 // preserved this.
12060 assert(result.isLValue() || result.isAddrLabelDiff());
12061 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
12062}
12063
12064static QualType GetExprType(const Expr *E) {
12065 QualType Ty = E->getType();
12066 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
12067 Ty = AtomicRHS->getValueType();
12068 return Ty;
12069}
12070
12071/// Attempts to estimate an approximate range for the given integer expression.
12072/// Returns a range if successful, otherwise it returns \c std::nullopt if a
12073/// reliable estimation cannot be determined.
12074///
12075/// \param MaxWidth The width to which the value will be truncated.
12076/// \param InConstantContext If \c true, interpret the expression within a
12077/// constant context.
12078/// \param Approximate If \c true, provide a likely range of values by assuming
12079/// that arithmetic on narrower types remains within those types.
12080/// If \c false, return a range that includes all possible values
12081/// resulting from the expression.
12082/// \returns A range of values that the expression might take, or
12083/// std::nullopt if a reliable estimation cannot be determined.
12084static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12085 unsigned MaxWidth,
12086 bool InConstantContext,
12087 bool Approximate) {
12088 E = E->IgnoreParens();
12089
12090 // Try a full evaluation first.
12091 Expr::EvalResult result;
12092 if (E->EvaluateAsRValue(Result&: result, Ctx: C, InConstantContext))
12093 return GetValueRange(result&: result.Val, Ty: GetExprType(E), MaxWidth);
12094
12095 // I think we only want to look through implicit casts here; if the
12096 // user has an explicit widening cast, we should treat the value as
12097 // being of the new, wider type.
12098 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Val: E)) {
12099 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
12100 return TryGetExprRange(C, E: CE->getSubExpr(), MaxWidth, InConstantContext,
12101 Approximate);
12102
12103 IntRange OutputTypeRange = IntRange::forValueOfType(C, T: GetExprType(E: CE));
12104
12105 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
12106 CE->getCastKind() == CK_BooleanToSignedIntegral;
12107
12108 // Assume that non-integer casts can span the full range of the type.
12109 if (!isIntegerCast)
12110 return OutputTypeRange;
12111
12112 std::optional<IntRange> SubRange = TryGetExprRange(
12113 C, E: CE->getSubExpr(), MaxWidth: std::min(a: MaxWidth, b: OutputTypeRange.Width),
12114 InConstantContext, Approximate);
12115 if (!SubRange)
12116 return std::nullopt;
12117
12118 // Bail out if the subexpr's range is as wide as the cast type.
12119 if (SubRange->Width >= OutputTypeRange.Width)
12120 return OutputTypeRange;
12121
12122 // Otherwise, we take the smaller width, and we're non-negative if
12123 // either the output type or the subexpr is.
12124 return IntRange(SubRange->Width,
12125 SubRange->NonNegative || OutputTypeRange.NonNegative);
12126 }
12127
12128 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12129 // If we can fold the condition, just take that operand.
12130 bool CondResult;
12131 if (CO->getCond()->EvaluateAsBooleanCondition(Result&: CondResult, Ctx: C))
12132 return TryGetExprRange(
12133 C, E: CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
12134 InConstantContext, Approximate);
12135
12136 // Otherwise, conservatively merge.
12137 // TryGetExprRange requires an integer expression, but a throw expression
12138 // results in a void type.
12139 Expr *TrueExpr = CO->getTrueExpr();
12140 if (TrueExpr->getType()->isVoidType())
12141 return std::nullopt;
12142
12143 std::optional<IntRange> L =
12144 TryGetExprRange(C, E: TrueExpr, MaxWidth, InConstantContext, Approximate);
12145 if (!L)
12146 return std::nullopt;
12147
12148 Expr *FalseExpr = CO->getFalseExpr();
12149 if (FalseExpr->getType()->isVoidType())
12150 return std::nullopt;
12151
12152 std::optional<IntRange> R =
12153 TryGetExprRange(C, E: FalseExpr, MaxWidth, InConstantContext, Approximate);
12154 if (!R)
12155 return std::nullopt;
12156
12157 return IntRange::join(L: *L, R: *R);
12158 }
12159
12160 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
12161 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
12162
12163 switch (BO->getOpcode()) {
12164 case BO_Cmp:
12165 llvm_unreachable("builtin <=> should have class type");
12166
12167 // Boolean-valued operations are single-bit and positive.
12168 case BO_LAnd:
12169 case BO_LOr:
12170 case BO_LT:
12171 case BO_GT:
12172 case BO_LE:
12173 case BO_GE:
12174 case BO_EQ:
12175 case BO_NE:
12176 return IntRange::forBoolType();
12177
12178 // The type of the assignments is the type of the LHS, so the RHS
12179 // is not necessarily the same type.
12180 case BO_MulAssign:
12181 case BO_DivAssign:
12182 case BO_RemAssign:
12183 case BO_AddAssign:
12184 case BO_SubAssign:
12185 case BO_XorAssign:
12186 case BO_OrAssign:
12187 // TODO: bitfields?
12188 return IntRange::forValueOfType(C, T: GetExprType(E));
12189
12190 // Simple assignments just pass through the RHS, which will have
12191 // been coerced to the LHS type.
12192 case BO_Assign:
12193 // TODO: bitfields?
12194 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
12195 Approximate);
12196
12197 // Operations with opaque sources are black-listed.
12198 case BO_PtrMemD:
12199 case BO_PtrMemI:
12200 return IntRange::forValueOfType(C, T: GetExprType(E));
12201
12202 // Bitwise-and uses the *infinum* of the two source ranges.
12203 case BO_And:
12204 case BO_AndAssign:
12205 Combine = IntRange::bit_and;
12206 break;
12207
12208 // Left shift gets black-listed based on a judgement call.
12209 case BO_Shl:
12210 // ...except that we want to treat '1 << (blah)' as logically
12211 // positive. It's an important idiom.
12212 if (IntegerLiteral *I
12213 = dyn_cast<IntegerLiteral>(Val: BO->getLHS()->IgnoreParenCasts())) {
12214 if (I->getValue() == 1) {
12215 IntRange R = IntRange::forValueOfType(C, T: GetExprType(E));
12216 return IntRange(R.Width, /*NonNegative*/ true);
12217 }
12218 }
12219 [[fallthrough]];
12220
12221 case BO_ShlAssign:
12222 return IntRange::forValueOfType(C, T: GetExprType(E));
12223
12224 // Right shift by a constant can narrow its left argument.
12225 case BO_Shr:
12226 case BO_ShrAssign: {
12227 std::optional<IntRange> L = TryGetExprRange(
12228 C, E: BO->getLHS(), MaxWidth, InConstantContext, Approximate);
12229 if (!L)
12230 return std::nullopt;
12231
12232 // If the shift amount is a positive constant, drop the width by
12233 // that much.
12234 if (std::optional<llvm::APSInt> shift =
12235 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
12236 if (shift->isNonNegative()) {
12237 if (shift->uge(RHS: L->Width))
12238 L->Width = (L->NonNegative ? 0 : 1);
12239 else
12240 L->Width -= shift->getZExtValue();
12241 }
12242 }
12243
12244 return L;
12245 }
12246
12247 // Comma acts as its right operand.
12248 case BO_Comma:
12249 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
12250 Approximate);
12251
12252 case BO_Add:
12253 if (!Approximate)
12254 Combine = IntRange::sum;
12255 break;
12256
12257 case BO_Sub:
12258 if (BO->getLHS()->getType()->isPointerType())
12259 return IntRange::forValueOfType(C, T: GetExprType(E));
12260 if (!Approximate)
12261 Combine = IntRange::difference;
12262 break;
12263
12264 case BO_Mul:
12265 if (!Approximate)
12266 Combine = IntRange::product;
12267 break;
12268
12269 // The width of a division result is mostly determined by the size
12270 // of the LHS.
12271 case BO_Div: {
12272 // Don't 'pre-truncate' the operands.
12273 unsigned opWidth = C.getIntWidth(T: GetExprType(E));
12274 std::optional<IntRange> L = TryGetExprRange(
12275 C, E: BO->getLHS(), MaxWidth: opWidth, InConstantContext, Approximate);
12276 if (!L)
12277 return std::nullopt;
12278
12279 // If the divisor is constant, use that.
12280 if (std::optional<llvm::APSInt> divisor =
12281 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
12282 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12283 if (log2 >= L->Width)
12284 L->Width = (L->NonNegative ? 0 : 1);
12285 else
12286 L->Width = std::min(a: L->Width - log2, b: MaxWidth);
12287 return L;
12288 }
12289
12290 // Otherwise, just use the LHS's width.
12291 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12292 // could be -1.
12293 std::optional<IntRange> R = TryGetExprRange(
12294 C, E: BO->getRHS(), MaxWidth: opWidth, InConstantContext, Approximate);
12295 if (!R)
12296 return std::nullopt;
12297
12298 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12299 }
12300
12301 case BO_Rem:
12302 Combine = IntRange::rem;
12303 break;
12304
12305 // The default behavior is okay for these.
12306 case BO_Xor:
12307 case BO_Or:
12308 break;
12309 }
12310
12311 // Combine the two ranges, but limit the result to the type in which we
12312 // performed the computation.
12313 QualType T = GetExprType(E);
12314 unsigned opWidth = C.getIntWidth(T);
12315 std::optional<IntRange> L = TryGetExprRange(C, E: BO->getLHS(), MaxWidth: opWidth,
12316 InConstantContext, Approximate);
12317 if (!L)
12318 return std::nullopt;
12319
12320 std::optional<IntRange> R = TryGetExprRange(C, E: BO->getRHS(), MaxWidth: opWidth,
12321 InConstantContext, Approximate);
12322 if (!R)
12323 return std::nullopt;
12324
12325 IntRange C = Combine(*L, *R);
12326 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12327 C.Width = std::min(a: C.Width, b: MaxWidth);
12328 return C;
12329 }
12330
12331 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
12332 switch (UO->getOpcode()) {
12333 // Boolean-valued operations are white-listed.
12334 case UO_LNot:
12335 return IntRange::forBoolType();
12336
12337 // Operations with opaque sources are black-listed.
12338 case UO_Deref:
12339 case UO_AddrOf: // should be impossible
12340 return IntRange::forValueOfType(C, T: GetExprType(E));
12341
12342 case UO_Minus: {
12343 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12344 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12345 Approximate);
12346 }
12347
12348 std::optional<IntRange> SubRange = TryGetExprRange(
12349 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12350
12351 if (!SubRange)
12352 return std::nullopt;
12353
12354 // If the range was previously non-negative, we need an extra bit for the
12355 // sign bit. Otherwise, we need an extra bit because the negation of the
12356 // most-negative value is one bit wider than that value.
12357 return IntRange(std::min(a: SubRange->Width + 1, b: MaxWidth), false);
12358 }
12359
12360 case UO_Not: {
12361 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12362 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12363 Approximate);
12364 }
12365
12366 std::optional<IntRange> SubRange = TryGetExprRange(
12367 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12368
12369 if (!SubRange)
12370 return std::nullopt;
12371
12372 // The width increments by 1 if the sub-expression cannot be negative
12373 // since it now can be.
12374 return IntRange(
12375 std::min(a: SubRange->Width + (int)SubRange->NonNegative, b: MaxWidth),
12376 false);
12377 }
12378
12379 default:
12380 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12381 Approximate);
12382 }
12383 }
12384
12385 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
12386 // The source expression is null for the OpaqueValueExpr that stands in for
12387 // a non-type template argument of pointer or reference type; fall back to
12388 // the range of the type in that case.
12389 if (const Expr *SourceExpr = OVE->getSourceExpr())
12390 return TryGetExprRange(C, E: SourceExpr, MaxWidth, InConstantContext,
12391 Approximate);
12392 }
12393
12394 if (const auto *BitField = E->getSourceBitField())
12395 return IntRange(BitField->getBitWidthValue(),
12396 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12397
12398 if (GetExprType(E)->isVoidType())
12399 return std::nullopt;
12400
12401 return IntRange::forValueOfType(C, T: GetExprType(E));
12402}
12403
12404static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12405 bool InConstantContext,
12406 bool Approximate) {
12407 return TryGetExprRange(C, E, MaxWidth: C.getIntWidth(T: GetExprType(E)), InConstantContext,
12408 Approximate);
12409}
12410
12411/// Checks whether the given value, which currently has the given
12412/// source semantics, has the same value when coerced through the
12413/// target semantics.
12414static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12415 const llvm::fltSemantics &Src,
12416 const llvm::fltSemantics &Tgt) {
12417 llvm::APFloat truncated = value;
12418
12419 bool ignored;
12420 truncated.convert(ToSemantics: Src, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
12421 truncated.convert(ToSemantics: Tgt, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
12422
12423 return truncated.bitwiseIsEqual(RHS: value);
12424}
12425
12426/// Checks whether the given value, which currently has the given
12427/// source semantics, has the same value when coerced through the
12428/// target semantics.
12429///
12430/// The value might be a vector of floats (or a complex number).
12431static bool IsSameFloatAfterCast(const APValue &value,
12432 const llvm::fltSemantics &Src,
12433 const llvm::fltSemantics &Tgt) {
12434 if (value.isFloat())
12435 return IsSameFloatAfterCast(value: value.getFloat(), Src, Tgt);
12436
12437 if (value.isVector()) {
12438 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12439 if (!IsSameFloatAfterCast(value: value.getVectorElt(I: i), Src, Tgt))
12440 return false;
12441 return true;
12442 }
12443
12444 if (value.isMatrix()) {
12445 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12446 if (!IsSameFloatAfterCast(value: value.getMatrixElt(Idx: i), Src, Tgt))
12447 return false;
12448 return true;
12449 }
12450
12451 assert(value.isComplexFloat());
12452 return (IsSameFloatAfterCast(value: value.getComplexFloatReal(), Src, Tgt) &&
12453 IsSameFloatAfterCast(value: value.getComplexFloatImag(), Src, Tgt));
12454}
12455
12456static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12457 bool IsListInit = false);
12458
12459static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12460 // Suppress cases where we are comparing against an enum constant.
12461 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()))
12462 if (isa<EnumConstantDecl>(Val: DR->getDecl()))
12463 return true;
12464
12465 // Suppress cases where the value is expanded from a macro, unless that macro
12466 // is how a language represents a boolean literal. This is the case in both C
12467 // and Objective-C.
12468 SourceLocation BeginLoc = E->getBeginLoc();
12469 if (BeginLoc.isMacroID()) {
12470 StringRef MacroName = Lexer::getImmediateMacroName(
12471 Loc: BeginLoc, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
12472 return MacroName != "YES" && MacroName != "NO" &&
12473 MacroName != "true" && MacroName != "false";
12474 }
12475
12476 return false;
12477}
12478
12479static bool isKnownToHaveUnsignedValue(const Expr *E) {
12480 return E->getType()->isIntegerType() &&
12481 (!E->getType()->isSignedIntegerType() ||
12482 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
12483}
12484
12485namespace {
12486/// The promoted range of values of a type. In general this has the
12487/// following structure:
12488///
12489/// |-----------| . . . |-----------|
12490/// ^ ^ ^ ^
12491/// Min HoleMin HoleMax Max
12492///
12493/// ... where there is only a hole if a signed type is promoted to unsigned
12494/// (in which case Min and Max are the smallest and largest representable
12495/// values).
12496struct PromotedRange {
12497 // Min, or HoleMax if there is a hole.
12498 llvm::APSInt PromotedMin;
12499 // Max, or HoleMin if there is a hole.
12500 llvm::APSInt PromotedMax;
12501
12502 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12503 if (R.Width == 0)
12504 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12505 else if (R.Width >= BitWidth && !Unsigned) {
12506 // Promotion made the type *narrower*. This happens when promoting
12507 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12508 // Treat all values of 'signed int' as being in range for now.
12509 PromotedMin = llvm::APSInt::getMinValue(numBits: BitWidth, Unsigned);
12510 PromotedMax = llvm::APSInt::getMaxValue(numBits: BitWidth, Unsigned);
12511 } else {
12512 PromotedMin = llvm::APSInt::getMinValue(numBits: R.Width, Unsigned: R.NonNegative)
12513 .extOrTrunc(width: BitWidth);
12514 PromotedMin.setIsUnsigned(Unsigned);
12515
12516 PromotedMax = llvm::APSInt::getMaxValue(numBits: R.Width, Unsigned: R.NonNegative)
12517 .extOrTrunc(width: BitWidth);
12518 PromotedMax.setIsUnsigned(Unsigned);
12519 }
12520 }
12521
12522 // Determine whether this range is contiguous (has no hole).
12523 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12524
12525 // Where a constant value is within the range.
12526 enum ComparisonResult {
12527 LT = 0x1,
12528 LE = 0x2,
12529 GT = 0x4,
12530 GE = 0x8,
12531 EQ = 0x10,
12532 NE = 0x20,
12533 InRangeFlag = 0x40,
12534
12535 Less = LE | LT | NE,
12536 Min = LE | InRangeFlag,
12537 InRange = InRangeFlag,
12538 Max = GE | InRangeFlag,
12539 Greater = GE | GT | NE,
12540
12541 OnlyValue = LE | GE | EQ | InRangeFlag,
12542 InHole = NE
12543 };
12544
12545 ComparisonResult compare(const llvm::APSInt &Value) const {
12546 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12547 Value.isUnsigned() == PromotedMin.isUnsigned());
12548 if (!isContiguous()) {
12549 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12550 if (Value.isMinValue()) return Min;
12551 if (Value.isMaxValue()) return Max;
12552 if (Value >= PromotedMin) return InRange;
12553 if (Value <= PromotedMax) return InRange;
12554 return InHole;
12555 }
12556
12557 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMin)) {
12558 case -1: return Less;
12559 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12560 case 1:
12561 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMax)) {
12562 case -1: return InRange;
12563 case 0: return Max;
12564 case 1: return Greater;
12565 }
12566 }
12567
12568 llvm_unreachable("impossible compare result");
12569 }
12570
12571 static std::optional<StringRef>
12572 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12573 if (Op == BO_Cmp) {
12574 ComparisonResult LTFlag = LT, GTFlag = GT;
12575 if (ConstantOnRHS) std::swap(a&: LTFlag, b&: GTFlag);
12576
12577 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12578 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12579 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12580 return std::nullopt;
12581 }
12582
12583 ComparisonResult TrueFlag, FalseFlag;
12584 if (Op == BO_EQ) {
12585 TrueFlag = EQ;
12586 FalseFlag = NE;
12587 } else if (Op == BO_NE) {
12588 TrueFlag = NE;
12589 FalseFlag = EQ;
12590 } else {
12591 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12592 TrueFlag = LT;
12593 FalseFlag = GE;
12594 } else {
12595 TrueFlag = GT;
12596 FalseFlag = LE;
12597 }
12598 if (Op == BO_GE || Op == BO_LE)
12599 std::swap(a&: TrueFlag, b&: FalseFlag);
12600 }
12601 if (R & TrueFlag)
12602 return StringRef("true");
12603 if (R & FalseFlag)
12604 return StringRef("false");
12605 return std::nullopt;
12606 }
12607};
12608}
12609
12610static bool HasEnumType(const Expr *E) {
12611 // Strip off implicit integral promotions.
12612 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
12613 if (ICE->getCastKind() != CK_IntegralCast &&
12614 ICE->getCastKind() != CK_NoOp)
12615 break;
12616 E = ICE->getSubExpr();
12617 }
12618
12619 return E->getType()->isEnumeralType();
12620}
12621
12622static int classifyConstantValue(Expr *Constant) {
12623 // The values of this enumeration are used in the diagnostics
12624 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12625 enum ConstantValueKind {
12626 Miscellaneous = 0,
12627 LiteralTrue,
12628 LiteralFalse
12629 };
12630 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Val: Constant))
12631 return BL->getValue() ? ConstantValueKind::LiteralTrue
12632 : ConstantValueKind::LiteralFalse;
12633 return ConstantValueKind::Miscellaneous;
12634}
12635
12636static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12637 Expr *Constant, Expr *Other,
12638 const llvm::APSInt &Value,
12639 bool RhsConstant) {
12640 if (S.inTemplateInstantiation())
12641 return false;
12642
12643 Expr *OriginalOther = Other;
12644
12645 Constant = Constant->IgnoreParenImpCasts();
12646 Other = Other->IgnoreParenImpCasts();
12647
12648 // Suppress warnings on tautological comparisons between values of the same
12649 // enumeration type. There are only two ways we could warn on this:
12650 // - If the constant is outside the range of representable values of
12651 // the enumeration. In such a case, we should warn about the cast
12652 // to enumeration type, not about the comparison.
12653 // - If the constant is the maximum / minimum in-range value. For an
12654 // enumeratin type, such comparisons can be meaningful and useful.
12655 if (Constant->getType()->isEnumeralType() &&
12656 S.Context.hasSameUnqualifiedType(T1: Constant->getType(), T2: Other->getType()))
12657 return false;
12658
12659 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12660 C&: S.Context, E: Other, InConstantContext: S.isConstantEvaluatedContext(), /*Approximate=*/false);
12661 if (!OtherValueRange)
12662 return false;
12663
12664 QualType OtherT = Other->getType();
12665 if (const auto *AT = OtherT->getAs<AtomicType>())
12666 OtherT = AT->getValueType();
12667 IntRange OtherTypeRange = IntRange::forValueOfType(C&: S.Context, T: OtherT);
12668
12669 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12670 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12671 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12672 S.ObjC().NSAPIObj->isObjCBOOLType(T: OtherT) &&
12673 OtherT->isSpecificBuiltinType(K: BuiltinType::SChar);
12674
12675 // Whether we're treating Other as being a bool because of the form of
12676 // expression despite it having another type (typically 'int' in C).
12677 bool OtherIsBooleanDespiteType =
12678 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12679 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12680 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12681
12682 // Check if all values in the range of possible values of this expression
12683 // lead to the same comparison outcome.
12684 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12685 Value.isUnsigned());
12686 auto Cmp = OtherPromotedValueRange.compare(Value);
12687 auto Result = PromotedRange::constantValue(Op: E->getOpcode(), R: Cmp, ConstantOnRHS: RhsConstant);
12688 if (!Result)
12689 return false;
12690
12691 // Also consider the range determined by the type alone. This allows us to
12692 // classify the warning under the proper diagnostic group.
12693 bool TautologicalTypeCompare = false;
12694 {
12695 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12696 Value.isUnsigned());
12697 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12698 if (auto TypeResult = PromotedRange::constantValue(Op: E->getOpcode(), R: TypeCmp,
12699 ConstantOnRHS: RhsConstant)) {
12700 TautologicalTypeCompare = true;
12701 Cmp = TypeCmp;
12702 Result = TypeResult;
12703 }
12704 }
12705
12706 // Don't warn if the non-constant operand actually always evaluates to the
12707 // same value.
12708 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12709 return false;
12710
12711 // Suppress the diagnostic for an in-range comparison if the constant comes
12712 // from a macro or enumerator. We don't want to diagnose
12713 //
12714 // some_long_value <= INT_MAX
12715 //
12716 // when sizeof(int) == sizeof(long).
12717 bool InRange = Cmp & PromotedRange::InRangeFlag;
12718 if (InRange && IsEnumConstOrFromMacro(S, E: Constant))
12719 return false;
12720
12721 // A comparison of an unsigned bit-field against 0 is really a type problem,
12722 // even though at the type level the bit-field might promote to 'signed int'.
12723 if (Other->refersToBitField() && InRange && Value == 0 &&
12724 Other->getType()->isUnsignedIntegerOrEnumerationType())
12725 TautologicalTypeCompare = true;
12726
12727 // If this is a comparison to an enum constant, include that
12728 // constant in the diagnostic.
12729 const EnumConstantDecl *ED = nullptr;
12730 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: Constant))
12731 ED = dyn_cast<EnumConstantDecl>(Val: DR->getDecl());
12732
12733 // Should be enough for uint128 (39 decimal digits)
12734 SmallString<64> PrettySourceValue;
12735 llvm::raw_svector_ostream OS(PrettySourceValue);
12736 if (ED) {
12737 OS << '\'' << *ED << "' (" << Value << ")";
12738 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12739 Val: Constant->IgnoreParenImpCasts())) {
12740 OS << (BL->getValue() ? "YES" : "NO");
12741 } else {
12742 OS << Value;
12743 }
12744
12745 if (!TautologicalTypeCompare) {
12746 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_tautological_compare_value_range)
12747 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12748 << E->getOpcodeStr() << OS.str() << *Result
12749 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12750 return true;
12751 }
12752
12753 if (IsObjCSignedCharBool) {
12754 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12755 PD: S.PDiag(DiagID: diag::warn_tautological_compare_objc_bool)
12756 << OS.str() << *Result);
12757 return true;
12758 }
12759
12760 // FIXME: We use a somewhat different formatting for the in-range cases and
12761 // cases involving boolean values for historical reasons. We should pick a
12762 // consistent way of presenting these diagnostics.
12763 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12764
12765 S.DiagRuntimeBehavior(
12766 Loc: E->getOperatorLoc(), Statement: E,
12767 PD: S.PDiag(DiagID: !InRange ? diag::warn_out_of_range_compare
12768 : diag::warn_tautological_bool_compare)
12769 << OS.str() << classifyConstantValue(Constant) << OtherT
12770 << OtherIsBooleanDespiteType << *Result
12771 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12772 } else {
12773 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12774 unsigned Diag =
12775 (isKnownToHaveUnsignedValue(E: OriginalOther) && Value == 0)
12776 ? (HasEnumType(E: OriginalOther)
12777 ? diag::warn_unsigned_enum_always_true_comparison
12778 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12779 : diag::warn_unsigned_always_true_comparison)
12780 : diag::warn_tautological_constant_compare;
12781
12782 S.Diag(Loc: E->getOperatorLoc(), DiagID: Diag)
12783 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12784 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12785 }
12786
12787 return true;
12788}
12789
12790/// Analyze the operands of the given comparison. Implements the
12791/// fallback case from AnalyzeComparison.
12792static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12793 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12794 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12795}
12796
12797/// Implements -Wsign-compare.
12798///
12799/// \param E the binary operator to check for warnings
12800static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12801 // The type the comparison is being performed in.
12802 QualType T = E->getLHS()->getType();
12803
12804 // Only analyze comparison operators where both sides have been converted to
12805 // the same type.
12806 if (!S.Context.hasSameUnqualifiedType(T1: T, T2: E->getRHS()->getType()))
12807 return AnalyzeImpConvsInComparison(S, E);
12808
12809 // Don't analyze value-dependent comparisons directly.
12810 if (E->isValueDependent())
12811 return AnalyzeImpConvsInComparison(S, E);
12812
12813 Expr *LHS = E->getLHS();
12814 Expr *RHS = E->getRHS();
12815
12816 if (T->isIntegralType(Ctx: S.Context)) {
12817 std::optional<llvm::APSInt> RHSValue =
12818 RHS->getIntegerConstantExpr(Ctx: S.Context);
12819 std::optional<llvm::APSInt> LHSValue =
12820 LHS->getIntegerConstantExpr(Ctx: S.Context);
12821
12822 // We don't care about expressions whose result is a constant.
12823 if (RHSValue && LHSValue)
12824 return AnalyzeImpConvsInComparison(S, E);
12825
12826 // We only care about expressions where just one side is literal
12827 if ((bool)RHSValue ^ (bool)LHSValue) {
12828 // Is the constant on the RHS or LHS?
12829 const bool RhsConstant = (bool)RHSValue;
12830 Expr *Const = RhsConstant ? RHS : LHS;
12831 Expr *Other = RhsConstant ? LHS : RHS;
12832 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12833
12834 // Check whether an integer constant comparison results in a value
12835 // of 'true' or 'false'.
12836 if (CheckTautologicalComparison(S, E, Constant: Const, Other, Value, RhsConstant))
12837 return AnalyzeImpConvsInComparison(S, E);
12838 }
12839 }
12840
12841 if (!T->hasUnsignedIntegerRepresentation()) {
12842 // We don't do anything special if this isn't an unsigned integral
12843 // comparison: we're only interested in integral comparisons, and
12844 // signed comparisons only happen in cases we don't care to warn about.
12845 return AnalyzeImpConvsInComparison(S, E);
12846 }
12847
12848 LHS = LHS->IgnoreParenImpCasts();
12849 RHS = RHS->IgnoreParenImpCasts();
12850
12851 if (!S.getLangOpts().CPlusPlus) {
12852 // Avoid warning about comparison of integers with different signs when
12853 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12854 // the type of `E`.
12855 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: LHS->getType()))
12856 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12857 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: RHS->getType()))
12858 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12859 }
12860
12861 // Check to see if one of the (unmodified) operands is of different
12862 // signedness.
12863 Expr *signedOperand, *unsignedOperand;
12864 if (LHS->getType()->hasSignedIntegerRepresentation()) {
12865 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12866 "unsigned comparison between two signed integer expressions?");
12867 signedOperand = LHS;
12868 unsignedOperand = RHS;
12869 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12870 signedOperand = RHS;
12871 unsignedOperand = LHS;
12872 } else {
12873 return AnalyzeImpConvsInComparison(S, E);
12874 }
12875
12876 // Otherwise, calculate the effective range of the signed operand.
12877 std::optional<IntRange> signedRange =
12878 TryGetExprRange(C&: S.Context, E: signedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12879 /*Approximate=*/true);
12880 if (!signedRange)
12881 return;
12882
12883 // Go ahead and analyze implicit conversions in the operands. Note
12884 // that we skip the implicit conversions on both sides.
12885 AnalyzeImplicitConversions(S, E: LHS, CC: E->getOperatorLoc());
12886 AnalyzeImplicitConversions(S, E: RHS, CC: E->getOperatorLoc());
12887
12888 // If the signed range is non-negative, -Wsign-compare won't fire.
12889 if (signedRange->NonNegative)
12890 return;
12891
12892 // For (in)equality comparisons, if the unsigned operand is a
12893 // constant which cannot collide with a overflowed signed operand,
12894 // then reinterpreting the signed operand as unsigned will not
12895 // change the result of the comparison.
12896 if (E->isEqualityOp()) {
12897 unsigned comparisonWidth = S.Context.getIntWidth(T);
12898 std::optional<IntRange> unsignedRange = TryGetExprRange(
12899 C&: S.Context, E: unsignedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12900 /*Approximate=*/true);
12901 if (!unsignedRange)
12902 return;
12903
12904 // We should never be unable to prove that the unsigned operand is
12905 // non-negative.
12906 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12907
12908 if (unsignedRange->Width < comparisonWidth)
12909 return;
12910 }
12911
12912 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12913 PD: S.PDiag(DiagID: diag::warn_mixed_sign_comparison)
12914 << LHS->getType() << RHS->getType()
12915 << LHS->getSourceRange() << RHS->getSourceRange());
12916}
12917
12918/// Analyzes an attempt to assign the given value to a bitfield.
12919///
12920/// Returns true if there was something fishy about the attempt.
12921static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12922 SourceLocation InitLoc) {
12923 assert(Bitfield->isBitField());
12924 if (Bitfield->isInvalidDecl())
12925 return false;
12926
12927 // White-list bool bitfields.
12928 QualType BitfieldType = Bitfield->getType();
12929 if (BitfieldType->isBooleanType())
12930 return false;
12931
12932 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12933 // If the underlying enum type was not explicitly specified as an unsigned
12934 // type and the enum contain only positive values, MSVC++ will cause an
12935 // inconsistency by storing this as a signed type.
12936 if (S.getLangOpts().CPlusPlus11 &&
12937 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12938 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12939 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12940 S.Diag(Loc: InitLoc, DiagID: diag::warn_no_underlying_type_specified_for_enum_bitfield)
12941 << BitfieldEnumDecl;
12942 }
12943 }
12944
12945 // Ignore value- or type-dependent expressions.
12946 if (Bitfield->getBitWidth()->isValueDependent() ||
12947 Bitfield->getBitWidth()->isTypeDependent() ||
12948 Init->isValueDependent() ||
12949 Init->isTypeDependent())
12950 return false;
12951
12952 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12953 unsigned FieldWidth = Bitfield->getBitWidthValue();
12954
12955 Expr::EvalResult Result;
12956 if (!OriginalInit->EvaluateAsInt(Result, Ctx: S.Context,
12957 AllowSideEffects: Expr::SE_AllowSideEffects)) {
12958 // The RHS is not constant. If the RHS has an enum type, make sure the
12959 // bitfield is wide enough to hold all the values of the enum without
12960 // truncation.
12961 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12962 const PreferredTypeAttr *PTAttr = nullptr;
12963 if (!ED) {
12964 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12965 if (PTAttr)
12966 ED = PTAttr->getType()->getAsEnumDecl();
12967 }
12968 if (ED) {
12969 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12970
12971 // Enum types are implicitly signed on Windows, so check if there are any
12972 // negative enumerators to see if the enum was intended to be signed or
12973 // not.
12974 bool SignedEnum = ED->getNumNegativeBits() > 0;
12975
12976 // Check for surprising sign changes when assigning enum values to a
12977 // bitfield of different signedness. If the bitfield is signed and we
12978 // have exactly the right number of bits to store this unsigned enum,
12979 // suggest changing the enum to an unsigned type. This typically happens
12980 // on Windows where unfixed enums always use an underlying type of 'int'.
12981 unsigned DiagID = 0;
12982 if (SignedEnum && !SignedBitfield) {
12983 DiagID =
12984 PTAttr == nullptr
12985 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12986 : diag::
12987 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12988 } else if (SignedBitfield && !SignedEnum &&
12989 ED->getNumPositiveBits() == FieldWidth) {
12990 DiagID =
12991 PTAttr == nullptr
12992 ? diag::warn_signed_bitfield_enum_conversion
12993 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12994 }
12995 if (DiagID) {
12996 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
12997 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12998 SourceRange TypeRange =
12999 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
13000 S.Diag(Loc: Bitfield->getTypeSpecStartLoc(), DiagID: diag::note_change_bitfield_sign)
13001 << SignedEnum << TypeRange;
13002 if (PTAttr)
13003 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
13004 << ED;
13005 }
13006
13007 // Compute the required bitwidth. If the enum has negative values, we need
13008 // one more bit than the normal number of positive bits to represent the
13009 // sign bit.
13010 unsigned BitsNeeded = SignedEnum ? std::max(a: ED->getNumPositiveBits() + 1,
13011 b: ED->getNumNegativeBits())
13012 : ED->getNumPositiveBits();
13013
13014 // Check the bitwidth.
13015 if (BitsNeeded > FieldWidth) {
13016 Expr *WidthExpr = Bitfield->getBitWidth();
13017 auto DiagID =
13018 PTAttr == nullptr
13019 ? diag::warn_bitfield_too_small_for_enum
13020 : diag::warn_preferred_type_bitfield_too_small_for_enum;
13021 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
13022 S.Diag(Loc: WidthExpr->getExprLoc(), DiagID: diag::note_widen_bitfield)
13023 << BitsNeeded << ED << WidthExpr->getSourceRange();
13024 if (PTAttr)
13025 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
13026 << ED;
13027 }
13028 }
13029
13030 return false;
13031 }
13032
13033 llvm::APSInt Value = Result.Val.getInt();
13034
13035 unsigned OriginalWidth = Value.getBitWidth();
13036
13037 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
13038 // false positives where the user is demonstrating they intend to use the
13039 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
13040 // to a one-bit bit-field to see if the value came from a macro named 'true'.
13041 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
13042 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
13043 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
13044 if (S.SourceMgr.isInSystemMacro(loc: MaybeMacroLoc) &&
13045 S.findMacroSpelling(loc&: MaybeMacroLoc, name: "true"))
13046 return false;
13047 }
13048
13049 if (!Value.isSigned() || Value.isNegative())
13050 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: OriginalInit))
13051 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
13052 OriginalWidth = Value.getSignificantBits();
13053
13054 if (OriginalWidth <= FieldWidth)
13055 return false;
13056
13057 // Compute the value which the bitfield will contain.
13058 llvm::APSInt TruncatedValue = Value.trunc(width: FieldWidth);
13059 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
13060
13061 // Check whether the stored value is equal to the original value.
13062 TruncatedValue = TruncatedValue.extend(width: OriginalWidth);
13063 if (llvm::APSInt::isSameValue(I1: Value, I2: TruncatedValue))
13064 return false;
13065
13066 std::string PrettyValue = toString(I: Value, Radix: 10);
13067 std::string PrettyTrunc = toString(I: TruncatedValue, Radix: 10);
13068
13069 S.Diag(Loc: InitLoc, DiagID: OneAssignedToOneBitBitfield
13070 ? diag::warn_impcast_single_bit_bitield_precision_constant
13071 : diag::warn_impcast_bitfield_precision_constant)
13072 << PrettyValue << PrettyTrunc << OriginalInit->getType()
13073 << Init->getSourceRange();
13074
13075 return true;
13076}
13077
13078/// Analyze the given simple or compound assignment for warning-worthy
13079/// operations.
13080static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
13081 // Just recurse on the LHS.
13082 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
13083
13084 // We want to recurse on the RHS as normal unless we're assigning to
13085 // a bitfield.
13086 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
13087 if (AnalyzeBitFieldAssignment(S, Bitfield, Init: E->getRHS(),
13088 InitLoc: E->getOperatorLoc())) {
13089 // Recurse, ignoring any implicit conversions on the RHS.
13090 return AnalyzeImplicitConversions(S, E: E->getRHS()->IgnoreParenImpCasts(),
13091 CC: E->getOperatorLoc());
13092 }
13093 }
13094
13095 // Set context flag for overflow behavior type assignment analysis, use RAII
13096 // pattern to handle nested assignments.
13097 llvm::SaveAndRestore OBTAssignmentContext(
13098 S.InOverflowBehaviorAssignmentContext, true);
13099
13100 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
13101
13102 // Diagnose implicitly sequentially-consistent atomic assignment.
13103 if (E->getLHS()->getType()->isAtomicType())
13104 S.Diag(Loc: E->getRHS()->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13105}
13106
13107/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13108static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
13109 QualType T, SourceLocation CContext, unsigned diag,
13110 bool PruneControlFlow = false) {
13111 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
13112 // address space annotations isn't really useful. The warnings aren't because
13113 // you're converting a `private int` to `unsigned int`, it is because you're
13114 // conerting `int` to `unsigned int`.
13115 if (SourceType.hasAddressSpace())
13116 SourceType = S.getASTContext().removeAddrSpaceQualType(T: SourceType);
13117 if (T.hasAddressSpace())
13118 T = S.getASTContext().removeAddrSpaceQualType(T);
13119 if (PruneControlFlow) {
13120 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13121 PD: S.PDiag(DiagID: diag)
13122 << SourceType << T << E->getSourceRange()
13123 << SourceRange(CContext));
13124 return;
13125 }
13126 S.Diag(Loc: E->getExprLoc(), DiagID: diag)
13127 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
13128}
13129
13130/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13131static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
13132 SourceLocation CContext, unsigned diag,
13133 bool PruneControlFlow = false) {
13134 DiagnoseImpCast(S, E, SourceType: E->getType(), T, CContext, diag, PruneControlFlow);
13135}
13136
13137/// Diagnose an implicit cast from a floating point value to an integer value.
13138static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
13139 SourceLocation CContext) {
13140 bool IsBool = T->isSpecificBuiltinType(K: BuiltinType::Bool);
13141 bool PruneWarnings = S.inTemplateInstantiation();
13142
13143 const Expr *InnerE = E->IgnoreParenImpCasts();
13144 // We also want to warn on, e.g., "int i = -1.234"
13145 if (const auto *UOp = dyn_cast<UnaryOperator>(Val: InnerE))
13146 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
13147 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
13148
13149 bool IsLiteral = isa<FloatingLiteral>(Val: E) || isa<FloatingLiteral>(Val: InnerE);
13150
13151 llvm::APFloat Value(0.0);
13152 bool IsConstant =
13153 E->EvaluateAsFloat(Result&: Value, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects);
13154 if (!IsConstant) {
13155 if (S.ObjC().isSignedCharBool(Ty: T)) {
13156 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
13157 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_float_to_objc_signed_char_bool)
13158 << E->getType());
13159 }
13160
13161 return DiagnoseImpCast(S, E, T, CContext,
13162 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13163 }
13164
13165 bool isExact = false;
13166
13167 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
13168 T->hasUnsignedIntegerRepresentation());
13169 llvm::APFloat::opStatus Result = Value.convertToInteger(
13170 Result&: IntegerValue, RM: llvm::APFloat::rmTowardZero, IsExact: &isExact);
13171
13172 // FIXME: Force the precision of the source value down so we don't print
13173 // digits which are usually useless (we don't really care here if we
13174 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
13175 // would automatically print the shortest representation, but it's a bit
13176 // tricky to implement.
13177 SmallString<16> PrettySourceValue;
13178 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
13179 precision = (precision * 59 + 195) / 196;
13180 Value.toString(Str&: PrettySourceValue, FormatPrecision: precision);
13181
13182 if (S.ObjC().isSignedCharBool(Ty: T) && IntegerValue != 0 && IntegerValue != 1) {
13183 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
13184 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
13185 << PrettySourceValue);
13186 }
13187
13188 if (Result == llvm::APFloat::opOK && isExact) {
13189 if (IsLiteral) return;
13190 return DiagnoseImpCast(S, E, T, CContext, diag: diag::warn_impcast_float_integer,
13191 PruneControlFlow: PruneWarnings);
13192 }
13193
13194 // Conversion of a floating-point value to a non-bool integer where the
13195 // integral part cannot be represented by the integer type is undefined.
13196 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
13197 return DiagnoseImpCast(
13198 S, E, T, CContext,
13199 diag: IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13200 : diag::warn_impcast_float_to_integer_out_of_range,
13201 PruneControlFlow: PruneWarnings);
13202
13203 unsigned DiagID = 0;
13204 if (IsLiteral) {
13205 // Warn on floating point literal to integer.
13206 DiagID = diag::warn_impcast_literal_float_to_integer;
13207 } else if (IntegerValue == 0) {
13208 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
13209 return DiagnoseImpCast(S, E, T, CContext,
13210 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13211 }
13212 // Warn on non-zero to zero conversion.
13213 DiagID = diag::warn_impcast_float_to_integer_zero;
13214 } else {
13215 if (IntegerValue.isUnsigned()) {
13216 if (!IntegerValue.isMaxValue()) {
13217 return DiagnoseImpCast(S, E, T, CContext,
13218 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13219 }
13220 } else { // IntegerValue.isSigned()
13221 if (!IntegerValue.isMaxSignedValue() &&
13222 !IntegerValue.isMinSignedValue()) {
13223 return DiagnoseImpCast(S, E, T, CContext,
13224 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13225 }
13226 }
13227 // Warn on evaluatable floating point expression to integer conversion.
13228 DiagID = diag::warn_impcast_float_to_integer;
13229 }
13230
13231 SmallString<16> PrettyTargetValue;
13232 if (IsBool)
13233 PrettyTargetValue = Value.isZero() ? "false" : "true";
13234 else
13235 IntegerValue.toString(Str&: PrettyTargetValue);
13236
13237 if (PruneWarnings) {
13238 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13239 PD: S.PDiag(DiagID)
13240 << E->getType() << T.getUnqualifiedType()
13241 << PrettySourceValue << PrettyTargetValue
13242 << E->getSourceRange() << SourceRange(CContext));
13243 } else {
13244 S.Diag(Loc: E->getExprLoc(), DiagID)
13245 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
13246 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
13247 }
13248}
13249
13250/// Analyze the given compound assignment for the possible losing of
13251/// floating-point precision.
13252static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
13253 assert(isa<CompoundAssignOperator>(E) &&
13254 "Must be compound assignment operation");
13255 // Recurse on the LHS and RHS in here
13256 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
13257 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
13258
13259 if (E->getLHS()->getType()->isAtomicType())
13260 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13261
13262 // Now check the outermost expression
13263 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13264 const auto *RBT = cast<CompoundAssignOperator>(Val: E)
13265 ->getComputationResultType()
13266 ->getAs<BuiltinType>();
13267
13268 // The below checks assume source is floating point.
13269 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13270
13271 // If source is floating point but target is an integer.
13272 if (ResultBT->isInteger())
13273 return DiagnoseImpCast(S, E, SourceType: E->getRHS()->getType(), T: E->getLHS()->getType(),
13274 CContext: E->getExprLoc(), diag: diag::warn_impcast_float_integer);
13275
13276 if (!ResultBT->isFloatingPoint())
13277 return;
13278
13279 // If both source and target are floating points, warn about losing precision.
13280 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13281 LHS: QualType(ResultBT, 0), RHS: QualType(RBT, 0));
13282 if (Order < 0 && !S.SourceMgr.isInSystemMacro(loc: E->getOperatorLoc()))
13283 // warn about dropping FP rank.
13284 DiagnoseImpCast(S, E: E->getRHS(), T: E->getLHS()->getType(), CContext: E->getOperatorLoc(),
13285 diag: diag::warn_impcast_float_result_precision);
13286}
13287
13288static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13289 IntRange Range) {
13290 if (!Range.Width) return "0";
13291
13292 llvm::APSInt ValueInRange = Value;
13293 ValueInRange.setIsSigned(!Range.NonNegative);
13294 ValueInRange = ValueInRange.trunc(width: Range.Width);
13295 return toString(I: ValueInRange, Radix: 10);
13296}
13297
13298static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
13299 bool ToBool) {
13300 if (!isa<ImplicitCastExpr>(Val: Ex))
13301 return false;
13302
13303 const Expr *InnerE = Ex->IgnoreParenImpCasts();
13304 const Type *Target = S.Context.getCanonicalType(T: Ex->getType()).getTypePtr();
13305 const Type *Source =
13306 S.Context.getCanonicalType(T: InnerE->getType()).getTypePtr();
13307 if (Target->isDependentType())
13308 return false;
13309
13310 const auto *FloatCandidateBT =
13311 dyn_cast<BuiltinType>(Val: ToBool ? Source : Target);
13312 const Type *BoolCandidateType = ToBool ? Target : Source;
13313
13314 return (BoolCandidateType->isSpecificBuiltinType(K: BuiltinType::Bool) &&
13315 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13316}
13317
13318static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
13319 SourceLocation CC) {
13320 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
13321 const Expr *CurrA = TheCall->getArg(Arg: I);
13322 if (!IsImplicitBoolFloatConversion(S, Ex: CurrA, ToBool: true))
13323 continue;
13324
13325 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
13326 S, Ex: TheCall->getArg(Arg: I - 1), ToBool: false));
13327 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
13328 S, Ex: TheCall->getArg(Arg: I + 1), ToBool: false));
13329 if (IsSwapped) {
13330 // Warn on this floating-point to bool conversion.
13331 DiagnoseImpCast(S, E: CurrA->IgnoreParenImpCasts(),
13332 T: CurrA->getType(), CContext: CC,
13333 diag: diag::warn_impcast_floating_point_to_bool);
13334 }
13335 }
13336}
13337
13338static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
13339 SourceLocation CC) {
13340 // Don't warn on functions which have return type nullptr_t.
13341 if (isa<CallExpr>(Val: E))
13342 return;
13343
13344 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13345 const Expr *NewE = E->IgnoreParenImpCasts();
13346 bool IsGNUNullExpr = isa<GNUNullExpr>(Val: NewE);
13347 bool HasNullPtrType = NewE->getType()->isNullPtrType();
13348 if (!IsGNUNullExpr && !HasNullPtrType)
13349 return;
13350
13351 // Return if target type is a safe conversion.
13352 if (T->isAnyPointerType() || T->isBlockPointerType() ||
13353 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13354 return;
13355
13356 if (S.Diags.isIgnored(DiagID: diag::warn_impcast_null_pointer_to_integer,
13357 Loc: E->getExprLoc()))
13358 return;
13359
13360 SourceLocation Loc = E->getSourceRange().getBegin();
13361
13362 // Venture through the macro stacks to get to the source of macro arguments.
13363 // The new location is a better location than the complete location that was
13364 // passed in.
13365 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13366 CC = S.SourceMgr.getTopMacroCallerLoc(Loc: CC);
13367
13368 // __null is usually wrapped in a macro. Go up a macro if that is the case.
13369 if (IsGNUNullExpr && Loc.isMacroID()) {
13370 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13371 Loc, SM: S.SourceMgr, LangOpts: S.getLangOpts());
13372 if (MacroName == "NULL")
13373 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
13374 }
13375
13376 // Only warn if the null and context location are in the same macro expansion.
13377 if (S.SourceMgr.getFileID(SpellingLoc: Loc) != S.SourceMgr.getFileID(SpellingLoc: CC))
13378 return;
13379
13380 S.Diag(Loc, DiagID: diag::warn_impcast_null_pointer_to_integer)
13381 << HasNullPtrType << T << SourceRange(CC)
13382 << FixItHint::CreateReplacement(RemoveRange: Loc,
13383 Code: S.getFixItZeroLiteralForType(T, Loc));
13384}
13385
13386// Helper function to filter out cases for constant width constant conversion.
13387// Don't warn on unsigned char array initialization or for non-decimal
13388// values.
13389static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
13390 SourceLocation CC) {
13391 // If initializing from a constant, and the constant starts with '0',
13392 // then it is a binary, octal, or hexadecimal. Allow these constants
13393 // to fill all the bits, even if there is a sign change.
13394 if (auto *IntLit = dyn_cast<IntegerLiteral>(Val: E->IgnoreParenImpCasts())) {
13395 const char FirstLiteralCharacter =
13396 S.getSourceManager().getCharacterData(SL: IntLit->getBeginLoc())[0];
13397 if (FirstLiteralCharacter == '0')
13398 return false;
13399 }
13400
13401 // If the CC location points to a '{' and the type is an unsigned char
13402 // type, assume it is an array initialization.
13403 if (T->isCharType() && !T->isSignedIntegerType() && CC.isValid()) {
13404 const char FirstContextCharacter =
13405 S.getSourceManager().getCharacterData(SL: CC)[0];
13406 if (FirstContextCharacter == '{')
13407 return false;
13408 }
13409
13410 return true;
13411}
13412
13413static const IntegerLiteral *getIntegerLiteral(Expr *E) {
13414 const auto *IL = dyn_cast<IntegerLiteral>(Val: E);
13415 if (!IL) {
13416 if (auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
13417 if (UO->getOpcode() == UO_Minus)
13418 return dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13419 }
13420 }
13421
13422 return IL;
13423}
13424
13425static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
13426 E = E->IgnoreParenImpCasts();
13427 SourceLocation ExprLoc = E->getExprLoc();
13428
13429 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
13430 BinaryOperator::Opcode Opc = BO->getOpcode();
13431 Expr::EvalResult Result;
13432 // Do not diagnose unsigned shifts.
13433 if (Opc == BO_Shl) {
13434 const auto *LHS = getIntegerLiteral(E: BO->getLHS());
13435 const auto *RHS = getIntegerLiteral(E: BO->getRHS());
13436 if (LHS && LHS->getValue() == 0)
13437 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always) << 0;
13438 else if (!E->isValueDependent() && LHS && RHS &&
13439 RHS->getValue().isNonNegative() &&
13440 E->EvaluateAsInt(Result, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects))
13441 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always)
13442 << (Result.Val.getInt() != 0);
13443 else if (E->getType()->isSignedIntegerType())
13444 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_in_bool_context)
13445 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "(")
13446 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: E->getEndLoc()),
13447 Code: ") != 0");
13448 }
13449 }
13450
13451 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
13452 const auto *LHS = getIntegerLiteral(E: CO->getTrueExpr());
13453 const auto *RHS = getIntegerLiteral(E: CO->getFalseExpr());
13454 if (!LHS || !RHS)
13455 return;
13456 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13457 (RHS->getValue() == 0 || RHS->getValue() == 1))
13458 // Do not diagnose common idioms.
13459 return;
13460 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13461 S.Diag(Loc: ExprLoc, DiagID: diag::warn_integer_constants_in_conditional_always_true);
13462 }
13463}
13464
13465static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source,
13466 const Type *Target, Expr *E,
13467 QualType T,
13468 SourceLocation CC) {
13469 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13470 Source != Target);
13471
13472 // Lone surrogates have a distinct representation in UTF-32.
13473 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13474 // so don't warn on such conversion.
13475 if (Source->isChar16Type() && Target->isChar32Type())
13476 return;
13477
13478 Expr::EvalResult Result;
13479 if (E->EvaluateAsInt(Result, Ctx: S.getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects,
13480 InConstantContext: S.isConstantEvaluatedContext())) {
13481 llvm::APSInt Value(32);
13482 Value = Result.Val.getInt();
13483 bool IsASCII = Value <= 0x7F;
13484 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13485 bool ConversionPreservesSemantics =
13486 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13487
13488 if (!ConversionPreservesSemantics) {
13489 auto IsSingleCodeUnitCP = [](const QualType &T,
13490 const llvm::APSInt &Value) {
13491 if (T->isChar8Type())
13492 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13493 if (T->isChar16Type())
13494 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13495 assert(T->isChar32Type());
13496 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13497 };
13498
13499 S.Diag(Loc: CC, DiagID: diag::warn_impcast_unicode_char_type_constant)
13500 << E->getType() << T
13501 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13502 << FormatUTFCodeUnitAsCodepoint(Value: Value.getExtValue(), T: E->getType());
13503 }
13504 } else {
13505 bool LosesPrecision = S.getASTContext().getIntWidth(T: E->getType()) >
13506 S.getASTContext().getIntWidth(T);
13507 DiagnoseImpCast(S, E, T, CContext: CC,
13508 diag: LosesPrecision ? diag::warn_impcast_unicode_precision
13509 : diag::warn_impcast_unicode_char_type);
13510 }
13511}
13512
13513bool Sema::DiscardingCFIUncheckedCallee(QualType From, QualType To) const {
13514 From = Context.getCanonicalType(T: From);
13515 To = Context.getCanonicalType(T: To);
13516 QualType MaybePointee = From->getPointeeType();
13517 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13518 From = MaybePointee;
13519 MaybePointee = To->getPointeeType();
13520 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13521 To = MaybePointee;
13522
13523 if (const auto *FromFn = From->getAs<FunctionType>()) {
13524 if (const auto *ToFn = To->getAs<FunctionType>()) {
13525 if (FromFn->getCFIUncheckedCalleeAttr() &&
13526 !ToFn->getCFIUncheckedCalleeAttr())
13527 return true;
13528 }
13529 }
13530 return false;
13531}
13532
13533void Sema::CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
13534 bool *ICContext, bool IsListInit) {
13535 if (E->isTypeDependent() || E->isValueDependent()) return;
13536
13537 const Type *Source = Context.getCanonicalType(T: E->getType()).getTypePtr();
13538 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13539 if (Source == Target) return;
13540 if (Target->isDependentType()) return;
13541
13542 // If the conversion context location is invalid don't complain. We also
13543 // don't want to emit a warning if the issue occurs from the expansion of
13544 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13545 // delay this check as long as possible. Once we detect we are in that
13546 // scenario, we just return.
13547 if (CC.isInvalid())
13548 return;
13549
13550 if (Source->isAtomicType())
13551 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13552
13553 // Diagnose implicit casts to bool.
13554 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool)) {
13555 if (isa<StringLiteral>(Val: E))
13556 // Warn on string literal to bool. Checks for string literals in logical
13557 // and expressions, for instance, assert(0 && "error here"), are
13558 // prevented by a check in AnalyzeImplicitConversions().
13559 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13560 diag: diag::warn_impcast_string_literal_to_bool);
13561 if (isa<ObjCStringLiteral>(Val: E) || isa<ObjCArrayLiteral>(Val: E) ||
13562 isa<ObjCDictionaryLiteral>(Val: E) || isa<ObjCBoxedExpr>(Val: E)) {
13563 // This covers the literal expressions that evaluate to Objective-C
13564 // objects.
13565 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13566 diag: diag::warn_impcast_objective_c_literal_to_bool);
13567 }
13568 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13569 // Warn on pointer to bool conversion that is always true.
13570 DiagnoseAlwaysNonNullPointer(E, NullType: Expr::NPCK_NotNull, /*IsEqual*/ false,
13571 Range: SourceRange(CC));
13572 }
13573 }
13574
13575 CheckOverflowBehaviorTypeConversion(E, T, CC);
13576
13577 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13578 // is a typedef for signed char (macOS), then that constant value has to be 1
13579 // or 0.
13580 if (ObjC().isSignedCharBool(Ty: T) && Source->isIntegralType(Ctx: Context)) {
13581 Expr::EvalResult Result;
13582 if (E->EvaluateAsInt(Result, Ctx: getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects)) {
13583 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13584 ObjC().adornBoolConversionDiagWithTernaryFixit(
13585 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
13586 << toString(I: Result.Val.getInt(), Radix: 10));
13587 }
13588 return;
13589 }
13590 }
13591
13592 // Check implicit casts from Objective-C collection literals to specialized
13593 // collection types, e.g., NSArray<NSString *> *.
13594 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Val: E))
13595 ObjC().checkArrayLiteral(TargetType: QualType(Target, 0), ArrayLiteral);
13596 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Val: E))
13597 ObjC().checkDictionaryLiteral(TargetType: QualType(Target, 0), DictionaryLiteral);
13598
13599 // Strip complex types.
13600 if (isa<ComplexType>(Val: Source)) {
13601 if (!isa<ComplexType>(Val: Target)) {
13602 if (SourceMgr.isInSystemMacro(loc: CC) || Target->isBooleanType())
13603 return;
13604
13605 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13606 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13607 diag: diag::err_impcast_incompatible_type);
13608 }
13609
13610 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13611 diag: getLangOpts().CPlusPlus
13612 ? diag::err_impcast_complex_scalar
13613 : diag::warn_impcast_complex_scalar);
13614 }
13615
13616 Source = cast<ComplexType>(Val: Source)->getElementType().getTypePtr();
13617 Target = cast<ComplexType>(Val: Target)->getElementType().getTypePtr();
13618 }
13619
13620 // Strip vector types.
13621 if (isa<VectorType>(Val: Source)) {
13622 if (Target->isSveVLSBuiltinType() &&
13623 (ARM().areCompatibleSveTypes(FirstType: QualType(Target, 0),
13624 SecondType: QualType(Source, 0)) ||
13625 ARM().areLaxCompatibleSveTypes(FirstType: QualType(Target, 0),
13626 SecondType: QualType(Source, 0))))
13627 return;
13628
13629 if (Target->isRVVVLSBuiltinType() &&
13630 (Context.areCompatibleRVVTypes(FirstType: QualType(Target, 0),
13631 SecondType: QualType(Source, 0)) ||
13632 Context.areLaxCompatibleRVVTypes(FirstType: QualType(Target, 0),
13633 SecondType: QualType(Source, 0))))
13634 return;
13635
13636 if (!isa<VectorType>(Val: Target)) {
13637 if (SourceMgr.isInSystemMacro(loc: CC))
13638 return;
13639 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_vector_scalar);
13640 }
13641 if (getLangOpts().HLSL &&
13642 Target->castAs<VectorType>()->getNumElements() <
13643 Source->castAs<VectorType>()->getNumElements()) {
13644 // Diagnose vector truncation but don't return. We may also want to
13645 // diagnose an element conversion.
13646 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13647 diag: diag::warn_hlsl_impcast_vector_truncation);
13648 }
13649
13650 // If the vector cast is cast between two vectors of the same size, it is
13651 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13652 if (!getLangOpts().HLSL &&
13653 Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13654 return;
13655
13656 Source = cast<VectorType>(Val: Source)->getElementType().getTypePtr();
13657 Target = cast<VectorType>(Val: Target)->getElementType().getTypePtr();
13658 }
13659 if (const auto *VecTy = dyn_cast<VectorType>(Val: Target))
13660 Target = VecTy->getElementType().getTypePtr();
13661
13662 // Strip matrix types.
13663 if (isa<ConstantMatrixType>(Val: Source)) {
13664 if (Target->isScalarType())
13665 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_matrix_scalar);
13666
13667 if (getLangOpts().HLSL && isa<ConstantMatrixType>(Val: Target) &&
13668 Target->castAs<ConstantMatrixType>()->getNumElementsFlattened() <
13669 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13670 // Diagnose Matrix truncation but don't return. We may also want to
13671 // diagnose an element conversion.
13672 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13673 diag: diag::warn_hlsl_impcast_matrix_truncation);
13674 }
13675
13676 Source = cast<ConstantMatrixType>(Val: Source)->getElementType().getTypePtr();
13677 Target = cast<ConstantMatrixType>(Val: Target)->getElementType().getTypePtr();
13678 }
13679 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Val: Target))
13680 Target = MatTy->getElementType().getTypePtr();
13681
13682 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Val: Source);
13683 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Val: Target);
13684
13685 // Strip SVE vector types
13686 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13687 // Need the original target type for vector type checks
13688 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13689 // Handle conversion from scalable to fixed when msve-vector-bits is
13690 // specified
13691 if (ARM().areCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13692 SecondType: QualType(Source, 0)) ||
13693 ARM().areLaxCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13694 SecondType: QualType(Source, 0)))
13695 return;
13696
13697 // If the vector cast is cast between two vectors of the same size, it is
13698 // a bitcast, not a conversion.
13699 if (Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13700 return;
13701
13702 Source = SourceBT->getSveEltType(Ctx: Context).getTypePtr();
13703 }
13704
13705 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13706 Target = TargetBT->getSveEltType(Ctx: Context).getTypePtr();
13707
13708 // Nothing to diagnose if stripping the wrappers left identical element types
13709 // (e.g. a scalar splatted to a vector of its own type).
13710 if (Source == Target)
13711 return;
13712
13713 // If the source is floating point...
13714 if (SourceBT && SourceBT->isFloatingPoint()) {
13715 // ...and the target is floating point...
13716 if (TargetBT && TargetBT->isFloatingPoint()) {
13717 // ...then warn if we're dropping FP rank.
13718
13719 int Order = getASTContext().getFloatingTypeSemanticOrder(
13720 LHS: QualType(SourceBT, 0), RHS: QualType(TargetBT, 0));
13721 if (Order > 0) {
13722 // Don't warn about float constants that are precisely
13723 // representable in the target type.
13724 Expr::EvalResult result;
13725 if (E->EvaluateAsRValue(Result&: result, Ctx: Context)) {
13726 // Value might be a float, a float vector, or a float complex.
13727 if (IsSameFloatAfterCast(
13728 value: result.Val,
13729 Src: Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)),
13730 Tgt: Context.getFloatTypeSemantics(T: QualType(SourceBT, 0))))
13731 return;
13732 }
13733
13734 if (SourceMgr.isInSystemMacro(loc: CC))
13735 return;
13736
13737 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_float_precision);
13738 }
13739 // ... or possibly if we're increasing rank, too
13740 else if (Order < 0) {
13741 if (SourceMgr.isInSystemMacro(loc: CC))
13742 return;
13743
13744 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_double_promotion);
13745 }
13746 return;
13747 }
13748
13749 // If the target is integral, always warn.
13750 if (TargetBT && TargetBT->isInteger()) {
13751 if (SourceMgr.isInSystemMacro(loc: CC))
13752 return;
13753
13754 DiagnoseFloatingImpCast(S&: *this, E, T, CContext: CC);
13755 }
13756
13757 // Detect the case where a call result is converted from floating-point to
13758 // to bool, and the final argument to the call is converted from bool, to
13759 // discover this typo:
13760 //
13761 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13762 //
13763 // FIXME: This is an incredibly special case; is there some more general
13764 // way to detect this class of misplaced-parentheses bug?
13765 if (Target->isBooleanType() && isa<CallExpr>(Val: E)) {
13766 // Check last argument of function call to see if it is an
13767 // implicit cast from a type matching the type the result
13768 // is being cast to.
13769 CallExpr *CEx = cast<CallExpr>(Val: E);
13770 if (unsigned NumArgs = CEx->getNumArgs()) {
13771 Expr *LastA = CEx->getArg(Arg: NumArgs - 1);
13772 Expr *InnerE = LastA->IgnoreParenImpCasts();
13773 if (isa<ImplicitCastExpr>(Val: LastA) &&
13774 InnerE->getType()->isBooleanType()) {
13775 // Warn on this floating-point to bool conversion
13776 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13777 diag: diag::warn_impcast_floating_point_to_bool);
13778 }
13779 }
13780 }
13781 return;
13782 }
13783
13784 // Valid casts involving fixed point types should be accounted for here.
13785 if (Source->isFixedPointType()) {
13786 if (Target->isUnsaturatedFixedPointType()) {
13787 Expr::EvalResult Result;
13788 if (E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13789 InConstantContext: isConstantEvaluatedContext())) {
13790 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13791 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(Ty: T);
13792 llvm::APFixedPoint MinVal = Context.getFixedPointMin(Ty: T);
13793 if (Value > MaxVal || Value < MinVal) {
13794 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13795 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13796 << Value.toString() << T
13797 << E->getSourceRange()
13798 << clang::SourceRange(CC));
13799 return;
13800 }
13801 }
13802 } else if (Target->isIntegerType()) {
13803 Expr::EvalResult Result;
13804 if (!isConstantEvaluatedContext() &&
13805 E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13806 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13807
13808 bool Overflowed;
13809 llvm::APSInt IntResult = FXResult.convertToInt(
13810 DstWidth: Context.getIntWidth(T), DstSign: Target->isSignedIntegerOrEnumerationType(),
13811 Overflow: &Overflowed);
13812
13813 if (Overflowed) {
13814 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13815 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13816 << FXResult.toString() << T
13817 << E->getSourceRange()
13818 << clang::SourceRange(CC));
13819 return;
13820 }
13821 }
13822 }
13823 } else if (Target->isUnsaturatedFixedPointType()) {
13824 if (Source->isIntegerType()) {
13825 Expr::EvalResult Result;
13826 if (!isConstantEvaluatedContext() &&
13827 E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13828 llvm::APSInt Value = Result.Val.getInt();
13829
13830 bool Overflowed;
13831 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13832 Value, DstFXSema: Context.getFixedPointSemantics(Ty: T), Overflow: &Overflowed);
13833
13834 if (Overflowed) {
13835 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13836 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13837 << toString(I: Value, /*Radix=*/10) << T
13838 << E->getSourceRange()
13839 << clang::SourceRange(CC));
13840 return;
13841 }
13842 }
13843 }
13844 }
13845
13846 // If we are casting an integer type to a floating point type without
13847 // initialization-list syntax, we might lose accuracy if the floating
13848 // point type has a narrower significand than the integer type.
13849 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13850 TargetBT->isFloatingType() && !IsListInit) {
13851 // Determine the number of precision bits in the source integer type.
13852 std::optional<IntRange> SourceRange =
13853 TryGetExprRange(C&: Context, E, InConstantContext: isConstantEvaluatedContext(),
13854 /*Approximate=*/true);
13855 if (!SourceRange)
13856 return;
13857 unsigned int SourcePrecision = SourceRange->Width;
13858
13859 // Determine the number of precision bits in the
13860 // target floating point type.
13861 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13862 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13863
13864 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13865 SourcePrecision > TargetPrecision) {
13866
13867 if (std::optional<llvm::APSInt> SourceInt =
13868 E->getIntegerConstantExpr(Ctx: Context)) {
13869 // If the source integer is a constant, convert it to the target
13870 // floating point type. Issue a warning if the value changes
13871 // during the whole conversion.
13872 llvm::APFloat TargetFloatValue(
13873 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13874 llvm::APFloat::opStatus ConversionStatus =
13875 TargetFloatValue.convertFromAPInt(
13876 Input: *SourceInt, IsSigned: SourceBT->isSignedInteger(),
13877 RM: llvm::APFloat::rmNearestTiesToEven);
13878
13879 if (ConversionStatus != llvm::APFloat::opOK) {
13880 SmallString<32> PrettySourceValue;
13881 SourceInt->toString(Str&: PrettySourceValue, Radix: 10);
13882 SmallString<32> PrettyTargetValue;
13883 TargetFloatValue.toString(Str&: PrettyTargetValue, FormatPrecision: TargetPrecision);
13884
13885 DiagRuntimeBehavior(
13886 Loc: E->getExprLoc(), Statement: E,
13887 PD: PDiag(DiagID: diag::warn_impcast_integer_float_precision_constant)
13888 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13889 << E->getSourceRange() << clang::SourceRange(CC));
13890 }
13891 } else {
13892 // Otherwise, the implicit conversion may lose precision.
13893 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13894 diag: diag::warn_impcast_integer_float_precision);
13895 }
13896 }
13897 }
13898
13899 DiagnoseNullConversion(S&: *this, E, T, CC);
13900
13901 DiscardMisalignedMemberAddress(T: Target, E);
13902
13903 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13904 DiagnoseMixedUnicodeImplicitConversion(S&: *this, Source, Target, E, T, CC);
13905 return;
13906 }
13907
13908 if (Target->isBooleanType())
13909 DiagnoseIntInBoolContext(S&: *this, E);
13910
13911 if (DiscardingCFIUncheckedCallee(From: QualType(Source, 0), To: QualType(Target, 0))) {
13912 Diag(Loc: CC, DiagID: diag::warn_cast_discards_cfi_unchecked_callee)
13913 << QualType(Source, 0) << QualType(Target, 0);
13914 }
13915
13916 if (!Source->isIntegerType() || !Target->isIntegerType())
13917 return;
13918
13919 // TODO: remove this early return once the false positives for constant->bool
13920 // in templates, macros, etc, are reduced or removed.
13921 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool))
13922 return;
13923
13924 if (ObjC().isSignedCharBool(Ty: T) && !Source->isCharType() &&
13925 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13926 return ObjC().adornBoolConversionDiagWithTernaryFixit(
13927 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_int_to_objc_signed_char_bool)
13928 << E->getType());
13929 }
13930 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13931 C&: Context, E, InConstantContext: isConstantEvaluatedContext(), /*Approximate=*/true);
13932 if (!LikelySourceRange)
13933 return;
13934
13935 IntRange SourceTypeRange =
13936 IntRange::forTargetOfCanonicalType(C&: Context, T: Source);
13937 IntRange TargetRange = IntRange::forTargetOfCanonicalType(C&: Context, T: Target);
13938
13939 if (LikelySourceRange->Width > TargetRange.Width) {
13940 // Check if target is a wrapping OBT - if so, don't warn about constant
13941 // conversion as this type may be used intentionally with implicit
13942 // truncation, especially during assignments.
13943 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13944 if (TargetOBT->isWrapKind()) {
13945 return;
13946 }
13947 }
13948
13949 // Check if source expression has an explicit __ob_wrap cast because if so,
13950 // wrapping was explicitly requested and we shouldn't warn
13951 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13952 if (SourceOBT->isWrapKind()) {
13953 return;
13954 }
13955 }
13956
13957 // If the source is a constant, use a default-on diagnostic.
13958 // TODO: this should happen for bitfield stores, too.
13959 Expr::EvalResult Result;
13960 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13961 InConstantContext: isConstantEvaluatedContext())) {
13962 llvm::APSInt Value(32);
13963 Value = Result.Val.getInt();
13964
13965 if (SourceMgr.isInSystemMacro(loc: CC))
13966 return;
13967
13968 std::string PrettySourceValue = toString(I: Value, Radix: 10);
13969 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
13970
13971 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13972 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
13973 << PrettySourceValue << PrettyTargetValue
13974 << E->getType() << T << E->getSourceRange()
13975 << SourceRange(CC));
13976 return;
13977 }
13978
13979 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13980 if (SourceMgr.isInSystemMacro(loc: CC))
13981 return;
13982
13983 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
13984 if (UO->getOpcode() == UO_Minus)
13985 return DiagnoseImpCast(
13986 S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_precision_on_negation);
13987 }
13988
13989 if (TargetRange.Width == 32 && Context.getIntWidth(T: E->getType()) == 64)
13990 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_64_32,
13991 /* pruneControlFlow */ PruneControlFlow: true);
13992 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13993 diag: diag::warn_impcast_integer_precision);
13994 }
13995
13996 if (TargetRange.Width > SourceTypeRange.Width) {
13997 if (auto *UO = dyn_cast<UnaryOperator>(Val: E))
13998 if (UO->getOpcode() == UO_Minus)
13999 if (Source->isUnsignedIntegerType()) {
14000 if (Target->isUnsignedIntegerType())
14001 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
14002 diag: diag::warn_impcast_high_order_zero_bits);
14003 if (Target->isSignedIntegerType())
14004 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
14005 diag: diag::warn_impcast_nonnegative_result);
14006 }
14007 }
14008
14009 if (TargetRange.Width == LikelySourceRange->Width &&
14010 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
14011 Source->isSignedIntegerType()) {
14012 // Warn when doing a signed to signed conversion, warn if the positive
14013 // source value is exactly the width of the target type, which will
14014 // cause a negative value to be stored.
14015
14016 Expr::EvalResult Result;
14017 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects) &&
14018 !SourceMgr.isInSystemMacro(loc: CC)) {
14019 llvm::APSInt Value = Result.Val.getInt();
14020 if (isSameWidthConstantConversion(S&: *this, E, T, CC)) {
14021 std::string PrettySourceValue = toString(I: Value, Radix: 10);
14022 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
14023
14024 Diag(Loc: E->getExprLoc(),
14025 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
14026 << PrettySourceValue << PrettyTargetValue << E->getType() << T
14027 << E->getSourceRange() << SourceRange(CC));
14028 return;
14029 }
14030 }
14031
14032 // Fall through for non-constants to give a sign conversion warning.
14033 }
14034
14035 if ((!isa<EnumType>(Val: Target) || !isa<EnumType>(Val: Source)) &&
14036 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
14037 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
14038 LikelySourceRange->Width == TargetRange.Width))) {
14039 if (SourceMgr.isInSystemMacro(loc: CC))
14040 return;
14041
14042 if (SourceBT && SourceBT->isInteger() && TargetBT &&
14043 TargetBT->isInteger() &&
14044 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
14045 return;
14046 }
14047
14048 unsigned DiagID = diag::warn_impcast_integer_sign;
14049
14050 // Traditionally, gcc has warned about this under -Wsign-compare.
14051 // We also want to warn about it in -Wconversion.
14052 // So if -Wconversion is off, use a completely identical diagnostic
14053 // in the sign-compare group.
14054 // The conditional-checking code will
14055 if (ICContext) {
14056 DiagID = diag::warn_impcast_integer_sign_conditional;
14057 *ICContext = true;
14058 }
14059
14060 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagID);
14061 }
14062
14063 // If we're implicitly converting from an integer into an enumeration, that
14064 // is valid in C but invalid in C++.
14065 QualType SourceType = E->getEnumCoercedType(Ctx: Context);
14066 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
14067 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Val: Target))
14068 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_int_to_enum);
14069
14070 // Diagnose conversions between different enumeration types.
14071 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
14072 // type, to give us better diagnostics.
14073 Source = Context.getCanonicalType(T: SourceType).getTypePtr();
14074
14075 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
14076 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
14077 if (SourceEnum->getDecl()->hasNameForLinkage() &&
14078 TargetEnum->getDecl()->hasNameForLinkage() &&
14079 SourceEnum != TargetEnum) {
14080 if (SourceMgr.isInSystemMacro(loc: CC))
14081 return;
14082
14083 return DiagnoseImpCast(S&: *this, E, SourceType, T, CContext: CC,
14084 diag: diag::warn_impcast_different_enum_types);
14085 }
14086}
14087
14088static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
14089 SourceLocation CC, QualType T);
14090
14091static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
14092 SourceLocation CC, bool &ICContext) {
14093 E = E->IgnoreParenImpCasts();
14094 // Diagnose incomplete type for second or third operand in C.
14095 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
14096 S.RequireCompleteExprType(E, DiagID: diag::err_incomplete_type);
14097
14098 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: E))
14099 return CheckConditionalOperator(S, E: CO, CC, T);
14100
14101 AnalyzeImplicitConversions(S, E, CC);
14102 if (E->getType() != T)
14103 return S.CheckImplicitConversion(E, T, CC, ICContext: &ICContext);
14104}
14105
14106static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
14107 SourceLocation CC, QualType T) {
14108 AnalyzeImplicitConversions(S, E: E->getCond(), CC: E->getQuestionLoc());
14109
14110 Expr *TrueExpr = E->getTrueExpr();
14111 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(Val: E))
14112 TrueExpr = BCO->getCommon();
14113
14114 bool Suspicious = false;
14115 CheckConditionalOperand(S, E: TrueExpr, T, CC, ICContext&: Suspicious);
14116 CheckConditionalOperand(S, E: E->getFalseExpr(), T, CC, ICContext&: Suspicious);
14117
14118 if (T->isBooleanType())
14119 DiagnoseIntInBoolContext(S, E);
14120
14121 // If -Wconversion would have warned about either of the candidates
14122 // for a signedness conversion to the context type...
14123 if (!Suspicious) return;
14124
14125 // ...but it's currently ignored...
14126 if (!S.Diags.isIgnored(DiagID: diag::warn_impcast_integer_sign_conditional, Loc: CC))
14127 return;
14128
14129 // ...then check whether it would have warned about either of the
14130 // candidates for a signedness conversion to the condition type.
14131 if (E->getType() == T) return;
14132
14133 Suspicious = false;
14134 S.CheckImplicitConversion(E: TrueExpr->IgnoreParenImpCasts(), T: E->getType(), CC,
14135 ICContext: &Suspicious);
14136 if (!Suspicious)
14137 S.CheckImplicitConversion(E: E->getFalseExpr()->IgnoreParenImpCasts(),
14138 T: E->getType(), CC, ICContext: &Suspicious);
14139}
14140
14141/// Check conversion of given expression to boolean.
14142/// Input argument E is a logical expression.
14143static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
14144 // Run the bool-like conversion checks only for C since there bools are
14145 // still not used as the return type from "boolean" operators or as the input
14146 // type for conditional operators.
14147 if (S.getLangOpts().CPlusPlus)
14148 return;
14149 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
14150 return;
14151 S.CheckImplicitConversion(E: E->IgnoreParenImpCasts(), T: S.Context.BoolTy, CC);
14152}
14153
14154namespace {
14155struct AnalyzeImplicitConversionsWorkItem {
14156 Expr *E;
14157 SourceLocation CC;
14158 bool IsListInit;
14159};
14160}
14161
14162static void CheckCommaOperand(
14163 Sema &S, Expr *E, QualType T, SourceLocation CC,
14164 bool ExtraCheckForImplicitConversion,
14165 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
14166 E = E->IgnoreParenImpCasts();
14167 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: false});
14168
14169 if (ExtraCheckForImplicitConversion && E->getType() != T)
14170 S.CheckImplicitConversion(E, T, CC);
14171}
14172
14173/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
14174/// that should be visited are added to WorkList.
14175static void AnalyzeImplicitConversions(
14176 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
14177 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
14178 Expr *OrigE = Item.E;
14179 SourceLocation CC = Item.CC;
14180
14181 QualType T = OrigE->getType();
14182 Expr *E = OrigE->IgnoreParenImpCasts();
14183
14184 // Propagate whether we are in a C++ list initialization expression.
14185 // If so, we do not issue warnings for implicit int-float conversion
14186 // precision loss, because C++11 narrowing already handles it.
14187 //
14188 // HLSL's initialization lists are special, so they shouldn't observe the C++
14189 // behavior here.
14190 bool IsListInit =
14191 Item.IsListInit || (isa<InitListExpr>(Val: OrigE) &&
14192 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
14193
14194 if (E->isTypeDependent() || E->isValueDependent())
14195 return;
14196
14197 Expr *SourceExpr = E;
14198 // Examine, but don't traverse into the source expression of an
14199 // OpaqueValueExpr, since it may have multiple parents and we don't want to
14200 // emit duplicate diagnostics. Its fine to examine the form or attempt to
14201 // evaluate it in the context of checking the specific conversion to T though.
14202 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
14203 if (auto *Src = OVE->getSourceExpr())
14204 SourceExpr = Src;
14205
14206 if (const auto *UO = dyn_cast<UnaryOperator>(Val: SourceExpr))
14207 if (UO->getOpcode() == UO_Not &&
14208 UO->getSubExpr()->isKnownToHaveBooleanValue())
14209 S.Diag(Loc: UO->getBeginLoc(), DiagID: diag::warn_bitwise_negation_bool)
14210 << OrigE->getSourceRange() << T->isBooleanType()
14211 << FixItHint::CreateReplacement(RemoveRange: UO->getBeginLoc(), Code: "!");
14212
14213 if (auto *BO = dyn_cast<BinaryOperator>(Val: SourceExpr)) {
14214 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14215 BO->getLHS()->isKnownToHaveBooleanValue() &&
14216 BO->getRHS()->isKnownToHaveBooleanValue() &&
14217 BO->getLHS()->HasSideEffects(Ctx: S.Context) &&
14218 BO->getRHS()->HasSideEffects(Ctx: S.Context)) {
14219 SourceManager &SM = S.getSourceManager();
14220 const LangOptions &LO = S.getLangOpts();
14221 SourceLocation BLoc = BO->getOperatorLoc();
14222 SourceLocation ELoc = Lexer::getLocForEndOfToken(Loc: BLoc, Offset: 0, SM, LangOpts: LO);
14223 StringRef SR = clang::Lexer::getSourceText(
14224 Range: clang::CharSourceRange::getTokenRange(B: BLoc, E: ELoc), SM, LangOpts: LO);
14225 // To reduce false positives, only issue the diagnostic if the operator
14226 // is explicitly spelled as a punctuator. This suppresses the diagnostic
14227 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
14228 // in C, along with other macro spellings the user might invent.
14229 if (SR.str() == "&" || SR.str() == "|") {
14230
14231 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_bitwise_instead_of_logical)
14232 << (BO->getOpcode() == BO_And ? "&" : "|")
14233 << OrigE->getSourceRange()
14234 << FixItHint::CreateReplacement(
14235 RemoveRange: BO->getOperatorLoc(),
14236 Code: (BO->getOpcode() == BO_And ? "&&" : "||"));
14237 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::note_cast_operand_to_int);
14238 }
14239 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
14240 /// Analyze the given comma operator. The basic idea behind the analysis
14241 /// is to analyze the left and right operands slightly differently. The
14242 /// left operand needs to check whether the operand itself has an implicit
14243 /// conversion, but not whether the left operand induces an implicit
14244 /// conversion for the entire comma expression itself. This is similar to
14245 /// how CheckConditionalOperand behaves; it's as-if the correct operand
14246 /// were directly used for the implicit conversion check.
14247 CheckCommaOperand(S, E: BO->getLHS(), T, CC: BO->getOperatorLoc(),
14248 /*ExtraCheckForImplicitConversion=*/false, WorkList);
14249 CheckCommaOperand(S, E: BO->getRHS(), T, CC: BO->getOperatorLoc(),
14250 /*ExtraCheckForImplicitConversion=*/true, WorkList);
14251 return;
14252 }
14253 }
14254
14255 // For conditional operators, we analyze the arguments as if they
14256 // were being fed directly into the output.
14257 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: SourceExpr)) {
14258 CheckConditionalOperator(S, E: CO, CC, T);
14259 return;
14260 }
14261
14262 // Check implicit argument conversions for function calls.
14263 if (const auto *Call = dyn_cast<CallExpr>(Val: SourceExpr))
14264 CheckImplicitArgumentConversions(S, TheCall: Call, CC);
14265
14266 // Go ahead and check any implicit conversions we might have skipped.
14267 // The non-canonical typecheck is just an optimization;
14268 // CheckImplicitConversion will filter out dead implicit conversions.
14269 if (SourceExpr->getType() != T)
14270 S.CheckImplicitConversion(E: SourceExpr, T, CC, ICContext: nullptr, IsListInit);
14271
14272 // Now continue drilling into this expression.
14273
14274 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E)) {
14275 // The bound subexpressions in a PseudoObjectExpr are not reachable
14276 // as transitive children.
14277 // FIXME: Use a more uniform representation for this.
14278 for (auto *SE : POE->semantics())
14279 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: SE))
14280 WorkList.push_back(Elt: {.E: OVE->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
14281 }
14282
14283 // Skip past explicit casts.
14284 if (auto *CE = dyn_cast<ExplicitCastExpr>(Val: E)) {
14285 E = CE->getSubExpr();
14286 // In the special case of a C++ function-style cast with braces,
14287 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
14288 // initializer. This InitListExpr basically belongs to the cast itself, so
14289 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
14290 if (isa<CXXFunctionalCastExpr>(Val: CE)) {
14291 if (auto *InitListE = dyn_cast<InitListExpr>(Val: E)) {
14292 if (InitListE->getNumInits() == 1) {
14293 E = InitListE->getInit(Init: 0);
14294 }
14295 }
14296 }
14297 E = E->IgnoreParenImpCasts();
14298 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14299 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
14300 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: IsListInit});
14301 return;
14302 }
14303
14304 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(Val: E)) {
14305 WorkList.push_back(Elt: {.E: OutArgE->getArgLValue(), .CC: CC, .IsListInit: IsListInit});
14306 // The base expression is only used to initialize the parameter for
14307 // arguments to `inout` parameters, so we only traverse down the base
14308 // expression for `inout` cases.
14309 if (OutArgE->isInOut())
14310 WorkList.push_back(
14311 Elt: {.E: OutArgE->getCastedTemporary()->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
14312 WorkList.push_back(Elt: {.E: OutArgE->getWritebackCast(), .CC: CC, .IsListInit: IsListInit});
14313 return;
14314 }
14315
14316 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
14317 // Do a somewhat different check with comparison operators.
14318 if (BO->isComparisonOp())
14319 return AnalyzeComparison(S, E: BO);
14320
14321 // And with simple assignments.
14322 if (BO->getOpcode() == BO_Assign)
14323 return AnalyzeAssignment(S, E: BO);
14324 // And with compound assignments.
14325 if (BO->isAssignmentOp())
14326 return AnalyzeCompoundAssignment(S, E: BO);
14327 }
14328
14329 // These break the otherwise-useful invariant below. Fortunately,
14330 // we don't really need to recurse into them, because any internal
14331 // expressions should have been analyzed already when they were
14332 // built into statements.
14333 if (isa<StmtExpr>(Val: E)) return;
14334
14335 // Don't descend into unevaluated contexts.
14336 if (isa<UnaryExprOrTypeTraitExpr>(Val: E)) return;
14337
14338 // Now just recurse over the expression's children.
14339 CC = E->getExprLoc();
14340 BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E);
14341 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14342 for (Stmt *SubStmt : E->children()) {
14343 Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: SubStmt);
14344 if (!ChildExpr)
14345 continue;
14346
14347 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(Val: E))
14348 if (ChildExpr == CSE->getOperand())
14349 // Do not recurse over a CoroutineSuspendExpr's operand.
14350 // The operand is also a subexpression of getCommonExpr(), and
14351 // recursing into it directly would produce duplicate diagnostics.
14352 continue;
14353
14354 if (IsLogicalAndOperator &&
14355 isa<StringLiteral>(Val: ChildExpr->IgnoreParenImpCasts()))
14356 // Ignore checking string literals that are in logical and operators.
14357 // This is a common pattern for asserts.
14358 continue;
14359 WorkList.push_back(Elt: {.E: ChildExpr, .CC: CC, .IsListInit: IsListInit});
14360 }
14361
14362 if (BO && BO->isLogicalOp()) {
14363 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14364 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
14365 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
14366
14367 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14368 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
14369 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
14370 }
14371
14372 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(Val: E)) {
14373 if (U->getOpcode() == UO_LNot) {
14374 ::CheckBoolLikeConversion(S, E: U->getSubExpr(), CC);
14375 } else if (U->getOpcode() != UO_AddrOf) {
14376 if (U->getSubExpr()->getType()->isAtomicType())
14377 S.Diag(Loc: U->getSubExpr()->getBeginLoc(),
14378 DiagID: diag::warn_atomic_implicit_seq_cst);
14379 }
14380 }
14381}
14382
14383/// AnalyzeImplicitConversions - Find and report any interesting
14384/// implicit conversions in the given expression. There are a couple
14385/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14386static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
14387 bool IsListInit/*= false*/) {
14388 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
14389 WorkList.push_back(Elt: {.E: OrigE, .CC: CC, .IsListInit: IsListInit});
14390 while (!WorkList.empty())
14391 AnalyzeImplicitConversions(S, Item: WorkList.pop_back_val(), WorkList);
14392}
14393
14394// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14395// Returns true when emitting a warning about taking the address of a reference.
14396static bool CheckForReference(Sema &SemaRef, const Expr *E,
14397 const PartialDiagnostic &PD) {
14398 E = E->IgnoreParenImpCasts();
14399
14400 const FunctionDecl *FD = nullptr;
14401
14402 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14403 if (!DRE->getDecl()->getType()->isReferenceType())
14404 return false;
14405 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
14406 if (!M->getMemberDecl()->getType()->isReferenceType())
14407 return false;
14408 } else if (const CallExpr *Call = dyn_cast<CallExpr>(Val: E)) {
14409 if (!Call->getCallReturnType(Ctx: SemaRef.Context)->isReferenceType())
14410 return false;
14411 FD = Call->getDirectCallee();
14412 } else {
14413 return false;
14414 }
14415
14416 SemaRef.Diag(Loc: E->getExprLoc(), PD);
14417
14418 // If possible, point to location of function.
14419 if (FD) {
14420 SemaRef.Diag(Loc: FD->getLocation(), DiagID: diag::note_reference_is_return_value) << FD;
14421 }
14422
14423 return true;
14424}
14425
14426// Returns true if the SourceLocation is expanded from any macro body.
14427// Returns false if the SourceLocation is invalid, is from not in a macro
14428// expansion, or is from expanded from a top-level macro argument.
14429static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
14430 if (Loc.isInvalid())
14431 return false;
14432
14433 while (Loc.isMacroID()) {
14434 if (SM.isMacroBodyExpansion(Loc))
14435 return true;
14436 Loc = SM.getImmediateMacroCallerLoc(Loc);
14437 }
14438
14439 return false;
14440}
14441
14442void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
14443 Expr::NullPointerConstantKind NullKind,
14444 bool IsEqual, SourceRange Range) {
14445 if (!E)
14446 return;
14447
14448 // Don't warn inside macros.
14449 if (E->getExprLoc().isMacroID()) {
14450 const SourceManager &SM = getSourceManager();
14451 if (IsInAnyMacroBody(SM, Loc: E->getExprLoc()) ||
14452 IsInAnyMacroBody(SM, Loc: Range.getBegin()))
14453 return;
14454 }
14455 E = E->IgnoreImpCasts();
14456
14457 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14458
14459 if (isa<CXXThisExpr>(Val: E)) {
14460 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14461 : diag::warn_this_bool_conversion;
14462 Diag(Loc: E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14463 return;
14464 }
14465
14466 bool IsAddressOf = false;
14467
14468 if (auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParens())) {
14469 if (UO->getOpcode() != UO_AddrOf)
14470 return;
14471 IsAddressOf = true;
14472 E = UO->getSubExpr();
14473 }
14474
14475 if (IsAddressOf) {
14476 unsigned DiagID = IsCompare
14477 ? diag::warn_address_of_reference_null_compare
14478 : diag::warn_address_of_reference_bool_conversion;
14479 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14480 << IsEqual;
14481 if (CheckForReference(SemaRef&: *this, E, PD)) {
14482 return;
14483 }
14484 }
14485
14486 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14487 bool IsParam = isa<NonNullAttr>(Val: NonnullAttr);
14488 std::string Str;
14489 llvm::raw_string_ostream S(Str);
14490 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
14491 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14492 : diag::warn_cast_nonnull_to_bool;
14493 Diag(Loc: E->getExprLoc(), DiagID) << IsParam << S.str()
14494 << E->getSourceRange() << Range << IsEqual;
14495 Diag(Loc: NonnullAttr->getLocation(), DiagID: diag::note_declared_nonnull) << IsParam;
14496 };
14497
14498 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14499 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts())) {
14500 if (auto *Callee = Call->getDirectCallee()) {
14501 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14502 ComplainAboutNonnullParamOrCall(A);
14503 return;
14504 }
14505 }
14506 }
14507
14508 // Complain if we are converting a lambda expression to a boolean value
14509 // outside of instantiation.
14510 if (!inTemplateInstantiation()) {
14511 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(Val: E)) {
14512 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14513 MRecordDecl && MRecordDecl->isLambda()) {
14514 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_impcast_pointer_to_bool)
14515 << /*LambdaPointerConversionOperatorType=*/3
14516 << MRecordDecl->getSourceRange() << Range << IsEqual;
14517 return;
14518 }
14519 }
14520 }
14521
14522 // Expect to find a single Decl. Skip anything more complicated.
14523 ValueDecl *D = nullptr;
14524 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(Val: E)) {
14525 D = R->getDecl();
14526 } else if (MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
14527 D = M->getMemberDecl();
14528 }
14529
14530 // Weak Decls can be null.
14531 if (!D || D->isWeak())
14532 return;
14533
14534 // Check for parameter decl with nonnull attribute
14535 if (const auto* PV = dyn_cast<ParmVarDecl>(Val: D)) {
14536 if (getCurFunction() &&
14537 !getCurFunction()->ModifiedNonNullParams.count(Ptr: PV)) {
14538 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14539 ComplainAboutNonnullParamOrCall(A);
14540 return;
14541 }
14542
14543 if (const auto *FD = dyn_cast<FunctionDecl>(Val: PV->getDeclContext())) {
14544 // Skip function template not specialized yet.
14545 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
14546 return;
14547 auto ParamIter = llvm::find(Range: FD->parameters(), Val: PV);
14548 assert(ParamIter != FD->param_end());
14549 unsigned ParamNo = std::distance(first: FD->param_begin(), last: ParamIter);
14550
14551 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14552 if (!NonNull->args_size()) {
14553 ComplainAboutNonnullParamOrCall(NonNull);
14554 return;
14555 }
14556
14557 for (const ParamIdx &ArgNo : NonNull->args()) {
14558 if (ArgNo.getASTIndex() == ParamNo) {
14559 ComplainAboutNonnullParamOrCall(NonNull);
14560 return;
14561 }
14562 }
14563 }
14564 }
14565 }
14566 }
14567
14568 QualType T = D->getType();
14569 // A reference to a function is never null either; look through it.
14570 const bool IsFunctionReference =
14571 T->isReferenceType() && T->getPointeeType()->isFunctionType();
14572 if (IsFunctionReference)
14573 T = T->getPointeeType();
14574 const bool IsArray = T->isArrayType();
14575 const bool IsFunction = T->isFunctionType();
14576
14577 // Address of function is used to silence the function warning.
14578 if (IsAddressOf && IsFunction) {
14579 return;
14580 }
14581
14582 // Found nothing.
14583 if (!IsAddressOf && !IsFunction && !IsArray)
14584 return;
14585
14586 // Pretty print the expression for the diagnostic.
14587 std::string Str;
14588 llvm::raw_string_ostream S(Str);
14589 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
14590
14591 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14592 : diag::warn_impcast_pointer_to_bool;
14593 enum {
14594 AddressOf,
14595 FunctionPointer,
14596 ArrayPointer
14597 } DiagType;
14598 if (IsAddressOf)
14599 DiagType = AddressOf;
14600 else if (IsFunction)
14601 DiagType = FunctionPointer;
14602 else if (IsArray)
14603 DiagType = ArrayPointer;
14604 else
14605 llvm_unreachable("Could not determine diagnostic.");
14606 Diag(Loc: E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14607 << Range << IsEqual;
14608
14609 // The fix-it notes below only apply to a bare function name, not a reference.
14610 if (!IsFunction || IsFunctionReference)
14611 return;
14612
14613 // Suggest '&' to silence the function warning.
14614 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_warning_silence)
14615 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "&");
14616
14617 // Check to see if '()' fixit should be emitted.
14618 QualType ReturnType;
14619 UnresolvedSet<4> NonTemplateOverloads;
14620 tryExprAsCall(E&: *E, ZeroArgCallReturnTy&: ReturnType, NonTemplateOverloads);
14621 if (ReturnType.isNull())
14622 return;
14623
14624 if (IsCompare) {
14625 // There are two cases here. If there is null constant, the only suggest
14626 // for a pointer return type. If the null is 0, then suggest if the return
14627 // type is a pointer or an integer type.
14628 if (!ReturnType->isPointerType()) {
14629 if (NullKind == Expr::NPCK_ZeroExpression ||
14630 NullKind == Expr::NPCK_ZeroLiteral) {
14631 if (!ReturnType->isIntegerType())
14632 return;
14633 } else {
14634 return;
14635 }
14636 }
14637 } else { // !IsCompare
14638 // For function to bool, only suggest if the function pointer has bool
14639 // return type.
14640 if (!ReturnType->isSpecificBuiltinType(K: BuiltinType::Bool))
14641 return;
14642 }
14643 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_to_function_call)
14644 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: E->getEndLoc()), Code: "()");
14645}
14646
14647bool Sema::CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
14648 SourceLocation CC) {
14649 QualType Source = E->getType();
14650 QualType Target = T;
14651
14652 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14653 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14654 // Overflow behavior type is being stripped - issue warning
14655 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14656 Target->isUnsignedIntegerType()) {
14657 // For unsigned wrap to unsigned conversions, use pedantic version
14658 unsigned DiagId =
14659 InOverflowBehaviorAssignmentContext
14660 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14661 : diag::warn_impcast_overflow_behavior_pedantic;
14662 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14663 } else {
14664 unsigned DiagId = InOverflowBehaviorAssignmentContext
14665 ? diag::warn_impcast_overflow_behavior_assignment
14666 : diag::warn_impcast_overflow_behavior;
14667 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14668 }
14669 }
14670 }
14671
14672 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14673 if (TargetOBT->isWrapKind()) {
14674 return true;
14675 }
14676 }
14677
14678 return false;
14679}
14680
14681void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14682 // Don't diagnose in unevaluated contexts.
14683 if (isUnevaluatedContext())
14684 return;
14685
14686 // Don't diagnose for value- or type-dependent expressions.
14687 if (E->isTypeDependent() || E->isValueDependent())
14688 return;
14689
14690 // Check for array bounds violations in cases where the check isn't triggered
14691 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14692 // ArraySubscriptExpr is on the RHS of a variable initialization.
14693 CheckArrayAccess(E);
14694
14695 // This is not the right CC for (e.g.) a variable initialization.
14696 AnalyzeImplicitConversions(S&: *this, OrigE: E, CC);
14697}
14698
14699void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14700 ::CheckBoolLikeConversion(S&: *this, E, CC);
14701}
14702
14703void Sema::CheckForIntOverflow (const Expr *E) {
14704 // Use a work list to deal with nested struct initializers.
14705 SmallVector<const Expr *, 2> Exprs(1, E);
14706
14707 do {
14708 const Expr *OriginalE = Exprs.pop_back_val();
14709 const Expr *E = OriginalE->IgnoreParenCasts();
14710
14711 if (isa<BinaryOperator>(Val: E) ||
14712 (isa<UnaryOperator>(Val: E) && cast<UnaryOperator>(Val: E)->canOverflow())) {
14713 E->EvaluateForOverflow(Ctx: Context);
14714 continue;
14715 }
14716
14717 if (const auto *InitList = dyn_cast<InitListExpr>(Val: OriginalE))
14718 Exprs.append(in_start: InitList->inits().begin(), in_end: InitList->inits().end());
14719 else if (isa<ObjCBoxedExpr>(Val: OriginalE))
14720 E->EvaluateForOverflow(Ctx: Context);
14721 else if (const auto *Call = dyn_cast<CallExpr>(Val: E))
14722 Exprs.append(in_start: Call->arg_begin(), in_end: Call->arg_end());
14723 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(Val: E))
14724 Exprs.append(in_start: Message->arg_begin(), in_end: Message->arg_end());
14725 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(Val: E))
14726 Exprs.append(in_start: Construct->arg_begin(), in_end: Construct->arg_end());
14727 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(Val: E))
14728 Exprs.push_back(Elt: Temporary->getSubExpr());
14729 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(Val: E))
14730 Exprs.push_back(Elt: Array->getIdx());
14731 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(Val: E))
14732 Exprs.push_back(Elt: Compound->getInitializer());
14733 else if (const auto *New = dyn_cast<CXXNewExpr>(Val: E);
14734 New && New->isArray()) {
14735 if (auto ArraySize = New->getArraySize())
14736 Exprs.push_back(Elt: *ArraySize);
14737 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: OriginalE))
14738 Exprs.push_back(Elt: MTE->getSubExpr());
14739 } while (!Exprs.empty());
14740}
14741
14742namespace {
14743
14744/// Visitor for expressions which looks for unsequenced operations on the
14745/// same object.
14746class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14747 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14748
14749 /// A tree of sequenced regions within an expression. Two regions are
14750 /// unsequenced if one is an ancestor or a descendent of the other. When we
14751 /// finish processing an expression with sequencing, such as a comma
14752 /// expression, we fold its tree nodes into its parent, since they are
14753 /// unsequenced with respect to nodes we will visit later.
14754 class SequenceTree {
14755 struct Value {
14756 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14757 unsigned Parent : 31;
14758 LLVM_PREFERRED_TYPE(bool)
14759 unsigned Merged : 1;
14760 };
14761 SmallVector<Value, 8> Values;
14762
14763 public:
14764 /// A region within an expression which may be sequenced with respect
14765 /// to some other region.
14766 class Seq {
14767 friend class SequenceTree;
14768
14769 unsigned Index;
14770
14771 explicit Seq(unsigned N) : Index(N) {}
14772
14773 public:
14774 Seq() : Index(0) {}
14775 };
14776
14777 SequenceTree() { Values.push_back(Elt: Value(0)); }
14778 Seq root() const { return Seq(0); }
14779
14780 /// Create a new sequence of operations, which is an unsequenced
14781 /// subset of \p Parent. This sequence of operations is sequenced with
14782 /// respect to other children of \p Parent.
14783 Seq allocate(Seq Parent) {
14784 Values.push_back(Elt: Value(Parent.Index));
14785 return Seq(Values.size() - 1);
14786 }
14787
14788 /// Merge a sequence of operations into its parent.
14789 void merge(Seq S) {
14790 Values[S.Index].Merged = true;
14791 }
14792
14793 /// Determine whether two operations are unsequenced. This operation
14794 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14795 /// should have been merged into its parent as appropriate.
14796 bool isUnsequenced(Seq Cur, Seq Old) {
14797 unsigned C = representative(K: Cur.Index);
14798 unsigned Target = representative(K: Old.Index);
14799 while (C >= Target) {
14800 if (C == Target)
14801 return true;
14802 C = Values[C].Parent;
14803 }
14804 return false;
14805 }
14806
14807 private:
14808 /// Pick a representative for a sequence.
14809 unsigned representative(unsigned K) {
14810 if (Values[K].Merged)
14811 // Perform path compression as we go.
14812 return Values[K].Parent = representative(K: Values[K].Parent);
14813 return K;
14814 }
14815 };
14816
14817 /// An object for which we can track unsequenced uses.
14818 using Object = const NamedDecl *;
14819
14820 /// Different flavors of object usage which we track. We only track the
14821 /// least-sequenced usage of each kind.
14822 enum UsageKind {
14823 /// A read of an object. Multiple unsequenced reads are OK.
14824 UK_Use,
14825
14826 /// A modification of an object which is sequenced before the value
14827 /// computation of the expression, such as ++n in C++.
14828 UK_ModAsValue,
14829
14830 /// A modification of an object which is not sequenced before the value
14831 /// computation of the expression, such as n++.
14832 UK_ModAsSideEffect,
14833
14834 UK_Count = UK_ModAsSideEffect + 1
14835 };
14836
14837 /// Bundle together a sequencing region and the expression corresponding
14838 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14839 struct Usage {
14840 const Expr *UsageExpr = nullptr;
14841 SequenceTree::Seq Seq;
14842
14843 Usage() = default;
14844 };
14845
14846 struct UsageInfo {
14847 Usage Uses[UK_Count];
14848
14849 /// Have we issued a diagnostic for this object already?
14850 bool Diagnosed = false;
14851
14852 UsageInfo();
14853 };
14854 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14855
14856 Sema &SemaRef;
14857
14858 /// Sequenced regions within the expression.
14859 SequenceTree Tree;
14860
14861 /// Declaration modifications and references which we have seen.
14862 UsageInfoMap UsageMap;
14863
14864 /// The region we are currently within.
14865 SequenceTree::Seq Region;
14866
14867 /// Filled in with declarations which were modified as a side-effect
14868 /// (that is, post-increment operations).
14869 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14870
14871 /// Expressions to check later. We defer checking these to reduce
14872 /// stack usage.
14873 SmallVectorImpl<const Expr *> &WorkList;
14874
14875 /// RAII object wrapping the visitation of a sequenced subexpression of an
14876 /// expression. At the end of this process, the side-effects of the evaluation
14877 /// become sequenced with respect to the value computation of the result, so
14878 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14879 /// UK_ModAsValue.
14880 struct SequencedSubexpression {
14881 SequencedSubexpression(SequenceChecker &Self)
14882 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14883 Self.ModAsSideEffect = &ModAsSideEffect;
14884 }
14885
14886 ~SequencedSubexpression() {
14887 for (const std::pair<Object, Usage> &M : llvm::reverse(C&: ModAsSideEffect)) {
14888 // Add a new usage with usage kind UK_ModAsValue, and then restore
14889 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14890 // the previous one was empty).
14891 UsageInfo &UI = Self.UsageMap[M.first];
14892 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14893 Self.addUsage(O: M.first, UI, UsageExpr: SideEffectUsage.UsageExpr, UK: UK_ModAsValue);
14894 SideEffectUsage = M.second;
14895 }
14896 Self.ModAsSideEffect = OldModAsSideEffect;
14897 }
14898
14899 SequenceChecker &Self;
14900 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14901 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14902 };
14903
14904 /// RAII object wrapping the visitation of a subexpression which we might
14905 /// choose to evaluate as a constant. If any subexpression is evaluated and
14906 /// found to be non-constant, this allows us to suppress the evaluation of
14907 /// the outer expression.
14908 class EvaluationTracker {
14909 public:
14910 EvaluationTracker(SequenceChecker &Self)
14911 : Self(Self), Prev(Self.EvalTracker) {
14912 Self.EvalTracker = this;
14913 }
14914
14915 ~EvaluationTracker() {
14916 Self.EvalTracker = Prev;
14917 if (Prev)
14918 Prev->EvalOK &= EvalOK;
14919 }
14920
14921 bool evaluate(const Expr *E, bool &Result) {
14922 if (!EvalOK || E->isValueDependent())
14923 return false;
14924 EvalOK = E->EvaluateAsBooleanCondition(
14925 Result, Ctx: Self.SemaRef.Context,
14926 InConstantContext: Self.SemaRef.isConstantEvaluatedContext());
14927 return EvalOK;
14928 }
14929
14930 private:
14931 SequenceChecker &Self;
14932 EvaluationTracker *Prev;
14933 bool EvalOK = true;
14934 } *EvalTracker = nullptr;
14935
14936 /// Find the object which is produced by the specified expression,
14937 /// if any.
14938 Object getObject(const Expr *E, bool Mod) const {
14939 E = E->IgnoreParenCasts();
14940 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) {
14941 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14942 return getObject(E: UO->getSubExpr(), Mod);
14943 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
14944 if (BO->getOpcode() == BO_Comma)
14945 return getObject(E: BO->getRHS(), Mod);
14946 if (Mod && BO->isAssignmentOp())
14947 return getObject(E: BO->getLHS(), Mod);
14948 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14949 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14950 if (isa<CXXThisExpr>(Val: ME->getBase()->IgnoreParenCasts()))
14951 return ME->getMemberDecl();
14952 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14953 // FIXME: If this is a reference, map through to its value.
14954 return DRE->getDecl();
14955 return nullptr;
14956 }
14957
14958 /// Note that an object \p O was modified or used by an expression
14959 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14960 /// the object \p O as obtained via the \p UsageMap.
14961 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14962 // Get the old usage for the given object and usage kind.
14963 Usage &U = UI.Uses[UK];
14964 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq)) {
14965 // If we have a modification as side effect and are in a sequenced
14966 // subexpression, save the old Usage so that we can restore it later
14967 // in SequencedSubexpression::~SequencedSubexpression.
14968 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14969 ModAsSideEffect->push_back(Elt: std::make_pair(x&: O, y&: U));
14970 // Then record the new usage with the current sequencing region.
14971 U.UsageExpr = UsageExpr;
14972 U.Seq = Region;
14973 }
14974 }
14975
14976 /// Check whether a modification or use of an object \p O in an expression
14977 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14978 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14979 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14980 /// usage and false we are checking for a mod-use unsequenced usage.
14981 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14982 UsageKind OtherKind, bool IsModMod) {
14983 if (UI.Diagnosed)
14984 return;
14985
14986 const Usage &U = UI.Uses[OtherKind];
14987 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq))
14988 return;
14989
14990 const Expr *Mod = U.UsageExpr;
14991 const Expr *ModOrUse = UsageExpr;
14992 if (OtherKind == UK_Use)
14993 std::swap(a&: Mod, b&: ModOrUse);
14994
14995 SemaRef.DiagRuntimeBehavior(
14996 Loc: Mod->getExprLoc(), Stmts: {Mod, ModOrUse},
14997 PD: SemaRef.PDiag(DiagID: IsModMod ? diag::warn_unsequenced_mod_mod
14998 : diag::warn_unsequenced_mod_use)
14999 << O << SourceRange(ModOrUse->getExprLoc()));
15000 UI.Diagnosed = true;
15001 }
15002
15003 // A note on note{Pre, Post}{Use, Mod}:
15004 //
15005 // (It helps to follow the algorithm with an expression such as
15006 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
15007 // operations before C++17 and both are well-defined in C++17).
15008 //
15009 // When visiting a node which uses/modify an object we first call notePreUse
15010 // or notePreMod before visiting its sub-expression(s). At this point the
15011 // children of the current node have not yet been visited and so the eventual
15012 // uses/modifications resulting from the children of the current node have not
15013 // been recorded yet.
15014 //
15015 // We then visit the children of the current node. After that notePostUse or
15016 // notePostMod is called. These will 1) detect an unsequenced modification
15017 // as side effect (as in "k++ + k") and 2) add a new usage with the
15018 // appropriate usage kind.
15019 //
15020 // We also have to be careful that some operation sequences modification as
15021 // side effect as well (for example: || or ,). To account for this we wrap
15022 // the visitation of such a sub-expression (for example: the LHS of || or ,)
15023 // with SequencedSubexpression. SequencedSubexpression is an RAII object
15024 // which record usages which are modifications as side effect, and then
15025 // downgrade them (or more accurately restore the previous usage which was a
15026 // modification as side effect) when exiting the scope of the sequenced
15027 // subexpression.
15028
15029 void notePreUse(Object O, const Expr *UseExpr) {
15030 UsageInfo &UI = UsageMap[O];
15031 // Uses conflict with other modifications.
15032 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
15033 }
15034
15035 void notePostUse(Object O, const Expr *UseExpr) {
15036 UsageInfo &UI = UsageMap[O];
15037 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
15038 /*IsModMod=*/false);
15039 addUsage(O, UI, UsageExpr: UseExpr, /*UsageKind=*/UK: UK_Use);
15040 }
15041
15042 void notePreMod(Object O, const Expr *ModExpr) {
15043 UsageInfo &UI = UsageMap[O];
15044 // Modifications conflict with other modifications and with uses.
15045 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
15046 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
15047 }
15048
15049 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
15050 UsageInfo &UI = UsageMap[O];
15051 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
15052 /*IsModMod=*/true);
15053 addUsage(O, UI, UsageExpr: ModExpr, /*UsageKind=*/UK);
15054 }
15055
15056public:
15057 SequenceChecker(Sema &S, const Expr *E,
15058 SmallVectorImpl<const Expr *> &WorkList)
15059 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
15060 Visit(S: E);
15061 // Silence a -Wunused-private-field since WorkList is now unused.
15062 // TODO: Evaluate if it can be used, and if not remove it.
15063 (void)this->WorkList;
15064 }
15065
15066 void VisitStmt(const Stmt *S) {
15067 // Skip all statements which aren't expressions for now.
15068 }
15069
15070 void VisitExpr(const Expr *E) {
15071 // By default, just recurse to evaluated subexpressions.
15072 Base::VisitStmt(S: E);
15073 }
15074
15075 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
15076 for (auto *Sub : CSE->children()) {
15077 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: Sub);
15078 if (!ChildExpr)
15079 continue;
15080
15081 if (ChildExpr == CSE->getOperand())
15082 // Do not recurse over a CoroutineSuspendExpr's operand.
15083 // The operand is also a subexpression of getCommonExpr(), and
15084 // recursing into it directly could confuse object management
15085 // for the sake of sequence tracking.
15086 continue;
15087
15088 Visit(S: Sub);
15089 }
15090 }
15091
15092 void VisitCastExpr(const CastExpr *E) {
15093 Object O = Object();
15094 if (E->getCastKind() == CK_LValueToRValue)
15095 O = getObject(E: E->getSubExpr(), Mod: false);
15096
15097 if (O)
15098 notePreUse(O, UseExpr: E);
15099 VisitExpr(E);
15100 if (O)
15101 notePostUse(O, UseExpr: E);
15102 }
15103
15104 void VisitSequencedExpressions(const Expr *SequencedBefore,
15105 const Expr *SequencedAfter) {
15106 SequenceTree::Seq BeforeRegion = Tree.allocate(Parent: Region);
15107 SequenceTree::Seq AfterRegion = Tree.allocate(Parent: Region);
15108 SequenceTree::Seq OldRegion = Region;
15109
15110 {
15111 SequencedSubexpression SeqBefore(*this);
15112 Region = BeforeRegion;
15113 Visit(S: SequencedBefore);
15114 }
15115
15116 Region = AfterRegion;
15117 Visit(S: SequencedAfter);
15118
15119 Region = OldRegion;
15120
15121 Tree.merge(S: BeforeRegion);
15122 Tree.merge(S: AfterRegion);
15123 }
15124
15125 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
15126 // C++17 [expr.sub]p1:
15127 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
15128 // expression E1 is sequenced before the expression E2.
15129 if (SemaRef.getLangOpts().CPlusPlus17)
15130 VisitSequencedExpressions(SequencedBefore: ASE->getLHS(), SequencedAfter: ASE->getRHS());
15131 else {
15132 Visit(S: ASE->getLHS());
15133 Visit(S: ASE->getRHS());
15134 }
15135 }
15136
15137 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15138 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15139 void VisitBinPtrMem(const BinaryOperator *BO) {
15140 // C++17 [expr.mptr.oper]p4:
15141 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
15142 // the expression E1 is sequenced before the expression E2.
15143 if (SemaRef.getLangOpts().CPlusPlus17)
15144 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
15145 else {
15146 Visit(S: BO->getLHS());
15147 Visit(S: BO->getRHS());
15148 }
15149 }
15150
15151 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15152 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15153 void VisitBinShlShr(const BinaryOperator *BO) {
15154 // C++17 [expr.shift]p4:
15155 // The expression E1 is sequenced before the expression E2.
15156 if (SemaRef.getLangOpts().CPlusPlus17)
15157 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
15158 else {
15159 Visit(S: BO->getLHS());
15160 Visit(S: BO->getRHS());
15161 }
15162 }
15163
15164 void VisitBinComma(const BinaryOperator *BO) {
15165 // C++11 [expr.comma]p1:
15166 // Every value computation and side effect associated with the left
15167 // expression is sequenced before every value computation and side
15168 // effect associated with the right expression.
15169 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
15170 }
15171
15172 void VisitBinAssign(const BinaryOperator *BO) {
15173 SequenceTree::Seq RHSRegion;
15174 SequenceTree::Seq LHSRegion;
15175 if (SemaRef.getLangOpts().CPlusPlus17) {
15176 RHSRegion = Tree.allocate(Parent: Region);
15177 LHSRegion = Tree.allocate(Parent: Region);
15178 } else {
15179 RHSRegion = Region;
15180 LHSRegion = Region;
15181 }
15182 SequenceTree::Seq OldRegion = Region;
15183
15184 // C++11 [expr.ass]p1:
15185 // [...] the assignment is sequenced after the value computation
15186 // of the right and left operands, [...]
15187 //
15188 // so check it before inspecting the operands and update the
15189 // map afterwards.
15190 Object O = getObject(E: BO->getLHS(), /*Mod=*/true);
15191 if (O)
15192 notePreMod(O, ModExpr: BO);
15193
15194 if (SemaRef.getLangOpts().CPlusPlus17) {
15195 // C++17 [expr.ass]p1:
15196 // [...] The right operand is sequenced before the left operand. [...]
15197 {
15198 SequencedSubexpression SeqBefore(*this);
15199 Region = RHSRegion;
15200 Visit(S: BO->getRHS());
15201 }
15202
15203 Region = LHSRegion;
15204 Visit(S: BO->getLHS());
15205
15206 if (O && isa<CompoundAssignOperator>(Val: BO))
15207 notePostUse(O, UseExpr: BO);
15208
15209 } else {
15210 // C++11 does not specify any sequencing between the LHS and RHS.
15211 Region = LHSRegion;
15212 Visit(S: BO->getLHS());
15213
15214 if (O && isa<CompoundAssignOperator>(Val: BO))
15215 notePostUse(O, UseExpr: BO);
15216
15217 Region = RHSRegion;
15218 Visit(S: BO->getRHS());
15219 }
15220
15221 // C++11 [expr.ass]p1:
15222 // the assignment is sequenced [...] before the value computation of the
15223 // assignment expression.
15224 // C11 6.5.16/3 has no such rule.
15225 Region = OldRegion;
15226 if (O)
15227 notePostMod(O, ModExpr: BO,
15228 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15229 : UK_ModAsSideEffect);
15230 if (SemaRef.getLangOpts().CPlusPlus17) {
15231 Tree.merge(S: RHSRegion);
15232 Tree.merge(S: LHSRegion);
15233 }
15234 }
15235
15236 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
15237 VisitBinAssign(BO: CAO);
15238 }
15239
15240 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15241 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15242 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
15243 Object O = getObject(E: UO->getSubExpr(), Mod: true);
15244 if (!O)
15245 return VisitExpr(E: UO);
15246
15247 notePreMod(O, ModExpr: UO);
15248 Visit(S: UO->getSubExpr());
15249 // C++11 [expr.pre.incr]p1:
15250 // the expression ++x is equivalent to x+=1
15251 notePostMod(O, ModExpr: UO,
15252 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15253 : UK_ModAsSideEffect);
15254 }
15255
15256 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15257 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15258 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
15259 Object O = getObject(E: UO->getSubExpr(), Mod: true);
15260 if (!O)
15261 return VisitExpr(E: UO);
15262
15263 notePreMod(O, ModExpr: UO);
15264 Visit(S: UO->getSubExpr());
15265 notePostMod(O, ModExpr: UO, UK: UK_ModAsSideEffect);
15266 }
15267
15268 void VisitBinLOr(const BinaryOperator *BO) {
15269 // C++11 [expr.log.or]p2:
15270 // If the second expression is evaluated, every value computation and
15271 // side effect associated with the first expression is sequenced before
15272 // every value computation and side effect associated with the
15273 // second expression.
15274 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
15275 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
15276 SequenceTree::Seq OldRegion = Region;
15277
15278 EvaluationTracker Eval(*this);
15279 {
15280 SequencedSubexpression Sequenced(*this);
15281 Region = LHSRegion;
15282 Visit(S: BO->getLHS());
15283 }
15284
15285 // C++11 [expr.log.or]p1:
15286 // [...] the second operand is not evaluated if the first operand
15287 // evaluates to true.
15288 bool EvalResult = false;
15289 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
15290 bool ShouldVisitRHS = !EvalOK || !EvalResult;
15291 if (ShouldVisitRHS) {
15292 Region = RHSRegion;
15293 Visit(S: BO->getRHS());
15294 }
15295
15296 Region = OldRegion;
15297 Tree.merge(S: LHSRegion);
15298 Tree.merge(S: RHSRegion);
15299 }
15300
15301 void VisitBinLAnd(const BinaryOperator *BO) {
15302 // C++11 [expr.log.and]p2:
15303 // If the second expression is evaluated, every value computation and
15304 // side effect associated with the first expression is sequenced before
15305 // every value computation and side effect associated with the
15306 // second expression.
15307 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
15308 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
15309 SequenceTree::Seq OldRegion = Region;
15310
15311 EvaluationTracker Eval(*this);
15312 {
15313 SequencedSubexpression Sequenced(*this);
15314 Region = LHSRegion;
15315 Visit(S: BO->getLHS());
15316 }
15317
15318 // C++11 [expr.log.and]p1:
15319 // [...] the second operand is not evaluated if the first operand is false.
15320 bool EvalResult = false;
15321 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
15322 bool ShouldVisitRHS = !EvalOK || EvalResult;
15323 if (ShouldVisitRHS) {
15324 Region = RHSRegion;
15325 Visit(S: BO->getRHS());
15326 }
15327
15328 Region = OldRegion;
15329 Tree.merge(S: LHSRegion);
15330 Tree.merge(S: RHSRegion);
15331 }
15332
15333 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15334 // C++11 [expr.cond]p1:
15335 // [...] Every value computation and side effect associated with the first
15336 // expression is sequenced before every value computation and side effect
15337 // associated with the second or third expression.
15338 SequenceTree::Seq ConditionRegion = Tree.allocate(Parent: Region);
15339
15340 // No sequencing is specified between the true and false expression.
15341 // However since exactly one of both is going to be evaluated we can
15342 // consider them to be sequenced. This is needed to avoid warning on
15343 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15344 // both the true and false expressions because we can't evaluate x.
15345 // This will still allow us to detect an expression like (pre C++17)
15346 // "(x ? y += 1 : y += 2) = y".
15347 //
15348 // We don't wrap the visitation of the true and false expression with
15349 // SequencedSubexpression because we don't want to downgrade modifications
15350 // as side effect in the true and false expressions after the visition
15351 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15352 // not warn between the two "y++", but we should warn between the "y++"
15353 // and the "y".
15354 SequenceTree::Seq TrueRegion = Tree.allocate(Parent: Region);
15355 SequenceTree::Seq FalseRegion = Tree.allocate(Parent: Region);
15356 SequenceTree::Seq OldRegion = Region;
15357
15358 EvaluationTracker Eval(*this);
15359 {
15360 SequencedSubexpression Sequenced(*this);
15361 Region = ConditionRegion;
15362 Visit(S: CO->getCond());
15363 }
15364
15365 // C++11 [expr.cond]p1:
15366 // [...] The first expression is contextually converted to bool (Clause 4).
15367 // It is evaluated and if it is true, the result of the conditional
15368 // expression is the value of the second expression, otherwise that of the
15369 // third expression. Only one of the second and third expressions is
15370 // evaluated. [...]
15371 bool EvalResult = false;
15372 bool EvalOK = Eval.evaluate(E: CO->getCond(), Result&: EvalResult);
15373 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15374 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15375 if (ShouldVisitTrueExpr) {
15376 Region = TrueRegion;
15377 Visit(S: CO->getTrueExpr());
15378 }
15379 if (ShouldVisitFalseExpr) {
15380 Region = FalseRegion;
15381 Visit(S: CO->getFalseExpr());
15382 }
15383
15384 Region = OldRegion;
15385 Tree.merge(S: ConditionRegion);
15386 Tree.merge(S: TrueRegion);
15387 Tree.merge(S: FalseRegion);
15388 }
15389
15390 void VisitCallExpr(const CallExpr *CE) {
15391 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15392
15393 if (CE->isUnevaluatedBuiltinCall(Ctx: Context))
15394 return;
15395
15396 // C++11 [intro.execution]p15:
15397 // When calling a function [...], every value computation and side effect
15398 // associated with any argument expression, or with the postfix expression
15399 // designating the called function, is sequenced before execution of every
15400 // expression or statement in the body of the function [and thus before
15401 // the value computation of its result].
15402 SequencedSubexpression Sequenced(*this);
15403 SemaRef.runWithSufficientStackSpace(Loc: CE->getExprLoc(), Fn: [&] {
15404 // C++17 [expr.call]p5
15405 // The postfix-expression is sequenced before each expression in the
15406 // expression-list and any default argument. [...]
15407 SequenceTree::Seq CalleeRegion;
15408 SequenceTree::Seq OtherRegion;
15409 if (SemaRef.getLangOpts().CPlusPlus17) {
15410 CalleeRegion = Tree.allocate(Parent: Region);
15411 OtherRegion = Tree.allocate(Parent: Region);
15412 } else {
15413 CalleeRegion = Region;
15414 OtherRegion = Region;
15415 }
15416 SequenceTree::Seq OldRegion = Region;
15417
15418 // Visit the callee expression first.
15419 Region = CalleeRegion;
15420 if (SemaRef.getLangOpts().CPlusPlus17) {
15421 SequencedSubexpression Sequenced(*this);
15422 Visit(S: CE->getCallee());
15423 } else {
15424 Visit(S: CE->getCallee());
15425 }
15426
15427 // Then visit the argument expressions.
15428 Region = OtherRegion;
15429 for (const Expr *Argument : CE->arguments())
15430 Visit(S: Argument);
15431
15432 Region = OldRegion;
15433 if (SemaRef.getLangOpts().CPlusPlus17) {
15434 Tree.merge(S: CalleeRegion);
15435 Tree.merge(S: OtherRegion);
15436 }
15437 });
15438 }
15439
15440 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15441 // C++17 [over.match.oper]p2:
15442 // [...] the operator notation is first transformed to the equivalent
15443 // function-call notation as summarized in Table 12 (where @ denotes one
15444 // of the operators covered in the specified subclause). However, the
15445 // operands are sequenced in the order prescribed for the built-in
15446 // operator (Clause 8).
15447 //
15448 // From the above only overloaded binary operators and overloaded call
15449 // operators have sequencing rules in C++17 that we need to handle
15450 // separately.
15451 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15452 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15453 return VisitCallExpr(CE: CXXOCE);
15454
15455 enum {
15456 NoSequencing,
15457 LHSBeforeRHS,
15458 RHSBeforeLHS,
15459 LHSBeforeRest
15460 } SequencingKind;
15461 switch (CXXOCE->getOperator()) {
15462 case OO_Equal:
15463 case OO_PlusEqual:
15464 case OO_MinusEqual:
15465 case OO_StarEqual:
15466 case OO_SlashEqual:
15467 case OO_PercentEqual:
15468 case OO_CaretEqual:
15469 case OO_AmpEqual:
15470 case OO_PipeEqual:
15471 case OO_LessLessEqual:
15472 case OO_GreaterGreaterEqual:
15473 SequencingKind = RHSBeforeLHS;
15474 break;
15475
15476 case OO_LessLess:
15477 case OO_GreaterGreater:
15478 case OO_AmpAmp:
15479 case OO_PipePipe:
15480 case OO_Comma:
15481 case OO_ArrowStar:
15482 case OO_Subscript:
15483 SequencingKind = LHSBeforeRHS;
15484 break;
15485
15486 case OO_Call:
15487 SequencingKind = LHSBeforeRest;
15488 break;
15489
15490 default:
15491 SequencingKind = NoSequencing;
15492 break;
15493 }
15494
15495 if (SequencingKind == NoSequencing)
15496 return VisitCallExpr(CE: CXXOCE);
15497
15498 // This is a call, so all subexpressions are sequenced before the result.
15499 SequencedSubexpression Sequenced(*this);
15500
15501 SemaRef.runWithSufficientStackSpace(Loc: CXXOCE->getExprLoc(), Fn: [&] {
15502 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15503 "Should only get there with C++17 and above!");
15504 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15505 "Should only get there with an overloaded binary operator"
15506 " or an overloaded call operator!");
15507
15508 if (SequencingKind == LHSBeforeRest) {
15509 assert(CXXOCE->getOperator() == OO_Call &&
15510 "We should only have an overloaded call operator here!");
15511
15512 // This is very similar to VisitCallExpr, except that we only have the
15513 // C++17 case. The postfix-expression is the first argument of the
15514 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15515 // are in the following arguments.
15516 //
15517 // Note that we intentionally do not visit the callee expression since
15518 // it is just a decayed reference to a function.
15519 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Parent: Region);
15520 SequenceTree::Seq ArgsRegion = Tree.allocate(Parent: Region);
15521 SequenceTree::Seq OldRegion = Region;
15522
15523 assert(CXXOCE->getNumArgs() >= 1 &&
15524 "An overloaded call operator must have at least one argument"
15525 " for the postfix-expression!");
15526 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15527 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15528 CXXOCE->getNumArgs() - 1);
15529
15530 // Visit the postfix-expression first.
15531 {
15532 Region = PostfixExprRegion;
15533 SequencedSubexpression Sequenced(*this);
15534 Visit(S: PostfixExpr);
15535 }
15536
15537 // Then visit the argument expressions.
15538 Region = ArgsRegion;
15539 for (const Expr *Arg : Args)
15540 Visit(S: Arg);
15541
15542 Region = OldRegion;
15543 Tree.merge(S: PostfixExprRegion);
15544 Tree.merge(S: ArgsRegion);
15545 } else {
15546 assert(CXXOCE->getNumArgs() == 2 &&
15547 "Should only have two arguments here!");
15548 assert((SequencingKind == LHSBeforeRHS ||
15549 SequencingKind == RHSBeforeLHS) &&
15550 "Unexpected sequencing kind!");
15551
15552 // We do not visit the callee expression since it is just a decayed
15553 // reference to a function.
15554 const Expr *E1 = CXXOCE->getArg(Arg: 0);
15555 const Expr *E2 = CXXOCE->getArg(Arg: 1);
15556 if (SequencingKind == RHSBeforeLHS)
15557 std::swap(a&: E1, b&: E2);
15558
15559 return VisitSequencedExpressions(SequencedBefore: E1, SequencedAfter: E2);
15560 }
15561 });
15562 }
15563
15564 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15565 // This is a call, so all subexpressions are sequenced before the result.
15566 SequencedSubexpression Sequenced(*this);
15567
15568 if (!CCE->isListInitialization())
15569 return VisitExpr(E: CCE);
15570
15571 // In C++11, list initializations are sequenced.
15572 SequenceExpressionsInOrder(
15573 ExpressionList: llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15574 }
15575
15576 void VisitInitListExpr(const InitListExpr *ILE) {
15577 if (!SemaRef.getLangOpts().CPlusPlus11)
15578 return VisitExpr(E: ILE);
15579
15580 // In C++11, list initializations are sequenced.
15581 SequenceExpressionsInOrder(ExpressionList: ILE->inits());
15582 }
15583
15584 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15585 // C++20 parenthesized list initializations are sequenced. See C++20
15586 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15587 SequenceExpressionsInOrder(ExpressionList: PLIE->getInitExprs());
15588 }
15589
15590private:
15591 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15592 SmallVector<SequenceTree::Seq, 32> Elts;
15593 SequenceTree::Seq Parent = Region;
15594 for (const Expr *E : ExpressionList) {
15595 if (!E)
15596 continue;
15597 Region = Tree.allocate(Parent);
15598 Elts.push_back(Elt: Region);
15599 Visit(S: E);
15600 }
15601
15602 // Forget that the initializers are sequenced.
15603 Region = Parent;
15604 for (unsigned I = 0; I < Elts.size(); ++I)
15605 Tree.merge(S: Elts[I]);
15606 }
15607};
15608
15609SequenceChecker::UsageInfo::UsageInfo() = default;
15610
15611} // namespace
15612
15613void Sema::CheckUnsequencedOperations(const Expr *E) {
15614 SmallVector<const Expr *, 8> WorkList;
15615 WorkList.push_back(Elt: E);
15616 while (!WorkList.empty()) {
15617 const Expr *Item = WorkList.pop_back_val();
15618 SequenceChecker(*this, Item, WorkList);
15619 }
15620}
15621
15622void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15623 bool IsConstexpr) {
15624 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15625 IsConstexpr || isa<ConstantExpr>(Val: E));
15626 CheckImplicitConversions(E, CC: CheckLoc);
15627 if (!E->isInstantiationDependent())
15628 CheckUnsequencedOperations(E);
15629 if (!IsConstexpr && !E->isValueDependent())
15630 CheckForIntOverflow(E);
15631}
15632
15633void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15634 FieldDecl *BitField,
15635 Expr *Init) {
15636 (void) AnalyzeBitFieldAssignment(S&: *this, Bitfield: BitField, Init, InitLoc);
15637}
15638
15639static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
15640 SourceLocation Loc) {
15641 if (!PType->isVariablyModifiedType())
15642 return;
15643 if (const auto *PointerTy = dyn_cast<PointerType>(Val&: PType)) {
15644 diagnoseArrayStarInParamType(S, PType: PointerTy->getPointeeType(), Loc);
15645 return;
15646 }
15647 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(Val&: PType)) {
15648 diagnoseArrayStarInParamType(S, PType: ReferenceTy->getPointeeType(), Loc);
15649 return;
15650 }
15651 if (const auto *ParenTy = dyn_cast<ParenType>(Val&: PType)) {
15652 diagnoseArrayStarInParamType(S, PType: ParenTy->getInnerType(), Loc);
15653 return;
15654 }
15655
15656 const ArrayType *AT = S.Context.getAsArrayType(T: PType);
15657 if (!AT)
15658 return;
15659
15660 if (AT->getSizeModifier() != ArraySizeModifier::Star) {
15661 diagnoseArrayStarInParamType(S, PType: AT->getElementType(), Loc);
15662 return;
15663 }
15664
15665 S.Diag(Loc, DiagID: diag::err_array_star_in_function_definition);
15666}
15667
15668bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
15669 bool CheckParameterNames) {
15670 bool HasInvalidParm = false;
15671 for (ParmVarDecl *Param : Parameters) {
15672 assert(Param && "null in a parameter list");
15673 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15674 // function declarator that is part of a function definition of
15675 // that function shall not have incomplete type.
15676 //
15677 // C++23 [dcl.fct.def.general]/p2
15678 // The type of a parameter [...] for a function definition
15679 // shall not be a (possibly cv-qualified) class type that is incomplete
15680 // or abstract within the function body unless the function is deleted.
15681 if (!Param->isInvalidDecl() &&
15682 (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
15683 DiagID: diag::err_typecheck_decl_incomplete_type) ||
15684 RequireNonAbstractType(Loc: Param->getBeginLoc(), T: Param->getOriginalType(),
15685 DiagID: diag::err_abstract_type_in_decl,
15686 Args: AbstractParamType))) {
15687 Param->setInvalidDecl();
15688 HasInvalidParm = true;
15689 }
15690
15691 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15692 // declaration of each parameter shall include an identifier.
15693 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15694 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15695 // Diagnose this as an extension in C17 and earlier.
15696 if (!getLangOpts().C23)
15697 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
15698 }
15699
15700 // C99 6.7.5.3p12:
15701 // If the function declarator is not part of a definition of that
15702 // function, parameters may have incomplete type and may use the [*]
15703 // notation in their sequences of declarator specifiers to specify
15704 // variable length array types.
15705 QualType PType = Param->getOriginalType();
15706 // FIXME: This diagnostic should point the '[*]' if source-location
15707 // information is added for it.
15708 diagnoseArrayStarInParamType(S&: *this, PType, Loc: Param->getLocation());
15709
15710 // If the parameter is a c++ class type and it has to be destructed in the
15711 // callee function, declare the destructor so that it can be called by the
15712 // callee function. Do not perform any direct access check on the dtor here.
15713 if (!Param->isInvalidDecl()) {
15714 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15715 if (!ClassDecl->isInvalidDecl() &&
15716 !ClassDecl->hasIrrelevantDestructor() &&
15717 !ClassDecl->isDependentContext() &&
15718 ClassDecl->isParamDestroyedInCallee()) {
15719 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
15720 MarkFunctionReferenced(Loc: Param->getLocation(), Func: Destructor);
15721 DiagnoseUseOfDecl(D: Destructor, Locs: Param->getLocation());
15722 }
15723 }
15724 }
15725
15726 // Parameters with the pass_object_size attribute only need to be marked
15727 // constant at function definitions. Because we lack information about
15728 // whether we're on a declaration or definition when we're instantiating the
15729 // attribute, we need to check for constness here.
15730 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15731 if (!Param->getType().isConstQualified())
15732 Diag(Loc: Param->getLocation(), DiagID: diag::err_attribute_pointers_only)
15733 << Attr->getSpelling() << 1;
15734
15735 // Check for parameter names shadowing fields from the class.
15736 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15737 // The owning context for the parameter should be the function, but we
15738 // want to see if this function's declaration context is a record.
15739 DeclContext *DC = Param->getDeclContext();
15740 if (DC && DC->isFunctionOrMethod()) {
15741 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC->getParent()))
15742 CheckShadowInheritedFields(Loc: Param->getLocation(), FieldName: Param->getDeclName(),
15743 RD, /*DeclIsField*/ false);
15744 }
15745 }
15746
15747 if (!Param->isInvalidDecl() &&
15748 Param->getOriginalType()->isWebAssemblyTableType()) {
15749 Param->setInvalidDecl();
15750 HasInvalidParm = true;
15751 Diag(Loc: Param->getLocation(), DiagID: diag::err_wasm_table_as_function_parameter);
15752 }
15753 }
15754
15755 return HasInvalidParm;
15756}
15757
15758std::optional<std::pair<
15759 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15760 *E,
15761 ASTContext
15762 &Ctx);
15763
15764/// Compute the alignment and offset of the base class object given the
15765/// derived-to-base cast expression and the alignment and offset of the derived
15766/// class object.
15767static std::pair<CharUnits, CharUnits>
15768getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15769 CharUnits BaseAlignment, CharUnits Offset,
15770 ASTContext &Ctx) {
15771 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15772 ++PathI) {
15773 const CXXBaseSpecifier *Base = *PathI;
15774 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15775 if (Base->isVirtual()) {
15776 // The complete object may have a lower alignment than the non-virtual
15777 // alignment of the base, in which case the base may be misaligned. Choose
15778 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15779 // conservative lower bound of the complete object alignment.
15780 CharUnits NonVirtualAlignment =
15781 Ctx.getASTRecordLayout(D: BaseDecl).getNonVirtualAlignment();
15782 BaseAlignment = std::min(a: BaseAlignment, b: NonVirtualAlignment);
15783 Offset = CharUnits::Zero();
15784 } else {
15785 const ASTRecordLayout &RL =
15786 Ctx.getASTRecordLayout(D: DerivedType->getAsCXXRecordDecl());
15787 Offset += RL.getBaseClassOffset(Base: BaseDecl);
15788 }
15789 DerivedType = Base->getType();
15790 }
15791
15792 return std::make_pair(x&: BaseAlignment, y&: Offset);
15793}
15794
15795/// Compute the alignment and offset of a binary additive operator.
15796static std::optional<std::pair<CharUnits, CharUnits>>
15797getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15798 bool IsSub, ASTContext &Ctx) {
15799 QualType PointeeType = PtrE->getType()->getPointeeType();
15800
15801 if (!PointeeType->isConstantSizeType())
15802 return std::nullopt;
15803
15804 auto P = getBaseAlignmentAndOffsetFromPtr(E: PtrE, Ctx);
15805
15806 if (!P)
15807 return std::nullopt;
15808
15809 CharUnits EltSize = Ctx.getTypeSizeInChars(T: PointeeType);
15810 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15811 CharUnits Offset = EltSize * IdxRes->getExtValue();
15812 if (IsSub)
15813 Offset = -Offset;
15814 return std::make_pair(x&: P->first, y: P->second + Offset);
15815 }
15816
15817 // If the integer expression isn't a constant expression, compute the lower
15818 // bound of the alignment using the alignment and offset of the pointer
15819 // expression and the element size.
15820 return std::make_pair(
15821 x: P->first.alignmentAtOffset(offset: P->second).alignmentAtOffset(offset: EltSize),
15822 y: CharUnits::Zero());
15823}
15824
15825/// This helper function takes an lvalue expression and returns the alignment of
15826/// a VarDecl and a constant offset from the VarDecl.
15827std::optional<std::pair<
15828 CharUnits,
15829 CharUnits>> static getBaseAlignmentAndOffsetFromLValue(const Expr *E,
15830 ASTContext &Ctx) {
15831 E = E->IgnoreParens();
15832 switch (E->getStmtClass()) {
15833 default:
15834 break;
15835 case Stmt::CStyleCastExprClass:
15836 case Stmt::CXXStaticCastExprClass:
15837 case Stmt::ImplicitCastExprClass: {
15838 auto *CE = cast<CastExpr>(Val: E);
15839 const Expr *From = CE->getSubExpr();
15840 switch (CE->getCastKind()) {
15841 default:
15842 break;
15843 case CK_NoOp:
15844 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15845 case CK_UncheckedDerivedToBase:
15846 case CK_DerivedToBase: {
15847 auto P = getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15848 if (!P)
15849 break;
15850 return getDerivedToBaseAlignmentAndOffset(CE, DerivedType: From->getType(), BaseAlignment: P->first,
15851 Offset: P->second, Ctx);
15852 }
15853 }
15854 break;
15855 }
15856 case Stmt::ArraySubscriptExprClass: {
15857 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
15858 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: ASE->getBase(), IntE: ASE->getIdx(),
15859 IsSub: false, Ctx);
15860 }
15861 case Stmt::DeclRefExprClass: {
15862 if (auto *VD = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: E)->getDecl())) {
15863 // FIXME: If VD is captured by copy or is an escaping __block variable,
15864 // use the alignment of VD's type.
15865 if (!VD->getType()->isReferenceType()) {
15866 // Dependent alignment cannot be resolved -> bail out.
15867 if (VD->hasDependentAlignment())
15868 break;
15869 return std::make_pair(x: Ctx.getDeclAlign(D: VD), y: CharUnits::Zero());
15870 }
15871 if (VD->hasInit())
15872 return getBaseAlignmentAndOffsetFromLValue(E: VD->getInit(), Ctx);
15873 }
15874 break;
15875 }
15876 case Stmt::MemberExprClass: {
15877 auto *ME = cast<MemberExpr>(Val: E);
15878 auto *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
15879 if (!FD || FD->getType()->isReferenceType() ||
15880 !ASTContext::hasLayout(D: FD->getParent()))
15881 break;
15882 std::optional<std::pair<CharUnits, CharUnits>> P;
15883 if (ME->isArrow())
15884 P = getBaseAlignmentAndOffsetFromPtr(E: ME->getBase(), Ctx);
15885 else
15886 P = getBaseAlignmentAndOffsetFromLValue(E: ME->getBase(), Ctx);
15887 if (!P)
15888 break;
15889 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(D: FD->getParent());
15890 uint64_t Offset = Layout.getFieldOffset(FieldNo: FD->getFieldIndex());
15891 return std::make_pair(x&: P->first,
15892 y: P->second + CharUnits::fromQuantity(Quantity: Offset));
15893 }
15894 case Stmt::UnaryOperatorClass: {
15895 auto *UO = cast<UnaryOperator>(Val: E);
15896 switch (UO->getOpcode()) {
15897 default:
15898 break;
15899 case UO_Deref:
15900 return getBaseAlignmentAndOffsetFromPtr(E: UO->getSubExpr(), Ctx);
15901 }
15902 break;
15903 }
15904 case Stmt::BinaryOperatorClass: {
15905 auto *BO = cast<BinaryOperator>(Val: E);
15906 auto Opcode = BO->getOpcode();
15907 switch (Opcode) {
15908 default:
15909 break;
15910 case BO_Comma:
15911 return getBaseAlignmentAndOffsetFromLValue(E: BO->getRHS(), Ctx);
15912 }
15913 break;
15914 }
15915 }
15916 return std::nullopt;
15917}
15918
15919/// This helper function takes a pointer expression and returns the alignment of
15920/// a VarDecl and a constant offset from the VarDecl.
15921std::optional<std::pair<
15922 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15923 *E,
15924 ASTContext
15925 &Ctx) {
15926 E = E->IgnoreParens();
15927 switch (E->getStmtClass()) {
15928 default:
15929 break;
15930 case Stmt::CStyleCastExprClass:
15931 case Stmt::CXXStaticCastExprClass:
15932 case Stmt::ImplicitCastExprClass: {
15933 auto *CE = cast<CastExpr>(Val: E);
15934 const Expr *From = CE->getSubExpr();
15935 switch (CE->getCastKind()) {
15936 default:
15937 break;
15938 case CK_NoOp:
15939 return getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15940 case CK_ArrayToPointerDecay:
15941 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15942 case CK_UncheckedDerivedToBase:
15943 case CK_DerivedToBase: {
15944 auto P = getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15945 if (!P)
15946 break;
15947 return getDerivedToBaseAlignmentAndOffset(
15948 CE, DerivedType: From->getType()->getPointeeType(), BaseAlignment: P->first, Offset: P->second, Ctx);
15949 }
15950 }
15951 break;
15952 }
15953 case Stmt::CXXThisExprClass: {
15954 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15955 CharUnits Alignment = Ctx.getASTRecordLayout(D: RD).getNonVirtualAlignment();
15956 return std::make_pair(x&: Alignment, y: CharUnits::Zero());
15957 }
15958 case Stmt::UnaryOperatorClass: {
15959 auto *UO = cast<UnaryOperator>(Val: E);
15960 if (UO->getOpcode() == UO_AddrOf)
15961 return getBaseAlignmentAndOffsetFromLValue(E: UO->getSubExpr(), Ctx);
15962 break;
15963 }
15964 case Stmt::BinaryOperatorClass: {
15965 auto *BO = cast<BinaryOperator>(Val: E);
15966 auto Opcode = BO->getOpcode();
15967 switch (Opcode) {
15968 default:
15969 break;
15970 case BO_Add:
15971 case BO_Sub: {
15972 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15973 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15974 std::swap(a&: LHS, b&: RHS);
15975 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: LHS, IntE: RHS, IsSub: Opcode == BO_Sub,
15976 Ctx);
15977 }
15978 case BO_Comma:
15979 return getBaseAlignmentAndOffsetFromPtr(E: BO->getRHS(), Ctx);
15980 }
15981 break;
15982 }
15983 }
15984 return std::nullopt;
15985}
15986
15987static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15988 // See if we can compute the alignment of a VarDecl and an offset from it.
15989 std::optional<std::pair<CharUnits, CharUnits>> P =
15990 getBaseAlignmentAndOffsetFromPtr(E, Ctx&: S.Context);
15991
15992 if (P)
15993 return P->first.alignmentAtOffset(offset: P->second);
15994
15995 // If that failed, return the type's alignment.
15996 return S.Context.getTypeAlignInChars(T: E->getType()->getPointeeType());
15997}
15998
15999void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
16000 // This is actually a lot of work to potentially be doing on every
16001 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
16002 if (getDiagnostics().isIgnored(DiagID: diag::warn_cast_align, Loc: TRange.getBegin()))
16003 return;
16004
16005 // Ignore dependent types.
16006 if (T->isDependentType() || Op->getType()->isDependentType())
16007 return;
16008
16009 // Require that the destination be a pointer type.
16010 const PointerType *DestPtr = T->getAs<PointerType>();
16011 if (!DestPtr) return;
16012
16013 // If the destination has alignment 1, we're done.
16014 QualType DestPointee = DestPtr->getPointeeType();
16015 if (DestPointee->isIncompleteType()) return;
16016 CharUnits DestAlign = Context.getTypeAlignInChars(T: DestPointee);
16017 if (DestAlign.isOne()) return;
16018
16019 // Require that the source be a pointer type.
16020 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
16021 if (!SrcPtr) return;
16022 QualType SrcPointee = SrcPtr->getPointeeType();
16023
16024 // Explicitly allow casts from cv void*. We already implicitly
16025 // allowed casts to cv void*, since they have alignment 1.
16026 // Also allow casts involving incomplete types, which implicitly
16027 // includes 'void'.
16028 if (SrcPointee->isIncompleteType()) return;
16029
16030 CharUnits SrcAlign = getPresumedAlignmentOfPointer(E: Op, S&: *this);
16031
16032 if (SrcAlign >= DestAlign) return;
16033
16034 Diag(Loc: TRange.getBegin(), DiagID: diag::warn_cast_align)
16035 << Op->getType() << T
16036 << static_cast<unsigned>(SrcAlign.getQuantity())
16037 << static_cast<unsigned>(DestAlign.getQuantity())
16038 << TRange << Op->getSourceRange();
16039}
16040
16041void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
16042 const ArraySubscriptExpr *ASE,
16043 bool AllowOnePastEnd, bool IndexNegated) {
16044 // Already diagnosed by the constant evaluator.
16045 if (isConstantEvaluatedContext())
16046 return;
16047
16048 IndexExpr = IndexExpr->IgnoreParenImpCasts();
16049 if (IndexExpr->isValueDependent())
16050 return;
16051
16052 const Type *EffectiveType =
16053 BaseExpr->getType()->getPointeeOrArrayElementType();
16054 BaseExpr = BaseExpr->IgnoreParenCasts();
16055 const ConstantArrayType *ArrayTy =
16056 Context.getAsConstantArrayType(T: BaseExpr->getType());
16057
16058 LangOptions::StrictFlexArraysLevelKind
16059 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
16060
16061 const Type *BaseType =
16062 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
16063 bool IsUnboundedArray =
16064 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
16065 Context, StrictFlexArraysLevel,
16066 /*IgnoreTemplateOrMacroSubstitution=*/true);
16067 if (EffectiveType->isDependentType() ||
16068 (!IsUnboundedArray && BaseType->isDependentType()))
16069 return;
16070
16071 Expr::EvalResult Result;
16072 if (!IndexExpr->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects))
16073 return;
16074
16075 llvm::APSInt index = Result.Val.getInt();
16076 if (IndexNegated) {
16077 index.setIsUnsigned(false);
16078 index = -index;
16079 }
16080
16081 if (IsUnboundedArray) {
16082 if (EffectiveType->isFunctionType())
16083 return;
16084 if (index.isUnsigned() || !index.isNegative()) {
16085 const auto &ASTC = getASTContext();
16086 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
16087 AddrSpace: EffectiveType->getCanonicalTypeInternal().getAddressSpace());
16088 if (index.getBitWidth() < AddrBits)
16089 index = index.zext(width: AddrBits);
16090 std::optional<CharUnits> ElemCharUnits =
16091 ASTC.getTypeSizeInCharsIfKnown(Ty: EffectiveType);
16092 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
16093 // pointer) bounds-checking isn't meaningful.
16094 if (!ElemCharUnits || ElemCharUnits->isZero())
16095 return;
16096 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
16097 // If index has more active bits than address space, we already know
16098 // we have a bounds violation to warn about. Otherwise, compute
16099 // address of (index + 1)th element, and warn about bounds violation
16100 // only if that address exceeds address space.
16101 if (index.getActiveBits() <= AddrBits) {
16102 bool Overflow;
16103 llvm::APInt Product(index);
16104 Product += 1;
16105 Product = Product.umul_ov(RHS: ElemBytes, Overflow);
16106 if (!Overflow && Product.getActiveBits() <= AddrBits)
16107 return;
16108 }
16109
16110 // Need to compute max possible elements in address space, since that
16111 // is included in diag message.
16112 llvm::APInt MaxElems = llvm::APInt::getMaxValue(numBits: AddrBits);
16113 MaxElems = MaxElems.zext(width: std::max(a: AddrBits + 1, b: ElemBytes.getBitWidth()));
16114 MaxElems += 1;
16115 ElemBytes = ElemBytes.zextOrTrunc(width: MaxElems.getBitWidth());
16116 MaxElems = MaxElems.udiv(RHS: ElemBytes);
16117
16118 unsigned DiagID =
16119 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
16120 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
16121
16122 // Diag message shows element size in bits and in "bytes" (platform-
16123 // dependent CharUnits)
16124 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16125 PD: PDiag(DiagID) << index << AddrBits
16126 << (unsigned)ASTC.toBits(CharSize: *ElemCharUnits)
16127 << ElemBytes << MaxElems
16128 << MaxElems.getZExtValue()
16129 << IndexExpr->getSourceRange());
16130
16131 const NamedDecl *ND = nullptr;
16132 // Try harder to find a NamedDecl to point at in the note.
16133 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
16134 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16135 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
16136 ND = DRE->getDecl();
16137 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
16138 ND = ME->getMemberDecl();
16139
16140 if (ND)
16141 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
16142 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
16143 }
16144 return;
16145 }
16146
16147 if (index.isUnsigned() || !index.isNegative()) {
16148 // It is possible that the type of the base expression after
16149 // IgnoreParenCasts is incomplete, even though the type of the base
16150 // expression before IgnoreParenCasts is complete (see PR39746 for an
16151 // example). In this case we have no information about whether the array
16152 // access exceeds the array bounds. However we can still diagnose an array
16153 // access which precedes the array bounds.
16154 if (BaseType->isIncompleteType())
16155 return;
16156
16157 llvm::APInt size = ArrayTy->getSize();
16158
16159 if (BaseType != EffectiveType) {
16160 // Make sure we're comparing apples to apples when comparing index to
16161 // size.
16162 uint64_t ptrarith_typesize = Context.getTypeSize(T: EffectiveType);
16163 uint64_t array_typesize = Context.getTypeSize(T: BaseType);
16164
16165 // Handle ptrarith_typesize being zero, such as when casting to void*.
16166 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
16167 if (!ptrarith_typesize)
16168 ptrarith_typesize = Context.getCharWidth();
16169
16170 if (ptrarith_typesize != array_typesize) {
16171 // There's a cast to a different size type involved.
16172 uint64_t ratio = array_typesize / ptrarith_typesize;
16173
16174 // TODO: Be smarter about handling cases where array_typesize is not a
16175 // multiple of ptrarith_typesize.
16176 if (ptrarith_typesize * ratio == array_typesize)
16177 size *= llvm::APInt(size.getBitWidth(), ratio);
16178 }
16179 }
16180
16181 if (size.getBitWidth() > index.getBitWidth())
16182 index = index.zext(width: size.getBitWidth());
16183 else if (size.getBitWidth() < index.getBitWidth())
16184 size = size.zext(width: index.getBitWidth());
16185
16186 // For array subscripting the index must be less than size, but for pointer
16187 // arithmetic also allow the index (offset) to be equal to size since
16188 // computing the next address after the end of the array is legal and
16189 // commonly done e.g. in C++ iterators and range-based for loops.
16190 if (AllowOnePastEnd ? index.ule(RHS: size) : index.ult(RHS: size))
16191 return;
16192
16193 // Suppress the warning if the subscript expression (as identified by the
16194 // ']' location) and the index expression are both from macro expansions
16195 // within a system header.
16196 if (ASE) {
16197 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
16198 Loc: ASE->getRBracketLoc());
16199 if (SourceMgr.isInSystemHeader(Loc: RBracketLoc)) {
16200 SourceLocation IndexLoc =
16201 SourceMgr.getSpellingLoc(Loc: IndexExpr->getBeginLoc());
16202 if (SourceMgr.isWrittenInSameFile(Loc1: RBracketLoc, Loc2: IndexLoc))
16203 return;
16204 }
16205 }
16206
16207 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
16208 : diag::warn_ptr_arith_exceeds_bounds;
16209 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
16210 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
16211
16212 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16213 PD: PDiag(DiagID)
16214 << index << ArrayTy->desugar() << CastMsg
16215 << CastMsgTy << IndexExpr->getSourceRange());
16216 } else {
16217 unsigned DiagID = diag::warn_array_index_precedes_bounds;
16218 if (!ASE) {
16219 DiagID = diag::warn_ptr_arith_precedes_bounds;
16220 if (index.isNegative()) index = -index;
16221 }
16222
16223 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16224 PD: PDiag(DiagID) << index << IndexExpr->getSourceRange());
16225 }
16226
16227 const NamedDecl *ND = nullptr;
16228 // Try harder to find a NamedDecl to point at in the note.
16229 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
16230 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16231 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
16232 ND = DRE->getDecl();
16233 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
16234 ND = ME->getMemberDecl();
16235
16236 if (ND)
16237 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
16238 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
16239}
16240
16241void Sema::CheckArrayAccess(const Expr *expr) {
16242 int AllowOnePastEnd = 0;
16243 while (expr) {
16244 expr = expr->IgnoreParenImpCasts();
16245 switch (expr->getStmtClass()) {
16246 case Stmt::ArraySubscriptExprClass: {
16247 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Val: expr);
16248 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getIdx(), ASE,
16249 AllowOnePastEnd: AllowOnePastEnd > 0);
16250 expr = ASE->getBase();
16251 break;
16252 }
16253 case Stmt::MemberExprClass: {
16254 expr = cast<MemberExpr>(Val: expr)->getBase();
16255 break;
16256 }
16257 case Stmt::CXXMemberCallExprClass: {
16258 expr = cast<CXXMemberCallExpr>(Val: expr)->getImplicitObjectArgument();
16259 break;
16260 }
16261 case Stmt::ArraySectionExprClass: {
16262 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(Val: expr);
16263 // FIXME: We should probably be checking all of the elements to the
16264 // 'length' here as well.
16265 if (ASE->getLowerBound())
16266 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getLowerBound(),
16267 /*ASE=*/nullptr, AllowOnePastEnd: AllowOnePastEnd > 0);
16268 return;
16269 }
16270 case Stmt::UnaryOperatorClass: {
16271 // Only unwrap the * and & unary operators
16272 const UnaryOperator *UO = cast<UnaryOperator>(Val: expr);
16273 expr = UO->getSubExpr();
16274 switch (UO->getOpcode()) {
16275 case UO_AddrOf:
16276 AllowOnePastEnd++;
16277 break;
16278 case UO_Deref:
16279 AllowOnePastEnd--;
16280 break;
16281 default:
16282 return;
16283 }
16284 break;
16285 }
16286 case Stmt::ConditionalOperatorClass: {
16287 const ConditionalOperator *cond = cast<ConditionalOperator>(Val: expr);
16288 if (const Expr *lhs = cond->getLHS())
16289 CheckArrayAccess(expr: lhs);
16290 if (const Expr *rhs = cond->getRHS())
16291 CheckArrayAccess(expr: rhs);
16292 return;
16293 }
16294 case Stmt::CXXOperatorCallExprClass: {
16295 const auto *OCE = cast<CXXOperatorCallExpr>(Val: expr);
16296 for (const auto *Arg : OCE->arguments())
16297 CheckArrayAccess(expr: Arg);
16298 return;
16299 }
16300 default:
16301 return;
16302 }
16303 }
16304}
16305
16306static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16307 Expr *RHS, bool isProperty) {
16308 // Check if RHS is an Objective-C object literal, which also can get
16309 // immediately zapped in a weak reference. Note that we explicitly
16310 // allow ObjCStringLiterals, since those are designed to never really die.
16311 RHS = RHS->IgnoreParenImpCasts();
16312
16313 // This enum needs to match with the 'select' in
16314 // warn_objc_arc_literal_assign (off-by-1).
16315 SemaObjC::ObjCLiteralKind Kind = S.ObjC().CheckLiteralKind(FromE: RHS);
16316 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
16317 return false;
16318
16319 S.Diag(Loc, DiagID: diag::warn_arc_literal_assign)
16320 << (unsigned) Kind
16321 << (isProperty ? 0 : 1)
16322 << RHS->getSourceRange();
16323
16324 return true;
16325}
16326
16327static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16328 Qualifiers::ObjCLifetime LT,
16329 Expr *RHS, bool isProperty) {
16330 // Strip off any implicit cast added to get to the one ARC-specific.
16331 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
16332 if (cast->getCastKind() == CK_ARCConsumeObject) {
16333 S.Diag(Loc, DiagID: diag::warn_arc_retained_assign)
16334 << (LT == Qualifiers::OCL_ExplicitNone)
16335 << (isProperty ? 0 : 1)
16336 << RHS->getSourceRange();
16337 return true;
16338 }
16339 RHS = cast->getSubExpr();
16340 }
16341
16342 if (LT == Qualifiers::OCL_Weak &&
16343 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16344 return true;
16345
16346 return false;
16347}
16348
16349bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16350 QualType LHS, Expr *RHS) {
16351 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16352
16353 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16354 return false;
16355
16356 if (checkUnsafeAssignObject(S&: *this, Loc, LT, RHS, isProperty: false))
16357 return true;
16358
16359 return false;
16360}
16361
16362void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16363 Expr *LHS, Expr *RHS) {
16364 QualType LHSType;
16365 // PropertyRef on LHS type need be directly obtained from
16366 // its declaration as it has a PseudoType.
16367 ObjCPropertyRefExpr *PRE
16368 = dyn_cast<ObjCPropertyRefExpr>(Val: LHS->IgnoreParens());
16369 if (PRE && !PRE->isImplicitProperty()) {
16370 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16371 if (PD)
16372 LHSType = PD->getType();
16373 }
16374
16375 if (LHSType.isNull())
16376 LHSType = LHS->getType();
16377
16378 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16379
16380 if (LT == Qualifiers::OCL_Weak) {
16381 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc))
16382 getCurFunction()->markSafeWeakUse(E: LHS);
16383 }
16384
16385 if (checkUnsafeAssigns(Loc, LHS: LHSType, RHS))
16386 return;
16387
16388 // FIXME. Check for other life times.
16389 if (LT != Qualifiers::OCL_None)
16390 return;
16391
16392 if (PRE) {
16393 if (PRE->isImplicitProperty())
16394 return;
16395 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16396 if (!PD)
16397 return;
16398
16399 unsigned Attributes = PD->getPropertyAttributes();
16400 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16401 // when 'assign' attribute was not explicitly specified
16402 // by user, ignore it and rely on property type itself
16403 // for lifetime info.
16404 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16405 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16406 LHSType->isObjCRetainableType())
16407 return;
16408
16409 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
16410 if (cast->getCastKind() == CK_ARCConsumeObject) {
16411 Diag(Loc, DiagID: diag::warn_arc_retained_property_assign)
16412 << RHS->getSourceRange();
16413 return;
16414 }
16415 RHS = cast->getSubExpr();
16416 }
16417 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16418 if (checkUnsafeAssignObject(S&: *this, Loc, LT: Qualifiers::OCL_Weak, RHS, isProperty: true))
16419 return;
16420 }
16421 }
16422}
16423
16424//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16425
16426static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16427 SourceLocation StmtLoc,
16428 const NullStmt *Body) {
16429 // Do not warn if the body is a macro that expands to nothing, e.g:
16430 //
16431 // #define CALL(x)
16432 // if (condition)
16433 // CALL(0);
16434 if (Body->hasLeadingEmptyMacro())
16435 return false;
16436
16437 // Get line numbers of statement and body.
16438 bool StmtLineInvalid;
16439 unsigned StmtLine = SourceMgr.getPresumedLineNumber(Loc: StmtLoc,
16440 Invalid: &StmtLineInvalid);
16441 if (StmtLineInvalid)
16442 return false;
16443
16444 bool BodyLineInvalid;
16445 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Loc: Body->getSemiLoc(),
16446 Invalid: &BodyLineInvalid);
16447 if (BodyLineInvalid)
16448 return false;
16449
16450 // Warn if null statement and body are on the same line.
16451 if (StmtLine != BodyLine)
16452 return false;
16453
16454 return true;
16455}
16456
16457void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16458 const Stmt *Body,
16459 unsigned DiagID) {
16460 // Since this is a syntactic check, don't emit diagnostic for template
16461 // instantiations, this just adds noise.
16462 if (CurrentInstantiationScope)
16463 return;
16464
16465 // The body should be a null statement.
16466 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
16467 if (!NBody)
16468 return;
16469
16470 // Do the usual checks.
16471 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
16472 return;
16473
16474 Diag(Loc: NBody->getSemiLoc(), DiagID);
16475 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
16476}
16477
16478void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16479 const Stmt *PossibleBody) {
16480 assert(!CurrentInstantiationScope); // Ensured by caller
16481
16482 SourceLocation StmtLoc;
16483 const Stmt *Body;
16484 unsigned DiagID;
16485 if (const ForStmt *FS = dyn_cast<ForStmt>(Val: S)) {
16486 StmtLoc = FS->getRParenLoc();
16487 Body = FS->getBody();
16488 DiagID = diag::warn_empty_for_body;
16489 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Val: S)) {
16490 StmtLoc = WS->getRParenLoc();
16491 Body = WS->getBody();
16492 DiagID = diag::warn_empty_while_body;
16493 } else
16494 return; // Neither `for' nor `while'.
16495
16496 // The body should be a null statement.
16497 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
16498 if (!NBody)
16499 return;
16500
16501 // Skip expensive checks if diagnostic is disabled.
16502 if (Diags.isIgnored(DiagID, Loc: NBody->getSemiLoc()))
16503 return;
16504
16505 // Do the usual checks.
16506 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
16507 return;
16508
16509 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16510 // noise level low, emit diagnostics only if for/while is followed by a
16511 // CompoundStmt, e.g.:
16512 // for (int i = 0; i < n; i++);
16513 // {
16514 // a(i);
16515 // }
16516 // or if for/while is followed by a statement with more indentation
16517 // than for/while itself:
16518 // for (int i = 0; i < n; i++);
16519 // a(i);
16520 bool ProbableTypo = isa<CompoundStmt>(Val: PossibleBody);
16521 if (!ProbableTypo) {
16522 bool BodyColInvalid;
16523 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16524 Loc: PossibleBody->getBeginLoc(), Invalid: &BodyColInvalid);
16525 if (BodyColInvalid)
16526 return;
16527
16528 bool StmtColInvalid;
16529 unsigned StmtCol =
16530 SourceMgr.getPresumedColumnNumber(Loc: S->getBeginLoc(), Invalid: &StmtColInvalid);
16531 if (StmtColInvalid)
16532 return;
16533
16534 if (BodyCol > StmtCol)
16535 ProbableTypo = true;
16536 }
16537
16538 if (ProbableTypo) {
16539 Diag(Loc: NBody->getSemiLoc(), DiagID);
16540 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
16541 }
16542}
16543
16544//===--- CHECK: Warn on self move with std::move. -------------------------===//
16545
16546void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16547 SourceLocation OpLoc) {
16548 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess, Loc: OpLoc))
16549 return;
16550
16551 if (inTemplateInstantiation())
16552 return;
16553
16554 // Strip parens and casts away.
16555 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16556 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16557
16558 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16559 // which we can treat as an inlined std::move
16560 if (const auto *CE = dyn_cast<CallExpr>(Val: RHSExpr);
16561 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16562 RHSExpr = CE->getArg(Arg: 0);
16563 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(Val: RHSExpr);
16564 CXXSCE && CXXSCE->isXValue())
16565 RHSExpr = CXXSCE->getSubExpr();
16566 else
16567 return;
16568
16569 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
16570 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
16571
16572 // Two DeclRefExpr's, check that the decls are the same.
16573 if (LHSDeclRef && RHSDeclRef) {
16574 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16575 return;
16576 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16577 RHSDeclRef->getDecl()->getCanonicalDecl())
16578 return;
16579
16580 auto D = Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16581 << LHSExpr->getType() << LHSExpr->getSourceRange()
16582 << RHSExpr->getSourceRange();
16583 if (const FieldDecl *F =
16584 getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDeclRef->getDecl()))
16585 D << 1 << F
16586 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
16587 else
16588 D << 0;
16589 return;
16590 }
16591
16592 // Member variables require a different approach to check for self moves.
16593 // MemberExpr's are the same if every nested MemberExpr refers to the same
16594 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16595 // the base Expr's are CXXThisExpr's.
16596 const Expr *LHSBase = LHSExpr;
16597 const Expr *RHSBase = RHSExpr;
16598 const MemberExpr *LHSME = dyn_cast<MemberExpr>(Val: LHSExpr);
16599 const MemberExpr *RHSME = dyn_cast<MemberExpr>(Val: RHSExpr);
16600 if (!LHSME || !RHSME)
16601 return;
16602
16603 while (LHSME && RHSME) {
16604 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16605 RHSME->getMemberDecl()->getCanonicalDecl())
16606 return;
16607
16608 LHSBase = LHSME->getBase();
16609 RHSBase = RHSME->getBase();
16610 LHSME = dyn_cast<MemberExpr>(Val: LHSBase);
16611 RHSME = dyn_cast<MemberExpr>(Val: RHSBase);
16612 }
16613
16614 LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSBase);
16615 RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSBase);
16616 if (LHSDeclRef && RHSDeclRef) {
16617 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16618 return;
16619 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16620 RHSDeclRef->getDecl()->getCanonicalDecl())
16621 return;
16622
16623 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16624 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16625 << RHSExpr->getSourceRange();
16626 return;
16627 }
16628
16629 if (isa<CXXThisExpr>(Val: LHSBase) && isa<CXXThisExpr>(Val: RHSBase))
16630 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16631 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16632 << RHSExpr->getSourceRange();
16633}
16634
16635//===--- Layout compatibility ----------------------------------------------//
16636
16637static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16638
16639/// Check if two enumeration types are layout-compatible.
16640static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16641 const EnumDecl *ED2) {
16642 // C++11 [dcl.enum] p8:
16643 // Two enumeration types are layout-compatible if they have the same
16644 // underlying type.
16645 return ED1->isComplete() && ED2->isComplete() &&
16646 C.hasSameType(T1: ED1->getIntegerType(), T2: ED2->getIntegerType());
16647}
16648
16649/// Check if two fields are layout-compatible.
16650/// Can be used on union members, which are exempt from alignment requirement
16651/// of common initial sequence.
16652static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16653 const FieldDecl *Field2,
16654 bool AreUnionMembers = false) {
16655#ifndef NDEBUG
16656 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16657 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16658 assert(((Field1Parent->isStructureOrClassType() &&
16659 Field2Parent->isStructureOrClassType()) ||
16660 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16661 "Can't evaluate layout compatibility between a struct field and a "
16662 "union field.");
16663 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16664 (AreUnionMembers && Field1Parent->isUnionType())) &&
16665 "AreUnionMembers should be 'true' for union fields (only).");
16666#endif
16667
16668 if (!isLayoutCompatible(C, T1: Field1->getType(), T2: Field2->getType()))
16669 return false;
16670
16671 if (Field1->isBitField() != Field2->isBitField())
16672 return false;
16673
16674 if (Field1->isBitField()) {
16675 // Make sure that the bit-fields are the same length.
16676 unsigned Bits1 = Field1->getBitWidthValue();
16677 unsigned Bits2 = Field2->getBitWidthValue();
16678
16679 if (Bits1 != Bits2)
16680 return false;
16681 }
16682
16683 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16684 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16685 return false;
16686
16687 if (!AreUnionMembers &&
16688 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16689 return false;
16690
16691 return true;
16692}
16693
16694/// Check if two standard-layout structs are layout-compatible.
16695/// (C++11 [class.mem] p17)
16696static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16697 const RecordDecl *RD2) {
16698 // Get to the class where the fields are declared
16699 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(Val: RD1))
16700 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16701
16702 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(Val: RD2))
16703 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16704
16705 // Check the fields.
16706 return llvm::equal(LRange: RD1->fields(), RRange: RD2->fields(),
16707 P: [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16708 return isLayoutCompatible(C, Field1: F1, Field2: F2);
16709 });
16710}
16711
16712/// Check if two standard-layout unions are layout-compatible.
16713/// (C++11 [class.mem] p18)
16714static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16715 const RecordDecl *RD2) {
16716 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16717 RD2->fields());
16718
16719 for (auto *Field1 : RD1->fields()) {
16720 auto It = llvm::find_if(Range&: UnmatchedFields, P: [&](const FieldDecl *Field2) {
16721 return isLayoutCompatible(C, Field1, Field2, /*IsUnionMember=*/AreUnionMembers: true);
16722 });
16723 if (It == UnmatchedFields.end())
16724 return false;
16725 [[maybe_unused]] bool Result = UnmatchedFields.erase(Ptr: *It);
16726 assert(Result);
16727 }
16728
16729 return UnmatchedFields.empty();
16730}
16731
16732static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16733 const RecordDecl *RD2) {
16734 if (RD1->isUnion() != RD2->isUnion())
16735 return false;
16736
16737 if (RD1->isUnion())
16738 return isLayoutCompatibleUnion(C, RD1, RD2);
16739 else
16740 return isLayoutCompatibleStruct(C, RD1, RD2);
16741}
16742
16743/// Check if two types are layout-compatible in C++11 sense.
16744static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16745 if (T1.isNull() || T2.isNull())
16746 return false;
16747
16748 // C++20 [basic.types] p11:
16749 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16750 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16751 // or layout-compatible standard-layout class types (11.4).
16752 T1 = T1.getCanonicalType().getUnqualifiedType();
16753 T2 = T2.getCanonicalType().getUnqualifiedType();
16754
16755 if (C.hasSameType(T1, T2))
16756 return true;
16757
16758 const Type::TypeClass TC1 = T1->getTypeClass();
16759 const Type::TypeClass TC2 = T2->getTypeClass();
16760
16761 if (TC1 != TC2)
16762 return false;
16763
16764 if (TC1 == Type::Enum)
16765 return isLayoutCompatible(C, ED1: T1->castAsEnumDecl(), ED2: T2->castAsEnumDecl());
16766 if (TC1 == Type::Record) {
16767 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16768 return false;
16769
16770 return isLayoutCompatible(C, RD1: T1->castAsRecordDecl(),
16771 RD2: T2->castAsRecordDecl());
16772 }
16773
16774 return false;
16775}
16776
16777bool Sema::IsLayoutCompatible(QualType T1, QualType T2) const {
16778 return isLayoutCompatible(C: getASTContext(), T1, T2);
16779}
16780
16781//===-------------- Pointer interconvertibility ----------------------------//
16782
16783bool Sema::IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
16784 const TypeSourceInfo *Derived) {
16785 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16786 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16787
16788 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16789 getASTContext().hasSameType(T1: BaseT, T2: DerivedT))
16790 return true;
16791
16792 if (!IsDerivedFrom(Loc: Derived->getTypeLoc().getBeginLoc(), Derived: DerivedT, Base: BaseT))
16793 return false;
16794
16795 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16796 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16797 return true;
16798
16799 return false;
16800}
16801
16802//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16803
16804/// Given a type tag expression find the type tag itself.
16805///
16806/// \param TypeExpr Type tag expression, as it appears in user's code.
16807///
16808/// \param VD Declaration of an identifier that appears in a type tag.
16809///
16810/// \param MagicValue Type tag magic value.
16811///
16812/// \param isConstantEvaluated whether the evalaution should be performed in
16813
16814/// constant context.
16815static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16816 const ValueDecl **VD, uint64_t *MagicValue,
16817 bool isConstantEvaluated) {
16818 while(true) {
16819 if (!TypeExpr)
16820 return false;
16821
16822 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16823
16824 switch (TypeExpr->getStmtClass()) {
16825 case Stmt::UnaryOperatorClass: {
16826 const UnaryOperator *UO = cast<UnaryOperator>(Val: TypeExpr);
16827 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16828 TypeExpr = UO->getSubExpr();
16829 continue;
16830 }
16831 return false;
16832 }
16833
16834 case Stmt::DeclRefExprClass: {
16835 const DeclRefExpr *DRE = cast<DeclRefExpr>(Val: TypeExpr);
16836 *VD = DRE->getDecl();
16837 return true;
16838 }
16839
16840 case Stmt::IntegerLiteralClass: {
16841 const IntegerLiteral *IL = cast<IntegerLiteral>(Val: TypeExpr);
16842 llvm::APInt MagicValueAPInt = IL->getValue();
16843 if (MagicValueAPInt.getActiveBits() <= 64) {
16844 *MagicValue = MagicValueAPInt.getZExtValue();
16845 return true;
16846 } else
16847 return false;
16848 }
16849
16850 case Stmt::BinaryConditionalOperatorClass:
16851 case Stmt::ConditionalOperatorClass: {
16852 const AbstractConditionalOperator *ACO =
16853 cast<AbstractConditionalOperator>(Val: TypeExpr);
16854 bool Result;
16855 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16856 InConstantContext: isConstantEvaluated)) {
16857 if (Result)
16858 TypeExpr = ACO->getTrueExpr();
16859 else
16860 TypeExpr = ACO->getFalseExpr();
16861 continue;
16862 }
16863 return false;
16864 }
16865
16866 case Stmt::BinaryOperatorClass: {
16867 const BinaryOperator *BO = cast<BinaryOperator>(Val: TypeExpr);
16868 if (BO->getOpcode() == BO_Comma) {
16869 TypeExpr = BO->getRHS();
16870 continue;
16871 }
16872 return false;
16873 }
16874
16875 default:
16876 return false;
16877 }
16878 }
16879}
16880
16881/// Retrieve the C type corresponding to type tag TypeExpr.
16882///
16883/// \param TypeExpr Expression that specifies a type tag.
16884///
16885/// \param MagicValues Registered magic values.
16886///
16887/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16888/// kind.
16889///
16890/// \param TypeInfo Information about the corresponding C type.
16891///
16892/// \param isConstantEvaluated whether the evalaution should be performed in
16893/// constant context.
16894///
16895/// \returns true if the corresponding C type was found.
16896static bool GetMatchingCType(
16897 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16898 const ASTContext &Ctx,
16899 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16900 *MagicValues,
16901 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16902 bool isConstantEvaluated) {
16903 FoundWrongKind = false;
16904
16905 // Variable declaration that has type_tag_for_datatype attribute.
16906 const ValueDecl *VD = nullptr;
16907
16908 uint64_t MagicValue;
16909
16910 if (!FindTypeTagExpr(TypeExpr, Ctx, VD: &VD, MagicValue: &MagicValue, isConstantEvaluated))
16911 return false;
16912
16913 if (VD) {
16914 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16915 if (I->getArgumentKind() != ArgumentKind) {
16916 FoundWrongKind = true;
16917 return false;
16918 }
16919 TypeInfo.Type = I->getMatchingCType();
16920 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16921 TypeInfo.MustBeNull = I->getMustBeNull();
16922 return true;
16923 }
16924 return false;
16925 }
16926
16927 if (!MagicValues)
16928 return false;
16929
16930 llvm::DenseMap<Sema::TypeTagMagicValue,
16931 Sema::TypeTagData>::const_iterator I =
16932 MagicValues->find(Val: std::make_pair(x&: ArgumentKind, y&: MagicValue));
16933 if (I == MagicValues->end())
16934 return false;
16935
16936 TypeInfo = I->second;
16937 return true;
16938}
16939
16940void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16941 uint64_t MagicValue, QualType Type,
16942 bool LayoutCompatible,
16943 bool MustBeNull) {
16944 if (!TypeTagForDatatypeMagicValues)
16945 TypeTagForDatatypeMagicValues.reset(
16946 p: new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16947
16948 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16949 (*TypeTagForDatatypeMagicValues)[Magic] =
16950 TypeTagData(Type, LayoutCompatible, MustBeNull);
16951}
16952
16953static bool IsSameCharType(QualType T1, QualType T2) {
16954 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16955 if (!BT1)
16956 return false;
16957
16958 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16959 if (!BT2)
16960 return false;
16961
16962 BuiltinType::Kind T1Kind = BT1->getKind();
16963 BuiltinType::Kind T2Kind = BT2->getKind();
16964
16965 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16966 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16967 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16968 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16969}
16970
16971void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16972 const ArrayRef<const Expr *> ExprArgs,
16973 SourceLocation CallSiteLoc) {
16974 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16975 bool IsPointerAttr = Attr->getIsPointer();
16976
16977 // Retrieve the argument representing the 'type_tag'.
16978 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16979 if (TypeTagIdxAST >= ExprArgs.size()) {
16980 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
16981 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16982 return;
16983 }
16984 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16985 bool FoundWrongKind;
16986 TypeTagData TypeInfo;
16987 if (!GetMatchingCType(ArgumentKind, TypeExpr: TypeTagExpr, Ctx: Context,
16988 MagicValues: TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16989 TypeInfo, isConstantEvaluated: isConstantEvaluatedContext())) {
16990 if (FoundWrongKind)
16991 Diag(Loc: TypeTagExpr->getExprLoc(),
16992 DiagID: diag::warn_type_tag_for_datatype_wrong_kind)
16993 << TypeTagExpr->getSourceRange();
16994 return;
16995 }
16996
16997 // Retrieve the argument representing the 'arg_idx'.
16998 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16999 if (ArgumentIdxAST >= ExprArgs.size()) {
17000 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
17001 << 1 << Attr->getArgumentIdx().getSourceIndex();
17002 return;
17003 }
17004 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
17005 if (IsPointerAttr) {
17006 // Skip implicit cast of pointer to `void *' (as a function argument).
17007 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgumentExpr))
17008 if (ICE->getType()->isVoidPointerType() &&
17009 ICE->getCastKind() == CK_BitCast)
17010 ArgumentExpr = ICE->getSubExpr();
17011 }
17012 QualType ArgumentType = ArgumentExpr->getType();
17013
17014 // Passing a `void*' pointer shouldn't trigger a warning.
17015 if (IsPointerAttr && ArgumentType->isVoidPointerType())
17016 return;
17017
17018 if (TypeInfo.MustBeNull) {
17019 // Type tag with matching void type requires a null pointer.
17020 if (!ArgumentExpr->isNullPointerConstant(Ctx&: Context,
17021 NPC: Expr::NPC_ValueDependentIsNotNull)) {
17022 Diag(Loc: ArgumentExpr->getExprLoc(),
17023 DiagID: diag::warn_type_safety_null_pointer_required)
17024 << ArgumentKind->getName()
17025 << ArgumentExpr->getSourceRange()
17026 << TypeTagExpr->getSourceRange();
17027 }
17028 return;
17029 }
17030
17031 QualType RequiredType = TypeInfo.Type;
17032 if (IsPointerAttr)
17033 RequiredType = Context.getPointerType(T: RequiredType);
17034
17035 bool mismatch = false;
17036 if (!TypeInfo.LayoutCompatible) {
17037 mismatch = !Context.hasSameType(T1: ArgumentType, T2: RequiredType);
17038
17039 // C++11 [basic.fundamental] p1:
17040 // Plain char, signed char, and unsigned char are three distinct types.
17041 //
17042 // But we treat plain `char' as equivalent to `signed char' or `unsigned
17043 // char' depending on the current char signedness mode.
17044 if (mismatch)
17045 if ((IsPointerAttr && IsSameCharType(T1: ArgumentType->getPointeeType(),
17046 T2: RequiredType->getPointeeType())) ||
17047 (!IsPointerAttr && IsSameCharType(T1: ArgumentType, T2: RequiredType)))
17048 mismatch = false;
17049 } else
17050 if (IsPointerAttr)
17051 mismatch = !isLayoutCompatible(C: Context,
17052 T1: ArgumentType->getPointeeType(),
17053 T2: RequiredType->getPointeeType());
17054 else
17055 mismatch = !isLayoutCompatible(C: Context, T1: ArgumentType, T2: RequiredType);
17056
17057 if (mismatch)
17058 Diag(Loc: ArgumentExpr->getExprLoc(), DiagID: diag::warn_type_safety_type_mismatch)
17059 << ArgumentType << ArgumentKind
17060 << TypeInfo.LayoutCompatible << RequiredType
17061 << ArgumentExpr->getSourceRange()
17062 << TypeTagExpr->getSourceRange();
17063}
17064
17065void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
17066 CharUnits Alignment) {
17067 currentEvaluationContext().MisalignedMembers.emplace_back(Args&: E, Args&: RD, Args&: MD,
17068 Args&: Alignment);
17069}
17070
17071void Sema::DiagnoseMisalignedMembers() {
17072 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
17073 const NamedDecl *ND = m.RD;
17074 if (ND->getName().empty()) {
17075 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
17076 ND = TD;
17077 }
17078 Diag(Loc: m.E->getBeginLoc(), DiagID: diag::warn_taking_address_of_packed_member)
17079 << m.MD << ND << m.E->getSourceRange();
17080 }
17081 currentEvaluationContext().MisalignedMembers.clear();
17082}
17083
17084void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
17085 E = E->IgnoreParens();
17086 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
17087 return;
17088 if (isa<UnaryOperator>(Val: E) &&
17089 cast<UnaryOperator>(Val: E)->getOpcode() == UO_AddrOf) {
17090 auto *Op = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
17091 if (isa<MemberExpr>(Val: Op)) {
17092 auto &MisalignedMembersForExpr =
17093 currentEvaluationContext().MisalignedMembers;
17094 auto *MA = llvm::find(Range&: MisalignedMembersForExpr, Val: MisalignedMember(Op));
17095 if (MA != MisalignedMembersForExpr.end() &&
17096 (T->isDependentType() || T->isIntegerType() ||
17097 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
17098 Context.getTypeAlignInChars(
17099 T: T->getPointeeType()) <= MA->Alignment))))
17100 MisalignedMembersForExpr.erase(CI: MA);
17101 }
17102 }
17103}
17104
17105void Sema::RefersToMemberWithReducedAlignment(
17106 Expr *E,
17107 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
17108 Action) {
17109 const auto *ME = dyn_cast<MemberExpr>(Val: E);
17110 if (!ME)
17111 return;
17112
17113 // No need to check expressions with an __unaligned-qualified type.
17114 if (E->getType().getQualifiers().hasUnaligned())
17115 return;
17116
17117 // For a chain of MemberExpr like "a.b.c.d" this list
17118 // will keep FieldDecl's like [d, c, b].
17119 SmallVector<FieldDecl *, 4> ReverseMemberChain;
17120 const MemberExpr *TopME = nullptr;
17121 bool AnyIsPacked = false;
17122 do {
17123 QualType BaseType = ME->getBase()->getType();
17124 if (BaseType->isDependentType())
17125 return;
17126 if (ME->isArrow())
17127 BaseType = BaseType->getPointeeType();
17128 auto *RD = BaseType->castAsRecordDecl();
17129 if (RD->isInvalidDecl())
17130 return;
17131
17132 ValueDecl *MD = ME->getMemberDecl();
17133 auto *FD = dyn_cast<FieldDecl>(Val: MD);
17134 // We do not care about non-data members.
17135 if (!FD || FD->isInvalidDecl())
17136 return;
17137
17138 AnyIsPacked =
17139 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17140 ReverseMemberChain.push_back(Elt: FD);
17141
17142 TopME = ME;
17143 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParens());
17144 } while (ME);
17145 assert(TopME && "We did not compute a topmost MemberExpr!");
17146
17147 // Not the scope of this diagnostic.
17148 if (!AnyIsPacked)
17149 return;
17150
17151 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17152 const auto *DRE = dyn_cast<DeclRefExpr>(Val: TopBase);
17153 // TODO: The innermost base of the member expression may be too complicated.
17154 // For now, just disregard these cases. This is left for future
17155 // improvement.
17156 if (!DRE && !isa<CXXThisExpr>(Val: TopBase))
17157 return;
17158
17159 // Alignment expected by the whole expression.
17160 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(T: E->getType());
17161
17162 // No need to do anything else with this case.
17163 if (ExpectedAlignment.isOne())
17164 return;
17165
17166 // Synthesize offset of the whole access.
17167 CharUnits Offset;
17168 for (const FieldDecl *FD : llvm::reverse(C&: ReverseMemberChain))
17169 Offset += Context.toCharUnitsFromBits(BitSize: Context.getFieldOffset(FD));
17170
17171 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17172 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17173 T: Context.getCanonicalTagType(TD: ReverseMemberChain.back()->getParent()));
17174
17175 // The base expression of the innermost MemberExpr may give
17176 // stronger guarantees than the class containing the member.
17177 if (DRE && !TopME->isArrow()) {
17178 const ValueDecl *VD = DRE->getDecl();
17179 if (!VD->getType()->isReferenceType())
17180 CompleteObjectAlignment =
17181 std::max(a: CompleteObjectAlignment, b: Context.getDeclAlign(D: VD));
17182 }
17183
17184 // Check if the synthesized offset fulfills the alignment.
17185 if (!Offset.isMultipleOf(N: ExpectedAlignment) ||
17186 // It may fulfill the offset it but the effective alignment may still be
17187 // lower than the expected expression alignment.
17188 CompleteObjectAlignment < ExpectedAlignment) {
17189 // If this happens, we want to determine a sensible culprit of this.
17190 // Intuitively, watching the chain of member expressions from right to
17191 // left, we start with the required alignment (as required by the field
17192 // type) but some packed attribute in that chain has reduced the alignment.
17193 // It may happen that another packed structure increases it again. But if
17194 // we are here such increase has not been enough. So pointing the first
17195 // FieldDecl that either is packed or else its RecordDecl is,
17196 // seems reasonable.
17197 FieldDecl *FD = nullptr;
17198 CharUnits Alignment;
17199 for (FieldDecl *FDI : ReverseMemberChain) {
17200 if (FDI->hasAttr<PackedAttr>() ||
17201 FDI->getParent()->hasAttr<PackedAttr>()) {
17202 FD = FDI;
17203 Alignment = std::min(a: Context.getTypeAlignInChars(T: FD->getType()),
17204 b: Context.getTypeAlignInChars(
17205 T: Context.getCanonicalTagType(TD: FD->getParent())));
17206 break;
17207 }
17208 }
17209 assert(FD && "We did not find a packed FieldDecl!");
17210 Action(E, FD->getParent(), FD, Alignment);
17211 }
17212}
17213
17214void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17215 using namespace std::placeholders;
17216
17217 RefersToMemberWithReducedAlignment(
17218 E: rhs, Action: std::bind(f: &Sema::AddPotentialMisalignedMembers, args: std::ref(t&: *this), args: _1,
17219 args: _2, args: _3, args: _4));
17220}
17221
17222bool Sema::PrepareBuiltinElementwiseMathOneArgCall(
17223 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17224 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17225 return true;
17226
17227 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
17228 if (A.isInvalid())
17229 return true;
17230
17231 TheCall->setArg(Arg: 0, ArgExpr: A.get());
17232 QualType TyA = A.get()->getType();
17233
17234 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
17235 ArgTyRestr, ArgOrdinal: 1))
17236 return true;
17237
17238 TheCall->setType(TyA);
17239 return false;
17240}
17241
17242bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
17243 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17244 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
17245 TheCall->setType(*Res);
17246 return false;
17247 }
17248 return true;
17249}
17250
17251bool Sema::BuiltinVectorToScalarMath(CallExpr *TheCall) {
17252 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
17253 if (!Res)
17254 return true;
17255
17256 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
17257 TheCall->setType(VecTy0->getElementType());
17258 else
17259 TheCall->setType(*Res);
17260
17261 return false;
17262}
17263
17264static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS,
17265 SourceLocation Loc) {
17266 QualType L = LHS->getEnumCoercedType(Ctx: S.Context),
17267 R = RHS->getEnumCoercedType(Ctx: S.Context);
17268 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
17269 !S.Context.hasSameUnqualifiedType(T1: L, T2: R)) {
17270 return S.Diag(Loc, DiagID: diag::err_conv_mixed_enum_types)
17271 << LHS->getSourceRange() << RHS->getSourceRange()
17272 << /*Arithmetic Between*/ 0 << L << R;
17273 }
17274 return false;
17275}
17276
17277/// Check if all arguments have the same type. If the types don't match, emit an
17278/// error message and return true. Otherwise return false.
17279///
17280/// For scalars we directly compare their unqualified types. But even if we
17281/// compare unqualified vector types, a difference in qualifiers in the element
17282/// types can make the vector types be considered not equal. For example,
17283/// vector of 4 'const float' values vs vector of 4 'float' values.
17284/// So we compare unqualified types of their elements and number of elements.
17285static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef,
17286 ArrayRef<Expr *> Args) {
17287 assert(!Args.empty() && "Should have at least one argument.");
17288
17289 Expr *Arg0 = Args.front();
17290 QualType Ty0 = Arg0->getType();
17291
17292 auto EmitError = [&](Expr *ArgI) {
17293 SemaRef.Diag(Loc: Arg0->getBeginLoc(),
17294 DiagID: diag::err_typecheck_call_different_arg_types)
17295 << Arg0->getType() << ArgI->getType();
17296 };
17297
17298 // Compare scalar types.
17299 if (!Ty0->isVectorType()) {
17300 for (Expr *ArgI : Args.drop_front())
17301 if (!SemaRef.Context.hasSameUnqualifiedType(T1: Ty0, T2: ArgI->getType())) {
17302 EmitError(ArgI);
17303 return true;
17304 }
17305
17306 return false;
17307 }
17308
17309 // Compare vector types.
17310 const auto *Vec0 = Ty0->castAs<VectorType>();
17311 for (Expr *ArgI : Args.drop_front()) {
17312 const auto *VecI = ArgI->getType()->getAs<VectorType>();
17313 if (!VecI ||
17314 !SemaRef.Context.hasSameUnqualifiedType(T1: Vec0->getElementType(),
17315 T2: VecI->getElementType()) ||
17316 Vec0->getNumElements() != VecI->getNumElements()) {
17317 EmitError(ArgI);
17318 return true;
17319 }
17320 }
17321
17322 return false;
17323}
17324
17325std::optional<QualType>
17326Sema::BuiltinVectorMath(CallExpr *TheCall,
17327 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17328 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
17329 return std::nullopt;
17330
17331 if (checkBuiltinVectorMathMixedEnums(
17332 S&: *this, LHS: TheCall->getArg(Arg: 0), RHS: TheCall->getArg(Arg: 1), Loc: TheCall->getExprLoc()))
17333 return std::nullopt;
17334
17335 Expr *Args[2];
17336 for (int I = 0; I < 2; ++I) {
17337 ExprResult Converted =
17338 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
17339 if (Converted.isInvalid())
17340 return std::nullopt;
17341 Args[I] = Converted.get();
17342 }
17343
17344 SourceLocation LocA = Args[0]->getBeginLoc();
17345 QualType TyA = Args[0]->getType();
17346
17347 if (checkMathBuiltinElementType(S&: *this, Loc: LocA, ArgTy: TyA, ArgTyRestr, ArgOrdinal: 1))
17348 return std::nullopt;
17349
17350 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
17351 return std::nullopt;
17352
17353 TheCall->setArg(Arg: 0, ArgExpr: Args[0]);
17354 TheCall->setArg(Arg: 1, ArgExpr: Args[1]);
17355 return TyA;
17356}
17357
17358bool Sema::BuiltinElementwiseTernaryMath(
17359 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17360 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
17361 return true;
17362
17363 SourceLocation Loc = TheCall->getExprLoc();
17364 if (checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 0),
17365 RHS: TheCall->getArg(Arg: 1), Loc) ||
17366 checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 1),
17367 RHS: TheCall->getArg(Arg: 2), Loc))
17368 return true;
17369
17370 Expr *Args[3];
17371 for (int I = 0; I < 3; ++I) {
17372 ExprResult Converted =
17373 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
17374 if (Converted.isInvalid())
17375 return true;
17376 Args[I] = Converted.get();
17377 }
17378
17379 int ArgOrdinal = 1;
17380 for (Expr *Arg : Args) {
17381 if (checkMathBuiltinElementType(S&: *this, Loc: Arg->getBeginLoc(), ArgTy: Arg->getType(),
17382 ArgTyRestr, ArgOrdinal: ArgOrdinal++))
17383 return true;
17384 }
17385
17386 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
17387 return true;
17388
17389 for (int I = 0; I < 3; ++I)
17390 TheCall->setArg(Arg: I, ArgExpr: Args[I]);
17391
17392 TheCall->setType(Args[0]->getType());
17393 return false;
17394}
17395
17396bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17397 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17398 return true;
17399
17400 ExprResult A = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
17401 if (A.isInvalid())
17402 return true;
17403
17404 TheCall->setArg(Arg: 0, ArgExpr: A.get());
17405 return false;
17406}
17407
17408bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17409 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17410 return true;
17411
17412 ExprResult Arg = TheCall->getArg(Arg: 0);
17413 QualType TyArg = Arg.get()->getType();
17414
17415 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17416 return Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
17417 DiagID: diag::err_builtin_invalid_arg_type)
17418 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17419
17420 TheCall->setType(TyArg);
17421 return false;
17422}
17423
17424ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17425 ExprResult CallResult) {
17426 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17427 return ExprError();
17428
17429 ExprResult MatrixArg = DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
17430 if (MatrixArg.isInvalid())
17431 return MatrixArg;
17432 Expr *Matrix = MatrixArg.get();
17433
17434 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17435 if (!MType) {
17436 Diag(Loc: Matrix->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17437 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17438 << Matrix->getType();
17439 return ExprError();
17440 }
17441
17442 // Create returned matrix type by swapping rows and columns of the argument
17443 // matrix type.
17444 QualType ResultType = Context.getConstantMatrixType(
17445 ElementType: MType->getElementType(), NumRows: MType->getNumColumns(), NumColumns: MType->getNumRows());
17446
17447 // Change the return type to the type of the returned matrix.
17448 TheCall->setType(ResultType);
17449
17450 // Update call argument to use the possibly converted matrix argument.
17451 TheCall->setArg(Arg: 0, ArgExpr: Matrix);
17452 return CallResult;
17453}
17454
17455// Get and verify the matrix dimensions.
17456static std::optional<unsigned>
17457getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17458 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(Ctx: S.Context);
17459 if (!Value) {
17460 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_scalar_unsigned_arg)
17461 << Name;
17462 return {};
17463 }
17464 uint64_t Dim = Value->getZExtValue();
17465 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17466 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_invalid_dimension)
17467 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17468 return {};
17469 }
17470 return Dim;
17471}
17472
17473ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17474 ExprResult CallResult) {
17475 if (!getLangOpts().MatrixTypes) {
17476 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
17477 return ExprError();
17478 }
17479
17480 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17481 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
17482 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
17483 << /*column*/ 1 << /*load*/ 0;
17484 return ExprError();
17485 }
17486
17487 if (checkArgCount(Call: TheCall, DesiredArgCount: 4))
17488 return ExprError();
17489
17490 unsigned PtrArgIdx = 0;
17491 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
17492 Expr *RowsExpr = TheCall->getArg(Arg: 1);
17493 Expr *ColumnsExpr = TheCall->getArg(Arg: 2);
17494 Expr *StrideExpr = TheCall->getArg(Arg: 3);
17495
17496 bool ArgError = false;
17497
17498 // Check pointer argument.
17499 {
17500 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
17501 if (PtrConv.isInvalid())
17502 return PtrConv;
17503 PtrExpr = PtrConv.get();
17504 TheCall->setArg(Arg: 0, ArgExpr: PtrExpr);
17505 if (PtrExpr->isTypeDependent()) {
17506 TheCall->setType(Context.DependentTy);
17507 return TheCall;
17508 }
17509 }
17510
17511 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17512 QualType ElementTy;
17513 if (!PtrTy) {
17514 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17515 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17516 << PtrExpr->getType();
17517 ArgError = true;
17518 } else {
17519 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17520
17521 if (!ConstantMatrixType::isValidElementType(T: ElementTy, LangOpts: getLangOpts())) {
17522 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17523 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17524 << /* no fp */ 0 << PtrExpr->getType();
17525 ArgError = true;
17526 }
17527 }
17528
17529 // Apply default Lvalue conversions and convert the expression to size_t.
17530 auto ApplyArgumentConversions = [this](Expr *E) {
17531 ExprResult Conv = DefaultLvalueConversion(E);
17532 if (Conv.isInvalid())
17533 return Conv;
17534
17535 return tryConvertExprToType(E: Conv.get(), Ty: Context.getSizeType());
17536 };
17537
17538 // Apply conversion to row and column expressions.
17539 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17540 if (!RowsConv.isInvalid()) {
17541 RowsExpr = RowsConv.get();
17542 TheCall->setArg(Arg: 1, ArgExpr: RowsExpr);
17543 } else
17544 RowsExpr = nullptr;
17545
17546 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17547 if (!ColumnsConv.isInvalid()) {
17548 ColumnsExpr = ColumnsConv.get();
17549 TheCall->setArg(Arg: 2, ArgExpr: ColumnsExpr);
17550 } else
17551 ColumnsExpr = nullptr;
17552
17553 // If any part of the result matrix type is still pending, just use
17554 // Context.DependentTy, until all parts are resolved.
17555 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17556 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17557 TheCall->setType(Context.DependentTy);
17558 return CallResult;
17559 }
17560
17561 // Check row and column dimensions.
17562 std::optional<unsigned> MaybeRows;
17563 if (RowsExpr)
17564 MaybeRows = getAndVerifyMatrixDimension(Expr: RowsExpr, Name: "row", S&: *this);
17565
17566 std::optional<unsigned> MaybeColumns;
17567 if (ColumnsExpr)
17568 MaybeColumns = getAndVerifyMatrixDimension(Expr: ColumnsExpr, Name: "column", S&: *this);
17569
17570 // Check stride argument.
17571 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17572 if (StrideConv.isInvalid())
17573 return ExprError();
17574 StrideExpr = StrideConv.get();
17575 TheCall->setArg(Arg: 3, ArgExpr: StrideExpr);
17576
17577 if (MaybeRows) {
17578 if (std::optional<llvm::APSInt> Value =
17579 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
17580 uint64_t Stride = Value->getZExtValue();
17581 if (Stride < *MaybeRows) {
17582 Diag(Loc: StrideExpr->getBeginLoc(),
17583 DiagID: diag::err_builtin_matrix_stride_too_small);
17584 ArgError = true;
17585 }
17586 }
17587 }
17588
17589 if (ArgError || !MaybeRows || !MaybeColumns)
17590 return ExprError();
17591
17592 TheCall->setType(
17593 Context.getConstantMatrixType(ElementType: ElementTy, NumRows: *MaybeRows, NumColumns: *MaybeColumns));
17594 return CallResult;
17595}
17596
17597ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17598 ExprResult CallResult) {
17599 if (!getLangOpts().MatrixTypes) {
17600 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
17601 return ExprError();
17602 }
17603
17604 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17605 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
17606 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
17607 << /*column*/ 1 << /*store*/ 1;
17608 return ExprError();
17609 }
17610
17611 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
17612 return ExprError();
17613
17614 unsigned PtrArgIdx = 1;
17615 Expr *MatrixExpr = TheCall->getArg(Arg: 0);
17616 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
17617 Expr *StrideExpr = TheCall->getArg(Arg: 2);
17618
17619 bool ArgError = false;
17620
17621 {
17622 ExprResult MatrixConv = DefaultLvalueConversion(E: MatrixExpr);
17623 if (MatrixConv.isInvalid())
17624 return MatrixConv;
17625 MatrixExpr = MatrixConv.get();
17626 TheCall->setArg(Arg: 0, ArgExpr: MatrixExpr);
17627 }
17628 if (MatrixExpr->isTypeDependent()) {
17629 TheCall->setType(Context.DependentTy);
17630 return TheCall;
17631 }
17632
17633 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17634 if (!MatrixTy) {
17635 Diag(Loc: MatrixExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17636 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17637 ArgError = true;
17638 }
17639
17640 {
17641 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
17642 if (PtrConv.isInvalid())
17643 return PtrConv;
17644 PtrExpr = PtrConv.get();
17645 TheCall->setArg(Arg: 1, ArgExpr: PtrExpr);
17646 if (PtrExpr->isTypeDependent()) {
17647 TheCall->setType(Context.DependentTy);
17648 return TheCall;
17649 }
17650 }
17651
17652 // Check pointer argument.
17653 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17654 if (!PtrTy) {
17655 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17656 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17657 << PtrExpr->getType();
17658 ArgError = true;
17659 } else {
17660 QualType ElementTy = PtrTy->getPointeeType();
17661 if (ElementTy.isConstQualified()) {
17662 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_matrix_store_to_const);
17663 ArgError = true;
17664 }
17665 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17666 if (MatrixTy &&
17667 !Context.hasSameType(T1: ElementTy, T2: MatrixTy->getElementType())) {
17668 Diag(Loc: PtrExpr->getBeginLoc(),
17669 DiagID: diag::err_builtin_matrix_pointer_arg_mismatch)
17670 << ElementTy << MatrixTy->getElementType();
17671 ArgError = true;
17672 }
17673 }
17674
17675 // Apply default Lvalue conversions and convert the stride expression to
17676 // size_t.
17677 {
17678 ExprResult StrideConv = DefaultLvalueConversion(E: StrideExpr);
17679 if (StrideConv.isInvalid())
17680 return StrideConv;
17681
17682 StrideConv = tryConvertExprToType(E: StrideConv.get(), Ty: Context.getSizeType());
17683 if (StrideConv.isInvalid())
17684 return StrideConv;
17685 StrideExpr = StrideConv.get();
17686 TheCall->setArg(Arg: 2, ArgExpr: StrideExpr);
17687 }
17688
17689 // Check stride argument.
17690 if (MatrixTy) {
17691 if (std::optional<llvm::APSInt> Value =
17692 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
17693 uint64_t Stride = Value->getZExtValue();
17694 if (Stride < MatrixTy->getNumRows()) {
17695 Diag(Loc: StrideExpr->getBeginLoc(),
17696 DiagID: diag::err_builtin_matrix_stride_too_small);
17697 ArgError = true;
17698 }
17699 }
17700 }
17701
17702 if (ArgError)
17703 return ExprError();
17704
17705 return CallResult;
17706}
17707
17708void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
17709 const NamedDecl *Callee) {
17710 // This warning does not make sense in code that has no runtime behavior.
17711 if (isUnevaluatedContext())
17712 return;
17713
17714 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17715
17716 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17717 return;
17718
17719 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17720 // all TCBs the callee is a part of.
17721 llvm::StringSet<> CalleeTCBs;
17722 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17723 CalleeTCBs.insert(key: A->getTCBName());
17724 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17725 CalleeTCBs.insert(key: A->getTCBName());
17726
17727 // Go through the TCBs the caller is a part of and emit warnings if Caller
17728 // is in a TCB that the Callee is not.
17729 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17730 StringRef CallerTCB = A->getTCBName();
17731 if (CalleeTCBs.count(Key: CallerTCB) == 0) {
17732 this->Diag(Loc: CallExprLoc, DiagID: diag::warn_tcb_enforcement_violation)
17733 << Callee << CallerTCB;
17734 }
17735 }
17736}
17737