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/Diagnostic.h"
45#include "clang/Basic/DiagnosticSema.h"
46#include "clang/Basic/IdentifierTable.h"
47#include "clang/Basic/LLVM.h"
48#include "clang/Basic/LangOptions.h"
49#include "clang/Basic/OpenCLOptions.h"
50#include "clang/Basic/OperatorKinds.h"
51#include "clang/Basic/PartialDiagnostic.h"
52#include "clang/Basic/SourceLocation.h"
53#include "clang/Basic/SourceManager.h"
54#include "clang/Basic/Specifiers.h"
55#include "clang/Basic/SyncScope.h"
56#include "clang/Basic/TargetInfo.h"
57#include "clang/Basic/TypeTraits.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/SemaSystemZ.h"
80#include "clang/Sema/SemaWasm.h"
81#include "clang/Sema/SemaX86.h"
82#include "llvm/ADT/APFloat.h"
83#include "llvm/ADT/APInt.h"
84#include "llvm/ADT/APSInt.h"
85#include "llvm/ADT/ArrayRef.h"
86#include "llvm/ADT/DenseMap.h"
87#include "llvm/ADT/FoldingSet.h"
88#include "llvm/ADT/STLExtras.h"
89#include "llvm/ADT/STLForwardCompat.h"
90#include "llvm/ADT/SmallBitVector.h"
91#include "llvm/ADT/SmallPtrSet.h"
92#include "llvm/ADT/SmallString.h"
93#include "llvm/ADT/SmallVector.h"
94#include "llvm/ADT/StringExtras.h"
95#include "llvm/ADT/StringRef.h"
96#include "llvm/ADT/StringSet.h"
97#include "llvm/ADT/StringSwitch.h"
98#include "llvm/Support/AtomicOrdering.h"
99#include "llvm/Support/Compiler.h"
100#include "llvm/Support/ConvertUTF.h"
101#include "llvm/Support/ErrorHandling.h"
102#include "llvm/Support/Format.h"
103#include "llvm/Support/Locale.h"
104#include "llvm/Support/MathExtras.h"
105#include "llvm/Support/SaveAndRestore.h"
106#include "llvm/Support/raw_ostream.h"
107#include "llvm/TargetParser/RISCVTargetParser.h"
108#include "llvm/TargetParser/Triple.h"
109#include <algorithm>
110#include <cassert>
111#include <cctype>
112#include <cstddef>
113#include <cstdint>
114#include <functional>
115#include <limits>
116#include <optional>
117#include <string>
118#include <tuple>
119#include <utility>
120
121using namespace clang;
122using namespace sema;
123
124SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
125 unsigned ByteNo) const {
126 return SL->getLocationOfByte(ByteNo, SM: getSourceManager(), Features: LangOpts,
127 Target: Context.getTargetInfo());
128}
129
130static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
131 Sema::FormatArgumentPassingKind B) {
132 return (A << 8) | B;
133}
134
135bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
136 unsigned ArgCount = Call->getNumArgs();
137 if (ArgCount >= MinArgCount)
138 return false;
139
140 return Diag(Loc: Call->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args)
141 << 0 /*function call*/ << MinArgCount << ArgCount
142 << /*is non object*/ 0 << Call->getSourceRange();
143}
144
145bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
146 unsigned ArgCount = Call->getNumArgs();
147 if (ArgCount <= MaxArgCount)
148 return false;
149 return Diag(Loc: Call->getEndLoc(), DiagID: diag::err_typecheck_call_too_many_args_at_most)
150 << 0 /*function call*/ << MaxArgCount << ArgCount
151 << /*is non object*/ 0 << Call->getSourceRange();
152}
153
154bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
155 unsigned MaxArgCount) {
156 return checkArgCountAtLeast(Call, MinArgCount) ||
157 checkArgCountAtMost(Call, MaxArgCount);
158}
159
160bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
161 unsigned ArgCount = Call->getNumArgs();
162 if (ArgCount == DesiredArgCount)
163 return false;
164
165 if (checkArgCountAtLeast(Call, MinArgCount: DesiredArgCount))
166 return true;
167 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
168
169 // Highlight all the excess arguments.
170 SourceRange Range(Call->getArg(Arg: DesiredArgCount)->getBeginLoc(),
171 Call->getArg(Arg: ArgCount - 1)->getEndLoc());
172
173 return Diag(Loc: Range.getBegin(), DiagID: diag::err_typecheck_call_too_many_args)
174 << 0 /*function call*/ << DesiredArgCount << ArgCount
175 << /*is non object*/ 0 << Range;
176}
177
178static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S) {
179 bool HasError = false;
180
181 for (const Expr *Arg : Call->arguments()) {
182 if (Arg->isValueDependent())
183 continue;
184
185 std::optional<std::string> ArgString = Arg->tryEvaluateString(Ctx&: S.Context);
186 int DiagMsgKind = -1;
187 // Arguments must be pointers to constant strings and cannot use '$'.
188 if (!ArgString.has_value())
189 DiagMsgKind = 0;
190 else if (ArgString->find(c: '$') != std::string::npos)
191 DiagMsgKind = 1;
192
193 if (DiagMsgKind >= 0) {
194 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_verbose_trap_arg)
195 << DiagMsgKind << Arg->getSourceRange();
196 HasError = true;
197 }
198 }
199
200 return !HasError;
201}
202
203static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty) {
204 if (Value->isTypeDependent())
205 return false;
206
207 InitializedEntity Entity =
208 InitializedEntity::InitializeParameter(Context&: S.Context, Type: Ty, Consumed: false);
209 ExprResult Result =
210 S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Value);
211 if (Result.isInvalid())
212 return true;
213 Value = Result.get();
214 return false;
215}
216
217/// Check that the first argument to __builtin_annotation is an integer
218/// and the second argument is a non-wide string literal.
219static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
220 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
221 return true;
222
223 // First argument should be an integer.
224 Expr *ValArg = TheCall->getArg(Arg: 0);
225 QualType Ty = ValArg->getType();
226 if (!Ty->isIntegerType()) {
227 S.Diag(Loc: ValArg->getBeginLoc(), DiagID: diag::err_builtin_annotation_first_arg)
228 << ValArg->getSourceRange();
229 return true;
230 }
231
232 // Second argument should be a constant string.
233 Expr *StrArg = TheCall->getArg(Arg: 1)->IgnoreParenCasts();
234 StringLiteral *Literal = dyn_cast<StringLiteral>(Val: StrArg);
235 if (!Literal || !Literal->isOrdinary()) {
236 S.Diag(Loc: StrArg->getBeginLoc(), DiagID: diag::err_builtin_annotation_second_arg)
237 << StrArg->getSourceRange();
238 return true;
239 }
240
241 TheCall->setType(Ty);
242 return false;
243}
244
245static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
246 // We need at least one argument.
247 if (TheCall->getNumArgs() < 1) {
248 S.Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
249 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
250 << TheCall->getCallee()->getSourceRange();
251 return true;
252 }
253
254 // All arguments should be wide string literals.
255 for (Expr *Arg : TheCall->arguments()) {
256 auto *Literal = dyn_cast<StringLiteral>(Val: Arg->IgnoreParenCasts());
257 if (!Literal || !Literal->isWide()) {
258 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_msvc_annotation_wide_str)
259 << Arg->getSourceRange();
260 return true;
261 }
262 }
263
264 return false;
265}
266
267/// Check that the argument to __builtin_addressof is a glvalue, and set the
268/// result type to the corresponding pointer type.
269static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
270 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
271 return true;
272
273 ExprResult Arg(TheCall->getArg(Arg: 0));
274 QualType ResultType = S.CheckAddressOfOperand(Operand&: Arg, OpLoc: TheCall->getBeginLoc());
275 if (ResultType.isNull())
276 return true;
277
278 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
279 TheCall->setType(ResultType);
280 return false;
281}
282
283/// Check that the argument to __builtin_function_start is a function.
284static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
285 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
286 return true;
287
288 if (TheCall->getArg(Arg: 0)->containsErrors())
289 return true;
290
291 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
292 if (Arg.isInvalid())
293 return true;
294
295 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
296 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
297 Val: Arg.get()->getAsBuiltinConstantDeclRef(Context: S.getASTContext()));
298
299 if (!FD) {
300 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_function_start_invalid_type)
301 << TheCall->getSourceRange();
302 return true;
303 }
304
305 return !S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
306 Loc: TheCall->getBeginLoc());
307}
308
309/// Check the number of arguments and set the result type to
310/// the argument type.
311static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
312 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
313 return true;
314
315 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
316 return false;
317}
318
319/// Check that the value argument for __builtin_is_aligned(value, alignment) and
320/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
321/// type (but not a function pointer) and that the alignment is a power-of-two.
322static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
323 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
324 return true;
325
326 clang::Expr *Source = TheCall->getArg(Arg: 0);
327 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
328
329 auto IsValidIntegerType = [](QualType Ty) {
330 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
331 };
332 QualType SrcTy = Source->getType();
333 // We should also be able to use it with arrays (but not functions!).
334 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
335 SrcTy = S.Context.getDecayedType(T: SrcTy);
336 }
337 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
338 SrcTy->isFunctionPointerType()) {
339 // FIXME: this is not quite the right error message since we don't allow
340 // floating point types, or member pointers.
341 S.Diag(Loc: Source->getExprLoc(), DiagID: diag::err_typecheck_expect_scalar_operand)
342 << SrcTy;
343 return true;
344 }
345
346 clang::Expr *AlignOp = TheCall->getArg(Arg: 1);
347 if (!IsValidIntegerType(AlignOp->getType())) {
348 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_typecheck_expect_int)
349 << AlignOp->getType();
350 return true;
351 }
352 Expr::EvalResult AlignResult;
353 unsigned MaxAlignmentBits = S.Context.getIntWidth(T: SrcTy) - 1;
354 // We can't check validity of alignment if it is value dependent.
355 if (!AlignOp->isValueDependent() &&
356 AlignOp->EvaluateAsInt(Result&: AlignResult, Ctx: S.Context,
357 AllowSideEffects: Expr::SE_AllowSideEffects)) {
358 llvm::APSInt AlignValue = AlignResult.Val.getInt();
359 llvm::APSInt MaxValue(
360 llvm::APInt::getOneBitSet(numBits: MaxAlignmentBits + 1, BitNo: MaxAlignmentBits));
361 if (AlignValue < 1) {
362 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_too_small) << 1;
363 return true;
364 }
365 if (llvm::APSInt::compareValues(I1: AlignValue, I2: MaxValue) > 0) {
366 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_too_big)
367 << toString(I: MaxValue, Radix: 10);
368 return true;
369 }
370 if (!AlignValue.isPowerOf2()) {
371 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_not_power_of_two);
372 return true;
373 }
374 if (AlignValue == 1) {
375 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::warn_alignment_builtin_useless)
376 << IsBooleanAlignBuiltin;
377 }
378 }
379
380 ExprResult SrcArg = S.PerformCopyInitialization(
381 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Type: SrcTy, Consumed: false),
382 EqualLoc: SourceLocation(), Init: Source);
383 if (SrcArg.isInvalid())
384 return true;
385 TheCall->setArg(Arg: 0, ArgExpr: SrcArg.get());
386 ExprResult AlignArg =
387 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
388 Context&: S.Context, Type: AlignOp->getType(), Consumed: false),
389 EqualLoc: SourceLocation(), Init: AlignOp);
390 if (AlignArg.isInvalid())
391 return true;
392 TheCall->setArg(Arg: 1, ArgExpr: AlignArg.get());
393 // For align_up/align_down, the return type is the same as the (potentially
394 // decayed) argument type including qualifiers. For is_aligned(), the result
395 // is always bool.
396 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
397 return false;
398}
399
400static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
401 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
402 return true;
403
404 std::pair<unsigned, const char *> Builtins[] = {
405 { Builtin::BI__builtin_add_overflow, "ckd_add" },
406 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
407 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
408 };
409
410 bool CkdOperation = llvm::any_of(Range&: Builtins, P: [&](const std::pair<unsigned,
411 const char *> &P) {
412 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
413 Lexer::getImmediateMacroName(Loc: TheCall->getExprLoc(),
414 SM: S.getSourceManager(), LangOpts: S.getLangOpts()) == P.second;
415 });
416
417 auto ValidCkdIntType = [](QualType QT) {
418 // A valid checked integer type is an integer type other than a plain char,
419 // bool, a bit-precise type, or an enumeration type.
420 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
421 return (BT->getKind() >= BuiltinType::Short &&
422 BT->getKind() <= BuiltinType::Int128) || (
423 BT->getKind() >= BuiltinType::UShort &&
424 BT->getKind() <= BuiltinType::UInt128) ||
425 BT->getKind() == BuiltinType::UChar ||
426 BT->getKind() == BuiltinType::SChar;
427 return false;
428 };
429
430 // First two arguments should be integers.
431 for (unsigned I = 0; I < 2; ++I) {
432 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: I));
433 if (Arg.isInvalid()) return true;
434 TheCall->setArg(Arg: I, ArgExpr: Arg.get());
435
436 QualType Ty = Arg.get()->getType();
437 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
438 if (!IsValid) {
439 S.Diag(Loc: Arg.get()->getBeginLoc(), DiagID: diag::err_overflow_builtin_must_be_int)
440 << CkdOperation << Ty << Arg.get()->getSourceRange();
441 return true;
442 }
443 }
444
445 // Third argument should be a pointer to a non-const integer.
446 // IRGen correctly handles volatile, restrict, and address spaces, and
447 // the other qualifiers aren't possible.
448 {
449 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 2));
450 if (Arg.isInvalid()) return true;
451 TheCall->setArg(Arg: 2, ArgExpr: Arg.get());
452
453 QualType Ty = Arg.get()->getType();
454 const auto *PtrTy = Ty->getAs<PointerType>();
455 if (!PtrTy ||
456 !PtrTy->getPointeeType()->isIntegerType() ||
457 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
458 PtrTy->getPointeeType().isConstQualified()) {
459 S.Diag(Loc: Arg.get()->getBeginLoc(),
460 DiagID: diag::err_overflow_builtin_must_be_ptr_int)
461 << CkdOperation << Ty << Arg.get()->getSourceRange();
462 return true;
463 }
464 }
465
466 // Disallow signed bit-precise integer args larger than 128 bits to mul
467 // function until we improve backend support.
468 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
469 for (unsigned I = 0; I < 3; ++I) {
470 const auto Arg = TheCall->getArg(Arg: I);
471 // Third argument will be a pointer.
472 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
473 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
474 S.getASTContext().getIntWidth(T: Ty) > 128)
475 return S.Diag(Loc: Arg->getBeginLoc(),
476 DiagID: diag::err_overflow_builtin_bit_int_max_size)
477 << 128;
478 }
479 }
480
481 return false;
482}
483
484namespace {
485struct BuiltinDumpStructGenerator {
486 Sema &S;
487 CallExpr *TheCall;
488 SourceLocation Loc = TheCall->getBeginLoc();
489 SmallVector<Expr *, 32> Actions;
490 DiagnosticErrorTrap ErrorTracker;
491 PrintingPolicy Policy;
492
493 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
494 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
495 Policy(S.Context.getPrintingPolicy()) {
496 Policy.AnonymousTagNameStyle =
497 llvm::to_underlying(E: PrintingPolicy::AnonymousTagMode::Plain);
498 }
499
500 Expr *makeOpaqueValueExpr(Expr *Inner) {
501 auto *OVE = new (S.Context)
502 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
503 Inner->getObjectKind(), Inner);
504 Actions.push_back(Elt: OVE);
505 return OVE;
506 }
507
508 Expr *getStringLiteral(llvm::StringRef Str) {
509 Expr *Lit = S.Context.getPredefinedStringLiteralFromCache(Key: Str);
510 // Wrap the literal in parentheses to attach a source location.
511 return new (S.Context) ParenExpr(Loc, Loc, Lit);
512 }
513
514 bool callPrintFunction(llvm::StringRef Format,
515 llvm::ArrayRef<Expr *> Exprs = {}) {
516 SmallVector<Expr *, 8> Args;
517 assert(TheCall->getNumArgs() >= 2);
518 Args.reserve(N: (TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
519 Args.assign(in_start: TheCall->arg_begin() + 2, in_end: TheCall->arg_end());
520 Args.push_back(Elt: getStringLiteral(Str: Format));
521 llvm::append_range(C&: Args, R&: Exprs);
522
523 // Register a note to explain why we're performing the call.
524 Sema::CodeSynthesisContext Ctx;
525 Ctx.Kind = Sema::CodeSynthesisContext::BuildingBuiltinDumpStructCall;
526 Ctx.PointOfInstantiation = Loc;
527 Ctx.CallArgs = Args.data();
528 Ctx.NumCallArgs = Args.size();
529 S.pushCodeSynthesisContext(Ctx);
530
531 ExprResult RealCall =
532 S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: TheCall->getArg(Arg: 1),
533 LParenLoc: TheCall->getBeginLoc(), ArgExprs: Args, RParenLoc: TheCall->getRParenLoc());
534
535 S.popCodeSynthesisContext();
536 if (!RealCall.isInvalid())
537 Actions.push_back(Elt: RealCall.get());
538 // Bail out if we've hit any errors, even if we managed to build the
539 // call. We don't want to produce more than one error.
540 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
541 }
542
543 Expr *getIndentString(unsigned Depth) {
544 if (!Depth)
545 return nullptr;
546
547 llvm::SmallString<32> Indent;
548 Indent.resize(N: Depth * Policy.Indentation, NV: ' ');
549 return getStringLiteral(Str: Indent);
550 }
551
552 Expr *getTypeString(QualType T) {
553 return getStringLiteral(Str: T.getAsString(Policy));
554 }
555
556 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
557 llvm::raw_svector_ostream OS(Str);
558
559 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
560 // than trying to print a single character.
561 if (auto *BT = T->getAs<BuiltinType>()) {
562 switch (BT->getKind()) {
563 case BuiltinType::Bool:
564 OS << "%d";
565 return true;
566 case BuiltinType::Char_U:
567 case BuiltinType::UChar:
568 OS << "%hhu";
569 return true;
570 case BuiltinType::Char_S:
571 case BuiltinType::SChar:
572 OS << "%hhd";
573 return true;
574 default:
575 break;
576 }
577 }
578
579 analyze_printf::PrintfSpecifier Specifier;
580 if (Specifier.fixType(QT: T, LangOpt: S.getLangOpts(), Ctx&: S.Context, /*IsObjCLiteral=*/false)) {
581 // We were able to guess how to format this.
582 if (Specifier.getConversionSpecifier().getKind() ==
583 analyze_printf::PrintfConversionSpecifier::sArg) {
584 // Wrap double-quotes around a '%s' specifier and limit its maximum
585 // length. Ideally we'd also somehow escape special characters in the
586 // contents but printf doesn't support that.
587 // FIXME: '%s' formatting is not safe in general.
588 OS << '"';
589 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
590 Specifier.toString(os&: OS);
591 OS << '"';
592 // FIXME: It would be nice to include a '...' if the string doesn't fit
593 // in the length limit.
594 } else {
595 Specifier.toString(os&: OS);
596 }
597 return true;
598 }
599
600 if (T->isPointerType()) {
601 // Format all pointers with '%p'.
602 OS << "%p";
603 return true;
604 }
605
606 return false;
607 }
608
609 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
610 Expr *IndentLit = getIndentString(Depth);
611 Expr *TypeLit = getTypeString(T: S.Context.getCanonicalTagType(TD: RD));
612 if (IndentLit ? callPrintFunction(Format: "%s%s", Exprs: {IndentLit, TypeLit})
613 : callPrintFunction(Format: "%s", Exprs: {TypeLit}))
614 return true;
615
616 return dumpRecordValue(RD, E, RecordIndent: IndentLit, Depth);
617 }
618
619 // Dump a record value. E should be a pointer or lvalue referring to an RD.
620 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
621 unsigned Depth) {
622 // FIXME: Decide what to do if RD is a union. At least we should probably
623 // turn off printing `const char*` members with `%s`, because that is very
624 // likely to crash if that's not the active member. Whatever we decide, we
625 // should document it.
626
627 // Build an OpaqueValueExpr so we can refer to E more than once without
628 // triggering re-evaluation.
629 Expr *RecordArg = makeOpaqueValueExpr(Inner: E);
630 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
631
632 if (callPrintFunction(Format: " {\n"))
633 return true;
634
635 // Dump each base class, regardless of whether they're aggregates.
636 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
637 for (const auto &Base : CXXRD->bases()) {
638 QualType BaseType =
639 RecordArgIsPtr ? S.Context.getPointerType(T: Base.getType())
640 : S.Context.getLValueReferenceType(T: Base.getType());
641 ExprResult BasePtr = S.BuildCStyleCastExpr(
642 LParenLoc: Loc, Ty: S.Context.getTrivialTypeSourceInfo(T: BaseType, Loc), RParenLoc: Loc,
643 Op: RecordArg);
644 if (BasePtr.isInvalid() ||
645 dumpUnnamedRecord(RD: Base.getType()->getAsRecordDecl(), E: BasePtr.get(),
646 Depth: Depth + 1))
647 return true;
648 }
649 }
650
651 Expr *FieldIndentArg = getIndentString(Depth: Depth + 1);
652
653 // Dump each field.
654 for (auto *D : RD->decls()) {
655 auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D);
656 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(Val: D);
657 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
658 continue;
659
660 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
661 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
662 getTypeString(T: FD->getType()),
663 getStringLiteral(Str: FD->getName())};
664
665 if (FD->isBitField()) {
666 Format += ": %zu ";
667 QualType SizeT = S.Context.getSizeType();
668 llvm::APInt BitWidth(S.Context.getIntWidth(T: SizeT),
669 FD->getBitWidthValue());
670 Args.push_back(Elt: IntegerLiteral::Create(C: S.Context, V: BitWidth, type: SizeT, l: Loc));
671 }
672
673 Format += "=";
674
675 ExprResult Field =
676 IFD ? S.BuildAnonymousStructUnionMemberReference(
677 SS: CXXScopeSpec(), nameLoc: Loc, indirectField: IFD,
678 FoundDecl: DeclAccessPair::make(D: IFD, AS: AS_public), baseObjectExpr: RecordArg, opLoc: Loc)
679 : S.BuildFieldReferenceExpr(
680 BaseExpr: RecordArg, IsArrow: RecordArgIsPtr, OpLoc: Loc, SS: CXXScopeSpec(), Field: FD,
681 FoundDecl: DeclAccessPair::make(D: FD, AS: AS_public),
682 MemberNameInfo: DeclarationNameInfo(FD->getDeclName(), Loc));
683 if (Field.isInvalid())
684 return true;
685
686 auto *InnerRD = FD->getType()->getAsRecordDecl();
687 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(Val: InnerRD);
688 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
689 // Recursively print the values of members of aggregate record type.
690 if (callPrintFunction(Format, Exprs: Args) ||
691 dumpRecordValue(RD: InnerRD, E: Field.get(), RecordIndent: FieldIndentArg, Depth: Depth + 1))
692 return true;
693 } else {
694 Format += " ";
695 if (appendFormatSpecifier(T: FD->getType(), Str&: Format)) {
696 // We know how to print this field.
697 Args.push_back(Elt: Field.get());
698 } else {
699 // We don't know how to print this field. Print out its address
700 // with a format specifier that a smart tool will be able to
701 // recognize and treat specially.
702 Format += "*%p";
703 ExprResult FieldAddr =
704 S.BuildUnaryOp(S: nullptr, OpLoc: Loc, Opc: UO_AddrOf, Input: Field.get());
705 if (FieldAddr.isInvalid())
706 return true;
707 Args.push_back(Elt: FieldAddr.get());
708 }
709 Format += "\n";
710 if (callPrintFunction(Format, Exprs: Args))
711 return true;
712 }
713 }
714
715 return RecordIndent ? callPrintFunction(Format: "%s}\n", Exprs: RecordIndent)
716 : callPrintFunction(Format: "}\n");
717 }
718
719 Expr *buildWrapper() {
720 auto *Wrapper = PseudoObjectExpr::Create(Context: S.Context, syntactic: TheCall, semantic: Actions,
721 resultIndex: PseudoObjectExpr::NoResult);
722 TheCall->setType(Wrapper->getType());
723 TheCall->setValueKind(Wrapper->getValueKind());
724 return Wrapper;
725 }
726};
727} // namespace
728
729static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall) {
730 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 2))
731 return ExprError();
732
733 ExprResult PtrArgResult = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
734 if (PtrArgResult.isInvalid())
735 return ExprError();
736 TheCall->setArg(Arg: 0, ArgExpr: PtrArgResult.get());
737
738 // First argument should be a pointer to a struct.
739 QualType PtrArgType = PtrArgResult.get()->getType();
740 if (!PtrArgType->isPointerType() ||
741 !PtrArgType->getPointeeType()->isRecordType()) {
742 S.Diag(Loc: PtrArgResult.get()->getBeginLoc(),
743 DiagID: diag::err_expected_struct_pointer_argument)
744 << 1 << TheCall->getDirectCallee() << PtrArgType;
745 return ExprError();
746 }
747 QualType Pointee = PtrArgType->getPointeeType();
748 const RecordDecl *RD = Pointee->getAsRecordDecl();
749 // Try to instantiate the class template as appropriate; otherwise, access to
750 // its data() may lead to a crash.
751 if (S.RequireCompleteType(Loc: PtrArgResult.get()->getBeginLoc(), T: Pointee,
752 DiagID: diag::err_incomplete_type))
753 return ExprError();
754 // Second argument is a callable, but we can't fully validate it until we try
755 // calling it.
756 QualType FnArgType = TheCall->getArg(Arg: 1)->getType();
757 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
758 !FnArgType->isBlockPointerType() &&
759 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
760 auto *BT = FnArgType->getAs<BuiltinType>();
761 switch (BT ? BT->getKind() : BuiltinType::Void) {
762 case BuiltinType::Dependent:
763 case BuiltinType::Overload:
764 case BuiltinType::BoundMember:
765 case BuiltinType::PseudoObject:
766 case BuiltinType::UnknownAny:
767 case BuiltinType::BuiltinFn:
768 // This might be a callable.
769 break;
770
771 default:
772 S.Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
773 DiagID: diag::err_expected_callable_argument)
774 << 2 << TheCall->getDirectCallee() << FnArgType;
775 return ExprError();
776 }
777 }
778
779 BuiltinDumpStructGenerator Generator(S, TheCall);
780
781 // Wrap parentheses around the given pointer. This is not necessary for
782 // correct code generation, but it means that when we pretty-print the call
783 // arguments in our diagnostics we will produce '(&s)->n' instead of the
784 // incorrect '&s->n'.
785 Expr *PtrArg = PtrArgResult.get();
786 PtrArg = new (S.Context)
787 ParenExpr(PtrArg->getBeginLoc(),
788 S.getLocForEndOfToken(Loc: PtrArg->getEndLoc()), PtrArg);
789 if (Generator.dumpUnnamedRecord(RD, E: PtrArg, Depth: 0))
790 return ExprError();
791
792 return Generator.buildWrapper();
793}
794
795static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
796 if (S.checkArgCount(Call: BuiltinCall, DesiredArgCount: 2))
797 return true;
798
799 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
800 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
801 Expr *Call = BuiltinCall->getArg(Arg: 0);
802 Expr *Chain = BuiltinCall->getArg(Arg: 1);
803
804 if (Call->getStmtClass() != Stmt::CallExprClass) {
805 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_not_call)
806 << Call->getSourceRange();
807 return true;
808 }
809
810 auto CE = cast<CallExpr>(Val: Call);
811 if (CE->getCallee()->getType()->isBlockPointerType()) {
812 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_block_call)
813 << Call->getSourceRange();
814 return true;
815 }
816
817 const Decl *TargetDecl = CE->getCalleeDecl();
818 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: TargetDecl))
819 if (FD->getBuiltinID()) {
820 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_builtin_call)
821 << Call->getSourceRange();
822 return true;
823 }
824
825 if (isa<CXXPseudoDestructorExpr>(Val: CE->getCallee()->IgnoreParens())) {
826 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_pdtor_call)
827 << Call->getSourceRange();
828 return true;
829 }
830
831 ExprResult ChainResult = S.UsualUnaryConversions(E: Chain);
832 if (ChainResult.isInvalid())
833 return true;
834 if (!ChainResult.get()->getType()->isPointerType()) {
835 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_second_argument_to_cwsc_not_pointer)
836 << Chain->getSourceRange();
837 return true;
838 }
839
840 QualType ReturnTy = CE->getCallReturnType(Ctx: S.Context);
841 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
842 QualType BuiltinTy = S.Context.getFunctionType(
843 ResultTy: ReturnTy, Args: ArgTys, EPI: FunctionProtoType::ExtProtoInfo());
844 QualType BuiltinPtrTy = S.Context.getPointerType(T: BuiltinTy);
845
846 Builtin =
847 S.ImpCastExprToType(E: Builtin, Type: BuiltinPtrTy, CK: CK_BuiltinFnToFnPtr).get();
848
849 BuiltinCall->setType(CE->getType());
850 BuiltinCall->setValueKind(CE->getValueKind());
851 BuiltinCall->setObjectKind(CE->getObjectKind());
852 BuiltinCall->setCallee(Builtin);
853 BuiltinCall->setArg(Arg: 1, ArgExpr: ChainResult.get());
854
855 return false;
856}
857
858namespace {
859
860class ScanfDiagnosticFormatHandler
861 : public analyze_format_string::FormatStringHandler {
862 // Accepts the argument index (relative to the first destination index) of the
863 // argument whose size we want.
864 using ComputeSizeFunction =
865 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
866
867 // Accepts the argument index (relative to the first destination index), the
868 // destination size, and the source size).
869 using DiagnoseFunction =
870 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
871
872 ComputeSizeFunction ComputeSizeArgument;
873 DiagnoseFunction Diagnose;
874
875public:
876 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
877 DiagnoseFunction Diagnose)
878 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
879
880 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
881 const char *StartSpecifier,
882 unsigned specifierLen) override {
883 if (!FS.consumesDataArgument())
884 return true;
885
886 unsigned NulByte = 0;
887 switch ((FS.getConversionSpecifier().getKind())) {
888 default:
889 return true;
890 case analyze_format_string::ConversionSpecifier::sArg:
891 case analyze_format_string::ConversionSpecifier::ScanListArg:
892 NulByte = 1;
893 break;
894 case analyze_format_string::ConversionSpecifier::cArg:
895 break;
896 }
897
898 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
899 if (FW.getHowSpecified() !=
900 analyze_format_string::OptionalAmount::HowSpecified::Constant)
901 return true;
902
903 unsigned SourceSize = FW.getConstantAmount() + NulByte;
904
905 std::optional<llvm::APSInt> DestSizeAPS =
906 ComputeSizeArgument(FS.getArgIndex());
907 if (!DestSizeAPS)
908 return true;
909
910 unsigned DestSize = DestSizeAPS->getZExtValue();
911
912 if (DestSize < SourceSize)
913 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
914
915 return true;
916 }
917};
918
919class EstimateSizeFormatHandler
920 : public analyze_format_string::FormatStringHandler {
921 size_t Size;
922 /// Whether the format string contains Linux kernel's format specifier
923 /// extension.
924 bool IsKernelCompatible = true;
925
926public:
927 EstimateSizeFormatHandler(StringRef Format)
928 : Size(std::min(a: Format.find(C: 0), b: Format.size()) +
929 1 /* null byte always written by sprintf */) {}
930
931 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
932 const char *, unsigned SpecifierLen,
933 const TargetInfo &) override {
934
935 const size_t FieldWidth = computeFieldWidth(FS);
936 const size_t Precision = computePrecision(FS);
937
938 // The actual format.
939 switch (FS.getConversionSpecifier().getKind()) {
940 // Just a char.
941 case analyze_format_string::ConversionSpecifier::cArg:
942 case analyze_format_string::ConversionSpecifier::CArg:
943 Size += std::max(a: FieldWidth, b: (size_t)1);
944 break;
945 // Just an integer.
946 case analyze_format_string::ConversionSpecifier::dArg:
947 case analyze_format_string::ConversionSpecifier::DArg:
948 case analyze_format_string::ConversionSpecifier::iArg:
949 case analyze_format_string::ConversionSpecifier::oArg:
950 case analyze_format_string::ConversionSpecifier::OArg:
951 case analyze_format_string::ConversionSpecifier::uArg:
952 case analyze_format_string::ConversionSpecifier::UArg:
953 case analyze_format_string::ConversionSpecifier::xArg:
954 case analyze_format_string::ConversionSpecifier::XArg:
955 Size += std::max(a: FieldWidth, b: Precision);
956 break;
957
958 // %g style conversion switches between %f or %e style dynamically.
959 // %g removes trailing zeros, and does not print decimal point if there are
960 // no digits that follow it. Thus %g can print a single digit.
961 // FIXME: If it is alternative form:
962 // For g and G conversions, trailing zeros are not removed from the result.
963 case analyze_format_string::ConversionSpecifier::gArg:
964 case analyze_format_string::ConversionSpecifier::GArg:
965 Size += 1;
966 break;
967
968 // Floating point number in the form '[+]ddd.ddd'.
969 case analyze_format_string::ConversionSpecifier::fArg:
970 case analyze_format_string::ConversionSpecifier::FArg:
971 Size += std::max(a: FieldWidth, b: 1 /* integer part */ +
972 (Precision ? 1 + Precision
973 : 0) /* period + decimal */);
974 break;
975
976 // Floating point number in the form '[-]d.ddde[+-]dd'.
977 case analyze_format_string::ConversionSpecifier::eArg:
978 case analyze_format_string::ConversionSpecifier::EArg:
979 Size +=
980 std::max(a: FieldWidth,
981 b: 1 /* integer part */ +
982 (Precision ? 1 + Precision : 0) /* period + decimal */ +
983 1 /* e or E letter */ + 2 /* exponent */);
984 break;
985
986 // Floating point number in the form '[-]0xh.hhhhp±dd'.
987 case analyze_format_string::ConversionSpecifier::aArg:
988 case analyze_format_string::ConversionSpecifier::AArg:
989 Size +=
990 std::max(a: FieldWidth,
991 b: 2 /* 0x */ + 1 /* integer part */ +
992 (Precision ? 1 + Precision : 0) /* period + decimal */ +
993 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
994 break;
995
996 // Just a string.
997 case analyze_format_string::ConversionSpecifier::sArg:
998 case analyze_format_string::ConversionSpecifier::SArg:
999 Size += FieldWidth;
1000 break;
1001
1002 // Just a pointer in the form '0xddd'.
1003 case analyze_format_string::ConversionSpecifier::pArg:
1004 // Linux kernel has its own extesion for `%p` specifier.
1005 // Kernel Document:
1006 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1007 IsKernelCompatible = false;
1008 Size += std::max(a: FieldWidth, b: 2 /* leading 0x */ + Precision);
1009 break;
1010
1011 // A plain percent.
1012 case analyze_format_string::ConversionSpecifier::PercentArg:
1013 Size += 1;
1014 break;
1015
1016 default:
1017 break;
1018 }
1019
1020 // If field width is specified, the sign/space is already accounted for
1021 // within the field width, so no additional size is needed.
1022 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1023 Size += 1;
1024
1025 if (FS.hasAlternativeForm()) {
1026 switch (FS.getConversionSpecifier().getKind()) {
1027 // For o conversion, it increases the precision, if and only if necessary,
1028 // to force the first digit of the result to be a zero
1029 // (if the value and precision are both 0, a single 0 is printed)
1030 case analyze_format_string::ConversionSpecifier::oArg:
1031 // For b conversion, a nonzero result has 0b prefixed to it.
1032 case analyze_format_string::ConversionSpecifier::bArg:
1033 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1034 // it.
1035 case analyze_format_string::ConversionSpecifier::xArg:
1036 case analyze_format_string::ConversionSpecifier::XArg:
1037 // Note: even when the prefix is added, if
1038 // (prefix_width <= FieldWidth - formatted_length) holds,
1039 // the prefix does not increase the format
1040 // size. e.g.(("%#3x", 0xf) is "0xf")
1041
1042 // If the result is zero, o, b, x, X adds nothing.
1043 break;
1044 // For a, A, e, E, f, F, g, and G conversions,
1045 // the result of converting a floating-point number always contains a
1046 // decimal-point
1047 case analyze_format_string::ConversionSpecifier::aArg:
1048 case analyze_format_string::ConversionSpecifier::AArg:
1049 case analyze_format_string::ConversionSpecifier::eArg:
1050 case analyze_format_string::ConversionSpecifier::EArg:
1051 case analyze_format_string::ConversionSpecifier::fArg:
1052 case analyze_format_string::ConversionSpecifier::FArg:
1053 case analyze_format_string::ConversionSpecifier::gArg:
1054 case analyze_format_string::ConversionSpecifier::GArg:
1055 Size += (Precision ? 0 : 1);
1056 break;
1057 // For other conversions, the behavior is undefined.
1058 default:
1059 break;
1060 }
1061 }
1062 assert(SpecifierLen <= Size && "no underflow");
1063 Size -= SpecifierLen;
1064 return true;
1065 }
1066
1067 size_t getSizeLowerBound() const { return Size; }
1068 bool isKernelCompatible() const { return IsKernelCompatible; }
1069
1070private:
1071 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1072 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1073 size_t FieldWidth = 0;
1074 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
1075 FieldWidth = FW.getConstantAmount();
1076 return FieldWidth;
1077 }
1078
1079 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1080 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1081 size_t Precision = 0;
1082
1083 // See man 3 printf for default precision value based on the specifier.
1084 switch (FW.getHowSpecified()) {
1085 case analyze_format_string::OptionalAmount::NotSpecified:
1086 switch (FS.getConversionSpecifier().getKind()) {
1087 default:
1088 break;
1089 case analyze_format_string::ConversionSpecifier::dArg: // %d
1090 case analyze_format_string::ConversionSpecifier::DArg: // %D
1091 case analyze_format_string::ConversionSpecifier::iArg: // %i
1092 Precision = 1;
1093 break;
1094 case analyze_format_string::ConversionSpecifier::oArg: // %d
1095 case analyze_format_string::ConversionSpecifier::OArg: // %D
1096 case analyze_format_string::ConversionSpecifier::uArg: // %d
1097 case analyze_format_string::ConversionSpecifier::UArg: // %D
1098 case analyze_format_string::ConversionSpecifier::xArg: // %d
1099 case analyze_format_string::ConversionSpecifier::XArg: // %D
1100 Precision = 1;
1101 break;
1102 case analyze_format_string::ConversionSpecifier::fArg: // %f
1103 case analyze_format_string::ConversionSpecifier::FArg: // %F
1104 case analyze_format_string::ConversionSpecifier::eArg: // %e
1105 case analyze_format_string::ConversionSpecifier::EArg: // %E
1106 case analyze_format_string::ConversionSpecifier::gArg: // %g
1107 case analyze_format_string::ConversionSpecifier::GArg: // %G
1108 Precision = 6;
1109 break;
1110 case analyze_format_string::ConversionSpecifier::pArg: // %d
1111 Precision = 1;
1112 break;
1113 }
1114 break;
1115 case analyze_format_string::OptionalAmount::Constant:
1116 Precision = FW.getConstantAmount();
1117 break;
1118 default:
1119 break;
1120 }
1121 return Precision;
1122 }
1123};
1124
1125} // namespace
1126
1127static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1128 StringRef &FormatStrRef, size_t &StrLen,
1129 ASTContext &Context) {
1130 if (const auto *Format = dyn_cast<StringLiteral>(Val: FormatExpr);
1131 Format && (Format->isOrdinary() || Format->isUTF8())) {
1132 FormatStrRef = Format->getString();
1133 const ConstantArrayType *T =
1134 Context.getAsConstantArrayType(T: Format->getType());
1135 assert(T && "String literal not of constant array type!");
1136 size_t TypeSize = T->getZExtSize();
1137 // In case there's a null byte somewhere.
1138 StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: FormatStrRef.find(C: 0));
1139 return true;
1140 }
1141 return false;
1142}
1143
1144void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1145 CallExpr *TheCall) {
1146 if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
1147 isConstantEvaluatedContext())
1148 return;
1149
1150 bool UseDABAttr = false;
1151 const FunctionDecl *UseDecl = FD;
1152
1153 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>();
1154 if (DABAttr) {
1155 UseDecl = DABAttr->getFunction();
1156 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1157 UseDABAttr = true;
1158 }
1159
1160 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/ConsiderWrapperFunctions: true);
1161
1162 if (!BuiltinID)
1163 return;
1164
1165 const TargetInfo &TI = getASTContext().getTargetInfo();
1166 unsigned SizeTypeWidth = TI.getTypeWidth(T: TI.getSizeType());
1167
1168 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> {
1169 // If we refer to a diagnose_as_builtin attribute, we need to change the
1170 // argument index to refer to the arguments of the called function. Unless
1171 // the index is out of bounds, which presumably means it's a variadic
1172 // function.
1173 if (!UseDABAttr)
1174 return Index;
1175 unsigned DABIndices = DABAttr->argIndices_size();
1176 unsigned NewIndex = Index < DABIndices
1177 ? DABAttr->argIndices_begin()[Index]
1178 : Index - DABIndices + FD->getNumParams();
1179 if (NewIndex >= TheCall->getNumArgs())
1180 return std::nullopt;
1181 return NewIndex;
1182 };
1183
1184 auto ComputeExplicitObjectSizeArgument =
1185 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1186 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1187 if (!IndexOptional)
1188 return std::nullopt;
1189 unsigned NewIndex = *IndexOptional;
1190 Expr::EvalResult Result;
1191 Expr *SizeArg = TheCall->getArg(Arg: NewIndex);
1192 if (!SizeArg->EvaluateAsInt(Result, Ctx: getASTContext()))
1193 return std::nullopt;
1194 llvm::APSInt Integer = Result.Val.getInt();
1195 Integer.setIsUnsigned(true);
1196 return Integer;
1197 };
1198
1199 auto ComputeSizeArgument =
1200 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1201 // If the parameter has a pass_object_size attribute, then we should use its
1202 // (potentially) more strict checking mode. Otherwise, conservatively assume
1203 // type 0.
1204 int BOSType = 0;
1205 // This check can fail for variadic functions.
1206 if (Index < FD->getNumParams()) {
1207 if (const auto *POS =
1208 FD->getParamDecl(i: Index)->getAttr<PassObjectSizeAttr>())
1209 BOSType = POS->getType();
1210 }
1211
1212 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1213 if (!IndexOptional)
1214 return std::nullopt;
1215 unsigned NewIndex = *IndexOptional;
1216
1217 if (NewIndex >= TheCall->getNumArgs())
1218 return std::nullopt;
1219
1220 const Expr *ObjArg = TheCall->getArg(Arg: NewIndex);
1221 if (std::optional<uint64_t> ObjSize =
1222 ObjArg->tryEvaluateObjectSize(Ctx: getASTContext(), Type: BOSType)) {
1223 // Get the object size in the target's size_t width.
1224 return llvm::APSInt::getUnsigned(X: *ObjSize).extOrTrunc(width: SizeTypeWidth);
1225 }
1226 return std::nullopt;
1227 };
1228
1229 auto ComputeStrLenArgument =
1230 [&](unsigned Index) -> std::optional<llvm::APSInt> {
1231 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1232 if (!IndexOptional)
1233 return std::nullopt;
1234 unsigned NewIndex = *IndexOptional;
1235
1236 const Expr *ObjArg = TheCall->getArg(Arg: NewIndex);
1237
1238 if (std::optional<uint64_t> Result =
1239 ObjArg->tryEvaluateStrLen(Ctx: getASTContext())) {
1240 // Add 1 for null byte.
1241 return llvm::APSInt::getUnsigned(X: *Result + 1).extOrTrunc(width: SizeTypeWidth);
1242 }
1243 return std::nullopt;
1244 };
1245
1246 std::optional<llvm::APSInt> SourceSize;
1247 std::optional<llvm::APSInt> DestinationSize;
1248 unsigned DiagID = 0;
1249 bool IsChkVariant = false;
1250
1251 auto GetFunctionName = [&]() {
1252 std::string FunctionNameStr =
1253 getASTContext().BuiltinInfo.getName(ID: BuiltinID);
1254 llvm::StringRef FunctionName = FunctionNameStr;
1255 // Skim off the details of whichever builtin was called to produce a better
1256 // diagnostic, as it's unlikely that the user wrote the __builtin
1257 // explicitly.
1258 if (IsChkVariant) {
1259 FunctionName = FunctionName.drop_front(N: std::strlen(s: "__builtin___"));
1260 FunctionName = FunctionName.drop_back(N: std::strlen(s: "_chk"));
1261 } else {
1262 FunctionName.consume_front(Prefix: "__builtin_");
1263 }
1264 return FunctionName.str();
1265 };
1266
1267 switch (BuiltinID) {
1268 default:
1269 return;
1270 case Builtin::BI__builtin_strcat:
1271 case Builtin::BIstrcat:
1272 case Builtin::BI__builtin_stpcpy:
1273 case Builtin::BIstpcpy:
1274 case Builtin::BI__builtin_strcpy:
1275 case Builtin::BIstrcpy: {
1276 DiagID = diag::warn_fortify_strlen_overflow;
1277 SourceSize = ComputeStrLenArgument(1);
1278 DestinationSize = ComputeSizeArgument(0);
1279 break;
1280 }
1281
1282 case Builtin::BI__builtin___strcat_chk:
1283 case Builtin::BI__builtin___stpcpy_chk:
1284 case Builtin::BI__builtin___strcpy_chk: {
1285 DiagID = diag::warn_fortify_strlen_overflow;
1286 SourceSize = ComputeStrLenArgument(1);
1287 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1288 IsChkVariant = true;
1289 break;
1290 }
1291
1292 case Builtin::BIscanf:
1293 case Builtin::BIfscanf:
1294 case Builtin::BIsscanf: {
1295 unsigned FormatIndex = 1;
1296 unsigned DataIndex = 2;
1297 if (BuiltinID == Builtin::BIscanf) {
1298 FormatIndex = 0;
1299 DataIndex = 1;
1300 }
1301
1302 const auto *FormatExpr =
1303 TheCall->getArg(Arg: FormatIndex)->IgnoreParenImpCasts();
1304
1305 StringRef FormatStrRef;
1306 size_t StrLen;
1307 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1308 return;
1309
1310 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1311 unsigned SourceSize) {
1312 DiagID = diag::warn_fortify_scanf_overflow;
1313 unsigned Index = ArgIndex + DataIndex;
1314 std::string FunctionName = GetFunctionName();
1315 DiagRuntimeBehavior(Loc: TheCall->getArg(Arg: Index)->getBeginLoc(), Statement: TheCall,
1316 PD: PDiag(DiagID) << FunctionName << (Index + 1)
1317 << DestSize << SourceSize);
1318 };
1319
1320 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1321 return ComputeSizeArgument(Index + DataIndex);
1322 };
1323 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1324 const char *FormatBytes = FormatStrRef.data();
1325 analyze_format_string::ParseScanfString(H, beg: FormatBytes,
1326 end: FormatBytes + StrLen, LO: getLangOpts(),
1327 Target: Context.getTargetInfo());
1328
1329 // Unlike the other cases, in this one we have already issued the diagnostic
1330 // here, so no need to continue (because unlike the other cases, here the
1331 // diagnostic refers to the argument number).
1332 return;
1333 }
1334
1335 case Builtin::BIsprintf:
1336 case Builtin::BI__builtin___sprintf_chk: {
1337 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1338 auto *FormatExpr = TheCall->getArg(Arg: FormatIndex)->IgnoreParenImpCasts();
1339
1340 StringRef FormatStrRef;
1341 size_t StrLen;
1342 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1343 EstimateSizeFormatHandler H(FormatStrRef);
1344 const char *FormatBytes = FormatStrRef.data();
1345 if (!analyze_format_string::ParsePrintfString(
1346 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1347 Target: Context.getTargetInfo(), isFreeBSDKPrintf: false)) {
1348 DiagID = H.isKernelCompatible()
1349 ? diag::warn_format_overflow
1350 : diag::warn_format_overflow_non_kprintf;
1351 SourceSize = llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1352 .extOrTrunc(width: SizeTypeWidth);
1353 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1354 DestinationSize = ComputeExplicitObjectSizeArgument(2);
1355 IsChkVariant = true;
1356 } else {
1357 DestinationSize = ComputeSizeArgument(0);
1358 }
1359 break;
1360 }
1361 }
1362 return;
1363 }
1364 case Builtin::BI__builtin___memcpy_chk:
1365 case Builtin::BI__builtin___memmove_chk:
1366 case Builtin::BI__builtin___memset_chk:
1367 case Builtin::BI__builtin___strlcat_chk:
1368 case Builtin::BI__builtin___strlcpy_chk:
1369 case Builtin::BI__builtin___strncat_chk:
1370 case Builtin::BI__builtin___strncpy_chk:
1371 case Builtin::BI__builtin___stpncpy_chk:
1372 case Builtin::BI__builtin___memccpy_chk:
1373 case Builtin::BI__builtin___mempcpy_chk: {
1374 DiagID = diag::warn_builtin_chk_overflow;
1375 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
1376 DestinationSize =
1377 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1378 IsChkVariant = true;
1379 break;
1380 }
1381
1382 case Builtin::BI__builtin___snprintf_chk:
1383 case Builtin::BI__builtin___vsnprintf_chk: {
1384 DiagID = diag::warn_builtin_chk_overflow;
1385 SourceSize = ComputeExplicitObjectSizeArgument(1);
1386 DestinationSize = ComputeExplicitObjectSizeArgument(3);
1387 IsChkVariant = true;
1388 break;
1389 }
1390
1391 case Builtin::BIstrncat:
1392 case Builtin::BI__builtin_strncat:
1393 case Builtin::BIstrncpy:
1394 case Builtin::BI__builtin_strncpy:
1395 case Builtin::BIstpncpy:
1396 case Builtin::BI__builtin_stpncpy: {
1397 // Whether these functions overflow depends on the runtime strlen of the
1398 // string, not just the buffer size, so emitting the "always overflow"
1399 // diagnostic isn't quite right. We should still diagnose passing a buffer
1400 // size larger than the destination buffer though; this is a runtime abort
1401 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1402 DiagID = diag::warn_fortify_source_size_mismatch;
1403 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1404 DestinationSize = ComputeSizeArgument(0);
1405 break;
1406 }
1407
1408 case Builtin::BImemcpy:
1409 case Builtin::BI__builtin_memcpy:
1410 case Builtin::BImemmove:
1411 case Builtin::BI__builtin_memmove:
1412 case Builtin::BImemset:
1413 case Builtin::BI__builtin_memset:
1414 case Builtin::BImempcpy:
1415 case Builtin::BI__builtin_mempcpy: {
1416 DiagID = diag::warn_fortify_source_overflow;
1417 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
1418 DestinationSize = ComputeSizeArgument(0);
1419 break;
1420 }
1421 case Builtin::BIsnprintf:
1422 case Builtin::BI__builtin_snprintf:
1423 case Builtin::BIvsnprintf:
1424 case Builtin::BI__builtin_vsnprintf: {
1425 DiagID = diag::warn_fortify_source_size_mismatch;
1426 SourceSize = ComputeExplicitObjectSizeArgument(1);
1427 const auto *FormatExpr = TheCall->getArg(Arg: 2)->IgnoreParenImpCasts();
1428 StringRef FormatStrRef;
1429 size_t StrLen;
1430 if (SourceSize &&
1431 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1432 EstimateSizeFormatHandler H(FormatStrRef);
1433 const char *FormatBytes = FormatStrRef.data();
1434 if (!analyze_format_string::ParsePrintfString(
1435 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1436 Target: Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1437 llvm::APSInt FormatSize =
1438 llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1439 .extOrTrunc(width: SizeTypeWidth);
1440 if (FormatSize > *SourceSize && *SourceSize != 0) {
1441 unsigned TruncationDiagID =
1442 H.isKernelCompatible() ? diag::warn_format_truncation
1443 : diag::warn_format_truncation_non_kprintf;
1444 SmallString<16> SpecifiedSizeStr;
1445 SmallString<16> FormatSizeStr;
1446 SourceSize->toString(Str&: SpecifiedSizeStr, /*Radix=*/10);
1447 FormatSize.toString(Str&: FormatSizeStr, /*Radix=*/10);
1448 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1449 PD: PDiag(DiagID: TruncationDiagID)
1450 << GetFunctionName() << SpecifiedSizeStr
1451 << FormatSizeStr);
1452 }
1453 }
1454 }
1455 DestinationSize = ComputeSizeArgument(0);
1456 const Expr *LenArg = TheCall->getArg(Arg: 1)->IgnoreCasts();
1457 const Expr *Dest = TheCall->getArg(Arg: 0)->IgnoreCasts();
1458 IdentifierInfo *FnInfo = FD->getIdentifier();
1459 CheckSizeofMemaccessArgument(SizeOfArg: LenArg, Dest, FnName: FnInfo);
1460 }
1461 }
1462
1463 if (!SourceSize || !DestinationSize ||
1464 llvm::APSInt::compareValues(I1: *SourceSize, I2: *DestinationSize) <= 0)
1465 return;
1466
1467 std::string FunctionName = GetFunctionName();
1468
1469 SmallString<16> DestinationStr;
1470 SmallString<16> SourceStr;
1471 DestinationSize->toString(Str&: DestinationStr, /*Radix=*/10);
1472 SourceSize->toString(Str&: SourceStr, /*Radix=*/10);
1473 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1474 PD: PDiag(DiagID)
1475 << FunctionName << DestinationStr << SourceStr);
1476}
1477
1478static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1479 Scope::ScopeFlags NeededScopeFlags,
1480 unsigned DiagID) {
1481 // Scopes aren't available during instantiation. Fortunately, builtin
1482 // functions cannot be template args so they cannot be formed through template
1483 // instantiation. Therefore checking once during the parse is sufficient.
1484 if (SemaRef.inTemplateInstantiation())
1485 return false;
1486
1487 Scope *S = SemaRef.getCurScope();
1488 while (S && !S->isSEHExceptScope())
1489 S = S->getParent();
1490 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1491 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
1492 SemaRef.Diag(Loc: TheCall->getExprLoc(), DiagID)
1493 << DRE->getDecl()->getIdentifier();
1494 return true;
1495 }
1496
1497 return false;
1498}
1499
1500// In OpenCL, __builtin_alloca_* should return a pointer to address space
1501// that corresponds to the stack address space i.e private address space.
1502static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1503 QualType RT = TheCall->getType();
1504 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1505 "__builtin_alloca has invalid address space");
1506
1507 RT = RT->getPointeeType();
1508 RT = S.Context.getAddrSpaceQualType(T: RT, AddressSpace: LangAS::opencl_private);
1509 TheCall->setType(S.Context.getPointerType(T: RT));
1510}
1511
1512static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1513 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 1))
1514 return true;
1515
1516 for (Expr *Arg : TheCall->arguments()) {
1517 // If argument is dependent on a template parameter, we can't resolve now.
1518 if (Arg->isTypeDependent() || Arg->isValueDependent())
1519 continue;
1520 // Reject void types.
1521 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1522 if (ArgTy->isVoidType())
1523 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_param_with_void_type);
1524 }
1525
1526 TheCall->setType(S.Context.getSizeType());
1527 return false;
1528}
1529
1530namespace {
1531enum PointerAuthOpKind {
1532 PAO_Strip,
1533 PAO_Sign,
1534 PAO_Auth,
1535 PAO_SignGeneric,
1536 PAO_Discriminator,
1537 PAO_BlendPointer,
1538 PAO_BlendInteger
1539};
1540}
1541
1542bool Sema::checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range) {
1543 if (getLangOpts().PointerAuthIntrinsics)
1544 return false;
1545
1546 Diag(Loc, DiagID: diag::err_ptrauth_disabled) << Range;
1547 return true;
1548}
1549
1550static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1551 return S.checkPointerAuthEnabled(Loc: E->getExprLoc(), Range: E->getSourceRange());
1552}
1553
1554static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1555 // Convert it to type 'int'.
1556 if (convertArgumentToType(S, Value&: Arg, Ty: S.Context.IntTy))
1557 return true;
1558
1559 // Value-dependent expressions are okay; wait for template instantiation.
1560 if (Arg->isValueDependent())
1561 return false;
1562
1563 unsigned KeyValue;
1564 return S.checkConstantPointerAuthKey(keyExpr: Arg, key&: KeyValue);
1565}
1566
1567bool Sema::checkConstantPointerAuthKey(Expr *Arg, unsigned &Result) {
1568 // Attempt to constant-evaluate the expression.
1569 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Ctx: Context);
1570 if (!KeyValue) {
1571 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_expr_not_ice)
1572 << 0 << Arg->getSourceRange();
1573 return true;
1574 }
1575
1576 // Ask the target to validate the key parameter.
1577 if (!Context.getTargetInfo().validatePointerAuthKey(value: *KeyValue)) {
1578 llvm::SmallString<32> Value;
1579 {
1580 llvm::raw_svector_ostream Str(Value);
1581 Str << *KeyValue;
1582 }
1583
1584 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_invalid_key)
1585 << Value << Arg->getSourceRange();
1586 return true;
1587 }
1588
1589 Result = KeyValue->getZExtValue();
1590 return false;
1591}
1592
1593bool Sema::checkPointerAuthDiscriminatorArg(Expr *Arg,
1594 PointerAuthDiscArgKind Kind,
1595 unsigned &IntVal) {
1596 if (!Arg) {
1597 IntVal = 0;
1598 return true;
1599 }
1600
1601 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
1602 if (!Result) {
1603 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_arg_not_ice);
1604 return false;
1605 }
1606
1607 unsigned Max;
1608 bool IsAddrDiscArg = false;
1609
1610 switch (Kind) {
1611 case PointerAuthDiscArgKind::Addr:
1612 Max = 1;
1613 IsAddrDiscArg = true;
1614 break;
1615 case PointerAuthDiscArgKind::Extra:
1616 Max = PointerAuthQualifier::MaxDiscriminator;
1617 break;
1618 };
1619
1620 if (*Result < 0 || *Result > Max) {
1621 if (IsAddrDiscArg)
1622 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_address_discrimination_invalid)
1623 << Result->getExtValue();
1624 else
1625 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_extra_discriminator_invalid)
1626 << Result->getExtValue() << Max;
1627
1628 return false;
1629 };
1630
1631 IntVal = Result->getZExtValue();
1632 return true;
1633}
1634
1635static std::pair<const ValueDecl *, CharUnits>
1636findConstantBaseAndOffset(Sema &S, Expr *E) {
1637 // Must evaluate as a pointer.
1638 Expr::EvalResult Result;
1639 if (!E->EvaluateAsRValue(Result, Ctx: S.Context) || !Result.Val.isLValue())
1640 return {nullptr, CharUnits()};
1641
1642 const auto *BaseDecl =
1643 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1644 if (!BaseDecl)
1645 return {nullptr, CharUnits()};
1646
1647 return {BaseDecl, Result.Val.getLValueOffset()};
1648}
1649
1650static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1651 bool RequireConstant = false) {
1652 if (Arg->hasPlaceholderType()) {
1653 ExprResult R = S.CheckPlaceholderExpr(E: Arg);
1654 if (R.isInvalid())
1655 return true;
1656 Arg = R.get();
1657 }
1658
1659 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1660 return OpKind != PAO_BlendInteger;
1661 };
1662 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1663 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1664 OpKind == PAO_SignGeneric;
1665 };
1666
1667 // Require the value to have the right range of type.
1668 QualType ExpectedTy;
1669 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1670 ExpectedTy = Arg->getType().getUnqualifiedType();
1671 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1672 ExpectedTy = S.Context.VoidPtrTy;
1673 } else if (AllowsInteger(OpKind) &&
1674 Arg->getType()->isIntegralOrUnscopedEnumerationType()) {
1675 ExpectedTy = S.Context.getUIntPtrType();
1676
1677 } else {
1678 // Diagnose the failures.
1679 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_value_bad_type)
1680 << unsigned(OpKind == PAO_Discriminator ? 1
1681 : OpKind == PAO_BlendPointer ? 2
1682 : OpKind == PAO_BlendInteger ? 3
1683 : 0)
1684 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1685 << Arg->getType() << Arg->getSourceRange();
1686 return true;
1687 }
1688
1689 // Convert to that type. This should just be an lvalue-to-rvalue
1690 // conversion.
1691 if (convertArgumentToType(S, Value&: Arg, Ty: ExpectedTy))
1692 return true;
1693
1694 if (!RequireConstant) {
1695 // Warn about null pointers for non-generic sign and auth operations.
1696 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1697 Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNull)) {
1698 S.Diag(Loc: Arg->getExprLoc(), DiagID: OpKind == PAO_Sign
1699 ? diag::warn_ptrauth_sign_null_pointer
1700 : diag::warn_ptrauth_auth_null_pointer)
1701 << Arg->getSourceRange();
1702 }
1703
1704 return false;
1705 }
1706
1707 // Perform special checking on the arguments to ptrauth_sign_constant.
1708
1709 // The main argument.
1710 if (OpKind == PAO_Sign) {
1711 // Require the value we're signing to have a special form.
1712 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Arg);
1713 bool Invalid;
1714
1715 // Must be rooted in a declaration reference.
1716 if (!BaseDecl)
1717 Invalid = true;
1718
1719 // If it's a function declaration, we can't have an offset.
1720 else if (isa<FunctionDecl>(Val: BaseDecl))
1721 Invalid = !Offset.isZero();
1722
1723 // Otherwise we're fine.
1724 else
1725 Invalid = false;
1726
1727 if (Invalid)
1728 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_pointer);
1729 return Invalid;
1730 }
1731
1732 // The discriminator argument.
1733 assert(OpKind == PAO_Discriminator);
1734
1735 // Must be a pointer or integer or blend thereof.
1736 Expr *Pointer = nullptr;
1737 Expr *Integer = nullptr;
1738 if (auto *Call = dyn_cast<CallExpr>(Val: Arg->IgnoreParens())) {
1739 if (Call->getBuiltinCallee() ==
1740 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1741 Pointer = Call->getArg(Arg: 0);
1742 Integer = Call->getArg(Arg: 1);
1743 }
1744 }
1745 if (!Pointer && !Integer) {
1746 if (Arg->getType()->isPointerType())
1747 Pointer = Arg;
1748 else
1749 Integer = Arg;
1750 }
1751
1752 // Check the pointer.
1753 bool Invalid = false;
1754 if (Pointer) {
1755 assert(Pointer->getType()->isPointerType());
1756
1757 // TODO: if we're initializing a global, check that the address is
1758 // somehow related to what we're initializing. This probably will
1759 // never really be feasible and we'll have to catch it at link-time.
1760 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Pointer);
1761 if (!BaseDecl || !isa<VarDecl>(Val: BaseDecl))
1762 Invalid = true;
1763 }
1764
1765 // Check the integer.
1766 if (Integer) {
1767 assert(Integer->getType()->isIntegerType());
1768 if (!Integer->isEvaluatable(Ctx: S.Context))
1769 Invalid = true;
1770 }
1771
1772 if (Invalid)
1773 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_discriminator);
1774 return Invalid;
1775}
1776
1777static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call) {
1778 if (S.checkArgCount(Call, DesiredArgCount: 2))
1779 return ExprError();
1780 if (checkPointerAuthEnabled(S, E: Call))
1781 return ExprError();
1782 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Strip) ||
1783 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]))
1784 return ExprError();
1785
1786 Call->setType(Call->getArgs()[0]->getType());
1787 return Call;
1788}
1789
1790static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call) {
1791 if (S.checkArgCount(Call, DesiredArgCount: 2))
1792 return ExprError();
1793 if (checkPointerAuthEnabled(S, E: Call))
1794 return ExprError();
1795 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_BlendPointer) ||
1796 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_BlendInteger))
1797 return ExprError();
1798
1799 Call->setType(S.Context.getUIntPtrType());
1800 return Call;
1801}
1802
1803static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call) {
1804 if (S.checkArgCount(Call, DesiredArgCount: 2))
1805 return ExprError();
1806 if (checkPointerAuthEnabled(S, E: Call))
1807 return ExprError();
1808 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_SignGeneric) ||
1809 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_Discriminator))
1810 return ExprError();
1811
1812 Call->setType(S.Context.getUIntPtrType());
1813 return Call;
1814}
1815
1816static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call,
1817 PointerAuthOpKind OpKind,
1818 bool RequireConstant) {
1819 if (S.checkArgCount(Call, DesiredArgCount: 3))
1820 return ExprError();
1821 if (checkPointerAuthEnabled(S, E: Call))
1822 return ExprError();
1823 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind, RequireConstant) ||
1824 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1825 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator,
1826 RequireConstant))
1827 return ExprError();
1828
1829 Call->setType(Call->getArgs()[0]->getType());
1830 return Call;
1831}
1832
1833static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call) {
1834 if (S.checkArgCount(Call, DesiredArgCount: 5))
1835 return ExprError();
1836 if (checkPointerAuthEnabled(S, E: Call))
1837 return ExprError();
1838 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
1839 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1840 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
1841 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
1842 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator))
1843 return ExprError();
1844
1845 Call->setType(Call->getArgs()[0]->getType());
1846 return Call;
1847}
1848
1849static ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call) {
1850 if (S.checkArgCount(Call, DesiredArgCount: 6))
1851 return ExprError();
1852 if (checkPointerAuthEnabled(S, E: Call))
1853 return ExprError();
1854 const Expr *AddendExpr = Call->getArg(Arg: 5);
1855 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(Ctx: S.Context);
1856 if (!AddendIsConstInt) {
1857 const Expr *Arg = Call->getArg(Arg: 5)->IgnoreParenImpCasts();
1858 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreParenCasts());
1859 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
1860 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_constant_integer_last_arg_type)
1861 << FDecl->getDeclName() << Arg->getSourceRange();
1862 }
1863 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
1864 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1865 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
1866 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
1867 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator) ||
1868 !AddendIsConstInt)
1869 return ExprError();
1870
1871 Call->setType(Call->getArgs()[0]->getType());
1872 return Call;
1873}
1874
1875static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call) {
1876 if (checkPointerAuthEnabled(S, E: Call))
1877 return ExprError();
1878
1879 // We've already performed normal call type-checking.
1880 const Expr *Arg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
1881
1882 // Operand must be an ordinary or UTF-8 string literal.
1883 const auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
1884 if (!Literal || Literal->getCharByteWidth() != 1) {
1885 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_string_not_literal)
1886 << (Literal ? 1 : 0) << Arg->getSourceRange();
1887 return ExprError();
1888 }
1889
1890 return Call;
1891}
1892
1893static ExprResult GetVTablePointer(Sema &S, CallExpr *Call) {
1894 if (S.checkArgCount(Call, DesiredArgCount: 1))
1895 return ExprError();
1896 Expr *FirstArg = Call->getArg(Arg: 0);
1897 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(E: FirstArg);
1898 if (FirstValue.isInvalid())
1899 return ExprError();
1900 Call->setArg(Arg: 0, ArgExpr: FirstValue.get());
1901 QualType FirstArgType = FirstArg->getType();
1902 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1903 FirstArgType = S.Context.getDecayedType(T: FirstArgType);
1904
1905 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
1906 if (!FirstArgRecord) {
1907 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
1908 << /*isPolymorphic=*/0 << FirstArgType;
1909 return ExprError();
1910 }
1911 if (S.RequireCompleteType(
1912 Loc: FirstArg->getBeginLoc(), T: FirstArgType->getPointeeType(),
1913 DiagID: diag::err_get_vtable_pointer_requires_complete_type)) {
1914 return ExprError();
1915 }
1916
1917 if (!FirstArgRecord->isPolymorphic()) {
1918 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
1919 << /*isPolymorphic=*/1 << FirstArgRecord;
1920 return ExprError();
1921 }
1922 QualType ReturnType = S.Context.getPointerType(T: S.Context.VoidTy.withConst());
1923 Call->setType(ReturnType);
1924 return Call;
1925}
1926
1927static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) {
1928 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
1929 return ExprError();
1930
1931 // Compute __builtin_launder's parameter type from the argument.
1932 // The parameter type is:
1933 // * The type of the argument if it's not an array or function type,
1934 // Otherwise,
1935 // * The decayed argument type.
1936 QualType ParamTy = [&]() {
1937 QualType ArgTy = TheCall->getArg(Arg: 0)->getType();
1938 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1939 return S.Context.getPointerType(T: Ty->getElementType());
1940 if (ArgTy->isFunctionType()) {
1941 return S.Context.getPointerType(T: ArgTy);
1942 }
1943 return ArgTy;
1944 }();
1945
1946 TheCall->setType(ParamTy);
1947
1948 auto DiagSelect = [&]() -> std::optional<unsigned> {
1949 if (!ParamTy->isPointerType())
1950 return 0;
1951 if (ParamTy->isFunctionPointerType())
1952 return 1;
1953 if (ParamTy->isVoidPointerType())
1954 return 2;
1955 return std::optional<unsigned>{};
1956 }();
1957 if (DiagSelect) {
1958 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_launder_invalid_arg)
1959 << *DiagSelect << TheCall->getSourceRange();
1960 return ExprError();
1961 }
1962
1963 // We either have an incomplete class type, or we have a class template
1964 // whose instantiation has not been forced. Example:
1965 //
1966 // template <class T> struct Foo { T value; };
1967 // Foo<int> *p = nullptr;
1968 // auto *d = __builtin_launder(p);
1969 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T: ParamTy->getPointeeType(),
1970 DiagID: diag::err_incomplete_type))
1971 return ExprError();
1972
1973 assert(ParamTy->getPointeeType()->isObjectType() &&
1974 "Unhandled non-object pointer case");
1975
1976 InitializedEntity Entity =
1977 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ParamTy, Consumed: false);
1978 ExprResult Arg =
1979 S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: TheCall->getArg(Arg: 0));
1980 if (Arg.isInvalid())
1981 return ExprError();
1982 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
1983
1984 return TheCall;
1985}
1986
1987static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall) {
1988 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
1989 return ExprError();
1990
1991 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
1992 if (Arg.isInvalid())
1993 return ExprError();
1994 QualType ParamTy = Arg.get()->getType();
1995 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
1996 TheCall->setType(S.Context.BoolTy);
1997
1998 // Only accept pointers to objects as arguments, which should have object
1999 // pointer or void pointer types.
2000 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2001 // LWG4138: Function pointer types not allowed
2002 if (PT->getPointeeType()->isFunctionType()) {
2003 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2004 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2005 << 1;
2006 return ExprError();
2007 }
2008 // Disallow VLAs too since those shouldn't be able to
2009 // be a template parameter for `std::is_within_lifetime`
2010 if (PT->getPointeeType()->isVariableArrayType()) {
2011 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(), DiagID: diag::err_vla_unsupported)
2012 << 1 << "__builtin_is_within_lifetime";
2013 return ExprError();
2014 }
2015 } else {
2016 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2017 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2018 << 0;
2019 return ExprError();
2020 }
2021 return TheCall;
2022}
2023
2024static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall) {
2025 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2026 return ExprError();
2027
2028 QualType Dest = TheCall->getArg(Arg: 0)->getType();
2029 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2030 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2031 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2032 << /*a pointer*/ 0;
2033 return ExprError();
2034 }
2035
2036 QualType T = Dest->getPointeeType();
2037 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T,
2038 DiagID: diag::err_incomplete_type))
2039 return ExprError();
2040
2041 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2042 T->isIncompleteArrayType()) {
2043 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2044 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2045 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2046 return ExprError();
2047 }
2048
2049 TheCall->setType(Dest);
2050
2051 QualType Src = TheCall->getArg(Arg: 1)->getType();
2052 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2053 S.Diag(Loc: TheCall->getArg(Arg: 1)->getExprLoc(),
2054 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2055 << /*the same*/ 3;
2056 return ExprError();
2057 }
2058
2059 Expr *SizeExpr = TheCall->getArg(Arg: 2);
2060 ExprResult Size = S.DefaultLvalueConversion(E: SizeExpr);
2061 if (Size.isInvalid())
2062 return ExprError();
2063
2064 Size = S.tryConvertExprToType(E: Size.get(), Ty: S.getASTContext().getSizeType());
2065 if (Size.isInvalid())
2066 return ExprError();
2067 SizeExpr = Size.get();
2068 TheCall->setArg(Arg: 2, ArgExpr: SizeExpr);
2069
2070 return TheCall;
2071}
2072
2073// Emit an error and return true if the current object format type is in the
2074// list of unsupported types.
2075static bool CheckBuiltinTargetNotInUnsupported(
2076 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2077 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2078 llvm::Triple::ObjectFormatType CurObjFormat =
2079 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2080 if (llvm::is_contained(Range&: UnsupportedObjectFormatTypes, Element: CurObjFormat)) {
2081 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2082 << TheCall->getSourceRange();
2083 return true;
2084 }
2085 return false;
2086}
2087
2088// Emit an error and return true if the current architecture is not in the list
2089// of supported architectures.
2090static bool
2091CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall,
2092 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2093 llvm::Triple::ArchType CurArch =
2094 S.getASTContext().getTargetInfo().getTriple().getArch();
2095 if (llvm::is_contained(Range&: SupportedArchs, Element: CurArch))
2096 return false;
2097 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2098 << TheCall->getSourceRange();
2099 return true;
2100}
2101
2102static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2103 SourceLocation CallSiteLoc);
2104
2105bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2106 CallExpr *TheCall) {
2107 switch (TI.getTriple().getArch()) {
2108 default:
2109 // Some builtins don't require additional checking, so just consider these
2110 // acceptable.
2111 return false;
2112 case llvm::Triple::arm:
2113 case llvm::Triple::armeb:
2114 case llvm::Triple::thumb:
2115 case llvm::Triple::thumbeb:
2116 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2117 case llvm::Triple::aarch64:
2118 case llvm::Triple::aarch64_32:
2119 case llvm::Triple::aarch64_be:
2120 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2121 case llvm::Triple::bpfeb:
2122 case llvm::Triple::bpfel:
2123 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2124 case llvm::Triple::dxil:
2125 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2126 case llvm::Triple::hexagon:
2127 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2128 case llvm::Triple::mips:
2129 case llvm::Triple::mipsel:
2130 case llvm::Triple::mips64:
2131 case llvm::Triple::mips64el:
2132 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2133 case llvm::Triple::spirv:
2134 case llvm::Triple::spirv32:
2135 case llvm::Triple::spirv64:
2136 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2137 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2138 return false;
2139 case llvm::Triple::systemz:
2140 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2141 case llvm::Triple::x86:
2142 case llvm::Triple::x86_64:
2143 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2144 case llvm::Triple::ppc:
2145 case llvm::Triple::ppcle:
2146 case llvm::Triple::ppc64:
2147 case llvm::Triple::ppc64le:
2148 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2149 case llvm::Triple::amdgcn:
2150 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2151 case llvm::Triple::riscv32:
2152 case llvm::Triple::riscv64:
2153 case llvm::Triple::riscv32be:
2154 case llvm::Triple::riscv64be:
2155 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2156 case llvm::Triple::loongarch32:
2157 case llvm::Triple::loongarch64:
2158 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2159 TheCall);
2160 case llvm::Triple::wasm32:
2161 case llvm::Triple::wasm64:
2162 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2163 case llvm::Triple::nvptx:
2164 case llvm::Triple::nvptx64:
2165 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2166 }
2167}
2168
2169static bool isValidMathElementType(QualType T) {
2170 return T->isDependentType() ||
2171 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2172}
2173
2174// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2175// not a valid type, emit an error message and return true. Otherwise return
2176// false.
2177static bool
2178checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy,
2179 Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr,
2180 int ArgOrdinal) {
2181 QualType EltTy = ArgTy;
2182 if (auto *VecTy = EltTy->getAs<VectorType>())
2183 EltTy = VecTy->getElementType();
2184
2185 switch (ArgTyRestr) {
2186 case Sema::EltwiseBuiltinArgTyRestriction::None:
2187 if (!ArgTy->getAs<VectorType>() && !isValidMathElementType(T: ArgTy)) {
2188 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2189 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2190 << ArgTy;
2191 }
2192 break;
2193 case Sema::EltwiseBuiltinArgTyRestriction::FloatTy:
2194 if (!EltTy->isRealFloatingType()) {
2195 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2196 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2197 << /* floating-point */ 1 << ArgTy;
2198 }
2199 break;
2200 case Sema::EltwiseBuiltinArgTyRestriction::IntegerTy:
2201 if (!EltTy->isIntegerType()) {
2202 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2203 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2204 << /* no fp */ 0 << ArgTy;
2205 }
2206 break;
2207 case Sema::EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy:
2208 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2209 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2210 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2211 << /* or fp */ 1 << ArgTy;
2212 }
2213 break;
2214 }
2215
2216 return false;
2217}
2218
2219/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2220/// This checks that the target supports the builtin and that the string
2221/// argument is constant and valid.
2222static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2223 const TargetInfo *AuxTI, unsigned BuiltinID) {
2224 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2225 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2226 "Expecting __builtin_cpu_...");
2227
2228 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2229 const TargetInfo *TheTI = &TI;
2230 auto SupportsBI = [=](const TargetInfo *TInfo) {
2231 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2232 (!IsCPUSupports && TInfo->supportsCpuIs()));
2233 };
2234 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2235 TheTI = AuxTI;
2236
2237 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2238 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2239 return S.Diag(Loc: TheCall->getBeginLoc(),
2240 DiagID: TI.getTriple().isOSAIX()
2241 ? diag::err_builtin_aix_os_unsupported
2242 : diag::err_builtin_target_unsupported)
2243 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2244
2245 Expr *Arg = TheCall->getArg(Arg: 0)->IgnoreParenImpCasts();
2246 // Check if the argument is a string literal.
2247 if (!isa<StringLiteral>(Val: Arg))
2248 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
2249 << Arg->getSourceRange();
2250
2251 // Check the contents of the string.
2252 StringRef Feature = cast<StringLiteral>(Val: Arg)->getString();
2253 if (IsCPUSupports && !TheTI->validateCpuSupports(Name: Feature)) {
2254 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_invalid_cpu_supports)
2255 << Arg->getSourceRange();
2256 return false;
2257 }
2258 if (!IsCPUSupports && !TheTI->validateCpuIs(Name: Feature))
2259 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_cpu_is)
2260 << Arg->getSourceRange();
2261 return false;
2262}
2263
2264/// Checks that __builtin_bswapg was called with a single argument, which is an
2265/// unsigned integer, and overrides the return value type to the integer type.
2266static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2267 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2268 return true;
2269 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2270 if (ArgRes.isInvalid())
2271 return true;
2272
2273 Expr *Arg = ArgRes.get();
2274 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2275 if (Arg->isTypeDependent())
2276 return false;
2277
2278 QualType ArgTy = Arg->getType();
2279
2280 if (!ArgTy->isIntegerType()) {
2281 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2282 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2283 << ArgTy;
2284 return true;
2285 }
2286 if (const auto *BT = dyn_cast<BitIntType>(Val&: ArgTy)) {
2287 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2288 BT->getNumBits() != 1) {
2289 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_bswapg_invalid_bit_width)
2290 << ArgTy << BT->getNumBits();
2291 return true;
2292 }
2293 }
2294 TheCall->setType(ArgTy);
2295 return false;
2296}
2297
2298/// Checks that __builtin_bitreverseg was called with a single argument, which
2299/// is an integer
2300static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2301 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2302 return true;
2303 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2304 if (ArgRes.isInvalid())
2305 return true;
2306
2307 Expr *Arg = ArgRes.get();
2308 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2309 if (Arg->isTypeDependent())
2310 return false;
2311
2312 QualType ArgTy = Arg->getType();
2313
2314 if (!ArgTy->isIntegerType()) {
2315 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2316 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2317 << ArgTy;
2318 return true;
2319 }
2320 TheCall->setType(ArgTy);
2321 return false;
2322}
2323
2324/// Checks that __builtin_popcountg was called with a single argument, which is
2325/// an unsigned integer.
2326static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2327 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2328 return true;
2329
2330 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2331 if (ArgRes.isInvalid())
2332 return true;
2333
2334 Expr *Arg = ArgRes.get();
2335 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2336
2337 QualType ArgTy = Arg->getType();
2338
2339 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2340 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2341 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2342 << ArgTy;
2343 return true;
2344 }
2345 return false;
2346}
2347
2348/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2349/// an unsigned integer, and an optional second argument, which is promoted to
2350/// an 'int'.
2351static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2352 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
2353 return true;
2354
2355 ExprResult Arg0Res = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2356 if (Arg0Res.isInvalid())
2357 return true;
2358
2359 Expr *Arg0 = Arg0Res.get();
2360 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2361
2362 QualType Arg0Ty = Arg0->getType();
2363
2364 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2365 S.Diag(Loc: Arg0->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2366 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2367 << Arg0Ty;
2368 return true;
2369 }
2370
2371 if (TheCall->getNumArgs() > 1) {
2372 ExprResult Arg1Res = S.UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
2373 if (Arg1Res.isInvalid())
2374 return true;
2375
2376 Expr *Arg1 = Arg1Res.get();
2377 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2378
2379 QualType Arg1Ty = Arg1->getType();
2380
2381 if (!Arg1Ty->isSpecificBuiltinType(K: BuiltinType::Int)) {
2382 S.Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2383 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2384 return true;
2385 }
2386 }
2387
2388 return false;
2389}
2390
2391class RotateIntegerConverter : public Sema::ContextualImplicitConverter {
2392 unsigned ArgIndex;
2393 bool OnlyUnsigned;
2394
2395 Sema::SemaDiagnosticBuilder emitError(Sema &S, SourceLocation Loc,
2396 QualType T) {
2397 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2398 << ArgIndex << /*scalar*/ 1
2399 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2400 << /*no fp*/ 0 << T;
2401 }
2402
2403public:
2404 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2405 : ContextualImplicitConverter(/*Suppress=*/false,
2406 /*SuppressConversion=*/true),
2407 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2408
2409 bool match(QualType T) override {
2410 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2411 }
2412
2413 Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2414 QualType T) override {
2415 return emitError(S, Loc, T);
2416 }
2417
2418 Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2419 QualType T) override {
2420 return emitError(S, Loc, T);
2421 }
2422
2423 Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2424 QualType T,
2425 QualType ConvTy) override {
2426 return emitError(S, Loc, T);
2427 }
2428
2429 Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2430 QualType ConvTy) override {
2431 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2432 }
2433
2434 Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2435 QualType T) override {
2436 return emitError(S, Loc, T);
2437 }
2438
2439 Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2440 QualType ConvTy) override {
2441 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2442 }
2443
2444 Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2445 QualType T,
2446 QualType ConvTy) override {
2447 llvm_unreachable("conversion functions are permitted");
2448 }
2449};
2450
2451/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2452/// arguments, that the first argument is an unsigned integer type, and that
2453/// the second argument is an integer type.
2454static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2455 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
2456 return true;
2457
2458 // First argument (value to rotate) must be unsigned integer type.
2459 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2460 ExprResult Arg0Res = S.PerformContextualImplicitConversion(
2461 Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), FromE: TheCall->getArg(Arg: 0), Converter&: Arg0Converter);
2462 if (Arg0Res.isInvalid())
2463 return true;
2464
2465 Expr *Arg0 = Arg0Res.get();
2466 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2467
2468 QualType Arg0Ty = Arg0->getType();
2469 if (!Arg0Ty->isUnsignedIntegerType())
2470 return true;
2471
2472 // Second argument (rotation count) must be integer type.
2473 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2474 ExprResult Arg1Res = S.PerformContextualImplicitConversion(
2475 Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), FromE: TheCall->getArg(Arg: 1), Converter&: Arg1Converter);
2476 if (Arg1Res.isInvalid())
2477 return true;
2478
2479 Expr *Arg1 = Arg1Res.get();
2480 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2481
2482 QualType Arg1Ty = Arg1->getType();
2483 if (!Arg1Ty->isIntegerType())
2484 return true;
2485
2486 TheCall->setType(Arg0Ty);
2487 return false;
2488}
2489
2490static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2491 unsigned Pos, bool AllowConst,
2492 bool AllowAS) {
2493 QualType MaskTy = MaskArg->getType();
2494 if (!MaskTy->isExtVectorBoolType())
2495 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2496 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2497 << MaskTy;
2498
2499 QualType PtrTy = PtrArg->getType();
2500 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2501 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2502 << Pos << "scalar pointer";
2503
2504 QualType PointeeTy = PtrTy->getPointeeType();
2505 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2506 (!AllowConst && PointeeTy.isConstQualified()) ||
2507 (!AllowAS && PointeeTy.hasAddressSpace())) {
2508 QualType Target =
2509 S.Context.getPointerType(T: PointeeTy.getAtomicUnqualifiedType());
2510 return S.Diag(Loc: PtrArg->getExprLoc(),
2511 DiagID: diag::err_typecheck_convert_incompatible)
2512 << PtrTy << Target << /*different qualifiers=*/5
2513 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2514 << PtrTy << Target;
2515 }
2516 return false;
2517}
2518
2519static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2520 bool TypeDependent = false;
2521 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2522 ExprResult Converted =
2523 S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg));
2524 if (Converted.isInvalid())
2525 return true;
2526 TheCall->setArg(Arg, ArgExpr: Converted.get());
2527 TypeDependent |= Converted.get()->isTypeDependent();
2528 }
2529
2530 if (TypeDependent)
2531 TheCall->setType(S.Context.DependentTy);
2532 return false;
2533}
2534
2535static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall) {
2536 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
2537 return ExprError();
2538
2539 if (ConvertMaskedBuiltinArgs(S, TheCall))
2540 return ExprError();
2541
2542 Expr *MaskArg = TheCall->getArg(Arg: 0);
2543 Expr *PtrArg = TheCall->getArg(Arg: 1);
2544 if (TheCall->isTypeDependent())
2545 return TheCall;
2546
2547 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 2, /*AllowConst=*/true,
2548 AllowAS: TheCall->getBuiltinCallee() ==
2549 Builtin::BI__builtin_masked_load))
2550 return ExprError();
2551
2552 QualType MaskTy = MaskArg->getType();
2553 QualType PtrTy = PtrArg->getType();
2554 QualType PointeeTy = PtrTy->getPointeeType();
2555 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2556
2557 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2558 NumElts: MaskVecTy->getNumElements());
2559 if (TheCall->getNumArgs() == 3) {
2560 Expr *PassThruArg = TheCall->getArg(Arg: 2);
2561 QualType PassThruTy = PassThruArg->getType();
2562 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2563 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2564 << /* third argument */ 3 << RetTy;
2565 }
2566
2567 TheCall->setType(RetTy);
2568 return TheCall;
2569}
2570
2571static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall) {
2572 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2573 return ExprError();
2574
2575 if (ConvertMaskedBuiltinArgs(S, TheCall))
2576 return ExprError();
2577
2578 Expr *MaskArg = TheCall->getArg(Arg: 0);
2579 Expr *ValArg = TheCall->getArg(Arg: 1);
2580 Expr *PtrArg = TheCall->getArg(Arg: 2);
2581 if (TheCall->isTypeDependent())
2582 return TheCall;
2583
2584 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/false,
2585 AllowAS: TheCall->getBuiltinCallee() ==
2586 Builtin::BI__builtin_masked_store))
2587 return ExprError();
2588
2589 QualType MaskTy = MaskArg->getType();
2590 QualType PtrTy = PtrArg->getType();
2591 QualType ValTy = ValArg->getType();
2592 if (!ValTy->isVectorType())
2593 return ExprError(
2594 S.Diag(Loc: ValArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2595 << 2 << "vector");
2596
2597 QualType PointeeTy = PtrTy->getPointeeType();
2598 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2599 QualType MemoryTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2600 NumElts: MaskVecTy->getNumElements());
2601 if (!S.Context.hasSameType(T1: ValTy.getUnqualifiedType(),
2602 T2: MemoryTy.getUnqualifiedType()))
2603 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
2604 DiagID: diag::err_vec_builtin_incompatible_vector)
2605 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2606 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
2607 TheCall->getArg(Arg: 1)->getEndLoc()));
2608
2609 TheCall->setType(S.Context.VoidTy);
2610 return TheCall;
2611}
2612
2613static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall) {
2614 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 3, MaxArgCount: 4))
2615 return ExprError();
2616
2617 if (ConvertMaskedBuiltinArgs(S, TheCall))
2618 return ExprError();
2619
2620 Expr *MaskArg = TheCall->getArg(Arg: 0);
2621 Expr *IdxArg = TheCall->getArg(Arg: 1);
2622 Expr *PtrArg = TheCall->getArg(Arg: 2);
2623 if (TheCall->isTypeDependent())
2624 return TheCall;
2625
2626 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/true,
2627 /*AllowAS=*/true))
2628 return ExprError();
2629
2630 QualType IdxTy = IdxArg->getType();
2631 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2632 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2633 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2634 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2635 << IdxTy;
2636
2637 QualType MaskTy = MaskArg->getType();
2638 QualType PtrTy = PtrArg->getType();
2639 QualType PointeeTy = PtrTy->getPointeeType();
2640 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2641 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2642 return ExprError(
2643 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2644 << S.getASTContext().BuiltinInfo.getQuotedName(
2645 ID: TheCall->getBuiltinCallee())
2646 << MaskTy << IdxTy);
2647
2648 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2649 NumElts: MaskVecTy->getNumElements());
2650 if (TheCall->getNumArgs() == 4) {
2651 Expr *PassThruArg = TheCall->getArg(Arg: 3);
2652 QualType PassThruTy = PassThruArg->getType();
2653 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2654 return S.Diag(Loc: PassThruArg->getExprLoc(),
2655 DiagID: diag::err_vec_masked_load_store_ptr)
2656 << /* fourth argument */ 4 << RetTy;
2657 }
2658
2659 TheCall->setType(RetTy);
2660 return TheCall;
2661}
2662
2663static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall) {
2664 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 4))
2665 return ExprError();
2666
2667 if (ConvertMaskedBuiltinArgs(S, TheCall))
2668 return ExprError();
2669
2670 Expr *MaskArg = TheCall->getArg(Arg: 0);
2671 Expr *IdxArg = TheCall->getArg(Arg: 1);
2672 Expr *ValArg = TheCall->getArg(Arg: 2);
2673 Expr *PtrArg = TheCall->getArg(Arg: 3);
2674 if (TheCall->isTypeDependent())
2675 return TheCall;
2676
2677 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 4, /*AllowConst=*/false,
2678 /*AllowAS=*/true))
2679 return ExprError();
2680
2681 QualType IdxTy = IdxArg->getType();
2682 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2683 if (!IdxTy->isExtVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2684 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2685 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2686 << IdxTy;
2687
2688 QualType ValTy = ValArg->getType();
2689 QualType MaskTy = MaskArg->getType();
2690 QualType PtrTy = PtrArg->getType();
2691 QualType PointeeTy = PtrTy->getPointeeType();
2692
2693 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2694 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2695 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2696 return ExprError(
2697 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2698 << S.getASTContext().BuiltinInfo.getQuotedName(
2699 ID: TheCall->getBuiltinCallee())
2700 << MaskTy << IdxTy);
2701 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2702 return ExprError(
2703 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2704 << S.getASTContext().BuiltinInfo.getQuotedName(
2705 ID: TheCall->getBuiltinCallee())
2706 << MaskTy << ValTy);
2707
2708 QualType ArgTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2709 NumElts: MaskVecTy->getNumElements());
2710 if (!S.Context.hasSameType(T1: ValTy.getUnqualifiedType(), T2: ArgTy))
2711 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
2712 DiagID: diag::err_vec_builtin_incompatible_vector)
2713 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2714 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
2715 TheCall->getArg(Arg: 1)->getEndLoc()));
2716
2717 TheCall->setType(S.Context.VoidTy);
2718 return TheCall;
2719}
2720
2721static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall) {
2722 SourceLocation Loc = TheCall->getBeginLoc();
2723 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2724 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2725
2726 if (Args.size() == 0) {
2727 S.Diag(Loc: TheCall->getBeginLoc(),
2728 DiagID: diag::err_typecheck_call_too_few_args_at_least)
2729 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2730 << /*is_non_object=*/0 << TheCall->getSourceRange();
2731 return ExprError();
2732 }
2733
2734 QualType FuncT = Args[0]->getType();
2735
2736 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2737 if (Args.size() < 2) {
2738 S.Diag(Loc: TheCall->getBeginLoc(),
2739 DiagID: diag::err_typecheck_call_too_few_args_at_least)
2740 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2741 << /*is_non_object=*/0 << TheCall->getSourceRange();
2742 return ExprError();
2743 }
2744
2745 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2746 QualType ObjectT = Args[1]->getType();
2747
2748 if (MPT->isMemberDataPointer() && S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
2749 return ExprError();
2750
2751 ExprResult ObjectArg = [&]() -> ExprResult {
2752 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2753 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2754 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2755 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2756 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2757 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2758 if (S.Context.hasSameType(T1: QualType(MemPtrClass, 0),
2759 T2: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc)) ||
2760 S.BuiltinIsBaseOf(RhsTLoc: Args[1]->getBeginLoc(), LhsT: QualType(MemPtrClass, 0),
2761 RhsT: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc))) {
2762 return Args[1];
2763 }
2764
2765 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2766 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2767 // reference_wrapper;
2768 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2769 if (RD->isInStdNamespace() &&
2770 RD->getDeclName().getAsString() == "reference_wrapper") {
2771 CXXScopeSpec SS;
2772 IdentifierInfo *GetName = &S.Context.Idents.get(Name: "get");
2773 UnqualifiedId GetID;
2774 GetID.setIdentifier(Id: GetName, IdLoc: Loc);
2775
2776 ExprResult MemExpr = S.ActOnMemberAccessExpr(
2777 S: S.getCurScope(), Base: Args[1], OpLoc: Loc, OpKind: tok::period, SS,
2778 /*TemplateKWLoc=*/SourceLocation(), Member&: GetID, ObjCImpDecl: nullptr);
2779
2780 if (MemExpr.isInvalid())
2781 return ExprError();
2782
2783 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemExpr.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
2784 }
2785 }
2786
2787 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2788 // class T and t1 does not satisfy the previous two items;
2789
2790 return S.ActOnUnaryOp(S: S.getCurScope(), OpLoc: Loc, Op: tok::star, Input: Args[1]);
2791 }();
2792
2793 if (ObjectArg.isInvalid())
2794 return ExprError();
2795
2796 ExprResult BinOp = S.ActOnBinOp(S: S.getCurScope(), TokLoc: TheCall->getBeginLoc(),
2797 Kind: tok::periodstar, LHSExpr: ObjectArg.get(), RHSExpr: Args[0]);
2798 if (BinOp.isInvalid())
2799 return ExprError();
2800
2801 if (MPT->isMemberDataPointer())
2802 return BinOp;
2803
2804 auto *MemCall = new (S.Context)
2805 ParenExpr(SourceLocation(), SourceLocation(), BinOp.get());
2806
2807 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemCall, LParenLoc: TheCall->getBeginLoc(),
2808 ArgExprs: Args.drop_front(N: 2), RParenLoc: TheCall->getRParenLoc());
2809 }
2810 return S.ActOnCallExpr(S: S.getCurScope(), Fn: Args.front(), LParenLoc: TheCall->getBeginLoc(),
2811 ArgExprs: Args.drop_front(), RParenLoc: TheCall->getRParenLoc());
2812}
2813
2814// Performs a similar job to Sema::UsualUnaryConversions, but without any
2815// implicit promotion of integral/enumeration types.
2816static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E) {
2817 // First, convert to an r-value.
2818 ExprResult Res = S.DefaultFunctionArrayLvalueConversion(E);
2819 if (Res.isInvalid())
2820 return ExprError();
2821
2822 // Promote floating-point types.
2823 return S.UsualUnaryFPConversions(E: Res.get());
2824}
2825
2826static QualType getVectorElementType(ASTContext &Context, QualType VecTy) {
2827 if (const auto *TyA = VecTy->getAs<VectorType>())
2828 return TyA->getElementType();
2829 if (VecTy->isSizelessVectorType())
2830 return VecTy->getSizelessVectorEltType(Ctx: Context);
2831 return QualType();
2832}
2833
2834ExprResult
2835Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2836 CallExpr *TheCall) {
2837 ExprResult TheCallResult(TheCall);
2838
2839 // Find out if any arguments are required to be integer constant expressions.
2840 unsigned ICEArguments = 0;
2841 ASTContext::GetBuiltinTypeError Error;
2842 Context.GetBuiltinType(ID: BuiltinID, Error, IntegerConstantArgs: &ICEArguments);
2843 if (Error != ASTContext::GE_None)
2844 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2845
2846 // If any arguments are required to be ICE's, check and diagnose.
2847 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2848 // Skip arguments not required to be ICE's.
2849 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2850
2851 llvm::APSInt Result;
2852 // If we don't have enough arguments, continue so we can issue better
2853 // diagnostic in checkArgCount(...)
2854 if (ArgNo < TheCall->getNumArgs() &&
2855 BuiltinConstantArg(TheCall, ArgNum: ArgNo, Result))
2856 return true;
2857 ICEArguments &= ~(1 << ArgNo);
2858 }
2859
2860 FPOptions FPO;
2861 switch (BuiltinID) {
2862 case Builtin::BI__builtin_cpu_supports:
2863 case Builtin::BI__builtin_cpu_is:
2864 if (BuiltinCpu(S&: *this, TI: Context.getTargetInfo(), TheCall,
2865 AuxTI: Context.getAuxTargetInfo(), BuiltinID))
2866 return ExprError();
2867 break;
2868 case Builtin::BI__builtin_cpu_init:
2869 if (!Context.getTargetInfo().supportsCpuInit()) {
2870 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2871 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2872 return ExprError();
2873 }
2874 break;
2875 case Builtin::BI__builtin___CFStringMakeConstantString:
2876 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2877 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2878 if (CheckBuiltinTargetNotInUnsupported(
2879 S&: *this, BuiltinID, TheCall,
2880 UnsupportedObjectFormatTypes: {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2881 return ExprError();
2882 assert(TheCall->getNumArgs() == 1 &&
2883 "Wrong # arguments to builtin CFStringMakeConstantString");
2884 if (ObjC().CheckObjCString(Arg: TheCall->getArg(Arg: 0)))
2885 return ExprError();
2886 break;
2887 case Builtin::BI__builtin_ms_va_start:
2888 case Builtin::BI__builtin_stdarg_start:
2889 case Builtin::BI__builtin_va_start:
2890 case Builtin::BI__builtin_c23_va_start:
2891 if (BuiltinVAStart(BuiltinID, TheCall))
2892 return ExprError();
2893 break;
2894 case Builtin::BI__va_start: {
2895 switch (Context.getTargetInfo().getTriple().getArch()) {
2896 case llvm::Triple::aarch64:
2897 case llvm::Triple::arm:
2898 case llvm::Triple::thumb:
2899 if (BuiltinVAStartARMMicrosoft(Call: TheCall))
2900 return ExprError();
2901 break;
2902 default:
2903 if (BuiltinVAStart(BuiltinID, TheCall))
2904 return ExprError();
2905 break;
2906 }
2907 break;
2908 }
2909
2910 // The acquire, release, and no fence variants are ARM and AArch64 only.
2911 case Builtin::BI_interlockedbittestandset_acq:
2912 case Builtin::BI_interlockedbittestandset_rel:
2913 case Builtin::BI_interlockedbittestandset_nf:
2914 case Builtin::BI_interlockedbittestandreset_acq:
2915 case Builtin::BI_interlockedbittestandreset_rel:
2916 case Builtin::BI_interlockedbittestandreset_nf:
2917 if (CheckBuiltinTargetInSupported(
2918 S&: *this, TheCall,
2919 SupportedArchs: {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2920 return ExprError();
2921 break;
2922
2923 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2924 case Builtin::BI_bittest64:
2925 case Builtin::BI_bittestandcomplement64:
2926 case Builtin::BI_bittestandreset64:
2927 case Builtin::BI_bittestandset64:
2928 case Builtin::BI_interlockedbittestandreset64:
2929 case Builtin::BI_interlockedbittestandset64:
2930 if (CheckBuiltinTargetInSupported(
2931 S&: *this, TheCall,
2932 SupportedArchs: {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2933 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2934 return ExprError();
2935 break;
2936
2937 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2938 case Builtin::BI_interlockedbittestandreset64_acq:
2939 case Builtin::BI_interlockedbittestandreset64_rel:
2940 case Builtin::BI_interlockedbittestandreset64_nf:
2941 case Builtin::BI_interlockedbittestandset64_acq:
2942 case Builtin::BI_interlockedbittestandset64_rel:
2943 case Builtin::BI_interlockedbittestandset64_nf:
2944 if (CheckBuiltinTargetInSupported(S&: *this, TheCall, SupportedArchs: {llvm::Triple::aarch64}))
2945 return ExprError();
2946 break;
2947
2948 case Builtin::BI__builtin_set_flt_rounds:
2949 if (CheckBuiltinTargetInSupported(
2950 S&: *this, TheCall,
2951 SupportedArchs: {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2952 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
2953 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
2954 llvm::Triple::ppc64le}))
2955 return ExprError();
2956 break;
2957
2958 case Builtin::BI__builtin_isgreater:
2959 case Builtin::BI__builtin_isgreaterequal:
2960 case Builtin::BI__builtin_isless:
2961 case Builtin::BI__builtin_islessequal:
2962 case Builtin::BI__builtin_islessgreater:
2963 case Builtin::BI__builtin_isunordered:
2964 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2965 return ExprError();
2966 break;
2967 case Builtin::BI__builtin_fpclassify:
2968 if (BuiltinFPClassification(TheCall, NumArgs: 6, BuiltinID))
2969 return ExprError();
2970 break;
2971 case Builtin::BI__builtin_isfpclass:
2972 if (BuiltinFPClassification(TheCall, NumArgs: 2, BuiltinID))
2973 return ExprError();
2974 break;
2975 case Builtin::BI__builtin_isfinite:
2976 case Builtin::BI__builtin_isinf:
2977 case Builtin::BI__builtin_isinf_sign:
2978 case Builtin::BI__builtin_isnan:
2979 case Builtin::BI__builtin_issignaling:
2980 case Builtin::BI__builtin_isnormal:
2981 case Builtin::BI__builtin_issubnormal:
2982 case Builtin::BI__builtin_iszero:
2983 case Builtin::BI__builtin_signbit:
2984 case Builtin::BI__builtin_signbitf:
2985 case Builtin::BI__builtin_signbitl:
2986 if (BuiltinFPClassification(TheCall, NumArgs: 1, BuiltinID))
2987 return ExprError();
2988 break;
2989 case Builtin::BI__builtin_shufflevector:
2990 return BuiltinShuffleVector(TheCall);
2991 // TheCall will be freed by the smart pointer here, but that's fine, since
2992 // BuiltinShuffleVector guts it, but then doesn't release it.
2993 case Builtin::BI__builtin_masked_load:
2994 case Builtin::BI__builtin_masked_expand_load:
2995 return BuiltinMaskedLoad(S&: *this, TheCall);
2996 case Builtin::BI__builtin_masked_store:
2997 case Builtin::BI__builtin_masked_compress_store:
2998 return BuiltinMaskedStore(S&: *this, TheCall);
2999 case Builtin::BI__builtin_masked_gather:
3000 return BuiltinMaskedGather(S&: *this, TheCall);
3001 case Builtin::BI__builtin_masked_scatter:
3002 return BuiltinMaskedScatter(S&: *this, TheCall);
3003 case Builtin::BI__builtin_invoke:
3004 return BuiltinInvoke(S&: *this, TheCall);
3005 case Builtin::BI__builtin_prefetch:
3006 if (BuiltinPrefetch(TheCall))
3007 return ExprError();
3008 break;
3009 case Builtin::BI__builtin_alloca_with_align:
3010 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3011 if (BuiltinAllocaWithAlign(TheCall))
3012 return ExprError();
3013 [[fallthrough]];
3014 case Builtin::BI__builtin_alloca:
3015 case Builtin::BI__builtin_alloca_uninitialized:
3016 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca)
3017 << TheCall->getDirectCallee();
3018 if (getLangOpts().OpenCL) {
3019 builtinAllocaAddrSpace(S&: *this, TheCall);
3020 }
3021 break;
3022 case Builtin::BI__builtin_infer_alloc_token:
3023 if (checkBuiltinInferAllocToken(S&: *this, TheCall))
3024 return ExprError();
3025 break;
3026 case Builtin::BI__arithmetic_fence:
3027 if (BuiltinArithmeticFence(TheCall))
3028 return ExprError();
3029 break;
3030 case Builtin::BI__assume:
3031 case Builtin::BI__builtin_assume:
3032 if (BuiltinAssume(TheCall))
3033 return ExprError();
3034 break;
3035 case Builtin::BI__builtin_assume_aligned:
3036 if (BuiltinAssumeAligned(TheCall))
3037 return ExprError();
3038 break;
3039 case Builtin::BI__builtin_dynamic_object_size:
3040 case Builtin::BI__builtin_object_size:
3041 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: 3))
3042 return ExprError();
3043 break;
3044 case Builtin::BI__builtin_longjmp:
3045 if (BuiltinLongjmp(TheCall))
3046 return ExprError();
3047 break;
3048 case Builtin::BI__builtin_setjmp:
3049 if (BuiltinSetjmp(TheCall))
3050 return ExprError();
3051 break;
3052 case Builtin::BI__builtin_classify_type:
3053 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3054 return true;
3055 TheCall->setType(Context.IntTy);
3056 break;
3057 case Builtin::BI__builtin_complex:
3058 if (BuiltinComplex(TheCall))
3059 return ExprError();
3060 break;
3061 case Builtin::BI__builtin_constant_p: {
3062 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3063 return true;
3064 ExprResult Arg = DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
3065 if (Arg.isInvalid()) return true;
3066 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
3067 TheCall->setType(Context.IntTy);
3068 break;
3069 }
3070 case Builtin::BI__builtin_launder:
3071 return BuiltinLaunder(S&: *this, TheCall);
3072 case Builtin::BI__builtin_is_within_lifetime:
3073 return BuiltinIsWithinLifetime(S&: *this, TheCall);
3074 case Builtin::BI__builtin_trivially_relocate:
3075 return BuiltinTriviallyRelocate(S&: *this, TheCall);
3076
3077 case Builtin::BI__sync_fetch_and_add:
3078 case Builtin::BI__sync_fetch_and_add_1:
3079 case Builtin::BI__sync_fetch_and_add_2:
3080 case Builtin::BI__sync_fetch_and_add_4:
3081 case Builtin::BI__sync_fetch_and_add_8:
3082 case Builtin::BI__sync_fetch_and_add_16:
3083 case Builtin::BI__sync_fetch_and_sub:
3084 case Builtin::BI__sync_fetch_and_sub_1:
3085 case Builtin::BI__sync_fetch_and_sub_2:
3086 case Builtin::BI__sync_fetch_and_sub_4:
3087 case Builtin::BI__sync_fetch_and_sub_8:
3088 case Builtin::BI__sync_fetch_and_sub_16:
3089 case Builtin::BI__sync_fetch_and_or:
3090 case Builtin::BI__sync_fetch_and_or_1:
3091 case Builtin::BI__sync_fetch_and_or_2:
3092 case Builtin::BI__sync_fetch_and_or_4:
3093 case Builtin::BI__sync_fetch_and_or_8:
3094 case Builtin::BI__sync_fetch_and_or_16:
3095 case Builtin::BI__sync_fetch_and_and:
3096 case Builtin::BI__sync_fetch_and_and_1:
3097 case Builtin::BI__sync_fetch_and_and_2:
3098 case Builtin::BI__sync_fetch_and_and_4:
3099 case Builtin::BI__sync_fetch_and_and_8:
3100 case Builtin::BI__sync_fetch_and_and_16:
3101 case Builtin::BI__sync_fetch_and_xor:
3102 case Builtin::BI__sync_fetch_and_xor_1:
3103 case Builtin::BI__sync_fetch_and_xor_2:
3104 case Builtin::BI__sync_fetch_and_xor_4:
3105 case Builtin::BI__sync_fetch_and_xor_8:
3106 case Builtin::BI__sync_fetch_and_xor_16:
3107 case Builtin::BI__sync_fetch_and_nand:
3108 case Builtin::BI__sync_fetch_and_nand_1:
3109 case Builtin::BI__sync_fetch_and_nand_2:
3110 case Builtin::BI__sync_fetch_and_nand_4:
3111 case Builtin::BI__sync_fetch_and_nand_8:
3112 case Builtin::BI__sync_fetch_and_nand_16:
3113 case Builtin::BI__sync_add_and_fetch:
3114 case Builtin::BI__sync_add_and_fetch_1:
3115 case Builtin::BI__sync_add_and_fetch_2:
3116 case Builtin::BI__sync_add_and_fetch_4:
3117 case Builtin::BI__sync_add_and_fetch_8:
3118 case Builtin::BI__sync_add_and_fetch_16:
3119 case Builtin::BI__sync_sub_and_fetch:
3120 case Builtin::BI__sync_sub_and_fetch_1:
3121 case Builtin::BI__sync_sub_and_fetch_2:
3122 case Builtin::BI__sync_sub_and_fetch_4:
3123 case Builtin::BI__sync_sub_and_fetch_8:
3124 case Builtin::BI__sync_sub_and_fetch_16:
3125 case Builtin::BI__sync_and_and_fetch:
3126 case Builtin::BI__sync_and_and_fetch_1:
3127 case Builtin::BI__sync_and_and_fetch_2:
3128 case Builtin::BI__sync_and_and_fetch_4:
3129 case Builtin::BI__sync_and_and_fetch_8:
3130 case Builtin::BI__sync_and_and_fetch_16:
3131 case Builtin::BI__sync_or_and_fetch:
3132 case Builtin::BI__sync_or_and_fetch_1:
3133 case Builtin::BI__sync_or_and_fetch_2:
3134 case Builtin::BI__sync_or_and_fetch_4:
3135 case Builtin::BI__sync_or_and_fetch_8:
3136 case Builtin::BI__sync_or_and_fetch_16:
3137 case Builtin::BI__sync_xor_and_fetch:
3138 case Builtin::BI__sync_xor_and_fetch_1:
3139 case Builtin::BI__sync_xor_and_fetch_2:
3140 case Builtin::BI__sync_xor_and_fetch_4:
3141 case Builtin::BI__sync_xor_and_fetch_8:
3142 case Builtin::BI__sync_xor_and_fetch_16:
3143 case Builtin::BI__sync_nand_and_fetch:
3144 case Builtin::BI__sync_nand_and_fetch_1:
3145 case Builtin::BI__sync_nand_and_fetch_2:
3146 case Builtin::BI__sync_nand_and_fetch_4:
3147 case Builtin::BI__sync_nand_and_fetch_8:
3148 case Builtin::BI__sync_nand_and_fetch_16:
3149 case Builtin::BI__sync_val_compare_and_swap:
3150 case Builtin::BI__sync_val_compare_and_swap_1:
3151 case Builtin::BI__sync_val_compare_and_swap_2:
3152 case Builtin::BI__sync_val_compare_and_swap_4:
3153 case Builtin::BI__sync_val_compare_and_swap_8:
3154 case Builtin::BI__sync_val_compare_and_swap_16:
3155 case Builtin::BI__sync_bool_compare_and_swap:
3156 case Builtin::BI__sync_bool_compare_and_swap_1:
3157 case Builtin::BI__sync_bool_compare_and_swap_2:
3158 case Builtin::BI__sync_bool_compare_and_swap_4:
3159 case Builtin::BI__sync_bool_compare_and_swap_8:
3160 case Builtin::BI__sync_bool_compare_and_swap_16:
3161 case Builtin::BI__sync_lock_test_and_set:
3162 case Builtin::BI__sync_lock_test_and_set_1:
3163 case Builtin::BI__sync_lock_test_and_set_2:
3164 case Builtin::BI__sync_lock_test_and_set_4:
3165 case Builtin::BI__sync_lock_test_and_set_8:
3166 case Builtin::BI__sync_lock_test_and_set_16:
3167 case Builtin::BI__sync_lock_release:
3168 case Builtin::BI__sync_lock_release_1:
3169 case Builtin::BI__sync_lock_release_2:
3170 case Builtin::BI__sync_lock_release_4:
3171 case Builtin::BI__sync_lock_release_8:
3172 case Builtin::BI__sync_lock_release_16:
3173 case Builtin::BI__sync_swap:
3174 case Builtin::BI__sync_swap_1:
3175 case Builtin::BI__sync_swap_2:
3176 case Builtin::BI__sync_swap_4:
3177 case Builtin::BI__sync_swap_8:
3178 case Builtin::BI__sync_swap_16:
3179 return BuiltinAtomicOverloaded(TheCallResult);
3180 case Builtin::BI__sync_synchronize:
3181 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
3182 << TheCall->getCallee()->getSourceRange();
3183 break;
3184 case Builtin::BI__builtin_nontemporal_load:
3185 case Builtin::BI__builtin_nontemporal_store:
3186 return BuiltinNontemporalOverloaded(TheCallResult);
3187 case Builtin::BI__builtin_memcpy_inline: {
3188 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3189 // We warn about copying to or from `nullptr` pointers when `size` is
3190 // greater than 0. When `size` is value dependent we cannot evaluate its
3191 // value so we bail out.
3192 if (SizeOp->isValueDependent())
3193 break;
3194 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero()) {
3195 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3196 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 1), CallSiteLoc: TheCall->getExprLoc());
3197 }
3198 break;
3199 }
3200 case Builtin::BI__builtin_memset_inline: {
3201 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3202 // We warn about filling to `nullptr` pointers when `size` is greater than
3203 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3204 // out.
3205 if (SizeOp->isValueDependent())
3206 break;
3207 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero())
3208 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3209 break;
3210 }
3211#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3212 case Builtin::BI##ID: \
3213 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3214#include "clang/Basic/Builtins.inc"
3215 case Builtin::BI__annotation:
3216 if (BuiltinMSVCAnnotation(S&: *this, TheCall))
3217 return ExprError();
3218 break;
3219 case Builtin::BI__builtin_annotation:
3220 if (BuiltinAnnotation(S&: *this, TheCall))
3221 return ExprError();
3222 break;
3223 case Builtin::BI__builtin_addressof:
3224 if (BuiltinAddressof(S&: *this, TheCall))
3225 return ExprError();
3226 break;
3227 case Builtin::BI__builtin_function_start:
3228 if (BuiltinFunctionStart(S&: *this, TheCall))
3229 return ExprError();
3230 break;
3231 case Builtin::BI__builtin_is_aligned:
3232 case Builtin::BI__builtin_align_up:
3233 case Builtin::BI__builtin_align_down:
3234 if (BuiltinAlignment(S&: *this, TheCall, ID: BuiltinID))
3235 return ExprError();
3236 break;
3237 case Builtin::BI__builtin_add_overflow:
3238 case Builtin::BI__builtin_sub_overflow:
3239 case Builtin::BI__builtin_mul_overflow:
3240 if (BuiltinOverflow(S&: *this, TheCall, BuiltinID))
3241 return ExprError();
3242 break;
3243 case Builtin::BI__builtin_operator_new:
3244 case Builtin::BI__builtin_operator_delete: {
3245 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3246 ExprResult Res =
3247 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3248 return Res;
3249 }
3250 case Builtin::BI__builtin_dump_struct:
3251 return BuiltinDumpStruct(S&: *this, TheCall);
3252 case Builtin::BI__builtin_expect_with_probability: {
3253 // We first want to ensure we are called with 3 arguments
3254 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
3255 return ExprError();
3256 // then check probability is constant float in range [0.0, 1.0]
3257 const Expr *ProbArg = TheCall->getArg(Arg: 2);
3258 SmallVector<PartialDiagnosticAt, 8> Notes;
3259 Expr::EvalResult Eval;
3260 Eval.Diag = &Notes;
3261 if ((!ProbArg->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context)) ||
3262 !Eval.Val.isFloat()) {
3263 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_not_constant_float)
3264 << ProbArg->getSourceRange();
3265 for (const PartialDiagnosticAt &PDiag : Notes)
3266 Diag(Loc: PDiag.first, PD: PDiag.second);
3267 return ExprError();
3268 }
3269 llvm::APFloat Probability = Eval.Val.getFloat();
3270 bool LoseInfo = false;
3271 Probability.convert(ToSemantics: llvm::APFloat::IEEEdouble(),
3272 RM: llvm::RoundingMode::Dynamic, losesInfo: &LoseInfo);
3273 if (!(Probability >= llvm::APFloat(0.0) &&
3274 Probability <= llvm::APFloat(1.0))) {
3275 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_out_of_range)
3276 << ProbArg->getSourceRange();
3277 return ExprError();
3278 }
3279 break;
3280 }
3281 case Builtin::BI__builtin_preserve_access_index:
3282 if (BuiltinPreserveAI(S&: *this, TheCall))
3283 return ExprError();
3284 break;
3285 case Builtin::BI__builtin_call_with_static_chain:
3286 if (BuiltinCallWithStaticChain(S&: *this, BuiltinCall: TheCall))
3287 return ExprError();
3288 break;
3289 case Builtin::BI__exception_code:
3290 case Builtin::BI_exception_code:
3291 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHExceptScope,
3292 DiagID: diag::err_seh___except_block))
3293 return ExprError();
3294 break;
3295 case Builtin::BI__exception_info:
3296 case Builtin::BI_exception_info:
3297 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHFilterScope,
3298 DiagID: diag::err_seh___except_filter))
3299 return ExprError();
3300 break;
3301 case Builtin::BI__GetExceptionInfo:
3302 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3303 return ExprError();
3304
3305 if (CheckCXXThrowOperand(
3306 ThrowLoc: TheCall->getBeginLoc(),
3307 ThrowTy: Context.getExceptionObjectType(T: FDecl->getParamDecl(i: 0)->getType()),
3308 E: TheCall))
3309 return ExprError();
3310
3311 TheCall->setType(Context.VoidPtrTy);
3312 break;
3313 case Builtin::BIaddressof:
3314 case Builtin::BI__addressof:
3315 case Builtin::BIforward:
3316 case Builtin::BIforward_like:
3317 case Builtin::BImove:
3318 case Builtin::BImove_if_noexcept:
3319 case Builtin::BIas_const: {
3320 // These are all expected to be of the form
3321 // T &/&&/* f(U &/&&)
3322 // where T and U only differ in qualification.
3323 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3324 return ExprError();
3325 QualType Param = FDecl->getParamDecl(i: 0)->getType();
3326 QualType Result = FDecl->getReturnType();
3327 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3328 BuiltinID == Builtin::BI__addressof;
3329 if (!(Param->isReferenceType() &&
3330 (ReturnsPointer ? Result->isAnyPointerType()
3331 : Result->isReferenceType()) &&
3332 Context.hasSameUnqualifiedType(T1: Param->getPointeeType(),
3333 T2: Result->getPointeeType()))) {
3334 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_move_forward_unsupported)
3335 << FDecl;
3336 return ExprError();
3337 }
3338 break;
3339 }
3340 case Builtin::BI__builtin_ptrauth_strip:
3341 return PointerAuthStrip(S&: *this, Call: TheCall);
3342 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3343 return PointerAuthBlendDiscriminator(S&: *this, Call: TheCall);
3344 case Builtin::BI__builtin_ptrauth_sign_constant:
3345 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3346 /*RequireConstant=*/true);
3347 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3348 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3349 /*RequireConstant=*/false);
3350 case Builtin::BI__builtin_ptrauth_auth:
3351 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Auth,
3352 /*RequireConstant=*/false);
3353 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3354 return PointerAuthSignGenericData(S&: *this, Call: TheCall);
3355 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3356 return PointerAuthAuthAndResign(S&: *this, Call: TheCall);
3357 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3358 return PointerAuthAuthLoadRelativeAndSign(S&: *this, Call: TheCall);
3359 case Builtin::BI__builtin_ptrauth_string_discriminator:
3360 return PointerAuthStringDiscriminator(S&: *this, Call: TheCall);
3361
3362 case Builtin::BI__builtin_get_vtable_pointer:
3363 return GetVTablePointer(S&: *this, Call: TheCall);
3364
3365 // OpenCL v2.0, s6.13.16 - Pipe functions
3366 case Builtin::BIread_pipe:
3367 case Builtin::BIwrite_pipe:
3368 // Since those two functions are declared with var args, we need a semantic
3369 // check for the argument.
3370 if (OpenCL().checkBuiltinRWPipe(Call: TheCall))
3371 return ExprError();
3372 break;
3373 case Builtin::BIreserve_read_pipe:
3374 case Builtin::BIreserve_write_pipe:
3375 case Builtin::BIwork_group_reserve_read_pipe:
3376 case Builtin::BIwork_group_reserve_write_pipe:
3377 if (OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3378 return ExprError();
3379 break;
3380 case Builtin::BIsub_group_reserve_read_pipe:
3381 case Builtin::BIsub_group_reserve_write_pipe:
3382 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3383 OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3384 return ExprError();
3385 break;
3386 case Builtin::BIcommit_read_pipe:
3387 case Builtin::BIcommit_write_pipe:
3388 case Builtin::BIwork_group_commit_read_pipe:
3389 case Builtin::BIwork_group_commit_write_pipe:
3390 if (OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3391 return ExprError();
3392 break;
3393 case Builtin::BIsub_group_commit_read_pipe:
3394 case Builtin::BIsub_group_commit_write_pipe:
3395 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3396 OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3397 return ExprError();
3398 break;
3399 case Builtin::BIget_pipe_num_packets:
3400 case Builtin::BIget_pipe_max_packets:
3401 if (OpenCL().checkBuiltinPipePackets(Call: TheCall))
3402 return ExprError();
3403 break;
3404 case Builtin::BIto_global:
3405 case Builtin::BIto_local:
3406 case Builtin::BIto_private:
3407 if (OpenCL().checkBuiltinToAddr(BuiltinID, Call: TheCall))
3408 return ExprError();
3409 break;
3410 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3411 case Builtin::BIenqueue_kernel:
3412 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3413 return ExprError();
3414 break;
3415 case Builtin::BIget_kernel_work_group_size:
3416 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3417 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3418 return ExprError();
3419 break;
3420 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3421 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3422 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3423 return ExprError();
3424 break;
3425 case Builtin::BI__builtin_os_log_format:
3426 Cleanup.setExprNeedsCleanups(true);
3427 [[fallthrough]];
3428 case Builtin::BI__builtin_os_log_format_buffer_size:
3429 if (BuiltinOSLogFormat(TheCall))
3430 return ExprError();
3431 break;
3432 case Builtin::BI__builtin_frame_address:
3433 case Builtin::BI__builtin_return_address: {
3434 if (BuiltinConstantArgRange(TheCall, ArgNum: 0, Low: 0, High: 0xFFFF))
3435 return ExprError();
3436
3437 // -Wframe-address warning if non-zero passed to builtin
3438 // return/frame address.
3439 Expr::EvalResult Result;
3440 if (!TheCall->getArg(Arg: 0)->isValueDependent() &&
3441 TheCall->getArg(Arg: 0)->EvaluateAsInt(Result, Ctx: getASTContext()) &&
3442 Result.Val.getInt() != 0)
3443 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_frame_address)
3444 << ((BuiltinID == Builtin::BI__builtin_return_address)
3445 ? "__builtin_return_address"
3446 : "__builtin_frame_address")
3447 << TheCall->getSourceRange();
3448 break;
3449 }
3450
3451 case Builtin::BI__builtin_nondeterministic_value: {
3452 if (BuiltinNonDeterministicValue(TheCall))
3453 return ExprError();
3454 break;
3455 }
3456
3457 // __builtin_elementwise_abs restricts the element type to signed integers or
3458 // floating point types only.
3459 case Builtin::BI__builtin_elementwise_abs:
3460 if (PrepareBuiltinElementwiseMathOneArgCall(
3461 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy))
3462 return ExprError();
3463 break;
3464
3465 // These builtins restrict the element type to floating point
3466 // types only.
3467 case Builtin::BI__builtin_elementwise_acos:
3468 case Builtin::BI__builtin_elementwise_asin:
3469 case Builtin::BI__builtin_elementwise_atan:
3470 case Builtin::BI__builtin_elementwise_ceil:
3471 case Builtin::BI__builtin_elementwise_cos:
3472 case Builtin::BI__builtin_elementwise_cosh:
3473 case Builtin::BI__builtin_elementwise_exp:
3474 case Builtin::BI__builtin_elementwise_exp2:
3475 case Builtin::BI__builtin_elementwise_exp10:
3476 case Builtin::BI__builtin_elementwise_floor:
3477 case Builtin::BI__builtin_elementwise_log:
3478 case Builtin::BI__builtin_elementwise_log2:
3479 case Builtin::BI__builtin_elementwise_log10:
3480 case Builtin::BI__builtin_elementwise_roundeven:
3481 case Builtin::BI__builtin_elementwise_round:
3482 case Builtin::BI__builtin_elementwise_rint:
3483 case Builtin::BI__builtin_elementwise_nearbyint:
3484 case Builtin::BI__builtin_elementwise_sin:
3485 case Builtin::BI__builtin_elementwise_sinh:
3486 case Builtin::BI__builtin_elementwise_sqrt:
3487 case Builtin::BI__builtin_elementwise_tan:
3488 case Builtin::BI__builtin_elementwise_tanh:
3489 case Builtin::BI__builtin_elementwise_trunc:
3490 case Builtin::BI__builtin_elementwise_canonicalize:
3491 if (PrepareBuiltinElementwiseMathOneArgCall(
3492 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3493 return ExprError();
3494 break;
3495 case Builtin::BI__builtin_elementwise_fma:
3496 if (BuiltinElementwiseTernaryMath(TheCall))
3497 return ExprError();
3498 break;
3499
3500 case Builtin::BI__builtin_elementwise_ldexp: {
3501 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3502 return ExprError();
3503
3504 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
3505 if (A.isInvalid())
3506 return ExprError();
3507 QualType TyA = A.get()->getType();
3508 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
3509 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1))
3510 return ExprError();
3511
3512 ExprResult Exp = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3513 if (Exp.isInvalid())
3514 return ExprError();
3515 QualType TyExp = Exp.get()->getType();
3516 if (checkMathBuiltinElementType(S&: *this, Loc: Exp.get()->getBeginLoc(), ArgTy: TyExp,
3517 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy,
3518 ArgOrdinal: 2))
3519 return ExprError();
3520
3521 // Check the two arguments are either scalars or vectors of equal length.
3522 const auto *Vec0 = TyA->getAs<VectorType>();
3523 const auto *Vec1 = TyExp->getAs<VectorType>();
3524 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3525 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3526 if (Arg0Length != Arg1Length) {
3527 Diag(Loc: Exp.get()->getBeginLoc(),
3528 DiagID: diag::err_typecheck_vector_lengths_not_equal)
3529 << TyA << TyExp << A.get()->getSourceRange()
3530 << Exp.get()->getSourceRange();
3531 return ExprError();
3532 }
3533
3534 TheCall->setArg(Arg: 0, ArgExpr: A.get());
3535 TheCall->setArg(Arg: 1, ArgExpr: Exp.get());
3536 TheCall->setType(TyA);
3537 break;
3538 }
3539
3540 // These builtins restrict the element type to floating point
3541 // types only, and take in two arguments.
3542 case Builtin::BI__builtin_elementwise_minnum:
3543 case Builtin::BI__builtin_elementwise_maxnum:
3544 case Builtin::BI__builtin_elementwise_minimum:
3545 case Builtin::BI__builtin_elementwise_maximum:
3546 case Builtin::BI__builtin_elementwise_minimumnum:
3547 case Builtin::BI__builtin_elementwise_maximumnum:
3548 case Builtin::BI__builtin_elementwise_atan2:
3549 case Builtin::BI__builtin_elementwise_fmod:
3550 case Builtin::BI__builtin_elementwise_pow:
3551 if (BuiltinElementwiseMath(TheCall,
3552 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3553 return ExprError();
3554 break;
3555 // These builtins restrict the element type to integer
3556 // types only.
3557 case Builtin::BI__builtin_elementwise_add_sat:
3558 case Builtin::BI__builtin_elementwise_sub_sat:
3559 if (BuiltinElementwiseMath(TheCall,
3560 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3561 return ExprError();
3562 break;
3563 case Builtin::BI__builtin_elementwise_fshl:
3564 case Builtin::BI__builtin_elementwise_fshr:
3565 if (BuiltinElementwiseTernaryMath(
3566 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3567 return ExprError();
3568 break;
3569 case Builtin::BI__builtin_elementwise_min:
3570 case Builtin::BI__builtin_elementwise_max: {
3571 if (BuiltinElementwiseMath(TheCall))
3572 return ExprError();
3573 Expr *Arg0 = TheCall->getArg(Arg: 0);
3574 Expr *Arg1 = TheCall->getArg(Arg: 1);
3575 QualType Ty0 = Arg0->getType();
3576 QualType Ty1 = Arg1->getType();
3577 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3578 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3579 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3580 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3581 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3582 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin_no_suggestion)
3583 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID);
3584 break;
3585 }
3586 case Builtin::BI__builtin_elementwise_popcount:
3587 case Builtin::BI__builtin_elementwise_bitreverse:
3588 if (PrepareBuiltinElementwiseMathOneArgCall(
3589 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3590 return ExprError();
3591 break;
3592 case Builtin::BI__builtin_elementwise_copysign: {
3593 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3594 return ExprError();
3595
3596 ExprResult Magnitude = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
3597 ExprResult Sign = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3598 if (Magnitude.isInvalid() || Sign.isInvalid())
3599 return ExprError();
3600
3601 QualType MagnitudeTy = Magnitude.get()->getType();
3602 QualType SignTy = Sign.get()->getType();
3603 if (checkMathBuiltinElementType(
3604 S&: *this, Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), ArgTy: MagnitudeTy,
3605 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1) ||
3606 checkMathBuiltinElementType(
3607 S&: *this, Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), ArgTy: SignTy,
3608 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 2)) {
3609 return ExprError();
3610 }
3611
3612 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3613 return Diag(Loc: Sign.get()->getBeginLoc(),
3614 DiagID: diag::err_typecheck_call_different_arg_types)
3615 << MagnitudeTy << SignTy;
3616 }
3617
3618 TheCall->setArg(Arg: 0, ArgExpr: Magnitude.get());
3619 TheCall->setArg(Arg: 1, ArgExpr: Sign.get());
3620 TheCall->setType(Magnitude.get()->getType());
3621 break;
3622 }
3623 case Builtin::BI__builtin_elementwise_clzg:
3624 case Builtin::BI__builtin_elementwise_ctzg:
3625 // These builtins can be unary or binary. Note for empty calls we call the
3626 // unary checker in order to not emit an error that says the function
3627 // expects 2 arguments, which would be misleading.
3628 if (TheCall->getNumArgs() <= 1) {
3629 if (PrepareBuiltinElementwiseMathOneArgCall(
3630 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3631 return ExprError();
3632 } else if (BuiltinElementwiseMath(
3633 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3634 return ExprError();
3635 break;
3636 case Builtin::BI__builtin_reduce_max:
3637 case Builtin::BI__builtin_reduce_min: {
3638 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3639 return ExprError();
3640
3641 const Expr *Arg = TheCall->getArg(Arg: 0);
3642 const auto *TyA = Arg->getType()->getAs<VectorType>();
3643
3644 QualType ElTy;
3645 if (TyA)
3646 ElTy = TyA->getElementType();
3647 else if (Arg->getType()->isSizelessVectorType())
3648 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
3649
3650 if (ElTy.isNull()) {
3651 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3652 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3653 << Arg->getType();
3654 return ExprError();
3655 }
3656
3657 TheCall->setType(ElTy);
3658 break;
3659 }
3660 case Builtin::BI__builtin_reduce_maximum:
3661 case Builtin::BI__builtin_reduce_minimum: {
3662 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3663 return ExprError();
3664
3665 const Expr *Arg = TheCall->getArg(Arg: 0);
3666 const auto *TyA = Arg->getType()->getAs<VectorType>();
3667
3668 QualType ElTy;
3669 if (TyA)
3670 ElTy = TyA->getElementType();
3671 else if (Arg->getType()->isSizelessVectorType())
3672 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
3673
3674 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3675 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3676 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3677 << Arg->getType();
3678 return ExprError();
3679 }
3680
3681 TheCall->setType(ElTy);
3682 break;
3683 }
3684
3685 // These builtins support vectors of integers only.
3686 // TODO: ADD/MUL should support floating-point types.
3687 case Builtin::BI__builtin_reduce_add:
3688 case Builtin::BI__builtin_reduce_mul:
3689 case Builtin::BI__builtin_reduce_xor:
3690 case Builtin::BI__builtin_reduce_or:
3691 case Builtin::BI__builtin_reduce_and: {
3692 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3693 return ExprError();
3694
3695 const Expr *Arg = TheCall->getArg(Arg: 0);
3696
3697 QualType ElTy = getVectorElementType(Context, VecTy: Arg->getType());
3698 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3699 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3700 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3701 << Arg->getType();
3702 return ExprError();
3703 }
3704
3705 TheCall->setType(ElTy);
3706 break;
3707 }
3708
3709 case Builtin::BI__builtin_reduce_assoc_fadd:
3710 case Builtin::BI__builtin_reduce_in_order_fadd: {
3711 // For in-order reductions require the user to specify the start value.
3712 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
3713 if (InOrder ? checkArgCount(Call: TheCall, DesiredArgCount: 2) : checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
3714 return ExprError();
3715
3716 ExprResult Vec = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
3717 if (Vec.isInvalid())
3718 return ExprError();
3719
3720 TheCall->setArg(Arg: 0, ArgExpr: Vec.get());
3721
3722 QualType ElTy = getVectorElementType(Context, VecTy: Vec.get()->getType());
3723 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
3724 Diag(Loc: Vec.get()->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3725 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3726 << Vec.get()->getType();
3727 return ExprError();
3728 }
3729
3730 if (TheCall->getNumArgs() == 2) {
3731 ExprResult StartValue = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3732 if (StartValue.isInvalid())
3733 return ExprError();
3734
3735 if (!StartValue.get()->getType()->isRealFloatingType()) {
3736 Diag(Loc: StartValue.get()->getBeginLoc(),
3737 DiagID: diag::err_builtin_invalid_arg_type)
3738 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
3739 << StartValue.get()->getType();
3740 return ExprError();
3741 }
3742 TheCall->setArg(Arg: 1, ArgExpr: StartValue.get());
3743 }
3744
3745 TheCall->setType(ElTy);
3746 break;
3747 }
3748
3749 case Builtin::BI__builtin_matrix_transpose:
3750 return BuiltinMatrixTranspose(TheCall, CallResult: TheCallResult);
3751
3752 case Builtin::BI__builtin_matrix_column_major_load:
3753 return BuiltinMatrixColumnMajorLoad(TheCall, CallResult: TheCallResult);
3754
3755 case Builtin::BI__builtin_matrix_column_major_store:
3756 return BuiltinMatrixColumnMajorStore(TheCall, CallResult: TheCallResult);
3757
3758 case Builtin::BI__builtin_verbose_trap:
3759 if (!checkBuiltinVerboseTrap(Call: TheCall, S&: *this))
3760 return ExprError();
3761 break;
3762
3763 case Builtin::BI__builtin_get_device_side_mangled_name: {
3764 auto Check = [](CallExpr *TheCall) {
3765 if (TheCall->getNumArgs() != 1)
3766 return false;
3767 auto *DRE = dyn_cast<DeclRefExpr>(Val: TheCall->getArg(Arg: 0)->IgnoreImpCasts());
3768 if (!DRE)
3769 return false;
3770 auto *D = DRE->getDecl();
3771 if (!isa<FunctionDecl>(Val: D) && !isa<VarDecl>(Val: D))
3772 return false;
3773 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3774 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3775 };
3776 if (!Check(TheCall)) {
3777 Diag(Loc: TheCall->getBeginLoc(),
3778 DiagID: diag::err_hip_invalid_args_builtin_mangled_name);
3779 return ExprError();
3780 }
3781 break;
3782 }
3783 case Builtin::BI__builtin_bswapg:
3784 if (BuiltinBswapg(S&: *this, TheCall))
3785 return ExprError();
3786 break;
3787 case Builtin::BI__builtin_bitreverseg:
3788 if (BuiltinBitreverseg(S&: *this, TheCall))
3789 return ExprError();
3790 break;
3791 case Builtin::BI__builtin_popcountg:
3792 if (BuiltinPopcountg(S&: *this, TheCall))
3793 return ExprError();
3794 break;
3795 case Builtin::BI__builtin_clzg:
3796 case Builtin::BI__builtin_ctzg:
3797 if (BuiltinCountZeroBitsGeneric(S&: *this, TheCall))
3798 return ExprError();
3799 break;
3800
3801 case Builtin::BI__builtin_stdc_rotate_left:
3802 case Builtin::BI__builtin_stdc_rotate_right:
3803 if (BuiltinRotateGeneric(S&: *this, TheCall))
3804 return ExprError();
3805 break;
3806
3807 case Builtin::BI__builtin_allow_runtime_check: {
3808 Expr *Arg = TheCall->getArg(Arg: 0);
3809 // Check if the argument is a string literal.
3810 if (!isa<StringLiteral>(Val: Arg->IgnoreParenImpCasts())) {
3811 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
3812 << Arg->getSourceRange();
3813 return ExprError();
3814 }
3815 break;
3816 }
3817
3818 case Builtin::BI__builtin_allow_sanitize_check: {
3819 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3820 return ExprError();
3821
3822 Expr *Arg = TheCall->getArg(Arg: 0);
3823 // Check if the argument is a string literal.
3824 const StringLiteral *SanitizerName =
3825 dyn_cast<StringLiteral>(Val: Arg->IgnoreParenImpCasts());
3826 if (!SanitizerName) {
3827 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
3828 << Arg->getSourceRange();
3829 return ExprError();
3830 }
3831 // Validate the sanitizer name.
3832 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
3833 .Cases(CaseStrings: {"address", "thread", "memory", "hwaddress",
3834 "kernel-address", "kernel-memory", "kernel-hwaddress"},
3835 Value: true)
3836 .Default(Value: false)) {
3837 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_builtin_argument)
3838 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
3839 << Arg->getSourceRange();
3840 return ExprError();
3841 }
3842 break;
3843 }
3844 case Builtin::BI__builtin_counted_by_ref:
3845 if (BuiltinCountedByRef(TheCall))
3846 return ExprError();
3847 break;
3848 }
3849
3850 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3851 return ExprError();
3852
3853 // Since the target specific builtins for each arch overlap, only check those
3854 // of the arch we are compiling for.
3855 if (Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID)) {
3856 if (Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID)) {
3857 assert(Context.getAuxTargetInfo() &&
3858 "Aux Target Builtin, but not an aux target?");
3859
3860 if (CheckTSBuiltinFunctionCall(
3861 TI: *Context.getAuxTargetInfo(),
3862 BuiltinID: Context.BuiltinInfo.getAuxBuiltinID(ID: BuiltinID), TheCall))
3863 return ExprError();
3864 } else {
3865 if (CheckTSBuiltinFunctionCall(TI: Context.getTargetInfo(), BuiltinID,
3866 TheCall))
3867 return ExprError();
3868 }
3869 }
3870
3871 return TheCallResult;
3872}
3873
3874bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3875 llvm::APSInt Result;
3876 // We can't check the value of a dependent argument.
3877 Expr *Arg = TheCall->getArg(Arg: ArgNum);
3878 if (Arg->isTypeDependent() || Arg->isValueDependent())
3879 return false;
3880
3881 // Check constant-ness first.
3882 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3883 return true;
3884
3885 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3886 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3887 return false;
3888
3889 return Diag(Loc: TheCall->getBeginLoc(),
3890 DiagID: diag::err_argument_not_contiguous_bit_field)
3891 << ArgNum << Arg->getSourceRange();
3892}
3893
3894bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3895 unsigned FirstArg, FormatStringInfo *FSI) {
3896 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
3897 bool IsVariadic = false;
3898 if (const FunctionType *FnTy = D->getFunctionType())
3899 IsVariadic = cast<FunctionProtoType>(Val: FnTy)->isVariadic();
3900 else if (const auto *BD = dyn_cast<BlockDecl>(Val: D))
3901 IsVariadic = BD->isVariadic();
3902 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D))
3903 IsVariadic = OMD->isVariadic();
3904
3905 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
3906 IsVariadic, FSI);
3907}
3908
3909bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3910 bool HasImplicitThisParam, bool IsVariadic,
3911 FormatStringInfo *FSI) {
3912 if (FirstArg == 0)
3913 FSI->ArgPassingKind = FAPK_VAList;
3914 else if (IsVariadic)
3915 FSI->ArgPassingKind = FAPK_Variadic;
3916 else
3917 FSI->ArgPassingKind = FAPK_Fixed;
3918 FSI->FormatIdx = FormatIdx - 1;
3919 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
3920
3921 // The way the format attribute works in GCC, the implicit this argument
3922 // of member functions is counted. However, it doesn't appear in our own
3923 // lists, so decrement format_idx in that case.
3924 if (HasImplicitThisParam) {
3925 if(FSI->FormatIdx == 0)
3926 return false;
3927 --FSI->FormatIdx;
3928 if (FSI->FirstDataArg != 0)
3929 --FSI->FirstDataArg;
3930 }
3931 return true;
3932}
3933
3934/// Checks if a the given expression evaluates to null.
3935///
3936/// Returns true if the value evaluates to null.
3937static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3938 // Treat (smart) pointers constructed from nullptr as null, whether we can
3939 // const-evaluate them or not.
3940 // This must happen first: the smart pointer expr might have _Nonnull type!
3941 if (isa<CXXNullPtrLiteralExpr>(
3942 Val: IgnoreExprNodes(E: Expr, Fns&: IgnoreImplicitAsWrittenSingleStep,
3943 Fns&: IgnoreElidableImplicitConstructorSingleStep)))
3944 return true;
3945
3946 // If the expression has non-null type, it doesn't evaluate to null.
3947 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3948 if (*nullability == NullabilityKind::NonNull)
3949 return false;
3950 }
3951
3952 // As a special case, transparent unions initialized with zero are
3953 // considered null for the purposes of the nonnull attribute.
3954 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3955 UT &&
3956 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
3957 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Val: Expr))
3958 if (const auto *ILE = dyn_cast<InitListExpr>(Val: CLE->getInitializer()))
3959 Expr = ILE->getInit(Init: 0);
3960 }
3961
3962 bool Result;
3963 return (!Expr->isValueDependent() &&
3964 Expr->EvaluateAsBooleanCondition(Result, Ctx: S.Context) &&
3965 !Result);
3966}
3967
3968static void CheckNonNullArgument(Sema &S,
3969 const Expr *ArgExpr,
3970 SourceLocation CallSiteLoc) {
3971 if (CheckNonNullExpr(S, Expr: ArgExpr))
3972 S.DiagRuntimeBehavior(Loc: CallSiteLoc, Statement: ArgExpr,
3973 PD: S.PDiag(DiagID: diag::warn_null_arg)
3974 << ArgExpr->getSourceRange());
3975}
3976
3977/// Determine whether the given type has a non-null nullability annotation.
3978static bool isNonNullType(QualType type) {
3979 if (auto nullability = type->getNullability())
3980 return *nullability == NullabilityKind::NonNull;
3981
3982 return false;
3983}
3984
3985static void CheckNonNullArguments(Sema &S,
3986 const NamedDecl *FDecl,
3987 const FunctionProtoType *Proto,
3988 ArrayRef<const Expr *> Args,
3989 SourceLocation CallSiteLoc) {
3990 assert((FDecl || Proto) && "Need a function declaration or prototype");
3991
3992 // Already checked by constant evaluator.
3993 if (S.isConstantEvaluatedContext())
3994 return;
3995 // Check the attributes attached to the method/function itself.
3996 llvm::SmallBitVector NonNullArgs;
3997 if (FDecl) {
3998 // Handle the nonnull attribute on the function/method declaration itself.
3999 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4000 if (!NonNull->args_size()) {
4001 // Easy case: all pointer arguments are nonnull.
4002 for (const auto *Arg : Args)
4003 if (S.isValidPointerAttrType(T: Arg->getType()))
4004 CheckNonNullArgument(S, ArgExpr: Arg, CallSiteLoc);
4005 return;
4006 }
4007
4008 for (const ParamIdx &Idx : NonNull->args()) {
4009 unsigned IdxAST = Idx.getASTIndex();
4010 if (IdxAST >= Args.size())
4011 continue;
4012 if (NonNullArgs.empty())
4013 NonNullArgs.resize(N: Args.size());
4014 NonNullArgs.set(IdxAST);
4015 }
4016 }
4017 }
4018
4019 if (FDecl && (isa<FunctionDecl>(Val: FDecl) || isa<ObjCMethodDecl>(Val: FDecl))) {
4020 // Handle the nonnull attribute on the parameters of the
4021 // function/method.
4022 ArrayRef<ParmVarDecl*> parms;
4023 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: FDecl))
4024 parms = FD->parameters();
4025 else
4026 parms = cast<ObjCMethodDecl>(Val: FDecl)->parameters();
4027
4028 unsigned ParamIndex = 0;
4029 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4030 I != E; ++I, ++ParamIndex) {
4031 const ParmVarDecl *PVD = *I;
4032 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(type: PVD->getType())) {
4033 if (NonNullArgs.empty())
4034 NonNullArgs.resize(N: Args.size());
4035
4036 NonNullArgs.set(ParamIndex);
4037 }
4038 }
4039 } else {
4040 // If we have a non-function, non-method declaration but no
4041 // function prototype, try to dig out the function prototype.
4042 if (!Proto) {
4043 if (const ValueDecl *VD = dyn_cast<ValueDecl>(Val: FDecl)) {
4044 QualType type = VD->getType().getNonReferenceType();
4045 if (auto pointerType = type->getAs<PointerType>())
4046 type = pointerType->getPointeeType();
4047 else if (auto blockType = type->getAs<BlockPointerType>())
4048 type = blockType->getPointeeType();
4049 // FIXME: data member pointers?
4050
4051 // Dig out the function prototype, if there is one.
4052 Proto = type->getAs<FunctionProtoType>();
4053 }
4054 }
4055
4056 // Fill in non-null argument information from the nullability
4057 // information on the parameter types (if we have them).
4058 if (Proto) {
4059 unsigned Index = 0;
4060 for (auto paramType : Proto->getParamTypes()) {
4061 if (isNonNullType(type: paramType)) {
4062 if (NonNullArgs.empty())
4063 NonNullArgs.resize(N: Args.size());
4064
4065 NonNullArgs.set(Index);
4066 }
4067
4068 ++Index;
4069 }
4070 }
4071 }
4072
4073 // Check for non-null arguments.
4074 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4075 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4076 if (NonNullArgs[ArgIndex])
4077 CheckNonNullArgument(S, ArgExpr: Args[ArgIndex], CallSiteLoc: Args[ArgIndex]->getExprLoc());
4078 }
4079}
4080
4081void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4082 StringRef ParamName, QualType ArgTy,
4083 QualType ParamTy) {
4084
4085 // If a function accepts a pointer or reference type
4086 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4087 return;
4088
4089 // If the parameter is a pointer type, get the pointee type for the
4090 // argument too. If the parameter is a reference type, don't try to get
4091 // the pointee type for the argument.
4092 if (ParamTy->isPointerType())
4093 ArgTy = ArgTy->getPointeeType();
4094
4095 // Remove reference or pointer
4096 ParamTy = ParamTy->getPointeeType();
4097
4098 // Find expected alignment, and the actual alignment of the passed object.
4099 // getTypeAlignInChars requires complete types
4100 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4101 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4102 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4103 return;
4104
4105 CharUnits ParamAlign = Context.getTypeAlignInChars(T: ParamTy);
4106 CharUnits ArgAlign = Context.getTypeAlignInChars(T: ArgTy);
4107
4108 // If the argument is less aligned than the parameter, there is a
4109 // potential alignment issue.
4110 if (ArgAlign < ParamAlign)
4111 Diag(Loc, DiagID: diag::warn_param_mismatched_alignment)
4112 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4113 << ParamName << (FDecl != nullptr) << FDecl;
4114}
4115
4116void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4117 const Expr *ThisArg,
4118 ArrayRef<const Expr *> Args) {
4119 if (!FD || Args.empty())
4120 return;
4121 auto GetArgAt = [&](int Idx) -> const Expr * {
4122 if (Idx == LifetimeCaptureByAttr::Global ||
4123 Idx == LifetimeCaptureByAttr::Unknown)
4124 return nullptr;
4125 if (IsMemberFunction && Idx == 0)
4126 return ThisArg;
4127 return Args[Idx - IsMemberFunction];
4128 };
4129 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4130 unsigned ArgIdx) {
4131 if (!Attr)
4132 return;
4133
4134 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4135 for (int CapturingParamIdx : Attr->params()) {
4136 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4137 // initialization codepath.
4138 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4139 isa<CXXConstructorDecl>(Val: FD))
4140 continue;
4141 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4142 CapturingEntity CE{.Entity: Capturing};
4143 // Ensure that 'Captured' outlives the 'Capturing' entity.
4144 checkCaptureByLifetime(SemaRef&: *this, Entity: CE, Init: Captured);
4145 }
4146 };
4147 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4148 HandleCaptureByAttr(FD->getParamDecl(i: I)->getAttr<LifetimeCaptureByAttr>(),
4149 I + IsMemberFunction);
4150 // Check when the implicit object param is captured.
4151 if (IsMemberFunction) {
4152 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4153 if (!TSI)
4154 return;
4155 AttributedTypeLoc ATL;
4156 for (TypeLoc TL = TSI->getTypeLoc();
4157 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4158 TL = ATL.getModifiedLoc())
4159 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4160 }
4161}
4162
4163void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4164 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4165 bool IsMemberFunction, SourceLocation Loc,
4166 SourceRange Range, VariadicCallType CallType) {
4167 // FIXME: We should check as much as we can in the template definition.
4168 if (CurContext->isDependentContext())
4169 return;
4170
4171 // Printf and scanf checking.
4172 llvm::SmallBitVector CheckedVarArgs;
4173 if (FDecl) {
4174 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4175 // Only create vector if there are format attributes.
4176 CheckedVarArgs.resize(N: Args.size());
4177 CheckFormatString(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4178 CheckedVarArgs);
4179 }
4180
4181 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4182 CheckedVarArgs.resize(N: Args.size());
4183 CheckFormatArguments(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4184 CheckedVarArgs);
4185 }
4186 }
4187
4188 // Refuse POD arguments that weren't caught by the format string
4189 // checks above.
4190 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: FDecl);
4191 if (CallType != VariadicCallType::DoesNotApply &&
4192 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4193 unsigned NumParams = Proto ? Proto->getNumParams()
4194 : isa_and_nonnull<FunctionDecl>(Val: FDecl)
4195 ? cast<FunctionDecl>(Val: FDecl)->getNumParams()
4196 : isa_and_nonnull<ObjCMethodDecl>(Val: FDecl)
4197 ? cast<ObjCMethodDecl>(Val: FDecl)->param_size()
4198 : 0;
4199
4200 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4201 // Args[ArgIdx] can be null in malformed code.
4202 if (const Expr *Arg = Args[ArgIdx]) {
4203 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4204 checkVariadicArgument(E: Arg, CT: CallType);
4205 }
4206 }
4207 }
4208 if (FD)
4209 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4210 if (FDecl || Proto) {
4211 CheckNonNullArguments(S&: *this, FDecl, Proto, Args, CallSiteLoc: Loc);
4212
4213 // Type safety checking.
4214 if (FDecl) {
4215 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4216 CheckArgumentWithTypeTag(Attr: I, ExprArgs: Args, CallSiteLoc: Loc);
4217 }
4218 }
4219
4220 // Check that passed arguments match the alignment of original arguments.
4221 // Try to get the missing prototype from the declaration.
4222 if (!Proto && FDecl) {
4223 const auto *FT = FDecl->getFunctionType();
4224 if (isa_and_nonnull<FunctionProtoType>(Val: FT))
4225 Proto = cast<FunctionProtoType>(Val: FDecl->getFunctionType());
4226 }
4227 if (Proto) {
4228 // For variadic functions, we may have more args than parameters.
4229 // For some K&R functions, we may have less args than parameters.
4230 const auto N = std::min<unsigned>(a: Proto->getNumParams(), b: Args.size());
4231 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4232 bool IsScalableArg = false;
4233 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4234 // Args[ArgIdx] can be null in malformed code.
4235 if (const Expr *Arg = Args[ArgIdx]) {
4236 if (Arg->containsErrors())
4237 continue;
4238
4239 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4240 FDecl->hasLinkage() &&
4241 FDecl->getFormalLinkage() != Linkage::Internal &&
4242 CallType == VariadicCallType::DoesNotApply)
4243 PPC().checkAIXMemberAlignment(Loc: (Arg->getExprLoc()), Arg);
4244
4245 QualType ParamTy = Proto->getParamType(i: ArgIdx);
4246 if (ParamTy->isSizelessVectorType())
4247 IsScalableArg = true;
4248 QualType ArgTy = Arg->getType();
4249 CheckArgAlignment(Loc: Arg->getExprLoc(), FDecl, ParamName: std::to_string(val: ArgIdx + 1),
4250 ArgTy, ParamTy);
4251 }
4252 }
4253
4254 // If the callee has an AArch64 SME attribute to indicate that it is an
4255 // __arm_streaming function, then the caller requires SME to be available.
4256 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
4257 if (ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask) {
4258 if (auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext)) {
4259 llvm::StringMap<bool> CallerFeatureMap;
4260 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, CallerFD);
4261 if (!CallerFeatureMap.contains(Key: "sme"))
4262 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4263 } else if (!Context.getTargetInfo().hasFeature(Feature: "sme")) {
4264 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4265 }
4266 }
4267
4268 // If the call requires a streaming-mode change and has scalable vector
4269 // arguments or return values, then warn the user that the streaming and
4270 // non-streaming vector lengths may be different.
4271 // When both streaming and non-streaming vector lengths are defined and
4272 // mismatched, produce an error.
4273 const auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext);
4274 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4275 (IsScalableArg || IsScalableRet)) {
4276 bool IsCalleeStreaming =
4277 ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
4278 bool IsCalleeStreamingCompatible =
4279 ExtInfo.AArch64SMEAttributes &
4280 FunctionType::SME_PStateSMCompatibleMask;
4281 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(FD: CallerFD);
4282 if (!IsCalleeStreamingCompatible &&
4283 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4284 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4285 const LangOptions &LO = getLangOpts();
4286 unsigned VL = LO.VScaleMin * 128;
4287 unsigned SVL = LO.VScaleStreamingMin * 128;
4288 bool IsVLMismatch = VL && SVL && VL != SVL;
4289
4290 auto EmitDiag = [&](bool IsArg) {
4291 if (IsVLMismatch) {
4292 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4293 // Emit warning for streaming-compatible callers
4294 Diag(Loc, DiagID: diag::warn_sme_streaming_compatible_vl_mismatch)
4295 << IsArg << IsCalleeStreaming << SVL << VL;
4296 else
4297 // Emit error otherwise
4298 Diag(Loc, DiagID: diag::err_sme_streaming_transition_vl_mismatch)
4299 << IsArg << SVL << VL;
4300 } else
4301 Diag(Loc, DiagID: diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4302 << IsArg;
4303 };
4304
4305 if (IsScalableArg)
4306 EmitDiag(true);
4307 if (IsScalableRet)
4308 EmitDiag(false);
4309 }
4310 }
4311
4312 FunctionType::ArmStateValue CalleeArmZAState =
4313 FunctionType::getArmZAState(AttrBits: ExtInfo.AArch64SMEAttributes);
4314 FunctionType::ArmStateValue CalleeArmZT0State =
4315 FunctionType::getArmZT0State(AttrBits: ExtInfo.AArch64SMEAttributes);
4316 if (CalleeArmZAState != FunctionType::ARM_None ||
4317 CalleeArmZT0State != FunctionType::ARM_None) {
4318 bool CallerHasZAState = false;
4319 bool CallerHasZT0State = false;
4320 if (CallerFD) {
4321 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4322 if (Attr && Attr->isNewZA())
4323 CallerHasZAState = true;
4324 if (Attr && Attr->isNewZT0())
4325 CallerHasZT0State = true;
4326 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4327 CallerHasZAState |=
4328 FunctionType::getArmZAState(
4329 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4330 FunctionType::ARM_None;
4331 CallerHasZT0State |=
4332 FunctionType::getArmZT0State(
4333 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4334 FunctionType::ARM_None;
4335 }
4336 }
4337
4338 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4339 Diag(Loc, DiagID: diag::err_sme_za_call_no_za_state);
4340
4341 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4342 Diag(Loc, DiagID: diag::err_sme_zt0_call_no_zt0_state);
4343
4344 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4345 CalleeArmZT0State != FunctionType::ARM_None) {
4346 Diag(Loc, DiagID: diag::err_sme_unimplemented_za_save_restore);
4347 Diag(Loc, DiagID: diag::note_sme_use_preserves_za);
4348 }
4349 }
4350 }
4351
4352 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4353 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4354 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4355 if (!Arg->isValueDependent()) {
4356 Expr::EvalResult Align;
4357 if (Arg->EvaluateAsInt(Result&: Align, Ctx: Context)) {
4358 const llvm::APSInt &I = Align.Val.getInt();
4359 if (!I.isPowerOf2())
4360 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_alignment_not_power_of_two)
4361 << Arg->getSourceRange();
4362
4363 if (I > Sema::MaximumAlignment)
4364 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_assume_aligned_too_great)
4365 << Arg->getSourceRange() << Sema::MaximumAlignment;
4366 }
4367 }
4368 }
4369
4370 if (FD)
4371 diagnoseArgDependentDiagnoseIfAttrs(Function: FD, ThisArg, Args, Loc);
4372}
4373
4374void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4375 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4376 DiagnoseUseOfDecl(D: Decl, Locs: Loc);
4377 }
4378}
4379
4380void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4381 ArrayRef<const Expr *> Args,
4382 const FunctionProtoType *Proto,
4383 SourceLocation Loc) {
4384 VariadicCallType CallType = Proto->isVariadic()
4385 ? VariadicCallType::Constructor
4386 : VariadicCallType::DoesNotApply;
4387
4388 auto *Ctor = cast<CXXConstructorDecl>(Val: FDecl);
4389 CheckArgAlignment(
4390 Loc, FDecl, ParamName: "'this'", ArgTy: Context.getPointerType(T: ThisType),
4391 ParamTy: Context.getPointerType(T: Ctor->getFunctionObjectParameterType()));
4392
4393 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4394 Loc, Range: SourceRange(), CallType);
4395}
4396
4397bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4398 const FunctionProtoType *Proto) {
4399 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(Val: TheCall) &&
4400 isa<CXXMethodDecl>(Val: FDecl);
4401 bool IsMemberFunction = isa<CXXMemberCallExpr>(Val: TheCall) ||
4402 IsMemberOperatorCall;
4403 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4404 Fn: TheCall->getCallee());
4405 Expr** Args = TheCall->getArgs();
4406 unsigned NumArgs = TheCall->getNumArgs();
4407
4408 Expr *ImplicitThis = nullptr;
4409 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4410 // If this is a call to a member operator, hide the first
4411 // argument from checkCall.
4412 // FIXME: Our choice of AST representation here is less than ideal.
4413 ImplicitThis = Args[0];
4414 ++Args;
4415 --NumArgs;
4416 } else if (IsMemberFunction && !FDecl->isStatic() &&
4417 !FDecl->hasCXXExplicitFunctionObjectParameter())
4418 ImplicitThis =
4419 cast<CXXMemberCallExpr>(Val: TheCall)->getImplicitObjectArgument();
4420
4421 if (ImplicitThis) {
4422 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4423 // used.
4424 QualType ThisType = ImplicitThis->getType();
4425 if (!ThisType->isPointerType()) {
4426 assert(!ThisType->isReferenceType());
4427 ThisType = Context.getPointerType(T: ThisType);
4428 }
4429
4430 QualType ThisTypeFromDecl = Context.getPointerType(
4431 T: cast<CXXMethodDecl>(Val: FDecl)->getFunctionObjectParameterType());
4432
4433 CheckArgAlignment(Loc: TheCall->getRParenLoc(), FDecl, ParamName: "'this'", ArgTy: ThisType,
4434 ParamTy: ThisTypeFromDecl);
4435 }
4436
4437 checkCall(FDecl, Proto, ThisArg: ImplicitThis, Args: llvm::ArrayRef(Args, NumArgs),
4438 IsMemberFunction, Loc: TheCall->getRParenLoc(),
4439 Range: TheCall->getCallee()->getSourceRange(), CallType);
4440
4441 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4442 // None of the checks below are needed for functions that don't have
4443 // simple names (e.g., C++ conversion functions).
4444 if (!FnInfo)
4445 return false;
4446
4447 // Enforce TCB except for builtin calls, which are always allowed.
4448 if (FDecl->getBuiltinID() == 0)
4449 CheckTCBEnforcement(CallExprLoc: TheCall->getExprLoc(), Callee: FDecl);
4450
4451 CheckAbsoluteValueFunction(Call: TheCall, FDecl);
4452 CheckMaxUnsignedZero(Call: TheCall, FDecl);
4453 CheckInfNaNFunction(Call: TheCall, FDecl);
4454
4455 if (getLangOpts().ObjC)
4456 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4457
4458 unsigned CMId = FDecl->getMemoryFunctionKind();
4459
4460 // Handle memory setting and copying functions.
4461 switch (CMId) {
4462 case 0:
4463 return false;
4464 case Builtin::BIstrlcpy: // fallthrough
4465 case Builtin::BIstrlcat:
4466 CheckStrlcpycatArguments(Call: TheCall, FnName: FnInfo);
4467 break;
4468 case Builtin::BIstrncat:
4469 CheckStrncatArguments(Call: TheCall, FnName: FnInfo);
4470 break;
4471 case Builtin::BIfree:
4472 CheckFreeArguments(E: TheCall);
4473 break;
4474 default:
4475 CheckMemaccessArguments(Call: TheCall, BId: CMId, FnName: FnInfo);
4476 }
4477
4478 return false;
4479}
4480
4481bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4482 const FunctionProtoType *Proto) {
4483 QualType Ty;
4484 if (const auto *V = dyn_cast<VarDecl>(Val: NDecl))
4485 Ty = V->getType().getNonReferenceType();
4486 else if (const auto *F = dyn_cast<FieldDecl>(Val: NDecl))
4487 Ty = F->getType().getNonReferenceType();
4488 else
4489 return false;
4490
4491 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4492 !Ty->isFunctionProtoType())
4493 return false;
4494
4495 VariadicCallType CallType;
4496 if (!Proto || !Proto->isVariadic()) {
4497 CallType = VariadicCallType::DoesNotApply;
4498 } else if (Ty->isBlockPointerType()) {
4499 CallType = VariadicCallType::Block;
4500 } else { // Ty->isFunctionPointerType()
4501 CallType = VariadicCallType::Function;
4502 }
4503
4504 checkCall(FDecl: NDecl, Proto, /*ThisArg=*/nullptr,
4505 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4506 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4507 Range: TheCall->getCallee()->getSourceRange(), CallType);
4508
4509 return false;
4510}
4511
4512bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4513 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4514 Fn: TheCall->getCallee());
4515 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4516 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4517 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4518 Range: TheCall->getCallee()->getSourceRange(), CallType);
4519
4520 return false;
4521}
4522
4523static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4524 if (!llvm::isValidAtomicOrderingCABI(I: Ordering))
4525 return false;
4526
4527 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4528 switch (Op) {
4529 case AtomicExpr::AO__c11_atomic_init:
4530 case AtomicExpr::AO__opencl_atomic_init:
4531 llvm_unreachable("There is no ordering argument for an init");
4532
4533 case AtomicExpr::AO__c11_atomic_load:
4534 case AtomicExpr::AO__opencl_atomic_load:
4535 case AtomicExpr::AO__hip_atomic_load:
4536 case AtomicExpr::AO__atomic_load_n:
4537 case AtomicExpr::AO__atomic_load:
4538 case AtomicExpr::AO__scoped_atomic_load_n:
4539 case AtomicExpr::AO__scoped_atomic_load:
4540 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4541 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4542
4543 case AtomicExpr::AO__c11_atomic_store:
4544 case AtomicExpr::AO__opencl_atomic_store:
4545 case AtomicExpr::AO__hip_atomic_store:
4546 case AtomicExpr::AO__atomic_store:
4547 case AtomicExpr::AO__atomic_store_n:
4548 case AtomicExpr::AO__scoped_atomic_store:
4549 case AtomicExpr::AO__scoped_atomic_store_n:
4550 case AtomicExpr::AO__atomic_clear:
4551 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4552 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4553 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4554
4555 default:
4556 return true;
4557 }
4558}
4559
4560ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4561 AtomicExpr::AtomicOp Op) {
4562 CallExpr *TheCall = cast<CallExpr>(Val: TheCallResult.get());
4563 DeclRefExpr *DRE =cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
4564 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4565 return BuildAtomicExpr(CallRange: {TheCall->getBeginLoc(), TheCall->getEndLoc()},
4566 ExprRange: DRE->getSourceRange(), RParenLoc: TheCall->getRParenLoc(), Args,
4567 Op);
4568}
4569
4570ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4571 SourceLocation RParenLoc, MultiExprArg Args,
4572 AtomicExpr::AtomicOp Op,
4573 AtomicArgumentOrder ArgOrder) {
4574 // All the non-OpenCL operations take one of the following forms.
4575 // The OpenCL operations take the __c11 forms with one extra argument for
4576 // synchronization scope.
4577 enum {
4578 // C __c11_atomic_init(A *, C)
4579 Init,
4580
4581 // C __c11_atomic_load(A *, int)
4582 Load,
4583
4584 // void __atomic_load(A *, CP, int)
4585 LoadCopy,
4586
4587 // void __atomic_store(A *, CP, int)
4588 Copy,
4589
4590 // C __c11_atomic_add(A *, M, int)
4591 Arithmetic,
4592
4593 // C __atomic_exchange_n(A *, CP, int)
4594 Xchg,
4595
4596 // void __atomic_exchange(A *, C *, CP, int)
4597 GNUXchg,
4598
4599 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4600 C11CmpXchg,
4601
4602 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4603 GNUCmpXchg,
4604
4605 // bool __atomic_test_and_set(A *, int)
4606 TestAndSetByte,
4607
4608 // void __atomic_clear(A *, int)
4609 ClearByte,
4610 } Form = Init;
4611
4612 const unsigned NumForm = ClearByte + 1;
4613 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4614 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4615 // where:
4616 // C is an appropriate type,
4617 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4618 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4619 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4620 // the int parameters are for orderings.
4621
4622 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4623 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4624 "need to update code for modified forms");
4625 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4626 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4627 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4628 "need to update code for modified C11 atomics");
4629 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4630 Op <= AtomicExpr::AO__opencl_atomic_store;
4631 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4632 Op <= AtomicExpr::AO__hip_atomic_store;
4633 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4634 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4635 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4636 Op <= AtomicExpr::AO__c11_atomic_store) ||
4637 IsOpenCL;
4638 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4639 Op == AtomicExpr::AO__atomic_store_n ||
4640 Op == AtomicExpr::AO__atomic_exchange_n ||
4641 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4642 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4643 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4644 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4645 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4646 // Bit mask for extra allowed value types other than integers for atomic
4647 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4648 // allow floating point.
4649 enum ArithOpExtraValueType {
4650 AOEVT_None = 0,
4651 AOEVT_Pointer = 1,
4652 AOEVT_FP = 2,
4653 };
4654 unsigned ArithAllows = AOEVT_None;
4655
4656 switch (Op) {
4657 case AtomicExpr::AO__c11_atomic_init:
4658 case AtomicExpr::AO__opencl_atomic_init:
4659 Form = Init;
4660 break;
4661
4662 case AtomicExpr::AO__c11_atomic_load:
4663 case AtomicExpr::AO__opencl_atomic_load:
4664 case AtomicExpr::AO__hip_atomic_load:
4665 case AtomicExpr::AO__atomic_load_n:
4666 case AtomicExpr::AO__scoped_atomic_load_n:
4667 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4668 Form = Load;
4669 break;
4670
4671 case AtomicExpr::AO__atomic_load:
4672 case AtomicExpr::AO__scoped_atomic_load:
4673 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4674 Form = LoadCopy;
4675 break;
4676
4677 case AtomicExpr::AO__c11_atomic_store:
4678 case AtomicExpr::AO__opencl_atomic_store:
4679 case AtomicExpr::AO__hip_atomic_store:
4680 case AtomicExpr::AO__atomic_store:
4681 case AtomicExpr::AO__atomic_store_n:
4682 case AtomicExpr::AO__scoped_atomic_store:
4683 case AtomicExpr::AO__scoped_atomic_store_n:
4684 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4685 Form = Copy;
4686 break;
4687 case AtomicExpr::AO__atomic_fetch_add:
4688 case AtomicExpr::AO__atomic_fetch_sub:
4689 case AtomicExpr::AO__atomic_add_fetch:
4690 case AtomicExpr::AO__atomic_sub_fetch:
4691 case AtomicExpr::AO__scoped_atomic_fetch_add:
4692 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4693 case AtomicExpr::AO__scoped_atomic_add_fetch:
4694 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4695 case AtomicExpr::AO__c11_atomic_fetch_add:
4696 case AtomicExpr::AO__c11_atomic_fetch_sub:
4697 case AtomicExpr::AO__opencl_atomic_fetch_add:
4698 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4699 case AtomicExpr::AO__hip_atomic_fetch_add:
4700 case AtomicExpr::AO__hip_atomic_fetch_sub:
4701 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4702 Form = Arithmetic;
4703 break;
4704 case AtomicExpr::AO__atomic_fetch_max:
4705 case AtomicExpr::AO__atomic_fetch_min:
4706 case AtomicExpr::AO__atomic_max_fetch:
4707 case AtomicExpr::AO__atomic_min_fetch:
4708 case AtomicExpr::AO__scoped_atomic_fetch_max:
4709 case AtomicExpr::AO__scoped_atomic_fetch_min:
4710 case AtomicExpr::AO__scoped_atomic_max_fetch:
4711 case AtomicExpr::AO__scoped_atomic_min_fetch:
4712 case AtomicExpr::AO__c11_atomic_fetch_max:
4713 case AtomicExpr::AO__c11_atomic_fetch_min:
4714 case AtomicExpr::AO__opencl_atomic_fetch_max:
4715 case AtomicExpr::AO__opencl_atomic_fetch_min:
4716 case AtomicExpr::AO__hip_atomic_fetch_max:
4717 case AtomicExpr::AO__hip_atomic_fetch_min:
4718 ArithAllows = AOEVT_FP;
4719 Form = Arithmetic;
4720 break;
4721 case AtomicExpr::AO__c11_atomic_fetch_and:
4722 case AtomicExpr::AO__c11_atomic_fetch_or:
4723 case AtomicExpr::AO__c11_atomic_fetch_xor:
4724 case AtomicExpr::AO__hip_atomic_fetch_and:
4725 case AtomicExpr::AO__hip_atomic_fetch_or:
4726 case AtomicExpr::AO__hip_atomic_fetch_xor:
4727 case AtomicExpr::AO__c11_atomic_fetch_nand:
4728 case AtomicExpr::AO__opencl_atomic_fetch_and:
4729 case AtomicExpr::AO__opencl_atomic_fetch_or:
4730 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4731 case AtomicExpr::AO__atomic_fetch_and:
4732 case AtomicExpr::AO__atomic_fetch_or:
4733 case AtomicExpr::AO__atomic_fetch_xor:
4734 case AtomicExpr::AO__atomic_fetch_nand:
4735 case AtomicExpr::AO__atomic_and_fetch:
4736 case AtomicExpr::AO__atomic_or_fetch:
4737 case AtomicExpr::AO__atomic_xor_fetch:
4738 case AtomicExpr::AO__atomic_nand_fetch:
4739 case AtomicExpr::AO__atomic_fetch_uinc:
4740 case AtomicExpr::AO__atomic_fetch_udec:
4741 case AtomicExpr::AO__scoped_atomic_fetch_and:
4742 case AtomicExpr::AO__scoped_atomic_fetch_or:
4743 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4744 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4745 case AtomicExpr::AO__scoped_atomic_and_fetch:
4746 case AtomicExpr::AO__scoped_atomic_or_fetch:
4747 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4748 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4749 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
4750 case AtomicExpr::AO__scoped_atomic_fetch_udec:
4751 Form = Arithmetic;
4752 break;
4753
4754 case AtomicExpr::AO__c11_atomic_exchange:
4755 case AtomicExpr::AO__hip_atomic_exchange:
4756 case AtomicExpr::AO__opencl_atomic_exchange:
4757 case AtomicExpr::AO__atomic_exchange_n:
4758 case AtomicExpr::AO__scoped_atomic_exchange_n:
4759 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4760 Form = Xchg;
4761 break;
4762
4763 case AtomicExpr::AO__atomic_exchange:
4764 case AtomicExpr::AO__scoped_atomic_exchange:
4765 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4766 Form = GNUXchg;
4767 break;
4768
4769 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4770 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4771 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4772 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4773 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4774 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4775 Form = C11CmpXchg;
4776 break;
4777
4778 case AtomicExpr::AO__atomic_compare_exchange:
4779 case AtomicExpr::AO__atomic_compare_exchange_n:
4780 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4781 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4782 ArithAllows = AOEVT_Pointer;
4783 Form = GNUCmpXchg;
4784 break;
4785
4786 case AtomicExpr::AO__atomic_test_and_set:
4787 Form = TestAndSetByte;
4788 break;
4789
4790 case AtomicExpr::AO__atomic_clear:
4791 Form = ClearByte;
4792 break;
4793 }
4794
4795 unsigned AdjustedNumArgs = NumArgs[Form];
4796 if ((IsOpenCL || IsHIP || IsScoped) &&
4797 Op != AtomicExpr::AO__opencl_atomic_init)
4798 ++AdjustedNumArgs;
4799 // Check we have the right number of arguments.
4800 if (Args.size() < AdjustedNumArgs) {
4801 Diag(Loc: CallRange.getEnd(), DiagID: diag::err_typecheck_call_too_few_args)
4802 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4803 << /*is non object*/ 0 << ExprRange;
4804 return ExprError();
4805 } else if (Args.size() > AdjustedNumArgs) {
4806 Diag(Loc: Args[AdjustedNumArgs]->getBeginLoc(),
4807 DiagID: diag::err_typecheck_call_too_many_args)
4808 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4809 << /*is non object*/ 0 << ExprRange;
4810 return ExprError();
4811 }
4812
4813 // Inspect the first argument of the atomic operation.
4814 Expr *Ptr = Args[0];
4815 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(E: Ptr);
4816 if (ConvertedPtr.isInvalid())
4817 return ExprError();
4818
4819 Ptr = ConvertedPtr.get();
4820 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4821 if (!pointerType) {
4822 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
4823 << Ptr->getType() << 0 << Ptr->getSourceRange();
4824 return ExprError();
4825 }
4826
4827 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4828 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4829 QualType ValType = AtomTy; // 'C'
4830 if (IsC11) {
4831 if (!AtomTy->isAtomicType()) {
4832 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_atomic)
4833 << Ptr->getType() << Ptr->getSourceRange();
4834 return ExprError();
4835 }
4836 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4837 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4838 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_atomic)
4839 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4840 << Ptr->getSourceRange();
4841 return ExprError();
4842 }
4843 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4844 } else if (Form != Load && Form != LoadCopy) {
4845 if (ValType.isConstQualified()) {
4846 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_pointer)
4847 << Ptr->getType() << Ptr->getSourceRange();
4848 return ExprError();
4849 }
4850 }
4851
4852 if (Form != TestAndSetByte && Form != ClearByte) {
4853 // Pointer to object of size zero is not allowed.
4854 if (RequireCompleteType(Loc: Ptr->getBeginLoc(), T: AtomTy,
4855 DiagID: diag::err_incomplete_type))
4856 return ExprError();
4857
4858 if (Context.getTypeInfoInChars(T: AtomTy).Width.isZero()) {
4859 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
4860 << Ptr->getType() << 1 << Ptr->getSourceRange();
4861 return ExprError();
4862 }
4863 } else {
4864 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4865 // non-const pointer type, including void* and pointers to incomplete
4866 // structs, but only access the first byte.
4867 AtomTy = Context.CharTy;
4868 AtomTy = AtomTy.withCVRQualifiers(
4869 CVR: pointerType->getPointeeType().getCVRQualifiers());
4870 QualType PointerQT = Context.getPointerType(T: AtomTy);
4871 pointerType = PointerQT->getAs<PointerType>();
4872 Ptr = ImpCastExprToType(E: Ptr, Type: PointerQT, CK: CK_BitCast).get();
4873 ValType = AtomTy;
4874 }
4875
4876 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4877 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4878 Diag(Loc: ExprRange.getBegin(),
4879 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
4880 << 0 << Ptr->getType() << Ptr->getSourceRange();
4881 return ExprError();
4882 }
4883
4884 // For an arithmetic operation, the implied arithmetic must be well-formed.
4885 // For _n operations, the value type must also be a valid atomic type.
4886 if (Form == Arithmetic || IsN) {
4887 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4888 // trivial type errors.
4889 auto IsAllowedValueType = [&](QualType ValType,
4890 unsigned AllowedType) -> bool {
4891 bool IsX87LongDouble =
4892 ValType->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
4893 &Context.getTargetInfo().getLongDoubleFormat() ==
4894 &llvm::APFloat::x87DoubleExtended();
4895 if (ValType->isIntegerType())
4896 return true;
4897 if (ValType->isPointerType())
4898 return AllowedType & AOEVT_Pointer;
4899 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4900 return false;
4901 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4902 if (IsX87LongDouble)
4903 return false;
4904 return true;
4905 };
4906 if (!IsAllowedValueType(ValType, ArithAllows)) {
4907 auto DID = ArithAllows & AOEVT_FP
4908 ? (ArithAllows & AOEVT_Pointer
4909 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4910 : diag::err_atomic_op_needs_atomic_int_or_fp)
4911 : (ArithAllows & AOEVT_Pointer
4912 ? diag::err_atomic_op_needs_atomic_int_or_ptr
4913 : diag::err_atomic_op_needs_atomic_int);
4914 Diag(Loc: ExprRange.getBegin(), DiagID: DID)
4915 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4916 return ExprError();
4917 }
4918 if (IsC11 && ValType->isPointerType() &&
4919 RequireCompleteType(Loc: Ptr->getBeginLoc(), T: ValType->getPointeeType(),
4920 DiagID: diag::err_incomplete_type)) {
4921 return ExprError();
4922 }
4923 }
4924
4925 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4926 !AtomTy->isScalarType()) {
4927 // For GNU atomics, require a trivially-copyable type. This is not part of
4928 // the GNU atomics specification but we enforce it for consistency with
4929 // other atomics which generally all require a trivially-copyable type. This
4930 // is because atomics just copy bits.
4931 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_trivial_copy)
4932 << Ptr->getType() << Ptr->getSourceRange();
4933 return ExprError();
4934 }
4935
4936 switch (ValType.getObjCLifetime()) {
4937 case Qualifiers::OCL_None:
4938 case Qualifiers::OCL_ExplicitNone:
4939 // okay
4940 break;
4941
4942 case Qualifiers::OCL_Weak:
4943 case Qualifiers::OCL_Strong:
4944 case Qualifiers::OCL_Autoreleasing:
4945 // FIXME: Can this happen? By this point, ValType should be known
4946 // to be trivially copyable.
4947 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_arc_atomic_ownership)
4948 << ValType << Ptr->getSourceRange();
4949 return ExprError();
4950 }
4951
4952 // All atomic operations have an overload which takes a pointer to a volatile
4953 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4954 // into the result or the other operands. Similarly atomic_load takes a
4955 // pointer to a const 'A'.
4956 ValType.removeLocalVolatile();
4957 ValType.removeLocalConst();
4958 QualType ResultType = ValType;
4959 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4960 Form == ClearByte)
4961 ResultType = Context.VoidTy;
4962 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4963 ResultType = Context.BoolTy;
4964
4965 // The type of a parameter passed 'by value'. In the GNU atomics, such
4966 // arguments are actually passed as pointers.
4967 QualType ByValType = ValType; // 'CP'
4968 bool IsPassedByAddress = false;
4969 if (!IsC11 && !IsHIP && !IsN) {
4970 ByValType = Ptr->getType();
4971 IsPassedByAddress = true;
4972 }
4973
4974 SmallVector<Expr *, 5> APIOrderedArgs;
4975 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4976 APIOrderedArgs.push_back(Elt: Args[0]);
4977 switch (Form) {
4978 case Init:
4979 case Load:
4980 APIOrderedArgs.push_back(Elt: Args[1]); // Val1/Order
4981 break;
4982 case LoadCopy:
4983 case Copy:
4984 case Arithmetic:
4985 case Xchg:
4986 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
4987 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4988 break;
4989 case GNUXchg:
4990 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
4991 APIOrderedArgs.push_back(Elt: Args[3]); // Val2
4992 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4993 break;
4994 case C11CmpXchg:
4995 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
4996 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
4997 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4998 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
4999 break;
5000 case GNUCmpXchg:
5001 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5002 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
5003 APIOrderedArgs.push_back(Elt: Args[5]); // Weak
5004 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5005 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
5006 break;
5007 case TestAndSetByte:
5008 case ClearByte:
5009 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5010 break;
5011 }
5012 } else
5013 APIOrderedArgs.append(in_start: Args.begin(), in_end: Args.end());
5014
5015 // The first argument's non-CV pointer type is used to deduce the type of
5016 // subsequent arguments, except for:
5017 // - weak flag (always converted to bool)
5018 // - memory order (always converted to int)
5019 // - scope (always converted to int)
5020 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5021 QualType Ty;
5022 if (i < NumVals[Form] + 1) {
5023 switch (i) {
5024 case 0:
5025 // The first argument is always a pointer. It has a fixed type.
5026 // It is always dereferenced, a nullptr is undefined.
5027 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5028 // Nothing else to do: we already know all we want about this pointer.
5029 continue;
5030 case 1:
5031 // The second argument is the non-atomic operand. For arithmetic, this
5032 // is always passed by value, and for a compare_exchange it is always
5033 // passed by address. For the rest, GNU uses by-address and C11 uses
5034 // by-value.
5035 assert(Form != Load);
5036 if (Form == Arithmetic && ValType->isPointerType())
5037 Ty = Context.getPointerDiffType();
5038 else if (Form == Init || Form == Arithmetic)
5039 Ty = ValType;
5040 else if (Form == Copy || Form == Xchg) {
5041 if (IsPassedByAddress) {
5042 // The value pointer is always dereferenced, a nullptr is undefined.
5043 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i],
5044 CallSiteLoc: ExprRange.getBegin());
5045 }
5046 Ty = ByValType;
5047 } else {
5048 Expr *ValArg = APIOrderedArgs[i];
5049 // The value pointer is always dereferenced, a nullptr is undefined.
5050 CheckNonNullArgument(S&: *this, ArgExpr: ValArg, CallSiteLoc: ExprRange.getBegin());
5051 LangAS AS = LangAS::Default;
5052 // Keep address space of non-atomic pointer type.
5053 if (const PointerType *PtrTy =
5054 ValArg->getType()->getAs<PointerType>()) {
5055 AS = PtrTy->getPointeeType().getAddressSpace();
5056 }
5057 Ty = Context.getPointerType(
5058 T: Context.getAddrSpaceQualType(T: ValType.getUnqualifiedType(), AddressSpace: AS));
5059 }
5060 break;
5061 case 2:
5062 // The third argument to compare_exchange / GNU exchange is the desired
5063 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5064 if (IsPassedByAddress)
5065 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5066 Ty = ByValType;
5067 break;
5068 case 3:
5069 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5070 Ty = Context.BoolTy;
5071 break;
5072 }
5073 } else {
5074 // The order(s) and scope are always converted to int.
5075 Ty = Context.IntTy;
5076 }
5077
5078 InitializedEntity Entity =
5079 InitializedEntity::InitializeParameter(Context, Type: Ty, Consumed: false);
5080 ExprResult Arg = APIOrderedArgs[i];
5081 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5082 if (Arg.isInvalid())
5083 return true;
5084 APIOrderedArgs[i] = Arg.get();
5085 }
5086
5087 // Permute the arguments into a 'consistent' order.
5088 SmallVector<Expr*, 5> SubExprs;
5089 SubExprs.push_back(Elt: Ptr);
5090 switch (Form) {
5091 case Init:
5092 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5093 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5094 break;
5095 case Load:
5096 case TestAndSetByte:
5097 case ClearByte:
5098 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Order
5099 break;
5100 case LoadCopy:
5101 case Copy:
5102 case Arithmetic:
5103 case Xchg:
5104 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Order
5105 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5106 break;
5107 case GNUXchg:
5108 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5109 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5110 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5111 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5112 break;
5113 case C11CmpXchg:
5114 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5115 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5116 SubExprs.push_back(Elt: APIOrderedArgs[4]); // OrderFail
5117 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5118 break;
5119 case GNUCmpXchg:
5120 SubExprs.push_back(Elt: APIOrderedArgs[4]); // Order
5121 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5122 SubExprs.push_back(Elt: APIOrderedArgs[5]); // OrderFail
5123 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5124 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Weak
5125 break;
5126 }
5127
5128 // If the memory orders are constants, check they are valid.
5129 if (SubExprs.size() >= 2 && Form != Init) {
5130 std::optional<llvm::APSInt> Success =
5131 SubExprs[1]->getIntegerConstantExpr(Ctx: Context);
5132 if (Success && !isValidOrderingForOp(Ordering: Success->getSExtValue(), Op)) {
5133 Diag(Loc: SubExprs[1]->getBeginLoc(),
5134 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5135 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5136 << SubExprs[1]->getSourceRange();
5137 }
5138 if (SubExprs.size() >= 5) {
5139 if (std::optional<llvm::APSInt> Failure =
5140 SubExprs[3]->getIntegerConstantExpr(Ctx: Context)) {
5141 if (!llvm::is_contained(
5142 Set: {llvm::AtomicOrderingCABI::relaxed,
5143 llvm::AtomicOrderingCABI::consume,
5144 llvm::AtomicOrderingCABI::acquire,
5145 llvm::AtomicOrderingCABI::seq_cst},
5146 Element: (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5147 Diag(Loc: SubExprs[3]->getBeginLoc(),
5148 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5149 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5150 }
5151 }
5152 }
5153 }
5154
5155 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5156 auto *Scope = Args[Args.size() - 1];
5157 if (std::optional<llvm::APSInt> Result =
5158 Scope->getIntegerConstantExpr(Ctx: Context)) {
5159 if (!ScopeModel->isValid(S: Result->getZExtValue()))
5160 Diag(Loc: Scope->getBeginLoc(), DiagID: diag::err_atomic_op_has_invalid_sync_scope)
5161 << Scope->getSourceRange();
5162 }
5163 SubExprs.push_back(Elt: Scope);
5164 }
5165
5166 AtomicExpr *AE = new (Context)
5167 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5168
5169 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5170 Op == AtomicExpr::AO__c11_atomic_store ||
5171 Op == AtomicExpr::AO__opencl_atomic_load ||
5172 Op == AtomicExpr::AO__hip_atomic_load ||
5173 Op == AtomicExpr::AO__opencl_atomic_store ||
5174 Op == AtomicExpr::AO__hip_atomic_store) &&
5175 Context.AtomicUsesUnsupportedLibcall(E: AE))
5176 Diag(Loc: AE->getBeginLoc(), DiagID: diag::err_atomic_load_store_uses_lib)
5177 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5178 Op == AtomicExpr::AO__opencl_atomic_load ||
5179 Op == AtomicExpr::AO__hip_atomic_load)
5180 ? 0
5181 : 1);
5182
5183 if (ValType->isBitIntType()) {
5184 Diag(Loc: Ptr->getExprLoc(), DiagID: diag::err_atomic_builtin_bit_int_prohibit);
5185 return ExprError();
5186 }
5187
5188 return AE;
5189}
5190
5191/// checkBuiltinArgument - Given a call to a builtin function, perform
5192/// normal type-checking on the given argument, updating the call in
5193/// place. This is useful when a builtin function requires custom
5194/// type-checking for some of its arguments but not necessarily all of
5195/// them.
5196///
5197/// Returns true on error.
5198static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5199 FunctionDecl *Fn = E->getDirectCallee();
5200 assert(Fn && "builtin call without direct callee!");
5201
5202 ParmVarDecl *Param = Fn->getParamDecl(i: ArgIndex);
5203 InitializedEntity Entity =
5204 InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Param);
5205
5206 ExprResult Arg = E->getArg(Arg: ArgIndex);
5207 Arg = S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5208 if (Arg.isInvalid())
5209 return true;
5210
5211 E->setArg(Arg: ArgIndex, ArgExpr: Arg.get());
5212 return false;
5213}
5214
5215ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5216 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5217 Expr *Callee = TheCall->getCallee();
5218 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Callee->IgnoreParenCasts());
5219 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
5220
5221 // Ensure that we have at least one argument to do type inference from.
5222 if (TheCall->getNumArgs() < 1) {
5223 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5224 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5225 << Callee->getSourceRange();
5226 return ExprError();
5227 }
5228
5229 // Inspect the first argument of the atomic builtin. This should always be
5230 // a pointer type, whose element is an integral scalar or pointer type.
5231 // Because it is a pointer type, we don't have to worry about any implicit
5232 // casts here.
5233 // FIXME: We don't allow floating point scalars as input.
5234 Expr *FirstArg = TheCall->getArg(Arg: 0);
5235 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(E: FirstArg);
5236 if (FirstArgResult.isInvalid())
5237 return ExprError();
5238 FirstArg = FirstArgResult.get();
5239 TheCall->setArg(Arg: 0, ArgExpr: FirstArg);
5240
5241 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5242 if (!pointerType) {
5243 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5244 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5245 return ExprError();
5246 }
5247
5248 QualType ValType = pointerType->getPointeeType();
5249 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5250 !ValType->isBlockPointerType()) {
5251 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer_intptr)
5252 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5253 return ExprError();
5254 }
5255 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5256 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5257 Diag(Loc: FirstArg->getBeginLoc(),
5258 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5259 << 1 << ValType << FirstArg->getSourceRange();
5260 return ExprError();
5261 }
5262
5263 if (ValType.isConstQualified()) {
5264 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_cannot_be_const)
5265 << FirstArg->getType() << FirstArg->getSourceRange();
5266 return ExprError();
5267 }
5268
5269 switch (ValType.getObjCLifetime()) {
5270 case Qualifiers::OCL_None:
5271 case Qualifiers::OCL_ExplicitNone:
5272 // okay
5273 break;
5274
5275 case Qualifiers::OCL_Weak:
5276 case Qualifiers::OCL_Strong:
5277 case Qualifiers::OCL_Autoreleasing:
5278 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_arc_atomic_ownership)
5279 << ValType << FirstArg->getSourceRange();
5280 return ExprError();
5281 }
5282
5283 // Strip any qualifiers off ValType.
5284 ValType = ValType.getUnqualifiedType();
5285
5286 // The majority of builtins return a value, but a few have special return
5287 // types, so allow them to override appropriately below.
5288 QualType ResultType = ValType;
5289
5290 // We need to figure out which concrete builtin this maps onto. For example,
5291 // __sync_fetch_and_add with a 2 byte object turns into
5292 // __sync_fetch_and_add_2.
5293#define BUILTIN_ROW(x) \
5294 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5295 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5296
5297 static const unsigned BuiltinIndices[][5] = {
5298 BUILTIN_ROW(__sync_fetch_and_add),
5299 BUILTIN_ROW(__sync_fetch_and_sub),
5300 BUILTIN_ROW(__sync_fetch_and_or),
5301 BUILTIN_ROW(__sync_fetch_and_and),
5302 BUILTIN_ROW(__sync_fetch_and_xor),
5303 BUILTIN_ROW(__sync_fetch_and_nand),
5304
5305 BUILTIN_ROW(__sync_add_and_fetch),
5306 BUILTIN_ROW(__sync_sub_and_fetch),
5307 BUILTIN_ROW(__sync_and_and_fetch),
5308 BUILTIN_ROW(__sync_or_and_fetch),
5309 BUILTIN_ROW(__sync_xor_and_fetch),
5310 BUILTIN_ROW(__sync_nand_and_fetch),
5311
5312 BUILTIN_ROW(__sync_val_compare_and_swap),
5313 BUILTIN_ROW(__sync_bool_compare_and_swap),
5314 BUILTIN_ROW(__sync_lock_test_and_set),
5315 BUILTIN_ROW(__sync_lock_release),
5316 BUILTIN_ROW(__sync_swap)
5317 };
5318#undef BUILTIN_ROW
5319
5320 // Determine the index of the size.
5321 unsigned SizeIndex;
5322 switch (Context.getTypeSizeInChars(T: ValType).getQuantity()) {
5323 case 1: SizeIndex = 0; break;
5324 case 2: SizeIndex = 1; break;
5325 case 4: SizeIndex = 2; break;
5326 case 8: SizeIndex = 3; break;
5327 case 16: SizeIndex = 4; break;
5328 default:
5329 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_pointer_size)
5330 << FirstArg->getType() << FirstArg->getSourceRange();
5331 return ExprError();
5332 }
5333
5334 // Each of these builtins has one pointer argument, followed by some number of
5335 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5336 // that we ignore. Find out which row of BuiltinIndices to read from as well
5337 // as the number of fixed args.
5338 unsigned BuiltinID = FDecl->getBuiltinID();
5339 unsigned BuiltinIndex, NumFixed = 1;
5340 bool WarnAboutSemanticsChange = false;
5341 switch (BuiltinID) {
5342 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5343 case Builtin::BI__sync_fetch_and_add:
5344 case Builtin::BI__sync_fetch_and_add_1:
5345 case Builtin::BI__sync_fetch_and_add_2:
5346 case Builtin::BI__sync_fetch_and_add_4:
5347 case Builtin::BI__sync_fetch_and_add_8:
5348 case Builtin::BI__sync_fetch_and_add_16:
5349 BuiltinIndex = 0;
5350 break;
5351
5352 case Builtin::BI__sync_fetch_and_sub:
5353 case Builtin::BI__sync_fetch_and_sub_1:
5354 case Builtin::BI__sync_fetch_and_sub_2:
5355 case Builtin::BI__sync_fetch_and_sub_4:
5356 case Builtin::BI__sync_fetch_and_sub_8:
5357 case Builtin::BI__sync_fetch_and_sub_16:
5358 BuiltinIndex = 1;
5359 break;
5360
5361 case Builtin::BI__sync_fetch_and_or:
5362 case Builtin::BI__sync_fetch_and_or_1:
5363 case Builtin::BI__sync_fetch_and_or_2:
5364 case Builtin::BI__sync_fetch_and_or_4:
5365 case Builtin::BI__sync_fetch_and_or_8:
5366 case Builtin::BI__sync_fetch_and_or_16:
5367 BuiltinIndex = 2;
5368 break;
5369
5370 case Builtin::BI__sync_fetch_and_and:
5371 case Builtin::BI__sync_fetch_and_and_1:
5372 case Builtin::BI__sync_fetch_and_and_2:
5373 case Builtin::BI__sync_fetch_and_and_4:
5374 case Builtin::BI__sync_fetch_and_and_8:
5375 case Builtin::BI__sync_fetch_and_and_16:
5376 BuiltinIndex = 3;
5377 break;
5378
5379 case Builtin::BI__sync_fetch_and_xor:
5380 case Builtin::BI__sync_fetch_and_xor_1:
5381 case Builtin::BI__sync_fetch_and_xor_2:
5382 case Builtin::BI__sync_fetch_and_xor_4:
5383 case Builtin::BI__sync_fetch_and_xor_8:
5384 case Builtin::BI__sync_fetch_and_xor_16:
5385 BuiltinIndex = 4;
5386 break;
5387
5388 case Builtin::BI__sync_fetch_and_nand:
5389 case Builtin::BI__sync_fetch_and_nand_1:
5390 case Builtin::BI__sync_fetch_and_nand_2:
5391 case Builtin::BI__sync_fetch_and_nand_4:
5392 case Builtin::BI__sync_fetch_and_nand_8:
5393 case Builtin::BI__sync_fetch_and_nand_16:
5394 BuiltinIndex = 5;
5395 WarnAboutSemanticsChange = true;
5396 break;
5397
5398 case Builtin::BI__sync_add_and_fetch:
5399 case Builtin::BI__sync_add_and_fetch_1:
5400 case Builtin::BI__sync_add_and_fetch_2:
5401 case Builtin::BI__sync_add_and_fetch_4:
5402 case Builtin::BI__sync_add_and_fetch_8:
5403 case Builtin::BI__sync_add_and_fetch_16:
5404 BuiltinIndex = 6;
5405 break;
5406
5407 case Builtin::BI__sync_sub_and_fetch:
5408 case Builtin::BI__sync_sub_and_fetch_1:
5409 case Builtin::BI__sync_sub_and_fetch_2:
5410 case Builtin::BI__sync_sub_and_fetch_4:
5411 case Builtin::BI__sync_sub_and_fetch_8:
5412 case Builtin::BI__sync_sub_and_fetch_16:
5413 BuiltinIndex = 7;
5414 break;
5415
5416 case Builtin::BI__sync_and_and_fetch:
5417 case Builtin::BI__sync_and_and_fetch_1:
5418 case Builtin::BI__sync_and_and_fetch_2:
5419 case Builtin::BI__sync_and_and_fetch_4:
5420 case Builtin::BI__sync_and_and_fetch_8:
5421 case Builtin::BI__sync_and_and_fetch_16:
5422 BuiltinIndex = 8;
5423 break;
5424
5425 case Builtin::BI__sync_or_and_fetch:
5426 case Builtin::BI__sync_or_and_fetch_1:
5427 case Builtin::BI__sync_or_and_fetch_2:
5428 case Builtin::BI__sync_or_and_fetch_4:
5429 case Builtin::BI__sync_or_and_fetch_8:
5430 case Builtin::BI__sync_or_and_fetch_16:
5431 BuiltinIndex = 9;
5432 break;
5433
5434 case Builtin::BI__sync_xor_and_fetch:
5435 case Builtin::BI__sync_xor_and_fetch_1:
5436 case Builtin::BI__sync_xor_and_fetch_2:
5437 case Builtin::BI__sync_xor_and_fetch_4:
5438 case Builtin::BI__sync_xor_and_fetch_8:
5439 case Builtin::BI__sync_xor_and_fetch_16:
5440 BuiltinIndex = 10;
5441 break;
5442
5443 case Builtin::BI__sync_nand_and_fetch:
5444 case Builtin::BI__sync_nand_and_fetch_1:
5445 case Builtin::BI__sync_nand_and_fetch_2:
5446 case Builtin::BI__sync_nand_and_fetch_4:
5447 case Builtin::BI__sync_nand_and_fetch_8:
5448 case Builtin::BI__sync_nand_and_fetch_16:
5449 BuiltinIndex = 11;
5450 WarnAboutSemanticsChange = true;
5451 break;
5452
5453 case Builtin::BI__sync_val_compare_and_swap:
5454 case Builtin::BI__sync_val_compare_and_swap_1:
5455 case Builtin::BI__sync_val_compare_and_swap_2:
5456 case Builtin::BI__sync_val_compare_and_swap_4:
5457 case Builtin::BI__sync_val_compare_and_swap_8:
5458 case Builtin::BI__sync_val_compare_and_swap_16:
5459 BuiltinIndex = 12;
5460 NumFixed = 2;
5461 break;
5462
5463 case Builtin::BI__sync_bool_compare_and_swap:
5464 case Builtin::BI__sync_bool_compare_and_swap_1:
5465 case Builtin::BI__sync_bool_compare_and_swap_2:
5466 case Builtin::BI__sync_bool_compare_and_swap_4:
5467 case Builtin::BI__sync_bool_compare_and_swap_8:
5468 case Builtin::BI__sync_bool_compare_and_swap_16:
5469 BuiltinIndex = 13;
5470 NumFixed = 2;
5471 ResultType = Context.BoolTy;
5472 break;
5473
5474 case Builtin::BI__sync_lock_test_and_set:
5475 case Builtin::BI__sync_lock_test_and_set_1:
5476 case Builtin::BI__sync_lock_test_and_set_2:
5477 case Builtin::BI__sync_lock_test_and_set_4:
5478 case Builtin::BI__sync_lock_test_and_set_8:
5479 case Builtin::BI__sync_lock_test_and_set_16:
5480 BuiltinIndex = 14;
5481 break;
5482
5483 case Builtin::BI__sync_lock_release:
5484 case Builtin::BI__sync_lock_release_1:
5485 case Builtin::BI__sync_lock_release_2:
5486 case Builtin::BI__sync_lock_release_4:
5487 case Builtin::BI__sync_lock_release_8:
5488 case Builtin::BI__sync_lock_release_16:
5489 BuiltinIndex = 15;
5490 NumFixed = 0;
5491 ResultType = Context.VoidTy;
5492 break;
5493
5494 case Builtin::BI__sync_swap:
5495 case Builtin::BI__sync_swap_1:
5496 case Builtin::BI__sync_swap_2:
5497 case Builtin::BI__sync_swap_4:
5498 case Builtin::BI__sync_swap_8:
5499 case Builtin::BI__sync_swap_16:
5500 BuiltinIndex = 16;
5501 break;
5502 }
5503
5504 // Now that we know how many fixed arguments we expect, first check that we
5505 // have at least that many.
5506 if (TheCall->getNumArgs() < 1+NumFixed) {
5507 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5508 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5509 << Callee->getSourceRange();
5510 return ExprError();
5511 }
5512
5513 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
5514 << Callee->getSourceRange();
5515
5516 if (WarnAboutSemanticsChange) {
5517 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_sync_fetch_and_nand_semantics_change)
5518 << Callee->getSourceRange();
5519 }
5520
5521 // Get the decl for the concrete builtin from this, we can tell what the
5522 // concrete integer type we should convert to is.
5523 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5524 std::string NewBuiltinName = Context.BuiltinInfo.getName(ID: NewBuiltinID);
5525 FunctionDecl *NewBuiltinDecl;
5526 if (NewBuiltinID == BuiltinID)
5527 NewBuiltinDecl = FDecl;
5528 else {
5529 // Perform builtin lookup to avoid redeclaring it.
5530 DeclarationName DN(&Context.Idents.get(Name: NewBuiltinName));
5531 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5532 LookupName(R&: Res, S: TUScope, /*AllowBuiltinCreation=*/true);
5533 assert(Res.getFoundDecl());
5534 NewBuiltinDecl = dyn_cast<FunctionDecl>(Val: Res.getFoundDecl());
5535 if (!NewBuiltinDecl)
5536 return ExprError();
5537 }
5538
5539 // The first argument --- the pointer --- has a fixed type; we
5540 // deduce the types of the rest of the arguments accordingly. Walk
5541 // the remaining arguments, converting them to the deduced value type.
5542 for (unsigned i = 0; i != NumFixed; ++i) {
5543 ExprResult Arg = TheCall->getArg(Arg: i+1);
5544
5545 // GCC does an implicit conversion to the pointer or integer ValType. This
5546 // can fail in some cases (1i -> int**), check for this error case now.
5547 // Initialize the argument.
5548 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5549 Type: ValType, /*consume*/ Consumed: false);
5550 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5551 if (Arg.isInvalid())
5552 return ExprError();
5553
5554 // Okay, we have something that *can* be converted to the right type. Check
5555 // to see if there is a potentially weird extension going on here. This can
5556 // happen when you do an atomic operation on something like an char* and
5557 // pass in 42. The 42 gets converted to char. This is even more strange
5558 // for things like 45.123 -> char, etc.
5559 // FIXME: Do this check.
5560 TheCall->setArg(Arg: i+1, ArgExpr: Arg.get());
5561 }
5562
5563 // Create a new DeclRefExpr to refer to the new decl.
5564 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5565 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: NewBuiltinDecl,
5566 /*enclosing*/ RefersToEnclosingVariableOrCapture: false, NameLoc: DRE->getLocation(), T: Context.BuiltinFnTy,
5567 VK: DRE->getValueKind(), FoundD: nullptr, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
5568
5569 // Set the callee in the CallExpr.
5570 // FIXME: This loses syntactic information.
5571 QualType CalleePtrTy = Context.getPointerType(T: NewBuiltinDecl->getType());
5572 ExprResult PromotedCall = ImpCastExprToType(E: NewDRE, Type: CalleePtrTy,
5573 CK: CK_BuiltinFnToFnPtr);
5574 TheCall->setCallee(PromotedCall.get());
5575
5576 // Change the result type of the call to match the original value type. This
5577 // is arbitrary, but the codegen for these builtins ins design to handle it
5578 // gracefully.
5579 TheCall->setType(ResultType);
5580
5581 // Prohibit problematic uses of bit-precise integer types with atomic
5582 // builtins. The arguments would have already been converted to the first
5583 // argument's type, so only need to check the first argument.
5584 const auto *BitIntValType = ValType->getAs<BitIntType>();
5585 if (BitIntValType && !llvm::isPowerOf2_64(Value: BitIntValType->getNumBits())) {
5586 Diag(Loc: FirstArg->getExprLoc(), DiagID: diag::err_atomic_builtin_ext_int_size);
5587 return ExprError();
5588 }
5589
5590 return TheCallResult;
5591}
5592
5593ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5594 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5595 DeclRefExpr *DRE =
5596 cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
5597 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
5598 unsigned BuiltinID = FDecl->getBuiltinID();
5599 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5600 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5601 "Unexpected nontemporal load/store builtin!");
5602 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5603 unsigned numArgs = isStore ? 2 : 1;
5604
5605 // Ensure that we have the proper number of arguments.
5606 if (checkArgCount(Call: TheCall, DesiredArgCount: numArgs))
5607 return ExprError();
5608
5609 // Inspect the last argument of the nontemporal builtin. This should always
5610 // be a pointer type, from which we imply the type of the memory access.
5611 // Because it is a pointer type, we don't have to worry about any implicit
5612 // casts here.
5613 Expr *PointerArg = TheCall->getArg(Arg: numArgs - 1);
5614 ExprResult PointerArgResult =
5615 DefaultFunctionArrayLvalueConversion(E: PointerArg);
5616
5617 if (PointerArgResult.isInvalid())
5618 return ExprError();
5619 PointerArg = PointerArgResult.get();
5620 TheCall->setArg(Arg: numArgs - 1, ArgExpr: PointerArg);
5621
5622 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5623 if (!pointerType) {
5624 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_nontemporal_builtin_must_be_pointer)
5625 << PointerArg->getType() << PointerArg->getSourceRange();
5626 return ExprError();
5627 }
5628
5629 QualType ValType = pointerType->getPointeeType();
5630
5631 // Strip any qualifiers off ValType.
5632 ValType = ValType.getUnqualifiedType();
5633 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5634 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5635 !ValType->isVectorType()) {
5636 Diag(Loc: DRE->getBeginLoc(),
5637 DiagID: diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5638 << PointerArg->getType() << PointerArg->getSourceRange();
5639 return ExprError();
5640 }
5641
5642 if (!isStore) {
5643 TheCall->setType(ValType);
5644 return TheCallResult;
5645 }
5646
5647 ExprResult ValArg = TheCall->getArg(Arg: 0);
5648 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5649 Context, Type: ValType, /*consume*/ Consumed: false);
5650 ValArg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: ValArg);
5651 if (ValArg.isInvalid())
5652 return ExprError();
5653
5654 TheCall->setArg(Arg: 0, ArgExpr: ValArg.get());
5655 TheCall->setType(Context.VoidTy);
5656 return TheCallResult;
5657}
5658
5659/// CheckObjCString - Checks that the format string argument to the os_log()
5660/// and os_trace() functions is correct, and converts it to const char *.
5661ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5662 Arg = Arg->IgnoreParenCasts();
5663 auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
5664 if (!Literal) {
5665 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Val: Arg)) {
5666 Literal = ObjcLiteral->getString();
5667 }
5668 }
5669
5670 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5671 return ExprError(
5672 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_os_log_format_not_string_constant)
5673 << Arg->getSourceRange());
5674 }
5675
5676 ExprResult Result(Literal);
5677 QualType ResultTy = Context.getPointerType(T: Context.CharTy.withConst());
5678 InitializedEntity Entity =
5679 InitializedEntity::InitializeParameter(Context, Type: ResultTy, Consumed: false);
5680 Result = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Result);
5681 return Result;
5682}
5683
5684/// Check that the user is calling the appropriate va_start builtin for the
5685/// target and calling convention.
5686static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5687 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5688 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5689 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5690 TT.getArch() == llvm::Triple::aarch64_32);
5691 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5692 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5693 if (IsX64 || IsAArch64) {
5694 CallingConv CC = CC_C;
5695 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5696 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5697 if (IsMSVAStart) {
5698 // Don't allow this in System V ABI functions.
5699 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5700 return S.Diag(Loc: Fn->getBeginLoc(),
5701 DiagID: diag::err_ms_va_start_used_in_sysv_function);
5702 } else {
5703 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5704 // On x64 Windows, don't allow this in System V ABI functions.
5705 // (Yes, that means there's no corresponding way to support variadic
5706 // System V ABI functions on Windows.)
5707 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5708 (!IsWindowsOrUEFI && CC == CC_Win64))
5709 return S.Diag(Loc: Fn->getBeginLoc(),
5710 DiagID: diag::err_va_start_used_in_wrong_abi_function)
5711 << !IsWindowsOrUEFI;
5712 }
5713 return false;
5714 }
5715
5716 if (IsMSVAStart)
5717 return S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_builtin_x64_aarch64_only);
5718 return false;
5719}
5720
5721static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5722 ParmVarDecl **LastParam = nullptr) {
5723 // Determine whether the current function, block, or obj-c method is variadic
5724 // and get its parameter list.
5725 bool IsVariadic = false;
5726 ArrayRef<ParmVarDecl *> Params;
5727 DeclContext *Caller = S.CurContext;
5728 if (auto *Block = dyn_cast<BlockDecl>(Val: Caller)) {
5729 IsVariadic = Block->isVariadic();
5730 Params = Block->parameters();
5731 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: Caller)) {
5732 IsVariadic = FD->isVariadic();
5733 Params = FD->parameters();
5734 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Val: Caller)) {
5735 IsVariadic = MD->isVariadic();
5736 // FIXME: This isn't correct for methods (results in bogus warning).
5737 Params = MD->parameters();
5738 } else if (isa<CapturedDecl>(Val: Caller)) {
5739 // We don't support va_start in a CapturedDecl.
5740 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_captured_stmt);
5741 return true;
5742 } else {
5743 // This must be some other declcontext that parses exprs.
5744 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_outside_function);
5745 return true;
5746 }
5747
5748 if (!IsVariadic) {
5749 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_fixed_function);
5750 return true;
5751 }
5752
5753 if (LastParam)
5754 *LastParam = Params.empty() ? nullptr : Params.back();
5755
5756 return false;
5757}
5758
5759bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5760 Expr *Fn = TheCall->getCallee();
5761 if (checkVAStartABI(S&: *this, BuiltinID, Fn))
5762 return true;
5763
5764 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5765 // This builtin requires one argument (the va_list), allows two arguments,
5766 // but diagnoses more than two arguments. e.g.,
5767 // __builtin_c23_va_start(); // error
5768 // __builtin_c23_va_start(list); // ok
5769 // __builtin_c23_va_start(list, param); // ok
5770 // __builtin_c23_va_start(list, anything, anything); // error
5771 // This differs from the GCC behavior in that they accept the last case
5772 // with a warning, but it doesn't seem like a useful behavior to allow.
5773 if (checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
5774 return true;
5775 } else {
5776 // In C23 mode, va_start only needs one argument. However, the builtin still
5777 // requires two arguments (which matches the behavior of the GCC builtin),
5778 // <stdarg.h> passes `0` as the second argument in C23 mode.
5779 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
5780 return true;
5781 }
5782
5783 // Type-check the first argument normally.
5784 if (checkBuiltinArgument(S&: *this, E: TheCall, ArgIndex: 0))
5785 return true;
5786
5787 // Check that the current function is variadic, and get its last parameter.
5788 ParmVarDecl *LastParam;
5789 if (checkVAStartIsInVariadicFunction(S&: *this, Fn, LastParam: &LastParam))
5790 return true;
5791
5792 // Verify that the second argument to the builtin is the last non-variadic
5793 // argument of the current function or method. In C23 mode, if the call is
5794 // not to __builtin_c23_va_start, and the second argument is an integer
5795 // constant expression with value 0, then we don't bother with this check.
5796 // For __builtin_c23_va_start, we only perform the check for the second
5797 // argument being the last argument to the current function if there is a
5798 // second argument present.
5799 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5800 TheCall->getNumArgs() < 2) {
5801 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
5802 return false;
5803 }
5804
5805 const Expr *Arg = TheCall->getArg(Arg: 1)->IgnoreParenCasts();
5806 if (std::optional<llvm::APSInt> Val =
5807 TheCall->getArg(Arg: 1)->getIntegerConstantExpr(Ctx: Context);
5808 Val && LangOpts.C23 && *Val == 0 &&
5809 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5810 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
5811 return false;
5812 }
5813
5814 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5815 // next block.
5816 QualType Type;
5817 SourceLocation ParamLoc;
5818 bool IsCRegister = false;
5819 bool SecondArgIsLastNonVariadicArgument = false;
5820 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: Arg)) {
5821 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: DR->getDecl())) {
5822 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5823
5824 Type = PV->getType();
5825 ParamLoc = PV->getLocation();
5826 IsCRegister =
5827 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5828 }
5829 }
5830
5831 if (!SecondArgIsLastNonVariadicArgument)
5832 Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
5833 DiagID: diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5834 else if (IsCRegister || Type->isReferenceType() ||
5835 Type->isSpecificBuiltinType(K: BuiltinType::Float) || [=] {
5836 // Promotable integers are UB, but enumerations need a bit of
5837 // extra checking to see what their promotable type actually is.
5838 if (!Context.isPromotableIntegerType(T: Type))
5839 return false;
5840 const auto *ED = Type->getAsEnumDecl();
5841 if (!ED)
5842 return true;
5843 return !Context.typesAreCompatible(T1: ED->getPromotionType(), T2: Type);
5844 }()) {
5845 unsigned Reason = 0;
5846 if (Type->isReferenceType()) Reason = 1;
5847 else if (IsCRegister) Reason = 2;
5848 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_va_start_type_is_undefined) << Reason;
5849 Diag(Loc: ParamLoc, DiagID: diag::note_parameter_type) << Type;
5850 }
5851
5852 return false;
5853}
5854
5855bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5856 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5857 const LangOptions &LO = getLangOpts();
5858
5859 if (LO.CPlusPlus)
5860 return Arg->getType()
5861 .getCanonicalType()
5862 .getTypePtr()
5863 ->getPointeeType()
5864 .withoutLocalFastQualifiers() == Context.CharTy;
5865
5866 // In C, allow aliasing through `char *`, this is required for AArch64 at
5867 // least.
5868 return true;
5869 };
5870
5871 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5872 // const char *named_addr);
5873
5874 Expr *Func = Call->getCallee();
5875
5876 if (Call->getNumArgs() < 3)
5877 return Diag(Loc: Call->getEndLoc(),
5878 DiagID: diag::err_typecheck_call_too_few_args_at_least)
5879 << 0 /*function call*/ << 3 << Call->getNumArgs()
5880 << /*is non object*/ 0;
5881
5882 // Type-check the first argument normally.
5883 if (checkBuiltinArgument(S&: *this, E: Call, ArgIndex: 0))
5884 return true;
5885
5886 // Check that the current function is variadic.
5887 if (checkVAStartIsInVariadicFunction(S&: *this, Fn: Func))
5888 return true;
5889
5890 // __va_start on Windows does not validate the parameter qualifiers
5891
5892 const Expr *Arg1 = Call->getArg(Arg: 1)->IgnoreParens();
5893 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5894
5895 const Expr *Arg2 = Call->getArg(Arg: 2)->IgnoreParens();
5896 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5897
5898 const QualType &ConstCharPtrTy =
5899 Context.getPointerType(T: Context.CharTy.withConst());
5900 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5901 Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
5902 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5903 << 0 /* qualifier difference */
5904 << 3 /* parameter mismatch */
5905 << 2 << Arg1->getType() << ConstCharPtrTy;
5906
5907 const QualType SizeTy = Context.getSizeType();
5908 if (!Context.hasSameType(
5909 T1: Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers(),
5910 T2: SizeTy))
5911 Diag(Loc: Arg2->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
5912 << Arg2->getType() << SizeTy << 1 /* different class */
5913 << 0 /* qualifier difference */
5914 << 3 /* parameter mismatch */
5915 << 3 << Arg2->getType() << SizeTy;
5916
5917 return false;
5918}
5919
5920bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5921 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
5922 return true;
5923
5924 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5925 TheCall->getFPFeaturesInEffect(LO: getLangOpts()).getNoHonorNaNs())
5926 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
5927 << 1 << 0 << TheCall->getSourceRange();
5928
5929 ExprResult OrigArg0 = TheCall->getArg(Arg: 0);
5930 ExprResult OrigArg1 = TheCall->getArg(Arg: 1);
5931
5932 // Do standard promotions between the two arguments, returning their common
5933 // type.
5934 QualType Res = UsualArithmeticConversions(
5935 LHS&: OrigArg0, RHS&: OrigArg1, Loc: TheCall->getExprLoc(), ACK: ArithConvKind::Comparison);
5936 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5937 return true;
5938
5939 // Make sure any conversions are pushed back into the call; this is
5940 // type safe since unordered compare builtins are declared as "_Bool
5941 // foo(...)".
5942 TheCall->setArg(Arg: 0, ArgExpr: OrigArg0.get());
5943 TheCall->setArg(Arg: 1, ArgExpr: OrigArg1.get());
5944
5945 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5946 return false;
5947
5948 // If the common type isn't a real floating type, then the arguments were
5949 // invalid for this operation.
5950 if (Res.isNull() || !Res->isRealFloatingType())
5951 return Diag(Loc: OrigArg0.get()->getBeginLoc(),
5952 DiagID: diag::err_typecheck_call_invalid_ordered_compare)
5953 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5954 << SourceRange(OrigArg0.get()->getBeginLoc(),
5955 OrigArg1.get()->getEndLoc());
5956
5957 return false;
5958}
5959
5960bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5961 unsigned BuiltinID) {
5962 if (checkArgCount(Call: TheCall, DesiredArgCount: NumArgs))
5963 return true;
5964
5965 FPOptions FPO = TheCall->getFPFeaturesInEffect(LO: getLangOpts());
5966 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5967 BuiltinID == Builtin::BI__builtin_isinf ||
5968 BuiltinID == Builtin::BI__builtin_isinf_sign))
5969 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
5970 << 0 << 0 << TheCall->getSourceRange();
5971
5972 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5973 BuiltinID == Builtin::BI__builtin_isunordered))
5974 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
5975 << 1 << 0 << TheCall->getSourceRange();
5976
5977 bool IsFPClass = NumArgs == 2;
5978
5979 // Find out position of floating-point argument.
5980 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5981
5982 // We can count on all parameters preceding the floating-point just being int.
5983 // Try all of those.
5984 for (unsigned i = 0; i < FPArgNo; ++i) {
5985 Expr *Arg = TheCall->getArg(Arg: i);
5986
5987 if (Arg->isTypeDependent())
5988 return false;
5989
5990 ExprResult Res = PerformImplicitConversion(From: Arg, ToType: Context.IntTy,
5991 Action: AssignmentAction::Passing);
5992
5993 if (Res.isInvalid())
5994 return true;
5995 TheCall->setArg(Arg: i, ArgExpr: Res.get());
5996 }
5997
5998 Expr *OrigArg = TheCall->getArg(Arg: FPArgNo);
5999
6000 if (OrigArg->isTypeDependent())
6001 return false;
6002
6003 // Usual Unary Conversions will convert half to float, which we want for
6004 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6005 // type how it is, but do normal L->Rvalue conversions.
6006 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
6007 ExprResult Res = UsualUnaryConversions(E: OrigArg);
6008
6009 if (!Res.isUsable())
6010 return true;
6011 OrigArg = Res.get();
6012 } else {
6013 ExprResult Res = DefaultFunctionArrayLvalueConversion(E: OrigArg);
6014
6015 if (!Res.isUsable())
6016 return true;
6017 OrigArg = Res.get();
6018 }
6019 TheCall->setArg(Arg: FPArgNo, ArgExpr: OrigArg);
6020
6021 QualType VectorResultTy;
6022 QualType ElementTy = OrigArg->getType();
6023 // TODO: When all classification function are implemented with is_fpclass,
6024 // vector argument can be supported in all of them.
6025 if (ElementTy->isVectorType() && IsFPClass) {
6026 VectorResultTy = GetSignedVectorType(V: ElementTy);
6027 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6028 }
6029
6030 // This operation requires a non-_Complex floating-point number.
6031 if (!ElementTy->isRealFloatingType())
6032 return Diag(Loc: OrigArg->getBeginLoc(),
6033 DiagID: diag::err_typecheck_call_invalid_unary_fp)
6034 << OrigArg->getType() << OrigArg->getSourceRange();
6035
6036 // __builtin_isfpclass has integer parameter that specify test mask. It is
6037 // passed in (...), so it should be analyzed completely here.
6038 if (IsFPClass)
6039 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: llvm::fcAllFlags))
6040 return true;
6041
6042 // TODO: enable this code to all classification functions.
6043 if (IsFPClass) {
6044 QualType ResultTy;
6045 if (!VectorResultTy.isNull())
6046 ResultTy = VectorResultTy;
6047 else
6048 ResultTy = Context.IntTy;
6049 TheCall->setType(ResultTy);
6050 }
6051
6052 return false;
6053}
6054
6055bool Sema::BuiltinComplex(CallExpr *TheCall) {
6056 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6057 return true;
6058
6059 bool Dependent = false;
6060 for (unsigned I = 0; I != 2; ++I) {
6061 Expr *Arg = TheCall->getArg(Arg: I);
6062 QualType T = Arg->getType();
6063 if (T->isDependentType()) {
6064 Dependent = true;
6065 continue;
6066 }
6067
6068 // Despite supporting _Complex int, GCC requires a real floating point type
6069 // for the operands of __builtin_complex.
6070 if (!T->isRealFloatingType()) {
6071 return Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_typecheck_call_requires_real_fp)
6072 << Arg->getType() << Arg->getSourceRange();
6073 }
6074
6075 ExprResult Converted = DefaultLvalueConversion(E: Arg);
6076 if (Converted.isInvalid())
6077 return true;
6078 TheCall->setArg(Arg: I, ArgExpr: Converted.get());
6079 }
6080
6081 if (Dependent) {
6082 TheCall->setType(Context.DependentTy);
6083 return false;
6084 }
6085
6086 Expr *Real = TheCall->getArg(Arg: 0);
6087 Expr *Imag = TheCall->getArg(Arg: 1);
6088 if (!Context.hasSameType(T1: Real->getType(), T2: Imag->getType())) {
6089 return Diag(Loc: Real->getBeginLoc(),
6090 DiagID: diag::err_typecheck_call_different_arg_types)
6091 << Real->getType() << Imag->getType()
6092 << Real->getSourceRange() << Imag->getSourceRange();
6093 }
6094
6095 TheCall->setType(Context.getComplexType(T: Real->getType()));
6096 return false;
6097}
6098
6099/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6100// This is declared to take (...), so we have to check everything.
6101ExprResult Sema::BuiltinShuffleVector(CallExpr *TheCall) {
6102 unsigned NumArgs = TheCall->getNumArgs();
6103 if (NumArgs < 2)
6104 return ExprError(Diag(Loc: TheCall->getEndLoc(),
6105 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6106 << 0 /*function call*/ << 2 << NumArgs
6107 << /*is non object*/ 0 << TheCall->getSourceRange());
6108
6109 // Determine which of the following types of shufflevector we're checking:
6110 // 1) unary, vector mask: (lhs, mask)
6111 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6112 QualType ResType = TheCall->getArg(Arg: 0)->getType();
6113 unsigned NumElements = 0;
6114
6115 if (!TheCall->getArg(Arg: 0)->isTypeDependent() &&
6116 !TheCall->getArg(Arg: 1)->isTypeDependent()) {
6117 QualType LHSType = TheCall->getArg(Arg: 0)->getType();
6118 QualType RHSType = TheCall->getArg(Arg: 1)->getType();
6119
6120 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6121 return ExprError(
6122 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_builtin_non_vector)
6123 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6124 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6125 TheCall->getArg(Arg: 1)->getEndLoc()));
6126
6127 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6128 unsigned NumResElements = NumArgs - 2;
6129
6130 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6131 // with mask. If so, verify that RHS is an integer vector type with the
6132 // same number of elts as lhs.
6133 if (NumArgs == 2) {
6134 if (!RHSType->hasIntegerRepresentation() ||
6135 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6136 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6137 DiagID: diag::err_vec_builtin_incompatible_vector)
6138 << TheCall->getDirectCallee()
6139 << /*isMoreThanTwoArgs*/ false
6140 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
6141 TheCall->getArg(Arg: 1)->getEndLoc()));
6142 } else if (!Context.hasSameUnqualifiedType(T1: LHSType, T2: RHSType)) {
6143 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6144 DiagID: diag::err_vec_builtin_incompatible_vector)
6145 << TheCall->getDirectCallee()
6146 << /*isMoreThanTwoArgs*/ false
6147 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6148 TheCall->getArg(Arg: 1)->getEndLoc()));
6149 } else if (NumElements != NumResElements) {
6150 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6151 ResType = ResType->isExtVectorType()
6152 ? Context.getExtVectorType(VectorType: EltType, NumElts: NumResElements)
6153 : Context.getVectorType(VectorType: EltType, NumElts: NumResElements,
6154 VecKind: VectorKind::Generic);
6155 }
6156 }
6157
6158 for (unsigned I = 2; I != NumArgs; ++I) {
6159 Expr *Arg = TheCall->getArg(Arg: I);
6160 if (Arg->isTypeDependent() || Arg->isValueDependent())
6161 continue;
6162
6163 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
6164 if (!Result)
6165 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6166 DiagID: diag::err_shufflevector_nonconstant_argument)
6167 << Arg->getSourceRange());
6168
6169 // Allow -1 which will be translated to undef in the IR.
6170 if (Result->isSigned() && Result->isAllOnes())
6171 ;
6172 else if (Result->getActiveBits() > 64 ||
6173 Result->getZExtValue() >= NumElements * 2)
6174 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6175 DiagID: diag::err_shufflevector_argument_too_large)
6176 << Arg->getSourceRange());
6177
6178 TheCall->setArg(Arg: I, ArgExpr: ConstantExpr::Create(Context, E: Arg, Result: APValue(*Result)));
6179 }
6180
6181 auto *Result = new (Context) ShuffleVectorExpr(
6182 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6183 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6184
6185 // All moved to Result.
6186 TheCall->shrinkNumArgs(NewNumArgs: 0);
6187 return Result;
6188}
6189
6190ExprResult Sema::ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6191 SourceLocation BuiltinLoc,
6192 SourceLocation RParenLoc) {
6193 ExprValueKind VK = VK_PRValue;
6194 ExprObjectKind OK = OK_Ordinary;
6195 QualType DstTy = TInfo->getType();
6196 QualType SrcTy = E->getType();
6197
6198 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6199 return ExprError(Diag(Loc: BuiltinLoc,
6200 DiagID: diag::err_convertvector_non_vector)
6201 << E->getSourceRange());
6202 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6203 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_builtin_non_vector_type)
6204 << "second"
6205 << "__builtin_convertvector");
6206
6207 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6208 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6209 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6210 if (SrcElts != DstElts)
6211 return ExprError(Diag(Loc: BuiltinLoc,
6212 DiagID: diag::err_convertvector_incompatible_vector)
6213 << E->getSourceRange());
6214 }
6215
6216 return ConvertVectorExpr::Create(C: Context, SrcExpr: E, TI: TInfo, DstType: DstTy, VK, OK, BuiltinLoc,
6217 RParenLoc, FPFeatures: CurFPFeatureOverrides());
6218}
6219
6220bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6221 unsigned NumArgs = TheCall->getNumArgs();
6222
6223 if (NumArgs > 3)
6224 return Diag(Loc: TheCall->getEndLoc(),
6225 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6226 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6227 << TheCall->getSourceRange();
6228
6229 // Argument 0 is checked for us and the remaining arguments must be
6230 // constant integers.
6231 for (unsigned i = 1; i != NumArgs; ++i)
6232 if (BuiltinConstantArgRange(TheCall, ArgNum: i, Low: 0, High: i == 1 ? 1 : 3))
6233 return true;
6234
6235 return false;
6236}
6237
6238bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6239 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6240 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
6241 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6242 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
6243 return true;
6244 Expr *Arg = TheCall->getArg(Arg: 0);
6245 if (Arg->isInstantiationDependent())
6246 return false;
6247
6248 QualType ArgTy = Arg->getType();
6249 if (!ArgTy->hasFloatingRepresentation())
6250 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_expect_flt_or_vector)
6251 << ArgTy;
6252 if (Arg->isLValue()) {
6253 ExprResult FirstArg = DefaultLvalueConversion(E: Arg);
6254 TheCall->setArg(Arg: 0, ArgExpr: FirstArg.get());
6255 }
6256 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
6257 return false;
6258}
6259
6260bool Sema::BuiltinAssume(CallExpr *TheCall) {
6261 Expr *Arg = TheCall->getArg(Arg: 0);
6262 if (Arg->isInstantiationDependent()) return false;
6263
6264 if (Arg->HasSideEffects(Ctx: Context))
6265 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_assume_side_effects)
6266 << Arg->getSourceRange()
6267 << cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getIdentifier();
6268
6269 return false;
6270}
6271
6272bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6273 // The alignment must be a constant integer.
6274 Expr *Arg = TheCall->getArg(Arg: 1);
6275
6276 // We can't check the value of a dependent argument.
6277 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6278 if (const auto *UE =
6279 dyn_cast<UnaryExprOrTypeTraitExpr>(Val: Arg->IgnoreParenImpCasts()))
6280 if (UE->getKind() == UETT_AlignOf ||
6281 UE->getKind() == UETT_PreferredAlignOf)
6282 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca_align_alignof)
6283 << Arg->getSourceRange();
6284
6285 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Ctx: Context);
6286
6287 if (!Result.isPowerOf2())
6288 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6289 << Arg->getSourceRange();
6290
6291 if (Result < Context.getCharWidth())
6292 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_small)
6293 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6294
6295 if (Result > std::numeric_limits<int32_t>::max())
6296 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_big)
6297 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6298 }
6299
6300 return false;
6301}
6302
6303bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6304 if (checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
6305 return true;
6306
6307 unsigned NumArgs = TheCall->getNumArgs();
6308 Expr *FirstArg = TheCall->getArg(Arg: 0);
6309
6310 {
6311 ExprResult FirstArgResult =
6312 DefaultFunctionArrayLvalueConversion(E: FirstArg);
6313 if (!FirstArgResult.get()->getType()->isPointerType()) {
6314 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_assume_aligned_invalid_arg)
6315 << TheCall->getSourceRange();
6316 return true;
6317 }
6318 TheCall->setArg(Arg: 0, ArgExpr: FirstArgResult.get());
6319 }
6320
6321 // The alignment must be a constant integer.
6322 Expr *SecondArg = TheCall->getArg(Arg: 1);
6323
6324 // We can't check the value of a dependent argument.
6325 if (!SecondArg->isValueDependent()) {
6326 llvm::APSInt Result;
6327 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
6328 return true;
6329
6330 if (!Result.isPowerOf2())
6331 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6332 << SecondArg->getSourceRange();
6333
6334 if (Result > Sema::MaximumAlignment)
6335 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_assume_aligned_too_great)
6336 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6337
6338 TheCall->setArg(Arg: 1,
6339 ArgExpr: ConstantExpr::Create(Context, E: SecondArg, Result: APValue(Result)));
6340 }
6341
6342 if (NumArgs > 2) {
6343 Expr *ThirdArg = TheCall->getArg(Arg: 2);
6344 if (convertArgumentToType(S&: *this, Value&: ThirdArg, Ty: Context.getSizeType()))
6345 return true;
6346 TheCall->setArg(Arg: 2, ArgExpr: ThirdArg);
6347 }
6348
6349 return false;
6350}
6351
6352bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6353 unsigned BuiltinID =
6354 cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getBuiltinID();
6355 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6356
6357 unsigned NumArgs = TheCall->getNumArgs();
6358 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6359 if (NumArgs < NumRequiredArgs) {
6360 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args)
6361 << 0 /* function call */ << NumRequiredArgs << NumArgs
6362 << /*is non object*/ 0 << TheCall->getSourceRange();
6363 }
6364 if (NumArgs >= NumRequiredArgs + 0x100) {
6365 return Diag(Loc: TheCall->getEndLoc(),
6366 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6367 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6368 << /*is non object*/ 0 << TheCall->getSourceRange();
6369 }
6370 unsigned i = 0;
6371
6372 // For formatting call, check buffer arg.
6373 if (!IsSizeCall) {
6374 ExprResult Arg(TheCall->getArg(Arg: i));
6375 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6376 Context, Type: Context.VoidPtrTy, Consumed: false);
6377 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
6378 if (Arg.isInvalid())
6379 return true;
6380 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6381 i++;
6382 }
6383
6384 // Check string literal arg.
6385 unsigned FormatIdx = i;
6386 {
6387 ExprResult Arg = CheckOSLogFormatStringArg(Arg: TheCall->getArg(Arg: i));
6388 if (Arg.isInvalid())
6389 return true;
6390 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6391 i++;
6392 }
6393
6394 // Make sure variadic args are scalar.
6395 unsigned FirstDataArg = i;
6396 while (i < NumArgs) {
6397 ExprResult Arg = DefaultVariadicArgumentPromotion(
6398 E: TheCall->getArg(Arg: i), CT: VariadicCallType::Function, FDecl: nullptr);
6399 if (Arg.isInvalid())
6400 return true;
6401 CharUnits ArgSize = Context.getTypeSizeInChars(T: Arg.get()->getType());
6402 if (ArgSize.getQuantity() >= 0x100) {
6403 return Diag(Loc: Arg.get()->getEndLoc(), DiagID: diag::err_os_log_argument_too_big)
6404 << i << (int)ArgSize.getQuantity() << 0xff
6405 << TheCall->getSourceRange();
6406 }
6407 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6408 i++;
6409 }
6410
6411 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6412 // call to avoid duplicate diagnostics.
6413 if (!IsSizeCall) {
6414 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6415 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6416 bool Success = CheckFormatArguments(
6417 Args, FAPK: FAPK_Variadic, ReferenceFormatString: nullptr, format_idx: FormatIdx, firstDataArg: FirstDataArg,
6418 Type: FormatStringType::OSLog, CallType: VariadicCallType::Function,
6419 Loc: TheCall->getBeginLoc(), range: SourceRange(), CheckedVarArgs);
6420 if (!Success)
6421 return true;
6422 }
6423
6424 if (IsSizeCall) {
6425 TheCall->setType(Context.getSizeType());
6426 } else {
6427 TheCall->setType(Context.VoidPtrTy);
6428 }
6429 return false;
6430}
6431
6432bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6433 llvm::APSInt &Result) {
6434 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6435
6436 if (Arg->isTypeDependent() || Arg->isValueDependent())
6437 return false;
6438
6439 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Ctx: Context);
6440 if (!R) {
6441 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
6442 auto *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
6443 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_constant_integer_arg_type)
6444 << FDecl->getDeclName() << Arg->getSourceRange();
6445 }
6446 Result = *R;
6447
6448 return false;
6449}
6450
6451bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6452 int High, bool RangeIsError) {
6453 if (isConstantEvaluatedContext())
6454 return false;
6455 llvm::APSInt Result;
6456
6457 // We can't check the value of a dependent argument.
6458 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6459 if (Arg->isTypeDependent() || Arg->isValueDependent())
6460 return false;
6461
6462 // Check constant-ness first.
6463 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6464 return true;
6465
6466 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6467 if (RangeIsError)
6468 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_invalid_range)
6469 << toString(I: Result, Radix: 10) << Low << High << Arg->getSourceRange();
6470 else
6471 // Defer the warning until we know if the code will be emitted so that
6472 // dead code can ignore this.
6473 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
6474 PD: PDiag(DiagID: diag::warn_argument_invalid_range)
6475 << toString(I: Result, Radix: 10) << Low << High
6476 << Arg->getSourceRange());
6477 }
6478
6479 return false;
6480}
6481
6482bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6483 unsigned Num) {
6484 llvm::APSInt Result;
6485
6486 // We can't check the value of a dependent argument.
6487 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6488 if (Arg->isTypeDependent() || Arg->isValueDependent())
6489 return false;
6490
6491 // Check constant-ness first.
6492 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6493 return true;
6494
6495 if (Result.getSExtValue() % Num != 0)
6496 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_multiple)
6497 << Num << Arg->getSourceRange();
6498
6499 return false;
6500}
6501
6502bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6503 llvm::APSInt Result;
6504
6505 // We can't check the value of a dependent argument.
6506 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6507 if (Arg->isTypeDependent() || Arg->isValueDependent())
6508 return false;
6509
6510 // Check constant-ness first.
6511 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6512 return true;
6513
6514 if (Result.isPowerOf2())
6515 return false;
6516
6517 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_power_of_2)
6518 << Arg->getSourceRange();
6519}
6520
6521static bool IsShiftedByte(llvm::APSInt Value) {
6522 if (Value.isNegative())
6523 return false;
6524
6525 // Check if it's a shifted byte, by shifting it down
6526 while (true) {
6527 // If the value fits in the bottom byte, the check passes.
6528 if (Value < 0x100)
6529 return true;
6530
6531 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6532 // fails.
6533 if ((Value & 0xFF) != 0)
6534 return false;
6535
6536 // If the bottom 8 bits are all 0, but something above that is nonzero,
6537 // then shifting the value right by 8 bits won't affect whether it's a
6538 // shifted byte or not. So do that, and go round again.
6539 Value >>= 8;
6540 }
6541}
6542
6543bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6544 unsigned ArgBits) {
6545 llvm::APSInt Result;
6546
6547 // We can't check the value of a dependent argument.
6548 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6549 if (Arg->isTypeDependent() || Arg->isValueDependent())
6550 return false;
6551
6552 // Check constant-ness first.
6553 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6554 return true;
6555
6556 // Truncate to the given size.
6557 Result = Result.getLoBits(numBits: ArgBits);
6558 Result.setIsUnsigned(true);
6559
6560 if (IsShiftedByte(Value: Result))
6561 return false;
6562
6563 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_shifted_byte)
6564 << Arg->getSourceRange();
6565}
6566
6567bool Sema::BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6568 unsigned ArgNum,
6569 unsigned ArgBits) {
6570 llvm::APSInt Result;
6571
6572 // We can't check the value of a dependent argument.
6573 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6574 if (Arg->isTypeDependent() || Arg->isValueDependent())
6575 return false;
6576
6577 // Check constant-ness first.
6578 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6579 return true;
6580
6581 // Truncate to the given size.
6582 Result = Result.getLoBits(numBits: ArgBits);
6583 Result.setIsUnsigned(true);
6584
6585 // Check to see if it's in either of the required forms.
6586 if (IsShiftedByte(Value: Result) ||
6587 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6588 return false;
6589
6590 return Diag(Loc: TheCall->getBeginLoc(),
6591 DiagID: diag::err_argument_not_shifted_byte_or_xxff)
6592 << Arg->getSourceRange();
6593}
6594
6595bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6596 if (!Context.getTargetInfo().hasSjLjLowering())
6597 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_unsupported)
6598 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6599
6600 Expr *Arg = TheCall->getArg(Arg: 1);
6601 llvm::APSInt Result;
6602
6603 // TODO: This is less than ideal. Overload this to take a value.
6604 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
6605 return true;
6606
6607 if (Result != 1)
6608 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_invalid_val)
6609 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6610
6611 return false;
6612}
6613
6614bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6615 if (!Context.getTargetInfo().hasSjLjLowering())
6616 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_setjmp_unsupported)
6617 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6618 return false;
6619}
6620
6621bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6622 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
6623 return true;
6624
6625 ExprResult ArgRes = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
6626 if (ArgRes.isInvalid())
6627 return true;
6628
6629 // For simplicity, we support only limited expressions for the argument.
6630 // Specifically a flexible array member or a pointer with counted_by:
6631 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
6632 // complex casting, which really shouldn't be a huge problem.
6633 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6634 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
6635 return Diag(Loc: Arg->getBeginLoc(),
6636 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
6637 << Arg->getSourceRange();
6638
6639 if (Arg->HasSideEffects(Ctx: Context))
6640 return Diag(Loc: Arg->getBeginLoc(),
6641 DiagID: diag::err_builtin_counted_by_ref_has_side_effects)
6642 << Arg->getSourceRange();
6643
6644 if (const auto *ME = dyn_cast<MemberExpr>(Val: Arg)) {
6645 const auto *CATy =
6646 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6647
6648 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6649 // Member has counted_by attribute - return pointer to count field
6650 const auto *MemberDecl = cast<FieldDecl>(Val: ME->getMemberDecl());
6651 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
6652 TheCall->setType(Context.getPointerType(T: CountFD->getType()));
6653 return false;
6654 }
6655 }
6656
6657 // FAMs and pointers without counted_by return void*
6658 QualType MemberTy = ME->getMemberDecl()->getType();
6659 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
6660 return Diag(Loc: Arg->getBeginLoc(),
6661 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
6662 << Arg->getSourceRange();
6663 } else {
6664 return Diag(Loc: Arg->getBeginLoc(),
6665 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
6666 << Arg->getSourceRange();
6667 }
6668
6669 TheCall->setType(Context.getPointerType(T: Context.VoidTy));
6670 return false;
6671}
6672
6673/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6674/// It allows leaking and modification of bounds safety information.
6675bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6676 BuiltinCountedByRefKind K) {
6677 const CallExpr *CE =
6678 E ? dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts()) : nullptr;
6679 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6680 return false;
6681
6682 switch (K) {
6683 case BuiltinCountedByRefKind::Assignment:
6684 case BuiltinCountedByRefKind::Initializer:
6685 Diag(Loc: E->getExprLoc(),
6686 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
6687 << 0 << E->getSourceRange();
6688 break;
6689 case BuiltinCountedByRefKind::FunctionArg:
6690 Diag(Loc: E->getExprLoc(),
6691 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
6692 << 1 << E->getSourceRange();
6693 break;
6694 case BuiltinCountedByRefKind::ReturnArg:
6695 Diag(Loc: E->getExprLoc(),
6696 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
6697 << 2 << E->getSourceRange();
6698 break;
6699 case BuiltinCountedByRefKind::ArraySubscript:
6700 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
6701 << 0 << E->getSourceRange();
6702 break;
6703 case BuiltinCountedByRefKind::BinaryExpr:
6704 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
6705 << 1 << E->getSourceRange();
6706 break;
6707 }
6708
6709 return true;
6710}
6711
6712namespace {
6713
6714class UncoveredArgHandler {
6715 enum { Unknown = -1, AllCovered = -2 };
6716
6717 signed FirstUncoveredArg = Unknown;
6718 SmallVector<const Expr *, 4> DiagnosticExprs;
6719
6720public:
6721 UncoveredArgHandler() = default;
6722
6723 bool hasUncoveredArg() const {
6724 return (FirstUncoveredArg >= 0);
6725 }
6726
6727 unsigned getUncoveredArg() const {
6728 assert(hasUncoveredArg() && "no uncovered argument");
6729 return FirstUncoveredArg;
6730 }
6731
6732 void setAllCovered() {
6733 // A string has been found with all arguments covered, so clear out
6734 // the diagnostics.
6735 DiagnosticExprs.clear();
6736 FirstUncoveredArg = AllCovered;
6737 }
6738
6739 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6740 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6741
6742 // Don't update if a previous string covers all arguments.
6743 if (FirstUncoveredArg == AllCovered)
6744 return;
6745
6746 // UncoveredArgHandler tracks the highest uncovered argument index
6747 // and with it all the strings that match this index.
6748 if (NewFirstUncoveredArg == FirstUncoveredArg)
6749 DiagnosticExprs.push_back(Elt: StrExpr);
6750 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6751 DiagnosticExprs.clear();
6752 DiagnosticExprs.push_back(Elt: StrExpr);
6753 FirstUncoveredArg = NewFirstUncoveredArg;
6754 }
6755 }
6756
6757 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6758};
6759
6760enum StringLiteralCheckType {
6761 SLCT_NotALiteral,
6762 SLCT_UncheckedLiteral,
6763 SLCT_CheckedLiteral
6764};
6765
6766} // namespace
6767
6768static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6769 BinaryOperatorKind BinOpKind,
6770 bool AddendIsRight) {
6771 unsigned BitWidth = Offset.getBitWidth();
6772 unsigned AddendBitWidth = Addend.getBitWidth();
6773 // There might be negative interim results.
6774 if (Addend.isUnsigned()) {
6775 Addend = Addend.zext(width: ++AddendBitWidth);
6776 Addend.setIsSigned(true);
6777 }
6778 // Adjust the bit width of the APSInts.
6779 if (AddendBitWidth > BitWidth) {
6780 Offset = Offset.sext(width: AddendBitWidth);
6781 BitWidth = AddendBitWidth;
6782 } else if (BitWidth > AddendBitWidth) {
6783 Addend = Addend.sext(width: BitWidth);
6784 }
6785
6786 bool Ov = false;
6787 llvm::APSInt ResOffset = Offset;
6788 if (BinOpKind == BO_Add)
6789 ResOffset = Offset.sadd_ov(RHS: Addend, Overflow&: Ov);
6790 else {
6791 assert(AddendIsRight && BinOpKind == BO_Sub &&
6792 "operator must be add or sub with addend on the right");
6793 ResOffset = Offset.ssub_ov(RHS: Addend, Overflow&: Ov);
6794 }
6795
6796 // We add an offset to a pointer here so we should support an offset as big as
6797 // possible.
6798 if (Ov) {
6799 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6800 "index (intermediate) result too big");
6801 Offset = Offset.sext(width: 2 * BitWidth);
6802 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6803 return;
6804 }
6805
6806 Offset = std::move(ResOffset);
6807}
6808
6809namespace {
6810
6811// This is a wrapper class around StringLiteral to support offsetted string
6812// literals as format strings. It takes the offset into account when returning
6813// the string and its length or the source locations to display notes correctly.
6814class FormatStringLiteral {
6815 const StringLiteral *FExpr;
6816 int64_t Offset;
6817
6818public:
6819 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6820 : FExpr(fexpr), Offset(Offset) {}
6821
6822 const StringLiteral *getFormatString() const { return FExpr; }
6823
6824 StringRef getString() const { return FExpr->getString().drop_front(N: Offset); }
6825
6826 unsigned getByteLength() const {
6827 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6828 }
6829
6830 unsigned getLength() const { return FExpr->getLength() - Offset; }
6831 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6832
6833 StringLiteralKind getKind() const { return FExpr->getKind(); }
6834
6835 QualType getType() const { return FExpr->getType(); }
6836
6837 bool isAscii() const { return FExpr->isOrdinary(); }
6838 bool isWide() const { return FExpr->isWide(); }
6839 bool isUTF8() const { return FExpr->isUTF8(); }
6840 bool isUTF16() const { return FExpr->isUTF16(); }
6841 bool isUTF32() const { return FExpr->isUTF32(); }
6842 bool isPascal() const { return FExpr->isPascal(); }
6843
6844 SourceLocation getLocationOfByte(
6845 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6846 const TargetInfo &Target, unsigned *StartToken = nullptr,
6847 unsigned *StartTokenByteOffset = nullptr) const {
6848 return FExpr->getLocationOfByte(ByteNo: ByteNo + Offset, SM, Features, Target,
6849 StartToken, StartTokenByteOffset);
6850 }
6851
6852 SourceLocation getBeginLoc() const LLVM_READONLY {
6853 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6854 }
6855
6856 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6857};
6858
6859} // namespace
6860
6861static void CheckFormatString(
6862 Sema &S, const FormatStringLiteral *FExpr,
6863 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6864 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
6865 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6866 bool inFunctionCall, VariadicCallType CallType,
6867 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6868 bool IgnoreStringsWithoutSpecifiers);
6869
6870static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6871 const Expr *E);
6872
6873// Determine if an expression is a string literal or constant string.
6874// If this function returns false on the arguments to a function expecting a
6875// format string, we will usually need to emit a warning.
6876// True string literals are then checked by CheckFormatString.
6877static StringLiteralCheckType
6878checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
6879 const Expr *E, ArrayRef<const Expr *> Args,
6880 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
6881 unsigned firstDataArg, FormatStringType Type,
6882 VariadicCallType CallType, bool InFunctionCall,
6883 llvm::SmallBitVector &CheckedVarArgs,
6884 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
6885 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
6886 bool IgnoreStringsWithoutSpecifiers = false) {
6887 if (S.isConstantEvaluatedContext())
6888 return SLCT_NotALiteral;
6889tryAgain:
6890 assert(Offset.isSigned() && "invalid offset");
6891
6892 if (E->isTypeDependent() || E->isValueDependent())
6893 return SLCT_NotALiteral;
6894
6895 E = E->IgnoreParenCasts();
6896
6897 if (E->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull))
6898 // Technically -Wformat-nonliteral does not warn about this case.
6899 // The behavior of printf and friends in this case is implementation
6900 // dependent. Ideally if the format string cannot be null then
6901 // it should have a 'nonnull' attribute in the function prototype.
6902 return SLCT_UncheckedLiteral;
6903
6904 switch (E->getStmtClass()) {
6905 case Stmt::InitListExprClass:
6906 // Handle expressions like {"foobar"}.
6907 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E)) {
6908 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
6909 format_idx, firstDataArg, Type, CallType,
6910 /*InFunctionCall*/ false, CheckedVarArgs,
6911 UncoveredArg, Offset, CallerFormatParamIdx,
6912 IgnoreStringsWithoutSpecifiers);
6913 }
6914 return SLCT_NotALiteral;
6915 case Stmt::BinaryConditionalOperatorClass:
6916 case Stmt::ConditionalOperatorClass: {
6917 // The expression is a literal if both sub-expressions were, and it was
6918 // completely checked only if both sub-expressions were checked.
6919 const AbstractConditionalOperator *C =
6920 cast<AbstractConditionalOperator>(Val: E);
6921
6922 // Determine whether it is necessary to check both sub-expressions, for
6923 // example, because the condition expression is a constant that can be
6924 // evaluated at compile time.
6925 bool CheckLeft = true, CheckRight = true;
6926
6927 bool Cond;
6928 if (C->getCond()->EvaluateAsBooleanCondition(
6929 Result&: Cond, Ctx: S.getASTContext(), InConstantContext: S.isConstantEvaluatedContext())) {
6930 if (Cond)
6931 CheckRight = false;
6932 else
6933 CheckLeft = false;
6934 }
6935
6936 // We need to maintain the offsets for the right and the left hand side
6937 // separately to check if every possible indexed expression is a valid
6938 // string literal. They might have different offsets for different string
6939 // literals in the end.
6940 StringLiteralCheckType Left;
6941 if (!CheckLeft)
6942 Left = SLCT_UncheckedLiteral;
6943 else {
6944 Left = checkFormatStringExpr(S, ReferenceFormatString, E: C->getTrueExpr(),
6945 Args, APK, format_idx, firstDataArg, Type,
6946 CallType, InFunctionCall, CheckedVarArgs,
6947 UncoveredArg, Offset, CallerFormatParamIdx,
6948 IgnoreStringsWithoutSpecifiers);
6949 if (Left == SLCT_NotALiteral || !CheckRight) {
6950 return Left;
6951 }
6952 }
6953
6954 StringLiteralCheckType Right = checkFormatStringExpr(
6955 S, ReferenceFormatString, E: C->getFalseExpr(), Args, APK, format_idx,
6956 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6957 UncoveredArg, Offset, CallerFormatParamIdx,
6958 IgnoreStringsWithoutSpecifiers);
6959
6960 return (CheckLeft && Left < Right) ? Left : Right;
6961 }
6962
6963 case Stmt::ImplicitCastExprClass:
6964 E = cast<ImplicitCastExpr>(Val: E)->getSubExpr();
6965 goto tryAgain;
6966
6967 case Stmt::OpaqueValueExprClass:
6968 if (const Expr *src = cast<OpaqueValueExpr>(Val: E)->getSourceExpr()) {
6969 E = src;
6970 goto tryAgain;
6971 }
6972 return SLCT_NotALiteral;
6973
6974 case Stmt::PredefinedExprClass:
6975 // While __func__, etc., are technically not string literals, they
6976 // cannot contain format specifiers and thus are not a security
6977 // liability.
6978 return SLCT_UncheckedLiteral;
6979
6980 case Stmt::DeclRefExprClass: {
6981 const DeclRefExpr *DR = cast<DeclRefExpr>(Val: E);
6982
6983 // As an exception, do not flag errors for variables binding to
6984 // const string literals.
6985 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: DR->getDecl())) {
6986 bool isConstant = false;
6987 QualType T = DR->getType();
6988
6989 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6990 isConstant = AT->getElementType().isConstant(Ctx: S.Context);
6991 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6992 isConstant = T.isConstant(Ctx: S.Context) &&
6993 PT->getPointeeType().isConstant(Ctx: S.Context);
6994 } else if (T->isObjCObjectPointerType()) {
6995 // In ObjC, there is usually no "const ObjectPointer" type,
6996 // so don't check if the pointee type is constant.
6997 isConstant = T.isConstant(Ctx: S.Context);
6998 }
6999
7000 if (isConstant) {
7001 if (const Expr *Init = VD->getAnyInitializer()) {
7002 // Look through initializers like const char c[] = { "foo" }
7003 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
7004 if (InitList->isStringLiteralInit())
7005 Init = InitList->getInit(Init: 0)->IgnoreParenImpCasts();
7006 }
7007 return checkFormatStringExpr(
7008 S, ReferenceFormatString, E: Init, Args, APK, format_idx,
7009 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7010 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7011 }
7012 }
7013
7014 // When the format argument is an argument of this function, and this
7015 // function also has the format attribute, there are several interactions
7016 // for which there shouldn't be a warning. For instance, when calling
7017 // v*printf from a function that has the printf format attribute, we
7018 // should not emit a warning about using `fmt`, even though it's not
7019 // constant, because the arguments have already been checked for the
7020 // caller of `logmessage`:
7021 //
7022 // __attribute__((format(printf, 1, 2)))
7023 // void logmessage(char const *fmt, ...) {
7024 // va_list ap;
7025 // va_start(ap, fmt);
7026 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7027 // ...
7028 // }
7029 //
7030 // Another interaction that we need to support is using a format string
7031 // specified by the format_matches attribute:
7032 //
7033 // __attribute__((format_matches(printf, 1, "%s %d")))
7034 // void logmessage(char const *fmt, const char *a, int b) {
7035 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7036 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7037 // ...
7038 // }
7039 //
7040 // Yet another interaction that we need to support is calling a variadic
7041 // format function from a format function that has fixed arguments. For
7042 // instance:
7043 //
7044 // __attribute__((format(printf, 1, 2)))
7045 // void logstring(char const *fmt, char const *str) {
7046 // printf(fmt, str); /* do not emit a warning about "fmt" */
7047 // }
7048 //
7049 // Same (and perhaps more relatably) for the variadic template case:
7050 //
7051 // template<typename... Args>
7052 // __attribute__((format(printf, 1, 2)))
7053 // void log(const char *fmt, Args&&... args) {
7054 // printf(fmt, forward<Args>(args)...);
7055 // /* do not emit a warning about "fmt" */
7056 // }
7057 //
7058 // Due to implementation difficulty, we only check the format, not the
7059 // format arguments, in all cases.
7060 //
7061 if (const auto *PV = dyn_cast<ParmVarDecl>(Val: VD)) {
7062 if (CallerFormatParamIdx)
7063 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7064 if (const auto *D = dyn_cast<Decl>(Val: PV->getDeclContext())) {
7065 for (const auto *PVFormatMatches :
7066 D->specific_attrs<FormatMatchesAttr>()) {
7067 Sema::FormatStringInfo CalleeFSI;
7068 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormatMatches->getFormatIdx(),
7069 FirstArg: 0, FSI: &CalleeFSI))
7070 continue;
7071 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7072 // If using the wrong type of format string, emit a diagnostic
7073 // here and stop checking to avoid irrelevant diagnostics.
7074 if (Type != S.GetFormatStringType(Format: PVFormatMatches)) {
7075 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7076 DiagID: diag::warn_format_string_type_incompatible)
7077 << PVFormatMatches->getType()->getName()
7078 << S.GetFormatStringTypeName(FST: Type);
7079 if (!InFunctionCall) {
7080 S.Diag(Loc: PVFormatMatches->getFormatString()->getBeginLoc(),
7081 DiagID: diag::note_format_string_defined);
7082 }
7083 return SLCT_UncheckedLiteral;
7084 }
7085 return checkFormatStringExpr(
7086 S, ReferenceFormatString, E: PVFormatMatches->getFormatString(),
7087 Args, APK, format_idx, firstDataArg, Type, CallType,
7088 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7089 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7090 }
7091 }
7092
7093 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7094 Sema::FormatStringInfo CallerFSI;
7095 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormat->getFormatIdx(),
7096 FirstArg: PVFormat->getFirstArg(), FSI: &CallerFSI))
7097 continue;
7098 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7099 // We also check if the formats are compatible.
7100 // We can't pass a 'scanf' string to a 'printf' function.
7101 if (Type != S.GetFormatStringType(Format: PVFormat)) {
7102 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7103 DiagID: diag::warn_format_string_type_incompatible)
7104 << PVFormat->getType()->getName()
7105 << S.GetFormatStringTypeName(FST: Type);
7106 if (!InFunctionCall) {
7107 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_format_string_defined);
7108 }
7109 return SLCT_UncheckedLiteral;
7110 }
7111 // Lastly, check that argument passing kinds transition in a
7112 // way that makes sense:
7113 // from a caller with FAPK_VAList, allow FAPK_VAList
7114 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7115 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7116 // from a caller with FAPK_Variadic, allow FAPK_VAList
7117 switch (combineFAPK(A: CallerFSI.ArgPassingKind, B: APK)) {
7118 case combineFAPK(A: Sema::FAPK_VAList, B: Sema::FAPK_VAList):
7119 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Fixed):
7120 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Variadic):
7121 case combineFAPK(A: Sema::FAPK_Variadic, B: Sema::FAPK_VAList):
7122 return SLCT_UncheckedLiteral;
7123 }
7124 }
7125 }
7126 }
7127 }
7128 }
7129
7130 return SLCT_NotALiteral;
7131 }
7132
7133 case Stmt::CallExprClass:
7134 case Stmt::CXXMemberCallExprClass: {
7135 const CallExpr *CE = cast<CallExpr>(Val: E);
7136 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Val: CE->getCalleeDecl())) {
7137 bool IsFirst = true;
7138 StringLiteralCheckType CommonResult;
7139 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7140 const Expr *Arg = CE->getArg(Arg: FA->getFormatIdx().getASTIndex());
7141 StringLiteralCheckType Result = checkFormatStringExpr(
7142 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7143 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7144 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7145 if (IsFirst) {
7146 CommonResult = Result;
7147 IsFirst = false;
7148 }
7149 }
7150 if (!IsFirst)
7151 return CommonResult;
7152
7153 if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) {
7154 unsigned BuiltinID = FD->getBuiltinID();
7155 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7156 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7157 const Expr *Arg = CE->getArg(Arg: 0);
7158 return checkFormatStringExpr(
7159 S, ReferenceFormatString, E: Arg, Args, APK, format_idx,
7160 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7161 UncoveredArg, Offset, CallerFormatParamIdx,
7162 IgnoreStringsWithoutSpecifiers);
7163 }
7164 }
7165 }
7166 if (const Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E))
7167 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7168 format_idx, firstDataArg, Type, CallType,
7169 /*InFunctionCall*/ false, CheckedVarArgs,
7170 UncoveredArg, Offset, CallerFormatParamIdx,
7171 IgnoreStringsWithoutSpecifiers);
7172 return SLCT_NotALiteral;
7173 }
7174 case Stmt::ObjCMessageExprClass: {
7175 const auto *ME = cast<ObjCMessageExpr>(Val: E);
7176 if (const auto *MD = ME->getMethodDecl()) {
7177 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7178 // As a special case heuristic, if we're using the method -[NSBundle
7179 // localizedStringForKey:value:table:], ignore any key strings that lack
7180 // format specifiers. The idea is that if the key doesn't have any
7181 // format specifiers then its probably just a key to map to the
7182 // localized strings. If it does have format specifiers though, then its
7183 // likely that the text of the key is the format string in the
7184 // programmer's language, and should be checked.
7185 const ObjCInterfaceDecl *IFace;
7186 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7187 IFace->getIdentifier()->isStr(Str: "NSBundle") &&
7188 MD->getSelector().isKeywordSelector(
7189 Names: {"localizedStringForKey", "value", "table"})) {
7190 IgnoreStringsWithoutSpecifiers = true;
7191 }
7192
7193 const Expr *Arg = ME->getArg(Arg: FA->getFormatIdx().getASTIndex());
7194 return checkFormatStringExpr(
7195 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7196 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7197 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7198 }
7199 }
7200
7201 return SLCT_NotALiteral;
7202 }
7203 case Stmt::ObjCStringLiteralClass:
7204 case Stmt::StringLiteralClass: {
7205 const StringLiteral *StrE = nullptr;
7206
7207 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(Val: E))
7208 StrE = ObjCFExpr->getString();
7209 else
7210 StrE = cast<StringLiteral>(Val: E);
7211
7212 if (StrE) {
7213 if (Offset.isNegative() || Offset > StrE->getLength()) {
7214 // TODO: It would be better to have an explicit warning for out of
7215 // bounds literals.
7216 return SLCT_NotALiteral;
7217 }
7218 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(width: 64).getSExtValue());
7219 CheckFormatString(S, FExpr: &FStr, ReferenceFormatString, OrigFormatExpr: E, Args, APK,
7220 format_idx, firstDataArg, Type, inFunctionCall: InFunctionCall,
7221 CallType, CheckedVarArgs, UncoveredArg,
7222 IgnoreStringsWithoutSpecifiers);
7223 return SLCT_CheckedLiteral;
7224 }
7225
7226 return SLCT_NotALiteral;
7227 }
7228 case Stmt::BinaryOperatorClass: {
7229 const BinaryOperator *BinOp = cast<BinaryOperator>(Val: E);
7230
7231 // A string literal + an int offset is still a string literal.
7232 if (BinOp->isAdditiveOp()) {
7233 Expr::EvalResult LResult, RResult;
7234
7235 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7236 Result&: LResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7237 InConstantContext: S.isConstantEvaluatedContext());
7238 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7239 Result&: RResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7240 InConstantContext: S.isConstantEvaluatedContext());
7241
7242 if (LIsInt != RIsInt) {
7243 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7244
7245 if (LIsInt) {
7246 if (BinOpKind == BO_Add) {
7247 sumOffsets(Offset, Addend: LResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7248 E = BinOp->getRHS();
7249 goto tryAgain;
7250 }
7251 } else {
7252 sumOffsets(Offset, Addend: RResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7253 E = BinOp->getLHS();
7254 goto tryAgain;
7255 }
7256 }
7257 }
7258
7259 return SLCT_NotALiteral;
7260 }
7261 case Stmt::UnaryOperatorClass: {
7262 const UnaryOperator *UnaOp = cast<UnaryOperator>(Val: E);
7263 auto ASE = dyn_cast<ArraySubscriptExpr>(Val: UnaOp->getSubExpr());
7264 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7265 Expr::EvalResult IndexResult;
7266 if (ASE->getRHS()->EvaluateAsInt(Result&: IndexResult, Ctx: S.Context,
7267 AllowSideEffects: Expr::SE_NoSideEffects,
7268 InConstantContext: S.isConstantEvaluatedContext())) {
7269 sumOffsets(Offset, Addend: IndexResult.Val.getInt(), BinOpKind: BO_Add,
7270 /*RHS is int*/ AddendIsRight: true);
7271 E = ASE->getBase();
7272 goto tryAgain;
7273 }
7274 }
7275
7276 return SLCT_NotALiteral;
7277 }
7278
7279 default:
7280 return SLCT_NotALiteral;
7281 }
7282}
7283
7284// If this expression can be evaluated at compile-time,
7285// check if the result is a StringLiteral and return it
7286// otherwise return nullptr
7287static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7288 const Expr *E) {
7289 Expr::EvalResult Result;
7290 if (E->EvaluateAsRValue(Result, Ctx: Context) && Result.Val.isLValue()) {
7291 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7292 if (isa_and_nonnull<StringLiteral>(Val: LVE))
7293 return LVE;
7294 }
7295 return nullptr;
7296}
7297
7298StringRef Sema::GetFormatStringTypeName(FormatStringType FST) {
7299 switch (FST) {
7300 case FormatStringType::Scanf:
7301 return "scanf";
7302 case FormatStringType::Printf:
7303 return "printf";
7304 case FormatStringType::NSString:
7305 return "NSString";
7306 case FormatStringType::Strftime:
7307 return "strftime";
7308 case FormatStringType::Strfmon:
7309 return "strfmon";
7310 case FormatStringType::Kprintf:
7311 return "kprintf";
7312 case FormatStringType::FreeBSDKPrintf:
7313 return "freebsd_kprintf";
7314 case FormatStringType::OSLog:
7315 return "os_log";
7316 default:
7317 return "<unknown>";
7318 }
7319}
7320
7321FormatStringType Sema::GetFormatStringType(StringRef Flavor) {
7322 return llvm::StringSwitch<FormatStringType>(Flavor)
7323 .Cases(CaseStrings: {"gnu_scanf", "scanf"}, Value: FormatStringType::Scanf)
7324 .Cases(CaseStrings: {"gnu_printf", "printf", "printf0", "syslog"},
7325 Value: FormatStringType::Printf)
7326 .Cases(CaseStrings: {"NSString", "CFString"}, Value: FormatStringType::NSString)
7327 .Cases(CaseStrings: {"gnu_strftime", "strftime"}, Value: FormatStringType::Strftime)
7328 .Cases(CaseStrings: {"gnu_strfmon", "strfmon"}, Value: FormatStringType::Strfmon)
7329 .Cases(CaseStrings: {"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7330 Value: FormatStringType::Kprintf)
7331 .Case(S: "freebsd_kprintf", Value: FormatStringType::FreeBSDKPrintf)
7332 .Case(S: "os_trace", Value: FormatStringType::OSLog)
7333 .Case(S: "os_log", Value: FormatStringType::OSLog)
7334 .Default(Value: FormatStringType::Unknown);
7335}
7336
7337FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7338 return GetFormatStringType(Flavor: Format->getType()->getName());
7339}
7340
7341FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7342 return GetFormatStringType(Flavor: Format->getType()->getName());
7343}
7344
7345bool Sema::CheckFormatArguments(const FormatAttr *Format,
7346 ArrayRef<const Expr *> Args, bool IsCXXMember,
7347 VariadicCallType CallType, SourceLocation Loc,
7348 SourceRange Range,
7349 llvm::SmallBitVector &CheckedVarArgs) {
7350 FormatStringInfo FSI;
7351 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: Format->getFirstArg(),
7352 HasImplicitThisParam: IsCXXMember,
7353 IsVariadic: CallType != VariadicCallType::DoesNotApply, FSI: &FSI))
7354 return CheckFormatArguments(
7355 Args, FAPK: FSI.ArgPassingKind, ReferenceFormatString: nullptr, format_idx: FSI.FormatIdx, firstDataArg: FSI.FirstDataArg,
7356 Type: GetFormatStringType(Format), CallType, Loc, range: Range, CheckedVarArgs);
7357 return false;
7358}
7359
7360bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7361 ArrayRef<const Expr *> Args, bool IsCXXMember,
7362 VariadicCallType CallType, SourceLocation Loc,
7363 SourceRange Range,
7364 llvm::SmallBitVector &CheckedVarArgs) {
7365 FormatStringInfo FSI;
7366 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: 0, HasImplicitThisParam: IsCXXMember, IsVariadic: false,
7367 FSI: &FSI)) {
7368 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7369 return CheckFormatArguments(Args, FAPK: FSI.ArgPassingKind,
7370 ReferenceFormatString: Format->getFormatString(), format_idx: FSI.FormatIdx,
7371 firstDataArg: FSI.FirstDataArg, Type: GetFormatStringType(Format),
7372 CallType, Loc, range: Range, CheckedVarArgs);
7373 }
7374 return false;
7375}
7376
7377static bool CheckMissingFormatAttribute(
7378 Sema *S, ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
7379 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7380 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7381 SourceLocation Loc) {
7382 if (S->getDiagnostics().isIgnored(DiagID: diag::warn_missing_format_attribute, Loc))
7383 return false;
7384
7385 DeclContext *DC = S->CurContext;
7386 if (!isa<ObjCMethodDecl>(Val: DC) && !isa<FunctionDecl>(Val: DC) && !isa<BlockDecl>(Val: DC))
7387 return false;
7388 Decl *Caller = cast<Decl>(Val: DC)->getCanonicalDecl();
7389
7390 unsigned NumCallerParams = getFunctionOrMethodNumParams(D: Caller);
7391
7392 // Find the offset to convert between attribute and parameter indexes.
7393 unsigned CallerArgumentIndexOffset =
7394 hasImplicitObjectParameter(D: Caller) ? 2 : 1;
7395
7396 unsigned FirstArgumentIndex = -1;
7397 switch (APK) {
7398 case Sema::FormatArgumentPassingKind::FAPK_Fixed:
7399 case Sema::FormatArgumentPassingKind::FAPK_Variadic: {
7400 // As an extension, clang allows the format attribute on non-variadic
7401 // functions.
7402 // Caller must have fixed arguments to pass them to a fixed or variadic
7403 // function. Try to match caller and callee arguments. If successful, then
7404 // emit a diag with the caller idx, otherwise we can't determine the callee
7405 // arguments.
7406 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7407 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7408 // There aren't enough arguments in the caller to pass to callee.
7409 return false;
7410 }
7411 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7412 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7413 const auto *Arg =
7414 dyn_cast<DeclRefExpr>(Val: Args[CalleeIdx]->IgnoreParenCasts());
7415 if (!Arg)
7416 return false;
7417 const auto *Param = dyn_cast<ParmVarDecl>(Val: Arg->getDecl());
7418 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7419 return false;
7420 }
7421 FirstArgumentIndex =
7422 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7423 break;
7424 }
7425 case Sema::FormatArgumentPassingKind::FAPK_VAList:
7426 // Caller arguments are either variadic or a va_list.
7427 FirstArgumentIndex = isFunctionOrMethodVariadic(D: Caller)
7428 ? (NumCallerParams + CallerArgumentIndexOffset)
7429 : 0;
7430 break;
7431 case Sema::FormatArgumentPassingKind::FAPK_Elsewhere:
7432 // The callee has a format_matches attribute. We will emit that instead.
7433 if (!ReferenceFormatString)
7434 return false;
7435 break;
7436 }
7437
7438 // Emit the diagnostic and fixit.
7439 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7440 StringRef FormatTypeName = S->GetFormatStringTypeName(FST: FormatType);
7441 NamedDecl *ND = dyn_cast<NamedDecl>(Val: Caller);
7442 do {
7443 std::string Attr, Fixit;
7444 llvm::raw_string_ostream AttrOS(Attr);
7445 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
7446 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7447 << FirstArgumentIndex << ")";
7448 } else {
7449 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7450 << ", \"";
7451 AttrOS.write_escaped(Str: ReferenceFormatString->getString());
7452 AttrOS << "\")";
7453 }
7454 AttrOS.flush();
7455 auto DB = S->Diag(Loc, DiagID: diag::warn_missing_format_attribute) << Attr;
7456 if (ND)
7457 DB << ND;
7458 else
7459 DB << "block";
7460
7461 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7462 if (isa<BlockDecl>(Val: Caller))
7463 break;
7464
7465 SourceLocation SL;
7466 llvm::raw_string_ostream IS(Fixit);
7467 // The attribute goes at the start of the declaration in C/C++ functions
7468 // and methods, but after the declaration for Objective-C methods.
7469 if (isa<ObjCMethodDecl>(Val: Caller)) {
7470 IS << ' ';
7471 SL = Caller->getEndLoc();
7472 }
7473 const LangOptions &LO = S->getLangOpts();
7474 if (LO.C23 || LO.CPlusPlus11)
7475 IS << "[[gnu::" << Attr << "]]";
7476 else if (LO.ObjC || LO.GNUMode)
7477 IS << "__attribute__((" << Attr << "))";
7478 else
7479 break;
7480 if (!isa<ObjCMethodDecl>(Val: Caller)) {
7481 IS << ' ';
7482 SL = Caller->getBeginLoc();
7483 }
7484 IS.flush();
7485
7486 DB << FixItHint::CreateInsertion(InsertionLoc: SL, Code: Fixit);
7487 } while (false);
7488
7489 // Add implicit format or format_matches attribute.
7490 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
7491 Caller->addAttr(A: FormatAttr::CreateImplicit(
7492 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
7493 FormatIdx: FormatStringIndex, FirstArg: FirstArgumentIndex));
7494 } else {
7495 Caller->addAttr(A: FormatMatchesAttr::CreateImplicit(
7496 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
7497 FormatIdx: FormatStringIndex, ExpectedFormat: ReferenceFormatString));
7498 }
7499
7500 {
7501 auto DB = S->Diag(Loc: Caller->getLocation(), DiagID: diag::note_entity_declared_at);
7502 if (ND)
7503 DB << ND;
7504 else
7505 DB << "block";
7506 }
7507 return true;
7508}
7509
7510bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7511 Sema::FormatArgumentPassingKind APK,
7512 StringLiteral *ReferenceFormatString,
7513 unsigned format_idx, unsigned firstDataArg,
7514 FormatStringType Type,
7515 VariadicCallType CallType, SourceLocation Loc,
7516 SourceRange Range,
7517 llvm::SmallBitVector &CheckedVarArgs) {
7518 // CHECK: printf/scanf-like function is called with no format string.
7519 if (format_idx >= Args.size()) {
7520 Diag(Loc, DiagID: diag::warn_missing_format_string) << Range;
7521 return false;
7522 }
7523
7524 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7525
7526 // CHECK: format string is not a string literal.
7527 //
7528 // Dynamically generated format strings are difficult to
7529 // automatically vet at compile time. Requiring that format strings
7530 // are string literals: (1) permits the checking of format strings by
7531 // the compiler and thereby (2) can practically remove the source of
7532 // many format string exploits.
7533
7534 // Format string can be either ObjC string (e.g. @"%d") or
7535 // C string (e.g. "%d")
7536 // ObjC string uses the same format specifiers as C string, so we can use
7537 // the same format string checking logic for both ObjC and C strings.
7538 UncoveredArgHandler UncoveredArg;
7539 std::optional<unsigned> CallerParamIdx;
7540 StringLiteralCheckType CT = checkFormatStringExpr(
7541 S&: *this, ReferenceFormatString, E: OrigFormatExpr, Args, APK, format_idx,
7542 firstDataArg, Type, CallType,
7543 /*IsFunctionCall*/ InFunctionCall: true, CheckedVarArgs, UncoveredArg,
7544 /*no string offset*/ Offset: llvm::APSInt(64, false) = 0, CallerFormatParamIdx: &CallerParamIdx);
7545
7546 // Generate a diagnostic where an uncovered argument is detected.
7547 if (UncoveredArg.hasUncoveredArg()) {
7548 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7549 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7550 UncoveredArg.Diagnose(S&: *this, /*IsFunctionCall*/true, ArgExpr: Args[ArgIdx]);
7551 }
7552
7553 if (CT != SLCT_NotALiteral)
7554 // Literal format string found, check done!
7555 return CT == SLCT_CheckedLiteral;
7556
7557 // Do not emit diag when the string param is a macro expansion and the
7558 // format is either NSString or CFString. This is a hack to prevent
7559 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7560 // which are usually used in place of NS and CF string literals.
7561 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7562 if (Type == FormatStringType::NSString &&
7563 SourceMgr.isInSystemMacro(loc: FormatLoc))
7564 return false;
7565
7566 if (CallerParamIdx && CheckMissingFormatAttribute(
7567 S: this, Args, APK, ReferenceFormatString, FormatIdx: format_idx,
7568 FirstDataArg: firstDataArg, FormatType: Type, CallerParamIdx: *CallerParamIdx, Loc))
7569 return false;
7570
7571 // Strftime is particular as it always uses a single 'time' argument,
7572 // so it is safe to pass a non-literal string.
7573 if (Type == FormatStringType::Strftime)
7574 return false;
7575
7576 // If there are no arguments specified, warn with -Wformat-security, otherwise
7577 // warn only with -Wformat-nonliteral.
7578 if (Args.size() == firstDataArg) {
7579 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral_noargs)
7580 << OrigFormatExpr->getSourceRange();
7581 switch (Type) {
7582 default:
7583 break;
7584 case FormatStringType::Kprintf:
7585 case FormatStringType::FreeBSDKPrintf:
7586 case FormatStringType::Printf:
7587 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
7588 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "\"%s\", ");
7589 break;
7590 case FormatStringType::NSString:
7591 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
7592 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "@\"%@\", ");
7593 break;
7594 }
7595 } else {
7596 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral)
7597 << OrigFormatExpr->getSourceRange();
7598 }
7599 return false;
7600}
7601
7602namespace {
7603
7604class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7605protected:
7606 Sema &S;
7607 const FormatStringLiteral *FExpr;
7608 const Expr *OrigFormatExpr;
7609 const FormatStringType FSType;
7610 const unsigned FirstDataArg;
7611 const unsigned NumDataArgs;
7612 const char *Beg; // Start of format string.
7613 const Sema::FormatArgumentPassingKind ArgPassingKind;
7614 ArrayRef<const Expr *> Args;
7615 unsigned FormatIdx;
7616 llvm::SmallBitVector CoveredArgs;
7617 bool usesPositionalArgs = false;
7618 bool atFirstArg = true;
7619 bool inFunctionCall;
7620 VariadicCallType CallType;
7621 llvm::SmallBitVector &CheckedVarArgs;
7622 UncoveredArgHandler &UncoveredArg;
7623
7624public:
7625 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7626 const Expr *origFormatExpr, const FormatStringType type,
7627 unsigned firstDataArg, unsigned numDataArgs,
7628 const char *beg, Sema::FormatArgumentPassingKind APK,
7629 ArrayRef<const Expr *> Args, unsigned formatIdx,
7630 bool inFunctionCall, VariadicCallType callType,
7631 llvm::SmallBitVector &CheckedVarArgs,
7632 UncoveredArgHandler &UncoveredArg)
7633 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7634 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7635 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7636 inFunctionCall(inFunctionCall), CallType(callType),
7637 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7638 CoveredArgs.resize(N: numDataArgs);
7639 CoveredArgs.reset();
7640 }
7641
7642 bool HasFormatArguments() const {
7643 return ArgPassingKind == Sema::FAPK_Fixed ||
7644 ArgPassingKind == Sema::FAPK_Variadic;
7645 }
7646
7647 void DoneProcessing();
7648
7649 void HandleIncompleteSpecifier(const char *startSpecifier,
7650 unsigned specifierLen) override;
7651
7652 void HandleInvalidLengthModifier(
7653 const analyze_format_string::FormatSpecifier &FS,
7654 const analyze_format_string::ConversionSpecifier &CS,
7655 const char *startSpecifier, unsigned specifierLen,
7656 unsigned DiagID);
7657
7658 void HandleNonStandardLengthModifier(
7659 const analyze_format_string::FormatSpecifier &FS,
7660 const char *startSpecifier, unsigned specifierLen);
7661
7662 void HandleNonStandardConversionSpecifier(
7663 const analyze_format_string::ConversionSpecifier &CS,
7664 const char *startSpecifier, unsigned specifierLen);
7665
7666 void HandlePosition(const char *startPos, unsigned posLen) override;
7667
7668 void HandleInvalidPosition(const char *startSpecifier,
7669 unsigned specifierLen,
7670 analyze_format_string::PositionContext p) override;
7671
7672 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7673
7674 void HandleNullChar(const char *nullCharacter) override;
7675
7676 template <typename Range>
7677 static void
7678 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7679 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7680 bool IsStringLocation, Range StringRange,
7681 ArrayRef<FixItHint> Fixit = {});
7682
7683protected:
7684 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7685 const char *startSpec,
7686 unsigned specifierLen,
7687 const char *csStart, unsigned csLen);
7688
7689 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7690 const char *startSpec,
7691 unsigned specifierLen);
7692
7693 SourceRange getFormatStringRange();
7694 CharSourceRange getSpecifierRange(const char *startSpecifier,
7695 unsigned specifierLen);
7696 SourceLocation getLocationOfByte(const char *x);
7697
7698 const Expr *getDataArg(unsigned i) const;
7699
7700 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7701 const analyze_format_string::ConversionSpecifier &CS,
7702 const char *startSpecifier, unsigned specifierLen,
7703 unsigned argIndex);
7704
7705 template <typename Range>
7706 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7707 bool IsStringLocation, Range StringRange,
7708 ArrayRef<FixItHint> Fixit = {});
7709};
7710
7711} // namespace
7712
7713SourceRange CheckFormatHandler::getFormatStringRange() {
7714 return OrigFormatExpr->getSourceRange();
7715}
7716
7717CharSourceRange CheckFormatHandler::
7718getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7719 SourceLocation Start = getLocationOfByte(x: startSpecifier);
7720 SourceLocation End = getLocationOfByte(x: startSpecifier + specifierLen - 1);
7721
7722 // Advance the end SourceLocation by one due to half-open ranges.
7723 End = End.getLocWithOffset(Offset: 1);
7724
7725 return CharSourceRange::getCharRange(B: Start, E: End);
7726}
7727
7728SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7729 return FExpr->getLocationOfByte(ByteNo: x - Beg, SM: S.getSourceManager(),
7730 Features: S.getLangOpts(), Target: S.Context.getTargetInfo());
7731}
7732
7733void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7734 unsigned specifierLen){
7735 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_incomplete_specifier),
7736 Loc: getLocationOfByte(x: startSpecifier),
7737 /*IsStringLocation*/true,
7738 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7739}
7740
7741void CheckFormatHandler::HandleInvalidLengthModifier(
7742 const analyze_format_string::FormatSpecifier &FS,
7743 const analyze_format_string::ConversionSpecifier &CS,
7744 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7745 using namespace analyze_format_string;
7746
7747 const LengthModifier &LM = FS.getLengthModifier();
7748 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
7749
7750 // See if we know how to fix this length modifier.
7751 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7752 if (FixedLM) {
7753 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
7754 Loc: getLocationOfByte(x: LM.getStart()),
7755 /*IsStringLocation*/true,
7756 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7757
7758 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
7759 << FixedLM->toString()
7760 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
7761
7762 } else {
7763 FixItHint Hint;
7764 if (DiagID == diag::warn_format_nonsensical_length)
7765 Hint = FixItHint::CreateRemoval(RemoveRange: LMRange);
7766
7767 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
7768 Loc: getLocationOfByte(x: LM.getStart()),
7769 /*IsStringLocation*/true,
7770 StringRange: getSpecifierRange(startSpecifier, specifierLen),
7771 FixIt: Hint);
7772 }
7773}
7774
7775void CheckFormatHandler::HandleNonStandardLengthModifier(
7776 const analyze_format_string::FormatSpecifier &FS,
7777 const char *startSpecifier, unsigned specifierLen) {
7778 using namespace analyze_format_string;
7779
7780 const LengthModifier &LM = FS.getLengthModifier();
7781 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
7782
7783 // See if we know how to fix this length modifier.
7784 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7785 if (FixedLM) {
7786 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7787 << LM.toString() << 0,
7788 Loc: getLocationOfByte(x: LM.getStart()),
7789 /*IsStringLocation*/true,
7790 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7791
7792 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
7793 << FixedLM->toString()
7794 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
7795
7796 } else {
7797 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7798 << LM.toString() << 0,
7799 Loc: getLocationOfByte(x: LM.getStart()),
7800 /*IsStringLocation*/true,
7801 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7802 }
7803}
7804
7805void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7806 const analyze_format_string::ConversionSpecifier &CS,
7807 const char *startSpecifier, unsigned specifierLen) {
7808 using namespace analyze_format_string;
7809
7810 // See if we know how to fix this conversion specifier.
7811 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7812 if (FixedCS) {
7813 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7814 << CS.toString() << /*conversion specifier*/1,
7815 Loc: getLocationOfByte(x: CS.getStart()),
7816 /*IsStringLocation*/true,
7817 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7818
7819 CharSourceRange CSRange = getSpecifierRange(startSpecifier: CS.getStart(), specifierLen: CS.getLength());
7820 S.Diag(Loc: getLocationOfByte(x: CS.getStart()), DiagID: diag::note_format_fix_specifier)
7821 << FixedCS->toString()
7822 << FixItHint::CreateReplacement(RemoveRange: CSRange, Code: FixedCS->toString());
7823 } else {
7824 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7825 << CS.toString() << /*conversion specifier*/1,
7826 Loc: getLocationOfByte(x: CS.getStart()),
7827 /*IsStringLocation*/true,
7828 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7829 }
7830}
7831
7832void CheckFormatHandler::HandlePosition(const char *startPos,
7833 unsigned posLen) {
7834 if (!S.getDiagnostics().isIgnored(
7835 DiagID: diag::warn_format_non_standard_positional_arg, Loc: SourceLocation()))
7836 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard_positional_arg),
7837 Loc: getLocationOfByte(x: startPos),
7838 /*IsStringLocation*/ true,
7839 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
7840}
7841
7842void CheckFormatHandler::HandleInvalidPosition(
7843 const char *startSpecifier, unsigned specifierLen,
7844 analyze_format_string::PositionContext p) {
7845 if (!S.getDiagnostics().isIgnored(
7846 DiagID: diag::warn_format_invalid_positional_specifier, Loc: SourceLocation()))
7847 EmitFormatDiagnostic(
7848 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7849 Loc: getLocationOfByte(x: startSpecifier), /*IsStringLocation*/ true,
7850 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7851}
7852
7853void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7854 unsigned posLen) {
7855 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_format_zero_positional_specifier,
7856 Loc: SourceLocation()))
7857 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_zero_positional_specifier),
7858 Loc: getLocationOfByte(x: startPos),
7859 /*IsStringLocation*/ true,
7860 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
7861}
7862
7863void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7864 if (!isa<ObjCStringLiteral>(Val: OrigFormatExpr)) {
7865 // The presence of a null character is likely an error.
7866 EmitFormatDiagnostic(
7867 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_contains_null_char),
7868 Loc: getLocationOfByte(x: nullCharacter), /*IsStringLocation*/true,
7869 StringRange: getFormatStringRange());
7870 }
7871}
7872
7873// Note that this may return NULL if there was an error parsing or building
7874// one of the argument expressions.
7875const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7876 return Args[FirstDataArg + i];
7877}
7878
7879void CheckFormatHandler::DoneProcessing() {
7880 // Does the number of data arguments exceed the number of
7881 // format conversions in the format string?
7882 if (HasFormatArguments()) {
7883 // Find any arguments that weren't covered.
7884 CoveredArgs.flip();
7885 signed notCoveredArg = CoveredArgs.find_first();
7886 if (notCoveredArg >= 0) {
7887 assert((unsigned)notCoveredArg < NumDataArgs);
7888 UncoveredArg.Update(NewFirstUncoveredArg: notCoveredArg, StrExpr: OrigFormatExpr);
7889 } else {
7890 UncoveredArg.setAllCovered();
7891 }
7892 }
7893}
7894
7895void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7896 const Expr *ArgExpr) {
7897 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7898 "Invalid state");
7899
7900 if (!ArgExpr)
7901 return;
7902
7903 SourceLocation Loc = ArgExpr->getBeginLoc();
7904
7905 if (S.getSourceManager().isInSystemMacro(loc: Loc))
7906 return;
7907
7908 PartialDiagnostic PDiag = S.PDiag(DiagID: diag::warn_printf_data_arg_not_used);
7909 for (auto E : DiagnosticExprs)
7910 PDiag << E->getSourceRange();
7911
7912 CheckFormatHandler::EmitFormatDiagnostic(
7913 S, InFunctionCall: IsFunctionCall, ArgumentExpr: DiagnosticExprs[0],
7914 PDiag, Loc, /*IsStringLocation*/false,
7915 StringRange: DiagnosticExprs[0]->getSourceRange());
7916}
7917
7918bool
7919CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7920 SourceLocation Loc,
7921 const char *startSpec,
7922 unsigned specifierLen,
7923 const char *csStart,
7924 unsigned csLen) {
7925 bool keepGoing = true;
7926 if (argIndex < NumDataArgs) {
7927 // Consider the argument coverered, even though the specifier doesn't
7928 // make sense.
7929 CoveredArgs.set(argIndex);
7930 }
7931 else {
7932 // If argIndex exceeds the number of data arguments we
7933 // don't issue a warning because that is just a cascade of warnings (and
7934 // they may have intended '%%' anyway). We don't want to continue processing
7935 // the format string after this point, however, as we will like just get
7936 // gibberish when trying to match arguments.
7937 keepGoing = false;
7938 }
7939
7940 StringRef Specifier(csStart, csLen);
7941
7942 // If the specifier in non-printable, it could be the first byte of a UTF-8
7943 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7944 // hex value.
7945 std::string CodePointStr;
7946 if (!llvm::sys::locale::isPrint(c: *csStart)) {
7947 llvm::UTF32 CodePoint;
7948 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7949 const llvm::UTF8 *E =
7950 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7951 llvm::ConversionResult Result =
7952 llvm::convertUTF8Sequence(source: B, sourceEnd: E, target: &CodePoint, flags: llvm::strictConversion);
7953
7954 if (Result != llvm::conversionOK) {
7955 unsigned char FirstChar = *csStart;
7956 CodePoint = (llvm::UTF32)FirstChar;
7957 }
7958
7959 llvm::raw_string_ostream OS(CodePointStr);
7960 if (CodePoint < 256)
7961 OS << "\\x" << llvm::format(Fmt: "%02x", Vals: CodePoint);
7962 else if (CodePoint <= 0xFFFF)
7963 OS << "\\u" << llvm::format(Fmt: "%04x", Vals: CodePoint);
7964 else
7965 OS << "\\U" << llvm::format(Fmt: "%08x", Vals: CodePoint);
7966 Specifier = CodePointStr;
7967 }
7968
7969 EmitFormatDiagnostic(
7970 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_conversion) << Specifier, Loc,
7971 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
7972
7973 return keepGoing;
7974}
7975
7976void
7977CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7978 const char *startSpec,
7979 unsigned specifierLen) {
7980 EmitFormatDiagnostic(
7981 PDiag: S.PDiag(DiagID: diag::warn_format_mix_positional_nonpositional_args),
7982 Loc, /*isStringLoc*/IsStringLocation: true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
7983}
7984
7985bool
7986CheckFormatHandler::CheckNumArgs(
7987 const analyze_format_string::FormatSpecifier &FS,
7988 const analyze_format_string::ConversionSpecifier &CS,
7989 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7990
7991 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7992 PartialDiagnostic PDiag = FS.usesPositionalArg()
7993 ? (S.PDiag(DiagID: diag::warn_printf_positional_arg_exceeds_data_args)
7994 << (argIndex+1) << NumDataArgs)
7995 : S.PDiag(DiagID: diag::warn_printf_insufficient_data_args);
7996 EmitFormatDiagnostic(
7997 PDiag, Loc: getLocationOfByte(x: CS.getStart()), /*IsStringLocation*/true,
7998 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7999
8000 // Since more arguments than conversion tokens are given, by extension
8001 // all arguments are covered, so mark this as so.
8002 UncoveredArg.setAllCovered();
8003 return false;
8004 }
8005 return true;
8006}
8007
8008template<typename Range>
8009void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8010 SourceLocation Loc,
8011 bool IsStringLocation,
8012 Range StringRange,
8013 ArrayRef<FixItHint> FixIt) {
8014 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8015 Loc, IsStringLocation, StringRange, FixIt);
8016}
8017
8018/// If the format string is not within the function call, emit a note
8019/// so that the function call and string are in diagnostic messages.
8020///
8021/// \param InFunctionCall if true, the format string is within the function
8022/// call and only one diagnostic message will be produced. Otherwise, an
8023/// extra note will be emitted pointing to location of the format string.
8024///
8025/// \param ArgumentExpr the expression that is passed as the format string
8026/// argument in the function call. Used for getting locations when two
8027/// diagnostics are emitted.
8028///
8029/// \param PDiag the callee should already have provided any strings for the
8030/// diagnostic message. This function only adds locations and fixits
8031/// to diagnostics.
8032///
8033/// \param Loc primary location for diagnostic. If two diagnostics are
8034/// required, one will be at Loc and a new SourceLocation will be created for
8035/// the other one.
8036///
8037/// \param IsStringLocation if true, Loc points to the format string should be
8038/// used for the note. Otherwise, Loc points to the argument list and will
8039/// be used with PDiag.
8040///
8041/// \param StringRange some or all of the string to highlight. This is
8042/// templated so it can accept either a CharSourceRange or a SourceRange.
8043///
8044/// \param FixIt optional fix it hint for the format string.
8045template <typename Range>
8046void CheckFormatHandler::EmitFormatDiagnostic(
8047 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8048 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8049 Range StringRange, ArrayRef<FixItHint> FixIt) {
8050 if (InFunctionCall) {
8051 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PD: PDiag);
8052 D << StringRange;
8053 D << FixIt;
8054 } else {
8055 S.Diag(Loc: IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PD: PDiag)
8056 << ArgumentExpr->getSourceRange();
8057
8058 const Sema::SemaDiagnosticBuilder &Note =
8059 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8060 diag::note_format_string_defined);
8061
8062 Note << StringRange;
8063 Note << FixIt;
8064 }
8065}
8066
8067//===--- CHECK: Printf format string checking -----------------------------===//
8068
8069namespace {
8070
8071class CheckPrintfHandler : public CheckFormatHandler {
8072public:
8073 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8074 const Expr *origFormatExpr, const FormatStringType type,
8075 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8076 const char *beg, Sema::FormatArgumentPassingKind APK,
8077 ArrayRef<const Expr *> Args, unsigned formatIdx,
8078 bool inFunctionCall, VariadicCallType CallType,
8079 llvm::SmallBitVector &CheckedVarArgs,
8080 UncoveredArgHandler &UncoveredArg)
8081 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8082 numDataArgs, beg, APK, Args, formatIdx,
8083 inFunctionCall, CallType, CheckedVarArgs,
8084 UncoveredArg) {}
8085
8086 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8087
8088 /// Returns true if '%@' specifiers are allowed in the format string.
8089 bool allowsObjCArg() const {
8090 return FSType == FormatStringType::NSString ||
8091 FSType == FormatStringType::OSLog ||
8092 FSType == FormatStringType::OSTrace;
8093 }
8094
8095 bool HandleInvalidPrintfConversionSpecifier(
8096 const analyze_printf::PrintfSpecifier &FS,
8097 const char *startSpecifier,
8098 unsigned specifierLen) override;
8099
8100 void handleInvalidMaskType(StringRef MaskType) override;
8101
8102 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8103 const char *startSpecifier, unsigned specifierLen,
8104 const TargetInfo &Target) override;
8105 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8106 const char *StartSpecifier,
8107 unsigned SpecifierLen,
8108 const Expr *E);
8109
8110 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8111 const char *startSpecifier, unsigned specifierLen);
8112 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8113 const analyze_printf::OptionalAmount &Amt,
8114 unsigned type,
8115 const char *startSpecifier, unsigned specifierLen);
8116 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8117 const analyze_printf::OptionalFlag &flag,
8118 const char *startSpecifier, unsigned specifierLen);
8119 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8120 const analyze_printf::OptionalFlag &ignoredFlag,
8121 const analyze_printf::OptionalFlag &flag,
8122 const char *startSpecifier, unsigned specifierLen);
8123 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8124 const Expr *E);
8125
8126 void HandleEmptyObjCModifierFlag(const char *startFlag,
8127 unsigned flagLen) override;
8128
8129 void HandleInvalidObjCModifierFlag(const char *startFlag,
8130 unsigned flagLen) override;
8131
8132 void
8133 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8134 const char *flagsEnd,
8135 const char *conversionPosition) override;
8136};
8137
8138/// Keeps around the information needed to verify that two specifiers are
8139/// compatible.
8140class EquatableFormatArgument {
8141public:
8142 enum SpecifierSensitivity : unsigned {
8143 SS_None,
8144 SS_Private,
8145 SS_Public,
8146 SS_Sensitive
8147 };
8148
8149 enum FormatArgumentRole : unsigned {
8150 FAR_Data,
8151 FAR_FieldWidth,
8152 FAR_Precision,
8153 FAR_Auxiliary, // FreeBSD kernel %b and %D
8154 };
8155
8156private:
8157 analyze_format_string::ArgType ArgType;
8158 analyze_format_string::LengthModifier::Kind LengthMod;
8159 StringRef SpecifierLetter;
8160 CharSourceRange Range;
8161 SourceLocation ElementLoc;
8162 FormatArgumentRole Role : 2;
8163 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8164 unsigned Position : 14;
8165 unsigned ModifierFor : 14; // not set for FAR_Data
8166
8167 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8168 bool InFunctionCall) const;
8169
8170public:
8171 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8172 analyze_format_string::LengthModifier::Kind LengthMod,
8173 StringRef SpecifierLetter,
8174 analyze_format_string::ArgType ArgType,
8175 FormatArgumentRole Role,
8176 SpecifierSensitivity Sensitivity, unsigned Position,
8177 unsigned ModifierFor)
8178 : ArgType(ArgType), LengthMod(LengthMod),
8179 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8180 Role(Role), Sensitivity(Sensitivity), Position(Position),
8181 ModifierFor(ModifierFor) {}
8182
8183 unsigned getPosition() const { return Position; }
8184 SourceLocation getSourceLocation() const { return ElementLoc; }
8185 CharSourceRange getSourceRange() const { return Range; }
8186 analyze_format_string::LengthModifier getLengthModifier() const {
8187 return analyze_format_string::LengthModifier(nullptr, LengthMod);
8188 }
8189 void setModifierFor(unsigned V) { ModifierFor = V; }
8190
8191 std::string buildFormatSpecifier() const {
8192 std::string result;
8193 llvm::raw_string_ostream(result)
8194 << getLengthModifier().toString() << SpecifierLetter;
8195 return result;
8196 }
8197
8198 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8199 const Expr *FmtExpr, bool InFunctionCall) const;
8200};
8201
8202/// Turns format strings into lists of EquatableSpecifier objects.
8203class DecomposePrintfHandler : public CheckPrintfHandler {
8204 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8205 bool HadError;
8206
8207 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8208 const Expr *origFormatExpr,
8209 const FormatStringType type, unsigned firstDataArg,
8210 unsigned numDataArgs, bool isObjC, const char *beg,
8211 Sema::FormatArgumentPassingKind APK,
8212 ArrayRef<const Expr *> Args, unsigned formatIdx,
8213 bool inFunctionCall, VariadicCallType CallType,
8214 llvm::SmallBitVector &CheckedVarArgs,
8215 UncoveredArgHandler &UncoveredArg,
8216 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8217 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8218 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8219 inFunctionCall, CallType, CheckedVarArgs,
8220 UncoveredArg),
8221 Specs(Specs), HadError(false) {}
8222
8223public:
8224 static bool
8225 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8226 FormatStringType type, bool IsObjC, bool InFunctionCall,
8227 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8228
8229 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8230 const char *startSpecifier,
8231 unsigned specifierLen,
8232 const TargetInfo &Target) override;
8233};
8234
8235} // namespace
8236
8237bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8238 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8239 unsigned specifierLen) {
8240 const analyze_printf::PrintfConversionSpecifier &CS =
8241 FS.getConversionSpecifier();
8242
8243 return HandleInvalidConversionSpecifier(argIndex: FS.getArgIndex(),
8244 Loc: getLocationOfByte(x: CS.getStart()),
8245 startSpec: startSpecifier, specifierLen,
8246 csStart: CS.getStart(), csLen: CS.getLength());
8247}
8248
8249void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8250 S.Diag(Loc: getLocationOfByte(x: MaskType.data()), DiagID: diag::err_invalid_mask_type_size);
8251}
8252
8253// Error out if struct or complex type argments are passed to os_log.
8254static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType,
8255 QualType T) {
8256 if (FSType != FormatStringType::OSLog)
8257 return false;
8258 return T->isRecordType() || T->isComplexType();
8259}
8260
8261bool CheckPrintfHandler::HandleAmount(
8262 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8263 const char *startSpecifier, unsigned specifierLen) {
8264 if (Amt.hasDataArgument()) {
8265 if (HasFormatArguments()) {
8266 unsigned argIndex = Amt.getArgIndex();
8267 if (argIndex >= NumDataArgs) {
8268 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_asterisk_missing_arg)
8269 << k,
8270 Loc: getLocationOfByte(x: Amt.getStart()),
8271 /*IsStringLocation*/ true,
8272 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8273 // Don't do any more checking. We will just emit
8274 // spurious errors.
8275 return false;
8276 }
8277
8278 // Type check the data argument. It should be an 'int'.
8279 // Although not in conformance with C99, we also allow the argument to be
8280 // an 'unsigned int' as that is a reasonably safe case. GCC also
8281 // doesn't emit a warning for that case.
8282 CoveredArgs.set(argIndex);
8283 const Expr *Arg = getDataArg(i: argIndex);
8284 if (!Arg)
8285 return false;
8286
8287 QualType T = Arg->getType();
8288
8289 const analyze_printf::ArgType &AT = Amt.getArgType(Ctx&: S.Context);
8290 assert(AT.isValid());
8291
8292 if (!AT.matchesType(C&: S.Context, argTy: T)) {
8293 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8294 ? diag::err_printf_asterisk_wrong_type
8295 : diag::warn_printf_asterisk_wrong_type;
8296 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID)
8297 << k << AT.getRepresentativeTypeName(C&: S.Context)
8298 << T << Arg->getSourceRange(),
8299 Loc: getLocationOfByte(x: Amt.getStart()),
8300 /*IsStringLocation*/ true,
8301 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8302 // Don't do any more checking. We will just emit
8303 // spurious errors.
8304 return false;
8305 }
8306 }
8307 }
8308 return true;
8309}
8310
8311void CheckPrintfHandler::HandleInvalidAmount(
8312 const analyze_printf::PrintfSpecifier &FS,
8313 const analyze_printf::OptionalAmount &Amt,
8314 unsigned type,
8315 const char *startSpecifier,
8316 unsigned specifierLen) {
8317 const analyze_printf::PrintfConversionSpecifier &CS =
8318 FS.getConversionSpecifier();
8319
8320 FixItHint fixit =
8321 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8322 ? FixItHint::CreateRemoval(RemoveRange: getSpecifierRange(startSpecifier: Amt.getStart(),
8323 specifierLen: Amt.getConstantLength()))
8324 : FixItHint();
8325
8326 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_optional_amount)
8327 << type << CS.toString(),
8328 Loc: getLocationOfByte(x: Amt.getStart()),
8329 /*IsStringLocation*/true,
8330 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8331 FixIt: fixit);
8332}
8333
8334void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8335 const analyze_printf::OptionalFlag &flag,
8336 const char *startSpecifier,
8337 unsigned specifierLen) {
8338 // Warn about pointless flag with a fixit removal.
8339 const analyze_printf::PrintfConversionSpecifier &CS =
8340 FS.getConversionSpecifier();
8341 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_flag)
8342 << flag.toString() << CS.toString(),
8343 Loc: getLocationOfByte(x: flag.getPosition()),
8344 /*IsStringLocation*/true,
8345 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8346 FixIt: FixItHint::CreateRemoval(
8347 RemoveRange: getSpecifierRange(startSpecifier: flag.getPosition(), specifierLen: 1)));
8348}
8349
8350void CheckPrintfHandler::HandleIgnoredFlag(
8351 const analyze_printf::PrintfSpecifier &FS,
8352 const analyze_printf::OptionalFlag &ignoredFlag,
8353 const analyze_printf::OptionalFlag &flag,
8354 const char *startSpecifier,
8355 unsigned specifierLen) {
8356 // Warn about ignored flag with a fixit removal.
8357 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_ignored_flag)
8358 << ignoredFlag.toString() << flag.toString(),
8359 Loc: getLocationOfByte(x: ignoredFlag.getPosition()),
8360 /*IsStringLocation*/true,
8361 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8362 FixIt: FixItHint::CreateRemoval(
8363 RemoveRange: getSpecifierRange(startSpecifier: ignoredFlag.getPosition(), specifierLen: 1)));
8364}
8365
8366void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8367 unsigned flagLen) {
8368 // Warn about an empty flag.
8369 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_empty_objc_flag),
8370 Loc: getLocationOfByte(x: startFlag),
8371 /*IsStringLocation*/true,
8372 StringRange: getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen));
8373}
8374
8375void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8376 unsigned flagLen) {
8377 // Warn about an invalid flag.
8378 auto Range = getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen);
8379 StringRef flag(startFlag, flagLen);
8380 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_invalid_objc_flag) << flag,
8381 Loc: getLocationOfByte(x: startFlag),
8382 /*IsStringLocation*/true,
8383 StringRange: Range, FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8384}
8385
8386void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8387 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8388 // Warn about using '[...]' without a '@' conversion.
8389 auto Range = getSpecifierRange(startSpecifier: flagsStart, specifierLen: flagsEnd - flagsStart + 1);
8390 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8391 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag) << StringRef(conversionPosition, 1),
8392 Loc: getLocationOfByte(x: conversionPosition),
8393 /*IsStringLocation*/ true, StringRange: Range,
8394 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8395}
8396
8397void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8398 const Expr *FmtExpr,
8399 bool InFunctionCall) const {
8400 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, ArgumentExpr: FmtExpr, PDiag,
8401 Loc: ElementLoc, IsStringLocation: true, StringRange: Range);
8402}
8403
8404bool EquatableFormatArgument::VerifyCompatible(
8405 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8406 bool InFunctionCall) const {
8407 using MK = analyze_format_string::ArgType::MatchKind;
8408 if (Role != Other.Role) {
8409 // diagnose and stop
8410 EmitDiagnostic(
8411 S, PDiag: S.PDiag(DiagID: diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8412 FmtExpr, InFunctionCall);
8413 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8414 return false;
8415 }
8416
8417 if (Role != FAR_Data) {
8418 if (ModifierFor != Other.ModifierFor) {
8419 // diagnose and stop
8420 EmitDiagnostic(S,
8421 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_modifierfor_mismatch)
8422 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8423 FmtExpr, InFunctionCall);
8424 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8425 return false;
8426 }
8427 return true;
8428 }
8429
8430 bool HadError = false;
8431 if (Sensitivity != Other.Sensitivity) {
8432 // diagnose and continue
8433 EmitDiagnostic(S,
8434 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_sensitivity_mismatch)
8435 << Sensitivity << Other.Sensitivity,
8436 FmtExpr, InFunctionCall);
8437 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8438 << 0 << Other.Range;
8439 }
8440
8441 switch (ArgType.matchesArgType(C&: S.Context, other: Other.ArgType)) {
8442 case MK::Match:
8443 break;
8444
8445 case MK::MatchPromotion:
8446 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8447 // MatchPromotion is treated as a failure by format_matches.
8448 case MK::NoMatch:
8449 case MK::NoMatchTypeConfusion:
8450 case MK::NoMatchPromotionTypeConfusion:
8451 EmitDiagnostic(S,
8452 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch)
8453 << buildFormatSpecifier()
8454 << Other.buildFormatSpecifier(),
8455 FmtExpr, InFunctionCall);
8456 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8457 << 0 << Other.Range;
8458 break;
8459
8460 case MK::NoMatchPedantic:
8461 EmitDiagnostic(S,
8462 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch_pedantic)
8463 << buildFormatSpecifier()
8464 << Other.buildFormatSpecifier(),
8465 FmtExpr, InFunctionCall);
8466 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8467 << 0 << Other.Range;
8468 break;
8469
8470 case MK::NoMatchSignedness:
8471 EmitDiagnostic(S,
8472 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_sign_mismatch)
8473 << buildFormatSpecifier()
8474 << Other.buildFormatSpecifier(),
8475 FmtExpr, InFunctionCall);
8476 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8477 << 0 << Other.Range;
8478 break;
8479 }
8480 return !HadError;
8481}
8482
8483bool DecomposePrintfHandler::GetSpecifiers(
8484 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8485 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8486 llvm::SmallVectorImpl<EquatableFormatArgument> &Args) {
8487 StringRef Data = FSL->getString();
8488 const char *Str = Data.data();
8489 llvm::SmallBitVector BV;
8490 UncoveredArgHandler UA;
8491 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8492 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8493 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8494 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8495 UA, Args);
8496
8497 if (!analyze_format_string::ParsePrintfString(
8498 H, beg: Str, end: Str + Data.size(), LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
8499 isFreeBSDKPrintf: Type == FormatStringType::FreeBSDKPrintf))
8500 H.DoneProcessing();
8501 if (H.HadError)
8502 return false;
8503
8504 llvm::stable_sort(Range&: Args, C: [](const EquatableFormatArgument &A,
8505 const EquatableFormatArgument &B) {
8506 return A.getPosition() < B.getPosition();
8507 });
8508 return true;
8509}
8510
8511bool DecomposePrintfHandler::HandlePrintfSpecifier(
8512 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8513 unsigned specifierLen, const TargetInfo &Target) {
8514 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8515 specifierLen, Target)) {
8516 HadError = true;
8517 return false;
8518 }
8519
8520 // Do not add any specifiers to the list for %%. This is possibly incorrect
8521 // if using a precision/width with a data argument, but that combination is
8522 // meaningless and we wouldn't know which format to attach the
8523 // precision/width to.
8524 const auto &CS = FS.getConversionSpecifier();
8525 if (CS.getKind() == analyze_format_string::ConversionSpecifier::PercentArg)
8526 return true;
8527
8528 // have to patch these to have the right ModifierFor if they are used
8529 const unsigned Unset = ~0;
8530 unsigned FieldWidthIndex = Unset;
8531 unsigned PrecisionIndex = Unset;
8532
8533 // field width?
8534 const auto &FieldWidth = FS.getFieldWidth();
8535 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8536 FieldWidthIndex = Specs.size();
8537 Specs.emplace_back(Args: getSpecifierRange(startSpecifier, specifierLen),
8538 Args: getLocationOfByte(x: FieldWidth.getStart()),
8539 Args: analyze_format_string::LengthModifier::None, Args: "*",
8540 Args: FieldWidth.getArgType(Ctx&: S.Context),
8541 Args: EquatableFormatArgument::FAR_FieldWidth,
8542 Args: EquatableFormatArgument::SS_None,
8543 Args: FieldWidth.usesPositionalArg()
8544 ? FieldWidth.getPositionalArgIndex() - 1
8545 : FieldWidthIndex,
8546 Args: 0);
8547 }
8548 // precision?
8549 const auto &Precision = FS.getPrecision();
8550 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8551 PrecisionIndex = Specs.size();
8552 Specs.emplace_back(
8553 Args: getSpecifierRange(startSpecifier, specifierLen),
8554 Args: getLocationOfByte(x: Precision.getStart()),
8555 Args: analyze_format_string::LengthModifier::None, Args: ".*",
8556 Args: Precision.getArgType(Ctx&: S.Context), Args: EquatableFormatArgument::FAR_Precision,
8557 Args: EquatableFormatArgument::SS_None,
8558 Args: Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8559 : PrecisionIndex,
8560 Args: 0);
8561 }
8562
8563 // this specifier
8564 unsigned SpecIndex =
8565 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8566 if (FieldWidthIndex != Unset)
8567 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8568 if (PrecisionIndex != Unset)
8569 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8570
8571 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8572 if (FS.isPrivate())
8573 Sensitivity = EquatableFormatArgument::SS_Private;
8574 else if (FS.isPublic())
8575 Sensitivity = EquatableFormatArgument::SS_Public;
8576 else if (FS.isSensitive())
8577 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8578 else
8579 Sensitivity = EquatableFormatArgument::SS_None;
8580
8581 Specs.emplace_back(
8582 Args: getSpecifierRange(startSpecifier, specifierLen),
8583 Args: getLocationOfByte(x: CS.getStart()), Args: FS.getLengthModifier().getKind(),
8584 Args: CS.getCharacters(), Args: FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext()),
8585 Args: EquatableFormatArgument::FAR_Data, Args&: Sensitivity, Args&: SpecIndex, Args: 0);
8586
8587 // auxiliary argument?
8588 if (CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDbArg ||
8589 CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDDArg) {
8590 Specs.emplace_back(Args: getSpecifierRange(startSpecifier, specifierLen),
8591 Args: getLocationOfByte(x: CS.getStart()),
8592 Args: analyze_format_string::LengthModifier::None,
8593 Args: CS.getCharacters(),
8594 Args: analyze_format_string::ArgType::CStrTy,
8595 Args: EquatableFormatArgument::FAR_Auxiliary, Args&: Sensitivity,
8596 Args: SpecIndex + 1, Args&: SpecIndex);
8597 }
8598 return true;
8599}
8600
8601// Determines if the specified is a C++ class or struct containing
8602// a member with the specified name and kind (e.g. a CXXMethodDecl named
8603// "c_str()").
8604template<typename MemberKind>
8605static llvm::SmallPtrSet<MemberKind*, 1>
8606CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8607 auto *RD = Ty->getAsCXXRecordDecl();
8608 llvm::SmallPtrSet<MemberKind*, 1> Results;
8609
8610 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8611 return Results;
8612
8613 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8614 Sema::LookupMemberName);
8615 R.suppressDiagnostics();
8616
8617 // We just need to include all members of the right kind turned up by the
8618 // filter, at this point.
8619 if (S.LookupQualifiedName(R, LookupCtx: RD))
8620 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8621 NamedDecl *decl = (*I)->getUnderlyingDecl();
8622 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8623 Results.insert(FK);
8624 }
8625 return Results;
8626}
8627
8628/// Check if we could call '.c_str()' on an object.
8629///
8630/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8631/// allow the call, or if it would be ambiguous).
8632bool Sema::hasCStrMethod(const Expr *E) {
8633 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8634
8635 MethodSet Results =
8636 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S&: *this, Ty: E->getType());
8637 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8638 MI != ME; ++MI)
8639 if ((*MI)->getMinRequiredArguments() == 0)
8640 return true;
8641 return false;
8642}
8643
8644// Check if a (w)string was passed when a (w)char* was needed, and offer a
8645// better diagnostic if so. AT is assumed to be valid.
8646// Returns true when a c_str() conversion method is found.
8647bool CheckPrintfHandler::checkForCStrMembers(
8648 const analyze_printf::ArgType &AT, const Expr *E) {
8649 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8650
8651 MethodSet Results =
8652 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S, Ty: E->getType());
8653
8654 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8655 MI != ME; ++MI) {
8656 const CXXMethodDecl *Method = *MI;
8657 if (Method->getMinRequiredArguments() == 0 &&
8658 AT.matchesType(C&: S.Context, argTy: Method->getReturnType())) {
8659 // FIXME: Suggest parens if the expression needs them.
8660 SourceLocation EndLoc = S.getLocForEndOfToken(Loc: E->getEndLoc());
8661 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_printf_c_str)
8662 << "c_str()" << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ".c_str()");
8663 return true;
8664 }
8665 }
8666
8667 return false;
8668}
8669
8670bool CheckPrintfHandler::HandlePrintfSpecifier(
8671 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8672 unsigned specifierLen, const TargetInfo &Target) {
8673 using namespace analyze_format_string;
8674 using namespace analyze_printf;
8675
8676 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8677
8678 if (FS.consumesDataArgument()) {
8679 if (atFirstArg) {
8680 atFirstArg = false;
8681 usesPositionalArgs = FS.usesPositionalArg();
8682 }
8683 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8684 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
8685 startSpec: startSpecifier, specifierLen);
8686 return false;
8687 }
8688 }
8689
8690 // First check if the field width, precision, and conversion specifier
8691 // have matching data arguments.
8692 if (!HandleAmount(Amt: FS.getFieldWidth(), /* field width */ k: 0,
8693 startSpecifier, specifierLen)) {
8694 return false;
8695 }
8696
8697 if (!HandleAmount(Amt: FS.getPrecision(), /* precision */ k: 1,
8698 startSpecifier, specifierLen)) {
8699 return false;
8700 }
8701
8702 if (!CS.consumesDataArgument()) {
8703 // FIXME: Technically specifying a precision or field width here
8704 // makes no sense. Worth issuing a warning at some point.
8705 return true;
8706 }
8707
8708 // Consume the argument.
8709 unsigned argIndex = FS.getArgIndex();
8710 if (argIndex < NumDataArgs) {
8711 // The check to see if the argIndex is valid will come later.
8712 // We set the bit here because we may exit early from this
8713 // function if we encounter some other error.
8714 CoveredArgs.set(argIndex);
8715 }
8716
8717 // FreeBSD kernel extensions.
8718 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8719 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8720 // We need at least two arguments.
8721 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex: argIndex + 1))
8722 return false;
8723
8724 if (HasFormatArguments()) {
8725 // Claim the second argument.
8726 CoveredArgs.set(argIndex + 1);
8727
8728 // Type check the first argument (int for %b, pointer for %D)
8729 const Expr *Ex = getDataArg(i: argIndex);
8730 const analyze_printf::ArgType &AT =
8731 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8732 ? ArgType(S.Context.IntTy)
8733 : ArgType::CPointerTy;
8734 if (AT.isValid() && !AT.matchesType(C&: S.Context, argTy: Ex->getType()))
8735 EmitFormatDiagnostic(
8736 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
8737 << AT.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
8738 << false << Ex->getSourceRange(),
8739 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
8740 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8741
8742 // Type check the second argument (char * for both %b and %D)
8743 Ex = getDataArg(i: argIndex + 1);
8744 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8745 if (AT2.isValid() && !AT2.matchesType(C&: S.Context, argTy: Ex->getType()))
8746 EmitFormatDiagnostic(
8747 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
8748 << AT2.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
8749 << false << Ex->getSourceRange(),
8750 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
8751 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8752 }
8753 return true;
8754 }
8755
8756 // Check for using an Objective-C specific conversion specifier
8757 // in a non-ObjC literal.
8758 if (!allowsObjCArg() && CS.isObjCArg()) {
8759 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8760 specifierLen);
8761 }
8762
8763 // %P can only be used with os_log.
8764 if (FSType != FormatStringType::OSLog &&
8765 CS.getKind() == ConversionSpecifier::PArg) {
8766 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8767 specifierLen);
8768 }
8769
8770 // %n is not allowed with os_log.
8771 if (FSType == FormatStringType::OSLog &&
8772 CS.getKind() == ConversionSpecifier::nArg) {
8773 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_os_log_format_narg),
8774 Loc: getLocationOfByte(x: CS.getStart()),
8775 /*IsStringLocation*/ false,
8776 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8777
8778 return true;
8779 }
8780
8781 // Only scalars are allowed for os_trace.
8782 if (FSType == FormatStringType::OSTrace &&
8783 (CS.getKind() == ConversionSpecifier::PArg ||
8784 CS.getKind() == ConversionSpecifier::sArg ||
8785 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8786 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8787 specifierLen);
8788 }
8789
8790 // Check for use of public/private annotation outside of os_log().
8791 if (FSType != FormatStringType::OSLog) {
8792 if (FS.isPublic().isSet()) {
8793 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
8794 << "public",
8795 Loc: getLocationOfByte(x: FS.isPublic().getPosition()),
8796 /*IsStringLocation*/ false,
8797 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8798 }
8799 if (FS.isPrivate().isSet()) {
8800 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
8801 << "private",
8802 Loc: getLocationOfByte(x: FS.isPrivate().getPosition()),
8803 /*IsStringLocation*/ false,
8804 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8805 }
8806 }
8807
8808 const llvm::Triple &Triple = Target.getTriple();
8809 if (CS.getKind() == ConversionSpecifier::nArg &&
8810 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8811 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_narg_not_supported),
8812 Loc: getLocationOfByte(x: CS.getStart()),
8813 /*IsStringLocation*/ false,
8814 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8815 }
8816
8817 // Check for invalid use of field width
8818 if (!FS.hasValidFieldWidth()) {
8819 HandleInvalidAmount(FS, Amt: FS.getFieldWidth(), /* field width */ type: 0,
8820 startSpecifier, specifierLen);
8821 }
8822
8823 // Check for invalid use of precision
8824 if (!FS.hasValidPrecision()) {
8825 HandleInvalidAmount(FS, Amt: FS.getPrecision(), /* precision */ type: 1,
8826 startSpecifier, specifierLen);
8827 }
8828
8829 // Precision is mandatory for %P specifier.
8830 if (CS.getKind() == ConversionSpecifier::PArg &&
8831 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8832 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_no_precision),
8833 Loc: getLocationOfByte(x: startSpecifier),
8834 /*IsStringLocation*/ false,
8835 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8836 }
8837
8838 // Check each flag does not conflict with any other component.
8839 if (!FS.hasValidThousandsGroupingPrefix())
8840 HandleFlag(FS, flag: FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8841 if (!FS.hasValidLeadingZeros())
8842 HandleFlag(FS, flag: FS.hasLeadingZeros(), startSpecifier, specifierLen);
8843 if (!FS.hasValidPlusPrefix())
8844 HandleFlag(FS, flag: FS.hasPlusPrefix(), startSpecifier, specifierLen);
8845 if (!FS.hasValidSpacePrefix())
8846 HandleFlag(FS, flag: FS.hasSpacePrefix(), startSpecifier, specifierLen);
8847 if (!FS.hasValidAlternativeForm())
8848 HandleFlag(FS, flag: FS.hasAlternativeForm(), startSpecifier, specifierLen);
8849 if (!FS.hasValidLeftJustified())
8850 HandleFlag(FS, flag: FS.isLeftJustified(), startSpecifier, specifierLen);
8851
8852 // Check that flags are not ignored by another flag
8853 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8854 HandleIgnoredFlag(FS, ignoredFlag: FS.hasSpacePrefix(), flag: FS.hasPlusPrefix(),
8855 startSpecifier, specifierLen);
8856 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8857 HandleIgnoredFlag(FS, ignoredFlag: FS.hasLeadingZeros(), flag: FS.isLeftJustified(),
8858 startSpecifier, specifierLen);
8859
8860 // Check the length modifier is valid with the given conversion specifier.
8861 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
8862 LO: S.getLangOpts()))
8863 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8864 DiagID: diag::warn_format_nonsensical_length);
8865 else if (!FS.hasStandardLengthModifier())
8866 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8867 else if (!FS.hasStandardLengthConversionCombination())
8868 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8869 DiagID: diag::warn_format_non_standard_conversion_spec);
8870
8871 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
8872 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8873
8874 // The remaining checks depend on the data arguments.
8875 if (!HasFormatArguments())
8876 return true;
8877
8878 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8879 return false;
8880
8881 const Expr *Arg = getDataArg(i: argIndex);
8882 if (!Arg)
8883 return true;
8884
8885 return checkFormatExpr(FS, StartSpecifier: startSpecifier, SpecifierLen: specifierLen, E: Arg);
8886}
8887
8888static bool requiresParensToAddCast(const Expr *E) {
8889 // FIXME: We should have a general way to reason about operator
8890 // precedence and whether parens are actually needed here.
8891 // Take care of a few common cases where they aren't.
8892 const Expr *Inside = E->IgnoreImpCasts();
8893 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: Inside))
8894 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8895
8896 switch (Inside->getStmtClass()) {
8897 case Stmt::ArraySubscriptExprClass:
8898 case Stmt::CallExprClass:
8899 case Stmt::CharacterLiteralClass:
8900 case Stmt::CXXBoolLiteralExprClass:
8901 case Stmt::DeclRefExprClass:
8902 case Stmt::FloatingLiteralClass:
8903 case Stmt::IntegerLiteralClass:
8904 case Stmt::MemberExprClass:
8905 case Stmt::ObjCArrayLiteralClass:
8906 case Stmt::ObjCBoolLiteralExprClass:
8907 case Stmt::ObjCBoxedExprClass:
8908 case Stmt::ObjCDictionaryLiteralClass:
8909 case Stmt::ObjCEncodeExprClass:
8910 case Stmt::ObjCIvarRefExprClass:
8911 case Stmt::ObjCMessageExprClass:
8912 case Stmt::ObjCPropertyRefExprClass:
8913 case Stmt::ObjCStringLiteralClass:
8914 case Stmt::ObjCSubscriptRefExprClass:
8915 case Stmt::ParenExprClass:
8916 case Stmt::StringLiteralClass:
8917 case Stmt::UnaryOperatorClass:
8918 return false;
8919 default:
8920 return true;
8921 }
8922}
8923
8924static std::pair<QualType, StringRef>
8925shouldNotPrintDirectly(const ASTContext &Context,
8926 QualType IntendedTy,
8927 const Expr *E) {
8928 // Use a 'while' to peel off layers of typedefs.
8929 QualType TyTy = IntendedTy;
8930 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8931 StringRef Name = UserTy->getDecl()->getName();
8932 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8933 .Case(S: "CFIndex", Value: Context.getNSIntegerType())
8934 .Case(S: "NSInteger", Value: Context.getNSIntegerType())
8935 .Case(S: "NSUInteger", Value: Context.getNSUIntegerType())
8936 .Case(S: "SInt32", Value: Context.IntTy)
8937 .Case(S: "UInt32", Value: Context.UnsignedIntTy)
8938 .Default(Value: QualType());
8939
8940 if (!CastTy.isNull())
8941 return std::make_pair(x&: CastTy, y&: Name);
8942
8943 TyTy = UserTy->desugar();
8944 }
8945
8946 // Strip parens if necessary.
8947 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Val: E))
8948 return shouldNotPrintDirectly(Context,
8949 IntendedTy: PE->getSubExpr()->getType(),
8950 E: PE->getSubExpr());
8951
8952 // If this is a conditional expression, then its result type is constructed
8953 // via usual arithmetic conversions and thus there might be no necessary
8954 // typedef sugar there. Recurse to operands to check for NSInteger &
8955 // Co. usage condition.
8956 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
8957 QualType TrueTy, FalseTy;
8958 StringRef TrueName, FalseName;
8959
8960 std::tie(args&: TrueTy, args&: TrueName) =
8961 shouldNotPrintDirectly(Context,
8962 IntendedTy: CO->getTrueExpr()->getType(),
8963 E: CO->getTrueExpr());
8964 std::tie(args&: FalseTy, args&: FalseName) =
8965 shouldNotPrintDirectly(Context,
8966 IntendedTy: CO->getFalseExpr()->getType(),
8967 E: CO->getFalseExpr());
8968
8969 if (TrueTy == FalseTy)
8970 return std::make_pair(x&: TrueTy, y&: TrueName);
8971 else if (TrueTy.isNull())
8972 return std::make_pair(x&: FalseTy, y&: FalseName);
8973 else if (FalseTy.isNull())
8974 return std::make_pair(x&: TrueTy, y&: TrueName);
8975 }
8976
8977 return std::make_pair(x: QualType(), y: StringRef());
8978}
8979
8980/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8981/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8982/// type do not count.
8983static bool
8984isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8985 QualType From = ICE->getSubExpr()->getType();
8986 QualType To = ICE->getType();
8987 // It's an integer promotion if the destination type is the promoted
8988 // source type.
8989 if (ICE->getCastKind() == CK_IntegralCast &&
8990 S.Context.isPromotableIntegerType(T: From) &&
8991 S.Context.getPromotedIntegerType(PromotableType: From) == To)
8992 return true;
8993 // Look through vector types, since we do default argument promotion for
8994 // those in OpenCL.
8995 if (const auto *VecTy = From->getAs<ExtVectorType>())
8996 From = VecTy->getElementType();
8997 if (const auto *VecTy = To->getAs<ExtVectorType>())
8998 To = VecTy->getElementType();
8999 // It's a floating promotion if the source type is a lower rank.
9000 return ICE->getCastKind() == CK_FloatingCast &&
9001 S.Context.getFloatingTypeOrder(LHS: From, RHS: To) < 0;
9002}
9003
9004static analyze_format_string::ArgType::MatchKind
9005handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match,
9006 DiagnosticsEngine &Diags, SourceLocation Loc) {
9007 if (Match == analyze_format_string::ArgType::NoMatchSignedness) {
9008 if (Diags.isIgnored(
9009 DiagID: diag::warn_format_conversion_argument_type_mismatch_signedness,
9010 Loc) ||
9011 Diags.isIgnored(
9012 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9013 DiagID: diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9014 return analyze_format_string::ArgType::Match;
9015 }
9016 }
9017 return Match;
9018}
9019
9020bool
9021CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9022 const char *StartSpecifier,
9023 unsigned SpecifierLen,
9024 const Expr *E) {
9025 using namespace analyze_format_string;
9026 using namespace analyze_printf;
9027
9028 // Now type check the data expression that matches the
9029 // format specifier.
9030 const analyze_printf::ArgType &AT = FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9031 if (!AT.isValid())
9032 return true;
9033
9034 QualType ExprTy = E->getType();
9035 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(Val&: ExprTy)) {
9036 ExprTy = TET->getUnderlyingExpr()->getType();
9037 }
9038
9039 if (const OverflowBehaviorType *OBT =
9040 dyn_cast<OverflowBehaviorType>(Val: ExprTy.getCanonicalType()))
9041 ExprTy = OBT->getUnderlyingType();
9042
9043 // When using the format attribute in C++, you can receive a function or an
9044 // array that will necessarily decay to a pointer when passed to the final
9045 // format consumer. Apply decay before type comparison.
9046 if (ExprTy->canDecayToPointerType())
9047 ExprTy = S.Context.getDecayedType(T: ExprTy);
9048
9049 // Diagnose attempts to print a boolean value as a character. Unlike other
9050 // -Wformat diagnostics, this is fine from a type perspective, but it still
9051 // doesn't make sense.
9052 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9053 E->isKnownToHaveBooleanValue()) {
9054 const CharSourceRange &CSR =
9055 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9056 SmallString<4> FSString;
9057 llvm::raw_svector_ostream os(FSString);
9058 FS.toString(os);
9059 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_bool_as_character)
9060 << FSString,
9061 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9062 return true;
9063 }
9064
9065 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9066 // dumping raw class data (like is-a pointer), not actual data.
9067 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
9068 ExprTy->isObjCObjectPointerType()) {
9069 const CharSourceRange &CSR =
9070 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9071 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_with_objc_pointer),
9072 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9073 return true;
9074 }
9075
9076 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9077 ArgType::MatchKind Match = AT.matchesType(C&: S.Context, argTy: ExprTy);
9078 ArgType::MatchKind OrigMatch = Match;
9079
9080 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9081 if (Match == ArgType::Match)
9082 return true;
9083
9084 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9085 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9086
9087 // Look through argument promotions for our error message's reported type.
9088 // This includes the integral and floating promotions, but excludes array
9089 // and function pointer decay (seeing that an argument intended to be a
9090 // string has type 'char [6]' is probably more confusing than 'char *') and
9091 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9092 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
9093 if (isArithmeticArgumentPromotion(S, ICE)) {
9094 E = ICE->getSubExpr();
9095 ExprTy = E->getType();
9096
9097 // Check if we didn't match because of an implicit cast from a 'char'
9098 // or 'short' to an 'int'. This is done because printf is a varargs
9099 // function.
9100 if (ICE->getType() == S.Context.IntTy ||
9101 ICE->getType() == S.Context.UnsignedIntTy) {
9102 // All further checking is done on the subexpression
9103 ImplicitMatch = AT.matchesType(C&: S.Context, argTy: ExprTy);
9104 if (OrigMatch == ArgType::NoMatchSignedness &&
9105 ImplicitMatch != ArgType::NoMatchSignedness)
9106 // If the original match was a signedness match this match on the
9107 // implicit cast type also need to be signedness match otherwise we
9108 // might introduce new unexpected warnings from -Wformat-signedness.
9109 return true;
9110 ImplicitMatch = handleFormatSignedness(
9111 Match: ImplicitMatch, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9112 if (ImplicitMatch == ArgType::Match)
9113 return true;
9114 }
9115 }
9116 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(Val: E)) {
9117 // Special case for 'a', which has type 'int' in C.
9118 // Note, however, that we do /not/ want to treat multibyte constants like
9119 // 'MooV' as characters! This form is deprecated but still exists. In
9120 // addition, don't treat expressions as of type 'char' if one byte length
9121 // modifier is provided.
9122 if (ExprTy == S.Context.IntTy &&
9123 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9124 if (llvm::isUIntN(N: S.Context.getCharWidth(), x: CL->getValue())) {
9125 ExprTy = S.Context.CharTy;
9126 // To improve check results, we consider a character literal in C
9127 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9128 // more likely a type confusion situation, so we will suggest to
9129 // use '%hhd' instead by discarding the MatchPromotion.
9130 if (Match == ArgType::MatchPromotion)
9131 Match = ArgType::NoMatch;
9132 }
9133 }
9134 if (Match == ArgType::MatchPromotion) {
9135 // WG14 N2562 only clarified promotions in *printf
9136 // For NSLog in ObjC, just preserve -Wformat behavior
9137 if (!S.getLangOpts().ObjC &&
9138 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9139 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9140 return true;
9141 Match = ArgType::NoMatch;
9142 }
9143 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9144 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9145 Match = ImplicitMatch;
9146 assert(Match != ArgType::MatchPromotion);
9147
9148 // Look through unscoped enums to their underlying type.
9149 bool IsEnum = false;
9150 bool IsScopedEnum = false;
9151 QualType IntendedTy = ExprTy;
9152 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9153 IntendedTy = ED->getIntegerType();
9154 if (!ED->isScoped()) {
9155 ExprTy = IntendedTy;
9156 // This controls whether we're talking about the underlying type or not,
9157 // which we only want to do when it's an unscoped enum.
9158 IsEnum = true;
9159 } else {
9160 IsScopedEnum = true;
9161 }
9162 }
9163
9164 // %C in an Objective-C context prints a unichar, not a wchar_t.
9165 // If the argument is an integer of some kind, believe the %C and suggest
9166 // a cast instead of changing the conversion specifier.
9167 if (isObjCContext() &&
9168 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9169 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9170 !ExprTy->isCharType()) {
9171 // 'unichar' is defined as a typedef of unsigned short, but we should
9172 // prefer using the typedef if it is visible.
9173 IntendedTy = S.Context.UnsignedShortTy;
9174
9175 // While we are here, check if the value is an IntegerLiteral that happens
9176 // to be within the valid range.
9177 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: E)) {
9178 const llvm::APInt &V = IL->getValue();
9179 if (V.getActiveBits() <= S.Context.getTypeSize(T: IntendedTy))
9180 return true;
9181 }
9182
9183 LookupResult Result(S, &S.Context.Idents.get(Name: "unichar"), E->getBeginLoc(),
9184 Sema::LookupOrdinaryName);
9185 if (S.LookupName(R&: Result, S: S.getCurScope())) {
9186 NamedDecl *ND = Result.getFoundDecl();
9187 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: ND))
9188 if (TD->getUnderlyingType() == IntendedTy)
9189 IntendedTy =
9190 S.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
9191 /*Qualifier=*/std::nullopt, Decl: TD);
9192 }
9193 }
9194 }
9195
9196 // Special-case some of Darwin's platform-independence types by suggesting
9197 // casts to primitive types that are known to be large enough.
9198 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9199 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9200 QualType CastTy;
9201 std::tie(args&: CastTy, args&: CastTyName) = shouldNotPrintDirectly(Context: S.Context, IntendedTy, E);
9202 if (!CastTy.isNull()) {
9203 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9204 // (long in ASTContext). Only complain to pedants or when they're the
9205 // underlying type of a scoped enum (which always needs a cast).
9206 if (!IsScopedEnum &&
9207 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9208 (AT.isSizeT() || AT.isPtrdiffT()) &&
9209 AT.matchesType(C&: S.Context, argTy: CastTy))
9210 Match = ArgType::NoMatchPedantic;
9211 IntendedTy = CastTy;
9212 ShouldNotPrintDirectly = true;
9213 }
9214 }
9215
9216 // We may be able to offer a FixItHint if it is a supported type.
9217 PrintfSpecifier fixedFS = FS;
9218 bool Success =
9219 fixedFS.fixType(QT: IntendedTy, LangOpt: S.getLangOpts(), Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9220
9221 if (Success) {
9222 // Get the fix string from the fixed format specifier
9223 SmallString<16> buf;
9224 llvm::raw_svector_ostream os(buf);
9225 fixedFS.toString(os);
9226
9227 CharSourceRange SpecRange = getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9228
9229 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9230 unsigned Diag;
9231 switch (Match) {
9232 case ArgType::Match:
9233 case ArgType::MatchPromotion:
9234 case ArgType::NoMatchPromotionTypeConfusion:
9235 llvm_unreachable("expected non-matching");
9236 case ArgType::NoMatchSignedness:
9237 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9238 break;
9239 case ArgType::NoMatchPedantic:
9240 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9241 break;
9242 case ArgType::NoMatchTypeConfusion:
9243 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9244 break;
9245 case ArgType::NoMatch:
9246 Diag = diag::warn_format_conversion_argument_type_mismatch;
9247 break;
9248 }
9249
9250 // In this case, the specifier is wrong and should be changed to match
9251 // the argument.
9252 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
9253 << AT.getRepresentativeTypeName(C&: S.Context)
9254 << IntendedTy << IsEnum << E->getSourceRange(),
9255 Loc: E->getBeginLoc(),
9256 /*IsStringLocation*/ false, StringRange: SpecRange,
9257 FixIt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9258 } else {
9259 // The canonical type for formatting this value is different from the
9260 // actual type of the expression. (This occurs, for example, with Darwin's
9261 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9262 // should be printed as 'long' for 64-bit compatibility.)
9263 // Rather than emitting a normal format/argument mismatch, we want to
9264 // add a cast to the recommended type (and correct the format string
9265 // if necessary). We should also do so for scoped enumerations.
9266 SmallString<16> CastBuf;
9267 llvm::raw_svector_ostream CastFix(CastBuf);
9268 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9269 IntendedTy.print(OS&: CastFix, Policy: S.Context.getPrintingPolicy());
9270 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9271
9272 SmallVector<FixItHint,4> Hints;
9273 ArgType::MatchKind IntendedMatch = AT.matchesType(C&: S.Context, argTy: IntendedTy);
9274 IntendedMatch = handleFormatSignedness(Match: IntendedMatch, Diags&: S.getDiagnostics(),
9275 Loc: E->getExprLoc());
9276 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9277 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9278
9279 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(Val: E)) {
9280 // If there's already a cast present, just replace it.
9281 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9282 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: CastRange, Code: CastFix.str()));
9283
9284 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9285 // If the expression has high enough precedence,
9286 // just write the C-style cast.
9287 Hints.push_back(
9288 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9289 } else {
9290 // Otherwise, add parens around the expression as well as the cast.
9291 CastFix << "(";
9292 Hints.push_back(
9293 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9294
9295 // We don't use getLocForEndOfToken because it returns invalid source
9296 // locations for macro expansions (by design).
9297 SourceLocation EndLoc = S.SourceMgr.getSpellingLoc(Loc: E->getEndLoc());
9298 SourceLocation After = EndLoc.getLocWithOffset(
9299 Offset: Lexer::MeasureTokenLength(Loc: EndLoc, SM: S.SourceMgr, LangOpts: S.LangOpts));
9300 Hints.push_back(Elt: FixItHint::CreateInsertion(InsertionLoc: After, Code: ")"));
9301 }
9302
9303 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9304 // The expression has a type that should not be printed directly.
9305 // We extract the name from the typedef because we don't want to show
9306 // the underlying type in the diagnostic.
9307 StringRef Name;
9308 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9309 Name = TypedefTy->getDecl()->getName();
9310 else
9311 Name = CastTyName;
9312 unsigned Diag = Match == ArgType::NoMatchPedantic
9313 ? diag::warn_format_argument_needs_cast_pedantic
9314 : diag::warn_format_argument_needs_cast;
9315 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag) << Name << IntendedTy << IsEnum
9316 << E->getSourceRange(),
9317 Loc: E->getBeginLoc(), /*IsStringLocation=*/false,
9318 StringRange: SpecRange, FixIt: Hints);
9319 } else {
9320 // In this case, the expression could be printed using a different
9321 // specifier, but we've decided that the specifier is probably correct
9322 // and we should cast instead. Just use the normal warning message.
9323
9324 unsigned Diag =
9325 IsScopedEnum
9326 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9327 : diag::warn_format_conversion_argument_type_mismatch;
9328
9329 EmitFormatDiagnostic(
9330 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9331 << IsEnum << E->getSourceRange(),
9332 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: SpecRange, FixIt: Hints);
9333 }
9334 }
9335 } else {
9336 const CharSourceRange &CSR = getSpecifierRange(startSpecifier: StartSpecifier,
9337 specifierLen: SpecifierLen);
9338 // Since the warning for passing non-POD types to variadic functions
9339 // was deferred until now, we emit a warning for non-POD
9340 // arguments here.
9341 bool EmitTypeMismatch = false;
9342 switch (S.isValidVarArgType(Ty: ExprTy)) {
9343 case VarArgKind::Valid:
9344 case VarArgKind::ValidInCXX11: {
9345 unsigned Diag;
9346 switch (Match) {
9347 case ArgType::Match:
9348 case ArgType::MatchPromotion:
9349 case ArgType::NoMatchPromotionTypeConfusion:
9350 llvm_unreachable("expected non-matching");
9351 case ArgType::NoMatchSignedness:
9352 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9353 break;
9354 case ArgType::NoMatchPedantic:
9355 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9356 break;
9357 case ArgType::NoMatchTypeConfusion:
9358 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9359 break;
9360 case ArgType::NoMatch:
9361 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy)
9362 ? diag::err_format_conversion_argument_type_mismatch
9363 : diag::warn_format_conversion_argument_type_mismatch;
9364 break;
9365 }
9366
9367 EmitFormatDiagnostic(
9368 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9369 << IsEnum << CSR << E->getSourceRange(),
9370 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9371 break;
9372 }
9373 case VarArgKind::Undefined:
9374 case VarArgKind::MSVCUndefined:
9375 if (CallType == VariadicCallType::DoesNotApply) {
9376 EmitTypeMismatch = true;
9377 } else {
9378 EmitFormatDiagnostic(
9379 PDiag: S.PDiag(DiagID: diag::warn_non_pod_vararg_with_format_string)
9380 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9381 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9382 << E->getSourceRange(),
9383 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9384 checkForCStrMembers(AT, E);
9385 }
9386 break;
9387
9388 case VarArgKind::Invalid:
9389 if (CallType == VariadicCallType::DoesNotApply)
9390 EmitTypeMismatch = true;
9391 else if (ExprTy->isObjCObjectType())
9392 EmitFormatDiagnostic(
9393 PDiag: S.PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg_format)
9394 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9395 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9396 << E->getSourceRange(),
9397 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9398 else
9399 // FIXME: If this is an initializer list, suggest removing the braces
9400 // or inserting a cast to the target type.
9401 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg_format)
9402 << isa<InitListExpr>(Val: E) << ExprTy << CallType
9403 << AT.getRepresentativeTypeName(C&: S.Context) << E->getSourceRange();
9404 break;
9405 }
9406
9407 if (EmitTypeMismatch) {
9408 // The function is not variadic, so we do not generate warnings about
9409 // being allowed to pass that object as a variadic argument. Instead,
9410 // since there are inherently no printf specifiers for types which cannot
9411 // be passed as variadic arguments, emit a plain old specifier mismatch
9412 // argument.
9413 EmitFormatDiagnostic(
9414 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9415 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << false
9416 << E->getSourceRange(),
9417 Loc: E->getBeginLoc(), IsStringLocation: false, StringRange: CSR);
9418 }
9419
9420 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9421 "format string specifier index out of range");
9422 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9423 }
9424
9425 return true;
9426}
9427
9428//===--- CHECK: Scanf format string checking ------------------------------===//
9429
9430namespace {
9431
9432class CheckScanfHandler : public CheckFormatHandler {
9433public:
9434 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9435 const Expr *origFormatExpr, FormatStringType type,
9436 unsigned firstDataArg, unsigned numDataArgs,
9437 const char *beg, Sema::FormatArgumentPassingKind APK,
9438 ArrayRef<const Expr *> Args, unsigned formatIdx,
9439 bool inFunctionCall, VariadicCallType CallType,
9440 llvm::SmallBitVector &CheckedVarArgs,
9441 UncoveredArgHandler &UncoveredArg)
9442 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9443 numDataArgs, beg, APK, Args, formatIdx,
9444 inFunctionCall, CallType, CheckedVarArgs,
9445 UncoveredArg) {}
9446
9447 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9448 const char *startSpecifier,
9449 unsigned specifierLen) override;
9450
9451 bool HandleInvalidScanfConversionSpecifier(
9452 const analyze_scanf::ScanfSpecifier &FS,
9453 const char *startSpecifier,
9454 unsigned specifierLen) override;
9455
9456 void HandleIncompleteScanList(const char *start, const char *end) override;
9457};
9458
9459} // namespace
9460
9461void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9462 const char *end) {
9463 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_scanlist_incomplete),
9464 Loc: getLocationOfByte(x: end), /*IsStringLocation*/true,
9465 StringRange: getSpecifierRange(startSpecifier: start, specifierLen: end - start));
9466}
9467
9468bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9469 const analyze_scanf::ScanfSpecifier &FS,
9470 const char *startSpecifier,
9471 unsigned specifierLen) {
9472 const analyze_scanf::ScanfConversionSpecifier &CS =
9473 FS.getConversionSpecifier();
9474
9475 return HandleInvalidConversionSpecifier(argIndex: FS.getArgIndex(),
9476 Loc: getLocationOfByte(x: CS.getStart()),
9477 startSpec: startSpecifier, specifierLen,
9478 csStart: CS.getStart(), csLen: CS.getLength());
9479}
9480
9481bool CheckScanfHandler::HandleScanfSpecifier(
9482 const analyze_scanf::ScanfSpecifier &FS,
9483 const char *startSpecifier,
9484 unsigned specifierLen) {
9485 using namespace analyze_scanf;
9486 using namespace analyze_format_string;
9487
9488 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9489
9490 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9491 // be used to decide if we are using positional arguments consistently.
9492 if (FS.consumesDataArgument()) {
9493 if (atFirstArg) {
9494 atFirstArg = false;
9495 usesPositionalArgs = FS.usesPositionalArg();
9496 }
9497 else if (usesPositionalArgs != FS.usesPositionalArg()) {
9498 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
9499 startSpec: startSpecifier, specifierLen);
9500 return false;
9501 }
9502 }
9503
9504 // Check if the field with is non-zero.
9505 const OptionalAmount &Amt = FS.getFieldWidth();
9506 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9507 if (Amt.getConstantAmount() == 0) {
9508 const CharSourceRange &R = getSpecifierRange(startSpecifier: Amt.getStart(),
9509 specifierLen: Amt.getConstantLength());
9510 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_nonzero_width),
9511 Loc: getLocationOfByte(x: Amt.getStart()),
9512 /*IsStringLocation*/true, StringRange: R,
9513 FixIt: FixItHint::CreateRemoval(RemoveRange: R));
9514 }
9515 }
9516
9517 if (!FS.consumesDataArgument()) {
9518 // FIXME: Technically specifying a precision or field width here
9519 // makes no sense. Worth issuing a warning at some point.
9520 return true;
9521 }
9522
9523 // Consume the argument.
9524 unsigned argIndex = FS.getArgIndex();
9525 if (argIndex < NumDataArgs) {
9526 // The check to see if the argIndex is valid will come later.
9527 // We set the bit here because we may exit early from this
9528 // function if we encounter some other error.
9529 CoveredArgs.set(argIndex);
9530 }
9531
9532 // Check the length modifier is valid with the given conversion specifier.
9533 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
9534 LO: S.getLangOpts()))
9535 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9536 DiagID: diag::warn_format_nonsensical_length);
9537 else if (!FS.hasStandardLengthModifier())
9538 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9539 else if (!FS.hasStandardLengthConversionCombination())
9540 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9541 DiagID: diag::warn_format_non_standard_conversion_spec);
9542
9543 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
9544 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9545
9546 // The remaining checks depend on the data arguments.
9547 if (!HasFormatArguments())
9548 return true;
9549
9550 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9551 return false;
9552
9553 // Check that the argument type matches the format specifier.
9554 const Expr *Ex = getDataArg(i: argIndex);
9555 if (!Ex)
9556 return true;
9557
9558 const analyze_format_string::ArgType &AT = FS.getArgType(Ctx&: S.Context);
9559
9560 if (!AT.isValid()) {
9561 return true;
9562 }
9563
9564 analyze_format_string::ArgType::MatchKind Match =
9565 AT.matchesType(C&: S.Context, argTy: Ex->getType());
9566 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: Ex->getExprLoc());
9567 if (Match == analyze_format_string::ArgType::Match)
9568 return true;
9569 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9570 bool Signedness = Match == analyze_format_string::ArgType::NoMatchSignedness;
9571
9572 ScanfSpecifier fixedFS = FS;
9573 bool Success = fixedFS.fixType(QT: Ex->getType(), RawQT: Ex->IgnoreImpCasts()->getType(),
9574 LangOpt: S.getLangOpts(), Ctx&: S.Context);
9575
9576 unsigned Diag =
9577 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9578 : Signedness
9579 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9580 : diag::warn_format_conversion_argument_type_mismatch;
9581
9582 if (Success) {
9583 // Get the fix string from the fixed format specifier.
9584 SmallString<128> buf;
9585 llvm::raw_svector_ostream os(buf);
9586 fixedFS.toString(os);
9587
9588 EmitFormatDiagnostic(
9589 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context)
9590 << Ex->getType() << false << Ex->getSourceRange(),
9591 Loc: Ex->getBeginLoc(),
9592 /*IsStringLocation*/ false,
9593 StringRange: getSpecifierRange(startSpecifier, specifierLen),
9594 FixIt: FixItHint::CreateReplacement(
9595 RemoveRange: getSpecifierRange(startSpecifier, specifierLen), Code: os.str()));
9596 } else {
9597 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
9598 << AT.getRepresentativeTypeName(C&: S.Context)
9599 << Ex->getType() << false << Ex->getSourceRange(),
9600 Loc: Ex->getBeginLoc(),
9601 /*IsStringLocation*/ false,
9602 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9603 }
9604
9605 return true;
9606}
9607
9608static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9609 ArrayRef<EquatableFormatArgument> RefArgs,
9610 const StringLiteral *Fmt,
9611 ArrayRef<EquatableFormatArgument> FmtArgs,
9612 const Expr *FmtExpr, bool InFunctionCall) {
9613 bool HadError = false;
9614 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9615 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9616 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9617 // In positional-style format strings, the same specifier can appear
9618 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9619 // are sorted by getPosition(), and we process each range of equal
9620 // getPosition() values as one group.
9621 // RefArgs are taken from a string literal that was given to
9622 // attribute(format_matches), and if we got this far, we have already
9623 // verified that if it has positional specifiers that appear in multiple
9624 // locations, then they are all mutually compatible. What's left for us to
9625 // do is verify that all specifiers with the same position in FmtArgs are
9626 // compatible with the RefArgs specifiers. We check each specifier from
9627 // FmtArgs against the first member of the RefArgs group.
9628 for (; FmtIter < FmtEnd; ++FmtIter) {
9629 // Clang does not diagnose missing format specifiers in positional-style
9630 // strings (TODO: which it probably should do, as it is UB to skip over a
9631 // format argument). Skip specifiers if needed.
9632 if (FmtIter->getPosition() < RefIter->getPosition())
9633 continue;
9634
9635 // Delimits a new getPosition() value.
9636 if (FmtIter->getPosition() > RefIter->getPosition())
9637 break;
9638
9639 HadError |=
9640 !FmtIter->VerifyCompatible(S, Other: *RefIter, FmtExpr, InFunctionCall);
9641 }
9642
9643 // Jump RefIter to the start of the next group.
9644 RefIter = std::find_if(first: RefIter + 1, last: RefEnd, pred: [=](const auto &Arg) {
9645 return Arg.getPosition() != RefIter->getPosition();
9646 });
9647 }
9648
9649 if (FmtIter < FmtEnd) {
9650 CheckFormatHandler::EmitFormatDiagnostic(
9651 S, InFunctionCall, ArgumentExpr: FmtExpr,
9652 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 1,
9653 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: FmtIter->getSourceRange());
9654 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with) << 1;
9655 } else if (RefIter < RefEnd) {
9656 CheckFormatHandler::EmitFormatDiagnostic(
9657 S, InFunctionCall, ArgumentExpr: FmtExpr,
9658 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 0,
9659 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: Fmt->getSourceRange());
9660 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with)
9661 << 1 << RefIter->getSourceRange();
9662 }
9663 return !HadError;
9664}
9665
9666static void CheckFormatString(
9667 Sema &S, const FormatStringLiteral *FExpr,
9668 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9669 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
9670 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9671 bool inFunctionCall, VariadicCallType CallType,
9672 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9673 bool IgnoreStringsWithoutSpecifiers) {
9674 // CHECK: is the format string a wide literal?
9675 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9676 CheckFormatHandler::EmitFormatDiagnostic(
9677 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
9678 PDiag: S.PDiag(DiagID: diag::warn_format_string_is_wide_literal), Loc: FExpr->getBeginLoc(),
9679 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
9680 return;
9681 }
9682
9683 // Str - The format string. NOTE: this is NOT null-terminated!
9684 StringRef StrRef = FExpr->getString();
9685 const char *Str = StrRef.data();
9686 // Account for cases where the string literal is truncated in a declaration.
9687 const ConstantArrayType *T =
9688 S.Context.getAsConstantArrayType(T: FExpr->getType());
9689 assert(T && "String literal not of constant array type!");
9690 size_t TypeSize = T->getZExtSize();
9691 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
9692 const unsigned numDataArgs = Args.size() - firstDataArg;
9693
9694 if (IgnoreStringsWithoutSpecifiers &&
9695 !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9696 Begin: Str, End: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
9697 return;
9698
9699 // Emit a warning if the string literal is truncated and does not contain an
9700 // embedded null character.
9701 if (TypeSize <= StrRef.size() && !StrRef.substr(Start: 0, N: TypeSize).contains(C: '\0')) {
9702 CheckFormatHandler::EmitFormatDiagnostic(
9703 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
9704 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_not_null_terminated),
9705 Loc: FExpr->getBeginLoc(),
9706 /*IsStringLocation=*/true, StringRange: OrigFormatExpr->getSourceRange());
9707 return;
9708 }
9709
9710 // CHECK: empty format string?
9711 if (StrLen == 0 && numDataArgs > 0) {
9712 CheckFormatHandler::EmitFormatDiagnostic(
9713 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
9714 PDiag: S.PDiag(DiagID: diag::warn_empty_format_string), Loc: FExpr->getBeginLoc(),
9715 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
9716 return;
9717 }
9718
9719 if (Type == FormatStringType::Printf || Type == FormatStringType::NSString ||
9720 Type == FormatStringType::Kprintf ||
9721 Type == FormatStringType::FreeBSDKPrintf ||
9722 Type == FormatStringType::OSLog || Type == FormatStringType::OSTrace) {
9723 bool IsObjC =
9724 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
9725 if (ReferenceFormatString == nullptr) {
9726 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9727 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9728 inFunctionCall, CallType, CheckedVarArgs,
9729 UncoveredArg);
9730
9731 if (!analyze_format_string::ParsePrintfString(
9732 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
9733 isFreeBSDKPrintf: Type == FormatStringType::Kprintf ||
9734 Type == FormatStringType::FreeBSDKPrintf))
9735 H.DoneProcessing();
9736 } else {
9737 S.CheckFormatStringsCompatible(
9738 FST: Type, AuthoritativeFormatString: ReferenceFormatString, TestedFormatString: FExpr->getFormatString(),
9739 FunctionCallArg: inFunctionCall ? nullptr : Args[format_idx]);
9740 }
9741 } else if (Type == FormatStringType::Scanf) {
9742 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9743 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9744 CallType, CheckedVarArgs, UncoveredArg);
9745
9746 if (!analyze_format_string::ParseScanfString(
9747 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
9748 H.DoneProcessing();
9749 } // TODO: handle other formats
9750}
9751
9752bool Sema::CheckFormatStringsCompatible(
9753 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9754 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9755 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
9756 Type != FormatStringType::Kprintf &&
9757 Type != FormatStringType::FreeBSDKPrintf &&
9758 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
9759 return true;
9760
9761 bool IsObjC =
9762 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
9763 llvm::SmallVector<EquatableFormatArgument, 9> RefArgs, FmtArgs;
9764 FormatStringLiteral RefLit = AuthoritativeFormatString;
9765 FormatStringLiteral TestLit = TestedFormatString;
9766 const Expr *Arg;
9767 bool DiagAtStringLiteral;
9768 if (FunctionCallArg) {
9769 Arg = FunctionCallArg;
9770 DiagAtStringLiteral = false;
9771 } else {
9772 Arg = TestedFormatString;
9773 DiagAtStringLiteral = true;
9774 }
9775 if (DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit,
9776 FmtExpr: AuthoritativeFormatString, Type,
9777 IsObjC, InFunctionCall: true, Args&: RefArgs) &&
9778 DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &TestLit, FmtExpr: Arg, Type, IsObjC,
9779 InFunctionCall: DiagAtStringLiteral, Args&: FmtArgs)) {
9780 return CompareFormatSpecifiers(S&: *this, Ref: AuthoritativeFormatString, RefArgs,
9781 Fmt: TestedFormatString, FmtArgs, FmtExpr: Arg,
9782 InFunctionCall: DiagAtStringLiteral);
9783 }
9784 return false;
9785}
9786
9787bool Sema::ValidateFormatString(FormatStringType Type,
9788 const StringLiteral *Str) {
9789 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
9790 Type != FormatStringType::Kprintf &&
9791 Type != FormatStringType::FreeBSDKPrintf &&
9792 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
9793 return true;
9794
9795 FormatStringLiteral RefLit = Str;
9796 llvm::SmallVector<EquatableFormatArgument, 9> Args;
9797 bool IsObjC =
9798 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
9799 if (!DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit, FmtExpr: Str, Type, IsObjC,
9800 InFunctionCall: true, Args))
9801 return false;
9802
9803 // Group arguments by getPosition() value, and check that each member of the
9804 // group is compatible with the first member. This verifies that when
9805 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9806 // are mutually compatible. As an optimization, don't test the first member
9807 // against itself.
9808 bool HadError = false;
9809 auto Iter = Args.begin();
9810 auto End = Args.end();
9811 while (Iter != End) {
9812 const auto &FirstInGroup = *Iter;
9813 for (++Iter;
9814 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9815 ++Iter) {
9816 HadError |= !Iter->VerifyCompatible(S&: *this, Other: FirstInGroup, FmtExpr: Str, InFunctionCall: true);
9817 }
9818 }
9819 return !HadError;
9820}
9821
9822bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9823 // Str - The format string. NOTE: this is NOT null-terminated!
9824 StringRef StrRef = FExpr->getString();
9825 const char *Str = StrRef.data();
9826 // Account for cases where the string literal is truncated in a declaration.
9827 const ConstantArrayType *T = Context.getAsConstantArrayType(T: FExpr->getType());
9828 assert(T && "String literal not of constant array type!");
9829 size_t TypeSize = T->getZExtSize();
9830 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
9831 return analyze_format_string::ParseFormatStringHasSArg(beg: Str, end: Str + StrLen,
9832 LO: getLangOpts(),
9833 Target: Context.getTargetInfo());
9834}
9835
9836//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9837
9838// Returns the related absolute value function that is larger, of 0 if one
9839// does not exist.
9840static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9841 switch (AbsFunction) {
9842 default:
9843 return 0;
9844
9845 case Builtin::BI__builtin_abs:
9846 return Builtin::BI__builtin_labs;
9847 case Builtin::BI__builtin_labs:
9848 return Builtin::BI__builtin_llabs;
9849 case Builtin::BI__builtin_llabs:
9850 return 0;
9851
9852 case Builtin::BI__builtin_fabsf:
9853 return Builtin::BI__builtin_fabs;
9854 case Builtin::BI__builtin_fabs:
9855 return Builtin::BI__builtin_fabsl;
9856 case Builtin::BI__builtin_fabsl:
9857 return 0;
9858
9859 case Builtin::BI__builtin_cabsf:
9860 return Builtin::BI__builtin_cabs;
9861 case Builtin::BI__builtin_cabs:
9862 return Builtin::BI__builtin_cabsl;
9863 case Builtin::BI__builtin_cabsl:
9864 return 0;
9865
9866 case Builtin::BIabs:
9867 return Builtin::BIlabs;
9868 case Builtin::BIlabs:
9869 return Builtin::BIllabs;
9870 case Builtin::BIllabs:
9871 return 0;
9872
9873 case Builtin::BIfabsf:
9874 return Builtin::BIfabs;
9875 case Builtin::BIfabs:
9876 return Builtin::BIfabsl;
9877 case Builtin::BIfabsl:
9878 return 0;
9879
9880 case Builtin::BIcabsf:
9881 return Builtin::BIcabs;
9882 case Builtin::BIcabs:
9883 return Builtin::BIcabsl;
9884 case Builtin::BIcabsl:
9885 return 0;
9886 }
9887}
9888
9889// Returns the argument type of the absolute value function.
9890static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9891 unsigned AbsType) {
9892 if (AbsType == 0)
9893 return QualType();
9894
9895 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9896 QualType BuiltinType = Context.GetBuiltinType(ID: AbsType, Error);
9897 if (Error != ASTContext::GE_None)
9898 return QualType();
9899
9900 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9901 if (!FT)
9902 return QualType();
9903
9904 if (FT->getNumParams() != 1)
9905 return QualType();
9906
9907 return FT->getParamType(i: 0);
9908}
9909
9910// Returns the best absolute value function, or zero, based on type and
9911// current absolute value function.
9912static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9913 unsigned AbsFunctionKind) {
9914 unsigned BestKind = 0;
9915 uint64_t ArgSize = Context.getTypeSize(T: ArgType);
9916 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9917 Kind = getLargerAbsoluteValueFunction(AbsFunction: Kind)) {
9918 QualType ParamType = getAbsoluteValueArgumentType(Context, AbsType: Kind);
9919 if (Context.getTypeSize(T: ParamType) >= ArgSize) {
9920 if (BestKind == 0)
9921 BestKind = Kind;
9922 else if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
9923 BestKind = Kind;
9924 break;
9925 }
9926 }
9927 }
9928 return BestKind;
9929}
9930
9931enum AbsoluteValueKind {
9932 AVK_Integer,
9933 AVK_Floating,
9934 AVK_Complex
9935};
9936
9937static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9938 if (T->isIntegralOrEnumerationType())
9939 return AVK_Integer;
9940 if (T->isRealFloatingType())
9941 return AVK_Floating;
9942 if (T->isAnyComplexType())
9943 return AVK_Complex;
9944
9945 llvm_unreachable("Type not integer, floating, or complex");
9946}
9947
9948// Changes the absolute value function to a different type. Preserves whether
9949// the function is a builtin.
9950static unsigned changeAbsFunction(unsigned AbsKind,
9951 AbsoluteValueKind ValueKind) {
9952 switch (ValueKind) {
9953 case AVK_Integer:
9954 switch (AbsKind) {
9955 default:
9956 return 0;
9957 case Builtin::BI__builtin_fabsf:
9958 case Builtin::BI__builtin_fabs:
9959 case Builtin::BI__builtin_fabsl:
9960 case Builtin::BI__builtin_cabsf:
9961 case Builtin::BI__builtin_cabs:
9962 case Builtin::BI__builtin_cabsl:
9963 return Builtin::BI__builtin_abs;
9964 case Builtin::BIfabsf:
9965 case Builtin::BIfabs:
9966 case Builtin::BIfabsl:
9967 case Builtin::BIcabsf:
9968 case Builtin::BIcabs:
9969 case Builtin::BIcabsl:
9970 return Builtin::BIabs;
9971 }
9972 case AVK_Floating:
9973 switch (AbsKind) {
9974 default:
9975 return 0;
9976 case Builtin::BI__builtin_abs:
9977 case Builtin::BI__builtin_labs:
9978 case Builtin::BI__builtin_llabs:
9979 case Builtin::BI__builtin_cabsf:
9980 case Builtin::BI__builtin_cabs:
9981 case Builtin::BI__builtin_cabsl:
9982 return Builtin::BI__builtin_fabsf;
9983 case Builtin::BIabs:
9984 case Builtin::BIlabs:
9985 case Builtin::BIllabs:
9986 case Builtin::BIcabsf:
9987 case Builtin::BIcabs:
9988 case Builtin::BIcabsl:
9989 return Builtin::BIfabsf;
9990 }
9991 case AVK_Complex:
9992 switch (AbsKind) {
9993 default:
9994 return 0;
9995 case Builtin::BI__builtin_abs:
9996 case Builtin::BI__builtin_labs:
9997 case Builtin::BI__builtin_llabs:
9998 case Builtin::BI__builtin_fabsf:
9999 case Builtin::BI__builtin_fabs:
10000 case Builtin::BI__builtin_fabsl:
10001 return Builtin::BI__builtin_cabsf;
10002 case Builtin::BIabs:
10003 case Builtin::BIlabs:
10004 case Builtin::BIllabs:
10005 case Builtin::BIfabsf:
10006 case Builtin::BIfabs:
10007 case Builtin::BIfabsl:
10008 return Builtin::BIcabsf;
10009 }
10010 }
10011 llvm_unreachable("Unable to convert function");
10012}
10013
10014static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10015 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10016 if (!FnInfo)
10017 return 0;
10018
10019 switch (FDecl->getBuiltinID()) {
10020 default:
10021 return 0;
10022 case Builtin::BI__builtin_abs:
10023 case Builtin::BI__builtin_fabs:
10024 case Builtin::BI__builtin_fabsf:
10025 case Builtin::BI__builtin_fabsl:
10026 case Builtin::BI__builtin_labs:
10027 case Builtin::BI__builtin_llabs:
10028 case Builtin::BI__builtin_cabs:
10029 case Builtin::BI__builtin_cabsf:
10030 case Builtin::BI__builtin_cabsl:
10031 case Builtin::BIabs:
10032 case Builtin::BIlabs:
10033 case Builtin::BIllabs:
10034 case Builtin::BIfabs:
10035 case Builtin::BIfabsf:
10036 case Builtin::BIfabsl:
10037 case Builtin::BIcabs:
10038 case Builtin::BIcabsf:
10039 case Builtin::BIcabsl:
10040 return FDecl->getBuiltinID();
10041 }
10042 llvm_unreachable("Unknown Builtin type");
10043}
10044
10045// If the replacement is valid, emit a note with replacement function.
10046// Additionally, suggest including the proper header if not already included.
10047static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10048 unsigned AbsKind, QualType ArgType) {
10049 bool EmitHeaderHint = true;
10050 const char *HeaderName = nullptr;
10051 std::string FunctionName;
10052 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10053 FunctionName = "std::abs";
10054 if (ArgType->isIntegralOrEnumerationType()) {
10055 HeaderName = "cstdlib";
10056 } else if (ArgType->isRealFloatingType()) {
10057 HeaderName = "cmath";
10058 } else {
10059 llvm_unreachable("Invalid Type");
10060 }
10061
10062 // Lookup all std::abs
10063 if (NamespaceDecl *Std = S.getStdNamespace()) {
10064 LookupResult R(S, &S.Context.Idents.get(Name: "abs"), Loc, Sema::LookupAnyName);
10065 R.suppressDiagnostics();
10066 S.LookupQualifiedName(R, LookupCtx: Std);
10067
10068 for (const auto *I : R) {
10069 const FunctionDecl *FDecl = nullptr;
10070 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(Val: I)) {
10071 FDecl = dyn_cast<FunctionDecl>(Val: UsingD->getTargetDecl());
10072 } else {
10073 FDecl = dyn_cast<FunctionDecl>(Val: I);
10074 }
10075 if (!FDecl)
10076 continue;
10077
10078 // Found std::abs(), check that they are the right ones.
10079 if (FDecl->getNumParams() != 1)
10080 continue;
10081
10082 // Check that the parameter type can handle the argument.
10083 QualType ParamType = FDecl->getParamDecl(i: 0)->getType();
10084 if (getAbsoluteValueKind(T: ArgType) == getAbsoluteValueKind(T: ParamType) &&
10085 S.Context.getTypeSize(T: ArgType) <=
10086 S.Context.getTypeSize(T: ParamType)) {
10087 // Found a function, don't need the header hint.
10088 EmitHeaderHint = false;
10089 break;
10090 }
10091 }
10092 }
10093 } else {
10094 FunctionName = S.Context.BuiltinInfo.getName(ID: AbsKind);
10095 HeaderName = S.Context.BuiltinInfo.getHeaderName(ID: AbsKind);
10096
10097 if (HeaderName) {
10098 DeclarationName DN(&S.Context.Idents.get(Name: FunctionName));
10099 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10100 R.suppressDiagnostics();
10101 S.LookupName(R, S: S.getCurScope());
10102
10103 if (R.isSingleResult()) {
10104 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
10105 if (FD && FD->getBuiltinID() == AbsKind) {
10106 EmitHeaderHint = false;
10107 } else {
10108 return;
10109 }
10110 } else if (!R.empty()) {
10111 return;
10112 }
10113 }
10114 }
10115
10116 S.Diag(Loc, DiagID: diag::note_replace_abs_function)
10117 << FunctionName << FixItHint::CreateReplacement(RemoveRange: Range, Code: FunctionName);
10118
10119 if (!HeaderName)
10120 return;
10121
10122 if (!EmitHeaderHint)
10123 return;
10124
10125 S.Diag(Loc, DiagID: diag::note_include_header_or_declare) << HeaderName
10126 << FunctionName;
10127}
10128
10129template <std::size_t StrLen>
10130static bool IsStdFunction(const FunctionDecl *FDecl,
10131 const char (&Str)[StrLen]) {
10132 if (!FDecl)
10133 return false;
10134 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10135 return false;
10136 if (!FDecl->isInStdNamespace())
10137 return false;
10138
10139 return true;
10140}
10141
10142enum class MathCheck { NaN, Inf };
10143static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10144 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10145 return llvm::is_contained(Set: names, Element: calleeName);
10146 };
10147
10148 switch (Check) {
10149 case MathCheck::NaN:
10150 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10151 "__builtin_nanf16", "__builtin_nanf128"});
10152 case MathCheck::Inf:
10153 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10154 "__builtin_inff16", "__builtin_inff128"});
10155 }
10156 llvm_unreachable("unknown MathCheck");
10157}
10158
10159static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10160 if (FDecl->getName() != "infinity")
10161 return false;
10162
10163 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(Val: FDecl)) {
10164 const CXXRecordDecl *RDecl = MDecl->getParent();
10165 if (RDecl->getName() != "numeric_limits")
10166 return false;
10167
10168 if (const NamespaceDecl *NSDecl =
10169 dyn_cast<NamespaceDecl>(Val: RDecl->getDeclContext()))
10170 return NSDecl->isStdNamespace();
10171 }
10172
10173 return false;
10174}
10175
10176void Sema::CheckInfNaNFunction(const CallExpr *Call,
10177 const FunctionDecl *FDecl) {
10178 if (!FDecl->getIdentifier())
10179 return;
10180
10181 FPOptions FPO = Call->getFPFeaturesInEffect(LO: getLangOpts());
10182 if (FPO.getNoHonorNaNs() &&
10183 (IsStdFunction(FDecl, Str: "isnan") || IsStdFunction(FDecl, Str: "isunordered") ||
10184 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::NaN))) {
10185 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10186 << 1 << 0 << Call->getSourceRange();
10187 return;
10188 }
10189
10190 if (FPO.getNoHonorInfs() &&
10191 (IsStdFunction(FDecl, Str: "isinf") || IsStdFunction(FDecl, Str: "isfinite") ||
10192 IsInfinityFunction(FDecl) ||
10193 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::Inf))) {
10194 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10195 << 0 << 0 << Call->getSourceRange();
10196 }
10197}
10198
10199void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10200 const FunctionDecl *FDecl) {
10201 if (Call->getNumArgs() != 1)
10202 return;
10203
10204 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10205 bool IsStdAbs = IsStdFunction(FDecl, Str: "abs");
10206 if (AbsKind == 0 && !IsStdAbs)
10207 return;
10208
10209 QualType ArgType = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
10210 QualType ParamType = Call->getArg(Arg: 0)->getType();
10211
10212 // Unsigned types cannot be negative. Suggest removing the absolute value
10213 // function call.
10214 if (ArgType->isUnsignedIntegerType()) {
10215 std::string FunctionName =
10216 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(ID: AbsKind);
10217 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_unsigned_abs) << ArgType << ParamType;
10218 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_abs)
10219 << FunctionName
10220 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange());
10221 return;
10222 }
10223
10224 // Taking the absolute value of a pointer is very suspicious, they probably
10225 // wanted to index into an array, dereference a pointer, call a function, etc.
10226 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10227 unsigned DiagType = 0;
10228 if (ArgType->isFunctionType())
10229 DiagType = 1;
10230 else if (ArgType->isArrayType())
10231 DiagType = 2;
10232
10233 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_pointer_abs) << DiagType << ArgType;
10234 return;
10235 }
10236
10237 // std::abs has overloads which prevent most of the absolute value problems
10238 // from occurring.
10239 if (IsStdAbs)
10240 return;
10241
10242 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(T: ArgType);
10243 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(T: ParamType);
10244
10245 // The argument and parameter are the same kind. Check if they are the right
10246 // size.
10247 if (ArgValueKind == ParamValueKind) {
10248 if (Context.getTypeSize(T: ArgType) <= Context.getTypeSize(T: ParamType))
10249 return;
10250
10251 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: AbsKind);
10252 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_abs_too_small)
10253 << FDecl << ArgType << ParamType;
10254
10255 if (NewAbsKind == 0)
10256 return;
10257
10258 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10259 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10260 return;
10261 }
10262
10263 // ArgValueKind != ParamValueKind
10264 // The wrong type of absolute value function was used. Attempt to find the
10265 // proper one.
10266 unsigned NewAbsKind = changeAbsFunction(AbsKind, ValueKind: ArgValueKind);
10267 NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: NewAbsKind);
10268 if (NewAbsKind == 0)
10269 return;
10270
10271 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_wrong_absolute_value_type)
10272 << FDecl << ParamValueKind << ArgValueKind;
10273
10274 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10275 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10276}
10277
10278//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10279void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10280 const FunctionDecl *FDecl) {
10281 if (!Call || !FDecl) return;
10282
10283 // Ignore template specializations and macros.
10284 if (inTemplateInstantiation()) return;
10285 if (Call->getExprLoc().isMacroID()) return;
10286
10287 // Only care about the one template argument, two function parameter std::max
10288 if (Call->getNumArgs() != 2) return;
10289 if (!IsStdFunction(FDecl, Str: "max")) return;
10290 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10291 if (!ArgList) return;
10292 if (ArgList->size() != 1) return;
10293
10294 // Check that template type argument is unsigned integer.
10295 const auto& TA = ArgList->get(Idx: 0);
10296 if (TA.getKind() != TemplateArgument::Type) return;
10297 QualType ArgType = TA.getAsType();
10298 if (!ArgType->isUnsignedIntegerType()) return;
10299
10300 // See if either argument is a literal zero.
10301 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10302 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E);
10303 if (!MTE) return false;
10304 const auto *Num = dyn_cast<IntegerLiteral>(Val: MTE->getSubExpr());
10305 if (!Num) return false;
10306 if (Num->getValue() != 0) return false;
10307 return true;
10308 };
10309
10310 const Expr *FirstArg = Call->getArg(Arg: 0);
10311 const Expr *SecondArg = Call->getArg(Arg: 1);
10312 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10313 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10314
10315 // Only warn when exactly one argument is zero.
10316 if (IsFirstArgZero == IsSecondArgZero) return;
10317
10318 SourceRange FirstRange = FirstArg->getSourceRange();
10319 SourceRange SecondRange = SecondArg->getSourceRange();
10320
10321 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10322
10323 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_max_unsigned_zero)
10324 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10325
10326 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10327 SourceRange RemovalRange;
10328 if (IsFirstArgZero) {
10329 RemovalRange = SourceRange(FirstRange.getBegin(),
10330 SecondRange.getBegin().getLocWithOffset(Offset: -1));
10331 } else {
10332 RemovalRange = SourceRange(getLocForEndOfToken(Loc: FirstRange.getEnd()),
10333 SecondRange.getEnd());
10334 }
10335
10336 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_max_call)
10337 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange())
10338 << FixItHint::CreateRemoval(RemoveRange: RemovalRange);
10339}
10340
10341//===--- CHECK: Standard memory functions ---------------------------------===//
10342
10343/// Takes the expression passed to the size_t parameter of functions
10344/// such as memcmp, strncat, etc and warns if it's a comparison.
10345///
10346/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10347static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10348 const IdentifierInfo *FnName,
10349 SourceLocation FnLoc,
10350 SourceLocation RParenLoc) {
10351 const auto *Size = dyn_cast<BinaryOperator>(Val: E);
10352 if (!Size)
10353 return false;
10354
10355 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10356 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10357 return false;
10358
10359 SourceRange SizeRange = Size->getSourceRange();
10360 S.Diag(Loc: Size->getOperatorLoc(), DiagID: diag::warn_memsize_comparison)
10361 << SizeRange << FnName;
10362 S.Diag(Loc: FnLoc, DiagID: diag::note_memsize_comparison_paren)
10363 << FnName
10364 << FixItHint::CreateInsertion(
10365 InsertionLoc: S.getLocForEndOfToken(Loc: Size->getLHS()->getEndLoc()), Code: ")")
10366 << FixItHint::CreateRemoval(RemoveRange: RParenLoc);
10367 S.Diag(Loc: SizeRange.getBegin(), DiagID: diag::note_memsize_comparison_cast_silence)
10368 << FixItHint::CreateInsertion(InsertionLoc: SizeRange.getBegin(), Code: "(size_t)(")
10369 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: SizeRange.getEnd()),
10370 Code: ")");
10371
10372 return true;
10373}
10374
10375/// Determine whether the given type is or contains a dynamic class type
10376/// (e.g., whether it has a vtable).
10377static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10378 bool &IsContained) {
10379 // Look through array types while ignoring qualifiers.
10380 const Type *Ty = T->getBaseElementTypeUnsafe();
10381 IsContained = false;
10382
10383 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10384 RD = RD ? RD->getDefinition() : nullptr;
10385 if (!RD || RD->isInvalidDecl())
10386 return nullptr;
10387
10388 if (RD->isDynamicClass())
10389 return RD;
10390
10391 // Check all the fields. If any bases were dynamic, the class is dynamic.
10392 // It's impossible for a class to transitively contain itself by value, so
10393 // infinite recursion is impossible.
10394 for (auto *FD : RD->fields()) {
10395 bool SubContained;
10396 if (const CXXRecordDecl *ContainedRD =
10397 getContainedDynamicClass(T: FD->getType(), IsContained&: SubContained)) {
10398 IsContained = true;
10399 return ContainedRD;
10400 }
10401 }
10402
10403 return nullptr;
10404}
10405
10406static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10407 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: E))
10408 if (Unary->getKind() == UETT_SizeOf)
10409 return Unary;
10410 return nullptr;
10411}
10412
10413/// If E is a sizeof expression, returns its argument expression,
10414/// otherwise returns NULL.
10415static const Expr *getSizeOfExprArg(const Expr *E) {
10416 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10417 if (!SizeOf->isArgumentType())
10418 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10419 return nullptr;
10420}
10421
10422/// If E is a sizeof expression, returns its argument type.
10423static QualType getSizeOfArgType(const Expr *E) {
10424 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10425 return SizeOf->getTypeOfArgument();
10426 return QualType();
10427}
10428
10429namespace {
10430
10431struct SearchNonTrivialToInitializeField
10432 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10433 using Super =
10434 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10435
10436 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10437
10438 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10439 SourceLocation SL) {
10440 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
10441 asDerived().visitArray(PDIK, AT, SL);
10442 return;
10443 }
10444
10445 Super::visitWithKind(PDIK, FT, Args&: SL);
10446 }
10447
10448 void visitARCStrong(QualType FT, SourceLocation SL) {
10449 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
10450 }
10451 void visitARCWeak(QualType FT, SourceLocation SL) {
10452 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
10453 }
10454 void visitStruct(QualType FT, SourceLocation SL) {
10455 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10456 visit(FT: FD->getType(), Args: FD->getLocation());
10457 }
10458 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10459 const ArrayType *AT, SourceLocation SL) {
10460 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
10461 }
10462 void visitTrivial(QualType FT, SourceLocation SL) {}
10463
10464 static void diag(QualType RT, const Expr *E, Sema &S) {
10465 SearchNonTrivialToInitializeField(E, S).visitStruct(FT: RT, SL: SourceLocation());
10466 }
10467
10468 ASTContext &getContext() { return S.getASTContext(); }
10469
10470 const Expr *E;
10471 Sema &S;
10472};
10473
10474struct SearchNonTrivialToCopyField
10475 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10476 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10477
10478 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10479
10480 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10481 SourceLocation SL) {
10482 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
10483 asDerived().visitArray(PCK, AT, SL);
10484 return;
10485 }
10486
10487 Super::visitWithKind(PCK, FT, Args&: SL);
10488 }
10489
10490 void visitARCStrong(QualType FT, SourceLocation SL) {
10491 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10492 }
10493 void visitARCWeak(QualType FT, SourceLocation SL) {
10494 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10495 }
10496 void visitPtrAuth(QualType FT, SourceLocation SL) {
10497 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10498 }
10499 void visitStruct(QualType FT, SourceLocation SL) {
10500 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10501 visit(FT: FD->getType(), Args: FD->getLocation());
10502 }
10503 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10504 SourceLocation SL) {
10505 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
10506 }
10507 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10508 SourceLocation SL) {}
10509 void visitTrivial(QualType FT, SourceLocation SL) {}
10510 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10511
10512 static void diag(QualType RT, const Expr *E, Sema &S) {
10513 SearchNonTrivialToCopyField(E, S).visitStruct(FT: RT, SL: SourceLocation());
10514 }
10515
10516 ASTContext &getContext() { return S.getASTContext(); }
10517
10518 const Expr *E;
10519 Sema &S;
10520};
10521
10522}
10523
10524/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10525static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10526 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10527
10528 if (const auto *BO = dyn_cast<BinaryOperator>(Val: SizeofExpr)) {
10529 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10530 return false;
10531
10532 return doesExprLikelyComputeSize(SizeofExpr: BO->getLHS()) ||
10533 doesExprLikelyComputeSize(SizeofExpr: BO->getRHS());
10534 }
10535
10536 return getAsSizeOfExpr(E: SizeofExpr) != nullptr;
10537}
10538
10539/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10540///
10541/// \code
10542/// #define MACRO 0
10543/// foo(MACRO);
10544/// foo(0);
10545/// \endcode
10546///
10547/// This should return true for the first call to foo, but not for the second
10548/// (regardless of whether foo is a macro or function).
10549static bool isArgumentExpandedFromMacro(SourceManager &SM,
10550 SourceLocation CallLoc,
10551 SourceLocation ArgLoc) {
10552 if (!CallLoc.isMacroID())
10553 return SM.getFileID(SpellingLoc: CallLoc) != SM.getFileID(SpellingLoc: ArgLoc);
10554
10555 return SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: CallLoc)) !=
10556 SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: ArgLoc));
10557}
10558
10559/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10560/// last two arguments transposed.
10561static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10562 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10563 return;
10564
10565 const Expr *SizeArg =
10566 Call->getArg(Arg: BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10567
10568 auto isLiteralZero = [](const Expr *E) {
10569 return (isa<IntegerLiteral>(Val: E) &&
10570 cast<IntegerLiteral>(Val: E)->getValue() == 0) ||
10571 (isa<CharacterLiteral>(Val: E) &&
10572 cast<CharacterLiteral>(Val: E)->getValue() == 0);
10573 };
10574
10575 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10576 SourceLocation CallLoc = Call->getRParenLoc();
10577 SourceManager &SM = S.getSourceManager();
10578 if (isLiteralZero(SizeArg) &&
10579 !isArgumentExpandedFromMacro(SM, CallLoc, ArgLoc: SizeArg->getExprLoc())) {
10580
10581 SourceLocation DiagLoc = SizeArg->getExprLoc();
10582
10583 // Some platforms #define bzero to __builtin_memset. See if this is the
10584 // case, and if so, emit a better diagnostic.
10585 if (BId == Builtin::BIbzero ||
10586 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10587 Loc: CallLoc, SM, LangOpts: S.getLangOpts()) == "bzero")) {
10588 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_bzero_size);
10589 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_bzero_size_silence);
10590 } else if (!isLiteralZero(Call->getArg(Arg: 1)->IgnoreImpCasts())) {
10591 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 0;
10592 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 0;
10593 }
10594 return;
10595 }
10596
10597 // If the second argument to a memset is a sizeof expression and the third
10598 // isn't, this is also likely an error. This should catch
10599 // 'memset(buf, sizeof(buf), 0xff)'.
10600 if (BId == Builtin::BImemset &&
10601 doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 1)) &&
10602 !doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 2))) {
10603 SourceLocation DiagLoc = Call->getArg(Arg: 1)->getExprLoc();
10604 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 1;
10605 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 1;
10606 return;
10607 }
10608}
10609
10610void Sema::CheckMemaccessArguments(const CallExpr *Call,
10611 unsigned BId,
10612 IdentifierInfo *FnName) {
10613 assert(BId != 0);
10614
10615 // It is possible to have a non-standard definition of memset. Validate
10616 // we have enough arguments, and if not, abort further checking.
10617 unsigned ExpectedNumArgs =
10618 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10619 if (Call->getNumArgs() < ExpectedNumArgs)
10620 return;
10621
10622 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10623 BId == Builtin::BIstrndup ? 1 : 2);
10624 unsigned LenArg =
10625 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10626 const Expr *LenExpr = Call->getArg(Arg: LenArg)->IgnoreParenImpCasts();
10627
10628 if (CheckMemorySizeofForComparison(S&: *this, E: LenExpr, FnName,
10629 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
10630 return;
10631
10632 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10633 CheckMemaccessSize(S&: *this, BId, Call);
10634
10635 // We have special checking when the length is a sizeof expression.
10636 QualType SizeOfArgTy = getSizeOfArgType(E: LenExpr);
10637
10638 // Although widely used, 'bzero' is not a standard function. Be more strict
10639 // with the argument types before allowing diagnostics and only allow the
10640 // form bzero(ptr, sizeof(...)).
10641 QualType FirstArgTy = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
10642 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10643 return;
10644
10645 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10646 const Expr *Dest = Call->getArg(Arg: ArgIdx)->IgnoreParenImpCasts();
10647 SourceRange ArgRange = Call->getArg(Arg: ArgIdx)->getSourceRange();
10648
10649 QualType DestTy = Dest->getType();
10650 QualType PointeeTy;
10651 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10652 PointeeTy = DestPtrTy->getPointeeType();
10653
10654 // Never warn about void type pointers. This can be used to suppress
10655 // false positives.
10656 if (PointeeTy->isVoidType())
10657 continue;
10658
10659 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10660 // actually comparing the expressions for equality. Because computing the
10661 // expression IDs can be expensive, we only do this if the diagnostic is
10662 // enabled.
10663 if (CheckSizeofMemaccessArgument(SizeOfArg: LenExpr, Dest, FnName))
10664 break;
10665
10666 // Also check for cases where the sizeof argument is the exact same
10667 // type as the memory argument, and where it points to a user-defined
10668 // record type.
10669 if (SizeOfArgTy != QualType()) {
10670 if (PointeeTy->isRecordType() &&
10671 Context.typesAreCompatible(T1: SizeOfArgTy, T2: DestTy)) {
10672 DiagRuntimeBehavior(Loc: LenExpr->getExprLoc(), Statement: Dest,
10673 PD: PDiag(DiagID: diag::warn_sizeof_pointer_type_memaccess)
10674 << FnName << SizeOfArgTy << ArgIdx
10675 << PointeeTy << Dest->getSourceRange()
10676 << LenExpr->getSourceRange());
10677 break;
10678 }
10679 }
10680 } else if (DestTy->isArrayType()) {
10681 PointeeTy = DestTy;
10682 }
10683
10684 if (PointeeTy == QualType())
10685 continue;
10686
10687 // Always complain about dynamic classes.
10688 bool IsContained;
10689 if (const CXXRecordDecl *ContainedRD =
10690 getContainedDynamicClass(T: PointeeTy, IsContained)) {
10691
10692 unsigned OperationType = 0;
10693 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10694 // "overwritten" if we're warning about the destination for any call
10695 // but memcmp; otherwise a verb appropriate to the call.
10696 if (ArgIdx != 0 || IsCmp) {
10697 if (BId == Builtin::BImemcpy)
10698 OperationType = 1;
10699 else if(BId == Builtin::BImemmove)
10700 OperationType = 2;
10701 else if (IsCmp)
10702 OperationType = 3;
10703 }
10704
10705 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10706 PD: PDiag(DiagID: diag::warn_dyn_class_memaccess)
10707 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10708 << IsContained << ContainedRD << OperationType
10709 << Call->getCallee()->getSourceRange());
10710 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10711 BId != Builtin::BImemset)
10712 DiagRuntimeBehavior(
10713 Loc: Dest->getExprLoc(), Statement: Dest,
10714 PD: PDiag(DiagID: diag::warn_arc_object_memaccess)
10715 << ArgIdx << FnName << PointeeTy
10716 << Call->getCallee()->getSourceRange());
10717 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10718
10719 // FIXME: Do not consider incomplete types even though they may be
10720 // completed later. GCC does not diagnose such code, but we may want to
10721 // consider diagnosing it in the future, perhaps under a different, but
10722 // related, diagnostic group.
10723 bool NonTriviallyCopyableCXXRecord =
10724 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10725 !PointeeTy.isTriviallyCopyableType(Context);
10726
10727 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10728 RD->isNonTrivialToPrimitiveDefaultInitialize()) {
10729 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10730 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
10731 << ArgIdx << FnName << PointeeTy << 0);
10732 SearchNonTrivialToInitializeField::diag(RT: PointeeTy, E: Dest, S&: *this);
10733 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10734 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10735 // FIXME: Limiting this warning to dest argument until we decide
10736 // whether it's valid for source argument too.
10737 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10738 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
10739 << FnName << PointeeTy);
10740 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10741 RD->isNonTrivialToPrimitiveCopy()) {
10742 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10743 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
10744 << ArgIdx << FnName << PointeeTy << 1);
10745 SearchNonTrivialToCopyField::diag(RT: PointeeTy, E: Dest, S&: *this);
10746 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10747 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10748 // FIXME: Limiting this warning to dest argument until we decide
10749 // whether it's valid for source argument too.
10750 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10751 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
10752 << FnName << PointeeTy);
10753 } else {
10754 continue;
10755 }
10756 } else
10757 continue;
10758
10759 DiagRuntimeBehavior(
10760 Loc: Dest->getExprLoc(), Statement: Dest,
10761 PD: PDiag(DiagID: diag::note_bad_memaccess_silence)
10762 << FixItHint::CreateInsertion(InsertionLoc: ArgRange.getBegin(), Code: "(void*)"));
10763 break;
10764 }
10765}
10766
10767bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
10768 IdentifierInfo *FnName) {
10769 llvm::FoldingSetNodeID SizeOfArgID;
10770 const Expr *SizeOfArg = getSizeOfExprArg(E: LenExpr);
10771 if (!SizeOfArg)
10772 return false;
10773 // Computing this warning is expensive, so we only do so if the warning is
10774 // enabled.
10775 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess,
10776 Loc: SizeOfArg->getExprLoc()))
10777 return false;
10778 QualType DestTy = Dest->getType();
10779 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
10780 if (!DestPtrTy)
10781 return false;
10782
10783 QualType PointeeTy = DestPtrTy->getPointeeType();
10784
10785 if (SizeOfArgID == llvm::FoldingSetNodeID())
10786 SizeOfArg->Profile(ID&: SizeOfArgID, Context, Canonical: true);
10787
10788 llvm::FoldingSetNodeID DestID;
10789 Dest->Profile(ID&: DestID, Context, Canonical: true);
10790 if (DestID == SizeOfArgID) {
10791 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10792 // over sizeof(src) as well.
10793 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10794 StringRef ReadableName = FnName->getName();
10795
10796 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Val: Dest);
10797 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
10798 ActionIdx = 1; // If its an address-of operator, just remove it.
10799 if (!PointeeTy->isIncompleteType() &&
10800 (Context.getTypeSize(T: PointeeTy) == Context.getCharWidth()))
10801 ActionIdx = 2; // If the pointee's size is sizeof(char),
10802 // suggest an explicit length.
10803
10804 // If the function is defined as a builtin macro, do not show macro
10805 // expansion.
10806 SourceLocation SL = SizeOfArg->getExprLoc();
10807 SourceRange DSR = Dest->getSourceRange();
10808 SourceRange SSR = SizeOfArg->getSourceRange();
10809 SourceManager &SM = getSourceManager();
10810
10811 if (SM.isMacroArgExpansion(Loc: SL)) {
10812 ReadableName = Lexer::getImmediateMacroName(Loc: SL, SM, LangOpts);
10813 SL = SM.getSpellingLoc(Loc: SL);
10814 DSR = SourceRange(SM.getSpellingLoc(Loc: DSR.getBegin()),
10815 SM.getSpellingLoc(Loc: DSR.getEnd()));
10816 SSR = SourceRange(SM.getSpellingLoc(Loc: SSR.getBegin()),
10817 SM.getSpellingLoc(Loc: SSR.getEnd()));
10818 }
10819
10820 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
10821 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess)
10822 << ReadableName << PointeeTy << DestTy << DSR
10823 << SSR);
10824 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
10825 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess_note)
10826 << ActionIdx << SSR);
10827 return true;
10828 }
10829 return false;
10830}
10831
10832// A little helper routine: ignore addition and subtraction of integer literals.
10833// This intentionally does not ignore all integer constant expressions because
10834// we don't want to remove sizeof().
10835static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10836 Ex = Ex->IgnoreParenCasts();
10837
10838 while (true) {
10839 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Val: Ex);
10840 if (!BO || !BO->isAdditiveOp())
10841 break;
10842
10843 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10844 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10845
10846 if (isa<IntegerLiteral>(Val: RHS))
10847 Ex = LHS;
10848 else if (isa<IntegerLiteral>(Val: LHS))
10849 Ex = RHS;
10850 else
10851 break;
10852 }
10853
10854 return Ex;
10855}
10856
10857static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10858 ASTContext &Context) {
10859 // Only handle constant-sized or VLAs, but not flexible members.
10860 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T: Ty)) {
10861 // Only issue the FIXIT for arrays of size > 1.
10862 if (CAT->getZExtSize() <= 1)
10863 return false;
10864 } else if (!Ty->isVariableArrayType()) {
10865 return false;
10866 }
10867 return true;
10868}
10869
10870void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10871 IdentifierInfo *FnName) {
10872
10873 // Don't crash if the user has the wrong number of arguments
10874 unsigned NumArgs = Call->getNumArgs();
10875 if ((NumArgs != 3) && (NumArgs != 4))
10876 return;
10877
10878 const Expr *SrcArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 1), Ctx&: Context);
10879 const Expr *SizeArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 2), Ctx&: Context);
10880 const Expr *CompareWithSrc = nullptr;
10881
10882 if (CheckMemorySizeofForComparison(S&: *this, E: SizeArg, FnName,
10883 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
10884 return;
10885
10886 // Look for 'strlcpy(dst, x, sizeof(x))'
10887 if (const Expr *Ex = getSizeOfExprArg(E: SizeArg))
10888 CompareWithSrc = Ex;
10889 else {
10890 // Look for 'strlcpy(dst, x, strlen(x))'
10891 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(Val: SizeArg)) {
10892 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10893 SizeCall->getNumArgs() == 1)
10894 CompareWithSrc = ignoreLiteralAdditions(Ex: SizeCall->getArg(Arg: 0), Ctx&: Context);
10895 }
10896 }
10897
10898 if (!CompareWithSrc)
10899 return;
10900
10901 // Determine if the argument to sizeof/strlen is equal to the source
10902 // argument. In principle there's all kinds of things you could do
10903 // here, for instance creating an == expression and evaluating it with
10904 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10905 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(Val: SrcArg);
10906 if (!SrcArgDRE)
10907 return;
10908
10909 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(Val: CompareWithSrc);
10910 if (!CompareWithSrcDRE ||
10911 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10912 return;
10913
10914 const Expr *OriginalSizeArg = Call->getArg(Arg: 2);
10915 Diag(Loc: CompareWithSrcDRE->getBeginLoc(), DiagID: diag::warn_strlcpycat_wrong_size)
10916 << OriginalSizeArg->getSourceRange() << FnName;
10917
10918 // Output a FIXIT hint if the destination is an array (rather than a
10919 // pointer to an array). This could be enhanced to handle some
10920 // pointers if we know the actual size, like if DstArg is 'array+2'
10921 // we could say 'sizeof(array)-2'.
10922 const Expr *DstArg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
10923 if (!isConstantSizeArrayWithMoreThanOneElement(Ty: DstArg->getType(), Context))
10924 return;
10925
10926 SmallString<128> sizeString;
10927 llvm::raw_svector_ostream OS(sizeString);
10928 OS << "sizeof(";
10929 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
10930 OS << ")";
10931
10932 Diag(Loc: OriginalSizeArg->getBeginLoc(), DiagID: diag::note_strlcpycat_wrong_size)
10933 << FixItHint::CreateReplacement(RemoveRange: OriginalSizeArg->getSourceRange(),
10934 Code: OS.str());
10935}
10936
10937/// Check if two expressions refer to the same declaration.
10938static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10939 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(Val: E1))
10940 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(Val: E2))
10941 return D1->getDecl() == D2->getDecl();
10942 return false;
10943}
10944
10945static const Expr *getStrlenExprArg(const Expr *E) {
10946 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
10947 const FunctionDecl *FD = CE->getDirectCallee();
10948 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10949 return nullptr;
10950 return CE->getArg(Arg: 0)->IgnoreParenCasts();
10951 }
10952 return nullptr;
10953}
10954
10955void Sema::CheckStrncatArguments(const CallExpr *CE,
10956 const IdentifierInfo *FnName) {
10957 // Don't crash if the user has the wrong number of arguments.
10958 if (CE->getNumArgs() < 3)
10959 return;
10960 const Expr *DstArg = CE->getArg(Arg: 0)->IgnoreParenCasts();
10961 const Expr *SrcArg = CE->getArg(Arg: 1)->IgnoreParenCasts();
10962 const Expr *LenArg = CE->getArg(Arg: 2)->IgnoreParenCasts();
10963
10964 if (CheckMemorySizeofForComparison(S&: *this, E: LenArg, FnName, FnLoc: CE->getBeginLoc(),
10965 RParenLoc: CE->getRParenLoc()))
10966 return;
10967
10968 // Identify common expressions, which are wrongly used as the size argument
10969 // to strncat and may lead to buffer overflows.
10970 unsigned PatternType = 0;
10971 if (const Expr *SizeOfArg = getSizeOfExprArg(E: LenArg)) {
10972 // - sizeof(dst)
10973 if (referToTheSameDecl(E1: SizeOfArg, E2: DstArg))
10974 PatternType = 1;
10975 // - sizeof(src)
10976 else if (referToTheSameDecl(E1: SizeOfArg, E2: SrcArg))
10977 PatternType = 2;
10978 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Val: LenArg)) {
10979 if (BE->getOpcode() == BO_Sub) {
10980 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10981 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10982 // - sizeof(dst) - strlen(dst)
10983 if (referToTheSameDecl(E1: DstArg, E2: getSizeOfExprArg(E: L)) &&
10984 referToTheSameDecl(E1: DstArg, E2: getStrlenExprArg(E: R)))
10985 PatternType = 1;
10986 // - sizeof(src) - (anything)
10987 else if (referToTheSameDecl(E1: SrcArg, E2: getSizeOfExprArg(E: L)))
10988 PatternType = 2;
10989 }
10990 }
10991
10992 if (PatternType == 0)
10993 return;
10994
10995 // Generate the diagnostic.
10996 SourceLocation SL = LenArg->getBeginLoc();
10997 SourceRange SR = LenArg->getSourceRange();
10998 SourceManager &SM = getSourceManager();
10999
11000 // If the function is defined as a builtin macro, do not show macro expansion.
11001 if (SM.isMacroArgExpansion(Loc: SL)) {
11002 SL = SM.getSpellingLoc(Loc: SL);
11003 SR = SourceRange(SM.getSpellingLoc(Loc: SR.getBegin()),
11004 SM.getSpellingLoc(Loc: SR.getEnd()));
11005 }
11006
11007 // Check if the destination is an array (rather than a pointer to an array).
11008 QualType DstTy = DstArg->getType();
11009 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(Ty: DstTy,
11010 Context);
11011 if (!isKnownSizeArray) {
11012 if (PatternType == 1)
11013 Diag(Loc: SL, DiagID: diag::warn_strncat_wrong_size) << SR;
11014 else
11015 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11016 return;
11017 }
11018
11019 if (PatternType == 1)
11020 Diag(Loc: SL, DiagID: diag::warn_strncat_large_size) << SR;
11021 else
11022 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11023
11024 SmallString<128> sizeString;
11025 llvm::raw_svector_ostream OS(sizeString);
11026 OS << "sizeof(";
11027 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11028 OS << ") - ";
11029 OS << "strlen(";
11030 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11031 OS << ") - 1";
11032
11033 Diag(Loc: SL, DiagID: diag::note_strncat_wrong_size)
11034 << FixItHint::CreateReplacement(RemoveRange: SR, Code: OS.str());
11035}
11036
11037namespace {
11038void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11039 const UnaryOperator *UnaryExpr, const Decl *D) {
11040 if (isa<FieldDecl, FunctionDecl, VarDecl>(Val: D)) {
11041 S.Diag(Loc: UnaryExpr->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11042 << CalleeName << 0 /*object: */ << cast<NamedDecl>(Val: D);
11043 return;
11044 }
11045}
11046
11047void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11048 const UnaryOperator *UnaryExpr) {
11049 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: UnaryExpr->getSubExpr())) {
11050 const Decl *D = Lvalue->getDecl();
11051 if (const auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
11052 if (!DD->getType()->isReferenceType())
11053 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11054 }
11055 }
11056
11057 if (const auto *Lvalue = dyn_cast<MemberExpr>(Val: UnaryExpr->getSubExpr()))
11058 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11059 D: Lvalue->getMemberDecl());
11060}
11061
11062void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11063 const UnaryOperator *UnaryExpr) {
11064 const auto *Lambda = dyn_cast<LambdaExpr>(
11065 Val: UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11066 if (!Lambda)
11067 return;
11068
11069 S.Diag(Loc: Lambda->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11070 << CalleeName << 2 /*object: lambda expression*/;
11071}
11072
11073void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11074 const DeclRefExpr *Lvalue) {
11075 const auto *Var = dyn_cast<VarDecl>(Val: Lvalue->getDecl());
11076 if (Var == nullptr)
11077 return;
11078
11079 S.Diag(Loc: Lvalue->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11080 << CalleeName << 0 /*object: */ << Var;
11081}
11082
11083void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11084 const CastExpr *Cast) {
11085 SmallString<128> SizeString;
11086 llvm::raw_svector_ostream OS(SizeString);
11087
11088 clang::CastKind Kind = Cast->getCastKind();
11089 if (Kind == clang::CK_BitCast &&
11090 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11091 return;
11092 if (Kind == clang::CK_IntegralToPointer &&
11093 !isa<IntegerLiteral>(
11094 Val: Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11095 return;
11096
11097 switch (Cast->getCastKind()) {
11098 case clang::CK_BitCast:
11099 case clang::CK_IntegralToPointer:
11100 case clang::CK_FunctionToPointerDecay:
11101 OS << '\'';
11102 Cast->printPretty(OS, Helper: nullptr, Policy: S.getPrintingPolicy());
11103 OS << '\'';
11104 break;
11105 default:
11106 return;
11107 }
11108
11109 S.Diag(Loc: Cast->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11110 << CalleeName << 0 /*object: */ << OS.str();
11111}
11112} // namespace
11113
11114void Sema::CheckFreeArguments(const CallExpr *E) {
11115 const std::string CalleeName =
11116 cast<FunctionDecl>(Val: E->getCalleeDecl())->getQualifiedNameAsString();
11117
11118 { // Prefer something that doesn't involve a cast to make things simpler.
11119 const Expr *Arg = E->getArg(Arg: 0)->IgnoreParenCasts();
11120 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Val: Arg))
11121 switch (UnaryExpr->getOpcode()) {
11122 case UnaryOperator::Opcode::UO_AddrOf:
11123 return CheckFreeArgumentsAddressof(S&: *this, CalleeName, UnaryExpr);
11124 case UnaryOperator::Opcode::UO_Plus:
11125 return CheckFreeArgumentsPlus(S&: *this, CalleeName, UnaryExpr);
11126 default:
11127 break;
11128 }
11129
11130 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: Arg))
11131 if (Lvalue->getType()->isArrayType())
11132 return CheckFreeArgumentsStackArray(S&: *this, CalleeName, Lvalue);
11133
11134 if (const auto *Label = dyn_cast<AddrLabelExpr>(Val: Arg)) {
11135 Diag(Loc: Label->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11136 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11137 return;
11138 }
11139
11140 if (isa<BlockExpr>(Val: Arg)) {
11141 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11142 << CalleeName << 1 /*object: block*/;
11143 return;
11144 }
11145 }
11146 // Maybe the cast was important, check after the other cases.
11147 if (const auto *Cast = dyn_cast<CastExpr>(Val: E->getArg(Arg: 0)))
11148 return CheckFreeArgumentsCast(S&: *this, CalleeName, Cast);
11149}
11150
11151void
11152Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11153 SourceLocation ReturnLoc,
11154 bool isObjCMethod,
11155 const AttrVec *Attrs,
11156 const FunctionDecl *FD) {
11157 // Check if the return value is null but should not be.
11158 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(container: *Attrs)) ||
11159 (!isObjCMethod && isNonNullType(type: lhsType))) &&
11160 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11161 Diag(Loc: ReturnLoc, DiagID: diag::warn_null_ret)
11162 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11163
11164 // C++11 [basic.stc.dynamic.allocation]p4:
11165 // If an allocation function declared with a non-throwing
11166 // exception-specification fails to allocate storage, it shall return
11167 // a null pointer. Any other allocation function that fails to allocate
11168 // storage shall indicate failure only by throwing an exception [...]
11169 if (FD) {
11170 OverloadedOperatorKind Op = FD->getOverloadedOperator();
11171 if (Op == OO_New || Op == OO_Array_New) {
11172 const FunctionProtoType *Proto
11173 = FD->getType()->castAs<FunctionProtoType>();
11174 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11175 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11176 Diag(Loc: ReturnLoc, DiagID: diag::warn_operator_new_returns_null)
11177 << FD << getLangOpts().CPlusPlus11;
11178 }
11179 }
11180
11181 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11182 Diag(Loc: ReturnLoc, DiagID: diag::err_wasm_table_art) << 1;
11183 }
11184
11185 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11186 // here prevent the user from using a PPC MMA type as trailing return type.
11187 if (Context.getTargetInfo().getTriple().isPPC64())
11188 PPC().CheckPPCMMAType(Type: RetValExp->getType(), TypeLoc: ReturnLoc);
11189}
11190
11191void Sema::CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
11192 const Expr *RHS, BinaryOperatorKind Opcode) {
11193 if (!BinaryOperator::isEqualityOp(Opc: Opcode))
11194 return;
11195
11196 // Match and capture subexpressions such as "(float) X == 0.1".
11197 const FloatingLiteral *FPLiteral;
11198 const CastExpr *FPCast;
11199 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11200 FPLiteral = dyn_cast<FloatingLiteral>(Val: L->IgnoreParens());
11201 FPCast = dyn_cast<CastExpr>(Val: R->IgnoreParens());
11202 return FPLiteral && FPCast;
11203 };
11204
11205 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11206 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11207 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11208 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11209 TargetTy->isFloatingPoint()) {
11210 bool Lossy;
11211 llvm::APFloat TargetC = FPLiteral->getValue();
11212 TargetC.convert(ToSemantics: Context.getFloatTypeSemantics(T: QualType(SourceTy, 0)),
11213 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Lossy);
11214 if (Lossy) {
11215 // If the literal cannot be represented in the source type, then a
11216 // check for == is always false and check for != is always true.
11217 Diag(Loc, DiagID: diag::warn_float_compare_literal)
11218 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11219 << LHS->getSourceRange() << RHS->getSourceRange();
11220 return;
11221 }
11222 }
11223 }
11224
11225 // Match a more general floating-point equality comparison (-Wfloat-equal).
11226 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11227 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11228
11229 // Special case: check for x == x (which is OK).
11230 // Do not emit warnings for such cases.
11231 if (const auto *DRL = dyn_cast<DeclRefExpr>(Val: LeftExprSansParen))
11232 if (const auto *DRR = dyn_cast<DeclRefExpr>(Val: RightExprSansParen))
11233 if (DRL->getDecl() == DRR->getDecl())
11234 return;
11235
11236 // Special case: check for comparisons against literals that can be exactly
11237 // represented by APFloat. In such cases, do not emit a warning. This
11238 // is a heuristic: often comparison against such literals are used to
11239 // detect if a value in a variable has not changed. This clearly can
11240 // lead to false negatives.
11241 if (const auto *FLL = dyn_cast<FloatingLiteral>(Val: LeftExprSansParen)) {
11242 if (FLL->isExact())
11243 return;
11244 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(Val: RightExprSansParen))
11245 if (FLR->isExact())
11246 return;
11247
11248 // Check for comparisons with builtin types.
11249 if (const auto *CL = dyn_cast<CallExpr>(Val: LeftExprSansParen);
11250 CL && CL->getBuiltinCallee())
11251 return;
11252
11253 if (const auto *CR = dyn_cast<CallExpr>(Val: RightExprSansParen);
11254 CR && CR->getBuiltinCallee())
11255 return;
11256
11257 // Emit the diagnostic.
11258 Diag(Loc, DiagID: diag::warn_floatingpoint_eq)
11259 << LHS->getSourceRange() << RHS->getSourceRange();
11260}
11261
11262//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11263//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11264
11265namespace {
11266
11267/// Structure recording the 'active' range of an integer-valued
11268/// expression.
11269struct IntRange {
11270 /// The number of bits active in the int. Note that this includes exactly one
11271 /// sign bit if !NonNegative.
11272 unsigned Width;
11273
11274 /// True if the int is known not to have negative values. If so, all leading
11275 /// bits before Width are known zero, otherwise they are known to be the
11276 /// same as the MSB within Width.
11277 bool NonNegative;
11278
11279 IntRange(unsigned Width, bool NonNegative)
11280 : Width(Width), NonNegative(NonNegative) {}
11281
11282 /// Number of bits excluding the sign bit.
11283 unsigned valueBits() const {
11284 return NonNegative ? Width : Width - 1;
11285 }
11286
11287 /// Returns the range of the bool type.
11288 static IntRange forBoolType() {
11289 return IntRange(1, true);
11290 }
11291
11292 /// Returns the range of an opaque value of the given integral type.
11293 static IntRange forValueOfType(ASTContext &C, QualType T) {
11294 return forValueOfCanonicalType(C,
11295 T: T->getCanonicalTypeInternal().getTypePtr());
11296 }
11297
11298 /// Returns the range of an opaque value of a canonical integral type.
11299 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11300 assert(T->isCanonicalUnqualified());
11301
11302 if (const auto *VT = dyn_cast<VectorType>(Val: T))
11303 T = VT->getElementType().getTypePtr();
11304 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
11305 T = MT->getElementType().getTypePtr();
11306 if (const auto *CT = dyn_cast<ComplexType>(Val: T))
11307 T = CT->getElementType().getTypePtr();
11308 if (const auto *AT = dyn_cast<AtomicType>(Val: T))
11309 T = AT->getValueType().getTypePtr();
11310 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11311 T = OBT->getUnderlyingType().getTypePtr();
11312
11313 if (!C.getLangOpts().CPlusPlus) {
11314 // For enum types in C code, use the underlying datatype.
11315 if (const auto *ED = T->getAsEnumDecl())
11316 T = ED->getIntegerType().getDesugaredType(Context: C).getTypePtr();
11317 } else if (auto *Enum = T->getAsEnumDecl()) {
11318 // For enum types in C++, use the known bit width of the enumerators.
11319 // In C++11, enums can have a fixed underlying type. Use this type to
11320 // compute the range.
11321 if (Enum->isFixed()) {
11322 return IntRange(C.getIntWidth(T: QualType(T, 0)),
11323 !Enum->getIntegerType()->isSignedIntegerType());
11324 }
11325
11326 unsigned NumPositive = Enum->getNumPositiveBits();
11327 unsigned NumNegative = Enum->getNumNegativeBits();
11328
11329 if (NumNegative == 0)
11330 return IntRange(NumPositive, true/*NonNegative*/);
11331 else
11332 return IntRange(std::max(a: NumPositive + 1, b: NumNegative),
11333 false/*NonNegative*/);
11334 }
11335
11336 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11337 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11338
11339 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11340 assert(BT->isInteger());
11341
11342 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11343 }
11344
11345 /// Returns the "target" range of a canonical integral type, i.e.
11346 /// the range of values expressible in the type.
11347 ///
11348 /// This matches forValueOfCanonicalType except that enums have the
11349 /// full range of their type, not the range of their enumerators.
11350 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11351 assert(T->isCanonicalUnqualified());
11352
11353 if (const VectorType *VT = dyn_cast<VectorType>(Val: T))
11354 T = VT->getElementType().getTypePtr();
11355 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
11356 T = MT->getElementType().getTypePtr();
11357 if (const ComplexType *CT = dyn_cast<ComplexType>(Val: T))
11358 T = CT->getElementType().getTypePtr();
11359 if (const AtomicType *AT = dyn_cast<AtomicType>(Val: T))
11360 T = AT->getValueType().getTypePtr();
11361 if (const auto *ED = T->getAsEnumDecl())
11362 T = C.getCanonicalType(T: ED->getIntegerType()).getTypePtr();
11363 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11364 T = OBT->getUnderlyingType().getTypePtr();
11365
11366 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11367 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11368
11369 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11370 assert(BT->isInteger());
11371
11372 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11373 }
11374
11375 /// Returns the supremum of two ranges: i.e. their conservative merge.
11376 static IntRange join(IntRange L, IntRange R) {
11377 bool Unsigned = L.NonNegative && R.NonNegative;
11378 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
11379 L.NonNegative && R.NonNegative);
11380 }
11381
11382 /// Return the range of a bitwise-AND of the two ranges.
11383 static IntRange bit_and(IntRange L, IntRange R) {
11384 unsigned Bits = std::max(a: L.Width, b: R.Width);
11385 bool NonNegative = false;
11386 if (L.NonNegative) {
11387 Bits = std::min(a: Bits, b: L.Width);
11388 NonNegative = true;
11389 }
11390 if (R.NonNegative) {
11391 Bits = std::min(a: Bits, b: R.Width);
11392 NonNegative = true;
11393 }
11394 return IntRange(Bits, NonNegative);
11395 }
11396
11397 /// Return the range of a sum of the two ranges.
11398 static IntRange sum(IntRange L, IntRange R) {
11399 bool Unsigned = L.NonNegative && R.NonNegative;
11400 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + 1 + !Unsigned,
11401 Unsigned);
11402 }
11403
11404 /// Return the range of a difference of the two ranges.
11405 static IntRange difference(IntRange L, IntRange R) {
11406 // We need a 1-bit-wider range if:
11407 // 1) LHS can be negative: least value can be reduced.
11408 // 2) RHS can be negative: greatest value can be increased.
11409 bool CanWiden = !L.NonNegative || !R.NonNegative;
11410 bool Unsigned = L.NonNegative && R.Width == 0;
11411 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + CanWiden +
11412 !Unsigned,
11413 Unsigned);
11414 }
11415
11416 /// Return the range of a product of the two ranges.
11417 static IntRange product(IntRange L, IntRange R) {
11418 // If both LHS and RHS can be negative, we can form
11419 // -2^L * -2^R = 2^(L + R)
11420 // which requires L + R + 1 value bits to represent.
11421 bool CanWiden = !L.NonNegative && !R.NonNegative;
11422 bool Unsigned = L.NonNegative && R.NonNegative;
11423 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11424 Unsigned);
11425 }
11426
11427 /// Return the range of a remainder operation between the two ranges.
11428 static IntRange rem(IntRange L, IntRange R) {
11429 // The result of a remainder can't be larger than the result of
11430 // either side. The sign of the result is the sign of the LHS.
11431 bool Unsigned = L.NonNegative;
11432 return IntRange(std::min(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
11433 Unsigned);
11434 }
11435};
11436
11437} // namespace
11438
11439static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11440 if (value.isSigned() && value.isNegative())
11441 return IntRange(value.getSignificantBits(), false);
11442
11443 if (value.getBitWidth() > MaxWidth)
11444 value = value.trunc(width: MaxWidth);
11445
11446 // isNonNegative() just checks the sign bit without considering
11447 // signedness.
11448 return IntRange(value.getActiveBits(), true);
11449}
11450
11451static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11452 if (result.isInt())
11453 return GetValueRange(value&: result.getInt(), MaxWidth);
11454
11455 if (result.isVector()) {
11456 IntRange R = GetValueRange(result&: result.getVectorElt(I: 0), Ty, MaxWidth);
11457 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11458 IntRange El = GetValueRange(result&: result.getVectorElt(I: i), Ty, MaxWidth);
11459 R = IntRange::join(L: R, R: El);
11460 }
11461 return R;
11462 }
11463
11464 if (result.isComplexInt()) {
11465 IntRange R = GetValueRange(value&: result.getComplexIntReal(), MaxWidth);
11466 IntRange I = GetValueRange(value&: result.getComplexIntImag(), MaxWidth);
11467 return IntRange::join(L: R, R: I);
11468 }
11469
11470 // This can happen with lossless casts to intptr_t of "based" lvalues.
11471 // Assume it might use arbitrary bits.
11472 // FIXME: The only reason we need to pass the type in here is to get
11473 // the sign right on this one case. It would be nice if APValue
11474 // preserved this.
11475 assert(result.isLValue() || result.isAddrLabelDiff());
11476 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11477}
11478
11479static QualType GetExprType(const Expr *E) {
11480 QualType Ty = E->getType();
11481 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11482 Ty = AtomicRHS->getValueType();
11483 return Ty;
11484}
11485
11486/// Attempts to estimate an approximate range for the given integer expression.
11487/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11488/// reliable estimation cannot be determined.
11489///
11490/// \param MaxWidth The width to which the value will be truncated.
11491/// \param InConstantContext If \c true, interpret the expression within a
11492/// constant context.
11493/// \param Approximate If \c true, provide a likely range of values by assuming
11494/// that arithmetic on narrower types remains within those types.
11495/// If \c false, return a range that includes all possible values
11496/// resulting from the expression.
11497/// \returns A range of values that the expression might take, or
11498/// std::nullopt if a reliable estimation cannot be determined.
11499static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11500 unsigned MaxWidth,
11501 bool InConstantContext,
11502 bool Approximate) {
11503 E = E->IgnoreParens();
11504
11505 // Try a full evaluation first.
11506 Expr::EvalResult result;
11507 if (E->EvaluateAsRValue(Result&: result, Ctx: C, InConstantContext))
11508 return GetValueRange(result&: result.Val, Ty: GetExprType(E), MaxWidth);
11509
11510 // I think we only want to look through implicit casts here; if the
11511 // user has an explicit widening cast, we should treat the value as
11512 // being of the new, wider type.
11513 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Val: E)) {
11514 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11515 return TryGetExprRange(C, E: CE->getSubExpr(), MaxWidth, InConstantContext,
11516 Approximate);
11517
11518 IntRange OutputTypeRange = IntRange::forValueOfType(C, T: GetExprType(E: CE));
11519
11520 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11521 CE->getCastKind() == CK_BooleanToSignedIntegral;
11522
11523 // Assume that non-integer casts can span the full range of the type.
11524 if (!isIntegerCast)
11525 return OutputTypeRange;
11526
11527 std::optional<IntRange> SubRange = TryGetExprRange(
11528 C, E: CE->getSubExpr(), MaxWidth: std::min(a: MaxWidth, b: OutputTypeRange.Width),
11529 InConstantContext, Approximate);
11530 if (!SubRange)
11531 return std::nullopt;
11532
11533 // Bail out if the subexpr's range is as wide as the cast type.
11534 if (SubRange->Width >= OutputTypeRange.Width)
11535 return OutputTypeRange;
11536
11537 // Otherwise, we take the smaller width, and we're non-negative if
11538 // either the output type or the subexpr is.
11539 return IntRange(SubRange->Width,
11540 SubRange->NonNegative || OutputTypeRange.NonNegative);
11541 }
11542
11543 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
11544 // If we can fold the condition, just take that operand.
11545 bool CondResult;
11546 if (CO->getCond()->EvaluateAsBooleanCondition(Result&: CondResult, Ctx: C))
11547 return TryGetExprRange(
11548 C, E: CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11549 InConstantContext, Approximate);
11550
11551 // Otherwise, conservatively merge.
11552 // TryGetExprRange requires an integer expression, but a throw expression
11553 // results in a void type.
11554 Expr *TrueExpr = CO->getTrueExpr();
11555 if (TrueExpr->getType()->isVoidType())
11556 return std::nullopt;
11557
11558 std::optional<IntRange> L =
11559 TryGetExprRange(C, E: TrueExpr, MaxWidth, InConstantContext, Approximate);
11560 if (!L)
11561 return std::nullopt;
11562
11563 Expr *FalseExpr = CO->getFalseExpr();
11564 if (FalseExpr->getType()->isVoidType())
11565 return std::nullopt;
11566
11567 std::optional<IntRange> R =
11568 TryGetExprRange(C, E: FalseExpr, MaxWidth, InConstantContext, Approximate);
11569 if (!R)
11570 return std::nullopt;
11571
11572 return IntRange::join(L: *L, R: *R);
11573 }
11574
11575 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
11576 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11577
11578 switch (BO->getOpcode()) {
11579 case BO_Cmp:
11580 llvm_unreachable("builtin <=> should have class type");
11581
11582 // Boolean-valued operations are single-bit and positive.
11583 case BO_LAnd:
11584 case BO_LOr:
11585 case BO_LT:
11586 case BO_GT:
11587 case BO_LE:
11588 case BO_GE:
11589 case BO_EQ:
11590 case BO_NE:
11591 return IntRange::forBoolType();
11592
11593 // The type of the assignments is the type of the LHS, so the RHS
11594 // is not necessarily the same type.
11595 case BO_MulAssign:
11596 case BO_DivAssign:
11597 case BO_RemAssign:
11598 case BO_AddAssign:
11599 case BO_SubAssign:
11600 case BO_XorAssign:
11601 case BO_OrAssign:
11602 // TODO: bitfields?
11603 return IntRange::forValueOfType(C, T: GetExprType(E));
11604
11605 // Simple assignments just pass through the RHS, which will have
11606 // been coerced to the LHS type.
11607 case BO_Assign:
11608 // TODO: bitfields?
11609 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
11610 Approximate);
11611
11612 // Operations with opaque sources are black-listed.
11613 case BO_PtrMemD:
11614 case BO_PtrMemI:
11615 return IntRange::forValueOfType(C, T: GetExprType(E));
11616
11617 // Bitwise-and uses the *infinum* of the two source ranges.
11618 case BO_And:
11619 case BO_AndAssign:
11620 Combine = IntRange::bit_and;
11621 break;
11622
11623 // Left shift gets black-listed based on a judgement call.
11624 case BO_Shl:
11625 // ...except that we want to treat '1 << (blah)' as logically
11626 // positive. It's an important idiom.
11627 if (IntegerLiteral *I
11628 = dyn_cast<IntegerLiteral>(Val: BO->getLHS()->IgnoreParenCasts())) {
11629 if (I->getValue() == 1) {
11630 IntRange R = IntRange::forValueOfType(C, T: GetExprType(E));
11631 return IntRange(R.Width, /*NonNegative*/ true);
11632 }
11633 }
11634 [[fallthrough]];
11635
11636 case BO_ShlAssign:
11637 return IntRange::forValueOfType(C, T: GetExprType(E));
11638
11639 // Right shift by a constant can narrow its left argument.
11640 case BO_Shr:
11641 case BO_ShrAssign: {
11642 std::optional<IntRange> L = TryGetExprRange(
11643 C, E: BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11644 if (!L)
11645 return std::nullopt;
11646
11647 // If the shift amount is a positive constant, drop the width by
11648 // that much.
11649 if (std::optional<llvm::APSInt> shift =
11650 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
11651 if (shift->isNonNegative()) {
11652 if (shift->uge(RHS: L->Width))
11653 L->Width = (L->NonNegative ? 0 : 1);
11654 else
11655 L->Width -= shift->getZExtValue();
11656 }
11657 }
11658
11659 return L;
11660 }
11661
11662 // Comma acts as its right operand.
11663 case BO_Comma:
11664 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
11665 Approximate);
11666
11667 case BO_Add:
11668 if (!Approximate)
11669 Combine = IntRange::sum;
11670 break;
11671
11672 case BO_Sub:
11673 if (BO->getLHS()->getType()->isPointerType())
11674 return IntRange::forValueOfType(C, T: GetExprType(E));
11675 if (!Approximate)
11676 Combine = IntRange::difference;
11677 break;
11678
11679 case BO_Mul:
11680 if (!Approximate)
11681 Combine = IntRange::product;
11682 break;
11683
11684 // The width of a division result is mostly determined by the size
11685 // of the LHS.
11686 case BO_Div: {
11687 // Don't 'pre-truncate' the operands.
11688 unsigned opWidth = C.getIntWidth(T: GetExprType(E));
11689 std::optional<IntRange> L = TryGetExprRange(
11690 C, E: BO->getLHS(), MaxWidth: opWidth, InConstantContext, Approximate);
11691 if (!L)
11692 return std::nullopt;
11693
11694 // If the divisor is constant, use that.
11695 if (std::optional<llvm::APSInt> divisor =
11696 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
11697 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11698 if (log2 >= L->Width)
11699 L->Width = (L->NonNegative ? 0 : 1);
11700 else
11701 L->Width = std::min(a: L->Width - log2, b: MaxWidth);
11702 return L;
11703 }
11704
11705 // Otherwise, just use the LHS's width.
11706 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11707 // could be -1.
11708 std::optional<IntRange> R = TryGetExprRange(
11709 C, E: BO->getRHS(), MaxWidth: opWidth, InConstantContext, Approximate);
11710 if (!R)
11711 return std::nullopt;
11712
11713 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11714 }
11715
11716 case BO_Rem:
11717 Combine = IntRange::rem;
11718 break;
11719
11720 // The default behavior is okay for these.
11721 case BO_Xor:
11722 case BO_Or:
11723 break;
11724 }
11725
11726 // Combine the two ranges, but limit the result to the type in which we
11727 // performed the computation.
11728 QualType T = GetExprType(E);
11729 unsigned opWidth = C.getIntWidth(T);
11730 std::optional<IntRange> L = TryGetExprRange(C, E: BO->getLHS(), MaxWidth: opWidth,
11731 InConstantContext, Approximate);
11732 if (!L)
11733 return std::nullopt;
11734
11735 std::optional<IntRange> R = TryGetExprRange(C, E: BO->getRHS(), MaxWidth: opWidth,
11736 InConstantContext, Approximate);
11737 if (!R)
11738 return std::nullopt;
11739
11740 IntRange C = Combine(*L, *R);
11741 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11742 C.Width = std::min(a: C.Width, b: MaxWidth);
11743 return C;
11744 }
11745
11746 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
11747 switch (UO->getOpcode()) {
11748 // Boolean-valued operations are white-listed.
11749 case UO_LNot:
11750 return IntRange::forBoolType();
11751
11752 // Operations with opaque sources are black-listed.
11753 case UO_Deref:
11754 case UO_AddrOf: // should be impossible
11755 return IntRange::forValueOfType(C, T: GetExprType(E));
11756
11757 case UO_Minus: {
11758 if (E->getType()->isUnsignedIntegerType()) {
11759 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
11760 Approximate);
11761 }
11762
11763 std::optional<IntRange> SubRange = TryGetExprRange(
11764 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11765
11766 if (!SubRange)
11767 return std::nullopt;
11768
11769 // If the range was previously non-negative, we need an extra bit for the
11770 // sign bit. Otherwise, we need an extra bit because the negation of the
11771 // most-negative value is one bit wider than that value.
11772 return IntRange(std::min(a: SubRange->Width + 1, b: MaxWidth), false);
11773 }
11774
11775 case UO_Not: {
11776 if (E->getType()->isUnsignedIntegerType()) {
11777 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
11778 Approximate);
11779 }
11780
11781 std::optional<IntRange> SubRange = TryGetExprRange(
11782 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11783
11784 if (!SubRange)
11785 return std::nullopt;
11786
11787 // The width increments by 1 if the sub-expression cannot be negative
11788 // since it now can be.
11789 return IntRange(
11790 std::min(a: SubRange->Width + (int)SubRange->NonNegative, b: MaxWidth),
11791 false);
11792 }
11793
11794 default:
11795 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
11796 Approximate);
11797 }
11798 }
11799
11800 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
11801 return TryGetExprRange(C, E: OVE->getSourceExpr(), MaxWidth, InConstantContext,
11802 Approximate);
11803
11804 if (const auto *BitField = E->getSourceBitField())
11805 return IntRange(BitField->getBitWidthValue(),
11806 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11807
11808 if (GetExprType(E)->isVoidType())
11809 return std::nullopt;
11810
11811 return IntRange::forValueOfType(C, T: GetExprType(E));
11812}
11813
11814static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11815 bool InConstantContext,
11816 bool Approximate) {
11817 return TryGetExprRange(C, E, MaxWidth: C.getIntWidth(T: GetExprType(E)), InConstantContext,
11818 Approximate);
11819}
11820
11821/// Checks whether the given value, which currently has the given
11822/// source semantics, has the same value when coerced through the
11823/// target semantics.
11824static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11825 const llvm::fltSemantics &Src,
11826 const llvm::fltSemantics &Tgt) {
11827 llvm::APFloat truncated = value;
11828
11829 bool ignored;
11830 truncated.convert(ToSemantics: Src, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
11831 truncated.convert(ToSemantics: Tgt, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
11832
11833 return truncated.bitwiseIsEqual(RHS: value);
11834}
11835
11836/// Checks whether the given value, which currently has the given
11837/// source semantics, has the same value when coerced through the
11838/// target semantics.
11839///
11840/// The value might be a vector of floats (or a complex number).
11841static bool IsSameFloatAfterCast(const APValue &value,
11842 const llvm::fltSemantics &Src,
11843 const llvm::fltSemantics &Tgt) {
11844 if (value.isFloat())
11845 return IsSameFloatAfterCast(value: value.getFloat(), Src, Tgt);
11846
11847 if (value.isVector()) {
11848 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11849 if (!IsSameFloatAfterCast(value: value.getVectorElt(I: i), Src, Tgt))
11850 return false;
11851 return true;
11852 }
11853
11854 if (value.isMatrix()) {
11855 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
11856 if (!IsSameFloatAfterCast(value: value.getMatrixElt(Idx: i), Src, Tgt))
11857 return false;
11858 return true;
11859 }
11860
11861 assert(value.isComplexFloat());
11862 return (IsSameFloatAfterCast(value: value.getComplexFloatReal(), Src, Tgt) &&
11863 IsSameFloatAfterCast(value: value.getComplexFloatImag(), Src, Tgt));
11864}
11865
11866static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11867 bool IsListInit = false);
11868
11869static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11870 // Suppress cases where we are comparing against an enum constant.
11871 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()))
11872 if (isa<EnumConstantDecl>(Val: DR->getDecl()))
11873 return true;
11874
11875 // Suppress cases where the value is expanded from a macro, unless that macro
11876 // is how a language represents a boolean literal. This is the case in both C
11877 // and Objective-C.
11878 SourceLocation BeginLoc = E->getBeginLoc();
11879 if (BeginLoc.isMacroID()) {
11880 StringRef MacroName = Lexer::getImmediateMacroName(
11881 Loc: BeginLoc, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
11882 return MacroName != "YES" && MacroName != "NO" &&
11883 MacroName != "true" && MacroName != "false";
11884 }
11885
11886 return false;
11887}
11888
11889static bool isKnownToHaveUnsignedValue(const Expr *E) {
11890 return E->getType()->isIntegerType() &&
11891 (!E->getType()->isSignedIntegerType() ||
11892 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11893}
11894
11895namespace {
11896/// The promoted range of values of a type. In general this has the
11897/// following structure:
11898///
11899/// |-----------| . . . |-----------|
11900/// ^ ^ ^ ^
11901/// Min HoleMin HoleMax Max
11902///
11903/// ... where there is only a hole if a signed type is promoted to unsigned
11904/// (in which case Min and Max are the smallest and largest representable
11905/// values).
11906struct PromotedRange {
11907 // Min, or HoleMax if there is a hole.
11908 llvm::APSInt PromotedMin;
11909 // Max, or HoleMin if there is a hole.
11910 llvm::APSInt PromotedMax;
11911
11912 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11913 if (R.Width == 0)
11914 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11915 else if (R.Width >= BitWidth && !Unsigned) {
11916 // Promotion made the type *narrower*. This happens when promoting
11917 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11918 // Treat all values of 'signed int' as being in range for now.
11919 PromotedMin = llvm::APSInt::getMinValue(numBits: BitWidth, Unsigned);
11920 PromotedMax = llvm::APSInt::getMaxValue(numBits: BitWidth, Unsigned);
11921 } else {
11922 PromotedMin = llvm::APSInt::getMinValue(numBits: R.Width, Unsigned: R.NonNegative)
11923 .extOrTrunc(width: BitWidth);
11924 PromotedMin.setIsUnsigned(Unsigned);
11925
11926 PromotedMax = llvm::APSInt::getMaxValue(numBits: R.Width, Unsigned: R.NonNegative)
11927 .extOrTrunc(width: BitWidth);
11928 PromotedMax.setIsUnsigned(Unsigned);
11929 }
11930 }
11931
11932 // Determine whether this range is contiguous (has no hole).
11933 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11934
11935 // Where a constant value is within the range.
11936 enum ComparisonResult {
11937 LT = 0x1,
11938 LE = 0x2,
11939 GT = 0x4,
11940 GE = 0x8,
11941 EQ = 0x10,
11942 NE = 0x20,
11943 InRangeFlag = 0x40,
11944
11945 Less = LE | LT | NE,
11946 Min = LE | InRangeFlag,
11947 InRange = InRangeFlag,
11948 Max = GE | InRangeFlag,
11949 Greater = GE | GT | NE,
11950
11951 OnlyValue = LE | GE | EQ | InRangeFlag,
11952 InHole = NE
11953 };
11954
11955 ComparisonResult compare(const llvm::APSInt &Value) const {
11956 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11957 Value.isUnsigned() == PromotedMin.isUnsigned());
11958 if (!isContiguous()) {
11959 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11960 if (Value.isMinValue()) return Min;
11961 if (Value.isMaxValue()) return Max;
11962 if (Value >= PromotedMin) return InRange;
11963 if (Value <= PromotedMax) return InRange;
11964 return InHole;
11965 }
11966
11967 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMin)) {
11968 case -1: return Less;
11969 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11970 case 1:
11971 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMax)) {
11972 case -1: return InRange;
11973 case 0: return Max;
11974 case 1: return Greater;
11975 }
11976 }
11977
11978 llvm_unreachable("impossible compare result");
11979 }
11980
11981 static std::optional<StringRef>
11982 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11983 if (Op == BO_Cmp) {
11984 ComparisonResult LTFlag = LT, GTFlag = GT;
11985 if (ConstantOnRHS) std::swap(a&: LTFlag, b&: GTFlag);
11986
11987 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11988 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11989 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11990 return std::nullopt;
11991 }
11992
11993 ComparisonResult TrueFlag, FalseFlag;
11994 if (Op == BO_EQ) {
11995 TrueFlag = EQ;
11996 FalseFlag = NE;
11997 } else if (Op == BO_NE) {
11998 TrueFlag = NE;
11999 FalseFlag = EQ;
12000 } else {
12001 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12002 TrueFlag = LT;
12003 FalseFlag = GE;
12004 } else {
12005 TrueFlag = GT;
12006 FalseFlag = LE;
12007 }
12008 if (Op == BO_GE || Op == BO_LE)
12009 std::swap(a&: TrueFlag, b&: FalseFlag);
12010 }
12011 if (R & TrueFlag)
12012 return StringRef("true");
12013 if (R & FalseFlag)
12014 return StringRef("false");
12015 return std::nullopt;
12016 }
12017};
12018}
12019
12020static bool HasEnumType(const Expr *E) {
12021 // Strip off implicit integral promotions.
12022 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
12023 if (ICE->getCastKind() != CK_IntegralCast &&
12024 ICE->getCastKind() != CK_NoOp)
12025 break;
12026 E = ICE->getSubExpr();
12027 }
12028
12029 return E->getType()->isEnumeralType();
12030}
12031
12032static int classifyConstantValue(Expr *Constant) {
12033 // The values of this enumeration are used in the diagnostics
12034 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12035 enum ConstantValueKind {
12036 Miscellaneous = 0,
12037 LiteralTrue,
12038 LiteralFalse
12039 };
12040 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Val: Constant))
12041 return BL->getValue() ? ConstantValueKind::LiteralTrue
12042 : ConstantValueKind::LiteralFalse;
12043 return ConstantValueKind::Miscellaneous;
12044}
12045
12046static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12047 Expr *Constant, Expr *Other,
12048 const llvm::APSInt &Value,
12049 bool RhsConstant) {
12050 if (S.inTemplateInstantiation())
12051 return false;
12052
12053 Expr *OriginalOther = Other;
12054
12055 Constant = Constant->IgnoreParenImpCasts();
12056 Other = Other->IgnoreParenImpCasts();
12057
12058 // Suppress warnings on tautological comparisons between values of the same
12059 // enumeration type. There are only two ways we could warn on this:
12060 // - If the constant is outside the range of representable values of
12061 // the enumeration. In such a case, we should warn about the cast
12062 // to enumeration type, not about the comparison.
12063 // - If the constant is the maximum / minimum in-range value. For an
12064 // enumeratin type, such comparisons can be meaningful and useful.
12065 if (Constant->getType()->isEnumeralType() &&
12066 S.Context.hasSameUnqualifiedType(T1: Constant->getType(), T2: Other->getType()))
12067 return false;
12068
12069 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12070 C&: S.Context, E: Other, InConstantContext: S.isConstantEvaluatedContext(), /*Approximate=*/false);
12071 if (!OtherValueRange)
12072 return false;
12073
12074 QualType OtherT = Other->getType();
12075 if (const auto *AT = OtherT->getAs<AtomicType>())
12076 OtherT = AT->getValueType();
12077 IntRange OtherTypeRange = IntRange::forValueOfType(C&: S.Context, T: OtherT);
12078
12079 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12080 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12081 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12082 S.ObjC().NSAPIObj->isObjCBOOLType(T: OtherT) &&
12083 OtherT->isSpecificBuiltinType(K: BuiltinType::SChar);
12084
12085 // Whether we're treating Other as being a bool because of the form of
12086 // expression despite it having another type (typically 'int' in C).
12087 bool OtherIsBooleanDespiteType =
12088 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12089 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12090 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12091
12092 // Check if all values in the range of possible values of this expression
12093 // lead to the same comparison outcome.
12094 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12095 Value.isUnsigned());
12096 auto Cmp = OtherPromotedValueRange.compare(Value);
12097 auto Result = PromotedRange::constantValue(Op: E->getOpcode(), R: Cmp, ConstantOnRHS: RhsConstant);
12098 if (!Result)
12099 return false;
12100
12101 // Also consider the range determined by the type alone. This allows us to
12102 // classify the warning under the proper diagnostic group.
12103 bool TautologicalTypeCompare = false;
12104 {
12105 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12106 Value.isUnsigned());
12107 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12108 if (auto TypeResult = PromotedRange::constantValue(Op: E->getOpcode(), R: TypeCmp,
12109 ConstantOnRHS: RhsConstant)) {
12110 TautologicalTypeCompare = true;
12111 Cmp = TypeCmp;
12112 Result = TypeResult;
12113 }
12114 }
12115
12116 // Don't warn if the non-constant operand actually always evaluates to the
12117 // same value.
12118 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12119 return false;
12120
12121 // Suppress the diagnostic for an in-range comparison if the constant comes
12122 // from a macro or enumerator. We don't want to diagnose
12123 //
12124 // some_long_value <= INT_MAX
12125 //
12126 // when sizeof(int) == sizeof(long).
12127 bool InRange = Cmp & PromotedRange::InRangeFlag;
12128 if (InRange && IsEnumConstOrFromMacro(S, E: Constant))
12129 return false;
12130
12131 // A comparison of an unsigned bit-field against 0 is really a type problem,
12132 // even though at the type level the bit-field might promote to 'signed int'.
12133 if (Other->refersToBitField() && InRange && Value == 0 &&
12134 Other->getType()->isUnsignedIntegerOrEnumerationType())
12135 TautologicalTypeCompare = true;
12136
12137 // If this is a comparison to an enum constant, include that
12138 // constant in the diagnostic.
12139 const EnumConstantDecl *ED = nullptr;
12140 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: Constant))
12141 ED = dyn_cast<EnumConstantDecl>(Val: DR->getDecl());
12142
12143 // Should be enough for uint128 (39 decimal digits)
12144 SmallString<64> PrettySourceValue;
12145 llvm::raw_svector_ostream OS(PrettySourceValue);
12146 if (ED) {
12147 OS << '\'' << *ED << "' (" << Value << ")";
12148 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12149 Val: Constant->IgnoreParenImpCasts())) {
12150 OS << (BL->getValue() ? "YES" : "NO");
12151 } else {
12152 OS << Value;
12153 }
12154
12155 if (!TautologicalTypeCompare) {
12156 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_tautological_compare_value_range)
12157 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12158 << E->getOpcodeStr() << OS.str() << *Result
12159 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12160 return true;
12161 }
12162
12163 if (IsObjCSignedCharBool) {
12164 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12165 PD: S.PDiag(DiagID: diag::warn_tautological_compare_objc_bool)
12166 << OS.str() << *Result);
12167 return true;
12168 }
12169
12170 // FIXME: We use a somewhat different formatting for the in-range cases and
12171 // cases involving boolean values for historical reasons. We should pick a
12172 // consistent way of presenting these diagnostics.
12173 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12174
12175 S.DiagRuntimeBehavior(
12176 Loc: E->getOperatorLoc(), Statement: E,
12177 PD: S.PDiag(DiagID: !InRange ? diag::warn_out_of_range_compare
12178 : diag::warn_tautological_bool_compare)
12179 << OS.str() << classifyConstantValue(Constant) << OtherT
12180 << OtherIsBooleanDespiteType << *Result
12181 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12182 } else {
12183 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12184 unsigned Diag =
12185 (isKnownToHaveUnsignedValue(E: OriginalOther) && Value == 0)
12186 ? (HasEnumType(E: OriginalOther)
12187 ? diag::warn_unsigned_enum_always_true_comparison
12188 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12189 : diag::warn_unsigned_always_true_comparison)
12190 : diag::warn_tautological_constant_compare;
12191
12192 S.Diag(Loc: E->getOperatorLoc(), DiagID: Diag)
12193 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12194 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12195 }
12196
12197 return true;
12198}
12199
12200/// Analyze the operands of the given comparison. Implements the
12201/// fallback case from AnalyzeComparison.
12202static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12203 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12204 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12205}
12206
12207/// Implements -Wsign-compare.
12208///
12209/// \param E the binary operator to check for warnings
12210static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12211 // The type the comparison is being performed in.
12212 QualType T = E->getLHS()->getType();
12213
12214 // Only analyze comparison operators where both sides have been converted to
12215 // the same type.
12216 if (!S.Context.hasSameUnqualifiedType(T1: T, T2: E->getRHS()->getType()))
12217 return AnalyzeImpConvsInComparison(S, E);
12218
12219 // Don't analyze value-dependent comparisons directly.
12220 if (E->isValueDependent())
12221 return AnalyzeImpConvsInComparison(S, E);
12222
12223 Expr *LHS = E->getLHS();
12224 Expr *RHS = E->getRHS();
12225
12226 if (T->isIntegralType(Ctx: S.Context)) {
12227 std::optional<llvm::APSInt> RHSValue =
12228 RHS->getIntegerConstantExpr(Ctx: S.Context);
12229 std::optional<llvm::APSInt> LHSValue =
12230 LHS->getIntegerConstantExpr(Ctx: S.Context);
12231
12232 // We don't care about expressions whose result is a constant.
12233 if (RHSValue && LHSValue)
12234 return AnalyzeImpConvsInComparison(S, E);
12235
12236 // We only care about expressions where just one side is literal
12237 if ((bool)RHSValue ^ (bool)LHSValue) {
12238 // Is the constant on the RHS or LHS?
12239 const bool RhsConstant = (bool)RHSValue;
12240 Expr *Const = RhsConstant ? RHS : LHS;
12241 Expr *Other = RhsConstant ? LHS : RHS;
12242 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12243
12244 // Check whether an integer constant comparison results in a value
12245 // of 'true' or 'false'.
12246 if (CheckTautologicalComparison(S, E, Constant: Const, Other, Value, RhsConstant))
12247 return AnalyzeImpConvsInComparison(S, E);
12248 }
12249 }
12250
12251 if (!T->hasUnsignedIntegerRepresentation()) {
12252 // We don't do anything special if this isn't an unsigned integral
12253 // comparison: we're only interested in integral comparisons, and
12254 // signed comparisons only happen in cases we don't care to warn about.
12255 return AnalyzeImpConvsInComparison(S, E);
12256 }
12257
12258 LHS = LHS->IgnoreParenImpCasts();
12259 RHS = RHS->IgnoreParenImpCasts();
12260
12261 if (!S.getLangOpts().CPlusPlus) {
12262 // Avoid warning about comparison of integers with different signs when
12263 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12264 // the type of `E`.
12265 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: LHS->getType()))
12266 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12267 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: RHS->getType()))
12268 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12269 }
12270
12271 // Check to see if one of the (unmodified) operands is of different
12272 // signedness.
12273 Expr *signedOperand, *unsignedOperand;
12274 if (LHS->getType()->hasSignedIntegerRepresentation()) {
12275 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12276 "unsigned comparison between two signed integer expressions?");
12277 signedOperand = LHS;
12278 unsignedOperand = RHS;
12279 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12280 signedOperand = RHS;
12281 unsignedOperand = LHS;
12282 } else {
12283 return AnalyzeImpConvsInComparison(S, E);
12284 }
12285
12286 // Otherwise, calculate the effective range of the signed operand.
12287 std::optional<IntRange> signedRange =
12288 TryGetExprRange(C&: S.Context, E: signedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12289 /*Approximate=*/true);
12290 if (!signedRange)
12291 return;
12292
12293 // Go ahead and analyze implicit conversions in the operands. Note
12294 // that we skip the implicit conversions on both sides.
12295 AnalyzeImplicitConversions(S, E: LHS, CC: E->getOperatorLoc());
12296 AnalyzeImplicitConversions(S, E: RHS, CC: E->getOperatorLoc());
12297
12298 // If the signed range is non-negative, -Wsign-compare won't fire.
12299 if (signedRange->NonNegative)
12300 return;
12301
12302 // For (in)equality comparisons, if the unsigned operand is a
12303 // constant which cannot collide with a overflowed signed operand,
12304 // then reinterpreting the signed operand as unsigned will not
12305 // change the result of the comparison.
12306 if (E->isEqualityOp()) {
12307 unsigned comparisonWidth = S.Context.getIntWidth(T);
12308 std::optional<IntRange> unsignedRange = TryGetExprRange(
12309 C&: S.Context, E: unsignedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12310 /*Approximate=*/true);
12311 if (!unsignedRange)
12312 return;
12313
12314 // We should never be unable to prove that the unsigned operand is
12315 // non-negative.
12316 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12317
12318 if (unsignedRange->Width < comparisonWidth)
12319 return;
12320 }
12321
12322 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12323 PD: S.PDiag(DiagID: diag::warn_mixed_sign_comparison)
12324 << LHS->getType() << RHS->getType()
12325 << LHS->getSourceRange() << RHS->getSourceRange());
12326}
12327
12328/// Analyzes an attempt to assign the given value to a bitfield.
12329///
12330/// Returns true if there was something fishy about the attempt.
12331static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12332 SourceLocation InitLoc) {
12333 assert(Bitfield->isBitField());
12334 if (Bitfield->isInvalidDecl())
12335 return false;
12336
12337 // White-list bool bitfields.
12338 QualType BitfieldType = Bitfield->getType();
12339 if (BitfieldType->isBooleanType())
12340 return false;
12341
12342 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12343 // If the underlying enum type was not explicitly specified as an unsigned
12344 // type and the enum contain only positive values, MSVC++ will cause an
12345 // inconsistency by storing this as a signed type.
12346 if (S.getLangOpts().CPlusPlus11 &&
12347 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12348 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12349 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12350 S.Diag(Loc: InitLoc, DiagID: diag::warn_no_underlying_type_specified_for_enum_bitfield)
12351 << BitfieldEnumDecl;
12352 }
12353 }
12354
12355 // Ignore value- or type-dependent expressions.
12356 if (Bitfield->getBitWidth()->isValueDependent() ||
12357 Bitfield->getBitWidth()->isTypeDependent() ||
12358 Init->isValueDependent() ||
12359 Init->isTypeDependent())
12360 return false;
12361
12362 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12363 unsigned FieldWidth = Bitfield->getBitWidthValue();
12364
12365 Expr::EvalResult Result;
12366 if (!OriginalInit->EvaluateAsInt(Result, Ctx: S.Context,
12367 AllowSideEffects: Expr::SE_AllowSideEffects)) {
12368 // The RHS is not constant. If the RHS has an enum type, make sure the
12369 // bitfield is wide enough to hold all the values of the enum without
12370 // truncation.
12371 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12372 const PreferredTypeAttr *PTAttr = nullptr;
12373 if (!ED) {
12374 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12375 if (PTAttr)
12376 ED = PTAttr->getType()->getAsEnumDecl();
12377 }
12378 if (ED) {
12379 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12380
12381 // Enum types are implicitly signed on Windows, so check if there are any
12382 // negative enumerators to see if the enum was intended to be signed or
12383 // not.
12384 bool SignedEnum = ED->getNumNegativeBits() > 0;
12385
12386 // Check for surprising sign changes when assigning enum values to a
12387 // bitfield of different signedness. If the bitfield is signed and we
12388 // have exactly the right number of bits to store this unsigned enum,
12389 // suggest changing the enum to an unsigned type. This typically happens
12390 // on Windows where unfixed enums always use an underlying type of 'int'.
12391 unsigned DiagID = 0;
12392 if (SignedEnum && !SignedBitfield) {
12393 DiagID =
12394 PTAttr == nullptr
12395 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12396 : diag::
12397 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12398 } else if (SignedBitfield && !SignedEnum &&
12399 ED->getNumPositiveBits() == FieldWidth) {
12400 DiagID =
12401 PTAttr == nullptr
12402 ? diag::warn_signed_bitfield_enum_conversion
12403 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12404 }
12405 if (DiagID) {
12406 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
12407 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12408 SourceRange TypeRange =
12409 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12410 S.Diag(Loc: Bitfield->getTypeSpecStartLoc(), DiagID: diag::note_change_bitfield_sign)
12411 << SignedEnum << TypeRange;
12412 if (PTAttr)
12413 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
12414 << ED;
12415 }
12416
12417 // Compute the required bitwidth. If the enum has negative values, we need
12418 // one more bit than the normal number of positive bits to represent the
12419 // sign bit.
12420 unsigned BitsNeeded = SignedEnum ? std::max(a: ED->getNumPositiveBits() + 1,
12421 b: ED->getNumNegativeBits())
12422 : ED->getNumPositiveBits();
12423
12424 // Check the bitwidth.
12425 if (BitsNeeded > FieldWidth) {
12426 Expr *WidthExpr = Bitfield->getBitWidth();
12427 auto DiagID =
12428 PTAttr == nullptr
12429 ? diag::warn_bitfield_too_small_for_enum
12430 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12431 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
12432 S.Diag(Loc: WidthExpr->getExprLoc(), DiagID: diag::note_widen_bitfield)
12433 << BitsNeeded << ED << WidthExpr->getSourceRange();
12434 if (PTAttr)
12435 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
12436 << ED;
12437 }
12438 }
12439
12440 return false;
12441 }
12442
12443 llvm::APSInt Value = Result.Val.getInt();
12444
12445 unsigned OriginalWidth = Value.getBitWidth();
12446
12447 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12448 // false positives where the user is demonstrating they intend to use the
12449 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12450 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12451 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12452 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12453 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12454 if (S.SourceMgr.isInSystemMacro(loc: MaybeMacroLoc) &&
12455 S.findMacroSpelling(loc&: MaybeMacroLoc, name: "true"))
12456 return false;
12457 }
12458
12459 if (!Value.isSigned() || Value.isNegative())
12460 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: OriginalInit))
12461 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12462 OriginalWidth = Value.getSignificantBits();
12463
12464 if (OriginalWidth <= FieldWidth)
12465 return false;
12466
12467 // Compute the value which the bitfield will contain.
12468 llvm::APSInt TruncatedValue = Value.trunc(width: FieldWidth);
12469 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12470
12471 // Check whether the stored value is equal to the original value.
12472 TruncatedValue = TruncatedValue.extend(width: OriginalWidth);
12473 if (llvm::APSInt::isSameValue(I1: Value, I2: TruncatedValue))
12474 return false;
12475
12476 std::string PrettyValue = toString(I: Value, Radix: 10);
12477 std::string PrettyTrunc = toString(I: TruncatedValue, Radix: 10);
12478
12479 S.Diag(Loc: InitLoc, DiagID: OneAssignedToOneBitBitfield
12480 ? diag::warn_impcast_single_bit_bitield_precision_constant
12481 : diag::warn_impcast_bitfield_precision_constant)
12482 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12483 << Init->getSourceRange();
12484
12485 return true;
12486}
12487
12488/// Analyze the given simple or compound assignment for warning-worthy
12489/// operations.
12490static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12491 // Just recurse on the LHS.
12492 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12493
12494 // We want to recurse on the RHS as normal unless we're assigning to
12495 // a bitfield.
12496 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12497 if (AnalyzeBitFieldAssignment(S, Bitfield, Init: E->getRHS(),
12498 InitLoc: E->getOperatorLoc())) {
12499 // Recurse, ignoring any implicit conversions on the RHS.
12500 return AnalyzeImplicitConversions(S, E: E->getRHS()->IgnoreParenImpCasts(),
12501 CC: E->getOperatorLoc());
12502 }
12503 }
12504
12505 // Set context flag for overflow behavior type assignment analysis, use RAII
12506 // pattern to handle nested assignments.
12507 llvm::SaveAndRestore OBTAssignmentContext(
12508 S.InOverflowBehaviorAssignmentContext, true);
12509
12510 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12511
12512 // Diagnose implicitly sequentially-consistent atomic assignment.
12513 if (E->getLHS()->getType()->isAtomicType())
12514 S.Diag(Loc: E->getRHS()->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
12515}
12516
12517/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12518static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12519 QualType T, SourceLocation CContext, unsigned diag,
12520 bool PruneControlFlow = false) {
12521 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12522 // address space annotations isn't really useful. The warnings aren't because
12523 // you're converting a `private int` to `unsigned int`, it is because you're
12524 // conerting `int` to `unsigned int`.
12525 if (SourceType.hasAddressSpace())
12526 SourceType = S.getASTContext().removeAddrSpaceQualType(T: SourceType);
12527 if (T.hasAddressSpace())
12528 T = S.getASTContext().removeAddrSpaceQualType(T);
12529 if (PruneControlFlow) {
12530 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
12531 PD: S.PDiag(DiagID: diag)
12532 << SourceType << T << E->getSourceRange()
12533 << SourceRange(CContext));
12534 return;
12535 }
12536 S.Diag(Loc: E->getExprLoc(), DiagID: diag)
12537 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12538}
12539
12540/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12541static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12542 SourceLocation CContext, unsigned diag,
12543 bool PruneControlFlow = false) {
12544 DiagnoseImpCast(S, E, SourceType: E->getType(), T, CContext, diag, PruneControlFlow);
12545}
12546
12547/// Diagnose an implicit cast from a floating point value to an integer value.
12548static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12549 SourceLocation CContext) {
12550 bool IsBool = T->isSpecificBuiltinType(K: BuiltinType::Bool);
12551 bool PruneWarnings = S.inTemplateInstantiation();
12552
12553 const Expr *InnerE = E->IgnoreParenImpCasts();
12554 // We also want to warn on, e.g., "int i = -1.234"
12555 if (const auto *UOp = dyn_cast<UnaryOperator>(Val: InnerE))
12556 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12557 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12558
12559 bool IsLiteral = isa<FloatingLiteral>(Val: E) || isa<FloatingLiteral>(Val: InnerE);
12560
12561 llvm::APFloat Value(0.0);
12562 bool IsConstant =
12563 E->EvaluateAsFloat(Result&: Value, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects);
12564 if (!IsConstant) {
12565 if (S.ObjC().isSignedCharBool(Ty: T)) {
12566 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
12567 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_float_to_objc_signed_char_bool)
12568 << E->getType());
12569 }
12570
12571 return DiagnoseImpCast(S, E, T, CContext,
12572 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12573 }
12574
12575 bool isExact = false;
12576
12577 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12578 T->hasUnsignedIntegerRepresentation());
12579 llvm::APFloat::opStatus Result = Value.convertToInteger(
12580 Result&: IntegerValue, RM: llvm::APFloat::rmTowardZero, IsExact: &isExact);
12581
12582 // FIXME: Force the precision of the source value down so we don't print
12583 // digits which are usually useless (we don't really care here if we
12584 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12585 // would automatically print the shortest representation, but it's a bit
12586 // tricky to implement.
12587 SmallString<16> PrettySourceValue;
12588 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12589 precision = (precision * 59 + 195) / 196;
12590 Value.toString(Str&: PrettySourceValue, FormatPrecision: precision);
12591
12592 if (S.ObjC().isSignedCharBool(Ty: T) && IntegerValue != 0 && IntegerValue != 1) {
12593 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
12594 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
12595 << PrettySourceValue);
12596 }
12597
12598 if (Result == llvm::APFloat::opOK && isExact) {
12599 if (IsLiteral) return;
12600 return DiagnoseImpCast(S, E, T, CContext, diag: diag::warn_impcast_float_integer,
12601 PruneControlFlow: PruneWarnings);
12602 }
12603
12604 // Conversion of a floating-point value to a non-bool integer where the
12605 // integral part cannot be represented by the integer type is undefined.
12606 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12607 return DiagnoseImpCast(
12608 S, E, T, CContext,
12609 diag: IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12610 : diag::warn_impcast_float_to_integer_out_of_range,
12611 PruneControlFlow: PruneWarnings);
12612
12613 unsigned DiagID = 0;
12614 if (IsLiteral) {
12615 // Warn on floating point literal to integer.
12616 DiagID = diag::warn_impcast_literal_float_to_integer;
12617 } else if (IntegerValue == 0) {
12618 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12619 return DiagnoseImpCast(S, E, T, CContext,
12620 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12621 }
12622 // Warn on non-zero to zero conversion.
12623 DiagID = diag::warn_impcast_float_to_integer_zero;
12624 } else {
12625 if (IntegerValue.isUnsigned()) {
12626 if (!IntegerValue.isMaxValue()) {
12627 return DiagnoseImpCast(S, E, T, CContext,
12628 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12629 }
12630 } else { // IntegerValue.isSigned()
12631 if (!IntegerValue.isMaxSignedValue() &&
12632 !IntegerValue.isMinSignedValue()) {
12633 return DiagnoseImpCast(S, E, T, CContext,
12634 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12635 }
12636 }
12637 // Warn on evaluatable floating point expression to integer conversion.
12638 DiagID = diag::warn_impcast_float_to_integer;
12639 }
12640
12641 SmallString<16> PrettyTargetValue;
12642 if (IsBool)
12643 PrettyTargetValue = Value.isZero() ? "false" : "true";
12644 else
12645 IntegerValue.toString(Str&: PrettyTargetValue);
12646
12647 if (PruneWarnings) {
12648 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
12649 PD: S.PDiag(DiagID)
12650 << E->getType() << T.getUnqualifiedType()
12651 << PrettySourceValue << PrettyTargetValue
12652 << E->getSourceRange() << SourceRange(CContext));
12653 } else {
12654 S.Diag(Loc: E->getExprLoc(), DiagID)
12655 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12656 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12657 }
12658}
12659
12660/// Analyze the given compound assignment for the possible losing of
12661/// floating-point precision.
12662static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12663 assert(isa<CompoundAssignOperator>(E) &&
12664 "Must be compound assignment operation");
12665 // Recurse on the LHS and RHS in here
12666 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12667 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12668
12669 if (E->getLHS()->getType()->isAtomicType())
12670 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
12671
12672 // Now check the outermost expression
12673 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12674 const auto *RBT = cast<CompoundAssignOperator>(Val: E)
12675 ->getComputationResultType()
12676 ->getAs<BuiltinType>();
12677
12678 // The below checks assume source is floating point.
12679 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12680
12681 // If source is floating point but target is an integer.
12682 if (ResultBT->isInteger())
12683 return DiagnoseImpCast(S, E, SourceType: E->getRHS()->getType(), T: E->getLHS()->getType(),
12684 CContext: E->getExprLoc(), diag: diag::warn_impcast_float_integer);
12685
12686 if (!ResultBT->isFloatingPoint())
12687 return;
12688
12689 // If both source and target are floating points, warn about losing precision.
12690 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12691 LHS: QualType(ResultBT, 0), RHS: QualType(RBT, 0));
12692 if (Order < 0 && !S.SourceMgr.isInSystemMacro(loc: E->getOperatorLoc()))
12693 // warn about dropping FP rank.
12694 DiagnoseImpCast(S, E: E->getRHS(), T: E->getLHS()->getType(), CContext: E->getOperatorLoc(),
12695 diag: diag::warn_impcast_float_result_precision);
12696}
12697
12698static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12699 IntRange Range) {
12700 if (!Range.Width) return "0";
12701
12702 llvm::APSInt ValueInRange = Value;
12703 ValueInRange.setIsSigned(!Range.NonNegative);
12704 ValueInRange = ValueInRange.trunc(width: Range.Width);
12705 return toString(I: ValueInRange, Radix: 10);
12706}
12707
12708static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12709 bool ToBool) {
12710 if (!isa<ImplicitCastExpr>(Val: Ex))
12711 return false;
12712
12713 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12714 const Type *Target = S.Context.getCanonicalType(T: Ex->getType()).getTypePtr();
12715 const Type *Source =
12716 S.Context.getCanonicalType(T: InnerE->getType()).getTypePtr();
12717 if (Target->isDependentType())
12718 return false;
12719
12720 const auto *FloatCandidateBT =
12721 dyn_cast<BuiltinType>(Val: ToBool ? Source : Target);
12722 const Type *BoolCandidateType = ToBool ? Target : Source;
12723
12724 return (BoolCandidateType->isSpecificBuiltinType(K: BuiltinType::Bool) &&
12725 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12726}
12727
12728static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12729 SourceLocation CC) {
12730 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12731 const Expr *CurrA = TheCall->getArg(Arg: I);
12732 if (!IsImplicitBoolFloatConversion(S, Ex: CurrA, ToBool: true))
12733 continue;
12734
12735 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12736 S, Ex: TheCall->getArg(Arg: I - 1), ToBool: false));
12737 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12738 S, Ex: TheCall->getArg(Arg: I + 1), ToBool: false));
12739 if (IsSwapped) {
12740 // Warn on this floating-point to bool conversion.
12741 DiagnoseImpCast(S, E: CurrA->IgnoreParenImpCasts(),
12742 T: CurrA->getType(), CContext: CC,
12743 diag: diag::warn_impcast_floating_point_to_bool);
12744 }
12745 }
12746}
12747
12748static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12749 SourceLocation CC) {
12750 // Don't warn on functions which have return type nullptr_t.
12751 if (isa<CallExpr>(Val: E))
12752 return;
12753
12754 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12755 const Expr *NewE = E->IgnoreParenImpCasts();
12756 bool IsGNUNullExpr = isa<GNUNullExpr>(Val: NewE);
12757 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12758 if (!IsGNUNullExpr && !HasNullPtrType)
12759 return;
12760
12761 // Return if target type is a safe conversion.
12762 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12763 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12764 return;
12765
12766 if (S.Diags.isIgnored(DiagID: diag::warn_impcast_null_pointer_to_integer,
12767 Loc: E->getExprLoc()))
12768 return;
12769
12770 SourceLocation Loc = E->getSourceRange().getBegin();
12771
12772 // Venture through the macro stacks to get to the source of macro arguments.
12773 // The new location is a better location than the complete location that was
12774 // passed in.
12775 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12776 CC = S.SourceMgr.getTopMacroCallerLoc(Loc: CC);
12777
12778 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12779 if (IsGNUNullExpr && Loc.isMacroID()) {
12780 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12781 Loc, SM: S.SourceMgr, LangOpts: S.getLangOpts());
12782 if (MacroName == "NULL")
12783 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12784 }
12785
12786 // Only warn if the null and context location are in the same macro expansion.
12787 if (S.SourceMgr.getFileID(SpellingLoc: Loc) != S.SourceMgr.getFileID(SpellingLoc: CC))
12788 return;
12789
12790 S.Diag(Loc, DiagID: diag::warn_impcast_null_pointer_to_integer)
12791 << HasNullPtrType << T << SourceRange(CC)
12792 << FixItHint::CreateReplacement(RemoveRange: Loc,
12793 Code: S.getFixItZeroLiteralForType(T, Loc));
12794}
12795
12796// Helper function to filter out cases for constant width constant conversion.
12797// Don't warn on char array initialization or for non-decimal values.
12798static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12799 SourceLocation CC) {
12800 // If initializing from a constant, and the constant starts with '0',
12801 // then it is a binary, octal, or hexadecimal. Allow these constants
12802 // to fill all the bits, even if there is a sign change.
12803 if (auto *IntLit = dyn_cast<IntegerLiteral>(Val: E->IgnoreParenImpCasts())) {
12804 const char FirstLiteralCharacter =
12805 S.getSourceManager().getCharacterData(SL: IntLit->getBeginLoc())[0];
12806 if (FirstLiteralCharacter == '0')
12807 return false;
12808 }
12809
12810 // If the CC location points to a '{', and the type is char, then assume
12811 // assume it is an array initialization.
12812 if (CC.isValid() && T->isCharType()) {
12813 const char FirstContextCharacter =
12814 S.getSourceManager().getCharacterData(SL: CC)[0];
12815 if (FirstContextCharacter == '{')
12816 return false;
12817 }
12818
12819 return true;
12820}
12821
12822static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12823 const auto *IL = dyn_cast<IntegerLiteral>(Val: E);
12824 if (!IL) {
12825 if (auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
12826 if (UO->getOpcode() == UO_Minus)
12827 return dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
12828 }
12829 }
12830
12831 return IL;
12832}
12833
12834static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12835 E = E->IgnoreParenImpCasts();
12836 SourceLocation ExprLoc = E->getExprLoc();
12837
12838 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
12839 BinaryOperator::Opcode Opc = BO->getOpcode();
12840 Expr::EvalResult Result;
12841 // Do not diagnose unsigned shifts.
12842 if (Opc == BO_Shl) {
12843 const auto *LHS = getIntegerLiteral(E: BO->getLHS());
12844 const auto *RHS = getIntegerLiteral(E: BO->getRHS());
12845 if (LHS && LHS->getValue() == 0)
12846 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always) << 0;
12847 else if (!E->isValueDependent() && LHS && RHS &&
12848 RHS->getValue().isNonNegative() &&
12849 E->EvaluateAsInt(Result, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects))
12850 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always)
12851 << (Result.Val.getInt() != 0);
12852 else if (E->getType()->isSignedIntegerType())
12853 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_in_bool_context)
12854 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "(")
12855 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: E->getEndLoc()),
12856 Code: ") != 0");
12857 }
12858 }
12859
12860 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12861 const auto *LHS = getIntegerLiteral(E: CO->getTrueExpr());
12862 const auto *RHS = getIntegerLiteral(E: CO->getFalseExpr());
12863 if (!LHS || !RHS)
12864 return;
12865 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12866 (RHS->getValue() == 0 || RHS->getValue() == 1))
12867 // Do not diagnose common idioms.
12868 return;
12869 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12870 S.Diag(Loc: ExprLoc, DiagID: diag::warn_integer_constants_in_conditional_always_true);
12871 }
12872}
12873
12874static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source,
12875 const Type *Target, Expr *E,
12876 QualType T,
12877 SourceLocation CC) {
12878 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12879 Source != Target);
12880
12881 // Lone surrogates have a distinct representation in UTF-32.
12882 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
12883 // so don't warn on such conversion.
12884 if (Source->isChar16Type() && Target->isChar32Type())
12885 return;
12886
12887 Expr::EvalResult Result;
12888 if (E->EvaluateAsInt(Result, Ctx: S.getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects,
12889 InConstantContext: S.isConstantEvaluatedContext())) {
12890 llvm::APSInt Value(32);
12891 Value = Result.Val.getInt();
12892 bool IsASCII = Value <= 0x7F;
12893 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
12894 bool ConversionPreservesSemantics =
12895 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12896
12897 if (!ConversionPreservesSemantics) {
12898 auto IsSingleCodeUnitCP = [](const QualType &T,
12899 const llvm::APSInt &Value) {
12900 if (T->isChar8Type())
12901 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12902 if (T->isChar16Type())
12903 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12904 assert(T->isChar32Type());
12905 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12906 };
12907
12908 S.Diag(Loc: CC, DiagID: diag::warn_impcast_unicode_char_type_constant)
12909 << E->getType() << T
12910 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12911 << FormatUTFCodeUnitAsCodepoint(Value: Value.getExtValue(), T: E->getType());
12912 }
12913 } else {
12914 bool LosesPrecision = S.getASTContext().getIntWidth(T: E->getType()) >
12915 S.getASTContext().getIntWidth(T);
12916 DiagnoseImpCast(S, E, T, CContext: CC,
12917 diag: LosesPrecision ? diag::warn_impcast_unicode_precision
12918 : diag::warn_impcast_unicode_char_type);
12919 }
12920}
12921
12922bool Sema::DiscardingCFIUncheckedCallee(QualType From, QualType To) const {
12923 From = Context.getCanonicalType(T: From);
12924 To = Context.getCanonicalType(T: To);
12925 QualType MaybePointee = From->getPointeeType();
12926 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12927 From = MaybePointee;
12928 MaybePointee = To->getPointeeType();
12929 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12930 To = MaybePointee;
12931
12932 if (const auto *FromFn = From->getAs<FunctionType>()) {
12933 if (const auto *ToFn = To->getAs<FunctionType>()) {
12934 if (FromFn->getCFIUncheckedCalleeAttr() &&
12935 !ToFn->getCFIUncheckedCalleeAttr())
12936 return true;
12937 }
12938 }
12939 return false;
12940}
12941
12942void Sema::CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
12943 bool *ICContext, bool IsListInit) {
12944 if (E->isTypeDependent() || E->isValueDependent()) return;
12945
12946 const Type *Source = Context.getCanonicalType(T: E->getType()).getTypePtr();
12947 const Type *Target = Context.getCanonicalType(T).getTypePtr();
12948 if (Source == Target) return;
12949 if (Target->isDependentType()) return;
12950
12951 // If the conversion context location is invalid don't complain. We also
12952 // don't want to emit a warning if the issue occurs from the expansion of
12953 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12954 // delay this check as long as possible. Once we detect we are in that
12955 // scenario, we just return.
12956 if (CC.isInvalid())
12957 return;
12958
12959 if (Source->isAtomicType())
12960 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
12961
12962 // Diagnose implicit casts to bool.
12963 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool)) {
12964 if (isa<StringLiteral>(Val: E))
12965 // Warn on string literal to bool. Checks for string literals in logical
12966 // and expressions, for instance, assert(0 && "error here"), are
12967 // prevented by a check in AnalyzeImplicitConversions().
12968 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
12969 diag: diag::warn_impcast_string_literal_to_bool);
12970 if (isa<ObjCStringLiteral>(Val: E) || isa<ObjCArrayLiteral>(Val: E) ||
12971 isa<ObjCDictionaryLiteral>(Val: E) || isa<ObjCBoxedExpr>(Val: E)) {
12972 // This covers the literal expressions that evaluate to Objective-C
12973 // objects.
12974 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
12975 diag: diag::warn_impcast_objective_c_literal_to_bool);
12976 }
12977 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12978 // Warn on pointer to bool conversion that is always true.
12979 DiagnoseAlwaysNonNullPointer(E, NullType: Expr::NPCK_NotNull, /*IsEqual*/ false,
12980 Range: SourceRange(CC));
12981 }
12982 }
12983
12984 CheckOverflowBehaviorTypeConversion(E, T, CC);
12985
12986 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12987 // is a typedef for signed char (macOS), then that constant value has to be 1
12988 // or 0.
12989 if (ObjC().isSignedCharBool(Ty: T) && Source->isIntegralType(Ctx: Context)) {
12990 Expr::EvalResult Result;
12991 if (E->EvaluateAsInt(Result, Ctx: getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects)) {
12992 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12993 ObjC().adornBoolConversionDiagWithTernaryFixit(
12994 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
12995 << toString(I: Result.Val.getInt(), Radix: 10));
12996 }
12997 return;
12998 }
12999 }
13000
13001 // Check implicit casts from Objective-C collection literals to specialized
13002 // collection types, e.g., NSArray<NSString *> *.
13003 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Val: E))
13004 ObjC().checkArrayLiteral(TargetType: QualType(Target, 0), ArrayLiteral);
13005 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Val: E))
13006 ObjC().checkDictionaryLiteral(TargetType: QualType(Target, 0), DictionaryLiteral);
13007
13008 // Strip vector types.
13009 if (isa<VectorType>(Val: Source)) {
13010 if (Target->isSveVLSBuiltinType() &&
13011 (ARM().areCompatibleSveTypes(FirstType: QualType(Target, 0),
13012 SecondType: QualType(Source, 0)) ||
13013 ARM().areLaxCompatibleSveTypes(FirstType: QualType(Target, 0),
13014 SecondType: QualType(Source, 0))))
13015 return;
13016
13017 if (Target->isRVVVLSBuiltinType() &&
13018 (Context.areCompatibleRVVTypes(FirstType: QualType(Target, 0),
13019 SecondType: QualType(Source, 0)) ||
13020 Context.areLaxCompatibleRVVTypes(FirstType: QualType(Target, 0),
13021 SecondType: QualType(Source, 0))))
13022 return;
13023
13024 if (!isa<VectorType>(Val: Target)) {
13025 if (SourceMgr.isInSystemMacro(loc: CC))
13026 return;
13027 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_vector_scalar);
13028 }
13029 if (getLangOpts().HLSL &&
13030 Target->castAs<VectorType>()->getNumElements() <
13031 Source->castAs<VectorType>()->getNumElements()) {
13032 // Diagnose vector truncation but don't return. We may also want to
13033 // diagnose an element conversion.
13034 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13035 diag: diag::warn_hlsl_impcast_vector_truncation);
13036 }
13037
13038 // If the vector cast is cast between two vectors of the same size, it is
13039 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13040 if (!getLangOpts().HLSL &&
13041 Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13042 return;
13043
13044 Source = cast<VectorType>(Val: Source)->getElementType().getTypePtr();
13045 Target = cast<VectorType>(Val: Target)->getElementType().getTypePtr();
13046 }
13047 if (const auto *VecTy = dyn_cast<VectorType>(Val: Target))
13048 Target = VecTy->getElementType().getTypePtr();
13049
13050 // Strip matrix types.
13051 if (isa<ConstantMatrixType>(Val: Source)) {
13052 if (Target->isScalarType())
13053 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_matrix_scalar);
13054
13055 if (getLangOpts().HLSL && isa<ConstantMatrixType>(Val: Target) &&
13056 Target->castAs<ConstantMatrixType>()->getNumElementsFlattened() <
13057 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13058 // Diagnose Matrix truncation but don't return. We may also want to
13059 // diagnose an element conversion.
13060 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13061 diag: diag::warn_hlsl_impcast_matrix_truncation);
13062 }
13063
13064 Source = cast<ConstantMatrixType>(Val: Source)->getElementType().getTypePtr();
13065 Target = cast<ConstantMatrixType>(Val: Target)->getElementType().getTypePtr();
13066 }
13067 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Val: Target))
13068 Target = MatTy->getElementType().getTypePtr();
13069
13070 // Strip complex types.
13071 if (isa<ComplexType>(Val: Source)) {
13072 if (!isa<ComplexType>(Val: Target)) {
13073 if (SourceMgr.isInSystemMacro(loc: CC) || Target->isBooleanType())
13074 return;
13075
13076 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13077 diag: getLangOpts().CPlusPlus
13078 ? diag::err_impcast_complex_scalar
13079 : diag::warn_impcast_complex_scalar);
13080 }
13081
13082 Source = cast<ComplexType>(Val: Source)->getElementType().getTypePtr();
13083 Target = cast<ComplexType>(Val: Target)->getElementType().getTypePtr();
13084 }
13085
13086 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Val: Source);
13087 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Val: Target);
13088
13089 // Strip SVE vector types
13090 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13091 // Need the original target type for vector type checks
13092 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13093 // Handle conversion from scalable to fixed when msve-vector-bits is
13094 // specified
13095 if (ARM().areCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13096 SecondType: QualType(Source, 0)) ||
13097 ARM().areLaxCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13098 SecondType: QualType(Source, 0)))
13099 return;
13100
13101 // If the vector cast is cast between two vectors of the same size, it is
13102 // a bitcast, not a conversion.
13103 if (Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13104 return;
13105
13106 Source = SourceBT->getSveEltType(Ctx: Context).getTypePtr();
13107 }
13108
13109 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13110 Target = TargetBT->getSveEltType(Ctx: Context).getTypePtr();
13111
13112 // If the source is floating point...
13113 if (SourceBT && SourceBT->isFloatingPoint()) {
13114 // ...and the target is floating point...
13115 if (TargetBT && TargetBT->isFloatingPoint()) {
13116 // ...then warn if we're dropping FP rank.
13117
13118 int Order = getASTContext().getFloatingTypeSemanticOrder(
13119 LHS: QualType(SourceBT, 0), RHS: QualType(TargetBT, 0));
13120 if (Order > 0) {
13121 // Don't warn about float constants that are precisely
13122 // representable in the target type.
13123 Expr::EvalResult result;
13124 if (E->EvaluateAsRValue(Result&: result, Ctx: Context)) {
13125 // Value might be a float, a float vector, or a float complex.
13126 if (IsSameFloatAfterCast(
13127 value: result.Val,
13128 Src: Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)),
13129 Tgt: Context.getFloatTypeSemantics(T: QualType(SourceBT, 0))))
13130 return;
13131 }
13132
13133 if (SourceMgr.isInSystemMacro(loc: CC))
13134 return;
13135
13136 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_float_precision);
13137 }
13138 // ... or possibly if we're increasing rank, too
13139 else if (Order < 0) {
13140 if (SourceMgr.isInSystemMacro(loc: CC))
13141 return;
13142
13143 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_double_promotion);
13144 }
13145 return;
13146 }
13147
13148 // If the target is integral, always warn.
13149 if (TargetBT && TargetBT->isInteger()) {
13150 if (SourceMgr.isInSystemMacro(loc: CC))
13151 return;
13152
13153 DiagnoseFloatingImpCast(S&: *this, E, T, CContext: CC);
13154 }
13155
13156 // Detect the case where a call result is converted from floating-point to
13157 // to bool, and the final argument to the call is converted from bool, to
13158 // discover this typo:
13159 //
13160 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13161 //
13162 // FIXME: This is an incredibly special case; is there some more general
13163 // way to detect this class of misplaced-parentheses bug?
13164 if (Target->isBooleanType() && isa<CallExpr>(Val: E)) {
13165 // Check last argument of function call to see if it is an
13166 // implicit cast from a type matching the type the result
13167 // is being cast to.
13168 CallExpr *CEx = cast<CallExpr>(Val: E);
13169 if (unsigned NumArgs = CEx->getNumArgs()) {
13170 Expr *LastA = CEx->getArg(Arg: NumArgs - 1);
13171 Expr *InnerE = LastA->IgnoreParenImpCasts();
13172 if (isa<ImplicitCastExpr>(Val: LastA) &&
13173 InnerE->getType()->isBooleanType()) {
13174 // Warn on this floating-point to bool conversion
13175 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13176 diag: diag::warn_impcast_floating_point_to_bool);
13177 }
13178 }
13179 }
13180 return;
13181 }
13182
13183 // Valid casts involving fixed point types should be accounted for here.
13184 if (Source->isFixedPointType()) {
13185 if (Target->isUnsaturatedFixedPointType()) {
13186 Expr::EvalResult Result;
13187 if (E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13188 InConstantContext: isConstantEvaluatedContext())) {
13189 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13190 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(Ty: T);
13191 llvm::APFixedPoint MinVal = Context.getFixedPointMin(Ty: T);
13192 if (Value > MaxVal || Value < MinVal) {
13193 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13194 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13195 << Value.toString() << T
13196 << E->getSourceRange()
13197 << clang::SourceRange(CC));
13198 return;
13199 }
13200 }
13201 } else if (Target->isIntegerType()) {
13202 Expr::EvalResult Result;
13203 if (!isConstantEvaluatedContext() &&
13204 E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13205 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13206
13207 bool Overflowed;
13208 llvm::APSInt IntResult = FXResult.convertToInt(
13209 DstWidth: Context.getIntWidth(T), DstSign: Target->isSignedIntegerOrEnumerationType(),
13210 Overflow: &Overflowed);
13211
13212 if (Overflowed) {
13213 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13214 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13215 << FXResult.toString() << T
13216 << E->getSourceRange()
13217 << clang::SourceRange(CC));
13218 return;
13219 }
13220 }
13221 }
13222 } else if (Target->isUnsaturatedFixedPointType()) {
13223 if (Source->isIntegerType()) {
13224 Expr::EvalResult Result;
13225 if (!isConstantEvaluatedContext() &&
13226 E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13227 llvm::APSInt Value = Result.Val.getInt();
13228
13229 bool Overflowed;
13230 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13231 Value, DstFXSema: Context.getFixedPointSemantics(Ty: T), Overflow: &Overflowed);
13232
13233 if (Overflowed) {
13234 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13235 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13236 << toString(I: Value, /*Radix=*/10) << T
13237 << E->getSourceRange()
13238 << clang::SourceRange(CC));
13239 return;
13240 }
13241 }
13242 }
13243 }
13244
13245 // If we are casting an integer type to a floating point type without
13246 // initialization-list syntax, we might lose accuracy if the floating
13247 // point type has a narrower significand than the integer type.
13248 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13249 TargetBT->isFloatingType() && !IsListInit) {
13250 // Determine the number of precision bits in the source integer type.
13251 std::optional<IntRange> SourceRange =
13252 TryGetExprRange(C&: Context, E, InConstantContext: isConstantEvaluatedContext(),
13253 /*Approximate=*/true);
13254 if (!SourceRange)
13255 return;
13256 unsigned int SourcePrecision = SourceRange->Width;
13257
13258 // Determine the number of precision bits in the
13259 // target floating point type.
13260 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13261 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13262
13263 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13264 SourcePrecision > TargetPrecision) {
13265
13266 if (std::optional<llvm::APSInt> SourceInt =
13267 E->getIntegerConstantExpr(Ctx: Context)) {
13268 // If the source integer is a constant, convert it to the target
13269 // floating point type. Issue a warning if the value changes
13270 // during the whole conversion.
13271 llvm::APFloat TargetFloatValue(
13272 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13273 llvm::APFloat::opStatus ConversionStatus =
13274 TargetFloatValue.convertFromAPInt(
13275 Input: *SourceInt, IsSigned: SourceBT->isSignedInteger(),
13276 RM: llvm::APFloat::rmNearestTiesToEven);
13277
13278 if (ConversionStatus != llvm::APFloat::opOK) {
13279 SmallString<32> PrettySourceValue;
13280 SourceInt->toString(Str&: PrettySourceValue, Radix: 10);
13281 SmallString<32> PrettyTargetValue;
13282 TargetFloatValue.toString(Str&: PrettyTargetValue, FormatPrecision: TargetPrecision);
13283
13284 DiagRuntimeBehavior(
13285 Loc: E->getExprLoc(), Statement: E,
13286 PD: PDiag(DiagID: diag::warn_impcast_integer_float_precision_constant)
13287 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13288 << E->getSourceRange() << clang::SourceRange(CC));
13289 }
13290 } else {
13291 // Otherwise, the implicit conversion may lose precision.
13292 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13293 diag: diag::warn_impcast_integer_float_precision);
13294 }
13295 }
13296 }
13297
13298 DiagnoseNullConversion(S&: *this, E, T, CC);
13299
13300 DiscardMisalignedMemberAddress(T: Target, E);
13301
13302 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13303 DiagnoseMixedUnicodeImplicitConversion(S&: *this, Source, Target, E, T, CC);
13304 return;
13305 }
13306
13307 if (Target->isBooleanType())
13308 DiagnoseIntInBoolContext(S&: *this, E);
13309
13310 if (DiscardingCFIUncheckedCallee(From: QualType(Source, 0), To: QualType(Target, 0))) {
13311 Diag(Loc: CC, DiagID: diag::warn_cast_discards_cfi_unchecked_callee)
13312 << QualType(Source, 0) << QualType(Target, 0);
13313 }
13314
13315 if (!Source->isIntegerType() || !Target->isIntegerType())
13316 return;
13317
13318 // TODO: remove this early return once the false positives for constant->bool
13319 // in templates, macros, etc, are reduced or removed.
13320 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool))
13321 return;
13322
13323 if (ObjC().isSignedCharBool(Ty: T) && !Source->isCharType() &&
13324 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13325 return ObjC().adornBoolConversionDiagWithTernaryFixit(
13326 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_int_to_objc_signed_char_bool)
13327 << E->getType());
13328 }
13329 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13330 C&: Context, E, InConstantContext: isConstantEvaluatedContext(), /*Approximate=*/true);
13331 if (!LikelySourceRange)
13332 return;
13333
13334 IntRange SourceTypeRange =
13335 IntRange::forTargetOfCanonicalType(C&: Context, T: Source);
13336 IntRange TargetRange = IntRange::forTargetOfCanonicalType(C&: Context, T: Target);
13337
13338 if (LikelySourceRange->Width > TargetRange.Width) {
13339 // Check if target is a wrapping OBT - if so, don't warn about constant
13340 // conversion as this type may be used intentionally with implicit
13341 // truncation, especially during assignments.
13342 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13343 if (TargetOBT->isWrapKind()) {
13344 return;
13345 }
13346 }
13347
13348 // Check if source expression has an explicit __ob_wrap cast because if so,
13349 // wrapping was explicitly requested and we shouldn't warn
13350 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13351 if (SourceOBT->isWrapKind()) {
13352 return;
13353 }
13354 }
13355
13356 // If the source is a constant, use a default-on diagnostic.
13357 // TODO: this should happen for bitfield stores, too.
13358 Expr::EvalResult Result;
13359 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13360 InConstantContext: isConstantEvaluatedContext())) {
13361 llvm::APSInt Value(32);
13362 Value = Result.Val.getInt();
13363
13364 if (SourceMgr.isInSystemMacro(loc: CC))
13365 return;
13366
13367 std::string PrettySourceValue = toString(I: Value, Radix: 10);
13368 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
13369
13370 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13371 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
13372 << PrettySourceValue << PrettyTargetValue
13373 << E->getType() << T << E->getSourceRange()
13374 << SourceRange(CC));
13375 return;
13376 }
13377
13378 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13379 if (SourceMgr.isInSystemMacro(loc: CC))
13380 return;
13381
13382 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
13383 if (UO->getOpcode() == UO_Minus)
13384 return DiagnoseImpCast(
13385 S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_precision_on_negation);
13386 }
13387
13388 if (TargetRange.Width == 32 && Context.getIntWidth(T: E->getType()) == 64)
13389 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_64_32,
13390 /* pruneControlFlow */ PruneControlFlow: true);
13391 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13392 diag: diag::warn_impcast_integer_precision);
13393 }
13394
13395 if (TargetRange.Width > SourceTypeRange.Width) {
13396 if (auto *UO = dyn_cast<UnaryOperator>(Val: E))
13397 if (UO->getOpcode() == UO_Minus)
13398 if (Source->isUnsignedIntegerType()) {
13399 if (Target->isUnsignedIntegerType())
13400 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13401 diag: diag::warn_impcast_high_order_zero_bits);
13402 if (Target->isSignedIntegerType())
13403 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13404 diag: diag::warn_impcast_nonnegative_result);
13405 }
13406 }
13407
13408 if (TargetRange.Width == LikelySourceRange->Width &&
13409 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13410 Source->isSignedIntegerType()) {
13411 // Warn when doing a signed to signed conversion, warn if the positive
13412 // source value is exactly the width of the target type, which will
13413 // cause a negative value to be stored.
13414
13415 Expr::EvalResult Result;
13416 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects) &&
13417 !SourceMgr.isInSystemMacro(loc: CC)) {
13418 llvm::APSInt Value = Result.Val.getInt();
13419 if (isSameWidthConstantConversion(S&: *this, E, T, CC)) {
13420 std::string PrettySourceValue = toString(I: Value, Radix: 10);
13421 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
13422
13423 Diag(Loc: E->getExprLoc(),
13424 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
13425 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13426 << E->getSourceRange() << SourceRange(CC));
13427 return;
13428 }
13429 }
13430
13431 // Fall through for non-constants to give a sign conversion warning.
13432 }
13433
13434 if ((!isa<EnumType>(Val: Target) || !isa<EnumType>(Val: Source)) &&
13435 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13436 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13437 LikelySourceRange->Width == TargetRange.Width))) {
13438 if (SourceMgr.isInSystemMacro(loc: CC))
13439 return;
13440
13441 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13442 TargetBT->isInteger() &&
13443 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13444 return;
13445 }
13446
13447 unsigned DiagID = diag::warn_impcast_integer_sign;
13448
13449 // Traditionally, gcc has warned about this under -Wsign-compare.
13450 // We also want to warn about it in -Wconversion.
13451 // So if -Wconversion is off, use a completely identical diagnostic
13452 // in the sign-compare group.
13453 // The conditional-checking code will
13454 if (ICContext) {
13455 DiagID = diag::warn_impcast_integer_sign_conditional;
13456 *ICContext = true;
13457 }
13458
13459 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagID);
13460 }
13461
13462 // If we're implicitly converting from an integer into an enumeration, that
13463 // is valid in C but invalid in C++.
13464 QualType SourceType = E->getEnumCoercedType(Ctx: Context);
13465 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13466 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Val: Target))
13467 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_int_to_enum);
13468
13469 // Diagnose conversions between different enumeration types.
13470 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13471 // type, to give us better diagnostics.
13472 Source = Context.getCanonicalType(T: SourceType).getTypePtr();
13473
13474 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13475 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13476 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13477 TargetEnum->getDecl()->hasNameForLinkage() &&
13478 SourceEnum != TargetEnum) {
13479 if (SourceMgr.isInSystemMacro(loc: CC))
13480 return;
13481
13482 return DiagnoseImpCast(S&: *this, E, SourceType, T, CContext: CC,
13483 diag: diag::warn_impcast_different_enum_types);
13484 }
13485}
13486
13487static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13488 SourceLocation CC, QualType T);
13489
13490static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13491 SourceLocation CC, bool &ICContext) {
13492 E = E->IgnoreParenImpCasts();
13493 // Diagnose incomplete type for second or third operand in C.
13494 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13495 S.RequireCompleteExprType(E, DiagID: diag::err_incomplete_type);
13496
13497 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: E))
13498 return CheckConditionalOperator(S, E: CO, CC, T);
13499
13500 AnalyzeImplicitConversions(S, E, CC);
13501 if (E->getType() != T)
13502 return S.CheckImplicitConversion(E, T, CC, ICContext: &ICContext);
13503}
13504
13505static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13506 SourceLocation CC, QualType T) {
13507 AnalyzeImplicitConversions(S, E: E->getCond(), CC: E->getQuestionLoc());
13508
13509 Expr *TrueExpr = E->getTrueExpr();
13510 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(Val: E))
13511 TrueExpr = BCO->getCommon();
13512
13513 bool Suspicious = false;
13514 CheckConditionalOperand(S, E: TrueExpr, T, CC, ICContext&: Suspicious);
13515 CheckConditionalOperand(S, E: E->getFalseExpr(), T, CC, ICContext&: Suspicious);
13516
13517 if (T->isBooleanType())
13518 DiagnoseIntInBoolContext(S, E);
13519
13520 // If -Wconversion would have warned about either of the candidates
13521 // for a signedness conversion to the context type...
13522 if (!Suspicious) return;
13523
13524 // ...but it's currently ignored...
13525 if (!S.Diags.isIgnored(DiagID: diag::warn_impcast_integer_sign_conditional, Loc: CC))
13526 return;
13527
13528 // ...then check whether it would have warned about either of the
13529 // candidates for a signedness conversion to the condition type.
13530 if (E->getType() == T) return;
13531
13532 Suspicious = false;
13533 S.CheckImplicitConversion(E: TrueExpr->IgnoreParenImpCasts(), T: E->getType(), CC,
13534 ICContext: &Suspicious);
13535 if (!Suspicious)
13536 S.CheckImplicitConversion(E: E->getFalseExpr()->IgnoreParenImpCasts(),
13537 T: E->getType(), CC, ICContext: &Suspicious);
13538}
13539
13540/// Check conversion of given expression to boolean.
13541/// Input argument E is a logical expression.
13542static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13543 // Run the bool-like conversion checks only for C since there bools are
13544 // still not used as the return type from "boolean" operators or as the input
13545 // type for conditional operators.
13546 if (S.getLangOpts().CPlusPlus)
13547 return;
13548 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13549 return;
13550 S.CheckImplicitConversion(E: E->IgnoreParenImpCasts(), T: S.Context.BoolTy, CC);
13551}
13552
13553namespace {
13554struct AnalyzeImplicitConversionsWorkItem {
13555 Expr *E;
13556 SourceLocation CC;
13557 bool IsListInit;
13558};
13559}
13560
13561static void CheckCommaOperand(
13562 Sema &S, Expr *E, QualType T, SourceLocation CC,
13563 bool ExtraCheckForImplicitConversion,
13564 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13565 E = E->IgnoreParenImpCasts();
13566 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: false});
13567
13568 if (ExtraCheckForImplicitConversion && E->getType() != T)
13569 S.CheckImplicitConversion(E, T, CC);
13570}
13571
13572/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13573/// that should be visited are added to WorkList.
13574static void AnalyzeImplicitConversions(
13575 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13576 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13577 Expr *OrigE = Item.E;
13578 SourceLocation CC = Item.CC;
13579
13580 QualType T = OrigE->getType();
13581 Expr *E = OrigE->IgnoreParenImpCasts();
13582
13583 // Propagate whether we are in a C++ list initialization expression.
13584 // If so, we do not issue warnings for implicit int-float conversion
13585 // precision loss, because C++11 narrowing already handles it.
13586 //
13587 // HLSL's initialization lists are special, so they shouldn't observe the C++
13588 // behavior here.
13589 bool IsListInit =
13590 Item.IsListInit || (isa<InitListExpr>(Val: OrigE) &&
13591 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13592
13593 if (E->isTypeDependent() || E->isValueDependent())
13594 return;
13595
13596 Expr *SourceExpr = E;
13597 // Examine, but don't traverse into the source expression of an
13598 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13599 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13600 // evaluate it in the context of checking the specific conversion to T though.
13601 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
13602 if (auto *Src = OVE->getSourceExpr())
13603 SourceExpr = Src;
13604
13605 if (const auto *UO = dyn_cast<UnaryOperator>(Val: SourceExpr))
13606 if (UO->getOpcode() == UO_Not &&
13607 UO->getSubExpr()->isKnownToHaveBooleanValue())
13608 S.Diag(Loc: UO->getBeginLoc(), DiagID: diag::warn_bitwise_negation_bool)
13609 << OrigE->getSourceRange() << T->isBooleanType()
13610 << FixItHint::CreateReplacement(RemoveRange: UO->getBeginLoc(), Code: "!");
13611
13612 if (auto *BO = dyn_cast<BinaryOperator>(Val: SourceExpr)) {
13613 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13614 BO->getLHS()->isKnownToHaveBooleanValue() &&
13615 BO->getRHS()->isKnownToHaveBooleanValue() &&
13616 BO->getLHS()->HasSideEffects(Ctx: S.Context) &&
13617 BO->getRHS()->HasSideEffects(Ctx: S.Context)) {
13618 SourceManager &SM = S.getSourceManager();
13619 const LangOptions &LO = S.getLangOpts();
13620 SourceLocation BLoc = BO->getOperatorLoc();
13621 SourceLocation ELoc = Lexer::getLocForEndOfToken(Loc: BLoc, Offset: 0, SM, LangOpts: LO);
13622 StringRef SR = clang::Lexer::getSourceText(
13623 Range: clang::CharSourceRange::getTokenRange(B: BLoc, E: ELoc), SM, LangOpts: LO);
13624 // To reduce false positives, only issue the diagnostic if the operator
13625 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13626 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13627 // in C, along with other macro spellings the user might invent.
13628 if (SR.str() == "&" || SR.str() == "|") {
13629
13630 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_bitwise_instead_of_logical)
13631 << (BO->getOpcode() == BO_And ? "&" : "|")
13632 << OrigE->getSourceRange()
13633 << FixItHint::CreateReplacement(
13634 RemoveRange: BO->getOperatorLoc(),
13635 Code: (BO->getOpcode() == BO_And ? "&&" : "||"));
13636 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::note_cast_operand_to_int);
13637 }
13638 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13639 /// Analyze the given comma operator. The basic idea behind the analysis
13640 /// is to analyze the left and right operands slightly differently. The
13641 /// left operand needs to check whether the operand itself has an implicit
13642 /// conversion, but not whether the left operand induces an implicit
13643 /// conversion for the entire comma expression itself. This is similar to
13644 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13645 /// were directly used for the implicit conversion check.
13646 CheckCommaOperand(S, E: BO->getLHS(), T, CC: BO->getOperatorLoc(),
13647 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13648 CheckCommaOperand(S, E: BO->getRHS(), T, CC: BO->getOperatorLoc(),
13649 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13650 return;
13651 }
13652 }
13653
13654 // For conditional operators, we analyze the arguments as if they
13655 // were being fed directly into the output.
13656 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: SourceExpr)) {
13657 CheckConditionalOperator(S, E: CO, CC, T);
13658 return;
13659 }
13660
13661 // Check implicit argument conversions for function calls.
13662 if (const auto *Call = dyn_cast<CallExpr>(Val: SourceExpr))
13663 CheckImplicitArgumentConversions(S, TheCall: Call, CC);
13664
13665 // Go ahead and check any implicit conversions we might have skipped.
13666 // The non-canonical typecheck is just an optimization;
13667 // CheckImplicitConversion will filter out dead implicit conversions.
13668 if (SourceExpr->getType() != T)
13669 S.CheckImplicitConversion(E: SourceExpr, T, CC, ICContext: nullptr, IsListInit);
13670
13671 // Now continue drilling into this expression.
13672
13673 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E)) {
13674 // The bound subexpressions in a PseudoObjectExpr are not reachable
13675 // as transitive children.
13676 // FIXME: Use a more uniform representation for this.
13677 for (auto *SE : POE->semantics())
13678 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: SE))
13679 WorkList.push_back(Elt: {.E: OVE->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
13680 }
13681
13682 // Skip past explicit casts.
13683 if (auto *CE = dyn_cast<ExplicitCastExpr>(Val: E)) {
13684 E = CE->getSubExpr();
13685 // In the special case of a C++ function-style cast with braces,
13686 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13687 // initializer. This InitListExpr basically belongs to the cast itself, so
13688 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13689 if (isa<CXXFunctionalCastExpr>(Val: CE)) {
13690 if (auto *InitListE = dyn_cast<InitListExpr>(Val: E)) {
13691 if (InitListE->getNumInits() == 1) {
13692 E = InitListE->getInit(Init: 0);
13693 }
13694 }
13695 }
13696 E = E->IgnoreParenImpCasts();
13697 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13698 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13699 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: IsListInit});
13700 return;
13701 }
13702
13703 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(Val: E)) {
13704 WorkList.push_back(Elt: {.E: OutArgE->getArgLValue(), .CC: CC, .IsListInit: IsListInit});
13705 // The base expression is only used to initialize the parameter for
13706 // arguments to `inout` parameters, so we only traverse down the base
13707 // expression for `inout` cases.
13708 if (OutArgE->isInOut())
13709 WorkList.push_back(
13710 Elt: {.E: OutArgE->getCastedTemporary()->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
13711 WorkList.push_back(Elt: {.E: OutArgE->getWritebackCast(), .CC: CC, .IsListInit: IsListInit});
13712 return;
13713 }
13714
13715 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
13716 // Do a somewhat different check with comparison operators.
13717 if (BO->isComparisonOp())
13718 return AnalyzeComparison(S, E: BO);
13719
13720 // And with simple assignments.
13721 if (BO->getOpcode() == BO_Assign)
13722 return AnalyzeAssignment(S, E: BO);
13723 // And with compound assignments.
13724 if (BO->isAssignmentOp())
13725 return AnalyzeCompoundAssignment(S, E: BO);
13726 }
13727
13728 // These break the otherwise-useful invariant below. Fortunately,
13729 // we don't really need to recurse into them, because any internal
13730 // expressions should have been analyzed already when they were
13731 // built into statements.
13732 if (isa<StmtExpr>(Val: E)) return;
13733
13734 // Don't descend into unevaluated contexts.
13735 if (isa<UnaryExprOrTypeTraitExpr>(Val: E)) return;
13736
13737 // Now just recurse over the expression's children.
13738 CC = E->getExprLoc();
13739 BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E);
13740 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13741 for (Stmt *SubStmt : E->children()) {
13742 Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: SubStmt);
13743 if (!ChildExpr)
13744 continue;
13745
13746 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(Val: E))
13747 if (ChildExpr == CSE->getOperand())
13748 // Do not recurse over a CoroutineSuspendExpr's operand.
13749 // The operand is also a subexpression of getCommonExpr(), and
13750 // recursing into it directly would produce duplicate diagnostics.
13751 continue;
13752
13753 if (IsLogicalAndOperator &&
13754 isa<StringLiteral>(Val: ChildExpr->IgnoreParenImpCasts()))
13755 // Ignore checking string literals that are in logical and operators.
13756 // This is a common pattern for asserts.
13757 continue;
13758 WorkList.push_back(Elt: {.E: ChildExpr, .CC: CC, .IsListInit: IsListInit});
13759 }
13760
13761 if (BO && BO->isLogicalOp()) {
13762 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13763 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
13764 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
13765
13766 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13767 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
13768 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
13769 }
13770
13771 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(Val: E)) {
13772 if (U->getOpcode() == UO_LNot) {
13773 ::CheckBoolLikeConversion(S, E: U->getSubExpr(), CC);
13774 } else if (U->getOpcode() != UO_AddrOf) {
13775 if (U->getSubExpr()->getType()->isAtomicType())
13776 S.Diag(Loc: U->getSubExpr()->getBeginLoc(),
13777 DiagID: diag::warn_atomic_implicit_seq_cst);
13778 }
13779 }
13780}
13781
13782/// AnalyzeImplicitConversions - Find and report any interesting
13783/// implicit conversions in the given expression. There are a couple
13784/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13785static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13786 bool IsListInit/*= false*/) {
13787 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13788 WorkList.push_back(Elt: {.E: OrigE, .CC: CC, .IsListInit: IsListInit});
13789 while (!WorkList.empty())
13790 AnalyzeImplicitConversions(S, Item: WorkList.pop_back_val(), WorkList);
13791}
13792
13793// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13794// Returns true when emitting a warning about taking the address of a reference.
13795static bool CheckForReference(Sema &SemaRef, const Expr *E,
13796 const PartialDiagnostic &PD) {
13797 E = E->IgnoreParenImpCasts();
13798
13799 const FunctionDecl *FD = nullptr;
13800
13801 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
13802 if (!DRE->getDecl()->getType()->isReferenceType())
13803 return false;
13804 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
13805 if (!M->getMemberDecl()->getType()->isReferenceType())
13806 return false;
13807 } else if (const CallExpr *Call = dyn_cast<CallExpr>(Val: E)) {
13808 if (!Call->getCallReturnType(Ctx: SemaRef.Context)->isReferenceType())
13809 return false;
13810 FD = Call->getDirectCallee();
13811 } else {
13812 return false;
13813 }
13814
13815 SemaRef.Diag(Loc: E->getExprLoc(), PD);
13816
13817 // If possible, point to location of function.
13818 if (FD) {
13819 SemaRef.Diag(Loc: FD->getLocation(), DiagID: diag::note_reference_is_return_value) << FD;
13820 }
13821
13822 return true;
13823}
13824
13825// Returns true if the SourceLocation is expanded from any macro body.
13826// Returns false if the SourceLocation is invalid, is from not in a macro
13827// expansion, or is from expanded from a top-level macro argument.
13828static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13829 if (Loc.isInvalid())
13830 return false;
13831
13832 while (Loc.isMacroID()) {
13833 if (SM.isMacroBodyExpansion(Loc))
13834 return true;
13835 Loc = SM.getImmediateMacroCallerLoc(Loc);
13836 }
13837
13838 return false;
13839}
13840
13841void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13842 Expr::NullPointerConstantKind NullKind,
13843 bool IsEqual, SourceRange Range) {
13844 if (!E)
13845 return;
13846
13847 // Don't warn inside macros.
13848 if (E->getExprLoc().isMacroID()) {
13849 const SourceManager &SM = getSourceManager();
13850 if (IsInAnyMacroBody(SM, Loc: E->getExprLoc()) ||
13851 IsInAnyMacroBody(SM, Loc: Range.getBegin()))
13852 return;
13853 }
13854 E = E->IgnoreImpCasts();
13855
13856 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13857
13858 if (isa<CXXThisExpr>(Val: E)) {
13859 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13860 : diag::warn_this_bool_conversion;
13861 Diag(Loc: E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13862 return;
13863 }
13864
13865 bool IsAddressOf = false;
13866
13867 if (auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParens())) {
13868 if (UO->getOpcode() != UO_AddrOf)
13869 return;
13870 IsAddressOf = true;
13871 E = UO->getSubExpr();
13872 }
13873
13874 if (IsAddressOf) {
13875 unsigned DiagID = IsCompare
13876 ? diag::warn_address_of_reference_null_compare
13877 : diag::warn_address_of_reference_bool_conversion;
13878 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13879 << IsEqual;
13880 if (CheckForReference(SemaRef&: *this, E, PD)) {
13881 return;
13882 }
13883 }
13884
13885 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13886 bool IsParam = isa<NonNullAttr>(Val: NonnullAttr);
13887 std::string Str;
13888 llvm::raw_string_ostream S(Str);
13889 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
13890 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13891 : diag::warn_cast_nonnull_to_bool;
13892 Diag(Loc: E->getExprLoc(), DiagID) << IsParam << S.str()
13893 << E->getSourceRange() << Range << IsEqual;
13894 Diag(Loc: NonnullAttr->getLocation(), DiagID: diag::note_declared_nonnull) << IsParam;
13895 };
13896
13897 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13898 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts())) {
13899 if (auto *Callee = Call->getDirectCallee()) {
13900 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13901 ComplainAboutNonnullParamOrCall(A);
13902 return;
13903 }
13904 }
13905 }
13906
13907 // Complain if we are converting a lambda expression to a boolean value
13908 // outside of instantiation.
13909 if (!inTemplateInstantiation()) {
13910 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(Val: E)) {
13911 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13912 MRecordDecl && MRecordDecl->isLambda()) {
13913 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_impcast_pointer_to_bool)
13914 << /*LambdaPointerConversionOperatorType=*/3
13915 << MRecordDecl->getSourceRange() << Range << IsEqual;
13916 return;
13917 }
13918 }
13919 }
13920
13921 // Expect to find a single Decl. Skip anything more complicated.
13922 ValueDecl *D = nullptr;
13923 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(Val: E)) {
13924 D = R->getDecl();
13925 } else if (MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
13926 D = M->getMemberDecl();
13927 }
13928
13929 // Weak Decls can be null.
13930 if (!D || D->isWeak())
13931 return;
13932
13933 // Check for parameter decl with nonnull attribute
13934 if (const auto* PV = dyn_cast<ParmVarDecl>(Val: D)) {
13935 if (getCurFunction() &&
13936 !getCurFunction()->ModifiedNonNullParams.count(Ptr: PV)) {
13937 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13938 ComplainAboutNonnullParamOrCall(A);
13939 return;
13940 }
13941
13942 if (const auto *FD = dyn_cast<FunctionDecl>(Val: PV->getDeclContext())) {
13943 // Skip function template not specialized yet.
13944 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13945 return;
13946 auto ParamIter = llvm::find(Range: FD->parameters(), Val: PV);
13947 assert(ParamIter != FD->param_end());
13948 unsigned ParamNo = std::distance(first: FD->param_begin(), last: ParamIter);
13949
13950 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13951 if (!NonNull->args_size()) {
13952 ComplainAboutNonnullParamOrCall(NonNull);
13953 return;
13954 }
13955
13956 for (const ParamIdx &ArgNo : NonNull->args()) {
13957 if (ArgNo.getASTIndex() == ParamNo) {
13958 ComplainAboutNonnullParamOrCall(NonNull);
13959 return;
13960 }
13961 }
13962 }
13963 }
13964 }
13965 }
13966
13967 QualType T = D->getType();
13968 const bool IsArray = T->isArrayType();
13969 const bool IsFunction = T->isFunctionType();
13970
13971 // Address of function is used to silence the function warning.
13972 if (IsAddressOf && IsFunction) {
13973 return;
13974 }
13975
13976 // Found nothing.
13977 if (!IsAddressOf && !IsFunction && !IsArray)
13978 return;
13979
13980 // Pretty print the expression for the diagnostic.
13981 std::string Str;
13982 llvm::raw_string_ostream S(Str);
13983 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
13984
13985 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13986 : diag::warn_impcast_pointer_to_bool;
13987 enum {
13988 AddressOf,
13989 FunctionPointer,
13990 ArrayPointer
13991 } DiagType;
13992 if (IsAddressOf)
13993 DiagType = AddressOf;
13994 else if (IsFunction)
13995 DiagType = FunctionPointer;
13996 else if (IsArray)
13997 DiagType = ArrayPointer;
13998 else
13999 llvm_unreachable("Could not determine diagnostic.");
14000 Diag(Loc: E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14001 << Range << IsEqual;
14002
14003 if (!IsFunction)
14004 return;
14005
14006 // Suggest '&' to silence the function warning.
14007 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_warning_silence)
14008 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "&");
14009
14010 // Check to see if '()' fixit should be emitted.
14011 QualType ReturnType;
14012 UnresolvedSet<4> NonTemplateOverloads;
14013 tryExprAsCall(E&: *E, ZeroArgCallReturnTy&: ReturnType, NonTemplateOverloads);
14014 if (ReturnType.isNull())
14015 return;
14016
14017 if (IsCompare) {
14018 // There are two cases here. If there is null constant, the only suggest
14019 // for a pointer return type. If the null is 0, then suggest if the return
14020 // type is a pointer or an integer type.
14021 if (!ReturnType->isPointerType()) {
14022 if (NullKind == Expr::NPCK_ZeroExpression ||
14023 NullKind == Expr::NPCK_ZeroLiteral) {
14024 if (!ReturnType->isIntegerType())
14025 return;
14026 } else {
14027 return;
14028 }
14029 }
14030 } else { // !IsCompare
14031 // For function to bool, only suggest if the function pointer has bool
14032 // return type.
14033 if (!ReturnType->isSpecificBuiltinType(K: BuiltinType::Bool))
14034 return;
14035 }
14036 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_to_function_call)
14037 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: E->getEndLoc()), Code: "()");
14038}
14039
14040bool Sema::CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
14041 SourceLocation CC) {
14042 QualType Source = E->getType();
14043 QualType Target = T;
14044
14045 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14046 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14047 // Overflow behavior type is being stripped - issue warning
14048 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14049 Target->isUnsignedIntegerType()) {
14050 // For unsigned wrap to unsigned conversions, use pedantic version
14051 unsigned DiagId =
14052 InOverflowBehaviorAssignmentContext
14053 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14054 : diag::warn_impcast_overflow_behavior_pedantic;
14055 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14056 } else {
14057 unsigned DiagId = InOverflowBehaviorAssignmentContext
14058 ? diag::warn_impcast_overflow_behavior_assignment
14059 : diag::warn_impcast_overflow_behavior;
14060 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14061 }
14062 }
14063 }
14064
14065 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14066 if (TargetOBT->isWrapKind()) {
14067 return true;
14068 }
14069 }
14070
14071 return false;
14072}
14073
14074void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14075 // Don't diagnose in unevaluated contexts.
14076 if (isUnevaluatedContext())
14077 return;
14078
14079 // Don't diagnose for value- or type-dependent expressions.
14080 if (E->isTypeDependent() || E->isValueDependent())
14081 return;
14082
14083 // Check for array bounds violations in cases where the check isn't triggered
14084 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14085 // ArraySubscriptExpr is on the RHS of a variable initialization.
14086 CheckArrayAccess(E);
14087
14088 // This is not the right CC for (e.g.) a variable initialization.
14089 AnalyzeImplicitConversions(S&: *this, OrigE: E, CC);
14090}
14091
14092void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14093 ::CheckBoolLikeConversion(S&: *this, E, CC);
14094}
14095
14096void Sema::CheckForIntOverflow (const Expr *E) {
14097 // Use a work list to deal with nested struct initializers.
14098 SmallVector<const Expr *, 2> Exprs(1, E);
14099
14100 do {
14101 const Expr *OriginalE = Exprs.pop_back_val();
14102 const Expr *E = OriginalE->IgnoreParenCasts();
14103
14104 if (isa<BinaryOperator, UnaryOperator>(Val: E)) {
14105 E->EvaluateForOverflow(Ctx: Context);
14106 continue;
14107 }
14108
14109 if (const auto *InitList = dyn_cast<InitListExpr>(Val: OriginalE))
14110 Exprs.append(in_start: InitList->inits().begin(), in_end: InitList->inits().end());
14111 else if (isa<ObjCBoxedExpr>(Val: OriginalE))
14112 E->EvaluateForOverflow(Ctx: Context);
14113 else if (const auto *Call = dyn_cast<CallExpr>(Val: E))
14114 Exprs.append(in_start: Call->arg_begin(), in_end: Call->arg_end());
14115 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(Val: E))
14116 Exprs.append(in_start: Message->arg_begin(), in_end: Message->arg_end());
14117 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(Val: E))
14118 Exprs.append(in_start: Construct->arg_begin(), in_end: Construct->arg_end());
14119 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(Val: E))
14120 Exprs.push_back(Elt: Temporary->getSubExpr());
14121 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(Val: E))
14122 Exprs.push_back(Elt: Array->getIdx());
14123 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(Val: E))
14124 Exprs.push_back(Elt: Compound->getInitializer());
14125 else if (const auto *New = dyn_cast<CXXNewExpr>(Val: E);
14126 New && New->isArray()) {
14127 if (auto ArraySize = New->getArraySize())
14128 Exprs.push_back(Elt: *ArraySize);
14129 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: OriginalE))
14130 Exprs.push_back(Elt: MTE->getSubExpr());
14131 } while (!Exprs.empty());
14132}
14133
14134namespace {
14135
14136/// Visitor for expressions which looks for unsequenced operations on the
14137/// same object.
14138class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14139 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14140
14141 /// A tree of sequenced regions within an expression. Two regions are
14142 /// unsequenced if one is an ancestor or a descendent of the other. When we
14143 /// finish processing an expression with sequencing, such as a comma
14144 /// expression, we fold its tree nodes into its parent, since they are
14145 /// unsequenced with respect to nodes we will visit later.
14146 class SequenceTree {
14147 struct Value {
14148 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14149 unsigned Parent : 31;
14150 LLVM_PREFERRED_TYPE(bool)
14151 unsigned Merged : 1;
14152 };
14153 SmallVector<Value, 8> Values;
14154
14155 public:
14156 /// A region within an expression which may be sequenced with respect
14157 /// to some other region.
14158 class Seq {
14159 friend class SequenceTree;
14160
14161 unsigned Index;
14162
14163 explicit Seq(unsigned N) : Index(N) {}
14164
14165 public:
14166 Seq() : Index(0) {}
14167 };
14168
14169 SequenceTree() { Values.push_back(Elt: Value(0)); }
14170 Seq root() const { return Seq(0); }
14171
14172 /// Create a new sequence of operations, which is an unsequenced
14173 /// subset of \p Parent. This sequence of operations is sequenced with
14174 /// respect to other children of \p Parent.
14175 Seq allocate(Seq Parent) {
14176 Values.push_back(Elt: Value(Parent.Index));
14177 return Seq(Values.size() - 1);
14178 }
14179
14180 /// Merge a sequence of operations into its parent.
14181 void merge(Seq S) {
14182 Values[S.Index].Merged = true;
14183 }
14184
14185 /// Determine whether two operations are unsequenced. This operation
14186 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14187 /// should have been merged into its parent as appropriate.
14188 bool isUnsequenced(Seq Cur, Seq Old) {
14189 unsigned C = representative(K: Cur.Index);
14190 unsigned Target = representative(K: Old.Index);
14191 while (C >= Target) {
14192 if (C == Target)
14193 return true;
14194 C = Values[C].Parent;
14195 }
14196 return false;
14197 }
14198
14199 private:
14200 /// Pick a representative for a sequence.
14201 unsigned representative(unsigned K) {
14202 if (Values[K].Merged)
14203 // Perform path compression as we go.
14204 return Values[K].Parent = representative(K: Values[K].Parent);
14205 return K;
14206 }
14207 };
14208
14209 /// An object for which we can track unsequenced uses.
14210 using Object = const NamedDecl *;
14211
14212 /// Different flavors of object usage which we track. We only track the
14213 /// least-sequenced usage of each kind.
14214 enum UsageKind {
14215 /// A read of an object. Multiple unsequenced reads are OK.
14216 UK_Use,
14217
14218 /// A modification of an object which is sequenced before the value
14219 /// computation of the expression, such as ++n in C++.
14220 UK_ModAsValue,
14221
14222 /// A modification of an object which is not sequenced before the value
14223 /// computation of the expression, such as n++.
14224 UK_ModAsSideEffect,
14225
14226 UK_Count = UK_ModAsSideEffect + 1
14227 };
14228
14229 /// Bundle together a sequencing region and the expression corresponding
14230 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14231 struct Usage {
14232 const Expr *UsageExpr = nullptr;
14233 SequenceTree::Seq Seq;
14234
14235 Usage() = default;
14236 };
14237
14238 struct UsageInfo {
14239 Usage Uses[UK_Count];
14240
14241 /// Have we issued a diagnostic for this object already?
14242 bool Diagnosed = false;
14243
14244 UsageInfo();
14245 };
14246 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14247
14248 Sema &SemaRef;
14249
14250 /// Sequenced regions within the expression.
14251 SequenceTree Tree;
14252
14253 /// Declaration modifications and references which we have seen.
14254 UsageInfoMap UsageMap;
14255
14256 /// The region we are currently within.
14257 SequenceTree::Seq Region;
14258
14259 /// Filled in with declarations which were modified as a side-effect
14260 /// (that is, post-increment operations).
14261 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14262
14263 /// Expressions to check later. We defer checking these to reduce
14264 /// stack usage.
14265 SmallVectorImpl<const Expr *> &WorkList;
14266
14267 /// RAII object wrapping the visitation of a sequenced subexpression of an
14268 /// expression. At the end of this process, the side-effects of the evaluation
14269 /// become sequenced with respect to the value computation of the result, so
14270 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14271 /// UK_ModAsValue.
14272 struct SequencedSubexpression {
14273 SequencedSubexpression(SequenceChecker &Self)
14274 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14275 Self.ModAsSideEffect = &ModAsSideEffect;
14276 }
14277
14278 ~SequencedSubexpression() {
14279 for (const std::pair<Object, Usage> &M : llvm::reverse(C&: ModAsSideEffect)) {
14280 // Add a new usage with usage kind UK_ModAsValue, and then restore
14281 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14282 // the previous one was empty).
14283 UsageInfo &UI = Self.UsageMap[M.first];
14284 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14285 Self.addUsage(O: M.first, UI, UsageExpr: SideEffectUsage.UsageExpr, UK: UK_ModAsValue);
14286 SideEffectUsage = M.second;
14287 }
14288 Self.ModAsSideEffect = OldModAsSideEffect;
14289 }
14290
14291 SequenceChecker &Self;
14292 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14293 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14294 };
14295
14296 /// RAII object wrapping the visitation of a subexpression which we might
14297 /// choose to evaluate as a constant. If any subexpression is evaluated and
14298 /// found to be non-constant, this allows us to suppress the evaluation of
14299 /// the outer expression.
14300 class EvaluationTracker {
14301 public:
14302 EvaluationTracker(SequenceChecker &Self)
14303 : Self(Self), Prev(Self.EvalTracker) {
14304 Self.EvalTracker = this;
14305 }
14306
14307 ~EvaluationTracker() {
14308 Self.EvalTracker = Prev;
14309 if (Prev)
14310 Prev->EvalOK &= EvalOK;
14311 }
14312
14313 bool evaluate(const Expr *E, bool &Result) {
14314 if (!EvalOK || E->isValueDependent())
14315 return false;
14316 EvalOK = E->EvaluateAsBooleanCondition(
14317 Result, Ctx: Self.SemaRef.Context,
14318 InConstantContext: Self.SemaRef.isConstantEvaluatedContext());
14319 return EvalOK;
14320 }
14321
14322 private:
14323 SequenceChecker &Self;
14324 EvaluationTracker *Prev;
14325 bool EvalOK = true;
14326 } *EvalTracker = nullptr;
14327
14328 /// Find the object which is produced by the specified expression,
14329 /// if any.
14330 Object getObject(const Expr *E, bool Mod) const {
14331 E = E->IgnoreParenCasts();
14332 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) {
14333 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14334 return getObject(E: UO->getSubExpr(), Mod);
14335 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
14336 if (BO->getOpcode() == BO_Comma)
14337 return getObject(E: BO->getRHS(), Mod);
14338 if (Mod && BO->isAssignmentOp())
14339 return getObject(E: BO->getLHS(), Mod);
14340 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14341 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14342 if (isa<CXXThisExpr>(Val: ME->getBase()->IgnoreParenCasts()))
14343 return ME->getMemberDecl();
14344 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14345 // FIXME: If this is a reference, map through to its value.
14346 return DRE->getDecl();
14347 return nullptr;
14348 }
14349
14350 /// Note that an object \p O was modified or used by an expression
14351 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14352 /// the object \p O as obtained via the \p UsageMap.
14353 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14354 // Get the old usage for the given object and usage kind.
14355 Usage &U = UI.Uses[UK];
14356 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq)) {
14357 // If we have a modification as side effect and are in a sequenced
14358 // subexpression, save the old Usage so that we can restore it later
14359 // in SequencedSubexpression::~SequencedSubexpression.
14360 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14361 ModAsSideEffect->push_back(Elt: std::make_pair(x&: O, y&: U));
14362 // Then record the new usage with the current sequencing region.
14363 U.UsageExpr = UsageExpr;
14364 U.Seq = Region;
14365 }
14366 }
14367
14368 /// Check whether a modification or use of an object \p O in an expression
14369 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14370 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14371 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14372 /// usage and false we are checking for a mod-use unsequenced usage.
14373 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14374 UsageKind OtherKind, bool IsModMod) {
14375 if (UI.Diagnosed)
14376 return;
14377
14378 const Usage &U = UI.Uses[OtherKind];
14379 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq))
14380 return;
14381
14382 const Expr *Mod = U.UsageExpr;
14383 const Expr *ModOrUse = UsageExpr;
14384 if (OtherKind == UK_Use)
14385 std::swap(a&: Mod, b&: ModOrUse);
14386
14387 SemaRef.DiagRuntimeBehavior(
14388 Loc: Mod->getExprLoc(), Stmts: {Mod, ModOrUse},
14389 PD: SemaRef.PDiag(DiagID: IsModMod ? diag::warn_unsequenced_mod_mod
14390 : diag::warn_unsequenced_mod_use)
14391 << O << SourceRange(ModOrUse->getExprLoc()));
14392 UI.Diagnosed = true;
14393 }
14394
14395 // A note on note{Pre, Post}{Use, Mod}:
14396 //
14397 // (It helps to follow the algorithm with an expression such as
14398 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14399 // operations before C++17 and both are well-defined in C++17).
14400 //
14401 // When visiting a node which uses/modify an object we first call notePreUse
14402 // or notePreMod before visiting its sub-expression(s). At this point the
14403 // children of the current node have not yet been visited and so the eventual
14404 // uses/modifications resulting from the children of the current node have not
14405 // been recorded yet.
14406 //
14407 // We then visit the children of the current node. After that notePostUse or
14408 // notePostMod is called. These will 1) detect an unsequenced modification
14409 // as side effect (as in "k++ + k") and 2) add a new usage with the
14410 // appropriate usage kind.
14411 //
14412 // We also have to be careful that some operation sequences modification as
14413 // side effect as well (for example: || or ,). To account for this we wrap
14414 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14415 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14416 // which record usages which are modifications as side effect, and then
14417 // downgrade them (or more accurately restore the previous usage which was a
14418 // modification as side effect) when exiting the scope of the sequenced
14419 // subexpression.
14420
14421 void notePreUse(Object O, const Expr *UseExpr) {
14422 UsageInfo &UI = UsageMap[O];
14423 // Uses conflict with other modifications.
14424 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14425 }
14426
14427 void notePostUse(Object O, const Expr *UseExpr) {
14428 UsageInfo &UI = UsageMap[O];
14429 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14430 /*IsModMod=*/false);
14431 addUsage(O, UI, UsageExpr: UseExpr, /*UsageKind=*/UK: UK_Use);
14432 }
14433
14434 void notePreMod(Object O, const Expr *ModExpr) {
14435 UsageInfo &UI = UsageMap[O];
14436 // Modifications conflict with other modifications and with uses.
14437 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14438 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14439 }
14440
14441 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14442 UsageInfo &UI = UsageMap[O];
14443 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14444 /*IsModMod=*/true);
14445 addUsage(O, UI, UsageExpr: ModExpr, /*UsageKind=*/UK);
14446 }
14447
14448public:
14449 SequenceChecker(Sema &S, const Expr *E,
14450 SmallVectorImpl<const Expr *> &WorkList)
14451 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14452 Visit(S: E);
14453 // Silence a -Wunused-private-field since WorkList is now unused.
14454 // TODO: Evaluate if it can be used, and if not remove it.
14455 (void)this->WorkList;
14456 }
14457
14458 void VisitStmt(const Stmt *S) {
14459 // Skip all statements which aren't expressions for now.
14460 }
14461
14462 void VisitExpr(const Expr *E) {
14463 // By default, just recurse to evaluated subexpressions.
14464 Base::VisitStmt(S: E);
14465 }
14466
14467 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14468 for (auto *Sub : CSE->children()) {
14469 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: Sub);
14470 if (!ChildExpr)
14471 continue;
14472
14473 if (ChildExpr == CSE->getOperand())
14474 // Do not recurse over a CoroutineSuspendExpr's operand.
14475 // The operand is also a subexpression of getCommonExpr(), and
14476 // recursing into it directly could confuse object management
14477 // for the sake of sequence tracking.
14478 continue;
14479
14480 Visit(S: Sub);
14481 }
14482 }
14483
14484 void VisitCastExpr(const CastExpr *E) {
14485 Object O = Object();
14486 if (E->getCastKind() == CK_LValueToRValue)
14487 O = getObject(E: E->getSubExpr(), Mod: false);
14488
14489 if (O)
14490 notePreUse(O, UseExpr: E);
14491 VisitExpr(E);
14492 if (O)
14493 notePostUse(O, UseExpr: E);
14494 }
14495
14496 void VisitSequencedExpressions(const Expr *SequencedBefore,
14497 const Expr *SequencedAfter) {
14498 SequenceTree::Seq BeforeRegion = Tree.allocate(Parent: Region);
14499 SequenceTree::Seq AfterRegion = Tree.allocate(Parent: Region);
14500 SequenceTree::Seq OldRegion = Region;
14501
14502 {
14503 SequencedSubexpression SeqBefore(*this);
14504 Region = BeforeRegion;
14505 Visit(S: SequencedBefore);
14506 }
14507
14508 Region = AfterRegion;
14509 Visit(S: SequencedAfter);
14510
14511 Region = OldRegion;
14512
14513 Tree.merge(S: BeforeRegion);
14514 Tree.merge(S: AfterRegion);
14515 }
14516
14517 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14518 // C++17 [expr.sub]p1:
14519 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14520 // expression E1 is sequenced before the expression E2.
14521 if (SemaRef.getLangOpts().CPlusPlus17)
14522 VisitSequencedExpressions(SequencedBefore: ASE->getLHS(), SequencedAfter: ASE->getRHS());
14523 else {
14524 Visit(S: ASE->getLHS());
14525 Visit(S: ASE->getRHS());
14526 }
14527 }
14528
14529 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14530 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14531 void VisitBinPtrMem(const BinaryOperator *BO) {
14532 // C++17 [expr.mptr.oper]p4:
14533 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14534 // the expression E1 is sequenced before the expression E2.
14535 if (SemaRef.getLangOpts().CPlusPlus17)
14536 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
14537 else {
14538 Visit(S: BO->getLHS());
14539 Visit(S: BO->getRHS());
14540 }
14541 }
14542
14543 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14544 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14545 void VisitBinShlShr(const BinaryOperator *BO) {
14546 // C++17 [expr.shift]p4:
14547 // The expression E1 is sequenced before the expression E2.
14548 if (SemaRef.getLangOpts().CPlusPlus17)
14549 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
14550 else {
14551 Visit(S: BO->getLHS());
14552 Visit(S: BO->getRHS());
14553 }
14554 }
14555
14556 void VisitBinComma(const BinaryOperator *BO) {
14557 // C++11 [expr.comma]p1:
14558 // Every value computation and side effect associated with the left
14559 // expression is sequenced before every value computation and side
14560 // effect associated with the right expression.
14561 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
14562 }
14563
14564 void VisitBinAssign(const BinaryOperator *BO) {
14565 SequenceTree::Seq RHSRegion;
14566 SequenceTree::Seq LHSRegion;
14567 if (SemaRef.getLangOpts().CPlusPlus17) {
14568 RHSRegion = Tree.allocate(Parent: Region);
14569 LHSRegion = Tree.allocate(Parent: Region);
14570 } else {
14571 RHSRegion = Region;
14572 LHSRegion = Region;
14573 }
14574 SequenceTree::Seq OldRegion = Region;
14575
14576 // C++11 [expr.ass]p1:
14577 // [...] the assignment is sequenced after the value computation
14578 // of the right and left operands, [...]
14579 //
14580 // so check it before inspecting the operands and update the
14581 // map afterwards.
14582 Object O = getObject(E: BO->getLHS(), /*Mod=*/true);
14583 if (O)
14584 notePreMod(O, ModExpr: BO);
14585
14586 if (SemaRef.getLangOpts().CPlusPlus17) {
14587 // C++17 [expr.ass]p1:
14588 // [...] The right operand is sequenced before the left operand. [...]
14589 {
14590 SequencedSubexpression SeqBefore(*this);
14591 Region = RHSRegion;
14592 Visit(S: BO->getRHS());
14593 }
14594
14595 Region = LHSRegion;
14596 Visit(S: BO->getLHS());
14597
14598 if (O && isa<CompoundAssignOperator>(Val: BO))
14599 notePostUse(O, UseExpr: BO);
14600
14601 } else {
14602 // C++11 does not specify any sequencing between the LHS and RHS.
14603 Region = LHSRegion;
14604 Visit(S: BO->getLHS());
14605
14606 if (O && isa<CompoundAssignOperator>(Val: BO))
14607 notePostUse(O, UseExpr: BO);
14608
14609 Region = RHSRegion;
14610 Visit(S: BO->getRHS());
14611 }
14612
14613 // C++11 [expr.ass]p1:
14614 // the assignment is sequenced [...] before the value computation of the
14615 // assignment expression.
14616 // C11 6.5.16/3 has no such rule.
14617 Region = OldRegion;
14618 if (O)
14619 notePostMod(O, ModExpr: BO,
14620 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14621 : UK_ModAsSideEffect);
14622 if (SemaRef.getLangOpts().CPlusPlus17) {
14623 Tree.merge(S: RHSRegion);
14624 Tree.merge(S: LHSRegion);
14625 }
14626 }
14627
14628 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14629 VisitBinAssign(BO: CAO);
14630 }
14631
14632 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14633 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14634 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14635 Object O = getObject(E: UO->getSubExpr(), Mod: true);
14636 if (!O)
14637 return VisitExpr(E: UO);
14638
14639 notePreMod(O, ModExpr: UO);
14640 Visit(S: UO->getSubExpr());
14641 // C++11 [expr.pre.incr]p1:
14642 // the expression ++x is equivalent to x+=1
14643 notePostMod(O, ModExpr: UO,
14644 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14645 : UK_ModAsSideEffect);
14646 }
14647
14648 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14649 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14650 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14651 Object O = getObject(E: UO->getSubExpr(), Mod: true);
14652 if (!O)
14653 return VisitExpr(E: UO);
14654
14655 notePreMod(O, ModExpr: UO);
14656 Visit(S: UO->getSubExpr());
14657 notePostMod(O, ModExpr: UO, UK: UK_ModAsSideEffect);
14658 }
14659
14660 void VisitBinLOr(const BinaryOperator *BO) {
14661 // C++11 [expr.log.or]p2:
14662 // If the second expression is evaluated, every value computation and
14663 // side effect associated with the first expression is sequenced before
14664 // every value computation and side effect associated with the
14665 // second expression.
14666 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
14667 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
14668 SequenceTree::Seq OldRegion = Region;
14669
14670 EvaluationTracker Eval(*this);
14671 {
14672 SequencedSubexpression Sequenced(*this);
14673 Region = LHSRegion;
14674 Visit(S: BO->getLHS());
14675 }
14676
14677 // C++11 [expr.log.or]p1:
14678 // [...] the second operand is not evaluated if the first operand
14679 // evaluates to true.
14680 bool EvalResult = false;
14681 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
14682 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14683 if (ShouldVisitRHS) {
14684 Region = RHSRegion;
14685 Visit(S: BO->getRHS());
14686 }
14687
14688 Region = OldRegion;
14689 Tree.merge(S: LHSRegion);
14690 Tree.merge(S: RHSRegion);
14691 }
14692
14693 void VisitBinLAnd(const BinaryOperator *BO) {
14694 // C++11 [expr.log.and]p2:
14695 // If the second expression is evaluated, every value computation and
14696 // side effect associated with the first expression is sequenced before
14697 // every value computation and side effect associated with the
14698 // second expression.
14699 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
14700 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
14701 SequenceTree::Seq OldRegion = Region;
14702
14703 EvaluationTracker Eval(*this);
14704 {
14705 SequencedSubexpression Sequenced(*this);
14706 Region = LHSRegion;
14707 Visit(S: BO->getLHS());
14708 }
14709
14710 // C++11 [expr.log.and]p1:
14711 // [...] the second operand is not evaluated if the first operand is false.
14712 bool EvalResult = false;
14713 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
14714 bool ShouldVisitRHS = !EvalOK || EvalResult;
14715 if (ShouldVisitRHS) {
14716 Region = RHSRegion;
14717 Visit(S: BO->getRHS());
14718 }
14719
14720 Region = OldRegion;
14721 Tree.merge(S: LHSRegion);
14722 Tree.merge(S: RHSRegion);
14723 }
14724
14725 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14726 // C++11 [expr.cond]p1:
14727 // [...] Every value computation and side effect associated with the first
14728 // expression is sequenced before every value computation and side effect
14729 // associated with the second or third expression.
14730 SequenceTree::Seq ConditionRegion = Tree.allocate(Parent: Region);
14731
14732 // No sequencing is specified between the true and false expression.
14733 // However since exactly one of both is going to be evaluated we can
14734 // consider them to be sequenced. This is needed to avoid warning on
14735 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14736 // both the true and false expressions because we can't evaluate x.
14737 // This will still allow us to detect an expression like (pre C++17)
14738 // "(x ? y += 1 : y += 2) = y".
14739 //
14740 // We don't wrap the visitation of the true and false expression with
14741 // SequencedSubexpression because we don't want to downgrade modifications
14742 // as side effect in the true and false expressions after the visition
14743 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14744 // not warn between the two "y++", but we should warn between the "y++"
14745 // and the "y".
14746 SequenceTree::Seq TrueRegion = Tree.allocate(Parent: Region);
14747 SequenceTree::Seq FalseRegion = Tree.allocate(Parent: Region);
14748 SequenceTree::Seq OldRegion = Region;
14749
14750 EvaluationTracker Eval(*this);
14751 {
14752 SequencedSubexpression Sequenced(*this);
14753 Region = ConditionRegion;
14754 Visit(S: CO->getCond());
14755 }
14756
14757 // C++11 [expr.cond]p1:
14758 // [...] The first expression is contextually converted to bool (Clause 4).
14759 // It is evaluated and if it is true, the result of the conditional
14760 // expression is the value of the second expression, otherwise that of the
14761 // third expression. Only one of the second and third expressions is
14762 // evaluated. [...]
14763 bool EvalResult = false;
14764 bool EvalOK = Eval.evaluate(E: CO->getCond(), Result&: EvalResult);
14765 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14766 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14767 if (ShouldVisitTrueExpr) {
14768 Region = TrueRegion;
14769 Visit(S: CO->getTrueExpr());
14770 }
14771 if (ShouldVisitFalseExpr) {
14772 Region = FalseRegion;
14773 Visit(S: CO->getFalseExpr());
14774 }
14775
14776 Region = OldRegion;
14777 Tree.merge(S: ConditionRegion);
14778 Tree.merge(S: TrueRegion);
14779 Tree.merge(S: FalseRegion);
14780 }
14781
14782 void VisitCallExpr(const CallExpr *CE) {
14783 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14784
14785 if (CE->isUnevaluatedBuiltinCall(Ctx: Context))
14786 return;
14787
14788 // C++11 [intro.execution]p15:
14789 // When calling a function [...], every value computation and side effect
14790 // associated with any argument expression, or with the postfix expression
14791 // designating the called function, is sequenced before execution of every
14792 // expression or statement in the body of the function [and thus before
14793 // the value computation of its result].
14794 SequencedSubexpression Sequenced(*this);
14795 SemaRef.runWithSufficientStackSpace(Loc: CE->getExprLoc(), Fn: [&] {
14796 // C++17 [expr.call]p5
14797 // The postfix-expression is sequenced before each expression in the
14798 // expression-list and any default argument. [...]
14799 SequenceTree::Seq CalleeRegion;
14800 SequenceTree::Seq OtherRegion;
14801 if (SemaRef.getLangOpts().CPlusPlus17) {
14802 CalleeRegion = Tree.allocate(Parent: Region);
14803 OtherRegion = Tree.allocate(Parent: Region);
14804 } else {
14805 CalleeRegion = Region;
14806 OtherRegion = Region;
14807 }
14808 SequenceTree::Seq OldRegion = Region;
14809
14810 // Visit the callee expression first.
14811 Region = CalleeRegion;
14812 if (SemaRef.getLangOpts().CPlusPlus17) {
14813 SequencedSubexpression Sequenced(*this);
14814 Visit(S: CE->getCallee());
14815 } else {
14816 Visit(S: CE->getCallee());
14817 }
14818
14819 // Then visit the argument expressions.
14820 Region = OtherRegion;
14821 for (const Expr *Argument : CE->arguments())
14822 Visit(S: Argument);
14823
14824 Region = OldRegion;
14825 if (SemaRef.getLangOpts().CPlusPlus17) {
14826 Tree.merge(S: CalleeRegion);
14827 Tree.merge(S: OtherRegion);
14828 }
14829 });
14830 }
14831
14832 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14833 // C++17 [over.match.oper]p2:
14834 // [...] the operator notation is first transformed to the equivalent
14835 // function-call notation as summarized in Table 12 (where @ denotes one
14836 // of the operators covered in the specified subclause). However, the
14837 // operands are sequenced in the order prescribed for the built-in
14838 // operator (Clause 8).
14839 //
14840 // From the above only overloaded binary operators and overloaded call
14841 // operators have sequencing rules in C++17 that we need to handle
14842 // separately.
14843 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14844 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14845 return VisitCallExpr(CE: CXXOCE);
14846
14847 enum {
14848 NoSequencing,
14849 LHSBeforeRHS,
14850 RHSBeforeLHS,
14851 LHSBeforeRest
14852 } SequencingKind;
14853 switch (CXXOCE->getOperator()) {
14854 case OO_Equal:
14855 case OO_PlusEqual:
14856 case OO_MinusEqual:
14857 case OO_StarEqual:
14858 case OO_SlashEqual:
14859 case OO_PercentEqual:
14860 case OO_CaretEqual:
14861 case OO_AmpEqual:
14862 case OO_PipeEqual:
14863 case OO_LessLessEqual:
14864 case OO_GreaterGreaterEqual:
14865 SequencingKind = RHSBeforeLHS;
14866 break;
14867
14868 case OO_LessLess:
14869 case OO_GreaterGreater:
14870 case OO_AmpAmp:
14871 case OO_PipePipe:
14872 case OO_Comma:
14873 case OO_ArrowStar:
14874 case OO_Subscript:
14875 SequencingKind = LHSBeforeRHS;
14876 break;
14877
14878 case OO_Call:
14879 SequencingKind = LHSBeforeRest;
14880 break;
14881
14882 default:
14883 SequencingKind = NoSequencing;
14884 break;
14885 }
14886
14887 if (SequencingKind == NoSequencing)
14888 return VisitCallExpr(CE: CXXOCE);
14889
14890 // This is a call, so all subexpressions are sequenced before the result.
14891 SequencedSubexpression Sequenced(*this);
14892
14893 SemaRef.runWithSufficientStackSpace(Loc: CXXOCE->getExprLoc(), Fn: [&] {
14894 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14895 "Should only get there with C++17 and above!");
14896 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14897 "Should only get there with an overloaded binary operator"
14898 " or an overloaded call operator!");
14899
14900 if (SequencingKind == LHSBeforeRest) {
14901 assert(CXXOCE->getOperator() == OO_Call &&
14902 "We should only have an overloaded call operator here!");
14903
14904 // This is very similar to VisitCallExpr, except that we only have the
14905 // C++17 case. The postfix-expression is the first argument of the
14906 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14907 // are in the following arguments.
14908 //
14909 // Note that we intentionally do not visit the callee expression since
14910 // it is just a decayed reference to a function.
14911 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Parent: Region);
14912 SequenceTree::Seq ArgsRegion = Tree.allocate(Parent: Region);
14913 SequenceTree::Seq OldRegion = Region;
14914
14915 assert(CXXOCE->getNumArgs() >= 1 &&
14916 "An overloaded call operator must have at least one argument"
14917 " for the postfix-expression!");
14918 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14919 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14920 CXXOCE->getNumArgs() - 1);
14921
14922 // Visit the postfix-expression first.
14923 {
14924 Region = PostfixExprRegion;
14925 SequencedSubexpression Sequenced(*this);
14926 Visit(S: PostfixExpr);
14927 }
14928
14929 // Then visit the argument expressions.
14930 Region = ArgsRegion;
14931 for (const Expr *Arg : Args)
14932 Visit(S: Arg);
14933
14934 Region = OldRegion;
14935 Tree.merge(S: PostfixExprRegion);
14936 Tree.merge(S: ArgsRegion);
14937 } else {
14938 assert(CXXOCE->getNumArgs() == 2 &&
14939 "Should only have two arguments here!");
14940 assert((SequencingKind == LHSBeforeRHS ||
14941 SequencingKind == RHSBeforeLHS) &&
14942 "Unexpected sequencing kind!");
14943
14944 // We do not visit the callee expression since it is just a decayed
14945 // reference to a function.
14946 const Expr *E1 = CXXOCE->getArg(Arg: 0);
14947 const Expr *E2 = CXXOCE->getArg(Arg: 1);
14948 if (SequencingKind == RHSBeforeLHS)
14949 std::swap(a&: E1, b&: E2);
14950
14951 return VisitSequencedExpressions(SequencedBefore: E1, SequencedAfter: E2);
14952 }
14953 });
14954 }
14955
14956 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14957 // This is a call, so all subexpressions are sequenced before the result.
14958 SequencedSubexpression Sequenced(*this);
14959
14960 if (!CCE->isListInitialization())
14961 return VisitExpr(E: CCE);
14962
14963 // In C++11, list initializations are sequenced.
14964 SequenceExpressionsInOrder(
14965 ExpressionList: llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14966 }
14967
14968 void VisitInitListExpr(const InitListExpr *ILE) {
14969 if (!SemaRef.getLangOpts().CPlusPlus11)
14970 return VisitExpr(E: ILE);
14971
14972 // In C++11, list initializations are sequenced.
14973 SequenceExpressionsInOrder(ExpressionList: ILE->inits());
14974 }
14975
14976 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14977 // C++20 parenthesized list initializations are sequenced. See C++20
14978 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14979 SequenceExpressionsInOrder(ExpressionList: PLIE->getInitExprs());
14980 }
14981
14982private:
14983 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14984 SmallVector<SequenceTree::Seq, 32> Elts;
14985 SequenceTree::Seq Parent = Region;
14986 for (const Expr *E : ExpressionList) {
14987 if (!E)
14988 continue;
14989 Region = Tree.allocate(Parent);
14990 Elts.push_back(Elt: Region);
14991 Visit(S: E);
14992 }
14993
14994 // Forget that the initializers are sequenced.
14995 Region = Parent;
14996 for (unsigned I = 0; I < Elts.size(); ++I)
14997 Tree.merge(S: Elts[I]);
14998 }
14999};
15000
15001SequenceChecker::UsageInfo::UsageInfo() = default;
15002
15003} // namespace
15004
15005void Sema::CheckUnsequencedOperations(const Expr *E) {
15006 SmallVector<const Expr *, 8> WorkList;
15007 WorkList.push_back(Elt: E);
15008 while (!WorkList.empty()) {
15009 const Expr *Item = WorkList.pop_back_val();
15010 SequenceChecker(*this, Item, WorkList);
15011 }
15012}
15013
15014void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15015 bool IsConstexpr) {
15016 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15017 IsConstexpr || isa<ConstantExpr>(Val: E));
15018 CheckImplicitConversions(E, CC: CheckLoc);
15019 if (!E->isInstantiationDependent())
15020 CheckUnsequencedOperations(E);
15021 if (!IsConstexpr && !E->isValueDependent())
15022 CheckForIntOverflow(E);
15023}
15024
15025void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15026 FieldDecl *BitField,
15027 Expr *Init) {
15028 (void) AnalyzeBitFieldAssignment(S&: *this, Bitfield: BitField, Init, InitLoc);
15029}
15030
15031static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
15032 SourceLocation Loc) {
15033 if (!PType->isVariablyModifiedType())
15034 return;
15035 if (const auto *PointerTy = dyn_cast<PointerType>(Val&: PType)) {
15036 diagnoseArrayStarInParamType(S, PType: PointerTy->getPointeeType(), Loc);
15037 return;
15038 }
15039 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(Val&: PType)) {
15040 diagnoseArrayStarInParamType(S, PType: ReferenceTy->getPointeeType(), Loc);
15041 return;
15042 }
15043 if (const auto *ParenTy = dyn_cast<ParenType>(Val&: PType)) {
15044 diagnoseArrayStarInParamType(S, PType: ParenTy->getInnerType(), Loc);
15045 return;
15046 }
15047
15048 const ArrayType *AT = S.Context.getAsArrayType(T: PType);
15049 if (!AT)
15050 return;
15051
15052 if (AT->getSizeModifier() != ArraySizeModifier::Star) {
15053 diagnoseArrayStarInParamType(S, PType: AT->getElementType(), Loc);
15054 return;
15055 }
15056
15057 S.Diag(Loc, DiagID: diag::err_array_star_in_function_definition);
15058}
15059
15060bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
15061 bool CheckParameterNames) {
15062 bool HasInvalidParm = false;
15063 for (ParmVarDecl *Param : Parameters) {
15064 assert(Param && "null in a parameter list");
15065 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15066 // function declarator that is part of a function definition of
15067 // that function shall not have incomplete type.
15068 //
15069 // C++23 [dcl.fct.def.general]/p2
15070 // The type of a parameter [...] for a function definition
15071 // shall not be a (possibly cv-qualified) class type that is incomplete
15072 // or abstract within the function body unless the function is deleted.
15073 if (!Param->isInvalidDecl() &&
15074 (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
15075 DiagID: diag::err_typecheck_decl_incomplete_type) ||
15076 RequireNonAbstractType(Loc: Param->getBeginLoc(), T: Param->getOriginalType(),
15077 DiagID: diag::err_abstract_type_in_decl,
15078 Args: AbstractParamType))) {
15079 Param->setInvalidDecl();
15080 HasInvalidParm = true;
15081 }
15082
15083 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15084 // declaration of each parameter shall include an identifier.
15085 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15086 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15087 // Diagnose this as an extension in C17 and earlier.
15088 if (!getLangOpts().C23)
15089 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
15090 }
15091
15092 // C99 6.7.5.3p12:
15093 // If the function declarator is not part of a definition of that
15094 // function, parameters may have incomplete type and may use the [*]
15095 // notation in their sequences of declarator specifiers to specify
15096 // variable length array types.
15097 QualType PType = Param->getOriginalType();
15098 // FIXME: This diagnostic should point the '[*]' if source-location
15099 // information is added for it.
15100 diagnoseArrayStarInParamType(S&: *this, PType, Loc: Param->getLocation());
15101
15102 // If the parameter is a c++ class type and it has to be destructed in the
15103 // callee function, declare the destructor so that it can be called by the
15104 // callee function. Do not perform any direct access check on the dtor here.
15105 if (!Param->isInvalidDecl()) {
15106 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15107 if (!ClassDecl->isInvalidDecl() &&
15108 !ClassDecl->hasIrrelevantDestructor() &&
15109 !ClassDecl->isDependentContext() &&
15110 ClassDecl->isParamDestroyedInCallee()) {
15111 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
15112 MarkFunctionReferenced(Loc: Param->getLocation(), Func: Destructor);
15113 DiagnoseUseOfDecl(D: Destructor, Locs: Param->getLocation());
15114 }
15115 }
15116 }
15117
15118 // Parameters with the pass_object_size attribute only need to be marked
15119 // constant at function definitions. Because we lack information about
15120 // whether we're on a declaration or definition when we're instantiating the
15121 // attribute, we need to check for constness here.
15122 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15123 if (!Param->getType().isConstQualified())
15124 Diag(Loc: Param->getLocation(), DiagID: diag::err_attribute_pointers_only)
15125 << Attr->getSpelling() << 1;
15126
15127 // Check for parameter names shadowing fields from the class.
15128 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15129 // The owning context for the parameter should be the function, but we
15130 // want to see if this function's declaration context is a record.
15131 DeclContext *DC = Param->getDeclContext();
15132 if (DC && DC->isFunctionOrMethod()) {
15133 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC->getParent()))
15134 CheckShadowInheritedFields(Loc: Param->getLocation(), FieldName: Param->getDeclName(),
15135 RD, /*DeclIsField*/ false);
15136 }
15137 }
15138
15139 if (!Param->isInvalidDecl() &&
15140 Param->getOriginalType()->isWebAssemblyTableType()) {
15141 Param->setInvalidDecl();
15142 HasInvalidParm = true;
15143 Diag(Loc: Param->getLocation(), DiagID: diag::err_wasm_table_as_function_parameter);
15144 }
15145 }
15146
15147 return HasInvalidParm;
15148}
15149
15150std::optional<std::pair<
15151 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15152 *E,
15153 ASTContext
15154 &Ctx);
15155
15156/// Compute the alignment and offset of the base class object given the
15157/// derived-to-base cast expression and the alignment and offset of the derived
15158/// class object.
15159static std::pair<CharUnits, CharUnits>
15160getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15161 CharUnits BaseAlignment, CharUnits Offset,
15162 ASTContext &Ctx) {
15163 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15164 ++PathI) {
15165 const CXXBaseSpecifier *Base = *PathI;
15166 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15167 if (Base->isVirtual()) {
15168 // The complete object may have a lower alignment than the non-virtual
15169 // alignment of the base, in which case the base may be misaligned. Choose
15170 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15171 // conservative lower bound of the complete object alignment.
15172 CharUnits NonVirtualAlignment =
15173 Ctx.getASTRecordLayout(D: BaseDecl).getNonVirtualAlignment();
15174 BaseAlignment = std::min(a: BaseAlignment, b: NonVirtualAlignment);
15175 Offset = CharUnits::Zero();
15176 } else {
15177 const ASTRecordLayout &RL =
15178 Ctx.getASTRecordLayout(D: DerivedType->getAsCXXRecordDecl());
15179 Offset += RL.getBaseClassOffset(Base: BaseDecl);
15180 }
15181 DerivedType = Base->getType();
15182 }
15183
15184 return std::make_pair(x&: BaseAlignment, y&: Offset);
15185}
15186
15187/// Compute the alignment and offset of a binary additive operator.
15188static std::optional<std::pair<CharUnits, CharUnits>>
15189getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15190 bool IsSub, ASTContext &Ctx) {
15191 QualType PointeeType = PtrE->getType()->getPointeeType();
15192
15193 if (!PointeeType->isConstantSizeType())
15194 return std::nullopt;
15195
15196 auto P = getBaseAlignmentAndOffsetFromPtr(E: PtrE, Ctx);
15197
15198 if (!P)
15199 return std::nullopt;
15200
15201 CharUnits EltSize = Ctx.getTypeSizeInChars(T: PointeeType);
15202 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15203 CharUnits Offset = EltSize * IdxRes->getExtValue();
15204 if (IsSub)
15205 Offset = -Offset;
15206 return std::make_pair(x&: P->first, y: P->second + Offset);
15207 }
15208
15209 // If the integer expression isn't a constant expression, compute the lower
15210 // bound of the alignment using the alignment and offset of the pointer
15211 // expression and the element size.
15212 return std::make_pair(
15213 x: P->first.alignmentAtOffset(offset: P->second).alignmentAtOffset(offset: EltSize),
15214 y: CharUnits::Zero());
15215}
15216
15217/// This helper function takes an lvalue expression and returns the alignment of
15218/// a VarDecl and a constant offset from the VarDecl.
15219std::optional<std::pair<
15220 CharUnits,
15221 CharUnits>> static getBaseAlignmentAndOffsetFromLValue(const Expr *E,
15222 ASTContext &Ctx) {
15223 E = E->IgnoreParens();
15224 switch (E->getStmtClass()) {
15225 default:
15226 break;
15227 case Stmt::CStyleCastExprClass:
15228 case Stmt::CXXStaticCastExprClass:
15229 case Stmt::ImplicitCastExprClass: {
15230 auto *CE = cast<CastExpr>(Val: E);
15231 const Expr *From = CE->getSubExpr();
15232 switch (CE->getCastKind()) {
15233 default:
15234 break;
15235 case CK_NoOp:
15236 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15237 case CK_UncheckedDerivedToBase:
15238 case CK_DerivedToBase: {
15239 auto P = getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15240 if (!P)
15241 break;
15242 return getDerivedToBaseAlignmentAndOffset(CE, DerivedType: From->getType(), BaseAlignment: P->first,
15243 Offset: P->second, Ctx);
15244 }
15245 }
15246 break;
15247 }
15248 case Stmt::ArraySubscriptExprClass: {
15249 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
15250 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: ASE->getBase(), IntE: ASE->getIdx(),
15251 IsSub: false, Ctx);
15252 }
15253 case Stmt::DeclRefExprClass: {
15254 if (auto *VD = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: E)->getDecl())) {
15255 // FIXME: If VD is captured by copy or is an escaping __block variable,
15256 // use the alignment of VD's type.
15257 if (!VD->getType()->isReferenceType()) {
15258 // Dependent alignment cannot be resolved -> bail out.
15259 if (VD->hasDependentAlignment())
15260 break;
15261 return std::make_pair(x: Ctx.getDeclAlign(D: VD), y: CharUnits::Zero());
15262 }
15263 if (VD->hasInit())
15264 return getBaseAlignmentAndOffsetFromLValue(E: VD->getInit(), Ctx);
15265 }
15266 break;
15267 }
15268 case Stmt::MemberExprClass: {
15269 auto *ME = cast<MemberExpr>(Val: E);
15270 auto *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
15271 if (!FD || FD->getType()->isReferenceType() ||
15272 FD->getParent()->isInvalidDecl())
15273 break;
15274 std::optional<std::pair<CharUnits, CharUnits>> P;
15275 if (ME->isArrow())
15276 P = getBaseAlignmentAndOffsetFromPtr(E: ME->getBase(), Ctx);
15277 else
15278 P = getBaseAlignmentAndOffsetFromLValue(E: ME->getBase(), Ctx);
15279 if (!P)
15280 break;
15281 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(D: FD->getParent());
15282 uint64_t Offset = Layout.getFieldOffset(FieldNo: FD->getFieldIndex());
15283 return std::make_pair(x&: P->first,
15284 y: P->second + CharUnits::fromQuantity(Quantity: Offset));
15285 }
15286 case Stmt::UnaryOperatorClass: {
15287 auto *UO = cast<UnaryOperator>(Val: E);
15288 switch (UO->getOpcode()) {
15289 default:
15290 break;
15291 case UO_Deref:
15292 return getBaseAlignmentAndOffsetFromPtr(E: UO->getSubExpr(), Ctx);
15293 }
15294 break;
15295 }
15296 case Stmt::BinaryOperatorClass: {
15297 auto *BO = cast<BinaryOperator>(Val: E);
15298 auto Opcode = BO->getOpcode();
15299 switch (Opcode) {
15300 default:
15301 break;
15302 case BO_Comma:
15303 return getBaseAlignmentAndOffsetFromLValue(E: BO->getRHS(), Ctx);
15304 }
15305 break;
15306 }
15307 }
15308 return std::nullopt;
15309}
15310
15311/// This helper function takes a pointer expression and returns the alignment of
15312/// a VarDecl and a constant offset from the VarDecl.
15313std::optional<std::pair<
15314 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15315 *E,
15316 ASTContext
15317 &Ctx) {
15318 E = E->IgnoreParens();
15319 switch (E->getStmtClass()) {
15320 default:
15321 break;
15322 case Stmt::CStyleCastExprClass:
15323 case Stmt::CXXStaticCastExprClass:
15324 case Stmt::ImplicitCastExprClass: {
15325 auto *CE = cast<CastExpr>(Val: E);
15326 const Expr *From = CE->getSubExpr();
15327 switch (CE->getCastKind()) {
15328 default:
15329 break;
15330 case CK_NoOp:
15331 return getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15332 case CK_ArrayToPointerDecay:
15333 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15334 case CK_UncheckedDerivedToBase:
15335 case CK_DerivedToBase: {
15336 auto P = getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15337 if (!P)
15338 break;
15339 return getDerivedToBaseAlignmentAndOffset(
15340 CE, DerivedType: From->getType()->getPointeeType(), BaseAlignment: P->first, Offset: P->second, Ctx);
15341 }
15342 }
15343 break;
15344 }
15345 case Stmt::CXXThisExprClass: {
15346 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15347 CharUnits Alignment = Ctx.getASTRecordLayout(D: RD).getNonVirtualAlignment();
15348 return std::make_pair(x&: Alignment, y: CharUnits::Zero());
15349 }
15350 case Stmt::UnaryOperatorClass: {
15351 auto *UO = cast<UnaryOperator>(Val: E);
15352 if (UO->getOpcode() == UO_AddrOf)
15353 return getBaseAlignmentAndOffsetFromLValue(E: UO->getSubExpr(), Ctx);
15354 break;
15355 }
15356 case Stmt::BinaryOperatorClass: {
15357 auto *BO = cast<BinaryOperator>(Val: E);
15358 auto Opcode = BO->getOpcode();
15359 switch (Opcode) {
15360 default:
15361 break;
15362 case BO_Add:
15363 case BO_Sub: {
15364 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15365 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15366 std::swap(a&: LHS, b&: RHS);
15367 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: LHS, IntE: RHS, IsSub: Opcode == BO_Sub,
15368 Ctx);
15369 }
15370 case BO_Comma:
15371 return getBaseAlignmentAndOffsetFromPtr(E: BO->getRHS(), Ctx);
15372 }
15373 break;
15374 }
15375 }
15376 return std::nullopt;
15377}
15378
15379static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15380 // See if we can compute the alignment of a VarDecl and an offset from it.
15381 std::optional<std::pair<CharUnits, CharUnits>> P =
15382 getBaseAlignmentAndOffsetFromPtr(E, Ctx&: S.Context);
15383
15384 if (P)
15385 return P->first.alignmentAtOffset(offset: P->second);
15386
15387 // If that failed, return the type's alignment.
15388 return S.Context.getTypeAlignInChars(T: E->getType()->getPointeeType());
15389}
15390
15391void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15392 // This is actually a lot of work to potentially be doing on every
15393 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15394 if (getDiagnostics().isIgnored(DiagID: diag::warn_cast_align, Loc: TRange.getBegin()))
15395 return;
15396
15397 // Ignore dependent types.
15398 if (T->isDependentType() || Op->getType()->isDependentType())
15399 return;
15400
15401 // Require that the destination be a pointer type.
15402 const PointerType *DestPtr = T->getAs<PointerType>();
15403 if (!DestPtr) return;
15404
15405 // If the destination has alignment 1, we're done.
15406 QualType DestPointee = DestPtr->getPointeeType();
15407 if (DestPointee->isIncompleteType()) return;
15408 CharUnits DestAlign = Context.getTypeAlignInChars(T: DestPointee);
15409 if (DestAlign.isOne()) return;
15410
15411 // Require that the source be a pointer type.
15412 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15413 if (!SrcPtr) return;
15414 QualType SrcPointee = SrcPtr->getPointeeType();
15415
15416 // Explicitly allow casts from cv void*. We already implicitly
15417 // allowed casts to cv void*, since they have alignment 1.
15418 // Also allow casts involving incomplete types, which implicitly
15419 // includes 'void'.
15420 if (SrcPointee->isIncompleteType()) return;
15421
15422 CharUnits SrcAlign = getPresumedAlignmentOfPointer(E: Op, S&: *this);
15423
15424 if (SrcAlign >= DestAlign) return;
15425
15426 Diag(Loc: TRange.getBegin(), DiagID: diag::warn_cast_align)
15427 << Op->getType() << T
15428 << static_cast<unsigned>(SrcAlign.getQuantity())
15429 << static_cast<unsigned>(DestAlign.getQuantity())
15430 << TRange << Op->getSourceRange();
15431}
15432
15433void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15434 const ArraySubscriptExpr *ASE,
15435 bool AllowOnePastEnd, bool IndexNegated) {
15436 // Already diagnosed by the constant evaluator.
15437 if (isConstantEvaluatedContext())
15438 return;
15439
15440 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15441 if (IndexExpr->isValueDependent())
15442 return;
15443
15444 const Type *EffectiveType =
15445 BaseExpr->getType()->getPointeeOrArrayElementType();
15446 BaseExpr = BaseExpr->IgnoreParenCasts();
15447 const ConstantArrayType *ArrayTy =
15448 Context.getAsConstantArrayType(T: BaseExpr->getType());
15449
15450 LangOptions::StrictFlexArraysLevelKind
15451 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15452
15453 const Type *BaseType =
15454 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15455 bool IsUnboundedArray =
15456 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15457 Context, StrictFlexArraysLevel,
15458 /*IgnoreTemplateOrMacroSubstitution=*/true);
15459 if (EffectiveType->isDependentType() ||
15460 (!IsUnboundedArray && BaseType->isDependentType()))
15461 return;
15462
15463 Expr::EvalResult Result;
15464 if (!IndexExpr->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects))
15465 return;
15466
15467 llvm::APSInt index = Result.Val.getInt();
15468 if (IndexNegated) {
15469 index.setIsUnsigned(false);
15470 index = -index;
15471 }
15472
15473 if (IsUnboundedArray) {
15474 if (EffectiveType->isFunctionType())
15475 return;
15476 if (index.isUnsigned() || !index.isNegative()) {
15477 const auto &ASTC = getASTContext();
15478 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15479 AddrSpace: EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15480 if (index.getBitWidth() < AddrBits)
15481 index = index.zext(width: AddrBits);
15482 std::optional<CharUnits> ElemCharUnits =
15483 ASTC.getTypeSizeInCharsIfKnown(Ty: EffectiveType);
15484 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15485 // pointer) bounds-checking isn't meaningful.
15486 if (!ElemCharUnits || ElemCharUnits->isZero())
15487 return;
15488 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15489 // If index has more active bits than address space, we already know
15490 // we have a bounds violation to warn about. Otherwise, compute
15491 // address of (index + 1)th element, and warn about bounds violation
15492 // only if that address exceeds address space.
15493 if (index.getActiveBits() <= AddrBits) {
15494 bool Overflow;
15495 llvm::APInt Product(index);
15496 Product += 1;
15497 Product = Product.umul_ov(RHS: ElemBytes, Overflow);
15498 if (!Overflow && Product.getActiveBits() <= AddrBits)
15499 return;
15500 }
15501
15502 // Need to compute max possible elements in address space, since that
15503 // is included in diag message.
15504 llvm::APInt MaxElems = llvm::APInt::getMaxValue(numBits: AddrBits);
15505 MaxElems = MaxElems.zext(width: std::max(a: AddrBits + 1, b: ElemBytes.getBitWidth()));
15506 MaxElems += 1;
15507 ElemBytes = ElemBytes.zextOrTrunc(width: MaxElems.getBitWidth());
15508 MaxElems = MaxElems.udiv(RHS: ElemBytes);
15509
15510 unsigned DiagID =
15511 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15512 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15513
15514 // Diag message shows element size in bits and in "bytes" (platform-
15515 // dependent CharUnits)
15516 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
15517 PD: PDiag(DiagID) << index << AddrBits
15518 << (unsigned)ASTC.toBits(CharSize: *ElemCharUnits)
15519 << ElemBytes << MaxElems
15520 << MaxElems.getZExtValue()
15521 << IndexExpr->getSourceRange());
15522
15523 const NamedDecl *ND = nullptr;
15524 // Try harder to find a NamedDecl to point at in the note.
15525 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
15526 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15527 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
15528 ND = DRE->getDecl();
15529 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
15530 ND = ME->getMemberDecl();
15531
15532 if (ND)
15533 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
15534 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
15535 }
15536 return;
15537 }
15538
15539 if (index.isUnsigned() || !index.isNegative()) {
15540 // It is possible that the type of the base expression after
15541 // IgnoreParenCasts is incomplete, even though the type of the base
15542 // expression before IgnoreParenCasts is complete (see PR39746 for an
15543 // example). In this case we have no information about whether the array
15544 // access exceeds the array bounds. However we can still diagnose an array
15545 // access which precedes the array bounds.
15546 if (BaseType->isIncompleteType())
15547 return;
15548
15549 llvm::APInt size = ArrayTy->getSize();
15550
15551 if (BaseType != EffectiveType) {
15552 // Make sure we're comparing apples to apples when comparing index to
15553 // size.
15554 uint64_t ptrarith_typesize = Context.getTypeSize(T: EffectiveType);
15555 uint64_t array_typesize = Context.getTypeSize(T: BaseType);
15556
15557 // Handle ptrarith_typesize being zero, such as when casting to void*.
15558 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15559 if (!ptrarith_typesize)
15560 ptrarith_typesize = Context.getCharWidth();
15561
15562 if (ptrarith_typesize != array_typesize) {
15563 // There's a cast to a different size type involved.
15564 uint64_t ratio = array_typesize / ptrarith_typesize;
15565
15566 // TODO: Be smarter about handling cases where array_typesize is not a
15567 // multiple of ptrarith_typesize.
15568 if (ptrarith_typesize * ratio == array_typesize)
15569 size *= llvm::APInt(size.getBitWidth(), ratio);
15570 }
15571 }
15572
15573 if (size.getBitWidth() > index.getBitWidth())
15574 index = index.zext(width: size.getBitWidth());
15575 else if (size.getBitWidth() < index.getBitWidth())
15576 size = size.zext(width: index.getBitWidth());
15577
15578 // For array subscripting the index must be less than size, but for pointer
15579 // arithmetic also allow the index (offset) to be equal to size since
15580 // computing the next address after the end of the array is legal and
15581 // commonly done e.g. in C++ iterators and range-based for loops.
15582 if (AllowOnePastEnd ? index.ule(RHS: size) : index.ult(RHS: size))
15583 return;
15584
15585 // Suppress the warning if the subscript expression (as identified by the
15586 // ']' location) and the index expression are both from macro expansions
15587 // within a system header.
15588 if (ASE) {
15589 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15590 Loc: ASE->getRBracketLoc());
15591 if (SourceMgr.isInSystemHeader(Loc: RBracketLoc)) {
15592 SourceLocation IndexLoc =
15593 SourceMgr.getSpellingLoc(Loc: IndexExpr->getBeginLoc());
15594 if (SourceMgr.isWrittenInSameFile(Loc1: RBracketLoc, Loc2: IndexLoc))
15595 return;
15596 }
15597 }
15598
15599 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15600 : diag::warn_ptr_arith_exceeds_bounds;
15601 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15602 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15603
15604 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
15605 PD: PDiag(DiagID)
15606 << index << ArrayTy->desugar() << CastMsg
15607 << CastMsgTy << IndexExpr->getSourceRange());
15608 } else {
15609 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15610 if (!ASE) {
15611 DiagID = diag::warn_ptr_arith_precedes_bounds;
15612 if (index.isNegative()) index = -index;
15613 }
15614
15615 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
15616 PD: PDiag(DiagID) << index << IndexExpr->getSourceRange());
15617 }
15618
15619 const NamedDecl *ND = nullptr;
15620 // Try harder to find a NamedDecl to point at in the note.
15621 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
15622 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15623 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
15624 ND = DRE->getDecl();
15625 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
15626 ND = ME->getMemberDecl();
15627
15628 if (ND)
15629 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
15630 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
15631}
15632
15633void Sema::CheckArrayAccess(const Expr *expr) {
15634 int AllowOnePastEnd = 0;
15635 while (expr) {
15636 expr = expr->IgnoreParenImpCasts();
15637 switch (expr->getStmtClass()) {
15638 case Stmt::ArraySubscriptExprClass: {
15639 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Val: expr);
15640 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getIdx(), ASE,
15641 AllowOnePastEnd: AllowOnePastEnd > 0);
15642 expr = ASE->getBase();
15643 break;
15644 }
15645 case Stmt::MemberExprClass: {
15646 expr = cast<MemberExpr>(Val: expr)->getBase();
15647 break;
15648 }
15649 case Stmt::CXXMemberCallExprClass: {
15650 expr = cast<CXXMemberCallExpr>(Val: expr)->getImplicitObjectArgument();
15651 break;
15652 }
15653 case Stmt::ArraySectionExprClass: {
15654 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(Val: expr);
15655 // FIXME: We should probably be checking all of the elements to the
15656 // 'length' here as well.
15657 if (ASE->getLowerBound())
15658 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getLowerBound(),
15659 /*ASE=*/nullptr, AllowOnePastEnd: AllowOnePastEnd > 0);
15660 return;
15661 }
15662 case Stmt::UnaryOperatorClass: {
15663 // Only unwrap the * and & unary operators
15664 const UnaryOperator *UO = cast<UnaryOperator>(Val: expr);
15665 expr = UO->getSubExpr();
15666 switch (UO->getOpcode()) {
15667 case UO_AddrOf:
15668 AllowOnePastEnd++;
15669 break;
15670 case UO_Deref:
15671 AllowOnePastEnd--;
15672 break;
15673 default:
15674 return;
15675 }
15676 break;
15677 }
15678 case Stmt::ConditionalOperatorClass: {
15679 const ConditionalOperator *cond = cast<ConditionalOperator>(Val: expr);
15680 if (const Expr *lhs = cond->getLHS())
15681 CheckArrayAccess(expr: lhs);
15682 if (const Expr *rhs = cond->getRHS())
15683 CheckArrayAccess(expr: rhs);
15684 return;
15685 }
15686 case Stmt::CXXOperatorCallExprClass: {
15687 const auto *OCE = cast<CXXOperatorCallExpr>(Val: expr);
15688 for (const auto *Arg : OCE->arguments())
15689 CheckArrayAccess(expr: Arg);
15690 return;
15691 }
15692 default:
15693 return;
15694 }
15695 }
15696}
15697
15698static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15699 Expr *RHS, bool isProperty) {
15700 // Check if RHS is an Objective-C object literal, which also can get
15701 // immediately zapped in a weak reference. Note that we explicitly
15702 // allow ObjCStringLiterals, since those are designed to never really die.
15703 RHS = RHS->IgnoreParenImpCasts();
15704
15705 // This enum needs to match with the 'select' in
15706 // warn_objc_arc_literal_assign (off-by-1).
15707 SemaObjC::ObjCLiteralKind Kind = S.ObjC().CheckLiteralKind(FromE: RHS);
15708 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15709 return false;
15710
15711 S.Diag(Loc, DiagID: diag::warn_arc_literal_assign)
15712 << (unsigned) Kind
15713 << (isProperty ? 0 : 1)
15714 << RHS->getSourceRange();
15715
15716 return true;
15717}
15718
15719static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15720 Qualifiers::ObjCLifetime LT,
15721 Expr *RHS, bool isProperty) {
15722 // Strip off any implicit cast added to get to the one ARC-specific.
15723 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
15724 if (cast->getCastKind() == CK_ARCConsumeObject) {
15725 S.Diag(Loc, DiagID: diag::warn_arc_retained_assign)
15726 << (LT == Qualifiers::OCL_ExplicitNone)
15727 << (isProperty ? 0 : 1)
15728 << RHS->getSourceRange();
15729 return true;
15730 }
15731 RHS = cast->getSubExpr();
15732 }
15733
15734 if (LT == Qualifiers::OCL_Weak &&
15735 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15736 return true;
15737
15738 return false;
15739}
15740
15741bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15742 QualType LHS, Expr *RHS) {
15743 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15744
15745 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15746 return false;
15747
15748 if (checkUnsafeAssignObject(S&: *this, Loc, LT, RHS, isProperty: false))
15749 return true;
15750
15751 return false;
15752}
15753
15754void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15755 Expr *LHS, Expr *RHS) {
15756 QualType LHSType;
15757 // PropertyRef on LHS type need be directly obtained from
15758 // its declaration as it has a PseudoType.
15759 ObjCPropertyRefExpr *PRE
15760 = dyn_cast<ObjCPropertyRefExpr>(Val: LHS->IgnoreParens());
15761 if (PRE && !PRE->isImplicitProperty()) {
15762 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15763 if (PD)
15764 LHSType = PD->getType();
15765 }
15766
15767 if (LHSType.isNull())
15768 LHSType = LHS->getType();
15769
15770 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15771
15772 if (LT == Qualifiers::OCL_Weak) {
15773 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc))
15774 getCurFunction()->markSafeWeakUse(E: LHS);
15775 }
15776
15777 if (checkUnsafeAssigns(Loc, LHS: LHSType, RHS))
15778 return;
15779
15780 // FIXME. Check for other life times.
15781 if (LT != Qualifiers::OCL_None)
15782 return;
15783
15784 if (PRE) {
15785 if (PRE->isImplicitProperty())
15786 return;
15787 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15788 if (!PD)
15789 return;
15790
15791 unsigned Attributes = PD->getPropertyAttributes();
15792 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15793 // when 'assign' attribute was not explicitly specified
15794 // by user, ignore it and rely on property type itself
15795 // for lifetime info.
15796 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15797 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15798 LHSType->isObjCRetainableType())
15799 return;
15800
15801 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
15802 if (cast->getCastKind() == CK_ARCConsumeObject) {
15803 Diag(Loc, DiagID: diag::warn_arc_retained_property_assign)
15804 << RHS->getSourceRange();
15805 return;
15806 }
15807 RHS = cast->getSubExpr();
15808 }
15809 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15810 if (checkUnsafeAssignObject(S&: *this, Loc, LT: Qualifiers::OCL_Weak, RHS, isProperty: true))
15811 return;
15812 }
15813 }
15814}
15815
15816//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15817
15818static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15819 SourceLocation StmtLoc,
15820 const NullStmt *Body) {
15821 // Do not warn if the body is a macro that expands to nothing, e.g:
15822 //
15823 // #define CALL(x)
15824 // if (condition)
15825 // CALL(0);
15826 if (Body->hasLeadingEmptyMacro())
15827 return false;
15828
15829 // Get line numbers of statement and body.
15830 bool StmtLineInvalid;
15831 unsigned StmtLine = SourceMgr.getPresumedLineNumber(Loc: StmtLoc,
15832 Invalid: &StmtLineInvalid);
15833 if (StmtLineInvalid)
15834 return false;
15835
15836 bool BodyLineInvalid;
15837 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Loc: Body->getSemiLoc(),
15838 Invalid: &BodyLineInvalid);
15839 if (BodyLineInvalid)
15840 return false;
15841
15842 // Warn if null statement and body are on the same line.
15843 if (StmtLine != BodyLine)
15844 return false;
15845
15846 return true;
15847}
15848
15849void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15850 const Stmt *Body,
15851 unsigned DiagID) {
15852 // Since this is a syntactic check, don't emit diagnostic for template
15853 // instantiations, this just adds noise.
15854 if (CurrentInstantiationScope)
15855 return;
15856
15857 // The body should be a null statement.
15858 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
15859 if (!NBody)
15860 return;
15861
15862 // Do the usual checks.
15863 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
15864 return;
15865
15866 Diag(Loc: NBody->getSemiLoc(), DiagID);
15867 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
15868}
15869
15870void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15871 const Stmt *PossibleBody) {
15872 assert(!CurrentInstantiationScope); // Ensured by caller
15873
15874 SourceLocation StmtLoc;
15875 const Stmt *Body;
15876 unsigned DiagID;
15877 if (const ForStmt *FS = dyn_cast<ForStmt>(Val: S)) {
15878 StmtLoc = FS->getRParenLoc();
15879 Body = FS->getBody();
15880 DiagID = diag::warn_empty_for_body;
15881 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Val: S)) {
15882 StmtLoc = WS->getRParenLoc();
15883 Body = WS->getBody();
15884 DiagID = diag::warn_empty_while_body;
15885 } else
15886 return; // Neither `for' nor `while'.
15887
15888 // The body should be a null statement.
15889 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
15890 if (!NBody)
15891 return;
15892
15893 // Skip expensive checks if diagnostic is disabled.
15894 if (Diags.isIgnored(DiagID, Loc: NBody->getSemiLoc()))
15895 return;
15896
15897 // Do the usual checks.
15898 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
15899 return;
15900
15901 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15902 // noise level low, emit diagnostics only if for/while is followed by a
15903 // CompoundStmt, e.g.:
15904 // for (int i = 0; i < n; i++);
15905 // {
15906 // a(i);
15907 // }
15908 // or if for/while is followed by a statement with more indentation
15909 // than for/while itself:
15910 // for (int i = 0; i < n; i++);
15911 // a(i);
15912 bool ProbableTypo = isa<CompoundStmt>(Val: PossibleBody);
15913 if (!ProbableTypo) {
15914 bool BodyColInvalid;
15915 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15916 Loc: PossibleBody->getBeginLoc(), Invalid: &BodyColInvalid);
15917 if (BodyColInvalid)
15918 return;
15919
15920 bool StmtColInvalid;
15921 unsigned StmtCol =
15922 SourceMgr.getPresumedColumnNumber(Loc: S->getBeginLoc(), Invalid: &StmtColInvalid);
15923 if (StmtColInvalid)
15924 return;
15925
15926 if (BodyCol > StmtCol)
15927 ProbableTypo = true;
15928 }
15929
15930 if (ProbableTypo) {
15931 Diag(Loc: NBody->getSemiLoc(), DiagID);
15932 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
15933 }
15934}
15935
15936//===--- CHECK: Warn on self move with std::move. -------------------------===//
15937
15938void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15939 SourceLocation OpLoc) {
15940 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess, Loc: OpLoc))
15941 return;
15942
15943 if (inTemplateInstantiation())
15944 return;
15945
15946 // Strip parens and casts away.
15947 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15948 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15949
15950 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15951 // which we can treat as an inlined std::move
15952 if (const auto *CE = dyn_cast<CallExpr>(Val: RHSExpr);
15953 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15954 RHSExpr = CE->getArg(Arg: 0);
15955 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(Val: RHSExpr);
15956 CXXSCE && CXXSCE->isXValue())
15957 RHSExpr = CXXSCE->getSubExpr();
15958 else
15959 return;
15960
15961 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15962 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15963
15964 // Two DeclRefExpr's, check that the decls are the same.
15965 if (LHSDeclRef && RHSDeclRef) {
15966 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15967 return;
15968 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15969 RHSDeclRef->getDecl()->getCanonicalDecl())
15970 return;
15971
15972 auto D = Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
15973 << LHSExpr->getType() << LHSExpr->getSourceRange()
15974 << RHSExpr->getSourceRange();
15975 if (const FieldDecl *F =
15976 getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDeclRef->getDecl()))
15977 D << 1 << F
15978 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15979 else
15980 D << 0;
15981 return;
15982 }
15983
15984 // Member variables require a different approach to check for self moves.
15985 // MemberExpr's are the same if every nested MemberExpr refers to the same
15986 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15987 // the base Expr's are CXXThisExpr's.
15988 const Expr *LHSBase = LHSExpr;
15989 const Expr *RHSBase = RHSExpr;
15990 const MemberExpr *LHSME = dyn_cast<MemberExpr>(Val: LHSExpr);
15991 const MemberExpr *RHSME = dyn_cast<MemberExpr>(Val: RHSExpr);
15992 if (!LHSME || !RHSME)
15993 return;
15994
15995 while (LHSME && RHSME) {
15996 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15997 RHSME->getMemberDecl()->getCanonicalDecl())
15998 return;
15999
16000 LHSBase = LHSME->getBase();
16001 RHSBase = RHSME->getBase();
16002 LHSME = dyn_cast<MemberExpr>(Val: LHSBase);
16003 RHSME = dyn_cast<MemberExpr>(Val: RHSBase);
16004 }
16005
16006 LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSBase);
16007 RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSBase);
16008 if (LHSDeclRef && RHSDeclRef) {
16009 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16010 return;
16011 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16012 RHSDeclRef->getDecl()->getCanonicalDecl())
16013 return;
16014
16015 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16016 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16017 << RHSExpr->getSourceRange();
16018 return;
16019 }
16020
16021 if (isa<CXXThisExpr>(Val: LHSBase) && isa<CXXThisExpr>(Val: RHSBase))
16022 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16023 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16024 << RHSExpr->getSourceRange();
16025}
16026
16027//===--- Layout compatibility ----------------------------------------------//
16028
16029static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16030
16031/// Check if two enumeration types are layout-compatible.
16032static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16033 const EnumDecl *ED2) {
16034 // C++11 [dcl.enum] p8:
16035 // Two enumeration types are layout-compatible if they have the same
16036 // underlying type.
16037 return ED1->isComplete() && ED2->isComplete() &&
16038 C.hasSameType(T1: ED1->getIntegerType(), T2: ED2->getIntegerType());
16039}
16040
16041/// Check if two fields are layout-compatible.
16042/// Can be used on union members, which are exempt from alignment requirement
16043/// of common initial sequence.
16044static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16045 const FieldDecl *Field2,
16046 bool AreUnionMembers = false) {
16047#ifndef NDEBUG
16048 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16049 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16050 assert(((Field1Parent->isStructureOrClassType() &&
16051 Field2Parent->isStructureOrClassType()) ||
16052 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16053 "Can't evaluate layout compatibility between a struct field and a "
16054 "union field.");
16055 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16056 (AreUnionMembers && Field1Parent->isUnionType())) &&
16057 "AreUnionMembers should be 'true' for union fields (only).");
16058#endif
16059
16060 if (!isLayoutCompatible(C, T1: Field1->getType(), T2: Field2->getType()))
16061 return false;
16062
16063 if (Field1->isBitField() != Field2->isBitField())
16064 return false;
16065
16066 if (Field1->isBitField()) {
16067 // Make sure that the bit-fields are the same length.
16068 unsigned Bits1 = Field1->getBitWidthValue();
16069 unsigned Bits2 = Field2->getBitWidthValue();
16070
16071 if (Bits1 != Bits2)
16072 return false;
16073 }
16074
16075 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16076 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16077 return false;
16078
16079 if (!AreUnionMembers &&
16080 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16081 return false;
16082
16083 return true;
16084}
16085
16086/// Check if two standard-layout structs are layout-compatible.
16087/// (C++11 [class.mem] p17)
16088static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16089 const RecordDecl *RD2) {
16090 // Get to the class where the fields are declared
16091 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(Val: RD1))
16092 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16093
16094 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(Val: RD2))
16095 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16096
16097 // Check the fields.
16098 return llvm::equal(LRange: RD1->fields(), RRange: RD2->fields(),
16099 P: [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16100 return isLayoutCompatible(C, Field1: F1, Field2: F2);
16101 });
16102}
16103
16104/// Check if two standard-layout unions are layout-compatible.
16105/// (C++11 [class.mem] p18)
16106static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16107 const RecordDecl *RD2) {
16108 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16109 RD2->fields());
16110
16111 for (auto *Field1 : RD1->fields()) {
16112 auto I = UnmatchedFields.begin();
16113 auto E = UnmatchedFields.end();
16114
16115 for ( ; I != E; ++I) {
16116 if (isLayoutCompatible(C, Field1, Field2: *I, /*IsUnionMember=*/AreUnionMembers: true)) {
16117 bool Result = UnmatchedFields.erase(Ptr: *I);
16118 (void) Result;
16119 assert(Result);
16120 break;
16121 }
16122 }
16123 if (I == E)
16124 return false;
16125 }
16126
16127 return UnmatchedFields.empty();
16128}
16129
16130static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16131 const RecordDecl *RD2) {
16132 if (RD1->isUnion() != RD2->isUnion())
16133 return false;
16134
16135 if (RD1->isUnion())
16136 return isLayoutCompatibleUnion(C, RD1, RD2);
16137 else
16138 return isLayoutCompatibleStruct(C, RD1, RD2);
16139}
16140
16141/// Check if two types are layout-compatible in C++11 sense.
16142static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16143 if (T1.isNull() || T2.isNull())
16144 return false;
16145
16146 // C++20 [basic.types] p11:
16147 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16148 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16149 // or layout-compatible standard-layout class types (11.4).
16150 T1 = T1.getCanonicalType().getUnqualifiedType();
16151 T2 = T2.getCanonicalType().getUnqualifiedType();
16152
16153 if (C.hasSameType(T1, T2))
16154 return true;
16155
16156 const Type::TypeClass TC1 = T1->getTypeClass();
16157 const Type::TypeClass TC2 = T2->getTypeClass();
16158
16159 if (TC1 != TC2)
16160 return false;
16161
16162 if (TC1 == Type::Enum)
16163 return isLayoutCompatible(C, ED1: T1->castAsEnumDecl(), ED2: T2->castAsEnumDecl());
16164 if (TC1 == Type::Record) {
16165 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16166 return false;
16167
16168 return isLayoutCompatible(C, RD1: T1->castAsRecordDecl(),
16169 RD2: T2->castAsRecordDecl());
16170 }
16171
16172 return false;
16173}
16174
16175bool Sema::IsLayoutCompatible(QualType T1, QualType T2) const {
16176 return isLayoutCompatible(C: getASTContext(), T1, T2);
16177}
16178
16179//===-------------- Pointer interconvertibility ----------------------------//
16180
16181bool Sema::IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
16182 const TypeSourceInfo *Derived) {
16183 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16184 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16185
16186 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16187 getASTContext().hasSameType(T1: BaseT, T2: DerivedT))
16188 return true;
16189
16190 if (!IsDerivedFrom(Loc: Derived->getTypeLoc().getBeginLoc(), Derived: DerivedT, Base: BaseT))
16191 return false;
16192
16193 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16194 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16195 return true;
16196
16197 return false;
16198}
16199
16200//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16201
16202/// Given a type tag expression find the type tag itself.
16203///
16204/// \param TypeExpr Type tag expression, as it appears in user's code.
16205///
16206/// \param VD Declaration of an identifier that appears in a type tag.
16207///
16208/// \param MagicValue Type tag magic value.
16209///
16210/// \param isConstantEvaluated whether the evalaution should be performed in
16211
16212/// constant context.
16213static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16214 const ValueDecl **VD, uint64_t *MagicValue,
16215 bool isConstantEvaluated) {
16216 while(true) {
16217 if (!TypeExpr)
16218 return false;
16219
16220 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16221
16222 switch (TypeExpr->getStmtClass()) {
16223 case Stmt::UnaryOperatorClass: {
16224 const UnaryOperator *UO = cast<UnaryOperator>(Val: TypeExpr);
16225 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16226 TypeExpr = UO->getSubExpr();
16227 continue;
16228 }
16229 return false;
16230 }
16231
16232 case Stmt::DeclRefExprClass: {
16233 const DeclRefExpr *DRE = cast<DeclRefExpr>(Val: TypeExpr);
16234 *VD = DRE->getDecl();
16235 return true;
16236 }
16237
16238 case Stmt::IntegerLiteralClass: {
16239 const IntegerLiteral *IL = cast<IntegerLiteral>(Val: TypeExpr);
16240 llvm::APInt MagicValueAPInt = IL->getValue();
16241 if (MagicValueAPInt.getActiveBits() <= 64) {
16242 *MagicValue = MagicValueAPInt.getZExtValue();
16243 return true;
16244 } else
16245 return false;
16246 }
16247
16248 case Stmt::BinaryConditionalOperatorClass:
16249 case Stmt::ConditionalOperatorClass: {
16250 const AbstractConditionalOperator *ACO =
16251 cast<AbstractConditionalOperator>(Val: TypeExpr);
16252 bool Result;
16253 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16254 InConstantContext: isConstantEvaluated)) {
16255 if (Result)
16256 TypeExpr = ACO->getTrueExpr();
16257 else
16258 TypeExpr = ACO->getFalseExpr();
16259 continue;
16260 }
16261 return false;
16262 }
16263
16264 case Stmt::BinaryOperatorClass: {
16265 const BinaryOperator *BO = cast<BinaryOperator>(Val: TypeExpr);
16266 if (BO->getOpcode() == BO_Comma) {
16267 TypeExpr = BO->getRHS();
16268 continue;
16269 }
16270 return false;
16271 }
16272
16273 default:
16274 return false;
16275 }
16276 }
16277}
16278
16279/// Retrieve the C type corresponding to type tag TypeExpr.
16280///
16281/// \param TypeExpr Expression that specifies a type tag.
16282///
16283/// \param MagicValues Registered magic values.
16284///
16285/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16286/// kind.
16287///
16288/// \param TypeInfo Information about the corresponding C type.
16289///
16290/// \param isConstantEvaluated whether the evalaution should be performed in
16291/// constant context.
16292///
16293/// \returns true if the corresponding C type was found.
16294static bool GetMatchingCType(
16295 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16296 const ASTContext &Ctx,
16297 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16298 *MagicValues,
16299 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16300 bool isConstantEvaluated) {
16301 FoundWrongKind = false;
16302
16303 // Variable declaration that has type_tag_for_datatype attribute.
16304 const ValueDecl *VD = nullptr;
16305
16306 uint64_t MagicValue;
16307
16308 if (!FindTypeTagExpr(TypeExpr, Ctx, VD: &VD, MagicValue: &MagicValue, isConstantEvaluated))
16309 return false;
16310
16311 if (VD) {
16312 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16313 if (I->getArgumentKind() != ArgumentKind) {
16314 FoundWrongKind = true;
16315 return false;
16316 }
16317 TypeInfo.Type = I->getMatchingCType();
16318 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16319 TypeInfo.MustBeNull = I->getMustBeNull();
16320 return true;
16321 }
16322 return false;
16323 }
16324
16325 if (!MagicValues)
16326 return false;
16327
16328 llvm::DenseMap<Sema::TypeTagMagicValue,
16329 Sema::TypeTagData>::const_iterator I =
16330 MagicValues->find(Val: std::make_pair(x&: ArgumentKind, y&: MagicValue));
16331 if (I == MagicValues->end())
16332 return false;
16333
16334 TypeInfo = I->second;
16335 return true;
16336}
16337
16338void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16339 uint64_t MagicValue, QualType Type,
16340 bool LayoutCompatible,
16341 bool MustBeNull) {
16342 if (!TypeTagForDatatypeMagicValues)
16343 TypeTagForDatatypeMagicValues.reset(
16344 p: new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16345
16346 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16347 (*TypeTagForDatatypeMagicValues)[Magic] =
16348 TypeTagData(Type, LayoutCompatible, MustBeNull);
16349}
16350
16351static bool IsSameCharType(QualType T1, QualType T2) {
16352 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16353 if (!BT1)
16354 return false;
16355
16356 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16357 if (!BT2)
16358 return false;
16359
16360 BuiltinType::Kind T1Kind = BT1->getKind();
16361 BuiltinType::Kind T2Kind = BT2->getKind();
16362
16363 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16364 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16365 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16366 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16367}
16368
16369void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16370 const ArrayRef<const Expr *> ExprArgs,
16371 SourceLocation CallSiteLoc) {
16372 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16373 bool IsPointerAttr = Attr->getIsPointer();
16374
16375 // Retrieve the argument representing the 'type_tag'.
16376 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16377 if (TypeTagIdxAST >= ExprArgs.size()) {
16378 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
16379 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16380 return;
16381 }
16382 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16383 bool FoundWrongKind;
16384 TypeTagData TypeInfo;
16385 if (!GetMatchingCType(ArgumentKind, TypeExpr: TypeTagExpr, Ctx: Context,
16386 MagicValues: TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16387 TypeInfo, isConstantEvaluated: isConstantEvaluatedContext())) {
16388 if (FoundWrongKind)
16389 Diag(Loc: TypeTagExpr->getExprLoc(),
16390 DiagID: diag::warn_type_tag_for_datatype_wrong_kind)
16391 << TypeTagExpr->getSourceRange();
16392 return;
16393 }
16394
16395 // Retrieve the argument representing the 'arg_idx'.
16396 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16397 if (ArgumentIdxAST >= ExprArgs.size()) {
16398 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
16399 << 1 << Attr->getArgumentIdx().getSourceIndex();
16400 return;
16401 }
16402 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16403 if (IsPointerAttr) {
16404 // Skip implicit cast of pointer to `void *' (as a function argument).
16405 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgumentExpr))
16406 if (ICE->getType()->isVoidPointerType() &&
16407 ICE->getCastKind() == CK_BitCast)
16408 ArgumentExpr = ICE->getSubExpr();
16409 }
16410 QualType ArgumentType = ArgumentExpr->getType();
16411
16412 // Passing a `void*' pointer shouldn't trigger a warning.
16413 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16414 return;
16415
16416 if (TypeInfo.MustBeNull) {
16417 // Type tag with matching void type requires a null pointer.
16418 if (!ArgumentExpr->isNullPointerConstant(Ctx&: Context,
16419 NPC: Expr::NPC_ValueDependentIsNotNull)) {
16420 Diag(Loc: ArgumentExpr->getExprLoc(),
16421 DiagID: diag::warn_type_safety_null_pointer_required)
16422 << ArgumentKind->getName()
16423 << ArgumentExpr->getSourceRange()
16424 << TypeTagExpr->getSourceRange();
16425 }
16426 return;
16427 }
16428
16429 QualType RequiredType = TypeInfo.Type;
16430 if (IsPointerAttr)
16431 RequiredType = Context.getPointerType(T: RequiredType);
16432
16433 bool mismatch = false;
16434 if (!TypeInfo.LayoutCompatible) {
16435 mismatch = !Context.hasSameType(T1: ArgumentType, T2: RequiredType);
16436
16437 // C++11 [basic.fundamental] p1:
16438 // Plain char, signed char, and unsigned char are three distinct types.
16439 //
16440 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16441 // char' depending on the current char signedness mode.
16442 if (mismatch)
16443 if ((IsPointerAttr && IsSameCharType(T1: ArgumentType->getPointeeType(),
16444 T2: RequiredType->getPointeeType())) ||
16445 (!IsPointerAttr && IsSameCharType(T1: ArgumentType, T2: RequiredType)))
16446 mismatch = false;
16447 } else
16448 if (IsPointerAttr)
16449 mismatch = !isLayoutCompatible(C: Context,
16450 T1: ArgumentType->getPointeeType(),
16451 T2: RequiredType->getPointeeType());
16452 else
16453 mismatch = !isLayoutCompatible(C: Context, T1: ArgumentType, T2: RequiredType);
16454
16455 if (mismatch)
16456 Diag(Loc: ArgumentExpr->getExprLoc(), DiagID: diag::warn_type_safety_type_mismatch)
16457 << ArgumentType << ArgumentKind
16458 << TypeInfo.LayoutCompatible << RequiredType
16459 << ArgumentExpr->getSourceRange()
16460 << TypeTagExpr->getSourceRange();
16461}
16462
16463void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16464 CharUnits Alignment) {
16465 currentEvaluationContext().MisalignedMembers.emplace_back(Args&: E, Args&: RD, Args&: MD,
16466 Args&: Alignment);
16467}
16468
16469void Sema::DiagnoseMisalignedMembers() {
16470 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16471 const NamedDecl *ND = m.RD;
16472 if (ND->getName().empty()) {
16473 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16474 ND = TD;
16475 }
16476 Diag(Loc: m.E->getBeginLoc(), DiagID: diag::warn_taking_address_of_packed_member)
16477 << m.MD << ND << m.E->getSourceRange();
16478 }
16479 currentEvaluationContext().MisalignedMembers.clear();
16480}
16481
16482void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16483 E = E->IgnoreParens();
16484 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16485 return;
16486 if (isa<UnaryOperator>(Val: E) &&
16487 cast<UnaryOperator>(Val: E)->getOpcode() == UO_AddrOf) {
16488 auto *Op = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
16489 if (isa<MemberExpr>(Val: Op)) {
16490 auto &MisalignedMembersForExpr =
16491 currentEvaluationContext().MisalignedMembers;
16492 auto *MA = llvm::find(Range&: MisalignedMembersForExpr, Val: MisalignedMember(Op));
16493 if (MA != MisalignedMembersForExpr.end() &&
16494 (T->isDependentType() || T->isIntegerType() ||
16495 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16496 Context.getTypeAlignInChars(
16497 T: T->getPointeeType()) <= MA->Alignment))))
16498 MisalignedMembersForExpr.erase(CI: MA);
16499 }
16500 }
16501}
16502
16503void Sema::RefersToMemberWithReducedAlignment(
16504 Expr *E,
16505 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16506 Action) {
16507 const auto *ME = dyn_cast<MemberExpr>(Val: E);
16508 if (!ME)
16509 return;
16510
16511 // No need to check expressions with an __unaligned-qualified type.
16512 if (E->getType().getQualifiers().hasUnaligned())
16513 return;
16514
16515 // For a chain of MemberExpr like "a.b.c.d" this list
16516 // will keep FieldDecl's like [d, c, b].
16517 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16518 const MemberExpr *TopME = nullptr;
16519 bool AnyIsPacked = false;
16520 do {
16521 QualType BaseType = ME->getBase()->getType();
16522 if (BaseType->isDependentType())
16523 return;
16524 if (ME->isArrow())
16525 BaseType = BaseType->getPointeeType();
16526 auto *RD = BaseType->castAsRecordDecl();
16527 if (RD->isInvalidDecl())
16528 return;
16529
16530 ValueDecl *MD = ME->getMemberDecl();
16531 auto *FD = dyn_cast<FieldDecl>(Val: MD);
16532 // We do not care about non-data members.
16533 if (!FD || FD->isInvalidDecl())
16534 return;
16535
16536 AnyIsPacked =
16537 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16538 ReverseMemberChain.push_back(Elt: FD);
16539
16540 TopME = ME;
16541 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParens());
16542 } while (ME);
16543 assert(TopME && "We did not compute a topmost MemberExpr!");
16544
16545 // Not the scope of this diagnostic.
16546 if (!AnyIsPacked)
16547 return;
16548
16549 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16550 const auto *DRE = dyn_cast<DeclRefExpr>(Val: TopBase);
16551 // TODO: The innermost base of the member expression may be too complicated.
16552 // For now, just disregard these cases. This is left for future
16553 // improvement.
16554 if (!DRE && !isa<CXXThisExpr>(Val: TopBase))
16555 return;
16556
16557 // Alignment expected by the whole expression.
16558 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(T: E->getType());
16559
16560 // No need to do anything else with this case.
16561 if (ExpectedAlignment.isOne())
16562 return;
16563
16564 // Synthesize offset of the whole access.
16565 CharUnits Offset;
16566 for (const FieldDecl *FD : llvm::reverse(C&: ReverseMemberChain))
16567 Offset += Context.toCharUnitsFromBits(BitSize: Context.getFieldOffset(FD));
16568
16569 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16570 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16571 T: Context.getCanonicalTagType(TD: ReverseMemberChain.back()->getParent()));
16572
16573 // The base expression of the innermost MemberExpr may give
16574 // stronger guarantees than the class containing the member.
16575 if (DRE && !TopME->isArrow()) {
16576 const ValueDecl *VD = DRE->getDecl();
16577 if (!VD->getType()->isReferenceType())
16578 CompleteObjectAlignment =
16579 std::max(a: CompleteObjectAlignment, b: Context.getDeclAlign(D: VD));
16580 }
16581
16582 // Check if the synthesized offset fulfills the alignment.
16583 if (!Offset.isMultipleOf(N: ExpectedAlignment) ||
16584 // It may fulfill the offset it but the effective alignment may still be
16585 // lower than the expected expression alignment.
16586 CompleteObjectAlignment < ExpectedAlignment) {
16587 // If this happens, we want to determine a sensible culprit of this.
16588 // Intuitively, watching the chain of member expressions from right to
16589 // left, we start with the required alignment (as required by the field
16590 // type) but some packed attribute in that chain has reduced the alignment.
16591 // It may happen that another packed structure increases it again. But if
16592 // we are here such increase has not been enough. So pointing the first
16593 // FieldDecl that either is packed or else its RecordDecl is,
16594 // seems reasonable.
16595 FieldDecl *FD = nullptr;
16596 CharUnits Alignment;
16597 for (FieldDecl *FDI : ReverseMemberChain) {
16598 if (FDI->hasAttr<PackedAttr>() ||
16599 FDI->getParent()->hasAttr<PackedAttr>()) {
16600 FD = FDI;
16601 Alignment = std::min(a: Context.getTypeAlignInChars(T: FD->getType()),
16602 b: Context.getTypeAlignInChars(
16603 T: Context.getCanonicalTagType(TD: FD->getParent())));
16604 break;
16605 }
16606 }
16607 assert(FD && "We did not find a packed FieldDecl!");
16608 Action(E, FD->getParent(), FD, Alignment);
16609 }
16610}
16611
16612void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16613 using namespace std::placeholders;
16614
16615 RefersToMemberWithReducedAlignment(
16616 E: rhs, Action: std::bind(f: &Sema::AddPotentialMisalignedMembers, args: std::ref(t&: *this), args: _1,
16617 args: _2, args: _3, args: _4));
16618}
16619
16620bool Sema::PrepareBuiltinElementwiseMathOneArgCall(
16621 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16622 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16623 return true;
16624
16625 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
16626 if (A.isInvalid())
16627 return true;
16628
16629 TheCall->setArg(Arg: 0, ArgExpr: A.get());
16630 QualType TyA = A.get()->getType();
16631
16632 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
16633 ArgTyRestr, ArgOrdinal: 1))
16634 return true;
16635
16636 TheCall->setType(TyA);
16637 return false;
16638}
16639
16640bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16641 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16642 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16643 TheCall->setType(*Res);
16644 return false;
16645 }
16646 return true;
16647}
16648
16649bool Sema::BuiltinVectorToScalarMath(CallExpr *TheCall) {
16650 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16651 if (!Res)
16652 return true;
16653
16654 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16655 TheCall->setType(VecTy0->getElementType());
16656 else
16657 TheCall->setType(*Res);
16658
16659 return false;
16660}
16661
16662static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS,
16663 SourceLocation Loc) {
16664 QualType L = LHS->getEnumCoercedType(Ctx: S.Context),
16665 R = RHS->getEnumCoercedType(Ctx: S.Context);
16666 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16667 !S.Context.hasSameUnqualifiedType(T1: L, T2: R)) {
16668 return S.Diag(Loc, DiagID: diag::err_conv_mixed_enum_types)
16669 << LHS->getSourceRange() << RHS->getSourceRange()
16670 << /*Arithmetic Between*/ 0 << L << R;
16671 }
16672 return false;
16673}
16674
16675/// Check if all arguments have the same type. If the types don't match, emit an
16676/// error message and return true. Otherwise return false.
16677///
16678/// For scalars we directly compare their unqualified types. But even if we
16679/// compare unqualified vector types, a difference in qualifiers in the element
16680/// types can make the vector types be considered not equal. For example,
16681/// vector of 4 'const float' values vs vector of 4 'float' values.
16682/// So we compare unqualified types of their elements and number of elements.
16683static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef,
16684 ArrayRef<Expr *> Args) {
16685 assert(!Args.empty() && "Should have at least one argument.");
16686
16687 Expr *Arg0 = Args.front();
16688 QualType Ty0 = Arg0->getType();
16689
16690 auto EmitError = [&](Expr *ArgI) {
16691 SemaRef.Diag(Loc: Arg0->getBeginLoc(),
16692 DiagID: diag::err_typecheck_call_different_arg_types)
16693 << Arg0->getType() << ArgI->getType();
16694 };
16695
16696 // Compare scalar types.
16697 if (!Ty0->isVectorType()) {
16698 for (Expr *ArgI : Args.drop_front())
16699 if (!SemaRef.Context.hasSameUnqualifiedType(T1: Ty0, T2: ArgI->getType())) {
16700 EmitError(ArgI);
16701 return true;
16702 }
16703
16704 return false;
16705 }
16706
16707 // Compare vector types.
16708 const auto *Vec0 = Ty0->castAs<VectorType>();
16709 for (Expr *ArgI : Args.drop_front()) {
16710 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16711 if (!VecI ||
16712 !SemaRef.Context.hasSameUnqualifiedType(T1: Vec0->getElementType(),
16713 T2: VecI->getElementType()) ||
16714 Vec0->getNumElements() != VecI->getNumElements()) {
16715 EmitError(ArgI);
16716 return true;
16717 }
16718 }
16719
16720 return false;
16721}
16722
16723std::optional<QualType>
16724Sema::BuiltinVectorMath(CallExpr *TheCall,
16725 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16726 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
16727 return std::nullopt;
16728
16729 if (checkBuiltinVectorMathMixedEnums(
16730 S&: *this, LHS: TheCall->getArg(Arg: 0), RHS: TheCall->getArg(Arg: 1), Loc: TheCall->getExprLoc()))
16731 return std::nullopt;
16732
16733 Expr *Args[2];
16734 for (int I = 0; I < 2; ++I) {
16735 ExprResult Converted =
16736 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
16737 if (Converted.isInvalid())
16738 return std::nullopt;
16739 Args[I] = Converted.get();
16740 }
16741
16742 SourceLocation LocA = Args[0]->getBeginLoc();
16743 QualType TyA = Args[0]->getType();
16744
16745 if (checkMathBuiltinElementType(S&: *this, Loc: LocA, ArgTy: TyA, ArgTyRestr, ArgOrdinal: 1))
16746 return std::nullopt;
16747
16748 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
16749 return std::nullopt;
16750
16751 TheCall->setArg(Arg: 0, ArgExpr: Args[0]);
16752 TheCall->setArg(Arg: 1, ArgExpr: Args[1]);
16753 return TyA;
16754}
16755
16756bool Sema::BuiltinElementwiseTernaryMath(
16757 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16758 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
16759 return true;
16760
16761 SourceLocation Loc = TheCall->getExprLoc();
16762 if (checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 0),
16763 RHS: TheCall->getArg(Arg: 1), Loc) ||
16764 checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 1),
16765 RHS: TheCall->getArg(Arg: 2), Loc))
16766 return true;
16767
16768 Expr *Args[3];
16769 for (int I = 0; I < 3; ++I) {
16770 ExprResult Converted =
16771 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
16772 if (Converted.isInvalid())
16773 return true;
16774 Args[I] = Converted.get();
16775 }
16776
16777 int ArgOrdinal = 1;
16778 for (Expr *Arg : Args) {
16779 if (checkMathBuiltinElementType(S&: *this, Loc: Arg->getBeginLoc(), ArgTy: Arg->getType(),
16780 ArgTyRestr, ArgOrdinal: ArgOrdinal++))
16781 return true;
16782 }
16783
16784 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
16785 return true;
16786
16787 for (int I = 0; I < 3; ++I)
16788 TheCall->setArg(Arg: I, ArgExpr: Args[I]);
16789
16790 TheCall->setType(Args[0]->getType());
16791 return false;
16792}
16793
16794bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16795 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16796 return true;
16797
16798 ExprResult A = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
16799 if (A.isInvalid())
16800 return true;
16801
16802 TheCall->setArg(Arg: 0, ArgExpr: A.get());
16803 return false;
16804}
16805
16806bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16807 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16808 return true;
16809
16810 ExprResult Arg = TheCall->getArg(Arg: 0);
16811 QualType TyArg = Arg.get()->getType();
16812
16813 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16814 return Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
16815 DiagID: diag::err_builtin_invalid_arg_type)
16816 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16817
16818 TheCall->setType(TyArg);
16819 return false;
16820}
16821
16822ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16823 ExprResult CallResult) {
16824 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16825 return ExprError();
16826
16827 ExprResult MatrixArg = DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
16828 if (MatrixArg.isInvalid())
16829 return MatrixArg;
16830 Expr *Matrix = MatrixArg.get();
16831
16832 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16833 if (!MType) {
16834 Diag(Loc: Matrix->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16835 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16836 << Matrix->getType();
16837 return ExprError();
16838 }
16839
16840 // Create returned matrix type by swapping rows and columns of the argument
16841 // matrix type.
16842 QualType ResultType = Context.getConstantMatrixType(
16843 ElementType: MType->getElementType(), NumRows: MType->getNumColumns(), NumColumns: MType->getNumRows());
16844
16845 // Change the return type to the type of the returned matrix.
16846 TheCall->setType(ResultType);
16847
16848 // Update call argument to use the possibly converted matrix argument.
16849 TheCall->setArg(Arg: 0, ArgExpr: Matrix);
16850 return CallResult;
16851}
16852
16853// Get and verify the matrix dimensions.
16854static std::optional<unsigned>
16855getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16856 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(Ctx: S.Context);
16857 if (!Value) {
16858 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_scalar_unsigned_arg)
16859 << Name;
16860 return {};
16861 }
16862 uint64_t Dim = Value->getZExtValue();
16863 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
16864 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_invalid_dimension)
16865 << Name << S.Context.getLangOpts().MaxMatrixDimension;
16866 return {};
16867 }
16868 return Dim;
16869}
16870
16871ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16872 ExprResult CallResult) {
16873 if (!getLangOpts().MatrixTypes) {
16874 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
16875 return ExprError();
16876 }
16877
16878 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16879 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
16880 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
16881 << /*column*/ 1 << /*load*/ 0;
16882 return ExprError();
16883 }
16884
16885 if (checkArgCount(Call: TheCall, DesiredArgCount: 4))
16886 return ExprError();
16887
16888 unsigned PtrArgIdx = 0;
16889 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
16890 Expr *RowsExpr = TheCall->getArg(Arg: 1);
16891 Expr *ColumnsExpr = TheCall->getArg(Arg: 2);
16892 Expr *StrideExpr = TheCall->getArg(Arg: 3);
16893
16894 bool ArgError = false;
16895
16896 // Check pointer argument.
16897 {
16898 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
16899 if (PtrConv.isInvalid())
16900 return PtrConv;
16901 PtrExpr = PtrConv.get();
16902 TheCall->setArg(Arg: 0, ArgExpr: PtrExpr);
16903 if (PtrExpr->isTypeDependent()) {
16904 TheCall->setType(Context.DependentTy);
16905 return TheCall;
16906 }
16907 }
16908
16909 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16910 QualType ElementTy;
16911 if (!PtrTy) {
16912 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16913 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16914 << PtrExpr->getType();
16915 ArgError = true;
16916 } else {
16917 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16918
16919 if (!ConstantMatrixType::isValidElementType(T: ElementTy, LangOpts: getLangOpts())) {
16920 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16921 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16922 << /* no fp */ 0 << PtrExpr->getType();
16923 ArgError = true;
16924 }
16925 }
16926
16927 // Apply default Lvalue conversions and convert the expression to size_t.
16928 auto ApplyArgumentConversions = [this](Expr *E) {
16929 ExprResult Conv = DefaultLvalueConversion(E);
16930 if (Conv.isInvalid())
16931 return Conv;
16932
16933 return tryConvertExprToType(E: Conv.get(), Ty: Context.getSizeType());
16934 };
16935
16936 // Apply conversion to row and column expressions.
16937 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16938 if (!RowsConv.isInvalid()) {
16939 RowsExpr = RowsConv.get();
16940 TheCall->setArg(Arg: 1, ArgExpr: RowsExpr);
16941 } else
16942 RowsExpr = nullptr;
16943
16944 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16945 if (!ColumnsConv.isInvalid()) {
16946 ColumnsExpr = ColumnsConv.get();
16947 TheCall->setArg(Arg: 2, ArgExpr: ColumnsExpr);
16948 } else
16949 ColumnsExpr = nullptr;
16950
16951 // If any part of the result matrix type is still pending, just use
16952 // Context.DependentTy, until all parts are resolved.
16953 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16954 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16955 TheCall->setType(Context.DependentTy);
16956 return CallResult;
16957 }
16958
16959 // Check row and column dimensions.
16960 std::optional<unsigned> MaybeRows;
16961 if (RowsExpr)
16962 MaybeRows = getAndVerifyMatrixDimension(Expr: RowsExpr, Name: "row", S&: *this);
16963
16964 std::optional<unsigned> MaybeColumns;
16965 if (ColumnsExpr)
16966 MaybeColumns = getAndVerifyMatrixDimension(Expr: ColumnsExpr, Name: "column", S&: *this);
16967
16968 // Check stride argument.
16969 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16970 if (StrideConv.isInvalid())
16971 return ExprError();
16972 StrideExpr = StrideConv.get();
16973 TheCall->setArg(Arg: 3, ArgExpr: StrideExpr);
16974
16975 if (MaybeRows) {
16976 if (std::optional<llvm::APSInt> Value =
16977 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
16978 uint64_t Stride = Value->getZExtValue();
16979 if (Stride < *MaybeRows) {
16980 Diag(Loc: StrideExpr->getBeginLoc(),
16981 DiagID: diag::err_builtin_matrix_stride_too_small);
16982 ArgError = true;
16983 }
16984 }
16985 }
16986
16987 if (ArgError || !MaybeRows || !MaybeColumns)
16988 return ExprError();
16989
16990 TheCall->setType(
16991 Context.getConstantMatrixType(ElementType: ElementTy, NumRows: *MaybeRows, NumColumns: *MaybeColumns));
16992 return CallResult;
16993}
16994
16995ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16996 ExprResult CallResult) {
16997 if (!getLangOpts().MatrixTypes) {
16998 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
16999 return ExprError();
17000 }
17001
17002 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17003 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
17004 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
17005 << /*column*/ 1 << /*store*/ 1;
17006 return ExprError();
17007 }
17008
17009 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
17010 return ExprError();
17011
17012 unsigned PtrArgIdx = 1;
17013 Expr *MatrixExpr = TheCall->getArg(Arg: 0);
17014 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
17015 Expr *StrideExpr = TheCall->getArg(Arg: 2);
17016
17017 bool ArgError = false;
17018
17019 {
17020 ExprResult MatrixConv = DefaultLvalueConversion(E: MatrixExpr);
17021 if (MatrixConv.isInvalid())
17022 return MatrixConv;
17023 MatrixExpr = MatrixConv.get();
17024 TheCall->setArg(Arg: 0, ArgExpr: MatrixExpr);
17025 }
17026 if (MatrixExpr->isTypeDependent()) {
17027 TheCall->setType(Context.DependentTy);
17028 return TheCall;
17029 }
17030
17031 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17032 if (!MatrixTy) {
17033 Diag(Loc: MatrixExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17034 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17035 ArgError = true;
17036 }
17037
17038 {
17039 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
17040 if (PtrConv.isInvalid())
17041 return PtrConv;
17042 PtrExpr = PtrConv.get();
17043 TheCall->setArg(Arg: 1, ArgExpr: PtrExpr);
17044 if (PtrExpr->isTypeDependent()) {
17045 TheCall->setType(Context.DependentTy);
17046 return TheCall;
17047 }
17048 }
17049
17050 // Check pointer argument.
17051 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17052 if (!PtrTy) {
17053 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17054 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17055 << PtrExpr->getType();
17056 ArgError = true;
17057 } else {
17058 QualType ElementTy = PtrTy->getPointeeType();
17059 if (ElementTy.isConstQualified()) {
17060 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_matrix_store_to_const);
17061 ArgError = true;
17062 }
17063 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17064 if (MatrixTy &&
17065 !Context.hasSameType(T1: ElementTy, T2: MatrixTy->getElementType())) {
17066 Diag(Loc: PtrExpr->getBeginLoc(),
17067 DiagID: diag::err_builtin_matrix_pointer_arg_mismatch)
17068 << ElementTy << MatrixTy->getElementType();
17069 ArgError = true;
17070 }
17071 }
17072
17073 // Apply default Lvalue conversions and convert the stride expression to
17074 // size_t.
17075 {
17076 ExprResult StrideConv = DefaultLvalueConversion(E: StrideExpr);
17077 if (StrideConv.isInvalid())
17078 return StrideConv;
17079
17080 StrideConv = tryConvertExprToType(E: StrideConv.get(), Ty: Context.getSizeType());
17081 if (StrideConv.isInvalid())
17082 return StrideConv;
17083 StrideExpr = StrideConv.get();
17084 TheCall->setArg(Arg: 2, ArgExpr: StrideExpr);
17085 }
17086
17087 // Check stride argument.
17088 if (MatrixTy) {
17089 if (std::optional<llvm::APSInt> Value =
17090 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
17091 uint64_t Stride = Value->getZExtValue();
17092 if (Stride < MatrixTy->getNumRows()) {
17093 Diag(Loc: StrideExpr->getBeginLoc(),
17094 DiagID: diag::err_builtin_matrix_stride_too_small);
17095 ArgError = true;
17096 }
17097 }
17098 }
17099
17100 if (ArgError)
17101 return ExprError();
17102
17103 return CallResult;
17104}
17105
17106void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
17107 const NamedDecl *Callee) {
17108 // This warning does not make sense in code that has no runtime behavior.
17109 if (isUnevaluatedContext())
17110 return;
17111
17112 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17113
17114 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17115 return;
17116
17117 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17118 // all TCBs the callee is a part of.
17119 llvm::StringSet<> CalleeTCBs;
17120 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17121 CalleeTCBs.insert(key: A->getTCBName());
17122 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17123 CalleeTCBs.insert(key: A->getTCBName());
17124
17125 // Go through the TCBs the caller is a part of and emit warnings if Caller
17126 // is in a TCB that the Callee is not.
17127 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17128 StringRef CallerTCB = A->getTCBName();
17129 if (CalleeTCBs.count(Key: CallerTCB) == 0) {
17130 this->Diag(Loc: CallExprLoc, DiagID: diag::warn_tcb_enforcement_violation)
17131 << Callee << CallerTCB;
17132 }
17133 }
17134}
17135