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
2826ExprResult
2827Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2828 CallExpr *TheCall) {
2829 ExprResult TheCallResult(TheCall);
2830
2831 // Find out if any arguments are required to be integer constant expressions.
2832 unsigned ICEArguments = 0;
2833 ASTContext::GetBuiltinTypeError Error;
2834 Context.GetBuiltinType(ID: BuiltinID, Error, IntegerConstantArgs: &ICEArguments);
2835 if (Error != ASTContext::GE_None)
2836 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2837
2838 // If any arguments are required to be ICE's, check and diagnose.
2839 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2840 // Skip arguments not required to be ICE's.
2841 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2842
2843 llvm::APSInt Result;
2844 // If we don't have enough arguments, continue so we can issue better
2845 // diagnostic in checkArgCount(...)
2846 if (ArgNo < TheCall->getNumArgs() &&
2847 BuiltinConstantArg(TheCall, ArgNum: ArgNo, Result))
2848 return true;
2849 ICEArguments &= ~(1 << ArgNo);
2850 }
2851
2852 FPOptions FPO;
2853 switch (BuiltinID) {
2854 case Builtin::BI__builtin_cpu_supports:
2855 case Builtin::BI__builtin_cpu_is:
2856 if (BuiltinCpu(S&: *this, TI: Context.getTargetInfo(), TheCall,
2857 AuxTI: Context.getAuxTargetInfo(), BuiltinID))
2858 return ExprError();
2859 break;
2860 case Builtin::BI__builtin_cpu_init:
2861 if (!Context.getTargetInfo().supportsCpuInit()) {
2862 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2863 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2864 return ExprError();
2865 }
2866 break;
2867 case Builtin::BI__builtin___CFStringMakeConstantString:
2868 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
2869 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
2870 if (CheckBuiltinTargetNotInUnsupported(
2871 S&: *this, BuiltinID, TheCall,
2872 UnsupportedObjectFormatTypes: {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
2873 return ExprError();
2874 assert(TheCall->getNumArgs() == 1 &&
2875 "Wrong # arguments to builtin CFStringMakeConstantString");
2876 if (ObjC().CheckObjCString(Arg: TheCall->getArg(Arg: 0)))
2877 return ExprError();
2878 break;
2879 case Builtin::BI__builtin_ms_va_start:
2880 case Builtin::BI__builtin_stdarg_start:
2881 case Builtin::BI__builtin_va_start:
2882 case Builtin::BI__builtin_c23_va_start:
2883 if (BuiltinVAStart(BuiltinID, TheCall))
2884 return ExprError();
2885 break;
2886 case Builtin::BI__va_start: {
2887 switch (Context.getTargetInfo().getTriple().getArch()) {
2888 case llvm::Triple::aarch64:
2889 case llvm::Triple::arm:
2890 case llvm::Triple::thumb:
2891 if (BuiltinVAStartARMMicrosoft(Call: TheCall))
2892 return ExprError();
2893 break;
2894 default:
2895 if (BuiltinVAStart(BuiltinID, TheCall))
2896 return ExprError();
2897 break;
2898 }
2899 break;
2900 }
2901
2902 // The acquire, release, and no fence variants are ARM and AArch64 only.
2903 case Builtin::BI_interlockedbittestandset_acq:
2904 case Builtin::BI_interlockedbittestandset_rel:
2905 case Builtin::BI_interlockedbittestandset_nf:
2906 case Builtin::BI_interlockedbittestandreset_acq:
2907 case Builtin::BI_interlockedbittestandreset_rel:
2908 case Builtin::BI_interlockedbittestandreset_nf:
2909 if (CheckBuiltinTargetInSupported(
2910 S&: *this, TheCall,
2911 SupportedArchs: {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
2912 return ExprError();
2913 break;
2914
2915 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
2916 case Builtin::BI_bittest64:
2917 case Builtin::BI_bittestandcomplement64:
2918 case Builtin::BI_bittestandreset64:
2919 case Builtin::BI_bittestandset64:
2920 case Builtin::BI_interlockedbittestandreset64:
2921 case Builtin::BI_interlockedbittestandset64:
2922 if (CheckBuiltinTargetInSupported(
2923 S&: *this, TheCall,
2924 SupportedArchs: {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
2925 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
2926 return ExprError();
2927 break;
2928
2929 // The 64-bit acquire, release, and no fence variants are AArch64 only.
2930 case Builtin::BI_interlockedbittestandreset64_acq:
2931 case Builtin::BI_interlockedbittestandreset64_rel:
2932 case Builtin::BI_interlockedbittestandreset64_nf:
2933 case Builtin::BI_interlockedbittestandset64_acq:
2934 case Builtin::BI_interlockedbittestandset64_rel:
2935 case Builtin::BI_interlockedbittestandset64_nf:
2936 if (CheckBuiltinTargetInSupported(S&: *this, TheCall, SupportedArchs: {llvm::Triple::aarch64}))
2937 return ExprError();
2938 break;
2939
2940 case Builtin::BI__builtin_set_flt_rounds:
2941 if (CheckBuiltinTargetInSupported(
2942 S&: *this, TheCall,
2943 SupportedArchs: {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
2944 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
2945 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
2946 llvm::Triple::ppc64le}))
2947 return ExprError();
2948 break;
2949
2950 case Builtin::BI__builtin_isgreater:
2951 case Builtin::BI__builtin_isgreaterequal:
2952 case Builtin::BI__builtin_isless:
2953 case Builtin::BI__builtin_islessequal:
2954 case Builtin::BI__builtin_islessgreater:
2955 case Builtin::BI__builtin_isunordered:
2956 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
2957 return ExprError();
2958 break;
2959 case Builtin::BI__builtin_fpclassify:
2960 if (BuiltinFPClassification(TheCall, NumArgs: 6, BuiltinID))
2961 return ExprError();
2962 break;
2963 case Builtin::BI__builtin_isfpclass:
2964 if (BuiltinFPClassification(TheCall, NumArgs: 2, BuiltinID))
2965 return ExprError();
2966 break;
2967 case Builtin::BI__builtin_isfinite:
2968 case Builtin::BI__builtin_isinf:
2969 case Builtin::BI__builtin_isinf_sign:
2970 case Builtin::BI__builtin_isnan:
2971 case Builtin::BI__builtin_issignaling:
2972 case Builtin::BI__builtin_isnormal:
2973 case Builtin::BI__builtin_issubnormal:
2974 case Builtin::BI__builtin_iszero:
2975 case Builtin::BI__builtin_signbit:
2976 case Builtin::BI__builtin_signbitf:
2977 case Builtin::BI__builtin_signbitl:
2978 if (BuiltinFPClassification(TheCall, NumArgs: 1, BuiltinID))
2979 return ExprError();
2980 break;
2981 case Builtin::BI__builtin_shufflevector:
2982 return BuiltinShuffleVector(TheCall);
2983 // TheCall will be freed by the smart pointer here, but that's fine, since
2984 // BuiltinShuffleVector guts it, but then doesn't release it.
2985 case Builtin::BI__builtin_masked_load:
2986 case Builtin::BI__builtin_masked_expand_load:
2987 return BuiltinMaskedLoad(S&: *this, TheCall);
2988 case Builtin::BI__builtin_masked_store:
2989 case Builtin::BI__builtin_masked_compress_store:
2990 return BuiltinMaskedStore(S&: *this, TheCall);
2991 case Builtin::BI__builtin_masked_gather:
2992 return BuiltinMaskedGather(S&: *this, TheCall);
2993 case Builtin::BI__builtin_masked_scatter:
2994 return BuiltinMaskedScatter(S&: *this, TheCall);
2995 case Builtin::BI__builtin_invoke:
2996 return BuiltinInvoke(S&: *this, TheCall);
2997 case Builtin::BI__builtin_prefetch:
2998 if (BuiltinPrefetch(TheCall))
2999 return ExprError();
3000 break;
3001 case Builtin::BI__builtin_alloca_with_align:
3002 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3003 if (BuiltinAllocaWithAlign(TheCall))
3004 return ExprError();
3005 [[fallthrough]];
3006 case Builtin::BI__builtin_alloca:
3007 case Builtin::BI__builtin_alloca_uninitialized:
3008 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca)
3009 << TheCall->getDirectCallee();
3010 if (getLangOpts().OpenCL) {
3011 builtinAllocaAddrSpace(S&: *this, TheCall);
3012 }
3013 break;
3014 case Builtin::BI__builtin_infer_alloc_token:
3015 if (checkBuiltinInferAllocToken(S&: *this, TheCall))
3016 return ExprError();
3017 break;
3018 case Builtin::BI__arithmetic_fence:
3019 if (BuiltinArithmeticFence(TheCall))
3020 return ExprError();
3021 break;
3022 case Builtin::BI__assume:
3023 case Builtin::BI__builtin_assume:
3024 if (BuiltinAssume(TheCall))
3025 return ExprError();
3026 break;
3027 case Builtin::BI__builtin_assume_aligned:
3028 if (BuiltinAssumeAligned(TheCall))
3029 return ExprError();
3030 break;
3031 case Builtin::BI__builtin_dynamic_object_size:
3032 case Builtin::BI__builtin_object_size:
3033 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: 3))
3034 return ExprError();
3035 break;
3036 case Builtin::BI__builtin_longjmp:
3037 if (BuiltinLongjmp(TheCall))
3038 return ExprError();
3039 break;
3040 case Builtin::BI__builtin_setjmp:
3041 if (BuiltinSetjmp(TheCall))
3042 return ExprError();
3043 break;
3044 case Builtin::BI__builtin_classify_type:
3045 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3046 return true;
3047 TheCall->setType(Context.IntTy);
3048 break;
3049 case Builtin::BI__builtin_complex:
3050 if (BuiltinComplex(TheCall))
3051 return ExprError();
3052 break;
3053 case Builtin::BI__builtin_constant_p: {
3054 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3055 return true;
3056 ExprResult Arg = DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
3057 if (Arg.isInvalid()) return true;
3058 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
3059 TheCall->setType(Context.IntTy);
3060 break;
3061 }
3062 case Builtin::BI__builtin_launder:
3063 return BuiltinLaunder(S&: *this, TheCall);
3064 case Builtin::BI__builtin_is_within_lifetime:
3065 return BuiltinIsWithinLifetime(S&: *this, TheCall);
3066 case Builtin::BI__builtin_trivially_relocate:
3067 return BuiltinTriviallyRelocate(S&: *this, TheCall);
3068
3069 case Builtin::BI__sync_fetch_and_add:
3070 case Builtin::BI__sync_fetch_and_add_1:
3071 case Builtin::BI__sync_fetch_and_add_2:
3072 case Builtin::BI__sync_fetch_and_add_4:
3073 case Builtin::BI__sync_fetch_and_add_8:
3074 case Builtin::BI__sync_fetch_and_add_16:
3075 case Builtin::BI__sync_fetch_and_sub:
3076 case Builtin::BI__sync_fetch_and_sub_1:
3077 case Builtin::BI__sync_fetch_and_sub_2:
3078 case Builtin::BI__sync_fetch_and_sub_4:
3079 case Builtin::BI__sync_fetch_and_sub_8:
3080 case Builtin::BI__sync_fetch_and_sub_16:
3081 case Builtin::BI__sync_fetch_and_or:
3082 case Builtin::BI__sync_fetch_and_or_1:
3083 case Builtin::BI__sync_fetch_and_or_2:
3084 case Builtin::BI__sync_fetch_and_or_4:
3085 case Builtin::BI__sync_fetch_and_or_8:
3086 case Builtin::BI__sync_fetch_and_or_16:
3087 case Builtin::BI__sync_fetch_and_and:
3088 case Builtin::BI__sync_fetch_and_and_1:
3089 case Builtin::BI__sync_fetch_and_and_2:
3090 case Builtin::BI__sync_fetch_and_and_4:
3091 case Builtin::BI__sync_fetch_and_and_8:
3092 case Builtin::BI__sync_fetch_and_and_16:
3093 case Builtin::BI__sync_fetch_and_xor:
3094 case Builtin::BI__sync_fetch_and_xor_1:
3095 case Builtin::BI__sync_fetch_and_xor_2:
3096 case Builtin::BI__sync_fetch_and_xor_4:
3097 case Builtin::BI__sync_fetch_and_xor_8:
3098 case Builtin::BI__sync_fetch_and_xor_16:
3099 case Builtin::BI__sync_fetch_and_nand:
3100 case Builtin::BI__sync_fetch_and_nand_1:
3101 case Builtin::BI__sync_fetch_and_nand_2:
3102 case Builtin::BI__sync_fetch_and_nand_4:
3103 case Builtin::BI__sync_fetch_and_nand_8:
3104 case Builtin::BI__sync_fetch_and_nand_16:
3105 case Builtin::BI__sync_add_and_fetch:
3106 case Builtin::BI__sync_add_and_fetch_1:
3107 case Builtin::BI__sync_add_and_fetch_2:
3108 case Builtin::BI__sync_add_and_fetch_4:
3109 case Builtin::BI__sync_add_and_fetch_8:
3110 case Builtin::BI__sync_add_and_fetch_16:
3111 case Builtin::BI__sync_sub_and_fetch:
3112 case Builtin::BI__sync_sub_and_fetch_1:
3113 case Builtin::BI__sync_sub_and_fetch_2:
3114 case Builtin::BI__sync_sub_and_fetch_4:
3115 case Builtin::BI__sync_sub_and_fetch_8:
3116 case Builtin::BI__sync_sub_and_fetch_16:
3117 case Builtin::BI__sync_and_and_fetch:
3118 case Builtin::BI__sync_and_and_fetch_1:
3119 case Builtin::BI__sync_and_and_fetch_2:
3120 case Builtin::BI__sync_and_and_fetch_4:
3121 case Builtin::BI__sync_and_and_fetch_8:
3122 case Builtin::BI__sync_and_and_fetch_16:
3123 case Builtin::BI__sync_or_and_fetch:
3124 case Builtin::BI__sync_or_and_fetch_1:
3125 case Builtin::BI__sync_or_and_fetch_2:
3126 case Builtin::BI__sync_or_and_fetch_4:
3127 case Builtin::BI__sync_or_and_fetch_8:
3128 case Builtin::BI__sync_or_and_fetch_16:
3129 case Builtin::BI__sync_xor_and_fetch:
3130 case Builtin::BI__sync_xor_and_fetch_1:
3131 case Builtin::BI__sync_xor_and_fetch_2:
3132 case Builtin::BI__sync_xor_and_fetch_4:
3133 case Builtin::BI__sync_xor_and_fetch_8:
3134 case Builtin::BI__sync_xor_and_fetch_16:
3135 case Builtin::BI__sync_nand_and_fetch:
3136 case Builtin::BI__sync_nand_and_fetch_1:
3137 case Builtin::BI__sync_nand_and_fetch_2:
3138 case Builtin::BI__sync_nand_and_fetch_4:
3139 case Builtin::BI__sync_nand_and_fetch_8:
3140 case Builtin::BI__sync_nand_and_fetch_16:
3141 case Builtin::BI__sync_val_compare_and_swap:
3142 case Builtin::BI__sync_val_compare_and_swap_1:
3143 case Builtin::BI__sync_val_compare_and_swap_2:
3144 case Builtin::BI__sync_val_compare_and_swap_4:
3145 case Builtin::BI__sync_val_compare_and_swap_8:
3146 case Builtin::BI__sync_val_compare_and_swap_16:
3147 case Builtin::BI__sync_bool_compare_and_swap:
3148 case Builtin::BI__sync_bool_compare_and_swap_1:
3149 case Builtin::BI__sync_bool_compare_and_swap_2:
3150 case Builtin::BI__sync_bool_compare_and_swap_4:
3151 case Builtin::BI__sync_bool_compare_and_swap_8:
3152 case Builtin::BI__sync_bool_compare_and_swap_16:
3153 case Builtin::BI__sync_lock_test_and_set:
3154 case Builtin::BI__sync_lock_test_and_set_1:
3155 case Builtin::BI__sync_lock_test_and_set_2:
3156 case Builtin::BI__sync_lock_test_and_set_4:
3157 case Builtin::BI__sync_lock_test_and_set_8:
3158 case Builtin::BI__sync_lock_test_and_set_16:
3159 case Builtin::BI__sync_lock_release:
3160 case Builtin::BI__sync_lock_release_1:
3161 case Builtin::BI__sync_lock_release_2:
3162 case Builtin::BI__sync_lock_release_4:
3163 case Builtin::BI__sync_lock_release_8:
3164 case Builtin::BI__sync_lock_release_16:
3165 case Builtin::BI__sync_swap:
3166 case Builtin::BI__sync_swap_1:
3167 case Builtin::BI__sync_swap_2:
3168 case Builtin::BI__sync_swap_4:
3169 case Builtin::BI__sync_swap_8:
3170 case Builtin::BI__sync_swap_16:
3171 return BuiltinAtomicOverloaded(TheCallResult);
3172 case Builtin::BI__sync_synchronize:
3173 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
3174 << TheCall->getCallee()->getSourceRange();
3175 break;
3176 case Builtin::BI__builtin_nontemporal_load:
3177 case Builtin::BI__builtin_nontemporal_store:
3178 return BuiltinNontemporalOverloaded(TheCallResult);
3179 case Builtin::BI__builtin_memcpy_inline: {
3180 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3181 // We warn about copying to or from `nullptr` pointers when `size` is
3182 // greater than 0. When `size` is value dependent we cannot evaluate its
3183 // value so we bail out.
3184 if (SizeOp->isValueDependent())
3185 break;
3186 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero()) {
3187 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3188 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 1), CallSiteLoc: TheCall->getExprLoc());
3189 }
3190 break;
3191 }
3192 case Builtin::BI__builtin_memset_inline: {
3193 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3194 // We warn about filling to `nullptr` pointers when `size` is greater than
3195 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3196 // out.
3197 if (SizeOp->isValueDependent())
3198 break;
3199 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero())
3200 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3201 break;
3202 }
3203#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3204 case Builtin::BI##ID: \
3205 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3206#include "clang/Basic/Builtins.inc"
3207 case Builtin::BI__annotation:
3208 if (BuiltinMSVCAnnotation(S&: *this, TheCall))
3209 return ExprError();
3210 break;
3211 case Builtin::BI__builtin_annotation:
3212 if (BuiltinAnnotation(S&: *this, TheCall))
3213 return ExprError();
3214 break;
3215 case Builtin::BI__builtin_addressof:
3216 if (BuiltinAddressof(S&: *this, TheCall))
3217 return ExprError();
3218 break;
3219 case Builtin::BI__builtin_function_start:
3220 if (BuiltinFunctionStart(S&: *this, TheCall))
3221 return ExprError();
3222 break;
3223 case Builtin::BI__builtin_is_aligned:
3224 case Builtin::BI__builtin_align_up:
3225 case Builtin::BI__builtin_align_down:
3226 if (BuiltinAlignment(S&: *this, TheCall, ID: BuiltinID))
3227 return ExprError();
3228 break;
3229 case Builtin::BI__builtin_add_overflow:
3230 case Builtin::BI__builtin_sub_overflow:
3231 case Builtin::BI__builtin_mul_overflow:
3232 if (BuiltinOverflow(S&: *this, TheCall, BuiltinID))
3233 return ExprError();
3234 break;
3235 case Builtin::BI__builtin_operator_new:
3236 case Builtin::BI__builtin_operator_delete: {
3237 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3238 ExprResult Res =
3239 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3240 return Res;
3241 }
3242 case Builtin::BI__builtin_dump_struct:
3243 return BuiltinDumpStruct(S&: *this, TheCall);
3244 case Builtin::BI__builtin_expect_with_probability: {
3245 // We first want to ensure we are called with 3 arguments
3246 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
3247 return ExprError();
3248 // then check probability is constant float in range [0.0, 1.0]
3249 const Expr *ProbArg = TheCall->getArg(Arg: 2);
3250 SmallVector<PartialDiagnosticAt, 8> Notes;
3251 Expr::EvalResult Eval;
3252 Eval.Diag = &Notes;
3253 if ((!ProbArg->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context)) ||
3254 !Eval.Val.isFloat()) {
3255 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_not_constant_float)
3256 << ProbArg->getSourceRange();
3257 for (const PartialDiagnosticAt &PDiag : Notes)
3258 Diag(Loc: PDiag.first, PD: PDiag.second);
3259 return ExprError();
3260 }
3261 llvm::APFloat Probability = Eval.Val.getFloat();
3262 bool LoseInfo = false;
3263 Probability.convert(ToSemantics: llvm::APFloat::IEEEdouble(),
3264 RM: llvm::RoundingMode::Dynamic, losesInfo: &LoseInfo);
3265 if (!(Probability >= llvm::APFloat(0.0) &&
3266 Probability <= llvm::APFloat(1.0))) {
3267 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_out_of_range)
3268 << ProbArg->getSourceRange();
3269 return ExprError();
3270 }
3271 break;
3272 }
3273 case Builtin::BI__builtin_preserve_access_index:
3274 if (BuiltinPreserveAI(S&: *this, TheCall))
3275 return ExprError();
3276 break;
3277 case Builtin::BI__builtin_call_with_static_chain:
3278 if (BuiltinCallWithStaticChain(S&: *this, BuiltinCall: TheCall))
3279 return ExprError();
3280 break;
3281 case Builtin::BI__exception_code:
3282 case Builtin::BI_exception_code:
3283 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHExceptScope,
3284 DiagID: diag::err_seh___except_block))
3285 return ExprError();
3286 break;
3287 case Builtin::BI__exception_info:
3288 case Builtin::BI_exception_info:
3289 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHFilterScope,
3290 DiagID: diag::err_seh___except_filter))
3291 return ExprError();
3292 break;
3293 case Builtin::BI__GetExceptionInfo:
3294 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3295 return ExprError();
3296
3297 if (CheckCXXThrowOperand(
3298 ThrowLoc: TheCall->getBeginLoc(),
3299 ThrowTy: Context.getExceptionObjectType(T: FDecl->getParamDecl(i: 0)->getType()),
3300 E: TheCall))
3301 return ExprError();
3302
3303 TheCall->setType(Context.VoidPtrTy);
3304 break;
3305 case Builtin::BIaddressof:
3306 case Builtin::BI__addressof:
3307 case Builtin::BIforward:
3308 case Builtin::BIforward_like:
3309 case Builtin::BImove:
3310 case Builtin::BImove_if_noexcept:
3311 case Builtin::BIas_const: {
3312 // These are all expected to be of the form
3313 // T &/&&/* f(U &/&&)
3314 // where T and U only differ in qualification.
3315 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3316 return ExprError();
3317 QualType Param = FDecl->getParamDecl(i: 0)->getType();
3318 QualType Result = FDecl->getReturnType();
3319 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3320 BuiltinID == Builtin::BI__addressof;
3321 if (!(Param->isReferenceType() &&
3322 (ReturnsPointer ? Result->isAnyPointerType()
3323 : Result->isReferenceType()) &&
3324 Context.hasSameUnqualifiedType(T1: Param->getPointeeType(),
3325 T2: Result->getPointeeType()))) {
3326 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_move_forward_unsupported)
3327 << FDecl;
3328 return ExprError();
3329 }
3330 break;
3331 }
3332 case Builtin::BI__builtin_ptrauth_strip:
3333 return PointerAuthStrip(S&: *this, Call: TheCall);
3334 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3335 return PointerAuthBlendDiscriminator(S&: *this, Call: TheCall);
3336 case Builtin::BI__builtin_ptrauth_sign_constant:
3337 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3338 /*RequireConstant=*/true);
3339 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3340 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3341 /*RequireConstant=*/false);
3342 case Builtin::BI__builtin_ptrauth_auth:
3343 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Auth,
3344 /*RequireConstant=*/false);
3345 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3346 return PointerAuthSignGenericData(S&: *this, Call: TheCall);
3347 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3348 return PointerAuthAuthAndResign(S&: *this, Call: TheCall);
3349 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3350 return PointerAuthAuthLoadRelativeAndSign(S&: *this, Call: TheCall);
3351 case Builtin::BI__builtin_ptrauth_string_discriminator:
3352 return PointerAuthStringDiscriminator(S&: *this, Call: TheCall);
3353
3354 case Builtin::BI__builtin_get_vtable_pointer:
3355 return GetVTablePointer(S&: *this, Call: TheCall);
3356
3357 // OpenCL v2.0, s6.13.16 - Pipe functions
3358 case Builtin::BIread_pipe:
3359 case Builtin::BIwrite_pipe:
3360 // Since those two functions are declared with var args, we need a semantic
3361 // check for the argument.
3362 if (OpenCL().checkBuiltinRWPipe(Call: TheCall))
3363 return ExprError();
3364 break;
3365 case Builtin::BIreserve_read_pipe:
3366 case Builtin::BIreserve_write_pipe:
3367 case Builtin::BIwork_group_reserve_read_pipe:
3368 case Builtin::BIwork_group_reserve_write_pipe:
3369 if (OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3370 return ExprError();
3371 break;
3372 case Builtin::BIsub_group_reserve_read_pipe:
3373 case Builtin::BIsub_group_reserve_write_pipe:
3374 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3375 OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3376 return ExprError();
3377 break;
3378 case Builtin::BIcommit_read_pipe:
3379 case Builtin::BIcommit_write_pipe:
3380 case Builtin::BIwork_group_commit_read_pipe:
3381 case Builtin::BIwork_group_commit_write_pipe:
3382 if (OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3383 return ExprError();
3384 break;
3385 case Builtin::BIsub_group_commit_read_pipe:
3386 case Builtin::BIsub_group_commit_write_pipe:
3387 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3388 OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3389 return ExprError();
3390 break;
3391 case Builtin::BIget_pipe_num_packets:
3392 case Builtin::BIget_pipe_max_packets:
3393 if (OpenCL().checkBuiltinPipePackets(Call: TheCall))
3394 return ExprError();
3395 break;
3396 case Builtin::BIto_global:
3397 case Builtin::BIto_local:
3398 case Builtin::BIto_private:
3399 if (OpenCL().checkBuiltinToAddr(BuiltinID, Call: TheCall))
3400 return ExprError();
3401 break;
3402 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3403 case Builtin::BIenqueue_kernel:
3404 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3405 return ExprError();
3406 break;
3407 case Builtin::BIget_kernel_work_group_size:
3408 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3409 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3410 return ExprError();
3411 break;
3412 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3413 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3414 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3415 return ExprError();
3416 break;
3417 case Builtin::BI__builtin_os_log_format:
3418 Cleanup.setExprNeedsCleanups(true);
3419 [[fallthrough]];
3420 case Builtin::BI__builtin_os_log_format_buffer_size:
3421 if (BuiltinOSLogFormat(TheCall))
3422 return ExprError();
3423 break;
3424 case Builtin::BI__builtin_frame_address:
3425 case Builtin::BI__builtin_return_address: {
3426 if (BuiltinConstantArgRange(TheCall, ArgNum: 0, Low: 0, High: 0xFFFF))
3427 return ExprError();
3428
3429 // -Wframe-address warning if non-zero passed to builtin
3430 // return/frame address.
3431 Expr::EvalResult Result;
3432 if (!TheCall->getArg(Arg: 0)->isValueDependent() &&
3433 TheCall->getArg(Arg: 0)->EvaluateAsInt(Result, Ctx: getASTContext()) &&
3434 Result.Val.getInt() != 0)
3435 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_frame_address)
3436 << ((BuiltinID == Builtin::BI__builtin_return_address)
3437 ? "__builtin_return_address"
3438 : "__builtin_frame_address")
3439 << TheCall->getSourceRange();
3440 break;
3441 }
3442
3443 case Builtin::BI__builtin_nondeterministic_value: {
3444 if (BuiltinNonDeterministicValue(TheCall))
3445 return ExprError();
3446 break;
3447 }
3448
3449 // __builtin_elementwise_abs restricts the element type to signed integers or
3450 // floating point types only.
3451 case Builtin::BI__builtin_elementwise_abs:
3452 if (PrepareBuiltinElementwiseMathOneArgCall(
3453 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy))
3454 return ExprError();
3455 break;
3456
3457 // These builtins restrict the element type to floating point
3458 // types only.
3459 case Builtin::BI__builtin_elementwise_acos:
3460 case Builtin::BI__builtin_elementwise_asin:
3461 case Builtin::BI__builtin_elementwise_atan:
3462 case Builtin::BI__builtin_elementwise_ceil:
3463 case Builtin::BI__builtin_elementwise_cos:
3464 case Builtin::BI__builtin_elementwise_cosh:
3465 case Builtin::BI__builtin_elementwise_exp:
3466 case Builtin::BI__builtin_elementwise_exp2:
3467 case Builtin::BI__builtin_elementwise_exp10:
3468 case Builtin::BI__builtin_elementwise_floor:
3469 case Builtin::BI__builtin_elementwise_log:
3470 case Builtin::BI__builtin_elementwise_log2:
3471 case Builtin::BI__builtin_elementwise_log10:
3472 case Builtin::BI__builtin_elementwise_roundeven:
3473 case Builtin::BI__builtin_elementwise_round:
3474 case Builtin::BI__builtin_elementwise_rint:
3475 case Builtin::BI__builtin_elementwise_nearbyint:
3476 case Builtin::BI__builtin_elementwise_sin:
3477 case Builtin::BI__builtin_elementwise_sinh:
3478 case Builtin::BI__builtin_elementwise_sqrt:
3479 case Builtin::BI__builtin_elementwise_tan:
3480 case Builtin::BI__builtin_elementwise_tanh:
3481 case Builtin::BI__builtin_elementwise_trunc:
3482 case Builtin::BI__builtin_elementwise_canonicalize:
3483 if (PrepareBuiltinElementwiseMathOneArgCall(
3484 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3485 return ExprError();
3486 break;
3487 case Builtin::BI__builtin_elementwise_fma:
3488 if (BuiltinElementwiseTernaryMath(TheCall))
3489 return ExprError();
3490 break;
3491
3492 case Builtin::BI__builtin_elementwise_ldexp: {
3493 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3494 return ExprError();
3495
3496 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
3497 if (A.isInvalid())
3498 return ExprError();
3499 QualType TyA = A.get()->getType();
3500 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
3501 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1))
3502 return ExprError();
3503
3504 ExprResult Exp = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3505 if (Exp.isInvalid())
3506 return ExprError();
3507 QualType TyExp = Exp.get()->getType();
3508 if (checkMathBuiltinElementType(S&: *this, Loc: Exp.get()->getBeginLoc(), ArgTy: TyExp,
3509 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy,
3510 ArgOrdinal: 2))
3511 return ExprError();
3512
3513 // Check the two arguments are either scalars or vectors of equal length.
3514 const auto *Vec0 = TyA->getAs<VectorType>();
3515 const auto *Vec1 = TyExp->getAs<VectorType>();
3516 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3517 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3518 if (Arg0Length != Arg1Length) {
3519 Diag(Loc: Exp.get()->getBeginLoc(),
3520 DiagID: diag::err_typecheck_vector_lengths_not_equal)
3521 << TyA << TyExp << A.get()->getSourceRange()
3522 << Exp.get()->getSourceRange();
3523 return ExprError();
3524 }
3525
3526 TheCall->setArg(Arg: 0, ArgExpr: A.get());
3527 TheCall->setArg(Arg: 1, ArgExpr: Exp.get());
3528 TheCall->setType(TyA);
3529 break;
3530 }
3531
3532 // These builtins restrict the element type to floating point
3533 // types only, and take in two arguments.
3534 case Builtin::BI__builtin_elementwise_minnum:
3535 case Builtin::BI__builtin_elementwise_maxnum:
3536 case Builtin::BI__builtin_elementwise_minimum:
3537 case Builtin::BI__builtin_elementwise_maximum:
3538 case Builtin::BI__builtin_elementwise_minimumnum:
3539 case Builtin::BI__builtin_elementwise_maximumnum:
3540 case Builtin::BI__builtin_elementwise_atan2:
3541 case Builtin::BI__builtin_elementwise_fmod:
3542 case Builtin::BI__builtin_elementwise_pow:
3543 if (BuiltinElementwiseMath(TheCall,
3544 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3545 return ExprError();
3546 break;
3547 // These builtins restrict the element type to integer
3548 // types only.
3549 case Builtin::BI__builtin_elementwise_add_sat:
3550 case Builtin::BI__builtin_elementwise_sub_sat:
3551 if (BuiltinElementwiseMath(TheCall,
3552 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3553 return ExprError();
3554 break;
3555 case Builtin::BI__builtin_elementwise_fshl:
3556 case Builtin::BI__builtin_elementwise_fshr:
3557 if (BuiltinElementwiseTernaryMath(
3558 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3559 return ExprError();
3560 break;
3561 case Builtin::BI__builtin_elementwise_min:
3562 case Builtin::BI__builtin_elementwise_max:
3563 if (BuiltinElementwiseMath(TheCall))
3564 return ExprError();
3565 break;
3566 case Builtin::BI__builtin_elementwise_popcount:
3567 case Builtin::BI__builtin_elementwise_bitreverse:
3568 if (PrepareBuiltinElementwiseMathOneArgCall(
3569 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3570 return ExprError();
3571 break;
3572 case Builtin::BI__builtin_elementwise_copysign: {
3573 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3574 return ExprError();
3575
3576 ExprResult Magnitude = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
3577 ExprResult Sign = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3578 if (Magnitude.isInvalid() || Sign.isInvalid())
3579 return ExprError();
3580
3581 QualType MagnitudeTy = Magnitude.get()->getType();
3582 QualType SignTy = Sign.get()->getType();
3583 if (checkMathBuiltinElementType(
3584 S&: *this, Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), ArgTy: MagnitudeTy,
3585 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1) ||
3586 checkMathBuiltinElementType(
3587 S&: *this, Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), ArgTy: SignTy,
3588 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 2)) {
3589 return ExprError();
3590 }
3591
3592 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3593 return Diag(Loc: Sign.get()->getBeginLoc(),
3594 DiagID: diag::err_typecheck_call_different_arg_types)
3595 << MagnitudeTy << SignTy;
3596 }
3597
3598 TheCall->setArg(Arg: 0, ArgExpr: Magnitude.get());
3599 TheCall->setArg(Arg: 1, ArgExpr: Sign.get());
3600 TheCall->setType(Magnitude.get()->getType());
3601 break;
3602 }
3603 case Builtin::BI__builtin_elementwise_clzg:
3604 case Builtin::BI__builtin_elementwise_ctzg:
3605 // These builtins can be unary or binary. Note for empty calls we call the
3606 // unary checker in order to not emit an error that says the function
3607 // expects 2 arguments, which would be misleading.
3608 if (TheCall->getNumArgs() <= 1) {
3609 if (PrepareBuiltinElementwiseMathOneArgCall(
3610 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3611 return ExprError();
3612 } else if (BuiltinElementwiseMath(
3613 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3614 return ExprError();
3615 break;
3616 case Builtin::BI__builtin_reduce_max:
3617 case Builtin::BI__builtin_reduce_min: {
3618 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3619 return ExprError();
3620
3621 const Expr *Arg = TheCall->getArg(Arg: 0);
3622 const auto *TyA = Arg->getType()->getAs<VectorType>();
3623
3624 QualType ElTy;
3625 if (TyA)
3626 ElTy = TyA->getElementType();
3627 else if (Arg->getType()->isSizelessVectorType())
3628 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
3629
3630 if (ElTy.isNull()) {
3631 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3632 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3633 << Arg->getType();
3634 return ExprError();
3635 }
3636
3637 TheCall->setType(ElTy);
3638 break;
3639 }
3640 case Builtin::BI__builtin_reduce_maximum:
3641 case Builtin::BI__builtin_reduce_minimum: {
3642 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3643 return ExprError();
3644
3645 const Expr *Arg = TheCall->getArg(Arg: 0);
3646 const auto *TyA = Arg->getType()->getAs<VectorType>();
3647
3648 QualType ElTy;
3649 if (TyA)
3650 ElTy = TyA->getElementType();
3651 else if (Arg->getType()->isSizelessVectorType())
3652 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
3653
3654 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3655 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3656 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3657 << Arg->getType();
3658 return ExprError();
3659 }
3660
3661 TheCall->setType(ElTy);
3662 break;
3663 }
3664
3665 // These builtins support vectors of integers only.
3666 // TODO: ADD/MUL should support floating-point types.
3667 case Builtin::BI__builtin_reduce_add:
3668 case Builtin::BI__builtin_reduce_mul:
3669 case Builtin::BI__builtin_reduce_xor:
3670 case Builtin::BI__builtin_reduce_or:
3671 case Builtin::BI__builtin_reduce_and: {
3672 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3673 return ExprError();
3674
3675 const Expr *Arg = TheCall->getArg(Arg: 0);
3676 const auto *TyA = Arg->getType()->getAs<VectorType>();
3677
3678 QualType ElTy;
3679 if (TyA)
3680 ElTy = TyA->getElementType();
3681 else if (Arg->getType()->isSizelessVectorType())
3682 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
3683
3684 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3685 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3686 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3687 << Arg->getType();
3688 return ExprError();
3689 }
3690
3691 TheCall->setType(ElTy);
3692 break;
3693 }
3694
3695 case Builtin::BI__builtin_matrix_transpose:
3696 return BuiltinMatrixTranspose(TheCall, CallResult: TheCallResult);
3697
3698 case Builtin::BI__builtin_matrix_column_major_load:
3699 return BuiltinMatrixColumnMajorLoad(TheCall, CallResult: TheCallResult);
3700
3701 case Builtin::BI__builtin_matrix_column_major_store:
3702 return BuiltinMatrixColumnMajorStore(TheCall, CallResult: TheCallResult);
3703
3704 case Builtin::BI__builtin_verbose_trap:
3705 if (!checkBuiltinVerboseTrap(Call: TheCall, S&: *this))
3706 return ExprError();
3707 break;
3708
3709 case Builtin::BI__builtin_get_device_side_mangled_name: {
3710 auto Check = [](CallExpr *TheCall) {
3711 if (TheCall->getNumArgs() != 1)
3712 return false;
3713 auto *DRE = dyn_cast<DeclRefExpr>(Val: TheCall->getArg(Arg: 0)->IgnoreImpCasts());
3714 if (!DRE)
3715 return false;
3716 auto *D = DRE->getDecl();
3717 if (!isa<FunctionDecl>(Val: D) && !isa<VarDecl>(Val: D))
3718 return false;
3719 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3720 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
3721 };
3722 if (!Check(TheCall)) {
3723 Diag(Loc: TheCall->getBeginLoc(),
3724 DiagID: diag::err_hip_invalid_args_builtin_mangled_name);
3725 return ExprError();
3726 }
3727 break;
3728 }
3729 case Builtin::BI__builtin_bswapg:
3730 if (BuiltinBswapg(S&: *this, TheCall))
3731 return ExprError();
3732 break;
3733 case Builtin::BI__builtin_bitreverseg:
3734 if (BuiltinBitreverseg(S&: *this, TheCall))
3735 return ExprError();
3736 break;
3737 case Builtin::BI__builtin_popcountg:
3738 if (BuiltinPopcountg(S&: *this, TheCall))
3739 return ExprError();
3740 break;
3741 case Builtin::BI__builtin_clzg:
3742 case Builtin::BI__builtin_ctzg:
3743 if (BuiltinCountZeroBitsGeneric(S&: *this, TheCall))
3744 return ExprError();
3745 break;
3746
3747 case Builtin::BI__builtin_stdc_rotate_left:
3748 case Builtin::BI__builtin_stdc_rotate_right:
3749 if (BuiltinRotateGeneric(S&: *this, TheCall))
3750 return ExprError();
3751 break;
3752
3753 case Builtin::BI__builtin_allow_runtime_check: {
3754 Expr *Arg = TheCall->getArg(Arg: 0);
3755 // Check if the argument is a string literal.
3756 if (!isa<StringLiteral>(Val: Arg->IgnoreParenImpCasts())) {
3757 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
3758 << Arg->getSourceRange();
3759 return ExprError();
3760 }
3761 break;
3762 }
3763
3764 case Builtin::BI__builtin_allow_sanitize_check: {
3765 Expr *Arg = TheCall->getArg(Arg: 0);
3766 // Check if the argument is a string literal.
3767 const StringLiteral *SanitizerName =
3768 dyn_cast<StringLiteral>(Val: Arg->IgnoreParenImpCasts());
3769 if (!SanitizerName) {
3770 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
3771 << Arg->getSourceRange();
3772 return ExprError();
3773 }
3774 // Validate the sanitizer name.
3775 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
3776 .Cases(CaseStrings: {"address", "thread", "memory", "hwaddress",
3777 "kernel-address", "kernel-memory", "kernel-hwaddress"},
3778 Value: true)
3779 .Default(Value: false)) {
3780 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_builtin_argument)
3781 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
3782 << Arg->getSourceRange();
3783 return ExprError();
3784 }
3785 break;
3786 }
3787 case Builtin::BI__builtin_counted_by_ref:
3788 if (BuiltinCountedByRef(TheCall))
3789 return ExprError();
3790 break;
3791 }
3792
3793 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
3794 return ExprError();
3795
3796 // Since the target specific builtins for each arch overlap, only check those
3797 // of the arch we are compiling for.
3798 if (Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID)) {
3799 if (Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID)) {
3800 assert(Context.getAuxTargetInfo() &&
3801 "Aux Target Builtin, but not an aux target?");
3802
3803 if (CheckTSBuiltinFunctionCall(
3804 TI: *Context.getAuxTargetInfo(),
3805 BuiltinID: Context.BuiltinInfo.getAuxBuiltinID(ID: BuiltinID), TheCall))
3806 return ExprError();
3807 } else {
3808 if (CheckTSBuiltinFunctionCall(TI: Context.getTargetInfo(), BuiltinID,
3809 TheCall))
3810 return ExprError();
3811 }
3812 }
3813
3814 return TheCallResult;
3815}
3816
3817bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3818 llvm::APSInt Result;
3819 // We can't check the value of a dependent argument.
3820 Expr *Arg = TheCall->getArg(Arg: ArgNum);
3821 if (Arg->isTypeDependent() || Arg->isValueDependent())
3822 return false;
3823
3824 // Check constant-ness first.
3825 if (BuiltinConstantArg(TheCall, ArgNum, Result))
3826 return true;
3827
3828 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3829 if (Result.isShiftedMask() || (~Result).isShiftedMask())
3830 return false;
3831
3832 return Diag(Loc: TheCall->getBeginLoc(),
3833 DiagID: diag::err_argument_not_contiguous_bit_field)
3834 << ArgNum << Arg->getSourceRange();
3835}
3836
3837bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
3838 unsigned FirstArg, FormatStringInfo *FSI) {
3839 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
3840 bool IsVariadic = false;
3841 if (const FunctionType *FnTy = D->getFunctionType())
3842 IsVariadic = cast<FunctionProtoType>(Val: FnTy)->isVariadic();
3843 else if (const auto *BD = dyn_cast<BlockDecl>(Val: D))
3844 IsVariadic = BD->isVariadic();
3845 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D))
3846 IsVariadic = OMD->isVariadic();
3847
3848 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
3849 IsVariadic, FSI);
3850}
3851
3852bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
3853 bool HasImplicitThisParam, bool IsVariadic,
3854 FormatStringInfo *FSI) {
3855 if (FirstArg == 0)
3856 FSI->ArgPassingKind = FAPK_VAList;
3857 else if (IsVariadic)
3858 FSI->ArgPassingKind = FAPK_Variadic;
3859 else
3860 FSI->ArgPassingKind = FAPK_Fixed;
3861 FSI->FormatIdx = FormatIdx - 1;
3862 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
3863
3864 // The way the format attribute works in GCC, the implicit this argument
3865 // of member functions is counted. However, it doesn't appear in our own
3866 // lists, so decrement format_idx in that case.
3867 if (HasImplicitThisParam) {
3868 if(FSI->FormatIdx == 0)
3869 return false;
3870 --FSI->FormatIdx;
3871 if (FSI->FirstDataArg != 0)
3872 --FSI->FirstDataArg;
3873 }
3874 return true;
3875}
3876
3877/// Checks if a the given expression evaluates to null.
3878///
3879/// Returns true if the value evaluates to null.
3880static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
3881 // Treat (smart) pointers constructed from nullptr as null, whether we can
3882 // const-evaluate them or not.
3883 // This must happen first: the smart pointer expr might have _Nonnull type!
3884 if (isa<CXXNullPtrLiteralExpr>(
3885 Val: IgnoreExprNodes(E: Expr, Fns&: IgnoreImplicitAsWrittenSingleStep,
3886 Fns&: IgnoreElidableImplicitConstructorSingleStep)))
3887 return true;
3888
3889 // If the expression has non-null type, it doesn't evaluate to null.
3890 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
3891 if (*nullability == NullabilityKind::NonNull)
3892 return false;
3893 }
3894
3895 // As a special case, transparent unions initialized with zero are
3896 // considered null for the purposes of the nonnull attribute.
3897 if (const RecordType *UT = Expr->getType()->getAsUnionType();
3898 UT &&
3899 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
3900 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Val: Expr))
3901 if (const auto *ILE = dyn_cast<InitListExpr>(Val: CLE->getInitializer()))
3902 Expr = ILE->getInit(Init: 0);
3903 }
3904
3905 bool Result;
3906 return (!Expr->isValueDependent() &&
3907 Expr->EvaluateAsBooleanCondition(Result, Ctx: S.Context) &&
3908 !Result);
3909}
3910
3911static void CheckNonNullArgument(Sema &S,
3912 const Expr *ArgExpr,
3913 SourceLocation CallSiteLoc) {
3914 if (CheckNonNullExpr(S, Expr: ArgExpr))
3915 S.DiagRuntimeBehavior(Loc: CallSiteLoc, Statement: ArgExpr,
3916 PD: S.PDiag(DiagID: diag::warn_null_arg)
3917 << ArgExpr->getSourceRange());
3918}
3919
3920/// Determine whether the given type has a non-null nullability annotation.
3921static bool isNonNullType(QualType type) {
3922 if (auto nullability = type->getNullability())
3923 return *nullability == NullabilityKind::NonNull;
3924
3925 return false;
3926}
3927
3928static void CheckNonNullArguments(Sema &S,
3929 const NamedDecl *FDecl,
3930 const FunctionProtoType *Proto,
3931 ArrayRef<const Expr *> Args,
3932 SourceLocation CallSiteLoc) {
3933 assert((FDecl || Proto) && "Need a function declaration or prototype");
3934
3935 // Already checked by constant evaluator.
3936 if (S.isConstantEvaluatedContext())
3937 return;
3938 // Check the attributes attached to the method/function itself.
3939 llvm::SmallBitVector NonNullArgs;
3940 if (FDecl) {
3941 // Handle the nonnull attribute on the function/method declaration itself.
3942 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
3943 if (!NonNull->args_size()) {
3944 // Easy case: all pointer arguments are nonnull.
3945 for (const auto *Arg : Args)
3946 if (S.isValidPointerAttrType(T: Arg->getType()))
3947 CheckNonNullArgument(S, ArgExpr: Arg, CallSiteLoc);
3948 return;
3949 }
3950
3951 for (const ParamIdx &Idx : NonNull->args()) {
3952 unsigned IdxAST = Idx.getASTIndex();
3953 if (IdxAST >= Args.size())
3954 continue;
3955 if (NonNullArgs.empty())
3956 NonNullArgs.resize(N: Args.size());
3957 NonNullArgs.set(IdxAST);
3958 }
3959 }
3960 }
3961
3962 if (FDecl && (isa<FunctionDecl>(Val: FDecl) || isa<ObjCMethodDecl>(Val: FDecl))) {
3963 // Handle the nonnull attribute on the parameters of the
3964 // function/method.
3965 ArrayRef<ParmVarDecl*> parms;
3966 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: FDecl))
3967 parms = FD->parameters();
3968 else
3969 parms = cast<ObjCMethodDecl>(Val: FDecl)->parameters();
3970
3971 unsigned ParamIndex = 0;
3972 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
3973 I != E; ++I, ++ParamIndex) {
3974 const ParmVarDecl *PVD = *I;
3975 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(type: PVD->getType())) {
3976 if (NonNullArgs.empty())
3977 NonNullArgs.resize(N: Args.size());
3978
3979 NonNullArgs.set(ParamIndex);
3980 }
3981 }
3982 } else {
3983 // If we have a non-function, non-method declaration but no
3984 // function prototype, try to dig out the function prototype.
3985 if (!Proto) {
3986 if (const ValueDecl *VD = dyn_cast<ValueDecl>(Val: FDecl)) {
3987 QualType type = VD->getType().getNonReferenceType();
3988 if (auto pointerType = type->getAs<PointerType>())
3989 type = pointerType->getPointeeType();
3990 else if (auto blockType = type->getAs<BlockPointerType>())
3991 type = blockType->getPointeeType();
3992 // FIXME: data member pointers?
3993
3994 // Dig out the function prototype, if there is one.
3995 Proto = type->getAs<FunctionProtoType>();
3996 }
3997 }
3998
3999 // Fill in non-null argument information from the nullability
4000 // information on the parameter types (if we have them).
4001 if (Proto) {
4002 unsigned Index = 0;
4003 for (auto paramType : Proto->getParamTypes()) {
4004 if (isNonNullType(type: paramType)) {
4005 if (NonNullArgs.empty())
4006 NonNullArgs.resize(N: Args.size());
4007
4008 NonNullArgs.set(Index);
4009 }
4010
4011 ++Index;
4012 }
4013 }
4014 }
4015
4016 // Check for non-null arguments.
4017 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4018 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4019 if (NonNullArgs[ArgIndex])
4020 CheckNonNullArgument(S, ArgExpr: Args[ArgIndex], CallSiteLoc: Args[ArgIndex]->getExprLoc());
4021 }
4022}
4023
4024void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4025 StringRef ParamName, QualType ArgTy,
4026 QualType ParamTy) {
4027
4028 // If a function accepts a pointer or reference type
4029 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4030 return;
4031
4032 // If the parameter is a pointer type, get the pointee type for the
4033 // argument too. If the parameter is a reference type, don't try to get
4034 // the pointee type for the argument.
4035 if (ParamTy->isPointerType())
4036 ArgTy = ArgTy->getPointeeType();
4037
4038 // Remove reference or pointer
4039 ParamTy = ParamTy->getPointeeType();
4040
4041 // Find expected alignment, and the actual alignment of the passed object.
4042 // getTypeAlignInChars requires complete types
4043 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4044 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4045 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4046 return;
4047
4048 CharUnits ParamAlign = Context.getTypeAlignInChars(T: ParamTy);
4049 CharUnits ArgAlign = Context.getTypeAlignInChars(T: ArgTy);
4050
4051 // If the argument is less aligned than the parameter, there is a
4052 // potential alignment issue.
4053 if (ArgAlign < ParamAlign)
4054 Diag(Loc, DiagID: diag::warn_param_mismatched_alignment)
4055 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4056 << ParamName << (FDecl != nullptr) << FDecl;
4057}
4058
4059void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4060 const Expr *ThisArg,
4061 ArrayRef<const Expr *> Args) {
4062 if (!FD || Args.empty())
4063 return;
4064 auto GetArgAt = [&](int Idx) -> const Expr * {
4065 if (Idx == LifetimeCaptureByAttr::Global ||
4066 Idx == LifetimeCaptureByAttr::Unknown)
4067 return nullptr;
4068 if (IsMemberFunction && Idx == 0)
4069 return ThisArg;
4070 return Args[Idx - IsMemberFunction];
4071 };
4072 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4073 unsigned ArgIdx) {
4074 if (!Attr)
4075 return;
4076
4077 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4078 for (int CapturingParamIdx : Attr->params()) {
4079 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4080 // initialization codepath.
4081 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4082 isa<CXXConstructorDecl>(Val: FD))
4083 continue;
4084 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4085 CapturingEntity CE{.Entity: Capturing};
4086 // Ensure that 'Captured' outlives the 'Capturing' entity.
4087 checkCaptureByLifetime(SemaRef&: *this, Entity: CE, Init: Captured);
4088 }
4089 };
4090 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4091 HandleCaptureByAttr(FD->getParamDecl(i: I)->getAttr<LifetimeCaptureByAttr>(),
4092 I + IsMemberFunction);
4093 // Check when the implicit object param is captured.
4094 if (IsMemberFunction) {
4095 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4096 if (!TSI)
4097 return;
4098 AttributedTypeLoc ATL;
4099 for (TypeLoc TL = TSI->getTypeLoc();
4100 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4101 TL = ATL.getModifiedLoc())
4102 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4103 }
4104}
4105
4106void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4107 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4108 bool IsMemberFunction, SourceLocation Loc,
4109 SourceRange Range, VariadicCallType CallType) {
4110 // FIXME: We should check as much as we can in the template definition.
4111 if (CurContext->isDependentContext())
4112 return;
4113
4114 // Printf and scanf checking.
4115 llvm::SmallBitVector CheckedVarArgs;
4116 if (FDecl) {
4117 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4118 // Only create vector if there are format attributes.
4119 CheckedVarArgs.resize(N: Args.size());
4120 CheckFormatString(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4121 CheckedVarArgs);
4122 }
4123
4124 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4125 CheckedVarArgs.resize(N: Args.size());
4126 CheckFormatArguments(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4127 CheckedVarArgs);
4128 }
4129 }
4130
4131 // Refuse POD arguments that weren't caught by the format string
4132 // checks above.
4133 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: FDecl);
4134 if (CallType != VariadicCallType::DoesNotApply &&
4135 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4136 unsigned NumParams = Proto ? Proto->getNumParams()
4137 : isa_and_nonnull<FunctionDecl>(Val: FDecl)
4138 ? cast<FunctionDecl>(Val: FDecl)->getNumParams()
4139 : isa_and_nonnull<ObjCMethodDecl>(Val: FDecl)
4140 ? cast<ObjCMethodDecl>(Val: FDecl)->param_size()
4141 : 0;
4142
4143 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4144 // Args[ArgIdx] can be null in malformed code.
4145 if (const Expr *Arg = Args[ArgIdx]) {
4146 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4147 checkVariadicArgument(E: Arg, CT: CallType);
4148 }
4149 }
4150 }
4151 if (FD)
4152 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4153 if (FDecl || Proto) {
4154 CheckNonNullArguments(S&: *this, FDecl, Proto, Args, CallSiteLoc: Loc);
4155
4156 // Type safety checking.
4157 if (FDecl) {
4158 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4159 CheckArgumentWithTypeTag(Attr: I, ExprArgs: Args, CallSiteLoc: Loc);
4160 }
4161 }
4162
4163 // Check that passed arguments match the alignment of original arguments.
4164 // Try to get the missing prototype from the declaration.
4165 if (!Proto && FDecl) {
4166 const auto *FT = FDecl->getFunctionType();
4167 if (isa_and_nonnull<FunctionProtoType>(Val: FT))
4168 Proto = cast<FunctionProtoType>(Val: FDecl->getFunctionType());
4169 }
4170 if (Proto) {
4171 // For variadic functions, we may have more args than parameters.
4172 // For some K&R functions, we may have less args than parameters.
4173 const auto N = std::min<unsigned>(a: Proto->getNumParams(), b: Args.size());
4174 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4175 bool IsScalableArg = false;
4176 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4177 // Args[ArgIdx] can be null in malformed code.
4178 if (const Expr *Arg = Args[ArgIdx]) {
4179 if (Arg->containsErrors())
4180 continue;
4181
4182 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4183 FDecl->hasLinkage() &&
4184 FDecl->getFormalLinkage() != Linkage::Internal &&
4185 CallType == VariadicCallType::DoesNotApply)
4186 PPC().checkAIXMemberAlignment(Loc: (Arg->getExprLoc()), Arg);
4187
4188 QualType ParamTy = Proto->getParamType(i: ArgIdx);
4189 if (ParamTy->isSizelessVectorType())
4190 IsScalableArg = true;
4191 QualType ArgTy = Arg->getType();
4192 CheckArgAlignment(Loc: Arg->getExprLoc(), FDecl, ParamName: std::to_string(val: ArgIdx + 1),
4193 ArgTy, ParamTy);
4194 }
4195 }
4196
4197 // If the callee has an AArch64 SME attribute to indicate that it is an
4198 // __arm_streaming function, then the caller requires SME to be available.
4199 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
4200 if (ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask) {
4201 if (auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext)) {
4202 llvm::StringMap<bool> CallerFeatureMap;
4203 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, CallerFD);
4204 if (!CallerFeatureMap.contains(Key: "sme"))
4205 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4206 } else if (!Context.getTargetInfo().hasFeature(Feature: "sme")) {
4207 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4208 }
4209 }
4210
4211 // If the call requires a streaming-mode change and has scalable vector
4212 // arguments or return values, then warn the user that the streaming and
4213 // non-streaming vector lengths may be different.
4214 // When both streaming and non-streaming vector lengths are defined and
4215 // mismatched, produce an error.
4216 const auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext);
4217 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4218 (IsScalableArg || IsScalableRet)) {
4219 bool IsCalleeStreaming =
4220 ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
4221 bool IsCalleeStreamingCompatible =
4222 ExtInfo.AArch64SMEAttributes &
4223 FunctionType::SME_PStateSMCompatibleMask;
4224 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(FD: CallerFD);
4225 if (!IsCalleeStreamingCompatible &&
4226 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4227 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4228 const LangOptions &LO = getLangOpts();
4229 unsigned VL = LO.VScaleMin * 128;
4230 unsigned SVL = LO.VScaleStreamingMin * 128;
4231 bool IsVLMismatch = VL && SVL && VL != SVL;
4232
4233 auto EmitDiag = [&](bool IsArg) {
4234 if (IsVLMismatch) {
4235 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4236 // Emit warning for streaming-compatible callers
4237 Diag(Loc, DiagID: diag::warn_sme_streaming_compatible_vl_mismatch)
4238 << IsArg << IsCalleeStreaming << SVL << VL;
4239 else
4240 // Emit error otherwise
4241 Diag(Loc, DiagID: diag::err_sme_streaming_transition_vl_mismatch)
4242 << IsArg << SVL << VL;
4243 } else
4244 Diag(Loc, DiagID: diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4245 << IsArg;
4246 };
4247
4248 if (IsScalableArg)
4249 EmitDiag(true);
4250 if (IsScalableRet)
4251 EmitDiag(false);
4252 }
4253 }
4254
4255 FunctionType::ArmStateValue CalleeArmZAState =
4256 FunctionType::getArmZAState(AttrBits: ExtInfo.AArch64SMEAttributes);
4257 FunctionType::ArmStateValue CalleeArmZT0State =
4258 FunctionType::getArmZT0State(AttrBits: ExtInfo.AArch64SMEAttributes);
4259 if (CalleeArmZAState != FunctionType::ARM_None ||
4260 CalleeArmZT0State != FunctionType::ARM_None) {
4261 bool CallerHasZAState = false;
4262 bool CallerHasZT0State = false;
4263 if (CallerFD) {
4264 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4265 if (Attr && Attr->isNewZA())
4266 CallerHasZAState = true;
4267 if (Attr && Attr->isNewZT0())
4268 CallerHasZT0State = true;
4269 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4270 CallerHasZAState |=
4271 FunctionType::getArmZAState(
4272 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4273 FunctionType::ARM_None;
4274 CallerHasZT0State |=
4275 FunctionType::getArmZT0State(
4276 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4277 FunctionType::ARM_None;
4278 }
4279 }
4280
4281 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4282 Diag(Loc, DiagID: diag::err_sme_za_call_no_za_state);
4283
4284 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4285 Diag(Loc, DiagID: diag::err_sme_zt0_call_no_zt0_state);
4286
4287 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4288 CalleeArmZT0State != FunctionType::ARM_None) {
4289 Diag(Loc, DiagID: diag::err_sme_unimplemented_za_save_restore);
4290 Diag(Loc, DiagID: diag::note_sme_use_preserves_za);
4291 }
4292 }
4293 }
4294
4295 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4296 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4297 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4298 if (!Arg->isValueDependent()) {
4299 Expr::EvalResult Align;
4300 if (Arg->EvaluateAsInt(Result&: Align, Ctx: Context)) {
4301 const llvm::APSInt &I = Align.Val.getInt();
4302 if (!I.isPowerOf2())
4303 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_alignment_not_power_of_two)
4304 << Arg->getSourceRange();
4305
4306 if (I > Sema::MaximumAlignment)
4307 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_assume_aligned_too_great)
4308 << Arg->getSourceRange() << Sema::MaximumAlignment;
4309 }
4310 }
4311 }
4312
4313 if (FD)
4314 diagnoseArgDependentDiagnoseIfAttrs(Function: FD, ThisArg, Args, Loc);
4315}
4316
4317void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4318 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4319 DiagnoseUseOfDecl(D: Decl, Locs: Loc);
4320 }
4321}
4322
4323void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4324 ArrayRef<const Expr *> Args,
4325 const FunctionProtoType *Proto,
4326 SourceLocation Loc) {
4327 VariadicCallType CallType = Proto->isVariadic()
4328 ? VariadicCallType::Constructor
4329 : VariadicCallType::DoesNotApply;
4330
4331 auto *Ctor = cast<CXXConstructorDecl>(Val: FDecl);
4332 CheckArgAlignment(
4333 Loc, FDecl, ParamName: "'this'", ArgTy: Context.getPointerType(T: ThisType),
4334 ParamTy: Context.getPointerType(T: Ctor->getFunctionObjectParameterType()));
4335
4336 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4337 Loc, Range: SourceRange(), CallType);
4338}
4339
4340bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4341 const FunctionProtoType *Proto) {
4342 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(Val: TheCall) &&
4343 isa<CXXMethodDecl>(Val: FDecl);
4344 bool IsMemberFunction = isa<CXXMemberCallExpr>(Val: TheCall) ||
4345 IsMemberOperatorCall;
4346 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4347 Fn: TheCall->getCallee());
4348 Expr** Args = TheCall->getArgs();
4349 unsigned NumArgs = TheCall->getNumArgs();
4350
4351 Expr *ImplicitThis = nullptr;
4352 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4353 // If this is a call to a member operator, hide the first
4354 // argument from checkCall.
4355 // FIXME: Our choice of AST representation here is less than ideal.
4356 ImplicitThis = Args[0];
4357 ++Args;
4358 --NumArgs;
4359 } else if (IsMemberFunction && !FDecl->isStatic() &&
4360 !FDecl->hasCXXExplicitFunctionObjectParameter())
4361 ImplicitThis =
4362 cast<CXXMemberCallExpr>(Val: TheCall)->getImplicitObjectArgument();
4363
4364 if (ImplicitThis) {
4365 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4366 // used.
4367 QualType ThisType = ImplicitThis->getType();
4368 if (!ThisType->isPointerType()) {
4369 assert(!ThisType->isReferenceType());
4370 ThisType = Context.getPointerType(T: ThisType);
4371 }
4372
4373 QualType ThisTypeFromDecl = Context.getPointerType(
4374 T: cast<CXXMethodDecl>(Val: FDecl)->getFunctionObjectParameterType());
4375
4376 CheckArgAlignment(Loc: TheCall->getRParenLoc(), FDecl, ParamName: "'this'", ArgTy: ThisType,
4377 ParamTy: ThisTypeFromDecl);
4378 }
4379
4380 checkCall(FDecl, Proto, ThisArg: ImplicitThis, Args: llvm::ArrayRef(Args, NumArgs),
4381 IsMemberFunction, Loc: TheCall->getRParenLoc(),
4382 Range: TheCall->getCallee()->getSourceRange(), CallType);
4383
4384 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4385 // None of the checks below are needed for functions that don't have
4386 // simple names (e.g., C++ conversion functions).
4387 if (!FnInfo)
4388 return false;
4389
4390 // Enforce TCB except for builtin calls, which are always allowed.
4391 if (FDecl->getBuiltinID() == 0)
4392 CheckTCBEnforcement(CallExprLoc: TheCall->getExprLoc(), Callee: FDecl);
4393
4394 CheckAbsoluteValueFunction(Call: TheCall, FDecl);
4395 CheckMaxUnsignedZero(Call: TheCall, FDecl);
4396 CheckInfNaNFunction(Call: TheCall, FDecl);
4397
4398 if (getLangOpts().ObjC)
4399 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4400
4401 unsigned CMId = FDecl->getMemoryFunctionKind();
4402
4403 // Handle memory setting and copying functions.
4404 switch (CMId) {
4405 case 0:
4406 return false;
4407 case Builtin::BIstrlcpy: // fallthrough
4408 case Builtin::BIstrlcat:
4409 CheckStrlcpycatArguments(Call: TheCall, FnName: FnInfo);
4410 break;
4411 case Builtin::BIstrncat:
4412 CheckStrncatArguments(Call: TheCall, FnName: FnInfo);
4413 break;
4414 case Builtin::BIfree:
4415 CheckFreeArguments(E: TheCall);
4416 break;
4417 default:
4418 CheckMemaccessArguments(Call: TheCall, BId: CMId, FnName: FnInfo);
4419 }
4420
4421 return false;
4422}
4423
4424bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4425 const FunctionProtoType *Proto) {
4426 QualType Ty;
4427 if (const auto *V = dyn_cast<VarDecl>(Val: NDecl))
4428 Ty = V->getType().getNonReferenceType();
4429 else if (const auto *F = dyn_cast<FieldDecl>(Val: NDecl))
4430 Ty = F->getType().getNonReferenceType();
4431 else
4432 return false;
4433
4434 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4435 !Ty->isFunctionProtoType())
4436 return false;
4437
4438 VariadicCallType CallType;
4439 if (!Proto || !Proto->isVariadic()) {
4440 CallType = VariadicCallType::DoesNotApply;
4441 } else if (Ty->isBlockPointerType()) {
4442 CallType = VariadicCallType::Block;
4443 } else { // Ty->isFunctionPointerType()
4444 CallType = VariadicCallType::Function;
4445 }
4446
4447 checkCall(FDecl: NDecl, Proto, /*ThisArg=*/nullptr,
4448 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4449 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4450 Range: TheCall->getCallee()->getSourceRange(), CallType);
4451
4452 return false;
4453}
4454
4455bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4456 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4457 Fn: TheCall->getCallee());
4458 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4459 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4460 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4461 Range: TheCall->getCallee()->getSourceRange(), CallType);
4462
4463 return false;
4464}
4465
4466static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4467 if (!llvm::isValidAtomicOrderingCABI(I: Ordering))
4468 return false;
4469
4470 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4471 switch (Op) {
4472 case AtomicExpr::AO__c11_atomic_init:
4473 case AtomicExpr::AO__opencl_atomic_init:
4474 llvm_unreachable("There is no ordering argument for an init");
4475
4476 case AtomicExpr::AO__c11_atomic_load:
4477 case AtomicExpr::AO__opencl_atomic_load:
4478 case AtomicExpr::AO__hip_atomic_load:
4479 case AtomicExpr::AO__atomic_load_n:
4480 case AtomicExpr::AO__atomic_load:
4481 case AtomicExpr::AO__scoped_atomic_load_n:
4482 case AtomicExpr::AO__scoped_atomic_load:
4483 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4484 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4485
4486 case AtomicExpr::AO__c11_atomic_store:
4487 case AtomicExpr::AO__opencl_atomic_store:
4488 case AtomicExpr::AO__hip_atomic_store:
4489 case AtomicExpr::AO__atomic_store:
4490 case AtomicExpr::AO__atomic_store_n:
4491 case AtomicExpr::AO__scoped_atomic_store:
4492 case AtomicExpr::AO__scoped_atomic_store_n:
4493 case AtomicExpr::AO__atomic_clear:
4494 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4495 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4496 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4497
4498 default:
4499 return true;
4500 }
4501}
4502
4503ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4504 AtomicExpr::AtomicOp Op) {
4505 CallExpr *TheCall = cast<CallExpr>(Val: TheCallResult.get());
4506 DeclRefExpr *DRE =cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
4507 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4508 return BuildAtomicExpr(CallRange: {TheCall->getBeginLoc(), TheCall->getEndLoc()},
4509 ExprRange: DRE->getSourceRange(), RParenLoc: TheCall->getRParenLoc(), Args,
4510 Op);
4511}
4512
4513ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4514 SourceLocation RParenLoc, MultiExprArg Args,
4515 AtomicExpr::AtomicOp Op,
4516 AtomicArgumentOrder ArgOrder) {
4517 // All the non-OpenCL operations take one of the following forms.
4518 // The OpenCL operations take the __c11 forms with one extra argument for
4519 // synchronization scope.
4520 enum {
4521 // C __c11_atomic_init(A *, C)
4522 Init,
4523
4524 // C __c11_atomic_load(A *, int)
4525 Load,
4526
4527 // void __atomic_load(A *, CP, int)
4528 LoadCopy,
4529
4530 // void __atomic_store(A *, CP, int)
4531 Copy,
4532
4533 // C __c11_atomic_add(A *, M, int)
4534 Arithmetic,
4535
4536 // C __atomic_exchange_n(A *, CP, int)
4537 Xchg,
4538
4539 // void __atomic_exchange(A *, C *, CP, int)
4540 GNUXchg,
4541
4542 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4543 C11CmpXchg,
4544
4545 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4546 GNUCmpXchg,
4547
4548 // bool __atomic_test_and_set(A *, int)
4549 TestAndSetByte,
4550
4551 // void __atomic_clear(A *, int)
4552 ClearByte,
4553 } Form = Init;
4554
4555 const unsigned NumForm = ClearByte + 1;
4556 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4557 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4558 // where:
4559 // C is an appropriate type,
4560 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4561 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4562 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4563 // the int parameters are for orderings.
4564
4565 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4566 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4567 "need to update code for modified forms");
4568 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4569 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4570 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4571 "need to update code for modified C11 atomics");
4572 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4573 Op <= AtomicExpr::AO__opencl_atomic_store;
4574 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4575 Op <= AtomicExpr::AO__hip_atomic_store;
4576 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4577 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4578 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4579 Op <= AtomicExpr::AO__c11_atomic_store) ||
4580 IsOpenCL;
4581 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4582 Op == AtomicExpr::AO__atomic_store_n ||
4583 Op == AtomicExpr::AO__atomic_exchange_n ||
4584 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
4585 Op == AtomicExpr::AO__scoped_atomic_load_n ||
4586 Op == AtomicExpr::AO__scoped_atomic_store_n ||
4587 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
4588 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
4589 // Bit mask for extra allowed value types other than integers for atomic
4590 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
4591 // allow floating point.
4592 enum ArithOpExtraValueType {
4593 AOEVT_None = 0,
4594 AOEVT_Pointer = 1,
4595 AOEVT_FP = 2,
4596 };
4597 unsigned ArithAllows = AOEVT_None;
4598
4599 switch (Op) {
4600 case AtomicExpr::AO__c11_atomic_init:
4601 case AtomicExpr::AO__opencl_atomic_init:
4602 Form = Init;
4603 break;
4604
4605 case AtomicExpr::AO__c11_atomic_load:
4606 case AtomicExpr::AO__opencl_atomic_load:
4607 case AtomicExpr::AO__hip_atomic_load:
4608 case AtomicExpr::AO__atomic_load_n:
4609 case AtomicExpr::AO__scoped_atomic_load_n:
4610 Form = Load;
4611 break;
4612
4613 case AtomicExpr::AO__atomic_load:
4614 case AtomicExpr::AO__scoped_atomic_load:
4615 Form = LoadCopy;
4616 break;
4617
4618 case AtomicExpr::AO__c11_atomic_store:
4619 case AtomicExpr::AO__opencl_atomic_store:
4620 case AtomicExpr::AO__hip_atomic_store:
4621 case AtomicExpr::AO__atomic_store:
4622 case AtomicExpr::AO__atomic_store_n:
4623 case AtomicExpr::AO__scoped_atomic_store:
4624 case AtomicExpr::AO__scoped_atomic_store_n:
4625 Form = Copy;
4626 break;
4627 case AtomicExpr::AO__atomic_fetch_add:
4628 case AtomicExpr::AO__atomic_fetch_sub:
4629 case AtomicExpr::AO__atomic_add_fetch:
4630 case AtomicExpr::AO__atomic_sub_fetch:
4631 case AtomicExpr::AO__scoped_atomic_fetch_add:
4632 case AtomicExpr::AO__scoped_atomic_fetch_sub:
4633 case AtomicExpr::AO__scoped_atomic_add_fetch:
4634 case AtomicExpr::AO__scoped_atomic_sub_fetch:
4635 case AtomicExpr::AO__c11_atomic_fetch_add:
4636 case AtomicExpr::AO__c11_atomic_fetch_sub:
4637 case AtomicExpr::AO__opencl_atomic_fetch_add:
4638 case AtomicExpr::AO__opencl_atomic_fetch_sub:
4639 case AtomicExpr::AO__hip_atomic_fetch_add:
4640 case AtomicExpr::AO__hip_atomic_fetch_sub:
4641 ArithAllows = AOEVT_Pointer | AOEVT_FP;
4642 Form = Arithmetic;
4643 break;
4644 case AtomicExpr::AO__atomic_fetch_max:
4645 case AtomicExpr::AO__atomic_fetch_min:
4646 case AtomicExpr::AO__atomic_max_fetch:
4647 case AtomicExpr::AO__atomic_min_fetch:
4648 case AtomicExpr::AO__scoped_atomic_fetch_max:
4649 case AtomicExpr::AO__scoped_atomic_fetch_min:
4650 case AtomicExpr::AO__scoped_atomic_max_fetch:
4651 case AtomicExpr::AO__scoped_atomic_min_fetch:
4652 case AtomicExpr::AO__c11_atomic_fetch_max:
4653 case AtomicExpr::AO__c11_atomic_fetch_min:
4654 case AtomicExpr::AO__opencl_atomic_fetch_max:
4655 case AtomicExpr::AO__opencl_atomic_fetch_min:
4656 case AtomicExpr::AO__hip_atomic_fetch_max:
4657 case AtomicExpr::AO__hip_atomic_fetch_min:
4658 ArithAllows = AOEVT_FP;
4659 Form = Arithmetic;
4660 break;
4661 case AtomicExpr::AO__c11_atomic_fetch_and:
4662 case AtomicExpr::AO__c11_atomic_fetch_or:
4663 case AtomicExpr::AO__c11_atomic_fetch_xor:
4664 case AtomicExpr::AO__hip_atomic_fetch_and:
4665 case AtomicExpr::AO__hip_atomic_fetch_or:
4666 case AtomicExpr::AO__hip_atomic_fetch_xor:
4667 case AtomicExpr::AO__c11_atomic_fetch_nand:
4668 case AtomicExpr::AO__opencl_atomic_fetch_and:
4669 case AtomicExpr::AO__opencl_atomic_fetch_or:
4670 case AtomicExpr::AO__opencl_atomic_fetch_xor:
4671 case AtomicExpr::AO__atomic_fetch_and:
4672 case AtomicExpr::AO__atomic_fetch_or:
4673 case AtomicExpr::AO__atomic_fetch_xor:
4674 case AtomicExpr::AO__atomic_fetch_nand:
4675 case AtomicExpr::AO__atomic_and_fetch:
4676 case AtomicExpr::AO__atomic_or_fetch:
4677 case AtomicExpr::AO__atomic_xor_fetch:
4678 case AtomicExpr::AO__atomic_nand_fetch:
4679 case AtomicExpr::AO__atomic_fetch_uinc:
4680 case AtomicExpr::AO__atomic_fetch_udec:
4681 case AtomicExpr::AO__scoped_atomic_fetch_and:
4682 case AtomicExpr::AO__scoped_atomic_fetch_or:
4683 case AtomicExpr::AO__scoped_atomic_fetch_xor:
4684 case AtomicExpr::AO__scoped_atomic_fetch_nand:
4685 case AtomicExpr::AO__scoped_atomic_and_fetch:
4686 case AtomicExpr::AO__scoped_atomic_or_fetch:
4687 case AtomicExpr::AO__scoped_atomic_xor_fetch:
4688 case AtomicExpr::AO__scoped_atomic_nand_fetch:
4689 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
4690 case AtomicExpr::AO__scoped_atomic_fetch_udec:
4691 Form = Arithmetic;
4692 break;
4693
4694 case AtomicExpr::AO__c11_atomic_exchange:
4695 case AtomicExpr::AO__hip_atomic_exchange:
4696 case AtomicExpr::AO__opencl_atomic_exchange:
4697 case AtomicExpr::AO__atomic_exchange_n:
4698 case AtomicExpr::AO__scoped_atomic_exchange_n:
4699 Form = Xchg;
4700 break;
4701
4702 case AtomicExpr::AO__atomic_exchange:
4703 case AtomicExpr::AO__scoped_atomic_exchange:
4704 Form = GNUXchg;
4705 break;
4706
4707 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4708 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4709 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4710 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4711 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4712 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4713 Form = C11CmpXchg;
4714 break;
4715
4716 case AtomicExpr::AO__atomic_compare_exchange:
4717 case AtomicExpr::AO__atomic_compare_exchange_n:
4718 case AtomicExpr::AO__scoped_atomic_compare_exchange:
4719 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
4720 Form = GNUCmpXchg;
4721 break;
4722
4723 case AtomicExpr::AO__atomic_test_and_set:
4724 Form = TestAndSetByte;
4725 break;
4726
4727 case AtomicExpr::AO__atomic_clear:
4728 Form = ClearByte;
4729 break;
4730 }
4731
4732 unsigned AdjustedNumArgs = NumArgs[Form];
4733 if ((IsOpenCL || IsHIP || IsScoped) &&
4734 Op != AtomicExpr::AO__opencl_atomic_init)
4735 ++AdjustedNumArgs;
4736 // Check we have the right number of arguments.
4737 if (Args.size() < AdjustedNumArgs) {
4738 Diag(Loc: CallRange.getEnd(), DiagID: diag::err_typecheck_call_too_few_args)
4739 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4740 << /*is non object*/ 0 << ExprRange;
4741 return ExprError();
4742 } else if (Args.size() > AdjustedNumArgs) {
4743 Diag(Loc: Args[AdjustedNumArgs]->getBeginLoc(),
4744 DiagID: diag::err_typecheck_call_too_many_args)
4745 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4746 << /*is non object*/ 0 << ExprRange;
4747 return ExprError();
4748 }
4749
4750 // Inspect the first argument of the atomic operation.
4751 Expr *Ptr = Args[0];
4752 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(E: Ptr);
4753 if (ConvertedPtr.isInvalid())
4754 return ExprError();
4755
4756 Ptr = ConvertedPtr.get();
4757 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4758 if (!pointerType) {
4759 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
4760 << Ptr->getType() << 0 << Ptr->getSourceRange();
4761 return ExprError();
4762 }
4763
4764 // For a __c11 builtin, this should be a pointer to an _Atomic type.
4765 QualType AtomTy = pointerType->getPointeeType(); // 'A'
4766 QualType ValType = AtomTy; // 'C'
4767 if (IsC11) {
4768 if (!AtomTy->isAtomicType()) {
4769 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_atomic)
4770 << Ptr->getType() << Ptr->getSourceRange();
4771 return ExprError();
4772 }
4773 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4774 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4775 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_atomic)
4776 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4777 << Ptr->getSourceRange();
4778 return ExprError();
4779 }
4780 ValType = AtomTy->castAs<AtomicType>()->getValueType();
4781 } else if (Form != Load && Form != LoadCopy) {
4782 if (ValType.isConstQualified()) {
4783 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_pointer)
4784 << Ptr->getType() << Ptr->getSourceRange();
4785 return ExprError();
4786 }
4787 }
4788
4789 if (Form != TestAndSetByte && Form != ClearByte) {
4790 // Pointer to object of size zero is not allowed.
4791 if (RequireCompleteType(Loc: Ptr->getBeginLoc(), T: AtomTy,
4792 DiagID: diag::err_incomplete_type))
4793 return ExprError();
4794
4795 if (Context.getTypeInfoInChars(T: AtomTy).Width.isZero()) {
4796 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
4797 << Ptr->getType() << 1 << Ptr->getSourceRange();
4798 return ExprError();
4799 }
4800 } else {
4801 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
4802 // non-const pointer type, including void* and pointers to incomplete
4803 // structs, but only access the first byte.
4804 AtomTy = Context.CharTy;
4805 AtomTy = AtomTy.withCVRQualifiers(
4806 CVR: pointerType->getPointeeType().getCVRQualifiers());
4807 QualType PointerQT = Context.getPointerType(T: AtomTy);
4808 pointerType = PointerQT->getAs<PointerType>();
4809 Ptr = ImpCastExprToType(E: Ptr, Type: PointerQT, CK: CK_BitCast).get();
4810 ValType = AtomTy;
4811 }
4812
4813 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
4814 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
4815 Diag(Loc: ExprRange.getBegin(),
4816 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
4817 << 0 << Ptr->getType() << Ptr->getSourceRange();
4818 return ExprError();
4819 }
4820
4821 // For an arithmetic operation, the implied arithmetic must be well-formed.
4822 if (Form == Arithmetic) {
4823 // GCC does not enforce these rules for GNU atomics, but we do to help catch
4824 // trivial type errors.
4825 auto IsAllowedValueType = [&](QualType ValType,
4826 unsigned AllowedType) -> bool {
4827 if (ValType->isIntegerType())
4828 return true;
4829 if (ValType->isPointerType())
4830 return AllowedType & AOEVT_Pointer;
4831 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
4832 return false;
4833 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
4834 if (ValType->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
4835 &Context.getTargetInfo().getLongDoubleFormat() ==
4836 &llvm::APFloat::x87DoubleExtended())
4837 return false;
4838 return true;
4839 };
4840 if (!IsAllowedValueType(ValType, ArithAllows)) {
4841 auto DID = ArithAllows & AOEVT_FP
4842 ? (ArithAllows & AOEVT_Pointer
4843 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
4844 : diag::err_atomic_op_needs_atomic_int_or_fp)
4845 : diag::err_atomic_op_needs_atomic_int;
4846 Diag(Loc: ExprRange.getBegin(), DiagID: DID)
4847 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4848 return ExprError();
4849 }
4850 if (IsC11 && ValType->isPointerType() &&
4851 RequireCompleteType(Loc: Ptr->getBeginLoc(), T: ValType->getPointeeType(),
4852 DiagID: diag::err_incomplete_type)) {
4853 return ExprError();
4854 }
4855 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4856 // For __atomic_*_n operations, the value type must be a scalar integral or
4857 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4858 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_atomic_int_or_ptr)
4859 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4860 return ExprError();
4861 }
4862
4863 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4864 !AtomTy->isScalarType()) {
4865 // For GNU atomics, require a trivially-copyable type. This is not part of
4866 // the GNU atomics specification but we enforce it for consistency with
4867 // other atomics which generally all require a trivially-copyable type. This
4868 // is because atomics just copy bits.
4869 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_trivial_copy)
4870 << Ptr->getType() << Ptr->getSourceRange();
4871 return ExprError();
4872 }
4873
4874 switch (ValType.getObjCLifetime()) {
4875 case Qualifiers::OCL_None:
4876 case Qualifiers::OCL_ExplicitNone:
4877 // okay
4878 break;
4879
4880 case Qualifiers::OCL_Weak:
4881 case Qualifiers::OCL_Strong:
4882 case Qualifiers::OCL_Autoreleasing:
4883 // FIXME: Can this happen? By this point, ValType should be known
4884 // to be trivially copyable.
4885 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_arc_atomic_ownership)
4886 << ValType << Ptr->getSourceRange();
4887 return ExprError();
4888 }
4889
4890 // All atomic operations have an overload which takes a pointer to a volatile
4891 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
4892 // into the result or the other operands. Similarly atomic_load takes a
4893 // pointer to a const 'A'.
4894 ValType.removeLocalVolatile();
4895 ValType.removeLocalConst();
4896 QualType ResultType = ValType;
4897 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
4898 Form == ClearByte)
4899 ResultType = Context.VoidTy;
4900 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
4901 ResultType = Context.BoolTy;
4902
4903 // The type of a parameter passed 'by value'. In the GNU atomics, such
4904 // arguments are actually passed as pointers.
4905 QualType ByValType = ValType; // 'CP'
4906 bool IsPassedByAddress = false;
4907 if (!IsC11 && !IsHIP && !IsN) {
4908 ByValType = Ptr->getType();
4909 IsPassedByAddress = true;
4910 }
4911
4912 SmallVector<Expr *, 5> APIOrderedArgs;
4913 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4914 APIOrderedArgs.push_back(Elt: Args[0]);
4915 switch (Form) {
4916 case Init:
4917 case Load:
4918 APIOrderedArgs.push_back(Elt: Args[1]); // Val1/Order
4919 break;
4920 case LoadCopy:
4921 case Copy:
4922 case Arithmetic:
4923 case Xchg:
4924 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
4925 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4926 break;
4927 case GNUXchg:
4928 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
4929 APIOrderedArgs.push_back(Elt: Args[3]); // Val2
4930 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4931 break;
4932 case C11CmpXchg:
4933 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
4934 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
4935 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4936 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
4937 break;
4938 case GNUCmpXchg:
4939 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
4940 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
4941 APIOrderedArgs.push_back(Elt: Args[5]); // Weak
4942 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4943 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
4944 break;
4945 case TestAndSetByte:
4946 case ClearByte:
4947 APIOrderedArgs.push_back(Elt: Args[1]); // Order
4948 break;
4949 }
4950 } else
4951 APIOrderedArgs.append(in_start: Args.begin(), in_end: Args.end());
4952
4953 // The first argument's non-CV pointer type is used to deduce the type of
4954 // subsequent arguments, except for:
4955 // - weak flag (always converted to bool)
4956 // - memory order (always converted to int)
4957 // - scope (always converted to int)
4958 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4959 QualType Ty;
4960 if (i < NumVals[Form] + 1) {
4961 switch (i) {
4962 case 0:
4963 // The first argument is always a pointer. It has a fixed type.
4964 // It is always dereferenced, a nullptr is undefined.
4965 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
4966 // Nothing else to do: we already know all we want about this pointer.
4967 continue;
4968 case 1:
4969 // The second argument is the non-atomic operand. For arithmetic, this
4970 // is always passed by value, and for a compare_exchange it is always
4971 // passed by address. For the rest, GNU uses by-address and C11 uses
4972 // by-value.
4973 assert(Form != Load);
4974 if (Form == Arithmetic && ValType->isPointerType())
4975 Ty = Context.getPointerDiffType();
4976 else if (Form == Init || Form == Arithmetic)
4977 Ty = ValType;
4978 else if (Form == Copy || Form == Xchg) {
4979 if (IsPassedByAddress) {
4980 // The value pointer is always dereferenced, a nullptr is undefined.
4981 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i],
4982 CallSiteLoc: ExprRange.getBegin());
4983 }
4984 Ty = ByValType;
4985 } else {
4986 Expr *ValArg = APIOrderedArgs[i];
4987 // The value pointer is always dereferenced, a nullptr is undefined.
4988 CheckNonNullArgument(S&: *this, ArgExpr: ValArg, CallSiteLoc: ExprRange.getBegin());
4989 LangAS AS = LangAS::Default;
4990 // Keep address space of non-atomic pointer type.
4991 if (const PointerType *PtrTy =
4992 ValArg->getType()->getAs<PointerType>()) {
4993 AS = PtrTy->getPointeeType().getAddressSpace();
4994 }
4995 Ty = Context.getPointerType(
4996 T: Context.getAddrSpaceQualType(T: ValType.getUnqualifiedType(), AddressSpace: AS));
4997 }
4998 break;
4999 case 2:
5000 // The third argument to compare_exchange / GNU exchange is the desired
5001 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5002 if (IsPassedByAddress)
5003 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5004 Ty = ByValType;
5005 break;
5006 case 3:
5007 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5008 Ty = Context.BoolTy;
5009 break;
5010 }
5011 } else {
5012 // The order(s) and scope are always converted to int.
5013 Ty = Context.IntTy;
5014 }
5015
5016 InitializedEntity Entity =
5017 InitializedEntity::InitializeParameter(Context, Type: Ty, Consumed: false);
5018 ExprResult Arg = APIOrderedArgs[i];
5019 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5020 if (Arg.isInvalid())
5021 return true;
5022 APIOrderedArgs[i] = Arg.get();
5023 }
5024
5025 // Permute the arguments into a 'consistent' order.
5026 SmallVector<Expr*, 5> SubExprs;
5027 SubExprs.push_back(Elt: Ptr);
5028 switch (Form) {
5029 case Init:
5030 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5031 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5032 break;
5033 case Load:
5034 case TestAndSetByte:
5035 case ClearByte:
5036 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Order
5037 break;
5038 case LoadCopy:
5039 case Copy:
5040 case Arithmetic:
5041 case Xchg:
5042 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Order
5043 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5044 break;
5045 case GNUXchg:
5046 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5047 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5048 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5049 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5050 break;
5051 case C11CmpXchg:
5052 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5053 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5054 SubExprs.push_back(Elt: APIOrderedArgs[4]); // OrderFail
5055 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5056 break;
5057 case GNUCmpXchg:
5058 SubExprs.push_back(Elt: APIOrderedArgs[4]); // Order
5059 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5060 SubExprs.push_back(Elt: APIOrderedArgs[5]); // OrderFail
5061 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5062 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Weak
5063 break;
5064 }
5065
5066 // If the memory orders are constants, check they are valid.
5067 if (SubExprs.size() >= 2 && Form != Init) {
5068 std::optional<llvm::APSInt> Success =
5069 SubExprs[1]->getIntegerConstantExpr(Ctx: Context);
5070 if (Success && !isValidOrderingForOp(Ordering: Success->getSExtValue(), Op)) {
5071 Diag(Loc: SubExprs[1]->getBeginLoc(),
5072 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5073 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5074 << SubExprs[1]->getSourceRange();
5075 }
5076 if (SubExprs.size() >= 5) {
5077 if (std::optional<llvm::APSInt> Failure =
5078 SubExprs[3]->getIntegerConstantExpr(Ctx: Context)) {
5079 if (!llvm::is_contained(
5080 Set: {llvm::AtomicOrderingCABI::relaxed,
5081 llvm::AtomicOrderingCABI::consume,
5082 llvm::AtomicOrderingCABI::acquire,
5083 llvm::AtomicOrderingCABI::seq_cst},
5084 Element: (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5085 Diag(Loc: SubExprs[3]->getBeginLoc(),
5086 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5087 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5088 }
5089 }
5090 }
5091 }
5092
5093 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5094 auto *Scope = Args[Args.size() - 1];
5095 if (std::optional<llvm::APSInt> Result =
5096 Scope->getIntegerConstantExpr(Ctx: Context)) {
5097 if (!ScopeModel->isValid(S: Result->getZExtValue()))
5098 Diag(Loc: Scope->getBeginLoc(), DiagID: diag::err_atomic_op_has_invalid_sync_scope)
5099 << Scope->getSourceRange();
5100 }
5101 SubExprs.push_back(Elt: Scope);
5102 }
5103
5104 AtomicExpr *AE = new (Context)
5105 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5106
5107 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5108 Op == AtomicExpr::AO__c11_atomic_store ||
5109 Op == AtomicExpr::AO__opencl_atomic_load ||
5110 Op == AtomicExpr::AO__hip_atomic_load ||
5111 Op == AtomicExpr::AO__opencl_atomic_store ||
5112 Op == AtomicExpr::AO__hip_atomic_store) &&
5113 Context.AtomicUsesUnsupportedLibcall(E: AE))
5114 Diag(Loc: AE->getBeginLoc(), DiagID: diag::err_atomic_load_store_uses_lib)
5115 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5116 Op == AtomicExpr::AO__opencl_atomic_load ||
5117 Op == AtomicExpr::AO__hip_atomic_load)
5118 ? 0
5119 : 1);
5120
5121 if (ValType->isBitIntType()) {
5122 Diag(Loc: Ptr->getExprLoc(), DiagID: diag::err_atomic_builtin_bit_int_prohibit);
5123 return ExprError();
5124 }
5125
5126 return AE;
5127}
5128
5129/// checkBuiltinArgument - Given a call to a builtin function, perform
5130/// normal type-checking on the given argument, updating the call in
5131/// place. This is useful when a builtin function requires custom
5132/// type-checking for some of its arguments but not necessarily all of
5133/// them.
5134///
5135/// Returns true on error.
5136static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5137 FunctionDecl *Fn = E->getDirectCallee();
5138 assert(Fn && "builtin call without direct callee!");
5139
5140 ParmVarDecl *Param = Fn->getParamDecl(i: ArgIndex);
5141 InitializedEntity Entity =
5142 InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Param);
5143
5144 ExprResult Arg = E->getArg(Arg: ArgIndex);
5145 Arg = S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5146 if (Arg.isInvalid())
5147 return true;
5148
5149 E->setArg(Arg: ArgIndex, ArgExpr: Arg.get());
5150 return false;
5151}
5152
5153ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5154 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5155 Expr *Callee = TheCall->getCallee();
5156 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Callee->IgnoreParenCasts());
5157 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
5158
5159 // Ensure that we have at least one argument to do type inference from.
5160 if (TheCall->getNumArgs() < 1) {
5161 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5162 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5163 << Callee->getSourceRange();
5164 return ExprError();
5165 }
5166
5167 // Inspect the first argument of the atomic builtin. This should always be
5168 // a pointer type, whose element is an integral scalar or pointer type.
5169 // Because it is a pointer type, we don't have to worry about any implicit
5170 // casts here.
5171 // FIXME: We don't allow floating point scalars as input.
5172 Expr *FirstArg = TheCall->getArg(Arg: 0);
5173 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(E: FirstArg);
5174 if (FirstArgResult.isInvalid())
5175 return ExprError();
5176 FirstArg = FirstArgResult.get();
5177 TheCall->setArg(Arg: 0, ArgExpr: FirstArg);
5178
5179 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5180 if (!pointerType) {
5181 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5182 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5183 return ExprError();
5184 }
5185
5186 QualType ValType = pointerType->getPointeeType();
5187 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5188 !ValType->isBlockPointerType()) {
5189 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer_intptr)
5190 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5191 return ExprError();
5192 }
5193 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5194 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5195 Diag(Loc: FirstArg->getBeginLoc(),
5196 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5197 << 1 << ValType << FirstArg->getSourceRange();
5198 return ExprError();
5199 }
5200
5201 if (ValType.isConstQualified()) {
5202 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_cannot_be_const)
5203 << FirstArg->getType() << FirstArg->getSourceRange();
5204 return ExprError();
5205 }
5206
5207 switch (ValType.getObjCLifetime()) {
5208 case Qualifiers::OCL_None:
5209 case Qualifiers::OCL_ExplicitNone:
5210 // okay
5211 break;
5212
5213 case Qualifiers::OCL_Weak:
5214 case Qualifiers::OCL_Strong:
5215 case Qualifiers::OCL_Autoreleasing:
5216 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_arc_atomic_ownership)
5217 << ValType << FirstArg->getSourceRange();
5218 return ExprError();
5219 }
5220
5221 // Strip any qualifiers off ValType.
5222 ValType = ValType.getUnqualifiedType();
5223
5224 // The majority of builtins return a value, but a few have special return
5225 // types, so allow them to override appropriately below.
5226 QualType ResultType = ValType;
5227
5228 // We need to figure out which concrete builtin this maps onto. For example,
5229 // __sync_fetch_and_add with a 2 byte object turns into
5230 // __sync_fetch_and_add_2.
5231#define BUILTIN_ROW(x) \
5232 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5233 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5234
5235 static const unsigned BuiltinIndices[][5] = {
5236 BUILTIN_ROW(__sync_fetch_and_add),
5237 BUILTIN_ROW(__sync_fetch_and_sub),
5238 BUILTIN_ROW(__sync_fetch_and_or),
5239 BUILTIN_ROW(__sync_fetch_and_and),
5240 BUILTIN_ROW(__sync_fetch_and_xor),
5241 BUILTIN_ROW(__sync_fetch_and_nand),
5242
5243 BUILTIN_ROW(__sync_add_and_fetch),
5244 BUILTIN_ROW(__sync_sub_and_fetch),
5245 BUILTIN_ROW(__sync_and_and_fetch),
5246 BUILTIN_ROW(__sync_or_and_fetch),
5247 BUILTIN_ROW(__sync_xor_and_fetch),
5248 BUILTIN_ROW(__sync_nand_and_fetch),
5249
5250 BUILTIN_ROW(__sync_val_compare_and_swap),
5251 BUILTIN_ROW(__sync_bool_compare_and_swap),
5252 BUILTIN_ROW(__sync_lock_test_and_set),
5253 BUILTIN_ROW(__sync_lock_release),
5254 BUILTIN_ROW(__sync_swap)
5255 };
5256#undef BUILTIN_ROW
5257
5258 // Determine the index of the size.
5259 unsigned SizeIndex;
5260 switch (Context.getTypeSizeInChars(T: ValType).getQuantity()) {
5261 case 1: SizeIndex = 0; break;
5262 case 2: SizeIndex = 1; break;
5263 case 4: SizeIndex = 2; break;
5264 case 8: SizeIndex = 3; break;
5265 case 16: SizeIndex = 4; break;
5266 default:
5267 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_pointer_size)
5268 << FirstArg->getType() << FirstArg->getSourceRange();
5269 return ExprError();
5270 }
5271
5272 // Each of these builtins has one pointer argument, followed by some number of
5273 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5274 // that we ignore. Find out which row of BuiltinIndices to read from as well
5275 // as the number of fixed args.
5276 unsigned BuiltinID = FDecl->getBuiltinID();
5277 unsigned BuiltinIndex, NumFixed = 1;
5278 bool WarnAboutSemanticsChange = false;
5279 switch (BuiltinID) {
5280 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5281 case Builtin::BI__sync_fetch_and_add:
5282 case Builtin::BI__sync_fetch_and_add_1:
5283 case Builtin::BI__sync_fetch_and_add_2:
5284 case Builtin::BI__sync_fetch_and_add_4:
5285 case Builtin::BI__sync_fetch_and_add_8:
5286 case Builtin::BI__sync_fetch_and_add_16:
5287 BuiltinIndex = 0;
5288 break;
5289
5290 case Builtin::BI__sync_fetch_and_sub:
5291 case Builtin::BI__sync_fetch_and_sub_1:
5292 case Builtin::BI__sync_fetch_and_sub_2:
5293 case Builtin::BI__sync_fetch_and_sub_4:
5294 case Builtin::BI__sync_fetch_and_sub_8:
5295 case Builtin::BI__sync_fetch_and_sub_16:
5296 BuiltinIndex = 1;
5297 break;
5298
5299 case Builtin::BI__sync_fetch_and_or:
5300 case Builtin::BI__sync_fetch_and_or_1:
5301 case Builtin::BI__sync_fetch_and_or_2:
5302 case Builtin::BI__sync_fetch_and_or_4:
5303 case Builtin::BI__sync_fetch_and_or_8:
5304 case Builtin::BI__sync_fetch_and_or_16:
5305 BuiltinIndex = 2;
5306 break;
5307
5308 case Builtin::BI__sync_fetch_and_and:
5309 case Builtin::BI__sync_fetch_and_and_1:
5310 case Builtin::BI__sync_fetch_and_and_2:
5311 case Builtin::BI__sync_fetch_and_and_4:
5312 case Builtin::BI__sync_fetch_and_and_8:
5313 case Builtin::BI__sync_fetch_and_and_16:
5314 BuiltinIndex = 3;
5315 break;
5316
5317 case Builtin::BI__sync_fetch_and_xor:
5318 case Builtin::BI__sync_fetch_and_xor_1:
5319 case Builtin::BI__sync_fetch_and_xor_2:
5320 case Builtin::BI__sync_fetch_and_xor_4:
5321 case Builtin::BI__sync_fetch_and_xor_8:
5322 case Builtin::BI__sync_fetch_and_xor_16:
5323 BuiltinIndex = 4;
5324 break;
5325
5326 case Builtin::BI__sync_fetch_and_nand:
5327 case Builtin::BI__sync_fetch_and_nand_1:
5328 case Builtin::BI__sync_fetch_and_nand_2:
5329 case Builtin::BI__sync_fetch_and_nand_4:
5330 case Builtin::BI__sync_fetch_and_nand_8:
5331 case Builtin::BI__sync_fetch_and_nand_16:
5332 BuiltinIndex = 5;
5333 WarnAboutSemanticsChange = true;
5334 break;
5335
5336 case Builtin::BI__sync_add_and_fetch:
5337 case Builtin::BI__sync_add_and_fetch_1:
5338 case Builtin::BI__sync_add_and_fetch_2:
5339 case Builtin::BI__sync_add_and_fetch_4:
5340 case Builtin::BI__sync_add_and_fetch_8:
5341 case Builtin::BI__sync_add_and_fetch_16:
5342 BuiltinIndex = 6;
5343 break;
5344
5345 case Builtin::BI__sync_sub_and_fetch:
5346 case Builtin::BI__sync_sub_and_fetch_1:
5347 case Builtin::BI__sync_sub_and_fetch_2:
5348 case Builtin::BI__sync_sub_and_fetch_4:
5349 case Builtin::BI__sync_sub_and_fetch_8:
5350 case Builtin::BI__sync_sub_and_fetch_16:
5351 BuiltinIndex = 7;
5352 break;
5353
5354 case Builtin::BI__sync_and_and_fetch:
5355 case Builtin::BI__sync_and_and_fetch_1:
5356 case Builtin::BI__sync_and_and_fetch_2:
5357 case Builtin::BI__sync_and_and_fetch_4:
5358 case Builtin::BI__sync_and_and_fetch_8:
5359 case Builtin::BI__sync_and_and_fetch_16:
5360 BuiltinIndex = 8;
5361 break;
5362
5363 case Builtin::BI__sync_or_and_fetch:
5364 case Builtin::BI__sync_or_and_fetch_1:
5365 case Builtin::BI__sync_or_and_fetch_2:
5366 case Builtin::BI__sync_or_and_fetch_4:
5367 case Builtin::BI__sync_or_and_fetch_8:
5368 case Builtin::BI__sync_or_and_fetch_16:
5369 BuiltinIndex = 9;
5370 break;
5371
5372 case Builtin::BI__sync_xor_and_fetch:
5373 case Builtin::BI__sync_xor_and_fetch_1:
5374 case Builtin::BI__sync_xor_and_fetch_2:
5375 case Builtin::BI__sync_xor_and_fetch_4:
5376 case Builtin::BI__sync_xor_and_fetch_8:
5377 case Builtin::BI__sync_xor_and_fetch_16:
5378 BuiltinIndex = 10;
5379 break;
5380
5381 case Builtin::BI__sync_nand_and_fetch:
5382 case Builtin::BI__sync_nand_and_fetch_1:
5383 case Builtin::BI__sync_nand_and_fetch_2:
5384 case Builtin::BI__sync_nand_and_fetch_4:
5385 case Builtin::BI__sync_nand_and_fetch_8:
5386 case Builtin::BI__sync_nand_and_fetch_16:
5387 BuiltinIndex = 11;
5388 WarnAboutSemanticsChange = true;
5389 break;
5390
5391 case Builtin::BI__sync_val_compare_and_swap:
5392 case Builtin::BI__sync_val_compare_and_swap_1:
5393 case Builtin::BI__sync_val_compare_and_swap_2:
5394 case Builtin::BI__sync_val_compare_and_swap_4:
5395 case Builtin::BI__sync_val_compare_and_swap_8:
5396 case Builtin::BI__sync_val_compare_and_swap_16:
5397 BuiltinIndex = 12;
5398 NumFixed = 2;
5399 break;
5400
5401 case Builtin::BI__sync_bool_compare_and_swap:
5402 case Builtin::BI__sync_bool_compare_and_swap_1:
5403 case Builtin::BI__sync_bool_compare_and_swap_2:
5404 case Builtin::BI__sync_bool_compare_and_swap_4:
5405 case Builtin::BI__sync_bool_compare_and_swap_8:
5406 case Builtin::BI__sync_bool_compare_and_swap_16:
5407 BuiltinIndex = 13;
5408 NumFixed = 2;
5409 ResultType = Context.BoolTy;
5410 break;
5411
5412 case Builtin::BI__sync_lock_test_and_set:
5413 case Builtin::BI__sync_lock_test_and_set_1:
5414 case Builtin::BI__sync_lock_test_and_set_2:
5415 case Builtin::BI__sync_lock_test_and_set_4:
5416 case Builtin::BI__sync_lock_test_and_set_8:
5417 case Builtin::BI__sync_lock_test_and_set_16:
5418 BuiltinIndex = 14;
5419 break;
5420
5421 case Builtin::BI__sync_lock_release:
5422 case Builtin::BI__sync_lock_release_1:
5423 case Builtin::BI__sync_lock_release_2:
5424 case Builtin::BI__sync_lock_release_4:
5425 case Builtin::BI__sync_lock_release_8:
5426 case Builtin::BI__sync_lock_release_16:
5427 BuiltinIndex = 15;
5428 NumFixed = 0;
5429 ResultType = Context.VoidTy;
5430 break;
5431
5432 case Builtin::BI__sync_swap:
5433 case Builtin::BI__sync_swap_1:
5434 case Builtin::BI__sync_swap_2:
5435 case Builtin::BI__sync_swap_4:
5436 case Builtin::BI__sync_swap_8:
5437 case Builtin::BI__sync_swap_16:
5438 BuiltinIndex = 16;
5439 break;
5440 }
5441
5442 // Now that we know how many fixed arguments we expect, first check that we
5443 // have at least that many.
5444 if (TheCall->getNumArgs() < 1+NumFixed) {
5445 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5446 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5447 << Callee->getSourceRange();
5448 return ExprError();
5449 }
5450
5451 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
5452 << Callee->getSourceRange();
5453
5454 if (WarnAboutSemanticsChange) {
5455 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_sync_fetch_and_nand_semantics_change)
5456 << Callee->getSourceRange();
5457 }
5458
5459 // Get the decl for the concrete builtin from this, we can tell what the
5460 // concrete integer type we should convert to is.
5461 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5462 std::string NewBuiltinName = Context.BuiltinInfo.getName(ID: NewBuiltinID);
5463 FunctionDecl *NewBuiltinDecl;
5464 if (NewBuiltinID == BuiltinID)
5465 NewBuiltinDecl = FDecl;
5466 else {
5467 // Perform builtin lookup to avoid redeclaring it.
5468 DeclarationName DN(&Context.Idents.get(Name: NewBuiltinName));
5469 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5470 LookupName(R&: Res, S: TUScope, /*AllowBuiltinCreation=*/true);
5471 assert(Res.getFoundDecl());
5472 NewBuiltinDecl = dyn_cast<FunctionDecl>(Val: Res.getFoundDecl());
5473 if (!NewBuiltinDecl)
5474 return ExprError();
5475 }
5476
5477 // The first argument --- the pointer --- has a fixed type; we
5478 // deduce the types of the rest of the arguments accordingly. Walk
5479 // the remaining arguments, converting them to the deduced value type.
5480 for (unsigned i = 0; i != NumFixed; ++i) {
5481 ExprResult Arg = TheCall->getArg(Arg: i+1);
5482
5483 // GCC does an implicit conversion to the pointer or integer ValType. This
5484 // can fail in some cases (1i -> int**), check for this error case now.
5485 // Initialize the argument.
5486 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5487 Type: ValType, /*consume*/ Consumed: false);
5488 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5489 if (Arg.isInvalid())
5490 return ExprError();
5491
5492 // Okay, we have something that *can* be converted to the right type. Check
5493 // to see if there is a potentially weird extension going on here. This can
5494 // happen when you do an atomic operation on something like an char* and
5495 // pass in 42. The 42 gets converted to char. This is even more strange
5496 // for things like 45.123 -> char, etc.
5497 // FIXME: Do this check.
5498 TheCall->setArg(Arg: i+1, ArgExpr: Arg.get());
5499 }
5500
5501 // Create a new DeclRefExpr to refer to the new decl.
5502 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5503 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: NewBuiltinDecl,
5504 /*enclosing*/ RefersToEnclosingVariableOrCapture: false, NameLoc: DRE->getLocation(), T: Context.BuiltinFnTy,
5505 VK: DRE->getValueKind(), FoundD: nullptr, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
5506
5507 // Set the callee in the CallExpr.
5508 // FIXME: This loses syntactic information.
5509 QualType CalleePtrTy = Context.getPointerType(T: NewBuiltinDecl->getType());
5510 ExprResult PromotedCall = ImpCastExprToType(E: NewDRE, Type: CalleePtrTy,
5511 CK: CK_BuiltinFnToFnPtr);
5512 TheCall->setCallee(PromotedCall.get());
5513
5514 // Change the result type of the call to match the original value type. This
5515 // is arbitrary, but the codegen for these builtins ins design to handle it
5516 // gracefully.
5517 TheCall->setType(ResultType);
5518
5519 // Prohibit problematic uses of bit-precise integer types with atomic
5520 // builtins. The arguments would have already been converted to the first
5521 // argument's type, so only need to check the first argument.
5522 const auto *BitIntValType = ValType->getAs<BitIntType>();
5523 if (BitIntValType && !llvm::isPowerOf2_64(Value: BitIntValType->getNumBits())) {
5524 Diag(Loc: FirstArg->getExprLoc(), DiagID: diag::err_atomic_builtin_ext_int_size);
5525 return ExprError();
5526 }
5527
5528 return TheCallResult;
5529}
5530
5531ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5532 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5533 DeclRefExpr *DRE =
5534 cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
5535 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
5536 unsigned BuiltinID = FDecl->getBuiltinID();
5537 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5538 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5539 "Unexpected nontemporal load/store builtin!");
5540 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5541 unsigned numArgs = isStore ? 2 : 1;
5542
5543 // Ensure that we have the proper number of arguments.
5544 if (checkArgCount(Call: TheCall, DesiredArgCount: numArgs))
5545 return ExprError();
5546
5547 // Inspect the last argument of the nontemporal builtin. This should always
5548 // be a pointer type, from which we imply the type of the memory access.
5549 // Because it is a pointer type, we don't have to worry about any implicit
5550 // casts here.
5551 Expr *PointerArg = TheCall->getArg(Arg: numArgs - 1);
5552 ExprResult PointerArgResult =
5553 DefaultFunctionArrayLvalueConversion(E: PointerArg);
5554
5555 if (PointerArgResult.isInvalid())
5556 return ExprError();
5557 PointerArg = PointerArgResult.get();
5558 TheCall->setArg(Arg: numArgs - 1, ArgExpr: PointerArg);
5559
5560 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5561 if (!pointerType) {
5562 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_nontemporal_builtin_must_be_pointer)
5563 << PointerArg->getType() << PointerArg->getSourceRange();
5564 return ExprError();
5565 }
5566
5567 QualType ValType = pointerType->getPointeeType();
5568
5569 // Strip any qualifiers off ValType.
5570 ValType = ValType.getUnqualifiedType();
5571 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5572 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5573 !ValType->isVectorType()) {
5574 Diag(Loc: DRE->getBeginLoc(),
5575 DiagID: diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5576 << PointerArg->getType() << PointerArg->getSourceRange();
5577 return ExprError();
5578 }
5579
5580 if (!isStore) {
5581 TheCall->setType(ValType);
5582 return TheCallResult;
5583 }
5584
5585 ExprResult ValArg = TheCall->getArg(Arg: 0);
5586 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5587 Context, Type: ValType, /*consume*/ Consumed: false);
5588 ValArg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: ValArg);
5589 if (ValArg.isInvalid())
5590 return ExprError();
5591
5592 TheCall->setArg(Arg: 0, ArgExpr: ValArg.get());
5593 TheCall->setType(Context.VoidTy);
5594 return TheCallResult;
5595}
5596
5597/// CheckObjCString - Checks that the format string argument to the os_log()
5598/// and os_trace() functions is correct, and converts it to const char *.
5599ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5600 Arg = Arg->IgnoreParenCasts();
5601 auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
5602 if (!Literal) {
5603 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Val: Arg)) {
5604 Literal = ObjcLiteral->getString();
5605 }
5606 }
5607
5608 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
5609 return ExprError(
5610 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_os_log_format_not_string_constant)
5611 << Arg->getSourceRange());
5612 }
5613
5614 ExprResult Result(Literal);
5615 QualType ResultTy = Context.getPointerType(T: Context.CharTy.withConst());
5616 InitializedEntity Entity =
5617 InitializedEntity::InitializeParameter(Context, Type: ResultTy, Consumed: false);
5618 Result = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Result);
5619 return Result;
5620}
5621
5622/// Check that the user is calling the appropriate va_start builtin for the
5623/// target and calling convention.
5624static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5625 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5626 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5627 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5628 TT.getArch() == llvm::Triple::aarch64_32);
5629 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
5630 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5631 if (IsX64 || IsAArch64) {
5632 CallingConv CC = CC_C;
5633 if (const FunctionDecl *FD = S.getCurFunctionDecl())
5634 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5635 if (IsMSVAStart) {
5636 // Don't allow this in System V ABI functions.
5637 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
5638 return S.Diag(Loc: Fn->getBeginLoc(),
5639 DiagID: diag::err_ms_va_start_used_in_sysv_function);
5640 } else {
5641 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5642 // On x64 Windows, don't allow this in System V ABI functions.
5643 // (Yes, that means there's no corresponding way to support variadic
5644 // System V ABI functions on Windows.)
5645 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
5646 (!IsWindowsOrUEFI && CC == CC_Win64))
5647 return S.Diag(Loc: Fn->getBeginLoc(),
5648 DiagID: diag::err_va_start_used_in_wrong_abi_function)
5649 << !IsWindowsOrUEFI;
5650 }
5651 return false;
5652 }
5653
5654 if (IsMSVAStart)
5655 return S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_builtin_x64_aarch64_only);
5656 return false;
5657}
5658
5659static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5660 ParmVarDecl **LastParam = nullptr) {
5661 // Determine whether the current function, block, or obj-c method is variadic
5662 // and get its parameter list.
5663 bool IsVariadic = false;
5664 ArrayRef<ParmVarDecl *> Params;
5665 DeclContext *Caller = S.CurContext;
5666 if (auto *Block = dyn_cast<BlockDecl>(Val: Caller)) {
5667 IsVariadic = Block->isVariadic();
5668 Params = Block->parameters();
5669 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: Caller)) {
5670 IsVariadic = FD->isVariadic();
5671 Params = FD->parameters();
5672 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Val: Caller)) {
5673 IsVariadic = MD->isVariadic();
5674 // FIXME: This isn't correct for methods (results in bogus warning).
5675 Params = MD->parameters();
5676 } else if (isa<CapturedDecl>(Val: Caller)) {
5677 // We don't support va_start in a CapturedDecl.
5678 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_captured_stmt);
5679 return true;
5680 } else {
5681 // This must be some other declcontext that parses exprs.
5682 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_outside_function);
5683 return true;
5684 }
5685
5686 if (!IsVariadic) {
5687 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_fixed_function);
5688 return true;
5689 }
5690
5691 if (LastParam)
5692 *LastParam = Params.empty() ? nullptr : Params.back();
5693
5694 return false;
5695}
5696
5697bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5698 Expr *Fn = TheCall->getCallee();
5699 if (checkVAStartABI(S&: *this, BuiltinID, Fn))
5700 return true;
5701
5702 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
5703 // This builtin requires one argument (the va_list), allows two arguments,
5704 // but diagnoses more than two arguments. e.g.,
5705 // __builtin_c23_va_start(); // error
5706 // __builtin_c23_va_start(list); // ok
5707 // __builtin_c23_va_start(list, param); // ok
5708 // __builtin_c23_va_start(list, anything, anything); // error
5709 // This differs from the GCC behavior in that they accept the last case
5710 // with a warning, but it doesn't seem like a useful behavior to allow.
5711 if (checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
5712 return true;
5713 } else {
5714 // In C23 mode, va_start only needs one argument. However, the builtin still
5715 // requires two arguments (which matches the behavior of the GCC builtin),
5716 // <stdarg.h> passes `0` as the second argument in C23 mode.
5717 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
5718 return true;
5719 }
5720
5721 // Type-check the first argument normally.
5722 if (checkBuiltinArgument(S&: *this, E: TheCall, ArgIndex: 0))
5723 return true;
5724
5725 // Check that the current function is variadic, and get its last parameter.
5726 ParmVarDecl *LastParam;
5727 if (checkVAStartIsInVariadicFunction(S&: *this, Fn, LastParam: &LastParam))
5728 return true;
5729
5730 // Verify that the second argument to the builtin is the last non-variadic
5731 // argument of the current function or method. In C23 mode, if the call is
5732 // not to __builtin_c23_va_start, and the second argument is an integer
5733 // constant expression with value 0, then we don't bother with this check.
5734 // For __builtin_c23_va_start, we only perform the check for the second
5735 // argument being the last argument to the current function if there is a
5736 // second argument present.
5737 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
5738 TheCall->getNumArgs() < 2) {
5739 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
5740 return false;
5741 }
5742
5743 const Expr *Arg = TheCall->getArg(Arg: 1)->IgnoreParenCasts();
5744 if (std::optional<llvm::APSInt> Val =
5745 TheCall->getArg(Arg: 1)->getIntegerConstantExpr(Ctx: Context);
5746 Val && LangOpts.C23 && *Val == 0 &&
5747 BuiltinID != Builtin::BI__builtin_c23_va_start) {
5748 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
5749 return false;
5750 }
5751
5752 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
5753 // next block.
5754 QualType Type;
5755 SourceLocation ParamLoc;
5756 bool IsCRegister = false;
5757 bool SecondArgIsLastNonVariadicArgument = false;
5758 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: Arg)) {
5759 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: DR->getDecl())) {
5760 SecondArgIsLastNonVariadicArgument = PV == LastParam;
5761
5762 Type = PV->getType();
5763 ParamLoc = PV->getLocation();
5764 IsCRegister =
5765 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5766 }
5767 }
5768
5769 if (!SecondArgIsLastNonVariadicArgument)
5770 Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
5771 DiagID: diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
5772 else if (IsCRegister || Type->isReferenceType() ||
5773 Type->isSpecificBuiltinType(K: BuiltinType::Float) || [=] {
5774 // Promotable integers are UB, but enumerations need a bit of
5775 // extra checking to see what their promotable type actually is.
5776 if (!Context.isPromotableIntegerType(T: Type))
5777 return false;
5778 const auto *ED = Type->getAsEnumDecl();
5779 if (!ED)
5780 return true;
5781 return !Context.typesAreCompatible(T1: ED->getPromotionType(), T2: Type);
5782 }()) {
5783 unsigned Reason = 0;
5784 if (Type->isReferenceType()) Reason = 1;
5785 else if (IsCRegister) Reason = 2;
5786 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_va_start_type_is_undefined) << Reason;
5787 Diag(Loc: ParamLoc, DiagID: diag::note_parameter_type) << Type;
5788 }
5789
5790 return false;
5791}
5792
5793bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
5794 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
5795 const LangOptions &LO = getLangOpts();
5796
5797 if (LO.CPlusPlus)
5798 return Arg->getType()
5799 .getCanonicalType()
5800 .getTypePtr()
5801 ->getPointeeType()
5802 .withoutLocalFastQualifiers() == Context.CharTy;
5803
5804 // In C, allow aliasing through `char *`, this is required for AArch64 at
5805 // least.
5806 return true;
5807 };
5808
5809 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5810 // const char *named_addr);
5811
5812 Expr *Func = Call->getCallee();
5813
5814 if (Call->getNumArgs() < 3)
5815 return Diag(Loc: Call->getEndLoc(),
5816 DiagID: diag::err_typecheck_call_too_few_args_at_least)
5817 << 0 /*function call*/ << 3 << Call->getNumArgs()
5818 << /*is non object*/ 0;
5819
5820 // Type-check the first argument normally.
5821 if (checkBuiltinArgument(S&: *this, E: Call, ArgIndex: 0))
5822 return true;
5823
5824 // Check that the current function is variadic.
5825 if (checkVAStartIsInVariadicFunction(S&: *this, Fn: Func))
5826 return true;
5827
5828 // __va_start on Windows does not validate the parameter qualifiers
5829
5830 const Expr *Arg1 = Call->getArg(Arg: 1)->IgnoreParens();
5831 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5832
5833 const Expr *Arg2 = Call->getArg(Arg: 2)->IgnoreParens();
5834 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5835
5836 const QualType &ConstCharPtrTy =
5837 Context.getPointerType(T: Context.CharTy.withConst());
5838 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
5839 Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
5840 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5841 << 0 /* qualifier difference */
5842 << 3 /* parameter mismatch */
5843 << 2 << Arg1->getType() << ConstCharPtrTy;
5844
5845 const QualType SizeTy = Context.getSizeType();
5846 if (!Context.hasSameType(
5847 T1: Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers(),
5848 T2: SizeTy))
5849 Diag(Loc: Arg2->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
5850 << Arg2->getType() << SizeTy << 1 /* different class */
5851 << 0 /* qualifier difference */
5852 << 3 /* parameter mismatch */
5853 << 3 << Arg2->getType() << SizeTy;
5854
5855 return false;
5856}
5857
5858bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
5859 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
5860 return true;
5861
5862 if (BuiltinID == Builtin::BI__builtin_isunordered &&
5863 TheCall->getFPFeaturesInEffect(LO: getLangOpts()).getNoHonorNaNs())
5864 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
5865 << 1 << 0 << TheCall->getSourceRange();
5866
5867 ExprResult OrigArg0 = TheCall->getArg(Arg: 0);
5868 ExprResult OrigArg1 = TheCall->getArg(Arg: 1);
5869
5870 // Do standard promotions between the two arguments, returning their common
5871 // type.
5872 QualType Res = UsualArithmeticConversions(
5873 LHS&: OrigArg0, RHS&: OrigArg1, Loc: TheCall->getExprLoc(), ACK: ArithConvKind::Comparison);
5874 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5875 return true;
5876
5877 // Make sure any conversions are pushed back into the call; this is
5878 // type safe since unordered compare builtins are declared as "_Bool
5879 // foo(...)".
5880 TheCall->setArg(Arg: 0, ArgExpr: OrigArg0.get());
5881 TheCall->setArg(Arg: 1, ArgExpr: OrigArg1.get());
5882
5883 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5884 return false;
5885
5886 // If the common type isn't a real floating type, then the arguments were
5887 // invalid for this operation.
5888 if (Res.isNull() || !Res->isRealFloatingType())
5889 return Diag(Loc: OrigArg0.get()->getBeginLoc(),
5890 DiagID: diag::err_typecheck_call_invalid_ordered_compare)
5891 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5892 << SourceRange(OrigArg0.get()->getBeginLoc(),
5893 OrigArg1.get()->getEndLoc());
5894
5895 return false;
5896}
5897
5898bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
5899 unsigned BuiltinID) {
5900 if (checkArgCount(Call: TheCall, DesiredArgCount: NumArgs))
5901 return true;
5902
5903 FPOptions FPO = TheCall->getFPFeaturesInEffect(LO: getLangOpts());
5904 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
5905 BuiltinID == Builtin::BI__builtin_isinf ||
5906 BuiltinID == Builtin::BI__builtin_isinf_sign))
5907 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
5908 << 0 << 0 << TheCall->getSourceRange();
5909
5910 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
5911 BuiltinID == Builtin::BI__builtin_isunordered))
5912 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
5913 << 1 << 0 << TheCall->getSourceRange();
5914
5915 bool IsFPClass = NumArgs == 2;
5916
5917 // Find out position of floating-point argument.
5918 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
5919
5920 // We can count on all parameters preceding the floating-point just being int.
5921 // Try all of those.
5922 for (unsigned i = 0; i < FPArgNo; ++i) {
5923 Expr *Arg = TheCall->getArg(Arg: i);
5924
5925 if (Arg->isTypeDependent())
5926 return false;
5927
5928 ExprResult Res = PerformImplicitConversion(From: Arg, ToType: Context.IntTy,
5929 Action: AssignmentAction::Passing);
5930
5931 if (Res.isInvalid())
5932 return true;
5933 TheCall->setArg(Arg: i, ArgExpr: Res.get());
5934 }
5935
5936 Expr *OrigArg = TheCall->getArg(Arg: FPArgNo);
5937
5938 if (OrigArg->isTypeDependent())
5939 return false;
5940
5941 // Usual Unary Conversions will convert half to float, which we want for
5942 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5943 // type how it is, but do normal L->Rvalue conversions.
5944 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
5945 ExprResult Res = UsualUnaryConversions(E: OrigArg);
5946
5947 if (!Res.isUsable())
5948 return true;
5949 OrigArg = Res.get();
5950 } else {
5951 ExprResult Res = DefaultFunctionArrayLvalueConversion(E: OrigArg);
5952
5953 if (!Res.isUsable())
5954 return true;
5955 OrigArg = Res.get();
5956 }
5957 TheCall->setArg(Arg: FPArgNo, ArgExpr: OrigArg);
5958
5959 QualType VectorResultTy;
5960 QualType ElementTy = OrigArg->getType();
5961 // TODO: When all classification function are implemented with is_fpclass,
5962 // vector argument can be supported in all of them.
5963 if (ElementTy->isVectorType() && IsFPClass) {
5964 VectorResultTy = GetSignedVectorType(V: ElementTy);
5965 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
5966 }
5967
5968 // This operation requires a non-_Complex floating-point number.
5969 if (!ElementTy->isRealFloatingType())
5970 return Diag(Loc: OrigArg->getBeginLoc(),
5971 DiagID: diag::err_typecheck_call_invalid_unary_fp)
5972 << OrigArg->getType() << OrigArg->getSourceRange();
5973
5974 // __builtin_isfpclass has integer parameter that specify test mask. It is
5975 // passed in (...), so it should be analyzed completely here.
5976 if (IsFPClass)
5977 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: llvm::fcAllFlags))
5978 return true;
5979
5980 // TODO: enable this code to all classification functions.
5981 if (IsFPClass) {
5982 QualType ResultTy;
5983 if (!VectorResultTy.isNull())
5984 ResultTy = VectorResultTy;
5985 else
5986 ResultTy = Context.IntTy;
5987 TheCall->setType(ResultTy);
5988 }
5989
5990 return false;
5991}
5992
5993bool Sema::BuiltinComplex(CallExpr *TheCall) {
5994 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
5995 return true;
5996
5997 bool Dependent = false;
5998 for (unsigned I = 0; I != 2; ++I) {
5999 Expr *Arg = TheCall->getArg(Arg: I);
6000 QualType T = Arg->getType();
6001 if (T->isDependentType()) {
6002 Dependent = true;
6003 continue;
6004 }
6005
6006 // Despite supporting _Complex int, GCC requires a real floating point type
6007 // for the operands of __builtin_complex.
6008 if (!T->isRealFloatingType()) {
6009 return Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_typecheck_call_requires_real_fp)
6010 << Arg->getType() << Arg->getSourceRange();
6011 }
6012
6013 ExprResult Converted = DefaultLvalueConversion(E: Arg);
6014 if (Converted.isInvalid())
6015 return true;
6016 TheCall->setArg(Arg: I, ArgExpr: Converted.get());
6017 }
6018
6019 if (Dependent) {
6020 TheCall->setType(Context.DependentTy);
6021 return false;
6022 }
6023
6024 Expr *Real = TheCall->getArg(Arg: 0);
6025 Expr *Imag = TheCall->getArg(Arg: 1);
6026 if (!Context.hasSameType(T1: Real->getType(), T2: Imag->getType())) {
6027 return Diag(Loc: Real->getBeginLoc(),
6028 DiagID: diag::err_typecheck_call_different_arg_types)
6029 << Real->getType() << Imag->getType()
6030 << Real->getSourceRange() << Imag->getSourceRange();
6031 }
6032
6033 TheCall->setType(Context.getComplexType(T: Real->getType()));
6034 return false;
6035}
6036
6037/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6038// This is declared to take (...), so we have to check everything.
6039ExprResult Sema::BuiltinShuffleVector(CallExpr *TheCall) {
6040 unsigned NumArgs = TheCall->getNumArgs();
6041 if (NumArgs < 2)
6042 return ExprError(Diag(Loc: TheCall->getEndLoc(),
6043 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6044 << 0 /*function call*/ << 2 << NumArgs
6045 << /*is non object*/ 0 << TheCall->getSourceRange());
6046
6047 // Determine which of the following types of shufflevector we're checking:
6048 // 1) unary, vector mask: (lhs, mask)
6049 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6050 QualType ResType = TheCall->getArg(Arg: 0)->getType();
6051 unsigned NumElements = 0;
6052
6053 if (!TheCall->getArg(Arg: 0)->isTypeDependent() &&
6054 !TheCall->getArg(Arg: 1)->isTypeDependent()) {
6055 QualType LHSType = TheCall->getArg(Arg: 0)->getType();
6056 QualType RHSType = TheCall->getArg(Arg: 1)->getType();
6057
6058 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6059 return ExprError(
6060 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_builtin_non_vector)
6061 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6062 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6063 TheCall->getArg(Arg: 1)->getEndLoc()));
6064
6065 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6066 unsigned NumResElements = NumArgs - 2;
6067
6068 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6069 // with mask. If so, verify that RHS is an integer vector type with the
6070 // same number of elts as lhs.
6071 if (NumArgs == 2) {
6072 if (!RHSType->hasIntegerRepresentation() ||
6073 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6074 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6075 DiagID: diag::err_vec_builtin_incompatible_vector)
6076 << TheCall->getDirectCallee()
6077 << /*isMoreThanTwoArgs*/ false
6078 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
6079 TheCall->getArg(Arg: 1)->getEndLoc()));
6080 } else if (!Context.hasSameUnqualifiedType(T1: LHSType, T2: RHSType)) {
6081 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6082 DiagID: diag::err_vec_builtin_incompatible_vector)
6083 << TheCall->getDirectCallee()
6084 << /*isMoreThanTwoArgs*/ false
6085 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6086 TheCall->getArg(Arg: 1)->getEndLoc()));
6087 } else if (NumElements != NumResElements) {
6088 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6089 ResType = ResType->isExtVectorType()
6090 ? Context.getExtVectorType(VectorType: EltType, NumElts: NumResElements)
6091 : Context.getVectorType(VectorType: EltType, NumElts: NumResElements,
6092 VecKind: VectorKind::Generic);
6093 }
6094 }
6095
6096 for (unsigned I = 2; I != NumArgs; ++I) {
6097 Expr *Arg = TheCall->getArg(Arg: I);
6098 if (Arg->isTypeDependent() || Arg->isValueDependent())
6099 continue;
6100
6101 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
6102 if (!Result)
6103 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6104 DiagID: diag::err_shufflevector_nonconstant_argument)
6105 << Arg->getSourceRange());
6106
6107 // Allow -1 which will be translated to undef in the IR.
6108 if (Result->isSigned() && Result->isAllOnes())
6109 ;
6110 else if (Result->getActiveBits() > 64 ||
6111 Result->getZExtValue() >= NumElements * 2)
6112 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6113 DiagID: diag::err_shufflevector_argument_too_large)
6114 << Arg->getSourceRange());
6115
6116 TheCall->setArg(Arg: I, ArgExpr: ConstantExpr::Create(Context, E: Arg, Result: APValue(*Result)));
6117 }
6118
6119 auto *Result = new (Context) ShuffleVectorExpr(
6120 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6121 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6122
6123 // All moved to Result.
6124 TheCall->shrinkNumArgs(NewNumArgs: 0);
6125 return Result;
6126}
6127
6128ExprResult Sema::ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6129 SourceLocation BuiltinLoc,
6130 SourceLocation RParenLoc) {
6131 ExprValueKind VK = VK_PRValue;
6132 ExprObjectKind OK = OK_Ordinary;
6133 QualType DstTy = TInfo->getType();
6134 QualType SrcTy = E->getType();
6135
6136 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6137 return ExprError(Diag(Loc: BuiltinLoc,
6138 DiagID: diag::err_convertvector_non_vector)
6139 << E->getSourceRange());
6140 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6141 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_builtin_non_vector_type)
6142 << "second"
6143 << "__builtin_convertvector");
6144
6145 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6146 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6147 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6148 if (SrcElts != DstElts)
6149 return ExprError(Diag(Loc: BuiltinLoc,
6150 DiagID: diag::err_convertvector_incompatible_vector)
6151 << E->getSourceRange());
6152 }
6153
6154 return ConvertVectorExpr::Create(C: Context, SrcExpr: E, TI: TInfo, DstType: DstTy, VK, OK, BuiltinLoc,
6155 RParenLoc, FPFeatures: CurFPFeatureOverrides());
6156}
6157
6158bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6159 unsigned NumArgs = TheCall->getNumArgs();
6160
6161 if (NumArgs > 3)
6162 return Diag(Loc: TheCall->getEndLoc(),
6163 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6164 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6165 << TheCall->getSourceRange();
6166
6167 // Argument 0 is checked for us and the remaining arguments must be
6168 // constant integers.
6169 for (unsigned i = 1; i != NumArgs; ++i)
6170 if (BuiltinConstantArgRange(TheCall, ArgNum: i, Low: 0, High: i == 1 ? 1 : 3))
6171 return true;
6172
6173 return false;
6174}
6175
6176bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6177 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6178 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
6179 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6180 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
6181 return true;
6182 Expr *Arg = TheCall->getArg(Arg: 0);
6183 if (Arg->isInstantiationDependent())
6184 return false;
6185
6186 QualType ArgTy = Arg->getType();
6187 if (!ArgTy->hasFloatingRepresentation())
6188 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_expect_flt_or_vector)
6189 << ArgTy;
6190 if (Arg->isLValue()) {
6191 ExprResult FirstArg = DefaultLvalueConversion(E: Arg);
6192 TheCall->setArg(Arg: 0, ArgExpr: FirstArg.get());
6193 }
6194 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
6195 return false;
6196}
6197
6198bool Sema::BuiltinAssume(CallExpr *TheCall) {
6199 Expr *Arg = TheCall->getArg(Arg: 0);
6200 if (Arg->isInstantiationDependent()) return false;
6201
6202 if (Arg->HasSideEffects(Ctx: Context))
6203 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_assume_side_effects)
6204 << Arg->getSourceRange()
6205 << cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getIdentifier();
6206
6207 return false;
6208}
6209
6210bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6211 // The alignment must be a constant integer.
6212 Expr *Arg = TheCall->getArg(Arg: 1);
6213
6214 // We can't check the value of a dependent argument.
6215 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6216 if (const auto *UE =
6217 dyn_cast<UnaryExprOrTypeTraitExpr>(Val: Arg->IgnoreParenImpCasts()))
6218 if (UE->getKind() == UETT_AlignOf ||
6219 UE->getKind() == UETT_PreferredAlignOf)
6220 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca_align_alignof)
6221 << Arg->getSourceRange();
6222
6223 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Ctx: Context);
6224
6225 if (!Result.isPowerOf2())
6226 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6227 << Arg->getSourceRange();
6228
6229 if (Result < Context.getCharWidth())
6230 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_small)
6231 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6232
6233 if (Result > std::numeric_limits<int32_t>::max())
6234 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_big)
6235 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6236 }
6237
6238 return false;
6239}
6240
6241bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6242 if (checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
6243 return true;
6244
6245 unsigned NumArgs = TheCall->getNumArgs();
6246 Expr *FirstArg = TheCall->getArg(Arg: 0);
6247
6248 {
6249 ExprResult FirstArgResult =
6250 DefaultFunctionArrayLvalueConversion(E: FirstArg);
6251 if (!FirstArgResult.get()->getType()->isPointerType()) {
6252 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_assume_aligned_invalid_arg)
6253 << TheCall->getSourceRange();
6254 return true;
6255 }
6256 TheCall->setArg(Arg: 0, ArgExpr: FirstArgResult.get());
6257 }
6258
6259 // The alignment must be a constant integer.
6260 Expr *SecondArg = TheCall->getArg(Arg: 1);
6261
6262 // We can't check the value of a dependent argument.
6263 if (!SecondArg->isValueDependent()) {
6264 llvm::APSInt Result;
6265 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
6266 return true;
6267
6268 if (!Result.isPowerOf2())
6269 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6270 << SecondArg->getSourceRange();
6271
6272 if (Result > Sema::MaximumAlignment)
6273 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_assume_aligned_too_great)
6274 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6275
6276 TheCall->setArg(Arg: 1,
6277 ArgExpr: ConstantExpr::Create(Context, E: SecondArg, Result: APValue(Result)));
6278 }
6279
6280 if (NumArgs > 2) {
6281 Expr *ThirdArg = TheCall->getArg(Arg: 2);
6282 if (convertArgumentToType(S&: *this, Value&: ThirdArg, Ty: Context.getSizeType()))
6283 return true;
6284 TheCall->setArg(Arg: 2, ArgExpr: ThirdArg);
6285 }
6286
6287 return false;
6288}
6289
6290bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6291 unsigned BuiltinID =
6292 cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getBuiltinID();
6293 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6294
6295 unsigned NumArgs = TheCall->getNumArgs();
6296 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6297 if (NumArgs < NumRequiredArgs) {
6298 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args)
6299 << 0 /* function call */ << NumRequiredArgs << NumArgs
6300 << /*is non object*/ 0 << TheCall->getSourceRange();
6301 }
6302 if (NumArgs >= NumRequiredArgs + 0x100) {
6303 return Diag(Loc: TheCall->getEndLoc(),
6304 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6305 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6306 << /*is non object*/ 0 << TheCall->getSourceRange();
6307 }
6308 unsigned i = 0;
6309
6310 // For formatting call, check buffer arg.
6311 if (!IsSizeCall) {
6312 ExprResult Arg(TheCall->getArg(Arg: i));
6313 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6314 Context, Type: Context.VoidPtrTy, Consumed: false);
6315 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
6316 if (Arg.isInvalid())
6317 return true;
6318 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6319 i++;
6320 }
6321
6322 // Check string literal arg.
6323 unsigned FormatIdx = i;
6324 {
6325 ExprResult Arg = CheckOSLogFormatStringArg(Arg: TheCall->getArg(Arg: i));
6326 if (Arg.isInvalid())
6327 return true;
6328 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6329 i++;
6330 }
6331
6332 // Make sure variadic args are scalar.
6333 unsigned FirstDataArg = i;
6334 while (i < NumArgs) {
6335 ExprResult Arg = DefaultVariadicArgumentPromotion(
6336 E: TheCall->getArg(Arg: i), CT: VariadicCallType::Function, FDecl: nullptr);
6337 if (Arg.isInvalid())
6338 return true;
6339 CharUnits ArgSize = Context.getTypeSizeInChars(T: Arg.get()->getType());
6340 if (ArgSize.getQuantity() >= 0x100) {
6341 return Diag(Loc: Arg.get()->getEndLoc(), DiagID: diag::err_os_log_argument_too_big)
6342 << i << (int)ArgSize.getQuantity() << 0xff
6343 << TheCall->getSourceRange();
6344 }
6345 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6346 i++;
6347 }
6348
6349 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6350 // call to avoid duplicate diagnostics.
6351 if (!IsSizeCall) {
6352 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6353 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6354 bool Success = CheckFormatArguments(
6355 Args, FAPK: FAPK_Variadic, ReferenceFormatString: nullptr, format_idx: FormatIdx, firstDataArg: FirstDataArg,
6356 Type: FormatStringType::OSLog, CallType: VariadicCallType::Function,
6357 Loc: TheCall->getBeginLoc(), range: SourceRange(), CheckedVarArgs);
6358 if (!Success)
6359 return true;
6360 }
6361
6362 if (IsSizeCall) {
6363 TheCall->setType(Context.getSizeType());
6364 } else {
6365 TheCall->setType(Context.VoidPtrTy);
6366 }
6367 return false;
6368}
6369
6370bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6371 llvm::APSInt &Result) {
6372 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6373
6374 if (Arg->isTypeDependent() || Arg->isValueDependent())
6375 return false;
6376
6377 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Ctx: Context);
6378 if (!R) {
6379 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
6380 auto *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
6381 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_constant_integer_arg_type)
6382 << FDecl->getDeclName() << Arg->getSourceRange();
6383 }
6384 Result = *R;
6385
6386 return false;
6387}
6388
6389bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6390 int High, bool RangeIsError) {
6391 if (isConstantEvaluatedContext())
6392 return false;
6393 llvm::APSInt Result;
6394
6395 // We can't check the value of a dependent argument.
6396 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6397 if (Arg->isTypeDependent() || Arg->isValueDependent())
6398 return false;
6399
6400 // Check constant-ness first.
6401 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6402 return true;
6403
6404 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6405 if (RangeIsError)
6406 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_invalid_range)
6407 << toString(I: Result, Radix: 10) << Low << High << Arg->getSourceRange();
6408 else
6409 // Defer the warning until we know if the code will be emitted so that
6410 // dead code can ignore this.
6411 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
6412 PD: PDiag(DiagID: diag::warn_argument_invalid_range)
6413 << toString(I: Result, Radix: 10) << Low << High
6414 << Arg->getSourceRange());
6415 }
6416
6417 return false;
6418}
6419
6420bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6421 unsigned Num) {
6422 llvm::APSInt Result;
6423
6424 // We can't check the value of a dependent argument.
6425 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6426 if (Arg->isTypeDependent() || Arg->isValueDependent())
6427 return false;
6428
6429 // Check constant-ness first.
6430 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6431 return true;
6432
6433 if (Result.getSExtValue() % Num != 0)
6434 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_multiple)
6435 << Num << Arg->getSourceRange();
6436
6437 return false;
6438}
6439
6440bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6441 llvm::APSInt Result;
6442
6443 // We can't check the value of a dependent argument.
6444 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6445 if (Arg->isTypeDependent() || Arg->isValueDependent())
6446 return false;
6447
6448 // Check constant-ness first.
6449 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6450 return true;
6451
6452 if (Result.isPowerOf2())
6453 return false;
6454
6455 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_power_of_2)
6456 << Arg->getSourceRange();
6457}
6458
6459static bool IsShiftedByte(llvm::APSInt Value) {
6460 if (Value.isNegative())
6461 return false;
6462
6463 // Check if it's a shifted byte, by shifting it down
6464 while (true) {
6465 // If the value fits in the bottom byte, the check passes.
6466 if (Value < 0x100)
6467 return true;
6468
6469 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6470 // fails.
6471 if ((Value & 0xFF) != 0)
6472 return false;
6473
6474 // If the bottom 8 bits are all 0, but something above that is nonzero,
6475 // then shifting the value right by 8 bits won't affect whether it's a
6476 // shifted byte or not. So do that, and go round again.
6477 Value >>= 8;
6478 }
6479}
6480
6481bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6482 unsigned ArgBits) {
6483 llvm::APSInt Result;
6484
6485 // We can't check the value of a dependent argument.
6486 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6487 if (Arg->isTypeDependent() || Arg->isValueDependent())
6488 return false;
6489
6490 // Check constant-ness first.
6491 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6492 return true;
6493
6494 // Truncate to the given size.
6495 Result = Result.getLoBits(numBits: ArgBits);
6496 Result.setIsUnsigned(true);
6497
6498 if (IsShiftedByte(Value: Result))
6499 return false;
6500
6501 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_shifted_byte)
6502 << Arg->getSourceRange();
6503}
6504
6505bool Sema::BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6506 unsigned ArgNum,
6507 unsigned ArgBits) {
6508 llvm::APSInt Result;
6509
6510 // We can't check the value of a dependent argument.
6511 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6512 if (Arg->isTypeDependent() || Arg->isValueDependent())
6513 return false;
6514
6515 // Check constant-ness first.
6516 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6517 return true;
6518
6519 // Truncate to the given size.
6520 Result = Result.getLoBits(numBits: ArgBits);
6521 Result.setIsUnsigned(true);
6522
6523 // Check to see if it's in either of the required forms.
6524 if (IsShiftedByte(Value: Result) ||
6525 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6526 return false;
6527
6528 return Diag(Loc: TheCall->getBeginLoc(),
6529 DiagID: diag::err_argument_not_shifted_byte_or_xxff)
6530 << Arg->getSourceRange();
6531}
6532
6533bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6534 if (!Context.getTargetInfo().hasSjLjLowering())
6535 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_unsupported)
6536 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6537
6538 Expr *Arg = TheCall->getArg(Arg: 1);
6539 llvm::APSInt Result;
6540
6541 // TODO: This is less than ideal. Overload this to take a value.
6542 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
6543 return true;
6544
6545 if (Result != 1)
6546 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_invalid_val)
6547 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6548
6549 return false;
6550}
6551
6552bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6553 if (!Context.getTargetInfo().hasSjLjLowering())
6554 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_setjmp_unsupported)
6555 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6556 return false;
6557}
6558
6559bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
6560 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
6561 return true;
6562
6563 ExprResult ArgRes = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
6564 if (ArgRes.isInvalid())
6565 return true;
6566
6567 // For simplicity, we support only limited expressions for the argument.
6568 // Specifically a flexible array member or a pointer with counted_by:
6569 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
6570 // complex casting, which really shouldn't be a huge problem.
6571 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
6572 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
6573 return Diag(Loc: Arg->getBeginLoc(),
6574 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
6575 << Arg->getSourceRange();
6576
6577 if (Arg->HasSideEffects(Ctx: Context))
6578 return Diag(Loc: Arg->getBeginLoc(),
6579 DiagID: diag::err_builtin_counted_by_ref_has_side_effects)
6580 << Arg->getSourceRange();
6581
6582 if (const auto *ME = dyn_cast<MemberExpr>(Val: Arg)) {
6583 const auto *CATy =
6584 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
6585
6586 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
6587 // Member has counted_by attribute - return pointer to count field
6588 const auto *MemberDecl = cast<FieldDecl>(Val: ME->getMemberDecl());
6589 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
6590 TheCall->setType(Context.getPointerType(T: CountFD->getType()));
6591 return false;
6592 }
6593 }
6594
6595 // FAMs and pointers without counted_by return void*
6596 QualType MemberTy = ME->getMemberDecl()->getType();
6597 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
6598 return Diag(Loc: Arg->getBeginLoc(),
6599 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
6600 << Arg->getSourceRange();
6601 } else {
6602 return Diag(Loc: Arg->getBeginLoc(),
6603 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
6604 << Arg->getSourceRange();
6605 }
6606
6607 TheCall->setType(Context.getPointerType(T: Context.VoidTy));
6608 return false;
6609}
6610
6611/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
6612/// It allows leaking and modification of bounds safety information.
6613bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
6614 BuiltinCountedByRefKind K) {
6615 const CallExpr *CE =
6616 E ? dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts()) : nullptr;
6617 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
6618 return false;
6619
6620 switch (K) {
6621 case BuiltinCountedByRefKind::Assignment:
6622 case BuiltinCountedByRefKind::Initializer:
6623 Diag(Loc: E->getExprLoc(),
6624 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
6625 << 0 << E->getSourceRange();
6626 break;
6627 case BuiltinCountedByRefKind::FunctionArg:
6628 Diag(Loc: E->getExprLoc(),
6629 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
6630 << 1 << E->getSourceRange();
6631 break;
6632 case BuiltinCountedByRefKind::ReturnArg:
6633 Diag(Loc: E->getExprLoc(),
6634 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
6635 << 2 << E->getSourceRange();
6636 break;
6637 case BuiltinCountedByRefKind::ArraySubscript:
6638 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
6639 << 0 << E->getSourceRange();
6640 break;
6641 case BuiltinCountedByRefKind::BinaryExpr:
6642 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
6643 << 1 << E->getSourceRange();
6644 break;
6645 }
6646
6647 return true;
6648}
6649
6650namespace {
6651
6652class UncoveredArgHandler {
6653 enum { Unknown = -1, AllCovered = -2 };
6654
6655 signed FirstUncoveredArg = Unknown;
6656 SmallVector<const Expr *, 4> DiagnosticExprs;
6657
6658public:
6659 UncoveredArgHandler() = default;
6660
6661 bool hasUncoveredArg() const {
6662 return (FirstUncoveredArg >= 0);
6663 }
6664
6665 unsigned getUncoveredArg() const {
6666 assert(hasUncoveredArg() && "no uncovered argument");
6667 return FirstUncoveredArg;
6668 }
6669
6670 void setAllCovered() {
6671 // A string has been found with all arguments covered, so clear out
6672 // the diagnostics.
6673 DiagnosticExprs.clear();
6674 FirstUncoveredArg = AllCovered;
6675 }
6676
6677 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6678 assert(NewFirstUncoveredArg >= 0 && "Outside range");
6679
6680 // Don't update if a previous string covers all arguments.
6681 if (FirstUncoveredArg == AllCovered)
6682 return;
6683
6684 // UncoveredArgHandler tracks the highest uncovered argument index
6685 // and with it all the strings that match this index.
6686 if (NewFirstUncoveredArg == FirstUncoveredArg)
6687 DiagnosticExprs.push_back(Elt: StrExpr);
6688 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6689 DiagnosticExprs.clear();
6690 DiagnosticExprs.push_back(Elt: StrExpr);
6691 FirstUncoveredArg = NewFirstUncoveredArg;
6692 }
6693 }
6694
6695 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6696};
6697
6698enum StringLiteralCheckType {
6699 SLCT_NotALiteral,
6700 SLCT_UncheckedLiteral,
6701 SLCT_CheckedLiteral
6702};
6703
6704} // namespace
6705
6706static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6707 BinaryOperatorKind BinOpKind,
6708 bool AddendIsRight) {
6709 unsigned BitWidth = Offset.getBitWidth();
6710 unsigned AddendBitWidth = Addend.getBitWidth();
6711 // There might be negative interim results.
6712 if (Addend.isUnsigned()) {
6713 Addend = Addend.zext(width: ++AddendBitWidth);
6714 Addend.setIsSigned(true);
6715 }
6716 // Adjust the bit width of the APSInts.
6717 if (AddendBitWidth > BitWidth) {
6718 Offset = Offset.sext(width: AddendBitWidth);
6719 BitWidth = AddendBitWidth;
6720 } else if (BitWidth > AddendBitWidth) {
6721 Addend = Addend.sext(width: BitWidth);
6722 }
6723
6724 bool Ov = false;
6725 llvm::APSInt ResOffset = Offset;
6726 if (BinOpKind == BO_Add)
6727 ResOffset = Offset.sadd_ov(RHS: Addend, Overflow&: Ov);
6728 else {
6729 assert(AddendIsRight && BinOpKind == BO_Sub &&
6730 "operator must be add or sub with addend on the right");
6731 ResOffset = Offset.ssub_ov(RHS: Addend, Overflow&: Ov);
6732 }
6733
6734 // We add an offset to a pointer here so we should support an offset as big as
6735 // possible.
6736 if (Ov) {
6737 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6738 "index (intermediate) result too big");
6739 Offset = Offset.sext(width: 2 * BitWidth);
6740 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6741 return;
6742 }
6743
6744 Offset = ResOffset;
6745}
6746
6747namespace {
6748
6749// This is a wrapper class around StringLiteral to support offsetted string
6750// literals as format strings. It takes the offset into account when returning
6751// the string and its length or the source locations to display notes correctly.
6752class FormatStringLiteral {
6753 const StringLiteral *FExpr;
6754 int64_t Offset;
6755
6756public:
6757 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6758 : FExpr(fexpr), Offset(Offset) {}
6759
6760 const StringLiteral *getFormatString() const { return FExpr; }
6761
6762 StringRef getString() const { return FExpr->getString().drop_front(N: Offset); }
6763
6764 unsigned getByteLength() const {
6765 return FExpr->getByteLength() - getCharByteWidth() * Offset;
6766 }
6767
6768 unsigned getLength() const { return FExpr->getLength() - Offset; }
6769 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6770
6771 StringLiteralKind getKind() const { return FExpr->getKind(); }
6772
6773 QualType getType() const { return FExpr->getType(); }
6774
6775 bool isAscii() const { return FExpr->isOrdinary(); }
6776 bool isWide() const { return FExpr->isWide(); }
6777 bool isUTF8() const { return FExpr->isUTF8(); }
6778 bool isUTF16() const { return FExpr->isUTF16(); }
6779 bool isUTF32() const { return FExpr->isUTF32(); }
6780 bool isPascal() const { return FExpr->isPascal(); }
6781
6782 SourceLocation getLocationOfByte(
6783 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6784 const TargetInfo &Target, unsigned *StartToken = nullptr,
6785 unsigned *StartTokenByteOffset = nullptr) const {
6786 return FExpr->getLocationOfByte(ByteNo: ByteNo + Offset, SM, Features, Target,
6787 StartToken, StartTokenByteOffset);
6788 }
6789
6790 SourceLocation getBeginLoc() const LLVM_READONLY {
6791 return FExpr->getBeginLoc().getLocWithOffset(Offset);
6792 }
6793
6794 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6795};
6796
6797} // namespace
6798
6799static void CheckFormatString(
6800 Sema &S, const FormatStringLiteral *FExpr,
6801 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
6802 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
6803 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
6804 bool inFunctionCall, VariadicCallType CallType,
6805 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
6806 bool IgnoreStringsWithoutSpecifiers);
6807
6808static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
6809 const Expr *E);
6810
6811// Determine if an expression is a string literal or constant string.
6812// If this function returns false on the arguments to a function expecting a
6813// format string, we will usually need to emit a warning.
6814// True string literals are then checked by CheckFormatString.
6815static StringLiteralCheckType
6816checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
6817 const Expr *E, ArrayRef<const Expr *> Args,
6818 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
6819 unsigned firstDataArg, FormatStringType Type,
6820 VariadicCallType CallType, bool InFunctionCall,
6821 llvm::SmallBitVector &CheckedVarArgs,
6822 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
6823 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
6824 bool IgnoreStringsWithoutSpecifiers = false) {
6825 if (S.isConstantEvaluatedContext())
6826 return SLCT_NotALiteral;
6827tryAgain:
6828 assert(Offset.isSigned() && "invalid offset");
6829
6830 if (E->isTypeDependent() || E->isValueDependent())
6831 return SLCT_NotALiteral;
6832
6833 E = E->IgnoreParenCasts();
6834
6835 if (E->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull))
6836 // Technically -Wformat-nonliteral does not warn about this case.
6837 // The behavior of printf and friends in this case is implementation
6838 // dependent. Ideally if the format string cannot be null then
6839 // it should have a 'nonnull' attribute in the function prototype.
6840 return SLCT_UncheckedLiteral;
6841
6842 switch (E->getStmtClass()) {
6843 case Stmt::InitListExprClass:
6844 // Handle expressions like {"foobar"}.
6845 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E)) {
6846 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
6847 format_idx, firstDataArg, Type, CallType,
6848 /*InFunctionCall*/ false, CheckedVarArgs,
6849 UncoveredArg, Offset, CallerFormatParamIdx,
6850 IgnoreStringsWithoutSpecifiers);
6851 }
6852 return SLCT_NotALiteral;
6853 case Stmt::BinaryConditionalOperatorClass:
6854 case Stmt::ConditionalOperatorClass: {
6855 // The expression is a literal if both sub-expressions were, and it was
6856 // completely checked only if both sub-expressions were checked.
6857 const AbstractConditionalOperator *C =
6858 cast<AbstractConditionalOperator>(Val: E);
6859
6860 // Determine whether it is necessary to check both sub-expressions, for
6861 // example, because the condition expression is a constant that can be
6862 // evaluated at compile time.
6863 bool CheckLeft = true, CheckRight = true;
6864
6865 bool Cond;
6866 if (C->getCond()->EvaluateAsBooleanCondition(
6867 Result&: Cond, Ctx: S.getASTContext(), InConstantContext: S.isConstantEvaluatedContext())) {
6868 if (Cond)
6869 CheckRight = false;
6870 else
6871 CheckLeft = false;
6872 }
6873
6874 // We need to maintain the offsets for the right and the left hand side
6875 // separately to check if every possible indexed expression is a valid
6876 // string literal. They might have different offsets for different string
6877 // literals in the end.
6878 StringLiteralCheckType Left;
6879 if (!CheckLeft)
6880 Left = SLCT_UncheckedLiteral;
6881 else {
6882 Left = checkFormatStringExpr(S, ReferenceFormatString, E: C->getTrueExpr(),
6883 Args, APK, format_idx, firstDataArg, Type,
6884 CallType, InFunctionCall, CheckedVarArgs,
6885 UncoveredArg, Offset, CallerFormatParamIdx,
6886 IgnoreStringsWithoutSpecifiers);
6887 if (Left == SLCT_NotALiteral || !CheckRight) {
6888 return Left;
6889 }
6890 }
6891
6892 StringLiteralCheckType Right = checkFormatStringExpr(
6893 S, ReferenceFormatString, E: C->getFalseExpr(), Args, APK, format_idx,
6894 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
6895 UncoveredArg, Offset, CallerFormatParamIdx,
6896 IgnoreStringsWithoutSpecifiers);
6897
6898 return (CheckLeft && Left < Right) ? Left : Right;
6899 }
6900
6901 case Stmt::ImplicitCastExprClass:
6902 E = cast<ImplicitCastExpr>(Val: E)->getSubExpr();
6903 goto tryAgain;
6904
6905 case Stmt::OpaqueValueExprClass:
6906 if (const Expr *src = cast<OpaqueValueExpr>(Val: E)->getSourceExpr()) {
6907 E = src;
6908 goto tryAgain;
6909 }
6910 return SLCT_NotALiteral;
6911
6912 case Stmt::PredefinedExprClass:
6913 // While __func__, etc., are technically not string literals, they
6914 // cannot contain format specifiers and thus are not a security
6915 // liability.
6916 return SLCT_UncheckedLiteral;
6917
6918 case Stmt::DeclRefExprClass: {
6919 const DeclRefExpr *DR = cast<DeclRefExpr>(Val: E);
6920
6921 // As an exception, do not flag errors for variables binding to
6922 // const string literals.
6923 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: DR->getDecl())) {
6924 bool isConstant = false;
6925 QualType T = DR->getType();
6926
6927 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6928 isConstant = AT->getElementType().isConstant(Ctx: S.Context);
6929 } else if (const PointerType *PT = T->getAs<PointerType>()) {
6930 isConstant = T.isConstant(Ctx: S.Context) &&
6931 PT->getPointeeType().isConstant(Ctx: S.Context);
6932 } else if (T->isObjCObjectPointerType()) {
6933 // In ObjC, there is usually no "const ObjectPointer" type,
6934 // so don't check if the pointee type is constant.
6935 isConstant = T.isConstant(Ctx: S.Context);
6936 }
6937
6938 if (isConstant) {
6939 if (const Expr *Init = VD->getAnyInitializer()) {
6940 // Look through initializers like const char c[] = { "foo" }
6941 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
6942 if (InitList->isStringLiteralInit())
6943 Init = InitList->getInit(Init: 0)->IgnoreParenImpCasts();
6944 }
6945 return checkFormatStringExpr(
6946 S, ReferenceFormatString, E: Init, Args, APK, format_idx,
6947 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
6948 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
6949 }
6950 }
6951
6952 // When the format argument is an argument of this function, and this
6953 // function also has the format attribute, there are several interactions
6954 // for which there shouldn't be a warning. For instance, when calling
6955 // v*printf from a function that has the printf format attribute, we
6956 // should not emit a warning about using `fmt`, even though it's not
6957 // constant, because the arguments have already been checked for the
6958 // caller of `logmessage`:
6959 //
6960 // __attribute__((format(printf, 1, 2)))
6961 // void logmessage(char const *fmt, ...) {
6962 // va_list ap;
6963 // va_start(ap, fmt);
6964 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
6965 // ...
6966 // }
6967 //
6968 // Another interaction that we need to support is using a format string
6969 // specified by the format_matches attribute:
6970 //
6971 // __attribute__((format_matches(printf, 1, "%s %d")))
6972 // void logmessage(char const *fmt, const char *a, int b) {
6973 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
6974 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
6975 // ...
6976 // }
6977 //
6978 // Yet another interaction that we need to support is calling a variadic
6979 // format function from a format function that has fixed arguments. For
6980 // instance:
6981 //
6982 // __attribute__((format(printf, 1, 2)))
6983 // void logstring(char const *fmt, char const *str) {
6984 // printf(fmt, str); /* do not emit a warning about "fmt" */
6985 // }
6986 //
6987 // Same (and perhaps more relatably) for the variadic template case:
6988 //
6989 // template<typename... Args>
6990 // __attribute__((format(printf, 1, 2)))
6991 // void log(const char *fmt, Args&&... args) {
6992 // printf(fmt, forward<Args>(args)...);
6993 // /* do not emit a warning about "fmt" */
6994 // }
6995 //
6996 // Due to implementation difficulty, we only check the format, not the
6997 // format arguments, in all cases.
6998 //
6999 if (const auto *PV = dyn_cast<ParmVarDecl>(Val: VD)) {
7000 if (CallerFormatParamIdx)
7001 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7002 if (const auto *D = dyn_cast<Decl>(Val: PV->getDeclContext())) {
7003 for (const auto *PVFormatMatches :
7004 D->specific_attrs<FormatMatchesAttr>()) {
7005 Sema::FormatStringInfo CalleeFSI;
7006 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormatMatches->getFormatIdx(),
7007 FirstArg: 0, FSI: &CalleeFSI))
7008 continue;
7009 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7010 // If using the wrong type of format string, emit a diagnostic
7011 // here and stop checking to avoid irrelevant diagnostics.
7012 if (Type != S.GetFormatStringType(Format: PVFormatMatches)) {
7013 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7014 DiagID: diag::warn_format_string_type_incompatible)
7015 << PVFormatMatches->getType()->getName()
7016 << S.GetFormatStringTypeName(FST: Type);
7017 if (!InFunctionCall) {
7018 S.Diag(Loc: PVFormatMatches->getFormatString()->getBeginLoc(),
7019 DiagID: diag::note_format_string_defined);
7020 }
7021 return SLCT_UncheckedLiteral;
7022 }
7023 return checkFormatStringExpr(
7024 S, ReferenceFormatString, E: PVFormatMatches->getFormatString(),
7025 Args, APK, format_idx, firstDataArg, Type, CallType,
7026 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7027 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7028 }
7029 }
7030
7031 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7032 Sema::FormatStringInfo CallerFSI;
7033 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormat->getFormatIdx(),
7034 FirstArg: PVFormat->getFirstArg(), FSI: &CallerFSI))
7035 continue;
7036 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7037 // We also check if the formats are compatible.
7038 // We can't pass a 'scanf' string to a 'printf' function.
7039 if (Type != S.GetFormatStringType(Format: PVFormat)) {
7040 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7041 DiagID: diag::warn_format_string_type_incompatible)
7042 << PVFormat->getType()->getName()
7043 << S.GetFormatStringTypeName(FST: Type);
7044 if (!InFunctionCall) {
7045 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_format_string_defined);
7046 }
7047 return SLCT_UncheckedLiteral;
7048 }
7049 // Lastly, check that argument passing kinds transition in a
7050 // way that makes sense:
7051 // from a caller with FAPK_VAList, allow FAPK_VAList
7052 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7053 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7054 // from a caller with FAPK_Variadic, allow FAPK_VAList
7055 switch (combineFAPK(A: CallerFSI.ArgPassingKind, B: APK)) {
7056 case combineFAPK(A: Sema::FAPK_VAList, B: Sema::FAPK_VAList):
7057 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Fixed):
7058 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Variadic):
7059 case combineFAPK(A: Sema::FAPK_Variadic, B: Sema::FAPK_VAList):
7060 return SLCT_UncheckedLiteral;
7061 }
7062 }
7063 }
7064 }
7065 }
7066 }
7067
7068 return SLCT_NotALiteral;
7069 }
7070
7071 case Stmt::CallExprClass:
7072 case Stmt::CXXMemberCallExprClass: {
7073 const CallExpr *CE = cast<CallExpr>(Val: E);
7074 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Val: CE->getCalleeDecl())) {
7075 bool IsFirst = true;
7076 StringLiteralCheckType CommonResult;
7077 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7078 const Expr *Arg = CE->getArg(Arg: FA->getFormatIdx().getASTIndex());
7079 StringLiteralCheckType Result = checkFormatStringExpr(
7080 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7081 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7082 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7083 if (IsFirst) {
7084 CommonResult = Result;
7085 IsFirst = false;
7086 }
7087 }
7088 if (!IsFirst)
7089 return CommonResult;
7090
7091 if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) {
7092 unsigned BuiltinID = FD->getBuiltinID();
7093 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7094 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7095 const Expr *Arg = CE->getArg(Arg: 0);
7096 return checkFormatStringExpr(
7097 S, ReferenceFormatString, E: Arg, Args, APK, format_idx,
7098 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7099 UncoveredArg, Offset, CallerFormatParamIdx,
7100 IgnoreStringsWithoutSpecifiers);
7101 }
7102 }
7103 }
7104 if (const Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E))
7105 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7106 format_idx, firstDataArg, Type, CallType,
7107 /*InFunctionCall*/ false, CheckedVarArgs,
7108 UncoveredArg, Offset, CallerFormatParamIdx,
7109 IgnoreStringsWithoutSpecifiers);
7110 return SLCT_NotALiteral;
7111 }
7112 case Stmt::ObjCMessageExprClass: {
7113 const auto *ME = cast<ObjCMessageExpr>(Val: E);
7114 if (const auto *MD = ME->getMethodDecl()) {
7115 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7116 // As a special case heuristic, if we're using the method -[NSBundle
7117 // localizedStringForKey:value:table:], ignore any key strings that lack
7118 // format specifiers. The idea is that if the key doesn't have any
7119 // format specifiers then its probably just a key to map to the
7120 // localized strings. If it does have format specifiers though, then its
7121 // likely that the text of the key is the format string in the
7122 // programmer's language, and should be checked.
7123 const ObjCInterfaceDecl *IFace;
7124 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7125 IFace->getIdentifier()->isStr(Str: "NSBundle") &&
7126 MD->getSelector().isKeywordSelector(
7127 Names: {"localizedStringForKey", "value", "table"})) {
7128 IgnoreStringsWithoutSpecifiers = true;
7129 }
7130
7131 const Expr *Arg = ME->getArg(Arg: FA->getFormatIdx().getASTIndex());
7132 return checkFormatStringExpr(
7133 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7134 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7135 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7136 }
7137 }
7138
7139 return SLCT_NotALiteral;
7140 }
7141 case Stmt::ObjCStringLiteralClass:
7142 case Stmt::StringLiteralClass: {
7143 const StringLiteral *StrE = nullptr;
7144
7145 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(Val: E))
7146 StrE = ObjCFExpr->getString();
7147 else
7148 StrE = cast<StringLiteral>(Val: E);
7149
7150 if (StrE) {
7151 if (Offset.isNegative() || Offset > StrE->getLength()) {
7152 // TODO: It would be better to have an explicit warning for out of
7153 // bounds literals.
7154 return SLCT_NotALiteral;
7155 }
7156 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(width: 64).getSExtValue());
7157 CheckFormatString(S, FExpr: &FStr, ReferenceFormatString, OrigFormatExpr: E, Args, APK,
7158 format_idx, firstDataArg, Type, inFunctionCall: InFunctionCall,
7159 CallType, CheckedVarArgs, UncoveredArg,
7160 IgnoreStringsWithoutSpecifiers);
7161 return SLCT_CheckedLiteral;
7162 }
7163
7164 return SLCT_NotALiteral;
7165 }
7166 case Stmt::BinaryOperatorClass: {
7167 const BinaryOperator *BinOp = cast<BinaryOperator>(Val: E);
7168
7169 // A string literal + an int offset is still a string literal.
7170 if (BinOp->isAdditiveOp()) {
7171 Expr::EvalResult LResult, RResult;
7172
7173 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7174 Result&: LResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7175 InConstantContext: S.isConstantEvaluatedContext());
7176 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7177 Result&: RResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7178 InConstantContext: S.isConstantEvaluatedContext());
7179
7180 if (LIsInt != RIsInt) {
7181 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7182
7183 if (LIsInt) {
7184 if (BinOpKind == BO_Add) {
7185 sumOffsets(Offset, Addend: LResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7186 E = BinOp->getRHS();
7187 goto tryAgain;
7188 }
7189 } else {
7190 sumOffsets(Offset, Addend: RResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7191 E = BinOp->getLHS();
7192 goto tryAgain;
7193 }
7194 }
7195 }
7196
7197 return SLCT_NotALiteral;
7198 }
7199 case Stmt::UnaryOperatorClass: {
7200 const UnaryOperator *UnaOp = cast<UnaryOperator>(Val: E);
7201 auto ASE = dyn_cast<ArraySubscriptExpr>(Val: UnaOp->getSubExpr());
7202 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7203 Expr::EvalResult IndexResult;
7204 if (ASE->getRHS()->EvaluateAsInt(Result&: IndexResult, Ctx: S.Context,
7205 AllowSideEffects: Expr::SE_NoSideEffects,
7206 InConstantContext: S.isConstantEvaluatedContext())) {
7207 sumOffsets(Offset, Addend: IndexResult.Val.getInt(), BinOpKind: BO_Add,
7208 /*RHS is int*/ AddendIsRight: true);
7209 E = ASE->getBase();
7210 goto tryAgain;
7211 }
7212 }
7213
7214 return SLCT_NotALiteral;
7215 }
7216
7217 default:
7218 return SLCT_NotALiteral;
7219 }
7220}
7221
7222// If this expression can be evaluated at compile-time,
7223// check if the result is a StringLiteral and return it
7224// otherwise return nullptr
7225static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7226 const Expr *E) {
7227 Expr::EvalResult Result;
7228 if (E->EvaluateAsRValue(Result, Ctx: Context) && Result.Val.isLValue()) {
7229 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7230 if (isa_and_nonnull<StringLiteral>(Val: LVE))
7231 return LVE;
7232 }
7233 return nullptr;
7234}
7235
7236StringRef Sema::GetFormatStringTypeName(FormatStringType FST) {
7237 switch (FST) {
7238 case FormatStringType::Scanf:
7239 return "scanf";
7240 case FormatStringType::Printf:
7241 return "printf";
7242 case FormatStringType::NSString:
7243 return "NSString";
7244 case FormatStringType::Strftime:
7245 return "strftime";
7246 case FormatStringType::Strfmon:
7247 return "strfmon";
7248 case FormatStringType::Kprintf:
7249 return "kprintf";
7250 case FormatStringType::FreeBSDKPrintf:
7251 return "freebsd_kprintf";
7252 case FormatStringType::OSLog:
7253 return "os_log";
7254 default:
7255 return "<unknown>";
7256 }
7257}
7258
7259FormatStringType Sema::GetFormatStringType(StringRef Flavor) {
7260 return llvm::StringSwitch<FormatStringType>(Flavor)
7261 .Cases(CaseStrings: {"gnu_scanf", "scanf"}, Value: FormatStringType::Scanf)
7262 .Cases(CaseStrings: {"gnu_printf", "printf", "printf0", "syslog"},
7263 Value: FormatStringType::Printf)
7264 .Cases(CaseStrings: {"NSString", "CFString"}, Value: FormatStringType::NSString)
7265 .Cases(CaseStrings: {"gnu_strftime", "strftime"}, Value: FormatStringType::Strftime)
7266 .Cases(CaseStrings: {"gnu_strfmon", "strfmon"}, Value: FormatStringType::Strfmon)
7267 .Cases(CaseStrings: {"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7268 Value: FormatStringType::Kprintf)
7269 .Case(S: "freebsd_kprintf", Value: FormatStringType::FreeBSDKPrintf)
7270 .Case(S: "os_trace", Value: FormatStringType::OSLog)
7271 .Case(S: "os_log", Value: FormatStringType::OSLog)
7272 .Default(Value: FormatStringType::Unknown);
7273}
7274
7275FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7276 return GetFormatStringType(Flavor: Format->getType()->getName());
7277}
7278
7279FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7280 return GetFormatStringType(Flavor: Format->getType()->getName());
7281}
7282
7283bool Sema::CheckFormatArguments(const FormatAttr *Format,
7284 ArrayRef<const Expr *> Args, bool IsCXXMember,
7285 VariadicCallType CallType, SourceLocation Loc,
7286 SourceRange Range,
7287 llvm::SmallBitVector &CheckedVarArgs) {
7288 FormatStringInfo FSI;
7289 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: Format->getFirstArg(),
7290 HasImplicitThisParam: IsCXXMember,
7291 IsVariadic: CallType != VariadicCallType::DoesNotApply, FSI: &FSI))
7292 return CheckFormatArguments(
7293 Args, FAPK: FSI.ArgPassingKind, ReferenceFormatString: nullptr, format_idx: FSI.FormatIdx, firstDataArg: FSI.FirstDataArg,
7294 Type: GetFormatStringType(Format), CallType, Loc, range: Range, CheckedVarArgs);
7295 return false;
7296}
7297
7298bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7299 ArrayRef<const Expr *> Args, bool IsCXXMember,
7300 VariadicCallType CallType, SourceLocation Loc,
7301 SourceRange Range,
7302 llvm::SmallBitVector &CheckedVarArgs) {
7303 FormatStringInfo FSI;
7304 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: 0, HasImplicitThisParam: IsCXXMember, IsVariadic: false,
7305 FSI: &FSI)) {
7306 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7307 return CheckFormatArguments(Args, FAPK: FSI.ArgPassingKind,
7308 ReferenceFormatString: Format->getFormatString(), format_idx: FSI.FormatIdx,
7309 firstDataArg: FSI.FirstDataArg, Type: GetFormatStringType(Format),
7310 CallType, Loc, range: Range, CheckedVarArgs);
7311 }
7312 return false;
7313}
7314
7315static bool CheckMissingFormatAttribute(
7316 Sema *S, ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
7317 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7318 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7319 SourceLocation Loc) {
7320 if (S->getDiagnostics().isIgnored(DiagID: diag::warn_missing_format_attribute, Loc))
7321 return false;
7322
7323 DeclContext *DC = S->CurContext;
7324 if (!isa<ObjCMethodDecl>(Val: DC) && !isa<FunctionDecl>(Val: DC) && !isa<BlockDecl>(Val: DC))
7325 return false;
7326 Decl *Caller = cast<Decl>(Val: DC)->getCanonicalDecl();
7327
7328 unsigned NumCallerParams = getFunctionOrMethodNumParams(D: Caller);
7329
7330 // Find the offset to convert between attribute and parameter indexes.
7331 unsigned CallerArgumentIndexOffset =
7332 hasImplicitObjectParameter(D: Caller) ? 2 : 1;
7333
7334 unsigned FirstArgumentIndex = -1;
7335 switch (APK) {
7336 case Sema::FormatArgumentPassingKind::FAPK_Fixed:
7337 case Sema::FormatArgumentPassingKind::FAPK_Variadic: {
7338 // As an extension, clang allows the format attribute on non-variadic
7339 // functions.
7340 // Caller must have fixed arguments to pass them to a fixed or variadic
7341 // function. Try to match caller and callee arguments. If successful, then
7342 // emit a diag with the caller idx, otherwise we can't determine the callee
7343 // arguments.
7344 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7345 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7346 // There aren't enough arguments in the caller to pass to callee.
7347 return false;
7348 }
7349 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7350 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7351 const auto *Arg =
7352 dyn_cast<DeclRefExpr>(Val: Args[CalleeIdx]->IgnoreParenCasts());
7353 if (!Arg)
7354 return false;
7355 const auto *Param = dyn_cast<ParmVarDecl>(Val: Arg->getDecl());
7356 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7357 return false;
7358 }
7359 FirstArgumentIndex =
7360 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7361 break;
7362 }
7363 case Sema::FormatArgumentPassingKind::FAPK_VAList:
7364 // Caller arguments are either variadic or a va_list.
7365 FirstArgumentIndex = isFunctionOrMethodVariadic(D: Caller)
7366 ? (NumCallerParams + CallerArgumentIndexOffset)
7367 : 0;
7368 break;
7369 case Sema::FormatArgumentPassingKind::FAPK_Elsewhere:
7370 // The callee has a format_matches attribute. We will emit that instead.
7371 if (!ReferenceFormatString)
7372 return false;
7373 break;
7374 }
7375
7376 // Emit the diagnostic and fixit.
7377 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7378 StringRef FormatTypeName = S->GetFormatStringTypeName(FST: FormatType);
7379 NamedDecl *ND = dyn_cast<NamedDecl>(Val: Caller);
7380 do {
7381 std::string Attr, Fixit;
7382 llvm::raw_string_ostream AttrOS(Attr);
7383 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
7384 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7385 << FirstArgumentIndex << ")";
7386 } else {
7387 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7388 << ", \"";
7389 AttrOS.write_escaped(Str: ReferenceFormatString->getString());
7390 AttrOS << "\")";
7391 }
7392 AttrOS.flush();
7393 auto DB = S->Diag(Loc, DiagID: diag::warn_missing_format_attribute) << Attr;
7394 if (ND)
7395 DB << ND;
7396 else
7397 DB << "block";
7398
7399 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7400 if (isa<BlockDecl>(Val: Caller))
7401 break;
7402
7403 SourceLocation SL;
7404 llvm::raw_string_ostream IS(Fixit);
7405 // The attribute goes at the start of the declaration in C/C++ functions
7406 // and methods, but after the declaration for Objective-C methods.
7407 if (isa<ObjCMethodDecl>(Val: Caller)) {
7408 IS << ' ';
7409 SL = Caller->getEndLoc();
7410 }
7411 const LangOptions &LO = S->getLangOpts();
7412 if (LO.C23 || LO.CPlusPlus11)
7413 IS << "[[gnu::" << Attr << "]]";
7414 else if (LO.ObjC || LO.GNUMode)
7415 IS << "__attribute__((" << Attr << "))";
7416 else
7417 break;
7418 if (!isa<ObjCMethodDecl>(Val: Caller)) {
7419 IS << ' ';
7420 SL = Caller->getBeginLoc();
7421 }
7422 IS.flush();
7423
7424 DB << FixItHint::CreateInsertion(InsertionLoc: SL, Code: Fixit);
7425 } while (false);
7426
7427 // Add implicit format or format_matches attribute.
7428 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
7429 Caller->addAttr(A: FormatAttr::CreateImplicit(
7430 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
7431 FormatIdx: FormatStringIndex, FirstArg: FirstArgumentIndex));
7432 } else {
7433 Caller->addAttr(A: FormatMatchesAttr::CreateImplicit(
7434 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
7435 FormatIdx: FormatStringIndex, ExpectedFormat: ReferenceFormatString));
7436 }
7437
7438 {
7439 auto DB = S->Diag(Loc: Caller->getLocation(), DiagID: diag::note_entity_declared_at);
7440 if (ND)
7441 DB << ND;
7442 else
7443 DB << "block";
7444 }
7445 return true;
7446}
7447
7448bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7449 Sema::FormatArgumentPassingKind APK,
7450 StringLiteral *ReferenceFormatString,
7451 unsigned format_idx, unsigned firstDataArg,
7452 FormatStringType Type,
7453 VariadicCallType CallType, SourceLocation Loc,
7454 SourceRange Range,
7455 llvm::SmallBitVector &CheckedVarArgs) {
7456 // CHECK: printf/scanf-like function is called with no format string.
7457 if (format_idx >= Args.size()) {
7458 Diag(Loc, DiagID: diag::warn_missing_format_string) << Range;
7459 return false;
7460 }
7461
7462 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7463
7464 // CHECK: format string is not a string literal.
7465 //
7466 // Dynamically generated format strings are difficult to
7467 // automatically vet at compile time. Requiring that format strings
7468 // are string literals: (1) permits the checking of format strings by
7469 // the compiler and thereby (2) can practically remove the source of
7470 // many format string exploits.
7471
7472 // Format string can be either ObjC string (e.g. @"%d") or
7473 // C string (e.g. "%d")
7474 // ObjC string uses the same format specifiers as C string, so we can use
7475 // the same format string checking logic for both ObjC and C strings.
7476 UncoveredArgHandler UncoveredArg;
7477 std::optional<unsigned> CallerParamIdx;
7478 StringLiteralCheckType CT = checkFormatStringExpr(
7479 S&: *this, ReferenceFormatString, E: OrigFormatExpr, Args, APK, format_idx,
7480 firstDataArg, Type, CallType,
7481 /*IsFunctionCall*/ InFunctionCall: true, CheckedVarArgs, UncoveredArg,
7482 /*no string offset*/ Offset: llvm::APSInt(64, false) = 0, CallerFormatParamIdx: &CallerParamIdx);
7483
7484 // Generate a diagnostic where an uncovered argument is detected.
7485 if (UncoveredArg.hasUncoveredArg()) {
7486 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7487 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7488 UncoveredArg.Diagnose(S&: *this, /*IsFunctionCall*/true, ArgExpr: Args[ArgIdx]);
7489 }
7490
7491 if (CT != SLCT_NotALiteral)
7492 // Literal format string found, check done!
7493 return CT == SLCT_CheckedLiteral;
7494
7495 // Do not emit diag when the string param is a macro expansion and the
7496 // format is either NSString or CFString. This is a hack to prevent
7497 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7498 // which are usually used in place of NS and CF string literals.
7499 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7500 if (Type == FormatStringType::NSString &&
7501 SourceMgr.isInSystemMacro(loc: FormatLoc))
7502 return false;
7503
7504 if (CallerParamIdx && CheckMissingFormatAttribute(
7505 S: this, Args, APK, ReferenceFormatString, FormatIdx: format_idx,
7506 FirstDataArg: firstDataArg, FormatType: Type, CallerParamIdx: *CallerParamIdx, Loc))
7507 return false;
7508
7509 // Strftime is particular as it always uses a single 'time' argument,
7510 // so it is safe to pass a non-literal string.
7511 if (Type == FormatStringType::Strftime)
7512 return false;
7513
7514 // If there are no arguments specified, warn with -Wformat-security, otherwise
7515 // warn only with -Wformat-nonliteral.
7516 if (Args.size() == firstDataArg) {
7517 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral_noargs)
7518 << OrigFormatExpr->getSourceRange();
7519 switch (Type) {
7520 default:
7521 break;
7522 case FormatStringType::Kprintf:
7523 case FormatStringType::FreeBSDKPrintf:
7524 case FormatStringType::Printf:
7525 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
7526 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "\"%s\", ");
7527 break;
7528 case FormatStringType::NSString:
7529 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
7530 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "@\"%@\", ");
7531 break;
7532 }
7533 } else {
7534 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral)
7535 << OrigFormatExpr->getSourceRange();
7536 }
7537 return false;
7538}
7539
7540namespace {
7541
7542class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7543protected:
7544 Sema &S;
7545 const FormatStringLiteral *FExpr;
7546 const Expr *OrigFormatExpr;
7547 const FormatStringType FSType;
7548 const unsigned FirstDataArg;
7549 const unsigned NumDataArgs;
7550 const char *Beg; // Start of format string.
7551 const Sema::FormatArgumentPassingKind ArgPassingKind;
7552 ArrayRef<const Expr *> Args;
7553 unsigned FormatIdx;
7554 llvm::SmallBitVector CoveredArgs;
7555 bool usesPositionalArgs = false;
7556 bool atFirstArg = true;
7557 bool inFunctionCall;
7558 VariadicCallType CallType;
7559 llvm::SmallBitVector &CheckedVarArgs;
7560 UncoveredArgHandler &UncoveredArg;
7561
7562public:
7563 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7564 const Expr *origFormatExpr, const FormatStringType type,
7565 unsigned firstDataArg, unsigned numDataArgs,
7566 const char *beg, Sema::FormatArgumentPassingKind APK,
7567 ArrayRef<const Expr *> Args, unsigned formatIdx,
7568 bool inFunctionCall, VariadicCallType callType,
7569 llvm::SmallBitVector &CheckedVarArgs,
7570 UncoveredArgHandler &UncoveredArg)
7571 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7572 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7573 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
7574 inFunctionCall(inFunctionCall), CallType(callType),
7575 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7576 CoveredArgs.resize(N: numDataArgs);
7577 CoveredArgs.reset();
7578 }
7579
7580 bool HasFormatArguments() const {
7581 return ArgPassingKind == Sema::FAPK_Fixed ||
7582 ArgPassingKind == Sema::FAPK_Variadic;
7583 }
7584
7585 void DoneProcessing();
7586
7587 void HandleIncompleteSpecifier(const char *startSpecifier,
7588 unsigned specifierLen) override;
7589
7590 void HandleInvalidLengthModifier(
7591 const analyze_format_string::FormatSpecifier &FS,
7592 const analyze_format_string::ConversionSpecifier &CS,
7593 const char *startSpecifier, unsigned specifierLen,
7594 unsigned DiagID);
7595
7596 void HandleNonStandardLengthModifier(
7597 const analyze_format_string::FormatSpecifier &FS,
7598 const char *startSpecifier, unsigned specifierLen);
7599
7600 void HandleNonStandardConversionSpecifier(
7601 const analyze_format_string::ConversionSpecifier &CS,
7602 const char *startSpecifier, unsigned specifierLen);
7603
7604 void HandlePosition(const char *startPos, unsigned posLen) override;
7605
7606 void HandleInvalidPosition(const char *startSpecifier,
7607 unsigned specifierLen,
7608 analyze_format_string::PositionContext p) override;
7609
7610 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7611
7612 void HandleNullChar(const char *nullCharacter) override;
7613
7614 template <typename Range>
7615 static void
7616 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7617 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7618 bool IsStringLocation, Range StringRange,
7619 ArrayRef<FixItHint> Fixit = {});
7620
7621protected:
7622 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7623 const char *startSpec,
7624 unsigned specifierLen,
7625 const char *csStart, unsigned csLen);
7626
7627 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7628 const char *startSpec,
7629 unsigned specifierLen);
7630
7631 SourceRange getFormatStringRange();
7632 CharSourceRange getSpecifierRange(const char *startSpecifier,
7633 unsigned specifierLen);
7634 SourceLocation getLocationOfByte(const char *x);
7635
7636 const Expr *getDataArg(unsigned i) const;
7637
7638 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7639 const analyze_format_string::ConversionSpecifier &CS,
7640 const char *startSpecifier, unsigned specifierLen,
7641 unsigned argIndex);
7642
7643 template <typename Range>
7644 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7645 bool IsStringLocation, Range StringRange,
7646 ArrayRef<FixItHint> Fixit = {});
7647};
7648
7649} // namespace
7650
7651SourceRange CheckFormatHandler::getFormatStringRange() {
7652 return OrigFormatExpr->getSourceRange();
7653}
7654
7655CharSourceRange CheckFormatHandler::
7656getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7657 SourceLocation Start = getLocationOfByte(x: startSpecifier);
7658 SourceLocation End = getLocationOfByte(x: startSpecifier + specifierLen - 1);
7659
7660 // Advance the end SourceLocation by one due to half-open ranges.
7661 End = End.getLocWithOffset(Offset: 1);
7662
7663 return CharSourceRange::getCharRange(B: Start, E: End);
7664}
7665
7666SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7667 return FExpr->getLocationOfByte(ByteNo: x - Beg, SM: S.getSourceManager(),
7668 Features: S.getLangOpts(), Target: S.Context.getTargetInfo());
7669}
7670
7671void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7672 unsigned specifierLen){
7673 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_incomplete_specifier),
7674 Loc: getLocationOfByte(x: startSpecifier),
7675 /*IsStringLocation*/true,
7676 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7677}
7678
7679void CheckFormatHandler::HandleInvalidLengthModifier(
7680 const analyze_format_string::FormatSpecifier &FS,
7681 const analyze_format_string::ConversionSpecifier &CS,
7682 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7683 using namespace analyze_format_string;
7684
7685 const LengthModifier &LM = FS.getLengthModifier();
7686 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
7687
7688 // See if we know how to fix this length modifier.
7689 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7690 if (FixedLM) {
7691 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
7692 Loc: getLocationOfByte(x: LM.getStart()),
7693 /*IsStringLocation*/true,
7694 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7695
7696 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
7697 << FixedLM->toString()
7698 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
7699
7700 } else {
7701 FixItHint Hint;
7702 if (DiagID == diag::warn_format_nonsensical_length)
7703 Hint = FixItHint::CreateRemoval(RemoveRange: LMRange);
7704
7705 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
7706 Loc: getLocationOfByte(x: LM.getStart()),
7707 /*IsStringLocation*/true,
7708 StringRange: getSpecifierRange(startSpecifier, specifierLen),
7709 FixIt: Hint);
7710 }
7711}
7712
7713void CheckFormatHandler::HandleNonStandardLengthModifier(
7714 const analyze_format_string::FormatSpecifier &FS,
7715 const char *startSpecifier, unsigned specifierLen) {
7716 using namespace analyze_format_string;
7717
7718 const LengthModifier &LM = FS.getLengthModifier();
7719 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
7720
7721 // See if we know how to fix this length modifier.
7722 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7723 if (FixedLM) {
7724 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7725 << LM.toString() << 0,
7726 Loc: getLocationOfByte(x: LM.getStart()),
7727 /*IsStringLocation*/true,
7728 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7729
7730 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
7731 << FixedLM->toString()
7732 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
7733
7734 } else {
7735 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7736 << LM.toString() << 0,
7737 Loc: getLocationOfByte(x: LM.getStart()),
7738 /*IsStringLocation*/true,
7739 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7740 }
7741}
7742
7743void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7744 const analyze_format_string::ConversionSpecifier &CS,
7745 const char *startSpecifier, unsigned specifierLen) {
7746 using namespace analyze_format_string;
7747
7748 // See if we know how to fix this conversion specifier.
7749 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7750 if (FixedCS) {
7751 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7752 << CS.toString() << /*conversion specifier*/1,
7753 Loc: getLocationOfByte(x: CS.getStart()),
7754 /*IsStringLocation*/true,
7755 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7756
7757 CharSourceRange CSRange = getSpecifierRange(startSpecifier: CS.getStart(), specifierLen: CS.getLength());
7758 S.Diag(Loc: getLocationOfByte(x: CS.getStart()), DiagID: diag::note_format_fix_specifier)
7759 << FixedCS->toString()
7760 << FixItHint::CreateReplacement(RemoveRange: CSRange, Code: FixedCS->toString());
7761 } else {
7762 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
7763 << CS.toString() << /*conversion specifier*/1,
7764 Loc: getLocationOfByte(x: CS.getStart()),
7765 /*IsStringLocation*/true,
7766 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7767 }
7768}
7769
7770void CheckFormatHandler::HandlePosition(const char *startPos,
7771 unsigned posLen) {
7772 if (!S.getDiagnostics().isIgnored(
7773 DiagID: diag::warn_format_non_standard_positional_arg, Loc: SourceLocation()))
7774 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard_positional_arg),
7775 Loc: getLocationOfByte(x: startPos),
7776 /*IsStringLocation*/ true,
7777 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
7778}
7779
7780void CheckFormatHandler::HandleInvalidPosition(
7781 const char *startSpecifier, unsigned specifierLen,
7782 analyze_format_string::PositionContext p) {
7783 if (!S.getDiagnostics().isIgnored(
7784 DiagID: diag::warn_format_invalid_positional_specifier, Loc: SourceLocation()))
7785 EmitFormatDiagnostic(
7786 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_positional_specifier) << (unsigned)p,
7787 Loc: getLocationOfByte(x: startSpecifier), /*IsStringLocation*/ true,
7788 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7789}
7790
7791void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7792 unsigned posLen) {
7793 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_format_zero_positional_specifier,
7794 Loc: SourceLocation()))
7795 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_zero_positional_specifier),
7796 Loc: getLocationOfByte(x: startPos),
7797 /*IsStringLocation*/ true,
7798 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
7799}
7800
7801void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7802 if (!isa<ObjCStringLiteral>(Val: OrigFormatExpr)) {
7803 // The presence of a null character is likely an error.
7804 EmitFormatDiagnostic(
7805 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_contains_null_char),
7806 Loc: getLocationOfByte(x: nullCharacter), /*IsStringLocation*/true,
7807 StringRange: getFormatStringRange());
7808 }
7809}
7810
7811// Note that this may return NULL if there was an error parsing or building
7812// one of the argument expressions.
7813const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7814 return Args[FirstDataArg + i];
7815}
7816
7817void CheckFormatHandler::DoneProcessing() {
7818 // Does the number of data arguments exceed the number of
7819 // format conversions in the format string?
7820 if (HasFormatArguments()) {
7821 // Find any arguments that weren't covered.
7822 CoveredArgs.flip();
7823 signed notCoveredArg = CoveredArgs.find_first();
7824 if (notCoveredArg >= 0) {
7825 assert((unsigned)notCoveredArg < NumDataArgs);
7826 UncoveredArg.Update(NewFirstUncoveredArg: notCoveredArg, StrExpr: OrigFormatExpr);
7827 } else {
7828 UncoveredArg.setAllCovered();
7829 }
7830 }
7831}
7832
7833void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7834 const Expr *ArgExpr) {
7835 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
7836 "Invalid state");
7837
7838 if (!ArgExpr)
7839 return;
7840
7841 SourceLocation Loc = ArgExpr->getBeginLoc();
7842
7843 if (S.getSourceManager().isInSystemMacro(loc: Loc))
7844 return;
7845
7846 PartialDiagnostic PDiag = S.PDiag(DiagID: diag::warn_printf_data_arg_not_used);
7847 for (auto E : DiagnosticExprs)
7848 PDiag << E->getSourceRange();
7849
7850 CheckFormatHandler::EmitFormatDiagnostic(
7851 S, InFunctionCall: IsFunctionCall, ArgumentExpr: DiagnosticExprs[0],
7852 PDiag, Loc, /*IsStringLocation*/false,
7853 StringRange: DiagnosticExprs[0]->getSourceRange());
7854}
7855
7856bool
7857CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7858 SourceLocation Loc,
7859 const char *startSpec,
7860 unsigned specifierLen,
7861 const char *csStart,
7862 unsigned csLen) {
7863 bool keepGoing = true;
7864 if (argIndex < NumDataArgs) {
7865 // Consider the argument coverered, even though the specifier doesn't
7866 // make sense.
7867 CoveredArgs.set(argIndex);
7868 }
7869 else {
7870 // If argIndex exceeds the number of data arguments we
7871 // don't issue a warning because that is just a cascade of warnings (and
7872 // they may have intended '%%' anyway). We don't want to continue processing
7873 // the format string after this point, however, as we will like just get
7874 // gibberish when trying to match arguments.
7875 keepGoing = false;
7876 }
7877
7878 StringRef Specifier(csStart, csLen);
7879
7880 // If the specifier in non-printable, it could be the first byte of a UTF-8
7881 // sequence. In that case, print the UTF-8 code point. If not, print the byte
7882 // hex value.
7883 std::string CodePointStr;
7884 if (!llvm::sys::locale::isPrint(c: *csStart)) {
7885 llvm::UTF32 CodePoint;
7886 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7887 const llvm::UTF8 *E =
7888 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7889 llvm::ConversionResult Result =
7890 llvm::convertUTF8Sequence(source: B, sourceEnd: E, target: &CodePoint, flags: llvm::strictConversion);
7891
7892 if (Result != llvm::conversionOK) {
7893 unsigned char FirstChar = *csStart;
7894 CodePoint = (llvm::UTF32)FirstChar;
7895 }
7896
7897 llvm::raw_string_ostream OS(CodePointStr);
7898 if (CodePoint < 256)
7899 OS << "\\x" << llvm::format(Fmt: "%02x", Vals: CodePoint);
7900 else if (CodePoint <= 0xFFFF)
7901 OS << "\\u" << llvm::format(Fmt: "%04x", Vals: CodePoint);
7902 else
7903 OS << "\\U" << llvm::format(Fmt: "%08x", Vals: CodePoint);
7904 Specifier = CodePointStr;
7905 }
7906
7907 EmitFormatDiagnostic(
7908 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_conversion) << Specifier, Loc,
7909 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
7910
7911 return keepGoing;
7912}
7913
7914void
7915CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7916 const char *startSpec,
7917 unsigned specifierLen) {
7918 EmitFormatDiagnostic(
7919 PDiag: S.PDiag(DiagID: diag::warn_format_mix_positional_nonpositional_args),
7920 Loc, /*isStringLoc*/IsStringLocation: true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
7921}
7922
7923bool
7924CheckFormatHandler::CheckNumArgs(
7925 const analyze_format_string::FormatSpecifier &FS,
7926 const analyze_format_string::ConversionSpecifier &CS,
7927 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7928
7929 if (HasFormatArguments() && argIndex >= NumDataArgs) {
7930 PartialDiagnostic PDiag = FS.usesPositionalArg()
7931 ? (S.PDiag(DiagID: diag::warn_printf_positional_arg_exceeds_data_args)
7932 << (argIndex+1) << NumDataArgs)
7933 : S.PDiag(DiagID: diag::warn_printf_insufficient_data_args);
7934 EmitFormatDiagnostic(
7935 PDiag, Loc: getLocationOfByte(x: CS.getStart()), /*IsStringLocation*/true,
7936 StringRange: getSpecifierRange(startSpecifier, specifierLen));
7937
7938 // Since more arguments than conversion tokens are given, by extension
7939 // all arguments are covered, so mark this as so.
7940 UncoveredArg.setAllCovered();
7941 return false;
7942 }
7943 return true;
7944}
7945
7946template<typename Range>
7947void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7948 SourceLocation Loc,
7949 bool IsStringLocation,
7950 Range StringRange,
7951 ArrayRef<FixItHint> FixIt) {
7952 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7953 Loc, IsStringLocation, StringRange, FixIt);
7954}
7955
7956/// If the format string is not within the function call, emit a note
7957/// so that the function call and string are in diagnostic messages.
7958///
7959/// \param InFunctionCall if true, the format string is within the function
7960/// call and only one diagnostic message will be produced. Otherwise, an
7961/// extra note will be emitted pointing to location of the format string.
7962///
7963/// \param ArgumentExpr the expression that is passed as the format string
7964/// argument in the function call. Used for getting locations when two
7965/// diagnostics are emitted.
7966///
7967/// \param PDiag the callee should already have provided any strings for the
7968/// diagnostic message. This function only adds locations and fixits
7969/// to diagnostics.
7970///
7971/// \param Loc primary location for diagnostic. If two diagnostics are
7972/// required, one will be at Loc and a new SourceLocation will be created for
7973/// the other one.
7974///
7975/// \param IsStringLocation if true, Loc points to the format string should be
7976/// used for the note. Otherwise, Loc points to the argument list and will
7977/// be used with PDiag.
7978///
7979/// \param StringRange some or all of the string to highlight. This is
7980/// templated so it can accept either a CharSourceRange or a SourceRange.
7981///
7982/// \param FixIt optional fix it hint for the format string.
7983template <typename Range>
7984void CheckFormatHandler::EmitFormatDiagnostic(
7985 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7986 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7987 Range StringRange, ArrayRef<FixItHint> FixIt) {
7988 if (InFunctionCall) {
7989 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PD: PDiag);
7990 D << StringRange;
7991 D << FixIt;
7992 } else {
7993 S.Diag(Loc: IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PD: PDiag)
7994 << ArgumentExpr->getSourceRange();
7995
7996 const Sema::SemaDiagnosticBuilder &Note =
7997 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7998 diag::note_format_string_defined);
7999
8000 Note << StringRange;
8001 Note << FixIt;
8002 }
8003}
8004
8005//===--- CHECK: Printf format string checking -----------------------------===//
8006
8007namespace {
8008
8009class CheckPrintfHandler : public CheckFormatHandler {
8010public:
8011 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8012 const Expr *origFormatExpr, const FormatStringType type,
8013 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8014 const char *beg, Sema::FormatArgumentPassingKind APK,
8015 ArrayRef<const Expr *> Args, unsigned formatIdx,
8016 bool inFunctionCall, VariadicCallType CallType,
8017 llvm::SmallBitVector &CheckedVarArgs,
8018 UncoveredArgHandler &UncoveredArg)
8019 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8020 numDataArgs, beg, APK, Args, formatIdx,
8021 inFunctionCall, CallType, CheckedVarArgs,
8022 UncoveredArg) {}
8023
8024 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8025
8026 /// Returns true if '%@' specifiers are allowed in the format string.
8027 bool allowsObjCArg() const {
8028 return FSType == FormatStringType::NSString ||
8029 FSType == FormatStringType::OSLog ||
8030 FSType == FormatStringType::OSTrace;
8031 }
8032
8033 bool HandleInvalidPrintfConversionSpecifier(
8034 const analyze_printf::PrintfSpecifier &FS,
8035 const char *startSpecifier,
8036 unsigned specifierLen) override;
8037
8038 void handleInvalidMaskType(StringRef MaskType) override;
8039
8040 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8041 const char *startSpecifier, unsigned specifierLen,
8042 const TargetInfo &Target) override;
8043 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8044 const char *StartSpecifier,
8045 unsigned SpecifierLen,
8046 const Expr *E);
8047
8048 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8049 const char *startSpecifier, unsigned specifierLen);
8050 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8051 const analyze_printf::OptionalAmount &Amt,
8052 unsigned type,
8053 const char *startSpecifier, unsigned specifierLen);
8054 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8055 const analyze_printf::OptionalFlag &flag,
8056 const char *startSpecifier, unsigned specifierLen);
8057 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8058 const analyze_printf::OptionalFlag &ignoredFlag,
8059 const analyze_printf::OptionalFlag &flag,
8060 const char *startSpecifier, unsigned specifierLen);
8061 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8062 const Expr *E);
8063
8064 void HandleEmptyObjCModifierFlag(const char *startFlag,
8065 unsigned flagLen) override;
8066
8067 void HandleInvalidObjCModifierFlag(const char *startFlag,
8068 unsigned flagLen) override;
8069
8070 void
8071 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8072 const char *flagsEnd,
8073 const char *conversionPosition) override;
8074};
8075
8076/// Keeps around the information needed to verify that two specifiers are
8077/// compatible.
8078class EquatableFormatArgument {
8079public:
8080 enum SpecifierSensitivity : unsigned {
8081 SS_None,
8082 SS_Private,
8083 SS_Public,
8084 SS_Sensitive
8085 };
8086
8087 enum FormatArgumentRole : unsigned {
8088 FAR_Data,
8089 FAR_FieldWidth,
8090 FAR_Precision,
8091 FAR_Auxiliary, // FreeBSD kernel %b and %D
8092 };
8093
8094private:
8095 analyze_format_string::ArgType ArgType;
8096 analyze_format_string::LengthModifier::Kind LengthMod;
8097 StringRef SpecifierLetter;
8098 CharSourceRange Range;
8099 SourceLocation ElementLoc;
8100 FormatArgumentRole Role : 2;
8101 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8102 unsigned Position : 14;
8103 unsigned ModifierFor : 14; // not set for FAR_Data
8104
8105 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8106 bool InFunctionCall) const;
8107
8108public:
8109 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8110 analyze_format_string::LengthModifier::Kind LengthMod,
8111 StringRef SpecifierLetter,
8112 analyze_format_string::ArgType ArgType,
8113 FormatArgumentRole Role,
8114 SpecifierSensitivity Sensitivity, unsigned Position,
8115 unsigned ModifierFor)
8116 : ArgType(ArgType), LengthMod(LengthMod),
8117 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8118 Role(Role), Sensitivity(Sensitivity), Position(Position),
8119 ModifierFor(ModifierFor) {}
8120
8121 unsigned getPosition() const { return Position; }
8122 SourceLocation getSourceLocation() const { return ElementLoc; }
8123 CharSourceRange getSourceRange() const { return Range; }
8124 analyze_format_string::LengthModifier getLengthModifier() const {
8125 return analyze_format_string::LengthModifier(nullptr, LengthMod);
8126 }
8127 void setModifierFor(unsigned V) { ModifierFor = V; }
8128
8129 std::string buildFormatSpecifier() const {
8130 std::string result;
8131 llvm::raw_string_ostream(result)
8132 << getLengthModifier().toString() << SpecifierLetter;
8133 return result;
8134 }
8135
8136 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8137 const Expr *FmtExpr, bool InFunctionCall) const;
8138};
8139
8140/// Turns format strings into lists of EquatableSpecifier objects.
8141class DecomposePrintfHandler : public CheckPrintfHandler {
8142 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8143 bool HadError;
8144
8145 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8146 const Expr *origFormatExpr,
8147 const FormatStringType type, unsigned firstDataArg,
8148 unsigned numDataArgs, bool isObjC, const char *beg,
8149 Sema::FormatArgumentPassingKind APK,
8150 ArrayRef<const Expr *> Args, unsigned formatIdx,
8151 bool inFunctionCall, VariadicCallType CallType,
8152 llvm::SmallBitVector &CheckedVarArgs,
8153 UncoveredArgHandler &UncoveredArg,
8154 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8155 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8156 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8157 inFunctionCall, CallType, CheckedVarArgs,
8158 UncoveredArg),
8159 Specs(Specs), HadError(false) {}
8160
8161public:
8162 static bool
8163 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8164 FormatStringType type, bool IsObjC, bool InFunctionCall,
8165 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8166
8167 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8168 const char *startSpecifier,
8169 unsigned specifierLen,
8170 const TargetInfo &Target) override;
8171};
8172
8173} // namespace
8174
8175bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8176 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8177 unsigned specifierLen) {
8178 const analyze_printf::PrintfConversionSpecifier &CS =
8179 FS.getConversionSpecifier();
8180
8181 return HandleInvalidConversionSpecifier(argIndex: FS.getArgIndex(),
8182 Loc: getLocationOfByte(x: CS.getStart()),
8183 startSpec: startSpecifier, specifierLen,
8184 csStart: CS.getStart(), csLen: CS.getLength());
8185}
8186
8187void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8188 S.Diag(Loc: getLocationOfByte(x: MaskType.data()), DiagID: diag::err_invalid_mask_type_size);
8189}
8190
8191// Error out if struct or complex type argments are passed to os_log.
8192static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType,
8193 QualType T) {
8194 if (FSType != FormatStringType::OSLog)
8195 return false;
8196 return T->isRecordType() || T->isComplexType();
8197}
8198
8199bool CheckPrintfHandler::HandleAmount(
8200 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8201 const char *startSpecifier, unsigned specifierLen) {
8202 if (Amt.hasDataArgument()) {
8203 if (HasFormatArguments()) {
8204 unsigned argIndex = Amt.getArgIndex();
8205 if (argIndex >= NumDataArgs) {
8206 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_asterisk_missing_arg)
8207 << k,
8208 Loc: getLocationOfByte(x: Amt.getStart()),
8209 /*IsStringLocation*/ true,
8210 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8211 // Don't do any more checking. We will just emit
8212 // spurious errors.
8213 return false;
8214 }
8215
8216 // Type check the data argument. It should be an 'int'.
8217 // Although not in conformance with C99, we also allow the argument to be
8218 // an 'unsigned int' as that is a reasonably safe case. GCC also
8219 // doesn't emit a warning for that case.
8220 CoveredArgs.set(argIndex);
8221 const Expr *Arg = getDataArg(i: argIndex);
8222 if (!Arg)
8223 return false;
8224
8225 QualType T = Arg->getType();
8226
8227 const analyze_printf::ArgType &AT = Amt.getArgType(Ctx&: S.Context);
8228 assert(AT.isValid());
8229
8230 if (!AT.matchesType(C&: S.Context, argTy: T)) {
8231 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8232 ? diag::err_printf_asterisk_wrong_type
8233 : diag::warn_printf_asterisk_wrong_type;
8234 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID)
8235 << k << AT.getRepresentativeTypeName(C&: S.Context)
8236 << T << Arg->getSourceRange(),
8237 Loc: getLocationOfByte(x: Amt.getStart()),
8238 /*IsStringLocation*/ true,
8239 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8240 // Don't do any more checking. We will just emit
8241 // spurious errors.
8242 return false;
8243 }
8244 }
8245 }
8246 return true;
8247}
8248
8249void CheckPrintfHandler::HandleInvalidAmount(
8250 const analyze_printf::PrintfSpecifier &FS,
8251 const analyze_printf::OptionalAmount &Amt,
8252 unsigned type,
8253 const char *startSpecifier,
8254 unsigned specifierLen) {
8255 const analyze_printf::PrintfConversionSpecifier &CS =
8256 FS.getConversionSpecifier();
8257
8258 FixItHint fixit =
8259 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8260 ? FixItHint::CreateRemoval(RemoveRange: getSpecifierRange(startSpecifier: Amt.getStart(),
8261 specifierLen: Amt.getConstantLength()))
8262 : FixItHint();
8263
8264 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_optional_amount)
8265 << type << CS.toString(),
8266 Loc: getLocationOfByte(x: Amt.getStart()),
8267 /*IsStringLocation*/true,
8268 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8269 FixIt: fixit);
8270}
8271
8272void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8273 const analyze_printf::OptionalFlag &flag,
8274 const char *startSpecifier,
8275 unsigned specifierLen) {
8276 // Warn about pointless flag with a fixit removal.
8277 const analyze_printf::PrintfConversionSpecifier &CS =
8278 FS.getConversionSpecifier();
8279 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_flag)
8280 << flag.toString() << CS.toString(),
8281 Loc: getLocationOfByte(x: flag.getPosition()),
8282 /*IsStringLocation*/true,
8283 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8284 FixIt: FixItHint::CreateRemoval(
8285 RemoveRange: getSpecifierRange(startSpecifier: flag.getPosition(), specifierLen: 1)));
8286}
8287
8288void CheckPrintfHandler::HandleIgnoredFlag(
8289 const analyze_printf::PrintfSpecifier &FS,
8290 const analyze_printf::OptionalFlag &ignoredFlag,
8291 const analyze_printf::OptionalFlag &flag,
8292 const char *startSpecifier,
8293 unsigned specifierLen) {
8294 // Warn about ignored flag with a fixit removal.
8295 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_ignored_flag)
8296 << ignoredFlag.toString() << flag.toString(),
8297 Loc: getLocationOfByte(x: ignoredFlag.getPosition()),
8298 /*IsStringLocation*/true,
8299 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8300 FixIt: FixItHint::CreateRemoval(
8301 RemoveRange: getSpecifierRange(startSpecifier: ignoredFlag.getPosition(), specifierLen: 1)));
8302}
8303
8304void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8305 unsigned flagLen) {
8306 // Warn about an empty flag.
8307 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_empty_objc_flag),
8308 Loc: getLocationOfByte(x: startFlag),
8309 /*IsStringLocation*/true,
8310 StringRange: getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen));
8311}
8312
8313void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8314 unsigned flagLen) {
8315 // Warn about an invalid flag.
8316 auto Range = getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen);
8317 StringRef flag(startFlag, flagLen);
8318 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_invalid_objc_flag) << flag,
8319 Loc: getLocationOfByte(x: startFlag),
8320 /*IsStringLocation*/true,
8321 StringRange: Range, FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8322}
8323
8324void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8325 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8326 // Warn about using '[...]' without a '@' conversion.
8327 auto Range = getSpecifierRange(startSpecifier: flagsStart, specifierLen: flagsEnd - flagsStart + 1);
8328 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8329 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag) << StringRef(conversionPosition, 1),
8330 Loc: getLocationOfByte(x: conversionPosition),
8331 /*IsStringLocation*/ true, StringRange: Range,
8332 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8333}
8334
8335void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8336 const Expr *FmtExpr,
8337 bool InFunctionCall) const {
8338 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, ArgumentExpr: FmtExpr, PDiag,
8339 Loc: ElementLoc, IsStringLocation: true, StringRange: Range);
8340}
8341
8342bool EquatableFormatArgument::VerifyCompatible(
8343 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8344 bool InFunctionCall) const {
8345 using MK = analyze_format_string::ArgType::MatchKind;
8346 if (Role != Other.Role) {
8347 // diagnose and stop
8348 EmitDiagnostic(
8349 S, PDiag: S.PDiag(DiagID: diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8350 FmtExpr, InFunctionCall);
8351 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8352 return false;
8353 }
8354
8355 if (Role != FAR_Data) {
8356 if (ModifierFor != Other.ModifierFor) {
8357 // diagnose and stop
8358 EmitDiagnostic(S,
8359 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_modifierfor_mismatch)
8360 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8361 FmtExpr, InFunctionCall);
8362 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8363 return false;
8364 }
8365 return true;
8366 }
8367
8368 bool HadError = false;
8369 if (Sensitivity != Other.Sensitivity) {
8370 // diagnose and continue
8371 EmitDiagnostic(S,
8372 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_sensitivity_mismatch)
8373 << Sensitivity << Other.Sensitivity,
8374 FmtExpr, InFunctionCall);
8375 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8376 << 0 << Other.Range;
8377 }
8378
8379 switch (ArgType.matchesArgType(C&: S.Context, other: Other.ArgType)) {
8380 case MK::Match:
8381 break;
8382
8383 case MK::MatchPromotion:
8384 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8385 // MatchPromotion is treated as a failure by format_matches.
8386 case MK::NoMatch:
8387 case MK::NoMatchTypeConfusion:
8388 case MK::NoMatchPromotionTypeConfusion:
8389 EmitDiagnostic(S,
8390 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch)
8391 << buildFormatSpecifier()
8392 << Other.buildFormatSpecifier(),
8393 FmtExpr, InFunctionCall);
8394 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8395 << 0 << Other.Range;
8396 break;
8397
8398 case MK::NoMatchPedantic:
8399 EmitDiagnostic(S,
8400 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch_pedantic)
8401 << buildFormatSpecifier()
8402 << Other.buildFormatSpecifier(),
8403 FmtExpr, InFunctionCall);
8404 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8405 << 0 << Other.Range;
8406 break;
8407
8408 case MK::NoMatchSignedness:
8409 EmitDiagnostic(S,
8410 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_sign_mismatch)
8411 << buildFormatSpecifier()
8412 << Other.buildFormatSpecifier(),
8413 FmtExpr, InFunctionCall);
8414 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8415 << 0 << Other.Range;
8416 break;
8417 }
8418 return !HadError;
8419}
8420
8421bool DecomposePrintfHandler::GetSpecifiers(
8422 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8423 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8424 llvm::SmallVectorImpl<EquatableFormatArgument> &Args) {
8425 StringRef Data = FSL->getString();
8426 const char *Str = Data.data();
8427 llvm::SmallBitVector BV;
8428 UncoveredArgHandler UA;
8429 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8430 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8431 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8432 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8433 UA, Args);
8434
8435 if (!analyze_format_string::ParsePrintfString(
8436 H, beg: Str, end: Str + Data.size(), LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
8437 isFreeBSDKPrintf: Type == FormatStringType::FreeBSDKPrintf))
8438 H.DoneProcessing();
8439 if (H.HadError)
8440 return false;
8441
8442 llvm::stable_sort(Range&: Args, C: [](const EquatableFormatArgument &A,
8443 const EquatableFormatArgument &B) {
8444 return A.getPosition() < B.getPosition();
8445 });
8446 return true;
8447}
8448
8449bool DecomposePrintfHandler::HandlePrintfSpecifier(
8450 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8451 unsigned specifierLen, const TargetInfo &Target) {
8452 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8453 specifierLen, Target)) {
8454 HadError = true;
8455 return false;
8456 }
8457
8458 // Do not add any specifiers to the list for %%. This is possibly incorrect
8459 // if using a precision/width with a data argument, but that combination is
8460 // meaningless and we wouldn't know which format to attach the
8461 // precision/width to.
8462 const auto &CS = FS.getConversionSpecifier();
8463 if (CS.getKind() == analyze_format_string::ConversionSpecifier::PercentArg)
8464 return true;
8465
8466 // have to patch these to have the right ModifierFor if they are used
8467 const unsigned Unset = ~0;
8468 unsigned FieldWidthIndex = Unset;
8469 unsigned PrecisionIndex = Unset;
8470
8471 // field width?
8472 const auto &FieldWidth = FS.getFieldWidth();
8473 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8474 FieldWidthIndex = Specs.size();
8475 Specs.emplace_back(Args: getSpecifierRange(startSpecifier, specifierLen),
8476 Args: getLocationOfByte(x: FieldWidth.getStart()),
8477 Args: analyze_format_string::LengthModifier::None, Args: "*",
8478 Args: FieldWidth.getArgType(Ctx&: S.Context),
8479 Args: EquatableFormatArgument::FAR_FieldWidth,
8480 Args: EquatableFormatArgument::SS_None,
8481 Args: FieldWidth.usesPositionalArg()
8482 ? FieldWidth.getPositionalArgIndex() - 1
8483 : FieldWidthIndex,
8484 Args: 0);
8485 }
8486 // precision?
8487 const auto &Precision = FS.getPrecision();
8488 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8489 PrecisionIndex = Specs.size();
8490 Specs.emplace_back(
8491 Args: getSpecifierRange(startSpecifier, specifierLen),
8492 Args: getLocationOfByte(x: Precision.getStart()),
8493 Args: analyze_format_string::LengthModifier::None, Args: ".*",
8494 Args: Precision.getArgType(Ctx&: S.Context), Args: EquatableFormatArgument::FAR_Precision,
8495 Args: EquatableFormatArgument::SS_None,
8496 Args: Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8497 : PrecisionIndex,
8498 Args: 0);
8499 }
8500
8501 // this specifier
8502 unsigned SpecIndex =
8503 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8504 if (FieldWidthIndex != Unset)
8505 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8506 if (PrecisionIndex != Unset)
8507 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8508
8509 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8510 if (FS.isPrivate())
8511 Sensitivity = EquatableFormatArgument::SS_Private;
8512 else if (FS.isPublic())
8513 Sensitivity = EquatableFormatArgument::SS_Public;
8514 else if (FS.isSensitive())
8515 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8516 else
8517 Sensitivity = EquatableFormatArgument::SS_None;
8518
8519 Specs.emplace_back(
8520 Args: getSpecifierRange(startSpecifier, specifierLen),
8521 Args: getLocationOfByte(x: CS.getStart()), Args: FS.getLengthModifier().getKind(),
8522 Args: CS.getCharacters(), Args: FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext()),
8523 Args: EquatableFormatArgument::FAR_Data, Args&: Sensitivity, Args&: SpecIndex, Args: 0);
8524
8525 // auxiliary argument?
8526 if (CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDbArg ||
8527 CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDDArg) {
8528 Specs.emplace_back(Args: getSpecifierRange(startSpecifier, specifierLen),
8529 Args: getLocationOfByte(x: CS.getStart()),
8530 Args: analyze_format_string::LengthModifier::None,
8531 Args: CS.getCharacters(),
8532 Args: analyze_format_string::ArgType::CStrTy,
8533 Args: EquatableFormatArgument::FAR_Auxiliary, Args&: Sensitivity,
8534 Args: SpecIndex + 1, Args&: SpecIndex);
8535 }
8536 return true;
8537}
8538
8539// Determines if the specified is a C++ class or struct containing
8540// a member with the specified name and kind (e.g. a CXXMethodDecl named
8541// "c_str()").
8542template<typename MemberKind>
8543static llvm::SmallPtrSet<MemberKind*, 1>
8544CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8545 auto *RD = Ty->getAsCXXRecordDecl();
8546 llvm::SmallPtrSet<MemberKind*, 1> Results;
8547
8548 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8549 return Results;
8550
8551 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8552 Sema::LookupMemberName);
8553 R.suppressDiagnostics();
8554
8555 // We just need to include all members of the right kind turned up by the
8556 // filter, at this point.
8557 if (S.LookupQualifiedName(R, LookupCtx: RD))
8558 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8559 NamedDecl *decl = (*I)->getUnderlyingDecl();
8560 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8561 Results.insert(FK);
8562 }
8563 return Results;
8564}
8565
8566/// Check if we could call '.c_str()' on an object.
8567///
8568/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8569/// allow the call, or if it would be ambiguous).
8570bool Sema::hasCStrMethod(const Expr *E) {
8571 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8572
8573 MethodSet Results =
8574 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S&: *this, Ty: E->getType());
8575 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8576 MI != ME; ++MI)
8577 if ((*MI)->getMinRequiredArguments() == 0)
8578 return true;
8579 return false;
8580}
8581
8582// Check if a (w)string was passed when a (w)char* was needed, and offer a
8583// better diagnostic if so. AT is assumed to be valid.
8584// Returns true when a c_str() conversion method is found.
8585bool CheckPrintfHandler::checkForCStrMembers(
8586 const analyze_printf::ArgType &AT, const Expr *E) {
8587 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8588
8589 MethodSet Results =
8590 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S, Ty: E->getType());
8591
8592 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8593 MI != ME; ++MI) {
8594 const CXXMethodDecl *Method = *MI;
8595 if (Method->getMinRequiredArguments() == 0 &&
8596 AT.matchesType(C&: S.Context, argTy: Method->getReturnType())) {
8597 // FIXME: Suggest parens if the expression needs them.
8598 SourceLocation EndLoc = S.getLocForEndOfToken(Loc: E->getEndLoc());
8599 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_printf_c_str)
8600 << "c_str()" << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ".c_str()");
8601 return true;
8602 }
8603 }
8604
8605 return false;
8606}
8607
8608bool CheckPrintfHandler::HandlePrintfSpecifier(
8609 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8610 unsigned specifierLen, const TargetInfo &Target) {
8611 using namespace analyze_format_string;
8612 using namespace analyze_printf;
8613
8614 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8615
8616 if (FS.consumesDataArgument()) {
8617 if (atFirstArg) {
8618 atFirstArg = false;
8619 usesPositionalArgs = FS.usesPositionalArg();
8620 }
8621 else if (usesPositionalArgs != FS.usesPositionalArg()) {
8622 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
8623 startSpec: startSpecifier, specifierLen);
8624 return false;
8625 }
8626 }
8627
8628 // First check if the field width, precision, and conversion specifier
8629 // have matching data arguments.
8630 if (!HandleAmount(Amt: FS.getFieldWidth(), /* field width */ k: 0,
8631 startSpecifier, specifierLen)) {
8632 return false;
8633 }
8634
8635 if (!HandleAmount(Amt: FS.getPrecision(), /* precision */ k: 1,
8636 startSpecifier, specifierLen)) {
8637 return false;
8638 }
8639
8640 if (!CS.consumesDataArgument()) {
8641 // FIXME: Technically specifying a precision or field width here
8642 // makes no sense. Worth issuing a warning at some point.
8643 return true;
8644 }
8645
8646 // Consume the argument.
8647 unsigned argIndex = FS.getArgIndex();
8648 if (argIndex < NumDataArgs) {
8649 // The check to see if the argIndex is valid will come later.
8650 // We set the bit here because we may exit early from this
8651 // function if we encounter some other error.
8652 CoveredArgs.set(argIndex);
8653 }
8654
8655 // FreeBSD kernel extensions.
8656 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8657 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8658 // We need at least two arguments.
8659 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex: argIndex + 1))
8660 return false;
8661
8662 if (HasFormatArguments()) {
8663 // Claim the second argument.
8664 CoveredArgs.set(argIndex + 1);
8665
8666 // Type check the first argument (int for %b, pointer for %D)
8667 const Expr *Ex = getDataArg(i: argIndex);
8668 const analyze_printf::ArgType &AT =
8669 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
8670 ? ArgType(S.Context.IntTy)
8671 : ArgType::CPointerTy;
8672 if (AT.isValid() && !AT.matchesType(C&: S.Context, argTy: Ex->getType()))
8673 EmitFormatDiagnostic(
8674 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
8675 << AT.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
8676 << false << Ex->getSourceRange(),
8677 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
8678 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8679
8680 // Type check the second argument (char * for both %b and %D)
8681 Ex = getDataArg(i: argIndex + 1);
8682 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8683 if (AT2.isValid() && !AT2.matchesType(C&: S.Context, argTy: Ex->getType()))
8684 EmitFormatDiagnostic(
8685 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
8686 << AT2.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
8687 << false << Ex->getSourceRange(),
8688 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
8689 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8690 }
8691 return true;
8692 }
8693
8694 // Check for using an Objective-C specific conversion specifier
8695 // in a non-ObjC literal.
8696 if (!allowsObjCArg() && CS.isObjCArg()) {
8697 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8698 specifierLen);
8699 }
8700
8701 // %P can only be used with os_log.
8702 if (FSType != FormatStringType::OSLog &&
8703 CS.getKind() == ConversionSpecifier::PArg) {
8704 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8705 specifierLen);
8706 }
8707
8708 // %n is not allowed with os_log.
8709 if (FSType == FormatStringType::OSLog &&
8710 CS.getKind() == ConversionSpecifier::nArg) {
8711 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_os_log_format_narg),
8712 Loc: getLocationOfByte(x: CS.getStart()),
8713 /*IsStringLocation*/ false,
8714 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8715
8716 return true;
8717 }
8718
8719 // Only scalars are allowed for os_trace.
8720 if (FSType == FormatStringType::OSTrace &&
8721 (CS.getKind() == ConversionSpecifier::PArg ||
8722 CS.getKind() == ConversionSpecifier::sArg ||
8723 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8724 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8725 specifierLen);
8726 }
8727
8728 // Check for use of public/private annotation outside of os_log().
8729 if (FSType != FormatStringType::OSLog) {
8730 if (FS.isPublic().isSet()) {
8731 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
8732 << "public",
8733 Loc: getLocationOfByte(x: FS.isPublic().getPosition()),
8734 /*IsStringLocation*/ false,
8735 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8736 }
8737 if (FS.isPrivate().isSet()) {
8738 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
8739 << "private",
8740 Loc: getLocationOfByte(x: FS.isPrivate().getPosition()),
8741 /*IsStringLocation*/ false,
8742 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8743 }
8744 }
8745
8746 const llvm::Triple &Triple = Target.getTriple();
8747 if (CS.getKind() == ConversionSpecifier::nArg &&
8748 (Triple.isAndroid() || Triple.isOSFuchsia())) {
8749 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_narg_not_supported),
8750 Loc: getLocationOfByte(x: CS.getStart()),
8751 /*IsStringLocation*/ false,
8752 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8753 }
8754
8755 // Check for invalid use of field width
8756 if (!FS.hasValidFieldWidth()) {
8757 HandleInvalidAmount(FS, Amt: FS.getFieldWidth(), /* field width */ type: 0,
8758 startSpecifier, specifierLen);
8759 }
8760
8761 // Check for invalid use of precision
8762 if (!FS.hasValidPrecision()) {
8763 HandleInvalidAmount(FS, Amt: FS.getPrecision(), /* precision */ type: 1,
8764 startSpecifier, specifierLen);
8765 }
8766
8767 // Precision is mandatory for %P specifier.
8768 if (CS.getKind() == ConversionSpecifier::PArg &&
8769 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8770 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_no_precision),
8771 Loc: getLocationOfByte(x: startSpecifier),
8772 /*IsStringLocation*/ false,
8773 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8774 }
8775
8776 // Check each flag does not conflict with any other component.
8777 if (!FS.hasValidThousandsGroupingPrefix())
8778 HandleFlag(FS, flag: FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8779 if (!FS.hasValidLeadingZeros())
8780 HandleFlag(FS, flag: FS.hasLeadingZeros(), startSpecifier, specifierLen);
8781 if (!FS.hasValidPlusPrefix())
8782 HandleFlag(FS, flag: FS.hasPlusPrefix(), startSpecifier, specifierLen);
8783 if (!FS.hasValidSpacePrefix())
8784 HandleFlag(FS, flag: FS.hasSpacePrefix(), startSpecifier, specifierLen);
8785 if (!FS.hasValidAlternativeForm())
8786 HandleFlag(FS, flag: FS.hasAlternativeForm(), startSpecifier, specifierLen);
8787 if (!FS.hasValidLeftJustified())
8788 HandleFlag(FS, flag: FS.isLeftJustified(), startSpecifier, specifierLen);
8789
8790 // Check that flags are not ignored by another flag
8791 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8792 HandleIgnoredFlag(FS, ignoredFlag: FS.hasSpacePrefix(), flag: FS.hasPlusPrefix(),
8793 startSpecifier, specifierLen);
8794 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8795 HandleIgnoredFlag(FS, ignoredFlag: FS.hasLeadingZeros(), flag: FS.isLeftJustified(),
8796 startSpecifier, specifierLen);
8797
8798 // Check the length modifier is valid with the given conversion specifier.
8799 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
8800 LO: S.getLangOpts()))
8801 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8802 DiagID: diag::warn_format_nonsensical_length);
8803 else if (!FS.hasStandardLengthModifier())
8804 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8805 else if (!FS.hasStandardLengthConversionCombination())
8806 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8807 DiagID: diag::warn_format_non_standard_conversion_spec);
8808
8809 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
8810 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8811
8812 // The remaining checks depend on the data arguments.
8813 if (!HasFormatArguments())
8814 return true;
8815
8816 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8817 return false;
8818
8819 const Expr *Arg = getDataArg(i: argIndex);
8820 if (!Arg)
8821 return true;
8822
8823 return checkFormatExpr(FS, StartSpecifier: startSpecifier, SpecifierLen: specifierLen, E: Arg);
8824}
8825
8826static bool requiresParensToAddCast(const Expr *E) {
8827 // FIXME: We should have a general way to reason about operator
8828 // precedence and whether parens are actually needed here.
8829 // Take care of a few common cases where they aren't.
8830 const Expr *Inside = E->IgnoreImpCasts();
8831 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: Inside))
8832 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8833
8834 switch (Inside->getStmtClass()) {
8835 case Stmt::ArraySubscriptExprClass:
8836 case Stmt::CallExprClass:
8837 case Stmt::CharacterLiteralClass:
8838 case Stmt::CXXBoolLiteralExprClass:
8839 case Stmt::DeclRefExprClass:
8840 case Stmt::FloatingLiteralClass:
8841 case Stmt::IntegerLiteralClass:
8842 case Stmt::MemberExprClass:
8843 case Stmt::ObjCArrayLiteralClass:
8844 case Stmt::ObjCBoolLiteralExprClass:
8845 case Stmt::ObjCBoxedExprClass:
8846 case Stmt::ObjCDictionaryLiteralClass:
8847 case Stmt::ObjCEncodeExprClass:
8848 case Stmt::ObjCIvarRefExprClass:
8849 case Stmt::ObjCMessageExprClass:
8850 case Stmt::ObjCPropertyRefExprClass:
8851 case Stmt::ObjCStringLiteralClass:
8852 case Stmt::ObjCSubscriptRefExprClass:
8853 case Stmt::ParenExprClass:
8854 case Stmt::StringLiteralClass:
8855 case Stmt::UnaryOperatorClass:
8856 return false;
8857 default:
8858 return true;
8859 }
8860}
8861
8862static std::pair<QualType, StringRef>
8863shouldNotPrintDirectly(const ASTContext &Context,
8864 QualType IntendedTy,
8865 const Expr *E) {
8866 // Use a 'while' to peel off layers of typedefs.
8867 QualType TyTy = IntendedTy;
8868 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8869 StringRef Name = UserTy->getDecl()->getName();
8870 QualType CastTy = llvm::StringSwitch<QualType>(Name)
8871 .Case(S: "CFIndex", Value: Context.getNSIntegerType())
8872 .Case(S: "NSInteger", Value: Context.getNSIntegerType())
8873 .Case(S: "NSUInteger", Value: Context.getNSUIntegerType())
8874 .Case(S: "SInt32", Value: Context.IntTy)
8875 .Case(S: "UInt32", Value: Context.UnsignedIntTy)
8876 .Default(Value: QualType());
8877
8878 if (!CastTy.isNull())
8879 return std::make_pair(x&: CastTy, y&: Name);
8880
8881 TyTy = UserTy->desugar();
8882 }
8883
8884 // Strip parens if necessary.
8885 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Val: E))
8886 return shouldNotPrintDirectly(Context,
8887 IntendedTy: PE->getSubExpr()->getType(),
8888 E: PE->getSubExpr());
8889
8890 // If this is a conditional expression, then its result type is constructed
8891 // via usual arithmetic conversions and thus there might be no necessary
8892 // typedef sugar there. Recurse to operands to check for NSInteger &
8893 // Co. usage condition.
8894 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
8895 QualType TrueTy, FalseTy;
8896 StringRef TrueName, FalseName;
8897
8898 std::tie(args&: TrueTy, args&: TrueName) =
8899 shouldNotPrintDirectly(Context,
8900 IntendedTy: CO->getTrueExpr()->getType(),
8901 E: CO->getTrueExpr());
8902 std::tie(args&: FalseTy, args&: FalseName) =
8903 shouldNotPrintDirectly(Context,
8904 IntendedTy: CO->getFalseExpr()->getType(),
8905 E: CO->getFalseExpr());
8906
8907 if (TrueTy == FalseTy)
8908 return std::make_pair(x&: TrueTy, y&: TrueName);
8909 else if (TrueTy.isNull())
8910 return std::make_pair(x&: FalseTy, y&: FalseName);
8911 else if (FalseTy.isNull())
8912 return std::make_pair(x&: TrueTy, y&: TrueName);
8913 }
8914
8915 return std::make_pair(x: QualType(), y: StringRef());
8916}
8917
8918/// Return true if \p ICE is an implicit argument promotion of an arithmetic
8919/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8920/// type do not count.
8921static bool
8922isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8923 QualType From = ICE->getSubExpr()->getType();
8924 QualType To = ICE->getType();
8925 // It's an integer promotion if the destination type is the promoted
8926 // source type.
8927 if (ICE->getCastKind() == CK_IntegralCast &&
8928 S.Context.isPromotableIntegerType(T: From) &&
8929 S.Context.getPromotedIntegerType(PromotableType: From) == To)
8930 return true;
8931 // Look through vector types, since we do default argument promotion for
8932 // those in OpenCL.
8933 if (const auto *VecTy = From->getAs<ExtVectorType>())
8934 From = VecTy->getElementType();
8935 if (const auto *VecTy = To->getAs<ExtVectorType>())
8936 To = VecTy->getElementType();
8937 // It's a floating promotion if the source type is a lower rank.
8938 return ICE->getCastKind() == CK_FloatingCast &&
8939 S.Context.getFloatingTypeOrder(LHS: From, RHS: To) < 0;
8940}
8941
8942static analyze_format_string::ArgType::MatchKind
8943handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match,
8944 DiagnosticsEngine &Diags, SourceLocation Loc) {
8945 if (Match == analyze_format_string::ArgType::NoMatchSignedness) {
8946 if (Diags.isIgnored(
8947 DiagID: diag::warn_format_conversion_argument_type_mismatch_signedness,
8948 Loc) ||
8949 Diags.isIgnored(
8950 // Arbitrary -Wformat diagnostic to detect -Wno-format:
8951 DiagID: diag::warn_format_conversion_argument_type_mismatch, Loc)) {
8952 return analyze_format_string::ArgType::Match;
8953 }
8954 }
8955 return Match;
8956}
8957
8958bool
8959CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8960 const char *StartSpecifier,
8961 unsigned SpecifierLen,
8962 const Expr *E) {
8963 using namespace analyze_format_string;
8964 using namespace analyze_printf;
8965
8966 // Now type check the data expression that matches the
8967 // format specifier.
8968 const analyze_printf::ArgType &AT = FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext());
8969 if (!AT.isValid())
8970 return true;
8971
8972 QualType ExprTy = E->getType();
8973 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(Val&: ExprTy)) {
8974 ExprTy = TET->getUnderlyingExpr()->getType();
8975 }
8976
8977 if (const OverflowBehaviorType *OBT =
8978 dyn_cast<OverflowBehaviorType>(Val: ExprTy.getCanonicalType()))
8979 ExprTy = OBT->getUnderlyingType();
8980
8981 // When using the format attribute in C++, you can receive a function or an
8982 // array that will necessarily decay to a pointer when passed to the final
8983 // format consumer. Apply decay before type comparison.
8984 if (ExprTy->canDecayToPointerType())
8985 ExprTy = S.Context.getDecayedType(T: ExprTy);
8986
8987 // Diagnose attempts to print a boolean value as a character. Unlike other
8988 // -Wformat diagnostics, this is fine from a type perspective, but it still
8989 // doesn't make sense.
8990 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8991 E->isKnownToHaveBooleanValue()) {
8992 const CharSourceRange &CSR =
8993 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
8994 SmallString<4> FSString;
8995 llvm::raw_svector_ostream os(FSString);
8996 FS.toString(os);
8997 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_bool_as_character)
8998 << FSString,
8999 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9000 return true;
9001 }
9002
9003 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9004 // dumping raw class data (like is-a pointer), not actual data.
9005 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
9006 ExprTy->isObjCObjectPointerType()) {
9007 const CharSourceRange &CSR =
9008 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9009 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_with_objc_pointer),
9010 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9011 return true;
9012 }
9013
9014 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9015 ArgType::MatchKind Match = AT.matchesType(C&: S.Context, argTy: ExprTy);
9016 ArgType::MatchKind OrigMatch = Match;
9017
9018 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9019 if (Match == ArgType::Match)
9020 return true;
9021
9022 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9023 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9024
9025 // Look through argument promotions for our error message's reported type.
9026 // This includes the integral and floating promotions, but excludes array
9027 // and function pointer decay (seeing that an argument intended to be a
9028 // string has type 'char [6]' is probably more confusing than 'char *') and
9029 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9030 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
9031 if (isArithmeticArgumentPromotion(S, ICE)) {
9032 E = ICE->getSubExpr();
9033 ExprTy = E->getType();
9034
9035 // Check if we didn't match because of an implicit cast from a 'char'
9036 // or 'short' to an 'int'. This is done because printf is a varargs
9037 // function.
9038 if (ICE->getType() == S.Context.IntTy ||
9039 ICE->getType() == S.Context.UnsignedIntTy) {
9040 // All further checking is done on the subexpression
9041 ImplicitMatch = AT.matchesType(C&: S.Context, argTy: ExprTy);
9042 if (OrigMatch == ArgType::NoMatchSignedness &&
9043 ImplicitMatch != ArgType::NoMatchSignedness)
9044 // If the original match was a signedness match this match on the
9045 // implicit cast type also need to be signedness match otherwise we
9046 // might introduce new unexpected warnings from -Wformat-signedness.
9047 return true;
9048 ImplicitMatch = handleFormatSignedness(
9049 Match: ImplicitMatch, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9050 if (ImplicitMatch == ArgType::Match)
9051 return true;
9052 }
9053 }
9054 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(Val: E)) {
9055 // Special case for 'a', which has type 'int' in C.
9056 // Note, however, that we do /not/ want to treat multibyte constants like
9057 // 'MooV' as characters! This form is deprecated but still exists. In
9058 // addition, don't treat expressions as of type 'char' if one byte length
9059 // modifier is provided.
9060 if (ExprTy == S.Context.IntTy &&
9061 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9062 if (llvm::isUIntN(N: S.Context.getCharWidth(), x: CL->getValue())) {
9063 ExprTy = S.Context.CharTy;
9064 // To improve check results, we consider a character literal in C
9065 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9066 // more likely a type confusion situation, so we will suggest to
9067 // use '%hhd' instead by discarding the MatchPromotion.
9068 if (Match == ArgType::MatchPromotion)
9069 Match = ArgType::NoMatch;
9070 }
9071 }
9072 if (Match == ArgType::MatchPromotion) {
9073 // WG14 N2562 only clarified promotions in *printf
9074 // For NSLog in ObjC, just preserve -Wformat behavior
9075 if (!S.getLangOpts().ObjC &&
9076 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9077 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9078 return true;
9079 Match = ArgType::NoMatch;
9080 }
9081 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9082 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9083 Match = ImplicitMatch;
9084 assert(Match != ArgType::MatchPromotion);
9085
9086 // Look through unscoped enums to their underlying type.
9087 bool IsEnum = false;
9088 bool IsScopedEnum = false;
9089 QualType IntendedTy = ExprTy;
9090 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9091 IntendedTy = ED->getIntegerType();
9092 if (!ED->isScoped()) {
9093 ExprTy = IntendedTy;
9094 // This controls whether we're talking about the underlying type or not,
9095 // which we only want to do when it's an unscoped enum.
9096 IsEnum = true;
9097 } else {
9098 IsScopedEnum = true;
9099 }
9100 }
9101
9102 // %C in an Objective-C context prints a unichar, not a wchar_t.
9103 // If the argument is an integer of some kind, believe the %C and suggest
9104 // a cast instead of changing the conversion specifier.
9105 if (isObjCContext() &&
9106 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9107 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9108 !ExprTy->isCharType()) {
9109 // 'unichar' is defined as a typedef of unsigned short, but we should
9110 // prefer using the typedef if it is visible.
9111 IntendedTy = S.Context.UnsignedShortTy;
9112
9113 // While we are here, check if the value is an IntegerLiteral that happens
9114 // to be within the valid range.
9115 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: E)) {
9116 const llvm::APInt &V = IL->getValue();
9117 if (V.getActiveBits() <= S.Context.getTypeSize(T: IntendedTy))
9118 return true;
9119 }
9120
9121 LookupResult Result(S, &S.Context.Idents.get(Name: "unichar"), E->getBeginLoc(),
9122 Sema::LookupOrdinaryName);
9123 if (S.LookupName(R&: Result, S: S.getCurScope())) {
9124 NamedDecl *ND = Result.getFoundDecl();
9125 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: ND))
9126 if (TD->getUnderlyingType() == IntendedTy)
9127 IntendedTy =
9128 S.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
9129 /*Qualifier=*/std::nullopt, Decl: TD);
9130 }
9131 }
9132 }
9133
9134 // Special-case some of Darwin's platform-independence types by suggesting
9135 // casts to primitive types that are known to be large enough.
9136 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9137 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9138 QualType CastTy;
9139 std::tie(args&: CastTy, args&: CastTyName) = shouldNotPrintDirectly(Context: S.Context, IntendedTy, E);
9140 if (!CastTy.isNull()) {
9141 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9142 // (long in ASTContext). Only complain to pedants or when they're the
9143 // underlying type of a scoped enum (which always needs a cast).
9144 if (!IsScopedEnum &&
9145 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9146 (AT.isSizeT() || AT.isPtrdiffT()) &&
9147 AT.matchesType(C&: S.Context, argTy: CastTy))
9148 Match = ArgType::NoMatchPedantic;
9149 IntendedTy = CastTy;
9150 ShouldNotPrintDirectly = true;
9151 }
9152 }
9153
9154 // We may be able to offer a FixItHint if it is a supported type.
9155 PrintfSpecifier fixedFS = FS;
9156 bool Success =
9157 fixedFS.fixType(QT: IntendedTy, LangOpt: S.getLangOpts(), Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9158
9159 if (Success) {
9160 // Get the fix string from the fixed format specifier
9161 SmallString<16> buf;
9162 llvm::raw_svector_ostream os(buf);
9163 fixedFS.toString(os);
9164
9165 CharSourceRange SpecRange = getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9166
9167 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9168 unsigned Diag;
9169 switch (Match) {
9170 case ArgType::Match:
9171 case ArgType::MatchPromotion:
9172 case ArgType::NoMatchPromotionTypeConfusion:
9173 llvm_unreachable("expected non-matching");
9174 case ArgType::NoMatchSignedness:
9175 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9176 break;
9177 case ArgType::NoMatchPedantic:
9178 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9179 break;
9180 case ArgType::NoMatchTypeConfusion:
9181 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9182 break;
9183 case ArgType::NoMatch:
9184 Diag = diag::warn_format_conversion_argument_type_mismatch;
9185 break;
9186 }
9187
9188 // In this case, the specifier is wrong and should be changed to match
9189 // the argument.
9190 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
9191 << AT.getRepresentativeTypeName(C&: S.Context)
9192 << IntendedTy << IsEnum << E->getSourceRange(),
9193 Loc: E->getBeginLoc(),
9194 /*IsStringLocation*/ false, StringRange: SpecRange,
9195 FixIt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9196 } else {
9197 // The canonical type for formatting this value is different from the
9198 // actual type of the expression. (This occurs, for example, with Darwin's
9199 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9200 // should be printed as 'long' for 64-bit compatibility.)
9201 // Rather than emitting a normal format/argument mismatch, we want to
9202 // add a cast to the recommended type (and correct the format string
9203 // if necessary). We should also do so for scoped enumerations.
9204 SmallString<16> CastBuf;
9205 llvm::raw_svector_ostream CastFix(CastBuf);
9206 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9207 IntendedTy.print(OS&: CastFix, Policy: S.Context.getPrintingPolicy());
9208 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9209
9210 SmallVector<FixItHint,4> Hints;
9211 ArgType::MatchKind IntendedMatch = AT.matchesType(C&: S.Context, argTy: IntendedTy);
9212 IntendedMatch = handleFormatSignedness(Match: IntendedMatch, Diags&: S.getDiagnostics(),
9213 Loc: E->getExprLoc());
9214 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9215 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9216
9217 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(Val: E)) {
9218 // If there's already a cast present, just replace it.
9219 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9220 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: CastRange, Code: CastFix.str()));
9221
9222 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9223 // If the expression has high enough precedence,
9224 // just write the C-style cast.
9225 Hints.push_back(
9226 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9227 } else {
9228 // Otherwise, add parens around the expression as well as the cast.
9229 CastFix << "(";
9230 Hints.push_back(
9231 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9232
9233 // We don't use getLocForEndOfToken because it returns invalid source
9234 // locations for macro expansions (by design).
9235 SourceLocation EndLoc = S.SourceMgr.getSpellingLoc(Loc: E->getEndLoc());
9236 SourceLocation After = EndLoc.getLocWithOffset(
9237 Offset: Lexer::MeasureTokenLength(Loc: EndLoc, SM: S.SourceMgr, LangOpts: S.LangOpts));
9238 Hints.push_back(Elt: FixItHint::CreateInsertion(InsertionLoc: After, Code: ")"));
9239 }
9240
9241 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9242 // The expression has a type that should not be printed directly.
9243 // We extract the name from the typedef because we don't want to show
9244 // the underlying type in the diagnostic.
9245 StringRef Name;
9246 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9247 Name = TypedefTy->getDecl()->getName();
9248 else
9249 Name = CastTyName;
9250 unsigned Diag = Match == ArgType::NoMatchPedantic
9251 ? diag::warn_format_argument_needs_cast_pedantic
9252 : diag::warn_format_argument_needs_cast;
9253 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag) << Name << IntendedTy << IsEnum
9254 << E->getSourceRange(),
9255 Loc: E->getBeginLoc(), /*IsStringLocation=*/false,
9256 StringRange: SpecRange, FixIt: Hints);
9257 } else {
9258 // In this case, the expression could be printed using a different
9259 // specifier, but we've decided that the specifier is probably correct
9260 // and we should cast instead. Just use the normal warning message.
9261
9262 unsigned Diag =
9263 IsScopedEnum
9264 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9265 : diag::warn_format_conversion_argument_type_mismatch;
9266
9267 EmitFormatDiagnostic(
9268 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9269 << IsEnum << E->getSourceRange(),
9270 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: SpecRange, FixIt: Hints);
9271 }
9272 }
9273 } else {
9274 const CharSourceRange &CSR = getSpecifierRange(startSpecifier: StartSpecifier,
9275 specifierLen: SpecifierLen);
9276 // Since the warning for passing non-POD types to variadic functions
9277 // was deferred until now, we emit a warning for non-POD
9278 // arguments here.
9279 bool EmitTypeMismatch = false;
9280 switch (S.isValidVarArgType(Ty: ExprTy)) {
9281 case VarArgKind::Valid:
9282 case VarArgKind::ValidInCXX11: {
9283 unsigned Diag;
9284 switch (Match) {
9285 case ArgType::Match:
9286 case ArgType::MatchPromotion:
9287 case ArgType::NoMatchPromotionTypeConfusion:
9288 llvm_unreachable("expected non-matching");
9289 case ArgType::NoMatchSignedness:
9290 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9291 break;
9292 case ArgType::NoMatchPedantic:
9293 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9294 break;
9295 case ArgType::NoMatchTypeConfusion:
9296 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9297 break;
9298 case ArgType::NoMatch:
9299 Diag = isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy)
9300 ? diag::err_format_conversion_argument_type_mismatch
9301 : diag::warn_format_conversion_argument_type_mismatch;
9302 break;
9303 }
9304
9305 EmitFormatDiagnostic(
9306 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9307 << IsEnum << CSR << E->getSourceRange(),
9308 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9309 break;
9310 }
9311 case VarArgKind::Undefined:
9312 case VarArgKind::MSVCUndefined:
9313 if (CallType == VariadicCallType::DoesNotApply) {
9314 EmitTypeMismatch = true;
9315 } else {
9316 EmitFormatDiagnostic(
9317 PDiag: S.PDiag(DiagID: diag::warn_non_pod_vararg_with_format_string)
9318 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9319 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9320 << E->getSourceRange(),
9321 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9322 checkForCStrMembers(AT, E);
9323 }
9324 break;
9325
9326 case VarArgKind::Invalid:
9327 if (CallType == VariadicCallType::DoesNotApply)
9328 EmitTypeMismatch = true;
9329 else if (ExprTy->isObjCObjectType())
9330 EmitFormatDiagnostic(
9331 PDiag: S.PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg_format)
9332 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9333 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9334 << E->getSourceRange(),
9335 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9336 else
9337 // FIXME: If this is an initializer list, suggest removing the braces
9338 // or inserting a cast to the target type.
9339 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg_format)
9340 << isa<InitListExpr>(Val: E) << ExprTy << CallType
9341 << AT.getRepresentativeTypeName(C&: S.Context) << E->getSourceRange();
9342 break;
9343 }
9344
9345 if (EmitTypeMismatch) {
9346 // The function is not variadic, so we do not generate warnings about
9347 // being allowed to pass that object as a variadic argument. Instead,
9348 // since there are inherently no printf specifiers for types which cannot
9349 // be passed as variadic arguments, emit a plain old specifier mismatch
9350 // argument.
9351 EmitFormatDiagnostic(
9352 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9353 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << false
9354 << E->getSourceRange(),
9355 Loc: E->getBeginLoc(), IsStringLocation: false, StringRange: CSR);
9356 }
9357
9358 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9359 "format string specifier index out of range");
9360 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9361 }
9362
9363 return true;
9364}
9365
9366//===--- CHECK: Scanf format string checking ------------------------------===//
9367
9368namespace {
9369
9370class CheckScanfHandler : public CheckFormatHandler {
9371public:
9372 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9373 const Expr *origFormatExpr, FormatStringType type,
9374 unsigned firstDataArg, unsigned numDataArgs,
9375 const char *beg, Sema::FormatArgumentPassingKind APK,
9376 ArrayRef<const Expr *> Args, unsigned formatIdx,
9377 bool inFunctionCall, VariadicCallType CallType,
9378 llvm::SmallBitVector &CheckedVarArgs,
9379 UncoveredArgHandler &UncoveredArg)
9380 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9381 numDataArgs, beg, APK, Args, formatIdx,
9382 inFunctionCall, CallType, CheckedVarArgs,
9383 UncoveredArg) {}
9384
9385 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9386 const char *startSpecifier,
9387 unsigned specifierLen) override;
9388
9389 bool HandleInvalidScanfConversionSpecifier(
9390 const analyze_scanf::ScanfSpecifier &FS,
9391 const char *startSpecifier,
9392 unsigned specifierLen) override;
9393
9394 void HandleIncompleteScanList(const char *start, const char *end) override;
9395};
9396
9397} // namespace
9398
9399void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9400 const char *end) {
9401 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_scanlist_incomplete),
9402 Loc: getLocationOfByte(x: end), /*IsStringLocation*/true,
9403 StringRange: getSpecifierRange(startSpecifier: start, specifierLen: end - start));
9404}
9405
9406bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9407 const analyze_scanf::ScanfSpecifier &FS,
9408 const char *startSpecifier,
9409 unsigned specifierLen) {
9410 const analyze_scanf::ScanfConversionSpecifier &CS =
9411 FS.getConversionSpecifier();
9412
9413 return HandleInvalidConversionSpecifier(argIndex: FS.getArgIndex(),
9414 Loc: getLocationOfByte(x: CS.getStart()),
9415 startSpec: startSpecifier, specifierLen,
9416 csStart: CS.getStart(), csLen: CS.getLength());
9417}
9418
9419bool CheckScanfHandler::HandleScanfSpecifier(
9420 const analyze_scanf::ScanfSpecifier &FS,
9421 const char *startSpecifier,
9422 unsigned specifierLen) {
9423 using namespace analyze_scanf;
9424 using namespace analyze_format_string;
9425
9426 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9427
9428 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9429 // be used to decide if we are using positional arguments consistently.
9430 if (FS.consumesDataArgument()) {
9431 if (atFirstArg) {
9432 atFirstArg = false;
9433 usesPositionalArgs = FS.usesPositionalArg();
9434 }
9435 else if (usesPositionalArgs != FS.usesPositionalArg()) {
9436 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
9437 startSpec: startSpecifier, specifierLen);
9438 return false;
9439 }
9440 }
9441
9442 // Check if the field with is non-zero.
9443 const OptionalAmount &Amt = FS.getFieldWidth();
9444 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9445 if (Amt.getConstantAmount() == 0) {
9446 const CharSourceRange &R = getSpecifierRange(startSpecifier: Amt.getStart(),
9447 specifierLen: Amt.getConstantLength());
9448 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_nonzero_width),
9449 Loc: getLocationOfByte(x: Amt.getStart()),
9450 /*IsStringLocation*/true, StringRange: R,
9451 FixIt: FixItHint::CreateRemoval(RemoveRange: R));
9452 }
9453 }
9454
9455 if (!FS.consumesDataArgument()) {
9456 // FIXME: Technically specifying a precision or field width here
9457 // makes no sense. Worth issuing a warning at some point.
9458 return true;
9459 }
9460
9461 // Consume the argument.
9462 unsigned argIndex = FS.getArgIndex();
9463 if (argIndex < NumDataArgs) {
9464 // The check to see if the argIndex is valid will come later.
9465 // We set the bit here because we may exit early from this
9466 // function if we encounter some other error.
9467 CoveredArgs.set(argIndex);
9468 }
9469
9470 // Check the length modifier is valid with the given conversion specifier.
9471 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
9472 LO: S.getLangOpts()))
9473 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9474 DiagID: diag::warn_format_nonsensical_length);
9475 else if (!FS.hasStandardLengthModifier())
9476 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9477 else if (!FS.hasStandardLengthConversionCombination())
9478 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9479 DiagID: diag::warn_format_non_standard_conversion_spec);
9480
9481 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
9482 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9483
9484 // The remaining checks depend on the data arguments.
9485 if (!HasFormatArguments())
9486 return true;
9487
9488 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9489 return false;
9490
9491 // Check that the argument type matches the format specifier.
9492 const Expr *Ex = getDataArg(i: argIndex);
9493 if (!Ex)
9494 return true;
9495
9496 const analyze_format_string::ArgType &AT = FS.getArgType(Ctx&: S.Context);
9497
9498 if (!AT.isValid()) {
9499 return true;
9500 }
9501
9502 analyze_format_string::ArgType::MatchKind Match =
9503 AT.matchesType(C&: S.Context, argTy: Ex->getType());
9504 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: Ex->getExprLoc());
9505 if (Match == analyze_format_string::ArgType::Match)
9506 return true;
9507 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9508 bool Signedness = Match == analyze_format_string::ArgType::NoMatchSignedness;
9509
9510 ScanfSpecifier fixedFS = FS;
9511 bool Success = fixedFS.fixType(QT: Ex->getType(), RawQT: Ex->IgnoreImpCasts()->getType(),
9512 LangOpt: S.getLangOpts(), Ctx&: S.Context);
9513
9514 unsigned Diag =
9515 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9516 : Signedness
9517 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9518 : diag::warn_format_conversion_argument_type_mismatch;
9519
9520 if (Success) {
9521 // Get the fix string from the fixed format specifier.
9522 SmallString<128> buf;
9523 llvm::raw_svector_ostream os(buf);
9524 fixedFS.toString(os);
9525
9526 EmitFormatDiagnostic(
9527 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context)
9528 << Ex->getType() << false << Ex->getSourceRange(),
9529 Loc: Ex->getBeginLoc(),
9530 /*IsStringLocation*/ false,
9531 StringRange: getSpecifierRange(startSpecifier, specifierLen),
9532 FixIt: FixItHint::CreateReplacement(
9533 RemoveRange: getSpecifierRange(startSpecifier, specifierLen), Code: os.str()));
9534 } else {
9535 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
9536 << AT.getRepresentativeTypeName(C&: S.Context)
9537 << Ex->getType() << false << Ex->getSourceRange(),
9538 Loc: Ex->getBeginLoc(),
9539 /*IsStringLocation*/ false,
9540 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9541 }
9542
9543 return true;
9544}
9545
9546static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9547 ArrayRef<EquatableFormatArgument> RefArgs,
9548 const StringLiteral *Fmt,
9549 ArrayRef<EquatableFormatArgument> FmtArgs,
9550 const Expr *FmtExpr, bool InFunctionCall) {
9551 bool HadError = false;
9552 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
9553 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
9554 while (FmtIter < FmtEnd && RefIter < RefEnd) {
9555 // In positional-style format strings, the same specifier can appear
9556 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
9557 // are sorted by getPosition(), and we process each range of equal
9558 // getPosition() values as one group.
9559 // RefArgs are taken from a string literal that was given to
9560 // attribute(format_matches), and if we got this far, we have already
9561 // verified that if it has positional specifiers that appear in multiple
9562 // locations, then they are all mutually compatible. What's left for us to
9563 // do is verify that all specifiers with the same position in FmtArgs are
9564 // compatible with the RefArgs specifiers. We check each specifier from
9565 // FmtArgs against the first member of the RefArgs group.
9566 for (; FmtIter < FmtEnd; ++FmtIter) {
9567 // Clang does not diagnose missing format specifiers in positional-style
9568 // strings (TODO: which it probably should do, as it is UB to skip over a
9569 // format argument). Skip specifiers if needed.
9570 if (FmtIter->getPosition() < RefIter->getPosition())
9571 continue;
9572
9573 // Delimits a new getPosition() value.
9574 if (FmtIter->getPosition() > RefIter->getPosition())
9575 break;
9576
9577 HadError |=
9578 !FmtIter->VerifyCompatible(S, Other: *RefIter, FmtExpr, InFunctionCall);
9579 }
9580
9581 // Jump RefIter to the start of the next group.
9582 RefIter = std::find_if(first: RefIter + 1, last: RefEnd, pred: [=](const auto &Arg) {
9583 return Arg.getPosition() != RefIter->getPosition();
9584 });
9585 }
9586
9587 if (FmtIter < FmtEnd) {
9588 CheckFormatHandler::EmitFormatDiagnostic(
9589 S, InFunctionCall, ArgumentExpr: FmtExpr,
9590 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 1,
9591 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: FmtIter->getSourceRange());
9592 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with) << 1;
9593 } else if (RefIter < RefEnd) {
9594 CheckFormatHandler::EmitFormatDiagnostic(
9595 S, InFunctionCall, ArgumentExpr: FmtExpr,
9596 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 0,
9597 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: Fmt->getSourceRange());
9598 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with)
9599 << 1 << RefIter->getSourceRange();
9600 }
9601 return !HadError;
9602}
9603
9604static void CheckFormatString(
9605 Sema &S, const FormatStringLiteral *FExpr,
9606 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
9607 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
9608 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
9609 bool inFunctionCall, VariadicCallType CallType,
9610 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
9611 bool IgnoreStringsWithoutSpecifiers) {
9612 // CHECK: is the format string a wide literal?
9613 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9614 CheckFormatHandler::EmitFormatDiagnostic(
9615 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
9616 PDiag: S.PDiag(DiagID: diag::warn_format_string_is_wide_literal), Loc: FExpr->getBeginLoc(),
9617 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
9618 return;
9619 }
9620
9621 // Str - The format string. NOTE: this is NOT null-terminated!
9622 StringRef StrRef = FExpr->getString();
9623 const char *Str = StrRef.data();
9624 // Account for cases where the string literal is truncated in a declaration.
9625 const ConstantArrayType *T =
9626 S.Context.getAsConstantArrayType(T: FExpr->getType());
9627 assert(T && "String literal not of constant array type!");
9628 size_t TypeSize = T->getZExtSize();
9629 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
9630 const unsigned numDataArgs = Args.size() - firstDataArg;
9631
9632 if (IgnoreStringsWithoutSpecifiers &&
9633 !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9634 Begin: Str, End: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
9635 return;
9636
9637 // Emit a warning if the string literal is truncated and does not contain an
9638 // embedded null character.
9639 if (TypeSize <= StrRef.size() && !StrRef.substr(Start: 0, N: TypeSize).contains(C: '\0')) {
9640 CheckFormatHandler::EmitFormatDiagnostic(
9641 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
9642 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_not_null_terminated),
9643 Loc: FExpr->getBeginLoc(),
9644 /*IsStringLocation=*/true, StringRange: OrigFormatExpr->getSourceRange());
9645 return;
9646 }
9647
9648 // CHECK: empty format string?
9649 if (StrLen == 0 && numDataArgs > 0) {
9650 CheckFormatHandler::EmitFormatDiagnostic(
9651 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
9652 PDiag: S.PDiag(DiagID: diag::warn_empty_format_string), Loc: FExpr->getBeginLoc(),
9653 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
9654 return;
9655 }
9656
9657 if (Type == FormatStringType::Printf || Type == FormatStringType::NSString ||
9658 Type == FormatStringType::Kprintf ||
9659 Type == FormatStringType::FreeBSDKPrintf ||
9660 Type == FormatStringType::OSLog || Type == FormatStringType::OSTrace) {
9661 bool IsObjC =
9662 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
9663 if (ReferenceFormatString == nullptr) {
9664 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9665 numDataArgs, IsObjC, Str, APK, Args, format_idx,
9666 inFunctionCall, CallType, CheckedVarArgs,
9667 UncoveredArg);
9668
9669 if (!analyze_format_string::ParsePrintfString(
9670 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
9671 isFreeBSDKPrintf: Type == FormatStringType::Kprintf ||
9672 Type == FormatStringType::FreeBSDKPrintf))
9673 H.DoneProcessing();
9674 } else {
9675 S.CheckFormatStringsCompatible(
9676 FST: Type, AuthoritativeFormatString: ReferenceFormatString, TestedFormatString: FExpr->getFormatString(),
9677 FunctionCallArg: inFunctionCall ? nullptr : Args[format_idx]);
9678 }
9679 } else if (Type == FormatStringType::Scanf) {
9680 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9681 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
9682 CallType, CheckedVarArgs, UncoveredArg);
9683
9684 if (!analyze_format_string::ParseScanfString(
9685 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
9686 H.DoneProcessing();
9687 } // TODO: handle other formats
9688}
9689
9690bool Sema::CheckFormatStringsCompatible(
9691 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
9692 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
9693 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
9694 Type != FormatStringType::Kprintf &&
9695 Type != FormatStringType::FreeBSDKPrintf &&
9696 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
9697 return true;
9698
9699 bool IsObjC =
9700 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
9701 llvm::SmallVector<EquatableFormatArgument, 9> RefArgs, FmtArgs;
9702 FormatStringLiteral RefLit = AuthoritativeFormatString;
9703 FormatStringLiteral TestLit = TestedFormatString;
9704 const Expr *Arg;
9705 bool DiagAtStringLiteral;
9706 if (FunctionCallArg) {
9707 Arg = FunctionCallArg;
9708 DiagAtStringLiteral = false;
9709 } else {
9710 Arg = TestedFormatString;
9711 DiagAtStringLiteral = true;
9712 }
9713 if (DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit,
9714 FmtExpr: AuthoritativeFormatString, Type,
9715 IsObjC, InFunctionCall: true, Args&: RefArgs) &&
9716 DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &TestLit, FmtExpr: Arg, Type, IsObjC,
9717 InFunctionCall: DiagAtStringLiteral, Args&: FmtArgs)) {
9718 return CompareFormatSpecifiers(S&: *this, Ref: AuthoritativeFormatString, RefArgs,
9719 Fmt: TestedFormatString, FmtArgs, FmtExpr: Arg,
9720 InFunctionCall: DiagAtStringLiteral);
9721 }
9722 return false;
9723}
9724
9725bool Sema::ValidateFormatString(FormatStringType Type,
9726 const StringLiteral *Str) {
9727 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
9728 Type != FormatStringType::Kprintf &&
9729 Type != FormatStringType::FreeBSDKPrintf &&
9730 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
9731 return true;
9732
9733 FormatStringLiteral RefLit = Str;
9734 llvm::SmallVector<EquatableFormatArgument, 9> Args;
9735 bool IsObjC =
9736 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
9737 if (!DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit, FmtExpr: Str, Type, IsObjC,
9738 InFunctionCall: true, Args))
9739 return false;
9740
9741 // Group arguments by getPosition() value, and check that each member of the
9742 // group is compatible with the first member. This verifies that when
9743 // positional arguments are used multiple times (such as %2$i %2$d), all uses
9744 // are mutually compatible. As an optimization, don't test the first member
9745 // against itself.
9746 bool HadError = false;
9747 auto Iter = Args.begin();
9748 auto End = Args.end();
9749 while (Iter != End) {
9750 const auto &FirstInGroup = *Iter;
9751 for (++Iter;
9752 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
9753 ++Iter) {
9754 HadError |= !Iter->VerifyCompatible(S&: *this, Other: FirstInGroup, FmtExpr: Str, InFunctionCall: true);
9755 }
9756 }
9757 return !HadError;
9758}
9759
9760bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9761 // Str - The format string. NOTE: this is NOT null-terminated!
9762 StringRef StrRef = FExpr->getString();
9763 const char *Str = StrRef.data();
9764 // Account for cases where the string literal is truncated in a declaration.
9765 const ConstantArrayType *T = Context.getAsConstantArrayType(T: FExpr->getType());
9766 assert(T && "String literal not of constant array type!");
9767 size_t TypeSize = T->getZExtSize();
9768 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
9769 return analyze_format_string::ParseFormatStringHasSArg(beg: Str, end: Str + StrLen,
9770 LO: getLangOpts(),
9771 Target: Context.getTargetInfo());
9772}
9773
9774//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9775
9776// Returns the related absolute value function that is larger, of 0 if one
9777// does not exist.
9778static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9779 switch (AbsFunction) {
9780 default:
9781 return 0;
9782
9783 case Builtin::BI__builtin_abs:
9784 return Builtin::BI__builtin_labs;
9785 case Builtin::BI__builtin_labs:
9786 return Builtin::BI__builtin_llabs;
9787 case Builtin::BI__builtin_llabs:
9788 return 0;
9789
9790 case Builtin::BI__builtin_fabsf:
9791 return Builtin::BI__builtin_fabs;
9792 case Builtin::BI__builtin_fabs:
9793 return Builtin::BI__builtin_fabsl;
9794 case Builtin::BI__builtin_fabsl:
9795 return 0;
9796
9797 case Builtin::BI__builtin_cabsf:
9798 return Builtin::BI__builtin_cabs;
9799 case Builtin::BI__builtin_cabs:
9800 return Builtin::BI__builtin_cabsl;
9801 case Builtin::BI__builtin_cabsl:
9802 return 0;
9803
9804 case Builtin::BIabs:
9805 return Builtin::BIlabs;
9806 case Builtin::BIlabs:
9807 return Builtin::BIllabs;
9808 case Builtin::BIllabs:
9809 return 0;
9810
9811 case Builtin::BIfabsf:
9812 return Builtin::BIfabs;
9813 case Builtin::BIfabs:
9814 return Builtin::BIfabsl;
9815 case Builtin::BIfabsl:
9816 return 0;
9817
9818 case Builtin::BIcabsf:
9819 return Builtin::BIcabs;
9820 case Builtin::BIcabs:
9821 return Builtin::BIcabsl;
9822 case Builtin::BIcabsl:
9823 return 0;
9824 }
9825}
9826
9827// Returns the argument type of the absolute value function.
9828static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9829 unsigned AbsType) {
9830 if (AbsType == 0)
9831 return QualType();
9832
9833 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9834 QualType BuiltinType = Context.GetBuiltinType(ID: AbsType, Error);
9835 if (Error != ASTContext::GE_None)
9836 return QualType();
9837
9838 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9839 if (!FT)
9840 return QualType();
9841
9842 if (FT->getNumParams() != 1)
9843 return QualType();
9844
9845 return FT->getParamType(i: 0);
9846}
9847
9848// Returns the best absolute value function, or zero, based on type and
9849// current absolute value function.
9850static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9851 unsigned AbsFunctionKind) {
9852 unsigned BestKind = 0;
9853 uint64_t ArgSize = Context.getTypeSize(T: ArgType);
9854 for (unsigned Kind = AbsFunctionKind; Kind != 0;
9855 Kind = getLargerAbsoluteValueFunction(AbsFunction: Kind)) {
9856 QualType ParamType = getAbsoluteValueArgumentType(Context, AbsType: Kind);
9857 if (Context.getTypeSize(T: ParamType) >= ArgSize) {
9858 if (BestKind == 0)
9859 BestKind = Kind;
9860 else if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
9861 BestKind = Kind;
9862 break;
9863 }
9864 }
9865 }
9866 return BestKind;
9867}
9868
9869enum AbsoluteValueKind {
9870 AVK_Integer,
9871 AVK_Floating,
9872 AVK_Complex
9873};
9874
9875static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9876 if (T->isIntegralOrEnumerationType())
9877 return AVK_Integer;
9878 if (T->isRealFloatingType())
9879 return AVK_Floating;
9880 if (T->isAnyComplexType())
9881 return AVK_Complex;
9882
9883 llvm_unreachable("Type not integer, floating, or complex");
9884}
9885
9886// Changes the absolute value function to a different type. Preserves whether
9887// the function is a builtin.
9888static unsigned changeAbsFunction(unsigned AbsKind,
9889 AbsoluteValueKind ValueKind) {
9890 switch (ValueKind) {
9891 case AVK_Integer:
9892 switch (AbsKind) {
9893 default:
9894 return 0;
9895 case Builtin::BI__builtin_fabsf:
9896 case Builtin::BI__builtin_fabs:
9897 case Builtin::BI__builtin_fabsl:
9898 case Builtin::BI__builtin_cabsf:
9899 case Builtin::BI__builtin_cabs:
9900 case Builtin::BI__builtin_cabsl:
9901 return Builtin::BI__builtin_abs;
9902 case Builtin::BIfabsf:
9903 case Builtin::BIfabs:
9904 case Builtin::BIfabsl:
9905 case Builtin::BIcabsf:
9906 case Builtin::BIcabs:
9907 case Builtin::BIcabsl:
9908 return Builtin::BIabs;
9909 }
9910 case AVK_Floating:
9911 switch (AbsKind) {
9912 default:
9913 return 0;
9914 case Builtin::BI__builtin_abs:
9915 case Builtin::BI__builtin_labs:
9916 case Builtin::BI__builtin_llabs:
9917 case Builtin::BI__builtin_cabsf:
9918 case Builtin::BI__builtin_cabs:
9919 case Builtin::BI__builtin_cabsl:
9920 return Builtin::BI__builtin_fabsf;
9921 case Builtin::BIabs:
9922 case Builtin::BIlabs:
9923 case Builtin::BIllabs:
9924 case Builtin::BIcabsf:
9925 case Builtin::BIcabs:
9926 case Builtin::BIcabsl:
9927 return Builtin::BIfabsf;
9928 }
9929 case AVK_Complex:
9930 switch (AbsKind) {
9931 default:
9932 return 0;
9933 case Builtin::BI__builtin_abs:
9934 case Builtin::BI__builtin_labs:
9935 case Builtin::BI__builtin_llabs:
9936 case Builtin::BI__builtin_fabsf:
9937 case Builtin::BI__builtin_fabs:
9938 case Builtin::BI__builtin_fabsl:
9939 return Builtin::BI__builtin_cabsf;
9940 case Builtin::BIabs:
9941 case Builtin::BIlabs:
9942 case Builtin::BIllabs:
9943 case Builtin::BIfabsf:
9944 case Builtin::BIfabs:
9945 case Builtin::BIfabsl:
9946 return Builtin::BIcabsf;
9947 }
9948 }
9949 llvm_unreachable("Unable to convert function");
9950}
9951
9952static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9953 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9954 if (!FnInfo)
9955 return 0;
9956
9957 switch (FDecl->getBuiltinID()) {
9958 default:
9959 return 0;
9960 case Builtin::BI__builtin_abs:
9961 case Builtin::BI__builtin_fabs:
9962 case Builtin::BI__builtin_fabsf:
9963 case Builtin::BI__builtin_fabsl:
9964 case Builtin::BI__builtin_labs:
9965 case Builtin::BI__builtin_llabs:
9966 case Builtin::BI__builtin_cabs:
9967 case Builtin::BI__builtin_cabsf:
9968 case Builtin::BI__builtin_cabsl:
9969 case Builtin::BIabs:
9970 case Builtin::BIlabs:
9971 case Builtin::BIllabs:
9972 case Builtin::BIfabs:
9973 case Builtin::BIfabsf:
9974 case Builtin::BIfabsl:
9975 case Builtin::BIcabs:
9976 case Builtin::BIcabsf:
9977 case Builtin::BIcabsl:
9978 return FDecl->getBuiltinID();
9979 }
9980 llvm_unreachable("Unknown Builtin type");
9981}
9982
9983// If the replacement is valid, emit a note with replacement function.
9984// Additionally, suggest including the proper header if not already included.
9985static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9986 unsigned AbsKind, QualType ArgType) {
9987 bool EmitHeaderHint = true;
9988 const char *HeaderName = nullptr;
9989 std::string FunctionName;
9990 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9991 FunctionName = "std::abs";
9992 if (ArgType->isIntegralOrEnumerationType()) {
9993 HeaderName = "cstdlib";
9994 } else if (ArgType->isRealFloatingType()) {
9995 HeaderName = "cmath";
9996 } else {
9997 llvm_unreachable("Invalid Type");
9998 }
9999
10000 // Lookup all std::abs
10001 if (NamespaceDecl *Std = S.getStdNamespace()) {
10002 LookupResult R(S, &S.Context.Idents.get(Name: "abs"), Loc, Sema::LookupAnyName);
10003 R.suppressDiagnostics();
10004 S.LookupQualifiedName(R, LookupCtx: Std);
10005
10006 for (const auto *I : R) {
10007 const FunctionDecl *FDecl = nullptr;
10008 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(Val: I)) {
10009 FDecl = dyn_cast<FunctionDecl>(Val: UsingD->getTargetDecl());
10010 } else {
10011 FDecl = dyn_cast<FunctionDecl>(Val: I);
10012 }
10013 if (!FDecl)
10014 continue;
10015
10016 // Found std::abs(), check that they are the right ones.
10017 if (FDecl->getNumParams() != 1)
10018 continue;
10019
10020 // Check that the parameter type can handle the argument.
10021 QualType ParamType = FDecl->getParamDecl(i: 0)->getType();
10022 if (getAbsoluteValueKind(T: ArgType) == getAbsoluteValueKind(T: ParamType) &&
10023 S.Context.getTypeSize(T: ArgType) <=
10024 S.Context.getTypeSize(T: ParamType)) {
10025 // Found a function, don't need the header hint.
10026 EmitHeaderHint = false;
10027 break;
10028 }
10029 }
10030 }
10031 } else {
10032 FunctionName = S.Context.BuiltinInfo.getName(ID: AbsKind);
10033 HeaderName = S.Context.BuiltinInfo.getHeaderName(ID: AbsKind);
10034
10035 if (HeaderName) {
10036 DeclarationName DN(&S.Context.Idents.get(Name: FunctionName));
10037 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10038 R.suppressDiagnostics();
10039 S.LookupName(R, S: S.getCurScope());
10040
10041 if (R.isSingleResult()) {
10042 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
10043 if (FD && FD->getBuiltinID() == AbsKind) {
10044 EmitHeaderHint = false;
10045 } else {
10046 return;
10047 }
10048 } else if (!R.empty()) {
10049 return;
10050 }
10051 }
10052 }
10053
10054 S.Diag(Loc, DiagID: diag::note_replace_abs_function)
10055 << FunctionName << FixItHint::CreateReplacement(RemoveRange: Range, Code: FunctionName);
10056
10057 if (!HeaderName)
10058 return;
10059
10060 if (!EmitHeaderHint)
10061 return;
10062
10063 S.Diag(Loc, DiagID: diag::note_include_header_or_declare) << HeaderName
10064 << FunctionName;
10065}
10066
10067template <std::size_t StrLen>
10068static bool IsStdFunction(const FunctionDecl *FDecl,
10069 const char (&Str)[StrLen]) {
10070 if (!FDecl)
10071 return false;
10072 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10073 return false;
10074 if (!FDecl->isInStdNamespace())
10075 return false;
10076
10077 return true;
10078}
10079
10080enum class MathCheck { NaN, Inf };
10081static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10082 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10083 return llvm::is_contained(Set: names, Element: calleeName);
10084 };
10085
10086 switch (Check) {
10087 case MathCheck::NaN:
10088 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10089 "__builtin_nanf16", "__builtin_nanf128"});
10090 case MathCheck::Inf:
10091 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10092 "__builtin_inff16", "__builtin_inff128"});
10093 }
10094 llvm_unreachable("unknown MathCheck");
10095}
10096
10097static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10098 if (FDecl->getName() != "infinity")
10099 return false;
10100
10101 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(Val: FDecl)) {
10102 const CXXRecordDecl *RDecl = MDecl->getParent();
10103 if (RDecl->getName() != "numeric_limits")
10104 return false;
10105
10106 if (const NamespaceDecl *NSDecl =
10107 dyn_cast<NamespaceDecl>(Val: RDecl->getDeclContext()))
10108 return NSDecl->isStdNamespace();
10109 }
10110
10111 return false;
10112}
10113
10114void Sema::CheckInfNaNFunction(const CallExpr *Call,
10115 const FunctionDecl *FDecl) {
10116 if (!FDecl->getIdentifier())
10117 return;
10118
10119 FPOptions FPO = Call->getFPFeaturesInEffect(LO: getLangOpts());
10120 if (FPO.getNoHonorNaNs() &&
10121 (IsStdFunction(FDecl, Str: "isnan") || IsStdFunction(FDecl, Str: "isunordered") ||
10122 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::NaN))) {
10123 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10124 << 1 << 0 << Call->getSourceRange();
10125 return;
10126 }
10127
10128 if (FPO.getNoHonorInfs() &&
10129 (IsStdFunction(FDecl, Str: "isinf") || IsStdFunction(FDecl, Str: "isfinite") ||
10130 IsInfinityFunction(FDecl) ||
10131 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::Inf))) {
10132 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10133 << 0 << 0 << Call->getSourceRange();
10134 }
10135}
10136
10137void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10138 const FunctionDecl *FDecl) {
10139 if (Call->getNumArgs() != 1)
10140 return;
10141
10142 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10143 bool IsStdAbs = IsStdFunction(FDecl, Str: "abs");
10144 if (AbsKind == 0 && !IsStdAbs)
10145 return;
10146
10147 QualType ArgType = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
10148 QualType ParamType = Call->getArg(Arg: 0)->getType();
10149
10150 // Unsigned types cannot be negative. Suggest removing the absolute value
10151 // function call.
10152 if (ArgType->isUnsignedIntegerType()) {
10153 std::string FunctionName =
10154 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(ID: AbsKind);
10155 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_unsigned_abs) << ArgType << ParamType;
10156 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_abs)
10157 << FunctionName
10158 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange());
10159 return;
10160 }
10161
10162 // Taking the absolute value of a pointer is very suspicious, they probably
10163 // wanted to index into an array, dereference a pointer, call a function, etc.
10164 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10165 unsigned DiagType = 0;
10166 if (ArgType->isFunctionType())
10167 DiagType = 1;
10168 else if (ArgType->isArrayType())
10169 DiagType = 2;
10170
10171 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_pointer_abs) << DiagType << ArgType;
10172 return;
10173 }
10174
10175 // std::abs has overloads which prevent most of the absolute value problems
10176 // from occurring.
10177 if (IsStdAbs)
10178 return;
10179
10180 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(T: ArgType);
10181 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(T: ParamType);
10182
10183 // The argument and parameter are the same kind. Check if they are the right
10184 // size.
10185 if (ArgValueKind == ParamValueKind) {
10186 if (Context.getTypeSize(T: ArgType) <= Context.getTypeSize(T: ParamType))
10187 return;
10188
10189 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: AbsKind);
10190 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_abs_too_small)
10191 << FDecl << ArgType << ParamType;
10192
10193 if (NewAbsKind == 0)
10194 return;
10195
10196 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10197 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10198 return;
10199 }
10200
10201 // ArgValueKind != ParamValueKind
10202 // The wrong type of absolute value function was used. Attempt to find the
10203 // proper one.
10204 unsigned NewAbsKind = changeAbsFunction(AbsKind, ValueKind: ArgValueKind);
10205 NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: NewAbsKind);
10206 if (NewAbsKind == 0)
10207 return;
10208
10209 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_wrong_absolute_value_type)
10210 << FDecl << ParamValueKind << ArgValueKind;
10211
10212 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10213 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10214}
10215
10216//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10217void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10218 const FunctionDecl *FDecl) {
10219 if (!Call || !FDecl) return;
10220
10221 // Ignore template specializations and macros.
10222 if (inTemplateInstantiation()) return;
10223 if (Call->getExprLoc().isMacroID()) return;
10224
10225 // Only care about the one template argument, two function parameter std::max
10226 if (Call->getNumArgs() != 2) return;
10227 if (!IsStdFunction(FDecl, Str: "max")) return;
10228 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10229 if (!ArgList) return;
10230 if (ArgList->size() != 1) return;
10231
10232 // Check that template type argument is unsigned integer.
10233 const auto& TA = ArgList->get(Idx: 0);
10234 if (TA.getKind() != TemplateArgument::Type) return;
10235 QualType ArgType = TA.getAsType();
10236 if (!ArgType->isUnsignedIntegerType()) return;
10237
10238 // See if either argument is a literal zero.
10239 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10240 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E);
10241 if (!MTE) return false;
10242 const auto *Num = dyn_cast<IntegerLiteral>(Val: MTE->getSubExpr());
10243 if (!Num) return false;
10244 if (Num->getValue() != 0) return false;
10245 return true;
10246 };
10247
10248 const Expr *FirstArg = Call->getArg(Arg: 0);
10249 const Expr *SecondArg = Call->getArg(Arg: 1);
10250 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10251 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10252
10253 // Only warn when exactly one argument is zero.
10254 if (IsFirstArgZero == IsSecondArgZero) return;
10255
10256 SourceRange FirstRange = FirstArg->getSourceRange();
10257 SourceRange SecondRange = SecondArg->getSourceRange();
10258
10259 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10260
10261 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_max_unsigned_zero)
10262 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10263
10264 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10265 SourceRange RemovalRange;
10266 if (IsFirstArgZero) {
10267 RemovalRange = SourceRange(FirstRange.getBegin(),
10268 SecondRange.getBegin().getLocWithOffset(Offset: -1));
10269 } else {
10270 RemovalRange = SourceRange(getLocForEndOfToken(Loc: FirstRange.getEnd()),
10271 SecondRange.getEnd());
10272 }
10273
10274 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_max_call)
10275 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange())
10276 << FixItHint::CreateRemoval(RemoveRange: RemovalRange);
10277}
10278
10279//===--- CHECK: Standard memory functions ---------------------------------===//
10280
10281/// Takes the expression passed to the size_t parameter of functions
10282/// such as memcmp, strncat, etc and warns if it's a comparison.
10283///
10284/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10285static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10286 const IdentifierInfo *FnName,
10287 SourceLocation FnLoc,
10288 SourceLocation RParenLoc) {
10289 const auto *Size = dyn_cast<BinaryOperator>(Val: E);
10290 if (!Size)
10291 return false;
10292
10293 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10294 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10295 return false;
10296
10297 SourceRange SizeRange = Size->getSourceRange();
10298 S.Diag(Loc: Size->getOperatorLoc(), DiagID: diag::warn_memsize_comparison)
10299 << SizeRange << FnName;
10300 S.Diag(Loc: FnLoc, DiagID: diag::note_memsize_comparison_paren)
10301 << FnName
10302 << FixItHint::CreateInsertion(
10303 InsertionLoc: S.getLocForEndOfToken(Loc: Size->getLHS()->getEndLoc()), Code: ")")
10304 << FixItHint::CreateRemoval(RemoveRange: RParenLoc);
10305 S.Diag(Loc: SizeRange.getBegin(), DiagID: diag::note_memsize_comparison_cast_silence)
10306 << FixItHint::CreateInsertion(InsertionLoc: SizeRange.getBegin(), Code: "(size_t)(")
10307 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: SizeRange.getEnd()),
10308 Code: ")");
10309
10310 return true;
10311}
10312
10313/// Determine whether the given type is or contains a dynamic class type
10314/// (e.g., whether it has a vtable).
10315static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10316 bool &IsContained) {
10317 // Look through array types while ignoring qualifiers.
10318 const Type *Ty = T->getBaseElementTypeUnsafe();
10319 IsContained = false;
10320
10321 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10322 RD = RD ? RD->getDefinition() : nullptr;
10323 if (!RD || RD->isInvalidDecl())
10324 return nullptr;
10325
10326 if (RD->isDynamicClass())
10327 return RD;
10328
10329 // Check all the fields. If any bases were dynamic, the class is dynamic.
10330 // It's impossible for a class to transitively contain itself by value, so
10331 // infinite recursion is impossible.
10332 for (auto *FD : RD->fields()) {
10333 bool SubContained;
10334 if (const CXXRecordDecl *ContainedRD =
10335 getContainedDynamicClass(T: FD->getType(), IsContained&: SubContained)) {
10336 IsContained = true;
10337 return ContainedRD;
10338 }
10339 }
10340
10341 return nullptr;
10342}
10343
10344static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10345 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: E))
10346 if (Unary->getKind() == UETT_SizeOf)
10347 return Unary;
10348 return nullptr;
10349}
10350
10351/// If E is a sizeof expression, returns its argument expression,
10352/// otherwise returns NULL.
10353static const Expr *getSizeOfExprArg(const Expr *E) {
10354 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10355 if (!SizeOf->isArgumentType())
10356 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10357 return nullptr;
10358}
10359
10360/// If E is a sizeof expression, returns its argument type.
10361static QualType getSizeOfArgType(const Expr *E) {
10362 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10363 return SizeOf->getTypeOfArgument();
10364 return QualType();
10365}
10366
10367namespace {
10368
10369struct SearchNonTrivialToInitializeField
10370 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10371 using Super =
10372 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10373
10374 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10375
10376 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10377 SourceLocation SL) {
10378 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
10379 asDerived().visitArray(PDIK, AT, SL);
10380 return;
10381 }
10382
10383 Super::visitWithKind(PDIK, FT, Args&: SL);
10384 }
10385
10386 void visitARCStrong(QualType FT, SourceLocation SL) {
10387 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
10388 }
10389 void visitARCWeak(QualType FT, SourceLocation SL) {
10390 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
10391 }
10392 void visitStruct(QualType FT, SourceLocation SL) {
10393 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10394 visit(FT: FD->getType(), Args: FD->getLocation());
10395 }
10396 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10397 const ArrayType *AT, SourceLocation SL) {
10398 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
10399 }
10400 void visitTrivial(QualType FT, SourceLocation SL) {}
10401
10402 static void diag(QualType RT, const Expr *E, Sema &S) {
10403 SearchNonTrivialToInitializeField(E, S).visitStruct(FT: RT, SL: SourceLocation());
10404 }
10405
10406 ASTContext &getContext() { return S.getASTContext(); }
10407
10408 const Expr *E;
10409 Sema &S;
10410};
10411
10412struct SearchNonTrivialToCopyField
10413 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10414 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10415
10416 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10417
10418 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10419 SourceLocation SL) {
10420 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
10421 asDerived().visitArray(PCK, AT, SL);
10422 return;
10423 }
10424
10425 Super::visitWithKind(PCK, FT, Args&: SL);
10426 }
10427
10428 void visitARCStrong(QualType FT, SourceLocation SL) {
10429 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10430 }
10431 void visitARCWeak(QualType FT, SourceLocation SL) {
10432 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10433 }
10434 void visitPtrAuth(QualType FT, SourceLocation SL) {
10435 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10436 }
10437 void visitStruct(QualType FT, SourceLocation SL) {
10438 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10439 visit(FT: FD->getType(), Args: FD->getLocation());
10440 }
10441 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10442 SourceLocation SL) {
10443 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
10444 }
10445 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10446 SourceLocation SL) {}
10447 void visitTrivial(QualType FT, SourceLocation SL) {}
10448 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10449
10450 static void diag(QualType RT, const Expr *E, Sema &S) {
10451 SearchNonTrivialToCopyField(E, S).visitStruct(FT: RT, SL: SourceLocation());
10452 }
10453
10454 ASTContext &getContext() { return S.getASTContext(); }
10455
10456 const Expr *E;
10457 Sema &S;
10458};
10459
10460}
10461
10462/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10463static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10464 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10465
10466 if (const auto *BO = dyn_cast<BinaryOperator>(Val: SizeofExpr)) {
10467 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10468 return false;
10469
10470 return doesExprLikelyComputeSize(SizeofExpr: BO->getLHS()) ||
10471 doesExprLikelyComputeSize(SizeofExpr: BO->getRHS());
10472 }
10473
10474 return getAsSizeOfExpr(E: SizeofExpr) != nullptr;
10475}
10476
10477/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10478///
10479/// \code
10480/// #define MACRO 0
10481/// foo(MACRO);
10482/// foo(0);
10483/// \endcode
10484///
10485/// This should return true for the first call to foo, but not for the second
10486/// (regardless of whether foo is a macro or function).
10487static bool isArgumentExpandedFromMacro(SourceManager &SM,
10488 SourceLocation CallLoc,
10489 SourceLocation ArgLoc) {
10490 if (!CallLoc.isMacroID())
10491 return SM.getFileID(SpellingLoc: CallLoc) != SM.getFileID(SpellingLoc: ArgLoc);
10492
10493 return SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: CallLoc)) !=
10494 SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: ArgLoc));
10495}
10496
10497/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10498/// last two arguments transposed.
10499static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10500 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10501 return;
10502
10503 const Expr *SizeArg =
10504 Call->getArg(Arg: BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10505
10506 auto isLiteralZero = [](const Expr *E) {
10507 return (isa<IntegerLiteral>(Val: E) &&
10508 cast<IntegerLiteral>(Val: E)->getValue() == 0) ||
10509 (isa<CharacterLiteral>(Val: E) &&
10510 cast<CharacterLiteral>(Val: E)->getValue() == 0);
10511 };
10512
10513 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10514 SourceLocation CallLoc = Call->getRParenLoc();
10515 SourceManager &SM = S.getSourceManager();
10516 if (isLiteralZero(SizeArg) &&
10517 !isArgumentExpandedFromMacro(SM, CallLoc, ArgLoc: SizeArg->getExprLoc())) {
10518
10519 SourceLocation DiagLoc = SizeArg->getExprLoc();
10520
10521 // Some platforms #define bzero to __builtin_memset. See if this is the
10522 // case, and if so, emit a better diagnostic.
10523 if (BId == Builtin::BIbzero ||
10524 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10525 Loc: CallLoc, SM, LangOpts: S.getLangOpts()) == "bzero")) {
10526 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_bzero_size);
10527 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_bzero_size_silence);
10528 } else if (!isLiteralZero(Call->getArg(Arg: 1)->IgnoreImpCasts())) {
10529 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 0;
10530 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 0;
10531 }
10532 return;
10533 }
10534
10535 // If the second argument to a memset is a sizeof expression and the third
10536 // isn't, this is also likely an error. This should catch
10537 // 'memset(buf, sizeof(buf), 0xff)'.
10538 if (BId == Builtin::BImemset &&
10539 doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 1)) &&
10540 !doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 2))) {
10541 SourceLocation DiagLoc = Call->getArg(Arg: 1)->getExprLoc();
10542 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 1;
10543 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 1;
10544 return;
10545 }
10546}
10547
10548void Sema::CheckMemaccessArguments(const CallExpr *Call,
10549 unsigned BId,
10550 IdentifierInfo *FnName) {
10551 assert(BId != 0);
10552
10553 // It is possible to have a non-standard definition of memset. Validate
10554 // we have enough arguments, and if not, abort further checking.
10555 unsigned ExpectedNumArgs =
10556 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10557 if (Call->getNumArgs() < ExpectedNumArgs)
10558 return;
10559
10560 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10561 BId == Builtin::BIstrndup ? 1 : 2);
10562 unsigned LenArg =
10563 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10564 const Expr *LenExpr = Call->getArg(Arg: LenArg)->IgnoreParenImpCasts();
10565
10566 if (CheckMemorySizeofForComparison(S&: *this, E: LenExpr, FnName,
10567 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
10568 return;
10569
10570 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10571 CheckMemaccessSize(S&: *this, BId, Call);
10572
10573 // We have special checking when the length is a sizeof expression.
10574 QualType SizeOfArgTy = getSizeOfArgType(E: LenExpr);
10575
10576 // Although widely used, 'bzero' is not a standard function. Be more strict
10577 // with the argument types before allowing diagnostics and only allow the
10578 // form bzero(ptr, sizeof(...)).
10579 QualType FirstArgTy = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
10580 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10581 return;
10582
10583 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10584 const Expr *Dest = Call->getArg(Arg: ArgIdx)->IgnoreParenImpCasts();
10585 SourceRange ArgRange = Call->getArg(Arg: ArgIdx)->getSourceRange();
10586
10587 QualType DestTy = Dest->getType();
10588 QualType PointeeTy;
10589 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10590 PointeeTy = DestPtrTy->getPointeeType();
10591
10592 // Never warn about void type pointers. This can be used to suppress
10593 // false positives.
10594 if (PointeeTy->isVoidType())
10595 continue;
10596
10597 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10598 // actually comparing the expressions for equality. Because computing the
10599 // expression IDs can be expensive, we only do this if the diagnostic is
10600 // enabled.
10601 if (CheckSizeofMemaccessArgument(SizeOfArg: LenExpr, Dest, FnName))
10602 break;
10603
10604 // Also check for cases where the sizeof argument is the exact same
10605 // type as the memory argument, and where it points to a user-defined
10606 // record type.
10607 if (SizeOfArgTy != QualType()) {
10608 if (PointeeTy->isRecordType() &&
10609 Context.typesAreCompatible(T1: SizeOfArgTy, T2: DestTy)) {
10610 DiagRuntimeBehavior(Loc: LenExpr->getExprLoc(), Statement: Dest,
10611 PD: PDiag(DiagID: diag::warn_sizeof_pointer_type_memaccess)
10612 << FnName << SizeOfArgTy << ArgIdx
10613 << PointeeTy << Dest->getSourceRange()
10614 << LenExpr->getSourceRange());
10615 break;
10616 }
10617 }
10618 } else if (DestTy->isArrayType()) {
10619 PointeeTy = DestTy;
10620 }
10621
10622 if (PointeeTy == QualType())
10623 continue;
10624
10625 // Always complain about dynamic classes.
10626 bool IsContained;
10627 if (const CXXRecordDecl *ContainedRD =
10628 getContainedDynamicClass(T: PointeeTy, IsContained)) {
10629
10630 unsigned OperationType = 0;
10631 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10632 // "overwritten" if we're warning about the destination for any call
10633 // but memcmp; otherwise a verb appropriate to the call.
10634 if (ArgIdx != 0 || IsCmp) {
10635 if (BId == Builtin::BImemcpy)
10636 OperationType = 1;
10637 else if(BId == Builtin::BImemmove)
10638 OperationType = 2;
10639 else if (IsCmp)
10640 OperationType = 3;
10641 }
10642
10643 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10644 PD: PDiag(DiagID: diag::warn_dyn_class_memaccess)
10645 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10646 << IsContained << ContainedRD << OperationType
10647 << Call->getCallee()->getSourceRange());
10648 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10649 BId != Builtin::BImemset)
10650 DiagRuntimeBehavior(
10651 Loc: Dest->getExprLoc(), Statement: Dest,
10652 PD: PDiag(DiagID: diag::warn_arc_object_memaccess)
10653 << ArgIdx << FnName << PointeeTy
10654 << Call->getCallee()->getSourceRange());
10655 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
10656
10657 // FIXME: Do not consider incomplete types even though they may be
10658 // completed later. GCC does not diagnose such code, but we may want to
10659 // consider diagnosing it in the future, perhaps under a different, but
10660 // related, diagnostic group.
10661 bool NonTriviallyCopyableCXXRecord =
10662 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
10663 !PointeeTy.isTriviallyCopyableType(Context);
10664
10665 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10666 RD->isNonTrivialToPrimitiveDefaultInitialize()) {
10667 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10668 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
10669 << ArgIdx << FnName << PointeeTy << 0);
10670 SearchNonTrivialToInitializeField::diag(RT: PointeeTy, E: Dest, S&: *this);
10671 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10672 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10673 // FIXME: Limiting this warning to dest argument until we decide
10674 // whether it's valid for source argument too.
10675 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10676 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
10677 << FnName << PointeeTy);
10678 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10679 RD->isNonTrivialToPrimitiveCopy()) {
10680 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10681 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
10682 << ArgIdx << FnName << PointeeTy << 1);
10683 SearchNonTrivialToCopyField::diag(RT: PointeeTy, E: Dest, S&: *this);
10684 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10685 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
10686 // FIXME: Limiting this warning to dest argument until we decide
10687 // whether it's valid for source argument too.
10688 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
10689 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
10690 << FnName << PointeeTy);
10691 } else {
10692 continue;
10693 }
10694 } else
10695 continue;
10696
10697 DiagRuntimeBehavior(
10698 Loc: Dest->getExprLoc(), Statement: Dest,
10699 PD: PDiag(DiagID: diag::note_bad_memaccess_silence)
10700 << FixItHint::CreateInsertion(InsertionLoc: ArgRange.getBegin(), Code: "(void*)"));
10701 break;
10702 }
10703}
10704
10705bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
10706 IdentifierInfo *FnName) {
10707 llvm::FoldingSetNodeID SizeOfArgID;
10708 const Expr *SizeOfArg = getSizeOfExprArg(E: LenExpr);
10709 if (!SizeOfArg)
10710 return false;
10711 // Computing this warning is expensive, so we only do so if the warning is
10712 // enabled.
10713 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess,
10714 Loc: SizeOfArg->getExprLoc()))
10715 return false;
10716 QualType DestTy = Dest->getType();
10717 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
10718 if (!DestPtrTy)
10719 return false;
10720
10721 QualType PointeeTy = DestPtrTy->getPointeeType();
10722
10723 if (SizeOfArgID == llvm::FoldingSetNodeID())
10724 SizeOfArg->Profile(ID&: SizeOfArgID, Context, Canonical: true);
10725
10726 llvm::FoldingSetNodeID DestID;
10727 Dest->Profile(ID&: DestID, Context, Canonical: true);
10728 if (DestID == SizeOfArgID) {
10729 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10730 // over sizeof(src) as well.
10731 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10732 StringRef ReadableName = FnName->getName();
10733
10734 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Val: Dest);
10735 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
10736 ActionIdx = 1; // If its an address-of operator, just remove it.
10737 if (!PointeeTy->isIncompleteType() &&
10738 (Context.getTypeSize(T: PointeeTy) == Context.getCharWidth()))
10739 ActionIdx = 2; // If the pointee's size is sizeof(char),
10740 // suggest an explicit length.
10741
10742 // If the function is defined as a builtin macro, do not show macro
10743 // expansion.
10744 SourceLocation SL = SizeOfArg->getExprLoc();
10745 SourceRange DSR = Dest->getSourceRange();
10746 SourceRange SSR = SizeOfArg->getSourceRange();
10747 SourceManager &SM = getSourceManager();
10748
10749 if (SM.isMacroArgExpansion(Loc: SL)) {
10750 ReadableName = Lexer::getImmediateMacroName(Loc: SL, SM, LangOpts);
10751 SL = SM.getSpellingLoc(Loc: SL);
10752 DSR = SourceRange(SM.getSpellingLoc(Loc: DSR.getBegin()),
10753 SM.getSpellingLoc(Loc: DSR.getEnd()));
10754 SSR = SourceRange(SM.getSpellingLoc(Loc: SSR.getBegin()),
10755 SM.getSpellingLoc(Loc: SSR.getEnd()));
10756 }
10757
10758 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
10759 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess)
10760 << ReadableName << PointeeTy << DestTy << DSR
10761 << SSR);
10762 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
10763 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess_note)
10764 << ActionIdx << SSR);
10765 return true;
10766 }
10767 return false;
10768}
10769
10770// A little helper routine: ignore addition and subtraction of integer literals.
10771// This intentionally does not ignore all integer constant expressions because
10772// we don't want to remove sizeof().
10773static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10774 Ex = Ex->IgnoreParenCasts();
10775
10776 while (true) {
10777 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Val: Ex);
10778 if (!BO || !BO->isAdditiveOp())
10779 break;
10780
10781 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10782 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10783
10784 if (isa<IntegerLiteral>(Val: RHS))
10785 Ex = LHS;
10786 else if (isa<IntegerLiteral>(Val: LHS))
10787 Ex = RHS;
10788 else
10789 break;
10790 }
10791
10792 return Ex;
10793}
10794
10795static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10796 ASTContext &Context) {
10797 // Only handle constant-sized or VLAs, but not flexible members.
10798 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T: Ty)) {
10799 // Only issue the FIXIT for arrays of size > 1.
10800 if (CAT->getZExtSize() <= 1)
10801 return false;
10802 } else if (!Ty->isVariableArrayType()) {
10803 return false;
10804 }
10805 return true;
10806}
10807
10808void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10809 IdentifierInfo *FnName) {
10810
10811 // Don't crash if the user has the wrong number of arguments
10812 unsigned NumArgs = Call->getNumArgs();
10813 if ((NumArgs != 3) && (NumArgs != 4))
10814 return;
10815
10816 const Expr *SrcArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 1), Ctx&: Context);
10817 const Expr *SizeArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 2), Ctx&: Context);
10818 const Expr *CompareWithSrc = nullptr;
10819
10820 if (CheckMemorySizeofForComparison(S&: *this, E: SizeArg, FnName,
10821 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
10822 return;
10823
10824 // Look for 'strlcpy(dst, x, sizeof(x))'
10825 if (const Expr *Ex = getSizeOfExprArg(E: SizeArg))
10826 CompareWithSrc = Ex;
10827 else {
10828 // Look for 'strlcpy(dst, x, strlen(x))'
10829 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(Val: SizeArg)) {
10830 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10831 SizeCall->getNumArgs() == 1)
10832 CompareWithSrc = ignoreLiteralAdditions(Ex: SizeCall->getArg(Arg: 0), Ctx&: Context);
10833 }
10834 }
10835
10836 if (!CompareWithSrc)
10837 return;
10838
10839 // Determine if the argument to sizeof/strlen is equal to the source
10840 // argument. In principle there's all kinds of things you could do
10841 // here, for instance creating an == expression and evaluating it with
10842 // EvaluateAsBooleanCondition, but this uses a more direct technique:
10843 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(Val: SrcArg);
10844 if (!SrcArgDRE)
10845 return;
10846
10847 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(Val: CompareWithSrc);
10848 if (!CompareWithSrcDRE ||
10849 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10850 return;
10851
10852 const Expr *OriginalSizeArg = Call->getArg(Arg: 2);
10853 Diag(Loc: CompareWithSrcDRE->getBeginLoc(), DiagID: diag::warn_strlcpycat_wrong_size)
10854 << OriginalSizeArg->getSourceRange() << FnName;
10855
10856 // Output a FIXIT hint if the destination is an array (rather than a
10857 // pointer to an array). This could be enhanced to handle some
10858 // pointers if we know the actual size, like if DstArg is 'array+2'
10859 // we could say 'sizeof(array)-2'.
10860 const Expr *DstArg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
10861 if (!isConstantSizeArrayWithMoreThanOneElement(Ty: DstArg->getType(), Context))
10862 return;
10863
10864 SmallString<128> sizeString;
10865 llvm::raw_svector_ostream OS(sizeString);
10866 OS << "sizeof(";
10867 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
10868 OS << ")";
10869
10870 Diag(Loc: OriginalSizeArg->getBeginLoc(), DiagID: diag::note_strlcpycat_wrong_size)
10871 << FixItHint::CreateReplacement(RemoveRange: OriginalSizeArg->getSourceRange(),
10872 Code: OS.str());
10873}
10874
10875/// Check if two expressions refer to the same declaration.
10876static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10877 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(Val: E1))
10878 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(Val: E2))
10879 return D1->getDecl() == D2->getDecl();
10880 return false;
10881}
10882
10883static const Expr *getStrlenExprArg(const Expr *E) {
10884 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
10885 const FunctionDecl *FD = CE->getDirectCallee();
10886 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10887 return nullptr;
10888 return CE->getArg(Arg: 0)->IgnoreParenCasts();
10889 }
10890 return nullptr;
10891}
10892
10893void Sema::CheckStrncatArguments(const CallExpr *CE,
10894 const IdentifierInfo *FnName) {
10895 // Don't crash if the user has the wrong number of arguments.
10896 if (CE->getNumArgs() < 3)
10897 return;
10898 const Expr *DstArg = CE->getArg(Arg: 0)->IgnoreParenCasts();
10899 const Expr *SrcArg = CE->getArg(Arg: 1)->IgnoreParenCasts();
10900 const Expr *LenArg = CE->getArg(Arg: 2)->IgnoreParenCasts();
10901
10902 if (CheckMemorySizeofForComparison(S&: *this, E: LenArg, FnName, FnLoc: CE->getBeginLoc(),
10903 RParenLoc: CE->getRParenLoc()))
10904 return;
10905
10906 // Identify common expressions, which are wrongly used as the size argument
10907 // to strncat and may lead to buffer overflows.
10908 unsigned PatternType = 0;
10909 if (const Expr *SizeOfArg = getSizeOfExprArg(E: LenArg)) {
10910 // - sizeof(dst)
10911 if (referToTheSameDecl(E1: SizeOfArg, E2: DstArg))
10912 PatternType = 1;
10913 // - sizeof(src)
10914 else if (referToTheSameDecl(E1: SizeOfArg, E2: SrcArg))
10915 PatternType = 2;
10916 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Val: LenArg)) {
10917 if (BE->getOpcode() == BO_Sub) {
10918 const Expr *L = BE->getLHS()->IgnoreParenCasts();
10919 const Expr *R = BE->getRHS()->IgnoreParenCasts();
10920 // - sizeof(dst) - strlen(dst)
10921 if (referToTheSameDecl(E1: DstArg, E2: getSizeOfExprArg(E: L)) &&
10922 referToTheSameDecl(E1: DstArg, E2: getStrlenExprArg(E: R)))
10923 PatternType = 1;
10924 // - sizeof(src) - (anything)
10925 else if (referToTheSameDecl(E1: SrcArg, E2: getSizeOfExprArg(E: L)))
10926 PatternType = 2;
10927 }
10928 }
10929
10930 if (PatternType == 0)
10931 return;
10932
10933 // Generate the diagnostic.
10934 SourceLocation SL = LenArg->getBeginLoc();
10935 SourceRange SR = LenArg->getSourceRange();
10936 SourceManager &SM = getSourceManager();
10937
10938 // If the function is defined as a builtin macro, do not show macro expansion.
10939 if (SM.isMacroArgExpansion(Loc: SL)) {
10940 SL = SM.getSpellingLoc(Loc: SL);
10941 SR = SourceRange(SM.getSpellingLoc(Loc: SR.getBegin()),
10942 SM.getSpellingLoc(Loc: SR.getEnd()));
10943 }
10944
10945 // Check if the destination is an array (rather than a pointer to an array).
10946 QualType DstTy = DstArg->getType();
10947 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(Ty: DstTy,
10948 Context);
10949 if (!isKnownSizeArray) {
10950 if (PatternType == 1)
10951 Diag(Loc: SL, DiagID: diag::warn_strncat_wrong_size) << SR;
10952 else
10953 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
10954 return;
10955 }
10956
10957 if (PatternType == 1)
10958 Diag(Loc: SL, DiagID: diag::warn_strncat_large_size) << SR;
10959 else
10960 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
10961
10962 SmallString<128> sizeString;
10963 llvm::raw_svector_ostream OS(sizeString);
10964 OS << "sizeof(";
10965 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
10966 OS << ") - ";
10967 OS << "strlen(";
10968 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
10969 OS << ") - 1";
10970
10971 Diag(Loc: SL, DiagID: diag::note_strncat_wrong_size)
10972 << FixItHint::CreateReplacement(RemoveRange: SR, Code: OS.str());
10973}
10974
10975namespace {
10976void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10977 const UnaryOperator *UnaryExpr, const Decl *D) {
10978 if (isa<FieldDecl, FunctionDecl, VarDecl>(Val: D)) {
10979 S.Diag(Loc: UnaryExpr->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
10980 << CalleeName << 0 /*object: */ << cast<NamedDecl>(Val: D);
10981 return;
10982 }
10983}
10984
10985void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10986 const UnaryOperator *UnaryExpr) {
10987 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: UnaryExpr->getSubExpr())) {
10988 const Decl *D = Lvalue->getDecl();
10989 if (const auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
10990 if (!DD->getType()->isReferenceType())
10991 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10992 }
10993 }
10994
10995 if (const auto *Lvalue = dyn_cast<MemberExpr>(Val: UnaryExpr->getSubExpr()))
10996 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10997 D: Lvalue->getMemberDecl());
10998}
10999
11000void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11001 const UnaryOperator *UnaryExpr) {
11002 const auto *Lambda = dyn_cast<LambdaExpr>(
11003 Val: UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11004 if (!Lambda)
11005 return;
11006
11007 S.Diag(Loc: Lambda->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11008 << CalleeName << 2 /*object: lambda expression*/;
11009}
11010
11011void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11012 const DeclRefExpr *Lvalue) {
11013 const auto *Var = dyn_cast<VarDecl>(Val: Lvalue->getDecl());
11014 if (Var == nullptr)
11015 return;
11016
11017 S.Diag(Loc: Lvalue->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11018 << CalleeName << 0 /*object: */ << Var;
11019}
11020
11021void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11022 const CastExpr *Cast) {
11023 SmallString<128> SizeString;
11024 llvm::raw_svector_ostream OS(SizeString);
11025
11026 clang::CastKind Kind = Cast->getCastKind();
11027 if (Kind == clang::CK_BitCast &&
11028 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11029 return;
11030 if (Kind == clang::CK_IntegralToPointer &&
11031 !isa<IntegerLiteral>(
11032 Val: Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11033 return;
11034
11035 switch (Cast->getCastKind()) {
11036 case clang::CK_BitCast:
11037 case clang::CK_IntegralToPointer:
11038 case clang::CK_FunctionToPointerDecay:
11039 OS << '\'';
11040 Cast->printPretty(OS, Helper: nullptr, Policy: S.getPrintingPolicy());
11041 OS << '\'';
11042 break;
11043 default:
11044 return;
11045 }
11046
11047 S.Diag(Loc: Cast->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11048 << CalleeName << 0 /*object: */ << OS.str();
11049}
11050} // namespace
11051
11052void Sema::CheckFreeArguments(const CallExpr *E) {
11053 const std::string CalleeName =
11054 cast<FunctionDecl>(Val: E->getCalleeDecl())->getQualifiedNameAsString();
11055
11056 { // Prefer something that doesn't involve a cast to make things simpler.
11057 const Expr *Arg = E->getArg(Arg: 0)->IgnoreParenCasts();
11058 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Val: Arg))
11059 switch (UnaryExpr->getOpcode()) {
11060 case UnaryOperator::Opcode::UO_AddrOf:
11061 return CheckFreeArgumentsAddressof(S&: *this, CalleeName, UnaryExpr);
11062 case UnaryOperator::Opcode::UO_Plus:
11063 return CheckFreeArgumentsPlus(S&: *this, CalleeName, UnaryExpr);
11064 default:
11065 break;
11066 }
11067
11068 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: Arg))
11069 if (Lvalue->getType()->isArrayType())
11070 return CheckFreeArgumentsStackArray(S&: *this, CalleeName, Lvalue);
11071
11072 if (const auto *Label = dyn_cast<AddrLabelExpr>(Val: Arg)) {
11073 Diag(Loc: Label->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11074 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11075 return;
11076 }
11077
11078 if (isa<BlockExpr>(Val: Arg)) {
11079 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11080 << CalleeName << 1 /*object: block*/;
11081 return;
11082 }
11083 }
11084 // Maybe the cast was important, check after the other cases.
11085 if (const auto *Cast = dyn_cast<CastExpr>(Val: E->getArg(Arg: 0)))
11086 return CheckFreeArgumentsCast(S&: *this, CalleeName, Cast);
11087}
11088
11089void
11090Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11091 SourceLocation ReturnLoc,
11092 bool isObjCMethod,
11093 const AttrVec *Attrs,
11094 const FunctionDecl *FD) {
11095 // Check if the return value is null but should not be.
11096 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(container: *Attrs)) ||
11097 (!isObjCMethod && isNonNullType(type: lhsType))) &&
11098 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11099 Diag(Loc: ReturnLoc, DiagID: diag::warn_null_ret)
11100 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11101
11102 // C++11 [basic.stc.dynamic.allocation]p4:
11103 // If an allocation function declared with a non-throwing
11104 // exception-specification fails to allocate storage, it shall return
11105 // a null pointer. Any other allocation function that fails to allocate
11106 // storage shall indicate failure only by throwing an exception [...]
11107 if (FD) {
11108 OverloadedOperatorKind Op = FD->getOverloadedOperator();
11109 if (Op == OO_New || Op == OO_Array_New) {
11110 const FunctionProtoType *Proto
11111 = FD->getType()->castAs<FunctionProtoType>();
11112 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11113 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11114 Diag(Loc: ReturnLoc, DiagID: diag::warn_operator_new_returns_null)
11115 << FD << getLangOpts().CPlusPlus11;
11116 }
11117 }
11118
11119 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11120 Diag(Loc: ReturnLoc, DiagID: diag::err_wasm_table_art) << 1;
11121 }
11122
11123 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11124 // here prevent the user from using a PPC MMA type as trailing return type.
11125 if (Context.getTargetInfo().getTriple().isPPC64())
11126 PPC().CheckPPCMMAType(Type: RetValExp->getType(), TypeLoc: ReturnLoc);
11127}
11128
11129void Sema::CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
11130 const Expr *RHS, BinaryOperatorKind Opcode) {
11131 if (!BinaryOperator::isEqualityOp(Opc: Opcode))
11132 return;
11133
11134 // Match and capture subexpressions such as "(float) X == 0.1".
11135 const FloatingLiteral *FPLiteral;
11136 const CastExpr *FPCast;
11137 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11138 FPLiteral = dyn_cast<FloatingLiteral>(Val: L->IgnoreParens());
11139 FPCast = dyn_cast<CastExpr>(Val: R->IgnoreParens());
11140 return FPLiteral && FPCast;
11141 };
11142
11143 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11144 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11145 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11146 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11147 TargetTy->isFloatingPoint()) {
11148 bool Lossy;
11149 llvm::APFloat TargetC = FPLiteral->getValue();
11150 TargetC.convert(ToSemantics: Context.getFloatTypeSemantics(T: QualType(SourceTy, 0)),
11151 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Lossy);
11152 if (Lossy) {
11153 // If the literal cannot be represented in the source type, then a
11154 // check for == is always false and check for != is always true.
11155 Diag(Loc, DiagID: diag::warn_float_compare_literal)
11156 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11157 << LHS->getSourceRange() << RHS->getSourceRange();
11158 return;
11159 }
11160 }
11161 }
11162
11163 // Match a more general floating-point equality comparison (-Wfloat-equal).
11164 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11165 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11166
11167 // Special case: check for x == x (which is OK).
11168 // Do not emit warnings for such cases.
11169 if (const auto *DRL = dyn_cast<DeclRefExpr>(Val: LeftExprSansParen))
11170 if (const auto *DRR = dyn_cast<DeclRefExpr>(Val: RightExprSansParen))
11171 if (DRL->getDecl() == DRR->getDecl())
11172 return;
11173
11174 // Special case: check for comparisons against literals that can be exactly
11175 // represented by APFloat. In such cases, do not emit a warning. This
11176 // is a heuristic: often comparison against such literals are used to
11177 // detect if a value in a variable has not changed. This clearly can
11178 // lead to false negatives.
11179 if (const auto *FLL = dyn_cast<FloatingLiteral>(Val: LeftExprSansParen)) {
11180 if (FLL->isExact())
11181 return;
11182 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(Val: RightExprSansParen))
11183 if (FLR->isExact())
11184 return;
11185
11186 // Check for comparisons with builtin types.
11187 if (const auto *CL = dyn_cast<CallExpr>(Val: LeftExprSansParen);
11188 CL && CL->getBuiltinCallee())
11189 return;
11190
11191 if (const auto *CR = dyn_cast<CallExpr>(Val: RightExprSansParen);
11192 CR && CR->getBuiltinCallee())
11193 return;
11194
11195 // Emit the diagnostic.
11196 Diag(Loc, DiagID: diag::warn_floatingpoint_eq)
11197 << LHS->getSourceRange() << RHS->getSourceRange();
11198}
11199
11200//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11201//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11202
11203namespace {
11204
11205/// Structure recording the 'active' range of an integer-valued
11206/// expression.
11207struct IntRange {
11208 /// The number of bits active in the int. Note that this includes exactly one
11209 /// sign bit if !NonNegative.
11210 unsigned Width;
11211
11212 /// True if the int is known not to have negative values. If so, all leading
11213 /// bits before Width are known zero, otherwise they are known to be the
11214 /// same as the MSB within Width.
11215 bool NonNegative;
11216
11217 IntRange(unsigned Width, bool NonNegative)
11218 : Width(Width), NonNegative(NonNegative) {}
11219
11220 /// Number of bits excluding the sign bit.
11221 unsigned valueBits() const {
11222 return NonNegative ? Width : Width - 1;
11223 }
11224
11225 /// Returns the range of the bool type.
11226 static IntRange forBoolType() {
11227 return IntRange(1, true);
11228 }
11229
11230 /// Returns the range of an opaque value of the given integral type.
11231 static IntRange forValueOfType(ASTContext &C, QualType T) {
11232 return forValueOfCanonicalType(C,
11233 T: T->getCanonicalTypeInternal().getTypePtr());
11234 }
11235
11236 /// Returns the range of an opaque value of a canonical integral type.
11237 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11238 assert(T->isCanonicalUnqualified());
11239
11240 if (const auto *VT = dyn_cast<VectorType>(Val: T))
11241 T = VT->getElementType().getTypePtr();
11242 if (const auto *CT = dyn_cast<ComplexType>(Val: T))
11243 T = CT->getElementType().getTypePtr();
11244 if (const auto *AT = dyn_cast<AtomicType>(Val: T))
11245 T = AT->getValueType().getTypePtr();
11246 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11247 T = OBT->getUnderlyingType().getTypePtr();
11248
11249 if (!C.getLangOpts().CPlusPlus) {
11250 // For enum types in C code, use the underlying datatype.
11251 if (const auto *ED = T->getAsEnumDecl())
11252 T = ED->getIntegerType().getDesugaredType(Context: C).getTypePtr();
11253 } else if (auto *Enum = T->getAsEnumDecl()) {
11254 // For enum types in C++, use the known bit width of the enumerators.
11255 // In C++11, enums can have a fixed underlying type. Use this type to
11256 // compute the range.
11257 if (Enum->isFixed()) {
11258 return IntRange(C.getIntWidth(T: QualType(T, 0)),
11259 !Enum->getIntegerType()->isSignedIntegerType());
11260 }
11261
11262 unsigned NumPositive = Enum->getNumPositiveBits();
11263 unsigned NumNegative = Enum->getNumNegativeBits();
11264
11265 if (NumNegative == 0)
11266 return IntRange(NumPositive, true/*NonNegative*/);
11267 else
11268 return IntRange(std::max(a: NumPositive + 1, b: NumNegative),
11269 false/*NonNegative*/);
11270 }
11271
11272 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11273 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11274
11275 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11276 assert(BT->isInteger());
11277
11278 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11279 }
11280
11281 /// Returns the "target" range of a canonical integral type, i.e.
11282 /// the range of values expressible in the type.
11283 ///
11284 /// This matches forValueOfCanonicalType except that enums have the
11285 /// full range of their type, not the range of their enumerators.
11286 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11287 assert(T->isCanonicalUnqualified());
11288
11289 if (const VectorType *VT = dyn_cast<VectorType>(Val: T))
11290 T = VT->getElementType().getTypePtr();
11291 if (const ComplexType *CT = dyn_cast<ComplexType>(Val: T))
11292 T = CT->getElementType().getTypePtr();
11293 if (const AtomicType *AT = dyn_cast<AtomicType>(Val: T))
11294 T = AT->getValueType().getTypePtr();
11295 if (const auto *ED = T->getAsEnumDecl())
11296 T = C.getCanonicalType(T: ED->getIntegerType()).getTypePtr();
11297 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11298 T = OBT->getUnderlyingType().getTypePtr();
11299
11300 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11301 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11302
11303 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11304 assert(BT->isInteger());
11305
11306 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11307 }
11308
11309 /// Returns the supremum of two ranges: i.e. their conservative merge.
11310 static IntRange join(IntRange L, IntRange R) {
11311 bool Unsigned = L.NonNegative && R.NonNegative;
11312 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
11313 L.NonNegative && R.NonNegative);
11314 }
11315
11316 /// Return the range of a bitwise-AND of the two ranges.
11317 static IntRange bit_and(IntRange L, IntRange R) {
11318 unsigned Bits = std::max(a: L.Width, b: R.Width);
11319 bool NonNegative = false;
11320 if (L.NonNegative) {
11321 Bits = std::min(a: Bits, b: L.Width);
11322 NonNegative = true;
11323 }
11324 if (R.NonNegative) {
11325 Bits = std::min(a: Bits, b: R.Width);
11326 NonNegative = true;
11327 }
11328 return IntRange(Bits, NonNegative);
11329 }
11330
11331 /// Return the range of a sum of the two ranges.
11332 static IntRange sum(IntRange L, IntRange R) {
11333 bool Unsigned = L.NonNegative && R.NonNegative;
11334 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + 1 + !Unsigned,
11335 Unsigned);
11336 }
11337
11338 /// Return the range of a difference of the two ranges.
11339 static IntRange difference(IntRange L, IntRange R) {
11340 // We need a 1-bit-wider range if:
11341 // 1) LHS can be negative: least value can be reduced.
11342 // 2) RHS can be negative: greatest value can be increased.
11343 bool CanWiden = !L.NonNegative || !R.NonNegative;
11344 bool Unsigned = L.NonNegative && R.Width == 0;
11345 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + CanWiden +
11346 !Unsigned,
11347 Unsigned);
11348 }
11349
11350 /// Return the range of a product of the two ranges.
11351 static IntRange product(IntRange L, IntRange R) {
11352 // If both LHS and RHS can be negative, we can form
11353 // -2^L * -2^R = 2^(L + R)
11354 // which requires L + R + 1 value bits to represent.
11355 bool CanWiden = !L.NonNegative && !R.NonNegative;
11356 bool Unsigned = L.NonNegative && R.NonNegative;
11357 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11358 Unsigned);
11359 }
11360
11361 /// Return the range of a remainder operation between the two ranges.
11362 static IntRange rem(IntRange L, IntRange R) {
11363 // The result of a remainder can't be larger than the result of
11364 // either side. The sign of the result is the sign of the LHS.
11365 bool Unsigned = L.NonNegative;
11366 return IntRange(std::min(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
11367 Unsigned);
11368 }
11369};
11370
11371} // namespace
11372
11373static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11374 if (value.isSigned() && value.isNegative())
11375 return IntRange(value.getSignificantBits(), false);
11376
11377 if (value.getBitWidth() > MaxWidth)
11378 value = value.trunc(width: MaxWidth);
11379
11380 // isNonNegative() just checks the sign bit without considering
11381 // signedness.
11382 return IntRange(value.getActiveBits(), true);
11383}
11384
11385static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11386 if (result.isInt())
11387 return GetValueRange(value&: result.getInt(), MaxWidth);
11388
11389 if (result.isVector()) {
11390 IntRange R = GetValueRange(result&: result.getVectorElt(I: 0), Ty, MaxWidth);
11391 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11392 IntRange El = GetValueRange(result&: result.getVectorElt(I: i), Ty, MaxWidth);
11393 R = IntRange::join(L: R, R: El);
11394 }
11395 return R;
11396 }
11397
11398 if (result.isComplexInt()) {
11399 IntRange R = GetValueRange(value&: result.getComplexIntReal(), MaxWidth);
11400 IntRange I = GetValueRange(value&: result.getComplexIntImag(), MaxWidth);
11401 return IntRange::join(L: R, R: I);
11402 }
11403
11404 // This can happen with lossless casts to intptr_t of "based" lvalues.
11405 // Assume it might use arbitrary bits.
11406 // FIXME: The only reason we need to pass the type in here is to get
11407 // the sign right on this one case. It would be nice if APValue
11408 // preserved this.
11409 assert(result.isLValue() || result.isAddrLabelDiff());
11410 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11411}
11412
11413static QualType GetExprType(const Expr *E) {
11414 QualType Ty = E->getType();
11415 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11416 Ty = AtomicRHS->getValueType();
11417 return Ty;
11418}
11419
11420/// Attempts to estimate an approximate range for the given integer expression.
11421/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11422/// reliable estimation cannot be determined.
11423///
11424/// \param MaxWidth The width to which the value will be truncated.
11425/// \param InConstantContext If \c true, interpret the expression within a
11426/// constant context.
11427/// \param Approximate If \c true, provide a likely range of values by assuming
11428/// that arithmetic on narrower types remains within those types.
11429/// If \c false, return a range that includes all possible values
11430/// resulting from the expression.
11431/// \returns A range of values that the expression might take, or
11432/// std::nullopt if a reliable estimation cannot be determined.
11433static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11434 unsigned MaxWidth,
11435 bool InConstantContext,
11436 bool Approximate) {
11437 E = E->IgnoreParens();
11438
11439 // Try a full evaluation first.
11440 Expr::EvalResult result;
11441 if (E->EvaluateAsRValue(Result&: result, Ctx: C, InConstantContext))
11442 return GetValueRange(result&: result.Val, Ty: GetExprType(E), MaxWidth);
11443
11444 // I think we only want to look through implicit casts here; if the
11445 // user has an explicit widening cast, we should treat the value as
11446 // being of the new, wider type.
11447 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Val: E)) {
11448 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11449 return TryGetExprRange(C, E: CE->getSubExpr(), MaxWidth, InConstantContext,
11450 Approximate);
11451
11452 IntRange OutputTypeRange = IntRange::forValueOfType(C, T: GetExprType(E: CE));
11453
11454 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11455 CE->getCastKind() == CK_BooleanToSignedIntegral;
11456
11457 // Assume that non-integer casts can span the full range of the type.
11458 if (!isIntegerCast)
11459 return OutputTypeRange;
11460
11461 std::optional<IntRange> SubRange = TryGetExprRange(
11462 C, E: CE->getSubExpr(), MaxWidth: std::min(a: MaxWidth, b: OutputTypeRange.Width),
11463 InConstantContext, Approximate);
11464 if (!SubRange)
11465 return std::nullopt;
11466
11467 // Bail out if the subexpr's range is as wide as the cast type.
11468 if (SubRange->Width >= OutputTypeRange.Width)
11469 return OutputTypeRange;
11470
11471 // Otherwise, we take the smaller width, and we're non-negative if
11472 // either the output type or the subexpr is.
11473 return IntRange(SubRange->Width,
11474 SubRange->NonNegative || OutputTypeRange.NonNegative);
11475 }
11476
11477 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
11478 // If we can fold the condition, just take that operand.
11479 bool CondResult;
11480 if (CO->getCond()->EvaluateAsBooleanCondition(Result&: CondResult, Ctx: C))
11481 return TryGetExprRange(
11482 C, E: CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11483 InConstantContext, Approximate);
11484
11485 // Otherwise, conservatively merge.
11486 // TryGetExprRange requires an integer expression, but a throw expression
11487 // results in a void type.
11488 Expr *TrueExpr = CO->getTrueExpr();
11489 if (TrueExpr->getType()->isVoidType())
11490 return std::nullopt;
11491
11492 std::optional<IntRange> L =
11493 TryGetExprRange(C, E: TrueExpr, MaxWidth, InConstantContext, Approximate);
11494 if (!L)
11495 return std::nullopt;
11496
11497 Expr *FalseExpr = CO->getFalseExpr();
11498 if (FalseExpr->getType()->isVoidType())
11499 return std::nullopt;
11500
11501 std::optional<IntRange> R =
11502 TryGetExprRange(C, E: FalseExpr, MaxWidth, InConstantContext, Approximate);
11503 if (!R)
11504 return std::nullopt;
11505
11506 return IntRange::join(L: *L, R: *R);
11507 }
11508
11509 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
11510 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11511
11512 switch (BO->getOpcode()) {
11513 case BO_Cmp:
11514 llvm_unreachable("builtin <=> should have class type");
11515
11516 // Boolean-valued operations are single-bit and positive.
11517 case BO_LAnd:
11518 case BO_LOr:
11519 case BO_LT:
11520 case BO_GT:
11521 case BO_LE:
11522 case BO_GE:
11523 case BO_EQ:
11524 case BO_NE:
11525 return IntRange::forBoolType();
11526
11527 // The type of the assignments is the type of the LHS, so the RHS
11528 // is not necessarily the same type.
11529 case BO_MulAssign:
11530 case BO_DivAssign:
11531 case BO_RemAssign:
11532 case BO_AddAssign:
11533 case BO_SubAssign:
11534 case BO_XorAssign:
11535 case BO_OrAssign:
11536 // TODO: bitfields?
11537 return IntRange::forValueOfType(C, T: GetExprType(E));
11538
11539 // Simple assignments just pass through the RHS, which will have
11540 // been coerced to the LHS type.
11541 case BO_Assign:
11542 // TODO: bitfields?
11543 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
11544 Approximate);
11545
11546 // Operations with opaque sources are black-listed.
11547 case BO_PtrMemD:
11548 case BO_PtrMemI:
11549 return IntRange::forValueOfType(C, T: GetExprType(E));
11550
11551 // Bitwise-and uses the *infinum* of the two source ranges.
11552 case BO_And:
11553 case BO_AndAssign:
11554 Combine = IntRange::bit_and;
11555 break;
11556
11557 // Left shift gets black-listed based on a judgement call.
11558 case BO_Shl:
11559 // ...except that we want to treat '1 << (blah)' as logically
11560 // positive. It's an important idiom.
11561 if (IntegerLiteral *I
11562 = dyn_cast<IntegerLiteral>(Val: BO->getLHS()->IgnoreParenCasts())) {
11563 if (I->getValue() == 1) {
11564 IntRange R = IntRange::forValueOfType(C, T: GetExprType(E));
11565 return IntRange(R.Width, /*NonNegative*/ true);
11566 }
11567 }
11568 [[fallthrough]];
11569
11570 case BO_ShlAssign:
11571 return IntRange::forValueOfType(C, T: GetExprType(E));
11572
11573 // Right shift by a constant can narrow its left argument.
11574 case BO_Shr:
11575 case BO_ShrAssign: {
11576 std::optional<IntRange> L = TryGetExprRange(
11577 C, E: BO->getLHS(), MaxWidth, InConstantContext, Approximate);
11578 if (!L)
11579 return std::nullopt;
11580
11581 // If the shift amount is a positive constant, drop the width by
11582 // that much.
11583 if (std::optional<llvm::APSInt> shift =
11584 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
11585 if (shift->isNonNegative()) {
11586 if (shift->uge(RHS: L->Width))
11587 L->Width = (L->NonNegative ? 0 : 1);
11588 else
11589 L->Width -= shift->getZExtValue();
11590 }
11591 }
11592
11593 return L;
11594 }
11595
11596 // Comma acts as its right operand.
11597 case BO_Comma:
11598 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
11599 Approximate);
11600
11601 case BO_Add:
11602 if (!Approximate)
11603 Combine = IntRange::sum;
11604 break;
11605
11606 case BO_Sub:
11607 if (BO->getLHS()->getType()->isPointerType())
11608 return IntRange::forValueOfType(C, T: GetExprType(E));
11609 if (!Approximate)
11610 Combine = IntRange::difference;
11611 break;
11612
11613 case BO_Mul:
11614 if (!Approximate)
11615 Combine = IntRange::product;
11616 break;
11617
11618 // The width of a division result is mostly determined by the size
11619 // of the LHS.
11620 case BO_Div: {
11621 // Don't 'pre-truncate' the operands.
11622 unsigned opWidth = C.getIntWidth(T: GetExprType(E));
11623 std::optional<IntRange> L = TryGetExprRange(
11624 C, E: BO->getLHS(), MaxWidth: opWidth, InConstantContext, Approximate);
11625 if (!L)
11626 return std::nullopt;
11627
11628 // If the divisor is constant, use that.
11629 if (std::optional<llvm::APSInt> divisor =
11630 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
11631 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11632 if (log2 >= L->Width)
11633 L->Width = (L->NonNegative ? 0 : 1);
11634 else
11635 L->Width = std::min(a: L->Width - log2, b: MaxWidth);
11636 return L;
11637 }
11638
11639 // Otherwise, just use the LHS's width.
11640 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11641 // could be -1.
11642 std::optional<IntRange> R = TryGetExprRange(
11643 C, E: BO->getRHS(), MaxWidth: opWidth, InConstantContext, Approximate);
11644 if (!R)
11645 return std::nullopt;
11646
11647 return IntRange(L->Width, L->NonNegative && R->NonNegative);
11648 }
11649
11650 case BO_Rem:
11651 Combine = IntRange::rem;
11652 break;
11653
11654 // The default behavior is okay for these.
11655 case BO_Xor:
11656 case BO_Or:
11657 break;
11658 }
11659
11660 // Combine the two ranges, but limit the result to the type in which we
11661 // performed the computation.
11662 QualType T = GetExprType(E);
11663 unsigned opWidth = C.getIntWidth(T);
11664 std::optional<IntRange> L = TryGetExprRange(C, E: BO->getLHS(), MaxWidth: opWidth,
11665 InConstantContext, Approximate);
11666 if (!L)
11667 return std::nullopt;
11668
11669 std::optional<IntRange> R = TryGetExprRange(C, E: BO->getRHS(), MaxWidth: opWidth,
11670 InConstantContext, Approximate);
11671 if (!R)
11672 return std::nullopt;
11673
11674 IntRange C = Combine(*L, *R);
11675 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11676 C.Width = std::min(a: C.Width, b: MaxWidth);
11677 return C;
11678 }
11679
11680 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
11681 switch (UO->getOpcode()) {
11682 // Boolean-valued operations are white-listed.
11683 case UO_LNot:
11684 return IntRange::forBoolType();
11685
11686 // Operations with opaque sources are black-listed.
11687 case UO_Deref:
11688 case UO_AddrOf: // should be impossible
11689 return IntRange::forValueOfType(C, T: GetExprType(E));
11690
11691 case UO_Minus: {
11692 if (E->getType()->isUnsignedIntegerType()) {
11693 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
11694 Approximate);
11695 }
11696
11697 std::optional<IntRange> SubRange = TryGetExprRange(
11698 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11699
11700 if (!SubRange)
11701 return std::nullopt;
11702
11703 // If the range was previously non-negative, we need an extra bit for the
11704 // sign bit. Otherwise, we need an extra bit because the negation of the
11705 // most-negative value is one bit wider than that value.
11706 return IntRange(std::min(a: SubRange->Width + 1, b: MaxWidth), false);
11707 }
11708
11709 case UO_Not: {
11710 if (E->getType()->isUnsignedIntegerType()) {
11711 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
11712 Approximate);
11713 }
11714
11715 std::optional<IntRange> SubRange = TryGetExprRange(
11716 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
11717
11718 if (!SubRange)
11719 return std::nullopt;
11720
11721 // The width increments by 1 if the sub-expression cannot be negative
11722 // since it now can be.
11723 return IntRange(
11724 std::min(a: SubRange->Width + (int)SubRange->NonNegative, b: MaxWidth),
11725 false);
11726 }
11727
11728 default:
11729 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
11730 Approximate);
11731 }
11732 }
11733
11734 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
11735 return TryGetExprRange(C, E: OVE->getSourceExpr(), MaxWidth, InConstantContext,
11736 Approximate);
11737
11738 if (const auto *BitField = E->getSourceBitField())
11739 return IntRange(BitField->getBitWidthValue(),
11740 BitField->getType()->isUnsignedIntegerOrEnumerationType());
11741
11742 if (GetExprType(E)->isVoidType())
11743 return std::nullopt;
11744
11745 return IntRange::forValueOfType(C, T: GetExprType(E));
11746}
11747
11748static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11749 bool InConstantContext,
11750 bool Approximate) {
11751 return TryGetExprRange(C, E, MaxWidth: C.getIntWidth(T: GetExprType(E)), InConstantContext,
11752 Approximate);
11753}
11754
11755/// Checks whether the given value, which currently has the given
11756/// source semantics, has the same value when coerced through the
11757/// target semantics.
11758static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11759 const llvm::fltSemantics &Src,
11760 const llvm::fltSemantics &Tgt) {
11761 llvm::APFloat truncated = value;
11762
11763 bool ignored;
11764 truncated.convert(ToSemantics: Src, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
11765 truncated.convert(ToSemantics: Tgt, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
11766
11767 return truncated.bitwiseIsEqual(RHS: value);
11768}
11769
11770/// Checks whether the given value, which currently has the given
11771/// source semantics, has the same value when coerced through the
11772/// target semantics.
11773///
11774/// The value might be a vector of floats (or a complex number).
11775static bool IsSameFloatAfterCast(const APValue &value,
11776 const llvm::fltSemantics &Src,
11777 const llvm::fltSemantics &Tgt) {
11778 if (value.isFloat())
11779 return IsSameFloatAfterCast(value: value.getFloat(), Src, Tgt);
11780
11781 if (value.isVector()) {
11782 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11783 if (!IsSameFloatAfterCast(value: value.getVectorElt(I: i), Src, Tgt))
11784 return false;
11785 return true;
11786 }
11787
11788 assert(value.isComplexFloat());
11789 return (IsSameFloatAfterCast(value: value.getComplexFloatReal(), Src, Tgt) &&
11790 IsSameFloatAfterCast(value: value.getComplexFloatImag(), Src, Tgt));
11791}
11792
11793static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11794 bool IsListInit = false);
11795
11796static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
11797 // Suppress cases where we are comparing against an enum constant.
11798 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()))
11799 if (isa<EnumConstantDecl>(Val: DR->getDecl()))
11800 return true;
11801
11802 // Suppress cases where the value is expanded from a macro, unless that macro
11803 // is how a language represents a boolean literal. This is the case in both C
11804 // and Objective-C.
11805 SourceLocation BeginLoc = E->getBeginLoc();
11806 if (BeginLoc.isMacroID()) {
11807 StringRef MacroName = Lexer::getImmediateMacroName(
11808 Loc: BeginLoc, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
11809 return MacroName != "YES" && MacroName != "NO" &&
11810 MacroName != "true" && MacroName != "false";
11811 }
11812
11813 return false;
11814}
11815
11816static bool isKnownToHaveUnsignedValue(const Expr *E) {
11817 return E->getType()->isIntegerType() &&
11818 (!E->getType()->isSignedIntegerType() ||
11819 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11820}
11821
11822namespace {
11823/// The promoted range of values of a type. In general this has the
11824/// following structure:
11825///
11826/// |-----------| . . . |-----------|
11827/// ^ ^ ^ ^
11828/// Min HoleMin HoleMax Max
11829///
11830/// ... where there is only a hole if a signed type is promoted to unsigned
11831/// (in which case Min and Max are the smallest and largest representable
11832/// values).
11833struct PromotedRange {
11834 // Min, or HoleMax if there is a hole.
11835 llvm::APSInt PromotedMin;
11836 // Max, or HoleMin if there is a hole.
11837 llvm::APSInt PromotedMax;
11838
11839 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11840 if (R.Width == 0)
11841 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11842 else if (R.Width >= BitWidth && !Unsigned) {
11843 // Promotion made the type *narrower*. This happens when promoting
11844 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11845 // Treat all values of 'signed int' as being in range for now.
11846 PromotedMin = llvm::APSInt::getMinValue(numBits: BitWidth, Unsigned);
11847 PromotedMax = llvm::APSInt::getMaxValue(numBits: BitWidth, Unsigned);
11848 } else {
11849 PromotedMin = llvm::APSInt::getMinValue(numBits: R.Width, Unsigned: R.NonNegative)
11850 .extOrTrunc(width: BitWidth);
11851 PromotedMin.setIsUnsigned(Unsigned);
11852
11853 PromotedMax = llvm::APSInt::getMaxValue(numBits: R.Width, Unsigned: R.NonNegative)
11854 .extOrTrunc(width: BitWidth);
11855 PromotedMax.setIsUnsigned(Unsigned);
11856 }
11857 }
11858
11859 // Determine whether this range is contiguous (has no hole).
11860 bool isContiguous() const { return PromotedMin <= PromotedMax; }
11861
11862 // Where a constant value is within the range.
11863 enum ComparisonResult {
11864 LT = 0x1,
11865 LE = 0x2,
11866 GT = 0x4,
11867 GE = 0x8,
11868 EQ = 0x10,
11869 NE = 0x20,
11870 InRangeFlag = 0x40,
11871
11872 Less = LE | LT | NE,
11873 Min = LE | InRangeFlag,
11874 InRange = InRangeFlag,
11875 Max = GE | InRangeFlag,
11876 Greater = GE | GT | NE,
11877
11878 OnlyValue = LE | GE | EQ | InRangeFlag,
11879 InHole = NE
11880 };
11881
11882 ComparisonResult compare(const llvm::APSInt &Value) const {
11883 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11884 Value.isUnsigned() == PromotedMin.isUnsigned());
11885 if (!isContiguous()) {
11886 assert(Value.isUnsigned() && "discontiguous range for signed compare");
11887 if (Value.isMinValue()) return Min;
11888 if (Value.isMaxValue()) return Max;
11889 if (Value >= PromotedMin) return InRange;
11890 if (Value <= PromotedMax) return InRange;
11891 return InHole;
11892 }
11893
11894 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMin)) {
11895 case -1: return Less;
11896 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11897 case 1:
11898 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMax)) {
11899 case -1: return InRange;
11900 case 0: return Max;
11901 case 1: return Greater;
11902 }
11903 }
11904
11905 llvm_unreachable("impossible compare result");
11906 }
11907
11908 static std::optional<StringRef>
11909 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11910 if (Op == BO_Cmp) {
11911 ComparisonResult LTFlag = LT, GTFlag = GT;
11912 if (ConstantOnRHS) std::swap(a&: LTFlag, b&: GTFlag);
11913
11914 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11915 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11916 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11917 return std::nullopt;
11918 }
11919
11920 ComparisonResult TrueFlag, FalseFlag;
11921 if (Op == BO_EQ) {
11922 TrueFlag = EQ;
11923 FalseFlag = NE;
11924 } else if (Op == BO_NE) {
11925 TrueFlag = NE;
11926 FalseFlag = EQ;
11927 } else {
11928 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11929 TrueFlag = LT;
11930 FalseFlag = GE;
11931 } else {
11932 TrueFlag = GT;
11933 FalseFlag = LE;
11934 }
11935 if (Op == BO_GE || Op == BO_LE)
11936 std::swap(a&: TrueFlag, b&: FalseFlag);
11937 }
11938 if (R & TrueFlag)
11939 return StringRef("true");
11940 if (R & FalseFlag)
11941 return StringRef("false");
11942 return std::nullopt;
11943 }
11944};
11945}
11946
11947static bool HasEnumType(const Expr *E) {
11948 // Strip off implicit integral promotions.
11949 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
11950 if (ICE->getCastKind() != CK_IntegralCast &&
11951 ICE->getCastKind() != CK_NoOp)
11952 break;
11953 E = ICE->getSubExpr();
11954 }
11955
11956 return E->getType()->isEnumeralType();
11957}
11958
11959static int classifyConstantValue(Expr *Constant) {
11960 // The values of this enumeration are used in the diagnostics
11961 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11962 enum ConstantValueKind {
11963 Miscellaneous = 0,
11964 LiteralTrue,
11965 LiteralFalse
11966 };
11967 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Val: Constant))
11968 return BL->getValue() ? ConstantValueKind::LiteralTrue
11969 : ConstantValueKind::LiteralFalse;
11970 return ConstantValueKind::Miscellaneous;
11971}
11972
11973static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11974 Expr *Constant, Expr *Other,
11975 const llvm::APSInt &Value,
11976 bool RhsConstant) {
11977 if (S.inTemplateInstantiation())
11978 return false;
11979
11980 Expr *OriginalOther = Other;
11981
11982 Constant = Constant->IgnoreParenImpCasts();
11983 Other = Other->IgnoreParenImpCasts();
11984
11985 // Suppress warnings on tautological comparisons between values of the same
11986 // enumeration type. There are only two ways we could warn on this:
11987 // - If the constant is outside the range of representable values of
11988 // the enumeration. In such a case, we should warn about the cast
11989 // to enumeration type, not about the comparison.
11990 // - If the constant is the maximum / minimum in-range value. For an
11991 // enumeratin type, such comparisons can be meaningful and useful.
11992 if (Constant->getType()->isEnumeralType() &&
11993 S.Context.hasSameUnqualifiedType(T1: Constant->getType(), T2: Other->getType()))
11994 return false;
11995
11996 std::optional<IntRange> OtherValueRange = TryGetExprRange(
11997 C&: S.Context, E: Other, InConstantContext: S.isConstantEvaluatedContext(), /*Approximate=*/false);
11998 if (!OtherValueRange)
11999 return false;
12000
12001 QualType OtherT = Other->getType();
12002 if (const auto *AT = OtherT->getAs<AtomicType>())
12003 OtherT = AT->getValueType();
12004 IntRange OtherTypeRange = IntRange::forValueOfType(C&: S.Context, T: OtherT);
12005
12006 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12007 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12008 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12009 S.ObjC().NSAPIObj->isObjCBOOLType(T: OtherT) &&
12010 OtherT->isSpecificBuiltinType(K: BuiltinType::SChar);
12011
12012 // Whether we're treating Other as being a bool because of the form of
12013 // expression despite it having another type (typically 'int' in C).
12014 bool OtherIsBooleanDespiteType =
12015 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12016 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12017 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12018
12019 // Check if all values in the range of possible values of this expression
12020 // lead to the same comparison outcome.
12021 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12022 Value.isUnsigned());
12023 auto Cmp = OtherPromotedValueRange.compare(Value);
12024 auto Result = PromotedRange::constantValue(Op: E->getOpcode(), R: Cmp, ConstantOnRHS: RhsConstant);
12025 if (!Result)
12026 return false;
12027
12028 // Also consider the range determined by the type alone. This allows us to
12029 // classify the warning under the proper diagnostic group.
12030 bool TautologicalTypeCompare = false;
12031 {
12032 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12033 Value.isUnsigned());
12034 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12035 if (auto TypeResult = PromotedRange::constantValue(Op: E->getOpcode(), R: TypeCmp,
12036 ConstantOnRHS: RhsConstant)) {
12037 TautologicalTypeCompare = true;
12038 Cmp = TypeCmp;
12039 Result = TypeResult;
12040 }
12041 }
12042
12043 // Don't warn if the non-constant operand actually always evaluates to the
12044 // same value.
12045 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12046 return false;
12047
12048 // Suppress the diagnostic for an in-range comparison if the constant comes
12049 // from a macro or enumerator. We don't want to diagnose
12050 //
12051 // some_long_value <= INT_MAX
12052 //
12053 // when sizeof(int) == sizeof(long).
12054 bool InRange = Cmp & PromotedRange::InRangeFlag;
12055 if (InRange && IsEnumConstOrFromMacro(S, E: Constant))
12056 return false;
12057
12058 // A comparison of an unsigned bit-field against 0 is really a type problem,
12059 // even though at the type level the bit-field might promote to 'signed int'.
12060 if (Other->refersToBitField() && InRange && Value == 0 &&
12061 Other->getType()->isUnsignedIntegerOrEnumerationType())
12062 TautologicalTypeCompare = true;
12063
12064 // If this is a comparison to an enum constant, include that
12065 // constant in the diagnostic.
12066 const EnumConstantDecl *ED = nullptr;
12067 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: Constant))
12068 ED = dyn_cast<EnumConstantDecl>(Val: DR->getDecl());
12069
12070 // Should be enough for uint128 (39 decimal digits)
12071 SmallString<64> PrettySourceValue;
12072 llvm::raw_svector_ostream OS(PrettySourceValue);
12073 if (ED) {
12074 OS << '\'' << *ED << "' (" << Value << ")";
12075 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12076 Val: Constant->IgnoreParenImpCasts())) {
12077 OS << (BL->getValue() ? "YES" : "NO");
12078 } else {
12079 OS << Value;
12080 }
12081
12082 if (!TautologicalTypeCompare) {
12083 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_tautological_compare_value_range)
12084 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12085 << E->getOpcodeStr() << OS.str() << *Result
12086 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12087 return true;
12088 }
12089
12090 if (IsObjCSignedCharBool) {
12091 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12092 PD: S.PDiag(DiagID: diag::warn_tautological_compare_objc_bool)
12093 << OS.str() << *Result);
12094 return true;
12095 }
12096
12097 // FIXME: We use a somewhat different formatting for the in-range cases and
12098 // cases involving boolean values for historical reasons. We should pick a
12099 // consistent way of presenting these diagnostics.
12100 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12101
12102 S.DiagRuntimeBehavior(
12103 Loc: E->getOperatorLoc(), Statement: E,
12104 PD: S.PDiag(DiagID: !InRange ? diag::warn_out_of_range_compare
12105 : diag::warn_tautological_bool_compare)
12106 << OS.str() << classifyConstantValue(Constant) << OtherT
12107 << OtherIsBooleanDespiteType << *Result
12108 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12109 } else {
12110 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12111 unsigned Diag =
12112 (isKnownToHaveUnsignedValue(E: OriginalOther) && Value == 0)
12113 ? (HasEnumType(E: OriginalOther)
12114 ? diag::warn_unsigned_enum_always_true_comparison
12115 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12116 : diag::warn_unsigned_always_true_comparison)
12117 : diag::warn_tautological_constant_compare;
12118
12119 S.Diag(Loc: E->getOperatorLoc(), DiagID: Diag)
12120 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12121 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12122 }
12123
12124 return true;
12125}
12126
12127/// Analyze the operands of the given comparison. Implements the
12128/// fallback case from AnalyzeComparison.
12129static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12130 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12131 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12132}
12133
12134/// Implements -Wsign-compare.
12135///
12136/// \param E the binary operator to check for warnings
12137static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12138 // The type the comparison is being performed in.
12139 QualType T = E->getLHS()->getType();
12140
12141 // Only analyze comparison operators where both sides have been converted to
12142 // the same type.
12143 if (!S.Context.hasSameUnqualifiedType(T1: T, T2: E->getRHS()->getType()))
12144 return AnalyzeImpConvsInComparison(S, E);
12145
12146 // Don't analyze value-dependent comparisons directly.
12147 if (E->isValueDependent())
12148 return AnalyzeImpConvsInComparison(S, E);
12149
12150 Expr *LHS = E->getLHS();
12151 Expr *RHS = E->getRHS();
12152
12153 if (T->isIntegralType(Ctx: S.Context)) {
12154 std::optional<llvm::APSInt> RHSValue =
12155 RHS->getIntegerConstantExpr(Ctx: S.Context);
12156 std::optional<llvm::APSInt> LHSValue =
12157 LHS->getIntegerConstantExpr(Ctx: S.Context);
12158
12159 // We don't care about expressions whose result is a constant.
12160 if (RHSValue && LHSValue)
12161 return AnalyzeImpConvsInComparison(S, E);
12162
12163 // We only care about expressions where just one side is literal
12164 if ((bool)RHSValue ^ (bool)LHSValue) {
12165 // Is the constant on the RHS or LHS?
12166 const bool RhsConstant = (bool)RHSValue;
12167 Expr *Const = RhsConstant ? RHS : LHS;
12168 Expr *Other = RhsConstant ? LHS : RHS;
12169 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12170
12171 // Check whether an integer constant comparison results in a value
12172 // of 'true' or 'false'.
12173 if (CheckTautologicalComparison(S, E, Constant: Const, Other, Value, RhsConstant))
12174 return AnalyzeImpConvsInComparison(S, E);
12175 }
12176 }
12177
12178 if (!T->hasUnsignedIntegerRepresentation()) {
12179 // We don't do anything special if this isn't an unsigned integral
12180 // comparison: we're only interested in integral comparisons, and
12181 // signed comparisons only happen in cases we don't care to warn about.
12182 return AnalyzeImpConvsInComparison(S, E);
12183 }
12184
12185 LHS = LHS->IgnoreParenImpCasts();
12186 RHS = RHS->IgnoreParenImpCasts();
12187
12188 if (!S.getLangOpts().CPlusPlus) {
12189 // Avoid warning about comparison of integers with different signs when
12190 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12191 // the type of `E`.
12192 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: LHS->getType()))
12193 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12194 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: RHS->getType()))
12195 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12196 }
12197
12198 // Check to see if one of the (unmodified) operands is of different
12199 // signedness.
12200 Expr *signedOperand, *unsignedOperand;
12201 if (LHS->getType()->hasSignedIntegerRepresentation()) {
12202 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12203 "unsigned comparison between two signed integer expressions?");
12204 signedOperand = LHS;
12205 unsignedOperand = RHS;
12206 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12207 signedOperand = RHS;
12208 unsignedOperand = LHS;
12209 } else {
12210 return AnalyzeImpConvsInComparison(S, E);
12211 }
12212
12213 // Otherwise, calculate the effective range of the signed operand.
12214 std::optional<IntRange> signedRange =
12215 TryGetExprRange(C&: S.Context, E: signedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12216 /*Approximate=*/true);
12217 if (!signedRange)
12218 return;
12219
12220 // Go ahead and analyze implicit conversions in the operands. Note
12221 // that we skip the implicit conversions on both sides.
12222 AnalyzeImplicitConversions(S, E: LHS, CC: E->getOperatorLoc());
12223 AnalyzeImplicitConversions(S, E: RHS, CC: E->getOperatorLoc());
12224
12225 // If the signed range is non-negative, -Wsign-compare won't fire.
12226 if (signedRange->NonNegative)
12227 return;
12228
12229 // For (in)equality comparisons, if the unsigned operand is a
12230 // constant which cannot collide with a overflowed signed operand,
12231 // then reinterpreting the signed operand as unsigned will not
12232 // change the result of the comparison.
12233 if (E->isEqualityOp()) {
12234 unsigned comparisonWidth = S.Context.getIntWidth(T);
12235 std::optional<IntRange> unsignedRange = TryGetExprRange(
12236 C&: S.Context, E: unsignedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12237 /*Approximate=*/true);
12238 if (!unsignedRange)
12239 return;
12240
12241 // We should never be unable to prove that the unsigned operand is
12242 // non-negative.
12243 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12244
12245 if (unsignedRange->Width < comparisonWidth)
12246 return;
12247 }
12248
12249 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12250 PD: S.PDiag(DiagID: diag::warn_mixed_sign_comparison)
12251 << LHS->getType() << RHS->getType()
12252 << LHS->getSourceRange() << RHS->getSourceRange());
12253}
12254
12255/// Analyzes an attempt to assign the given value to a bitfield.
12256///
12257/// Returns true if there was something fishy about the attempt.
12258static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12259 SourceLocation InitLoc) {
12260 assert(Bitfield->isBitField());
12261 if (Bitfield->isInvalidDecl())
12262 return false;
12263
12264 // White-list bool bitfields.
12265 QualType BitfieldType = Bitfield->getType();
12266 if (BitfieldType->isBooleanType())
12267 return false;
12268
12269 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12270 // If the underlying enum type was not explicitly specified as an unsigned
12271 // type and the enum contain only positive values, MSVC++ will cause an
12272 // inconsistency by storing this as a signed type.
12273 if (S.getLangOpts().CPlusPlus11 &&
12274 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12275 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12276 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12277 S.Diag(Loc: InitLoc, DiagID: diag::warn_no_underlying_type_specified_for_enum_bitfield)
12278 << BitfieldEnumDecl;
12279 }
12280 }
12281
12282 // Ignore value- or type-dependent expressions.
12283 if (Bitfield->getBitWidth()->isValueDependent() ||
12284 Bitfield->getBitWidth()->isTypeDependent() ||
12285 Init->isValueDependent() ||
12286 Init->isTypeDependent())
12287 return false;
12288
12289 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12290 unsigned FieldWidth = Bitfield->getBitWidthValue();
12291
12292 Expr::EvalResult Result;
12293 if (!OriginalInit->EvaluateAsInt(Result, Ctx: S.Context,
12294 AllowSideEffects: Expr::SE_AllowSideEffects)) {
12295 // The RHS is not constant. If the RHS has an enum type, make sure the
12296 // bitfield is wide enough to hold all the values of the enum without
12297 // truncation.
12298 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12299 const PreferredTypeAttr *PTAttr = nullptr;
12300 if (!ED) {
12301 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12302 if (PTAttr)
12303 ED = PTAttr->getType()->getAsEnumDecl();
12304 }
12305 if (ED) {
12306 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12307
12308 // Enum types are implicitly signed on Windows, so check if there are any
12309 // negative enumerators to see if the enum was intended to be signed or
12310 // not.
12311 bool SignedEnum = ED->getNumNegativeBits() > 0;
12312
12313 // Check for surprising sign changes when assigning enum values to a
12314 // bitfield of different signedness. If the bitfield is signed and we
12315 // have exactly the right number of bits to store this unsigned enum,
12316 // suggest changing the enum to an unsigned type. This typically happens
12317 // on Windows where unfixed enums always use an underlying type of 'int'.
12318 unsigned DiagID = 0;
12319 if (SignedEnum && !SignedBitfield) {
12320 DiagID =
12321 PTAttr == nullptr
12322 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12323 : diag::
12324 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12325 } else if (SignedBitfield && !SignedEnum &&
12326 ED->getNumPositiveBits() == FieldWidth) {
12327 DiagID =
12328 PTAttr == nullptr
12329 ? diag::warn_signed_bitfield_enum_conversion
12330 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12331 }
12332 if (DiagID) {
12333 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
12334 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12335 SourceRange TypeRange =
12336 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12337 S.Diag(Loc: Bitfield->getTypeSpecStartLoc(), DiagID: diag::note_change_bitfield_sign)
12338 << SignedEnum << TypeRange;
12339 if (PTAttr)
12340 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
12341 << ED;
12342 }
12343
12344 // Compute the required bitwidth. If the enum has negative values, we need
12345 // one more bit than the normal number of positive bits to represent the
12346 // sign bit.
12347 unsigned BitsNeeded = SignedEnum ? std::max(a: ED->getNumPositiveBits() + 1,
12348 b: ED->getNumNegativeBits())
12349 : ED->getNumPositiveBits();
12350
12351 // Check the bitwidth.
12352 if (BitsNeeded > FieldWidth) {
12353 Expr *WidthExpr = Bitfield->getBitWidth();
12354 auto DiagID =
12355 PTAttr == nullptr
12356 ? diag::warn_bitfield_too_small_for_enum
12357 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12358 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
12359 S.Diag(Loc: WidthExpr->getExprLoc(), DiagID: diag::note_widen_bitfield)
12360 << BitsNeeded << ED << WidthExpr->getSourceRange();
12361 if (PTAttr)
12362 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
12363 << ED;
12364 }
12365 }
12366
12367 return false;
12368 }
12369
12370 llvm::APSInt Value = Result.Val.getInt();
12371
12372 unsigned OriginalWidth = Value.getBitWidth();
12373
12374 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12375 // false positives where the user is demonstrating they intend to use the
12376 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12377 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12378 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12379 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12380 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12381 if (S.SourceMgr.isInSystemMacro(loc: MaybeMacroLoc) &&
12382 S.findMacroSpelling(loc&: MaybeMacroLoc, name: "true"))
12383 return false;
12384 }
12385
12386 if (!Value.isSigned() || Value.isNegative())
12387 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: OriginalInit))
12388 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12389 OriginalWidth = Value.getSignificantBits();
12390
12391 if (OriginalWidth <= FieldWidth)
12392 return false;
12393
12394 // Compute the value which the bitfield will contain.
12395 llvm::APSInt TruncatedValue = Value.trunc(width: FieldWidth);
12396 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12397
12398 // Check whether the stored value is equal to the original value.
12399 TruncatedValue = TruncatedValue.extend(width: OriginalWidth);
12400 if (llvm::APSInt::isSameValue(I1: Value, I2: TruncatedValue))
12401 return false;
12402
12403 std::string PrettyValue = toString(I: Value, Radix: 10);
12404 std::string PrettyTrunc = toString(I: TruncatedValue, Radix: 10);
12405
12406 S.Diag(Loc: InitLoc, DiagID: OneAssignedToOneBitBitfield
12407 ? diag::warn_impcast_single_bit_bitield_precision_constant
12408 : diag::warn_impcast_bitfield_precision_constant)
12409 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12410 << Init->getSourceRange();
12411
12412 return true;
12413}
12414
12415/// Analyze the given simple or compound assignment for warning-worthy
12416/// operations.
12417static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12418 // Just recurse on the LHS.
12419 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12420
12421 // We want to recurse on the RHS as normal unless we're assigning to
12422 // a bitfield.
12423 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12424 if (AnalyzeBitFieldAssignment(S, Bitfield, Init: E->getRHS(),
12425 InitLoc: E->getOperatorLoc())) {
12426 // Recurse, ignoring any implicit conversions on the RHS.
12427 return AnalyzeImplicitConversions(S, E: E->getRHS()->IgnoreParenImpCasts(),
12428 CC: E->getOperatorLoc());
12429 }
12430 }
12431
12432 // Set context flag for overflow behavior type assignment analysis, use RAII
12433 // pattern to handle nested assignments.
12434 llvm::SaveAndRestore OBTAssignmentContext(
12435 S.InOverflowBehaviorAssignmentContext, true);
12436
12437 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12438
12439 // Diagnose implicitly sequentially-consistent atomic assignment.
12440 if (E->getLHS()->getType()->isAtomicType())
12441 S.Diag(Loc: E->getRHS()->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
12442}
12443
12444/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12445static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12446 QualType T, SourceLocation CContext, unsigned diag,
12447 bool PruneControlFlow = false) {
12448 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12449 // address space annotations isn't really useful. The warnings aren't because
12450 // you're converting a `private int` to `unsigned int`, it is because you're
12451 // conerting `int` to `unsigned int`.
12452 if (SourceType.hasAddressSpace())
12453 SourceType = S.getASTContext().removeAddrSpaceQualType(T: SourceType);
12454 if (T.hasAddressSpace())
12455 T = S.getASTContext().removeAddrSpaceQualType(T);
12456 if (PruneControlFlow) {
12457 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
12458 PD: S.PDiag(DiagID: diag)
12459 << SourceType << T << E->getSourceRange()
12460 << SourceRange(CContext));
12461 return;
12462 }
12463 S.Diag(Loc: E->getExprLoc(), DiagID: diag)
12464 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12465}
12466
12467/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12468static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12469 SourceLocation CContext, unsigned diag,
12470 bool PruneControlFlow = false) {
12471 DiagnoseImpCast(S, E, SourceType: E->getType(), T, CContext, diag, PruneControlFlow);
12472}
12473
12474/// Diagnose an implicit cast from a floating point value to an integer value.
12475static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12476 SourceLocation CContext) {
12477 bool IsBool = T->isSpecificBuiltinType(K: BuiltinType::Bool);
12478 bool PruneWarnings = S.inTemplateInstantiation();
12479
12480 const Expr *InnerE = E->IgnoreParenImpCasts();
12481 // We also want to warn on, e.g., "int i = -1.234"
12482 if (const auto *UOp = dyn_cast<UnaryOperator>(Val: InnerE))
12483 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12484 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12485
12486 bool IsLiteral = isa<FloatingLiteral>(Val: E) || isa<FloatingLiteral>(Val: InnerE);
12487
12488 llvm::APFloat Value(0.0);
12489 bool IsConstant =
12490 E->EvaluateAsFloat(Result&: Value, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects);
12491 if (!IsConstant) {
12492 if (S.ObjC().isSignedCharBool(Ty: T)) {
12493 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
12494 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_float_to_objc_signed_char_bool)
12495 << E->getType());
12496 }
12497
12498 return DiagnoseImpCast(S, E, T, CContext,
12499 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12500 }
12501
12502 bool isExact = false;
12503
12504 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12505 T->hasUnsignedIntegerRepresentation());
12506 llvm::APFloat::opStatus Result = Value.convertToInteger(
12507 Result&: IntegerValue, RM: llvm::APFloat::rmTowardZero, IsExact: &isExact);
12508
12509 // FIXME: Force the precision of the source value down so we don't print
12510 // digits which are usually useless (we don't really care here if we
12511 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12512 // would automatically print the shortest representation, but it's a bit
12513 // tricky to implement.
12514 SmallString<16> PrettySourceValue;
12515 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12516 precision = (precision * 59 + 195) / 196;
12517 Value.toString(Str&: PrettySourceValue, FormatPrecision: precision);
12518
12519 if (S.ObjC().isSignedCharBool(Ty: T) && IntegerValue != 0 && IntegerValue != 1) {
12520 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
12521 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
12522 << PrettySourceValue);
12523 }
12524
12525 if (Result == llvm::APFloat::opOK && isExact) {
12526 if (IsLiteral) return;
12527 return DiagnoseImpCast(S, E, T, CContext, diag: diag::warn_impcast_float_integer,
12528 PruneControlFlow: PruneWarnings);
12529 }
12530
12531 // Conversion of a floating-point value to a non-bool integer where the
12532 // integral part cannot be represented by the integer type is undefined.
12533 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12534 return DiagnoseImpCast(
12535 S, E, T, CContext,
12536 diag: IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12537 : diag::warn_impcast_float_to_integer_out_of_range,
12538 PruneControlFlow: PruneWarnings);
12539
12540 unsigned DiagID = 0;
12541 if (IsLiteral) {
12542 // Warn on floating point literal to integer.
12543 DiagID = diag::warn_impcast_literal_float_to_integer;
12544 } else if (IntegerValue == 0) {
12545 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
12546 return DiagnoseImpCast(S, E, T, CContext,
12547 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12548 }
12549 // Warn on non-zero to zero conversion.
12550 DiagID = diag::warn_impcast_float_to_integer_zero;
12551 } else {
12552 if (IntegerValue.isUnsigned()) {
12553 if (!IntegerValue.isMaxValue()) {
12554 return DiagnoseImpCast(S, E, T, CContext,
12555 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12556 }
12557 } else { // IntegerValue.isSigned()
12558 if (!IntegerValue.isMaxSignedValue() &&
12559 !IntegerValue.isMinSignedValue()) {
12560 return DiagnoseImpCast(S, E, T, CContext,
12561 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12562 }
12563 }
12564 // Warn on evaluatable floating point expression to integer conversion.
12565 DiagID = diag::warn_impcast_float_to_integer;
12566 }
12567
12568 SmallString<16> PrettyTargetValue;
12569 if (IsBool)
12570 PrettyTargetValue = Value.isZero() ? "false" : "true";
12571 else
12572 IntegerValue.toString(Str&: PrettyTargetValue);
12573
12574 if (PruneWarnings) {
12575 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
12576 PD: S.PDiag(DiagID)
12577 << E->getType() << T.getUnqualifiedType()
12578 << PrettySourceValue << PrettyTargetValue
12579 << E->getSourceRange() << SourceRange(CContext));
12580 } else {
12581 S.Diag(Loc: E->getExprLoc(), DiagID)
12582 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12583 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12584 }
12585}
12586
12587/// Analyze the given compound assignment for the possible losing of
12588/// floating-point precision.
12589static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12590 assert(isa<CompoundAssignOperator>(E) &&
12591 "Must be compound assignment operation");
12592 // Recurse on the LHS and RHS in here
12593 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12594 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12595
12596 if (E->getLHS()->getType()->isAtomicType())
12597 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
12598
12599 // Now check the outermost expression
12600 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12601 const auto *RBT = cast<CompoundAssignOperator>(Val: E)
12602 ->getComputationResultType()
12603 ->getAs<BuiltinType>();
12604
12605 // The below checks assume source is floating point.
12606 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12607
12608 // If source is floating point but target is an integer.
12609 if (ResultBT->isInteger())
12610 return DiagnoseImpCast(S, E, SourceType: E->getRHS()->getType(), T: E->getLHS()->getType(),
12611 CContext: E->getExprLoc(), diag: diag::warn_impcast_float_integer);
12612
12613 if (!ResultBT->isFloatingPoint())
12614 return;
12615
12616 // If both source and target are floating points, warn about losing precision.
12617 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12618 LHS: QualType(ResultBT, 0), RHS: QualType(RBT, 0));
12619 if (Order < 0 && !S.SourceMgr.isInSystemMacro(loc: E->getOperatorLoc()))
12620 // warn about dropping FP rank.
12621 DiagnoseImpCast(S, E: E->getRHS(), T: E->getLHS()->getType(), CContext: E->getOperatorLoc(),
12622 diag: diag::warn_impcast_float_result_precision);
12623}
12624
12625static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12626 IntRange Range) {
12627 if (!Range.Width) return "0";
12628
12629 llvm::APSInt ValueInRange = Value;
12630 ValueInRange.setIsSigned(!Range.NonNegative);
12631 ValueInRange = ValueInRange.trunc(width: Range.Width);
12632 return toString(I: ValueInRange, Radix: 10);
12633}
12634
12635static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
12636 bool ToBool) {
12637 if (!isa<ImplicitCastExpr>(Val: Ex))
12638 return false;
12639
12640 const Expr *InnerE = Ex->IgnoreParenImpCasts();
12641 const Type *Target = S.Context.getCanonicalType(T: Ex->getType()).getTypePtr();
12642 const Type *Source =
12643 S.Context.getCanonicalType(T: InnerE->getType()).getTypePtr();
12644 if (Target->isDependentType())
12645 return false;
12646
12647 const auto *FloatCandidateBT =
12648 dyn_cast<BuiltinType>(Val: ToBool ? Source : Target);
12649 const Type *BoolCandidateType = ToBool ? Target : Source;
12650
12651 return (BoolCandidateType->isSpecificBuiltinType(K: BuiltinType::Bool) &&
12652 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12653}
12654
12655static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
12656 SourceLocation CC) {
12657 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
12658 const Expr *CurrA = TheCall->getArg(Arg: I);
12659 if (!IsImplicitBoolFloatConversion(S, Ex: CurrA, ToBool: true))
12660 continue;
12661
12662 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
12663 S, Ex: TheCall->getArg(Arg: I - 1), ToBool: false));
12664 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
12665 S, Ex: TheCall->getArg(Arg: I + 1), ToBool: false));
12666 if (IsSwapped) {
12667 // Warn on this floating-point to bool conversion.
12668 DiagnoseImpCast(S, E: CurrA->IgnoreParenImpCasts(),
12669 T: CurrA->getType(), CContext: CC,
12670 diag: diag::warn_impcast_floating_point_to_bool);
12671 }
12672 }
12673}
12674
12675static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12676 SourceLocation CC) {
12677 // Don't warn on functions which have return type nullptr_t.
12678 if (isa<CallExpr>(Val: E))
12679 return;
12680
12681 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12682 const Expr *NewE = E->IgnoreParenImpCasts();
12683 bool IsGNUNullExpr = isa<GNUNullExpr>(Val: NewE);
12684 bool HasNullPtrType = NewE->getType()->isNullPtrType();
12685 if (!IsGNUNullExpr && !HasNullPtrType)
12686 return;
12687
12688 // Return if target type is a safe conversion.
12689 if (T->isAnyPointerType() || T->isBlockPointerType() ||
12690 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12691 return;
12692
12693 if (S.Diags.isIgnored(DiagID: diag::warn_impcast_null_pointer_to_integer,
12694 Loc: E->getExprLoc()))
12695 return;
12696
12697 SourceLocation Loc = E->getSourceRange().getBegin();
12698
12699 // Venture through the macro stacks to get to the source of macro arguments.
12700 // The new location is a better location than the complete location that was
12701 // passed in.
12702 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12703 CC = S.SourceMgr.getTopMacroCallerLoc(Loc: CC);
12704
12705 // __null is usually wrapped in a macro. Go up a macro if that is the case.
12706 if (IsGNUNullExpr && Loc.isMacroID()) {
12707 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12708 Loc, SM: S.SourceMgr, LangOpts: S.getLangOpts());
12709 if (MacroName == "NULL")
12710 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12711 }
12712
12713 // Only warn if the null and context location are in the same macro expansion.
12714 if (S.SourceMgr.getFileID(SpellingLoc: Loc) != S.SourceMgr.getFileID(SpellingLoc: CC))
12715 return;
12716
12717 S.Diag(Loc, DiagID: diag::warn_impcast_null_pointer_to_integer)
12718 << HasNullPtrType << T << SourceRange(CC)
12719 << FixItHint::CreateReplacement(RemoveRange: Loc,
12720 Code: S.getFixItZeroLiteralForType(T, Loc));
12721}
12722
12723// Helper function to filter out cases for constant width constant conversion.
12724// Don't warn on char array initialization or for non-decimal values.
12725static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12726 SourceLocation CC) {
12727 // If initializing from a constant, and the constant starts with '0',
12728 // then it is a binary, octal, or hexadecimal. Allow these constants
12729 // to fill all the bits, even if there is a sign change.
12730 if (auto *IntLit = dyn_cast<IntegerLiteral>(Val: E->IgnoreParenImpCasts())) {
12731 const char FirstLiteralCharacter =
12732 S.getSourceManager().getCharacterData(SL: IntLit->getBeginLoc())[0];
12733 if (FirstLiteralCharacter == '0')
12734 return false;
12735 }
12736
12737 // If the CC location points to a '{', and the type is char, then assume
12738 // assume it is an array initialization.
12739 if (CC.isValid() && T->isCharType()) {
12740 const char FirstContextCharacter =
12741 S.getSourceManager().getCharacterData(SL: CC)[0];
12742 if (FirstContextCharacter == '{')
12743 return false;
12744 }
12745
12746 return true;
12747}
12748
12749static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12750 const auto *IL = dyn_cast<IntegerLiteral>(Val: E);
12751 if (!IL) {
12752 if (auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
12753 if (UO->getOpcode() == UO_Minus)
12754 return dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
12755 }
12756 }
12757
12758 return IL;
12759}
12760
12761static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12762 E = E->IgnoreParenImpCasts();
12763 SourceLocation ExprLoc = E->getExprLoc();
12764
12765 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
12766 BinaryOperator::Opcode Opc = BO->getOpcode();
12767 Expr::EvalResult Result;
12768 // Do not diagnose unsigned shifts.
12769 if (Opc == BO_Shl) {
12770 const auto *LHS = getIntegerLiteral(E: BO->getLHS());
12771 const auto *RHS = getIntegerLiteral(E: BO->getRHS());
12772 if (LHS && LHS->getValue() == 0)
12773 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always) << 0;
12774 else if (!E->isValueDependent() && LHS && RHS &&
12775 RHS->getValue().isNonNegative() &&
12776 E->EvaluateAsInt(Result, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects))
12777 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always)
12778 << (Result.Val.getInt() != 0);
12779 else if (E->getType()->isSignedIntegerType())
12780 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_in_bool_context)
12781 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "(")
12782 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: E->getEndLoc()),
12783 Code: ") != 0");
12784 }
12785 }
12786
12787 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12788 const auto *LHS = getIntegerLiteral(E: CO->getTrueExpr());
12789 const auto *RHS = getIntegerLiteral(E: CO->getFalseExpr());
12790 if (!LHS || !RHS)
12791 return;
12792 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12793 (RHS->getValue() == 0 || RHS->getValue() == 1))
12794 // Do not diagnose common idioms.
12795 return;
12796 if (LHS->getValue() != 0 && RHS->getValue() != 0)
12797 S.Diag(Loc: ExprLoc, DiagID: diag::warn_integer_constants_in_conditional_always_true);
12798 }
12799}
12800
12801static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source,
12802 const Type *Target, Expr *E,
12803 QualType T,
12804 SourceLocation CC) {
12805 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
12806 Source != Target);
12807
12808 // Lone surrogates have a distinct representation in UTF-32.
12809 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
12810 // so don't warn on such conversion.
12811 if (Source->isChar16Type() && Target->isChar32Type())
12812 return;
12813
12814 Expr::EvalResult Result;
12815 if (E->EvaluateAsInt(Result, Ctx: S.getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects,
12816 InConstantContext: S.isConstantEvaluatedContext())) {
12817 llvm::APSInt Value(32);
12818 Value = Result.Val.getInt();
12819 bool IsASCII = Value <= 0x7F;
12820 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
12821 bool ConversionPreservesSemantics =
12822 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
12823
12824 if (!ConversionPreservesSemantics) {
12825 auto IsSingleCodeUnitCP = [](const QualType &T,
12826 const llvm::APSInt &Value) {
12827 if (T->isChar8Type())
12828 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
12829 if (T->isChar16Type())
12830 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
12831 assert(T->isChar32Type());
12832 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
12833 };
12834
12835 S.Diag(Loc: CC, DiagID: diag::warn_impcast_unicode_char_type_constant)
12836 << E->getType() << T
12837 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
12838 << FormatUTFCodeUnitAsCodepoint(Value: Value.getExtValue(), T: E->getType());
12839 }
12840 } else {
12841 bool LosesPrecision = S.getASTContext().getIntWidth(T: E->getType()) >
12842 S.getASTContext().getIntWidth(T);
12843 DiagnoseImpCast(S, E, T, CContext: CC,
12844 diag: LosesPrecision ? diag::warn_impcast_unicode_precision
12845 : diag::warn_impcast_unicode_char_type);
12846 }
12847}
12848
12849bool Sema::DiscardingCFIUncheckedCallee(QualType From, QualType To) const {
12850 From = Context.getCanonicalType(T: From);
12851 To = Context.getCanonicalType(T: To);
12852 QualType MaybePointee = From->getPointeeType();
12853 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12854 From = MaybePointee;
12855 MaybePointee = To->getPointeeType();
12856 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
12857 To = MaybePointee;
12858
12859 if (const auto *FromFn = From->getAs<FunctionType>()) {
12860 if (const auto *ToFn = To->getAs<FunctionType>()) {
12861 if (FromFn->getCFIUncheckedCalleeAttr() &&
12862 !ToFn->getCFIUncheckedCalleeAttr())
12863 return true;
12864 }
12865 }
12866 return false;
12867}
12868
12869void Sema::CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
12870 bool *ICContext, bool IsListInit) {
12871 if (E->isTypeDependent() || E->isValueDependent()) return;
12872
12873 const Type *Source = Context.getCanonicalType(T: E->getType()).getTypePtr();
12874 const Type *Target = Context.getCanonicalType(T).getTypePtr();
12875 if (Source == Target) return;
12876 if (Target->isDependentType()) return;
12877
12878 // If the conversion context location is invalid don't complain. We also
12879 // don't want to emit a warning if the issue occurs from the expansion of
12880 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12881 // delay this check as long as possible. Once we detect we are in that
12882 // scenario, we just return.
12883 if (CC.isInvalid())
12884 return;
12885
12886 if (Source->isAtomicType())
12887 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
12888
12889 // Diagnose implicit casts to bool.
12890 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool)) {
12891 if (isa<StringLiteral>(Val: E))
12892 // Warn on string literal to bool. Checks for string literals in logical
12893 // and expressions, for instance, assert(0 && "error here"), are
12894 // prevented by a check in AnalyzeImplicitConversions().
12895 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
12896 diag: diag::warn_impcast_string_literal_to_bool);
12897 if (isa<ObjCStringLiteral>(Val: E) || isa<ObjCArrayLiteral>(Val: E) ||
12898 isa<ObjCDictionaryLiteral>(Val: E) || isa<ObjCBoxedExpr>(Val: E)) {
12899 // This covers the literal expressions that evaluate to Objective-C
12900 // objects.
12901 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
12902 diag: diag::warn_impcast_objective_c_literal_to_bool);
12903 }
12904 if (Source->isPointerType() || Source->canDecayToPointerType()) {
12905 // Warn on pointer to bool conversion that is always true.
12906 DiagnoseAlwaysNonNullPointer(E, NullType: Expr::NPCK_NotNull, /*IsEqual*/ false,
12907 Range: SourceRange(CC));
12908 }
12909 }
12910
12911 CheckOverflowBehaviorTypeConversion(E, T, CC);
12912
12913 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12914 // is a typedef for signed char (macOS), then that constant value has to be 1
12915 // or 0.
12916 if (ObjC().isSignedCharBool(Ty: T) && Source->isIntegralType(Ctx: Context)) {
12917 Expr::EvalResult Result;
12918 if (E->EvaluateAsInt(Result, Ctx: getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects)) {
12919 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12920 ObjC().adornBoolConversionDiagWithTernaryFixit(
12921 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
12922 << toString(I: Result.Val.getInt(), Radix: 10));
12923 }
12924 return;
12925 }
12926 }
12927
12928 // Check implicit casts from Objective-C collection literals to specialized
12929 // collection types, e.g., NSArray<NSString *> *.
12930 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Val: E))
12931 ObjC().checkArrayLiteral(TargetType: QualType(Target, 0), ArrayLiteral);
12932 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Val: E))
12933 ObjC().checkDictionaryLiteral(TargetType: QualType(Target, 0), DictionaryLiteral);
12934
12935 // Strip vector types.
12936 if (isa<VectorType>(Val: Source)) {
12937 if (Target->isSveVLSBuiltinType() &&
12938 (ARM().areCompatibleSveTypes(FirstType: QualType(Target, 0),
12939 SecondType: QualType(Source, 0)) ||
12940 ARM().areLaxCompatibleSveTypes(FirstType: QualType(Target, 0),
12941 SecondType: QualType(Source, 0))))
12942 return;
12943
12944 if (Target->isRVVVLSBuiltinType() &&
12945 (Context.areCompatibleRVVTypes(FirstType: QualType(Target, 0),
12946 SecondType: QualType(Source, 0)) ||
12947 Context.areLaxCompatibleRVVTypes(FirstType: QualType(Target, 0),
12948 SecondType: QualType(Source, 0))))
12949 return;
12950
12951 if (!isa<VectorType>(Val: Target)) {
12952 if (SourceMgr.isInSystemMacro(loc: CC))
12953 return;
12954 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_vector_scalar);
12955 }
12956 if (getLangOpts().HLSL &&
12957 Target->castAs<VectorType>()->getNumElements() <
12958 Source->castAs<VectorType>()->getNumElements()) {
12959 // Diagnose vector truncation but don't return. We may also want to
12960 // diagnose an element conversion.
12961 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
12962 diag: diag::warn_hlsl_impcast_vector_truncation);
12963 }
12964
12965 // If the vector cast is cast between two vectors of the same size, it is
12966 // a bitcast, not a conversion, except under HLSL where it is a conversion.
12967 if (!getLangOpts().HLSL &&
12968 Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
12969 return;
12970
12971 Source = cast<VectorType>(Val: Source)->getElementType().getTypePtr();
12972 Target = cast<VectorType>(Val: Target)->getElementType().getTypePtr();
12973 }
12974 if (const auto *VecTy = dyn_cast<VectorType>(Val: Target))
12975 Target = VecTy->getElementType().getTypePtr();
12976
12977 if (isa<ConstantMatrixType>(Val: Source)) {
12978 if (Target->isScalarType())
12979 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_matrix_scalar);
12980
12981 if (getLangOpts().HLSL &&
12982 Target->castAs<ConstantMatrixType>()->getNumElementsFlattened() <
12983 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
12984 // Diagnose Matrix truncation but don't return. We may also want to
12985 // diagnose an element conversion.
12986 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
12987 diag: diag::warn_hlsl_impcast_matrix_truncation);
12988 }
12989 }
12990 // Strip complex types.
12991 if (isa<ComplexType>(Val: Source)) {
12992 if (!isa<ComplexType>(Val: Target)) {
12993 if (SourceMgr.isInSystemMacro(loc: CC) || Target->isBooleanType())
12994 return;
12995
12996 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
12997 diag: getLangOpts().CPlusPlus
12998 ? diag::err_impcast_complex_scalar
12999 : diag::warn_impcast_complex_scalar);
13000 }
13001
13002 Source = cast<ComplexType>(Val: Source)->getElementType().getTypePtr();
13003 Target = cast<ComplexType>(Val: Target)->getElementType().getTypePtr();
13004 }
13005
13006 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Val: Source);
13007 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Val: Target);
13008
13009 // Strip SVE vector types
13010 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13011 // Need the original target type for vector type checks
13012 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13013 // Handle conversion from scalable to fixed when msve-vector-bits is
13014 // specified
13015 if (ARM().areCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13016 SecondType: QualType(Source, 0)) ||
13017 ARM().areLaxCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13018 SecondType: QualType(Source, 0)))
13019 return;
13020
13021 // If the vector cast is cast between two vectors of the same size, it is
13022 // a bitcast, not a conversion.
13023 if (Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13024 return;
13025
13026 Source = SourceBT->getSveEltType(Ctx: Context).getTypePtr();
13027 }
13028
13029 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13030 Target = TargetBT->getSveEltType(Ctx: Context).getTypePtr();
13031
13032 // If the source is floating point...
13033 if (SourceBT && SourceBT->isFloatingPoint()) {
13034 // ...and the target is floating point...
13035 if (TargetBT && TargetBT->isFloatingPoint()) {
13036 // ...then warn if we're dropping FP rank.
13037
13038 int Order = getASTContext().getFloatingTypeSemanticOrder(
13039 LHS: QualType(SourceBT, 0), RHS: QualType(TargetBT, 0));
13040 if (Order > 0) {
13041 // Don't warn about float constants that are precisely
13042 // representable in the target type.
13043 Expr::EvalResult result;
13044 if (E->EvaluateAsRValue(Result&: result, Ctx: Context)) {
13045 // Value might be a float, a float vector, or a float complex.
13046 if (IsSameFloatAfterCast(
13047 value: result.Val,
13048 Src: Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)),
13049 Tgt: Context.getFloatTypeSemantics(T: QualType(SourceBT, 0))))
13050 return;
13051 }
13052
13053 if (SourceMgr.isInSystemMacro(loc: CC))
13054 return;
13055
13056 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_float_precision);
13057 }
13058 // ... or possibly if we're increasing rank, too
13059 else if (Order < 0) {
13060 if (SourceMgr.isInSystemMacro(loc: CC))
13061 return;
13062
13063 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_double_promotion);
13064 }
13065 return;
13066 }
13067
13068 // If the target is integral, always warn.
13069 if (TargetBT && TargetBT->isInteger()) {
13070 if (SourceMgr.isInSystemMacro(loc: CC))
13071 return;
13072
13073 DiagnoseFloatingImpCast(S&: *this, E, T, CContext: CC);
13074 }
13075
13076 // Detect the case where a call result is converted from floating-point to
13077 // to bool, and the final argument to the call is converted from bool, to
13078 // discover this typo:
13079 //
13080 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13081 //
13082 // FIXME: This is an incredibly special case; is there some more general
13083 // way to detect this class of misplaced-parentheses bug?
13084 if (Target->isBooleanType() && isa<CallExpr>(Val: E)) {
13085 // Check last argument of function call to see if it is an
13086 // implicit cast from a type matching the type the result
13087 // is being cast to.
13088 CallExpr *CEx = cast<CallExpr>(Val: E);
13089 if (unsigned NumArgs = CEx->getNumArgs()) {
13090 Expr *LastA = CEx->getArg(Arg: NumArgs - 1);
13091 Expr *InnerE = LastA->IgnoreParenImpCasts();
13092 if (isa<ImplicitCastExpr>(Val: LastA) &&
13093 InnerE->getType()->isBooleanType()) {
13094 // Warn on this floating-point to bool conversion
13095 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13096 diag: diag::warn_impcast_floating_point_to_bool);
13097 }
13098 }
13099 }
13100 return;
13101 }
13102
13103 // Valid casts involving fixed point types should be accounted for here.
13104 if (Source->isFixedPointType()) {
13105 if (Target->isUnsaturatedFixedPointType()) {
13106 Expr::EvalResult Result;
13107 if (E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13108 InConstantContext: isConstantEvaluatedContext())) {
13109 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13110 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(Ty: T);
13111 llvm::APFixedPoint MinVal = Context.getFixedPointMin(Ty: T);
13112 if (Value > MaxVal || Value < MinVal) {
13113 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13114 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13115 << Value.toString() << T
13116 << E->getSourceRange()
13117 << clang::SourceRange(CC));
13118 return;
13119 }
13120 }
13121 } else if (Target->isIntegerType()) {
13122 Expr::EvalResult Result;
13123 if (!isConstantEvaluatedContext() &&
13124 E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13125 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13126
13127 bool Overflowed;
13128 llvm::APSInt IntResult = FXResult.convertToInt(
13129 DstWidth: Context.getIntWidth(T), DstSign: Target->isSignedIntegerOrEnumerationType(),
13130 Overflow: &Overflowed);
13131
13132 if (Overflowed) {
13133 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13134 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13135 << FXResult.toString() << T
13136 << E->getSourceRange()
13137 << clang::SourceRange(CC));
13138 return;
13139 }
13140 }
13141 }
13142 } else if (Target->isUnsaturatedFixedPointType()) {
13143 if (Source->isIntegerType()) {
13144 Expr::EvalResult Result;
13145 if (!isConstantEvaluatedContext() &&
13146 E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13147 llvm::APSInt Value = Result.Val.getInt();
13148
13149 bool Overflowed;
13150 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13151 Value, DstFXSema: Context.getFixedPointSemantics(Ty: T), Overflow: &Overflowed);
13152
13153 if (Overflowed) {
13154 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13155 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13156 << toString(I: Value, /*Radix=*/10) << T
13157 << E->getSourceRange()
13158 << clang::SourceRange(CC));
13159 return;
13160 }
13161 }
13162 }
13163 }
13164
13165 // If we are casting an integer type to a floating point type without
13166 // initialization-list syntax, we might lose accuracy if the floating
13167 // point type has a narrower significand than the integer type.
13168 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13169 TargetBT->isFloatingType() && !IsListInit) {
13170 // Determine the number of precision bits in the source integer type.
13171 std::optional<IntRange> SourceRange =
13172 TryGetExprRange(C&: Context, E, InConstantContext: isConstantEvaluatedContext(),
13173 /*Approximate=*/true);
13174 if (!SourceRange)
13175 return;
13176 unsigned int SourcePrecision = SourceRange->Width;
13177
13178 // Determine the number of precision bits in the
13179 // target floating point type.
13180 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13181 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13182
13183 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13184 SourcePrecision > TargetPrecision) {
13185
13186 if (std::optional<llvm::APSInt> SourceInt =
13187 E->getIntegerConstantExpr(Ctx: Context)) {
13188 // If the source integer is a constant, convert it to the target
13189 // floating point type. Issue a warning if the value changes
13190 // during the whole conversion.
13191 llvm::APFloat TargetFloatValue(
13192 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13193 llvm::APFloat::opStatus ConversionStatus =
13194 TargetFloatValue.convertFromAPInt(
13195 Input: *SourceInt, IsSigned: SourceBT->isSignedInteger(),
13196 RM: llvm::APFloat::rmNearestTiesToEven);
13197
13198 if (ConversionStatus != llvm::APFloat::opOK) {
13199 SmallString<32> PrettySourceValue;
13200 SourceInt->toString(Str&: PrettySourceValue, Radix: 10);
13201 SmallString<32> PrettyTargetValue;
13202 TargetFloatValue.toString(Str&: PrettyTargetValue, FormatPrecision: TargetPrecision);
13203
13204 DiagRuntimeBehavior(
13205 Loc: E->getExprLoc(), Statement: E,
13206 PD: PDiag(DiagID: diag::warn_impcast_integer_float_precision_constant)
13207 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13208 << E->getSourceRange() << clang::SourceRange(CC));
13209 }
13210 } else {
13211 // Otherwise, the implicit conversion may lose precision.
13212 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13213 diag: diag::warn_impcast_integer_float_precision);
13214 }
13215 }
13216 }
13217
13218 DiagnoseNullConversion(S&: *this, E, T, CC);
13219
13220 DiscardMisalignedMemberAddress(T: Target, E);
13221
13222 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13223 DiagnoseMixedUnicodeImplicitConversion(S&: *this, Source, Target, E, T, CC);
13224 return;
13225 }
13226
13227 if (Target->isBooleanType())
13228 DiagnoseIntInBoolContext(S&: *this, E);
13229
13230 if (DiscardingCFIUncheckedCallee(From: QualType(Source, 0), To: QualType(Target, 0))) {
13231 Diag(Loc: CC, DiagID: diag::warn_cast_discards_cfi_unchecked_callee)
13232 << QualType(Source, 0) << QualType(Target, 0);
13233 }
13234
13235 if (!Source->isIntegerType() || !Target->isIntegerType())
13236 return;
13237
13238 // TODO: remove this early return once the false positives for constant->bool
13239 // in templates, macros, etc, are reduced or removed.
13240 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool))
13241 return;
13242
13243 if (ObjC().isSignedCharBool(Ty: T) && !Source->isCharType() &&
13244 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13245 return ObjC().adornBoolConversionDiagWithTernaryFixit(
13246 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_int_to_objc_signed_char_bool)
13247 << E->getType());
13248 }
13249 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13250 C&: Context, E, InConstantContext: isConstantEvaluatedContext(), /*Approximate=*/true);
13251 if (!LikelySourceRange)
13252 return;
13253
13254 IntRange SourceTypeRange =
13255 IntRange::forTargetOfCanonicalType(C&: Context, T: Source);
13256 IntRange TargetRange = IntRange::forTargetOfCanonicalType(C&: Context, T: Target);
13257
13258 if (LikelySourceRange->Width > TargetRange.Width) {
13259 // Check if target is a wrapping OBT - if so, don't warn about constant
13260 // conversion as this type may be used intentionally with implicit
13261 // truncation, especially during assignments.
13262 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13263 if (TargetOBT->isWrapKind()) {
13264 return;
13265 }
13266 }
13267
13268 // Check if source expression has an explicit __ob_wrap cast because if so,
13269 // wrapping was explicitly requested and we shouldn't warn
13270 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13271 if (SourceOBT->isWrapKind()) {
13272 return;
13273 }
13274 }
13275
13276 // If the source is a constant, use a default-on diagnostic.
13277 // TODO: this should happen for bitfield stores, too.
13278 Expr::EvalResult Result;
13279 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13280 InConstantContext: isConstantEvaluatedContext())) {
13281 llvm::APSInt Value(32);
13282 Value = Result.Val.getInt();
13283
13284 if (SourceMgr.isInSystemMacro(loc: CC))
13285 return;
13286
13287 std::string PrettySourceValue = toString(I: Value, Radix: 10);
13288 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
13289
13290 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13291 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
13292 << PrettySourceValue << PrettyTargetValue
13293 << E->getType() << T << E->getSourceRange()
13294 << SourceRange(CC));
13295 return;
13296 }
13297
13298 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13299 if (SourceMgr.isInSystemMacro(loc: CC))
13300 return;
13301
13302 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
13303 if (UO->getOpcode() == UO_Minus)
13304 return DiagnoseImpCast(
13305 S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_precision_on_negation);
13306 }
13307
13308 if (TargetRange.Width == 32 && Context.getIntWidth(T: E->getType()) == 64)
13309 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_64_32,
13310 /* pruneControlFlow */ PruneControlFlow: true);
13311 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13312 diag: diag::warn_impcast_integer_precision);
13313 }
13314
13315 if (TargetRange.Width > SourceTypeRange.Width) {
13316 if (auto *UO = dyn_cast<UnaryOperator>(Val: E))
13317 if (UO->getOpcode() == UO_Minus)
13318 if (Source->isUnsignedIntegerType()) {
13319 if (Target->isUnsignedIntegerType())
13320 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13321 diag: diag::warn_impcast_high_order_zero_bits);
13322 if (Target->isSignedIntegerType())
13323 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13324 diag: diag::warn_impcast_nonnegative_result);
13325 }
13326 }
13327
13328 if (TargetRange.Width == LikelySourceRange->Width &&
13329 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13330 Source->isSignedIntegerType()) {
13331 // Warn when doing a signed to signed conversion, warn if the positive
13332 // source value is exactly the width of the target type, which will
13333 // cause a negative value to be stored.
13334
13335 Expr::EvalResult Result;
13336 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects) &&
13337 !SourceMgr.isInSystemMacro(loc: CC)) {
13338 llvm::APSInt Value = Result.Val.getInt();
13339 if (isSameWidthConstantConversion(S&: *this, E, T, CC)) {
13340 std::string PrettySourceValue = toString(I: Value, Radix: 10);
13341 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
13342
13343 Diag(Loc: E->getExprLoc(),
13344 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
13345 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13346 << E->getSourceRange() << SourceRange(CC));
13347 return;
13348 }
13349 }
13350
13351 // Fall through for non-constants to give a sign conversion warning.
13352 }
13353
13354 if ((!isa<EnumType>(Val: Target) || !isa<EnumType>(Val: Source)) &&
13355 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13356 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13357 LikelySourceRange->Width == TargetRange.Width))) {
13358 if (SourceMgr.isInSystemMacro(loc: CC))
13359 return;
13360
13361 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13362 TargetBT->isInteger() &&
13363 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13364 return;
13365 }
13366
13367 unsigned DiagID = diag::warn_impcast_integer_sign;
13368
13369 // Traditionally, gcc has warned about this under -Wsign-compare.
13370 // We also want to warn about it in -Wconversion.
13371 // So if -Wconversion is off, use a completely identical diagnostic
13372 // in the sign-compare group.
13373 // The conditional-checking code will
13374 if (ICContext) {
13375 DiagID = diag::warn_impcast_integer_sign_conditional;
13376 *ICContext = true;
13377 }
13378
13379 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagID);
13380 }
13381
13382 // If we're implicitly converting from an integer into an enumeration, that
13383 // is valid in C but invalid in C++.
13384 QualType SourceType = E->getEnumCoercedType(Ctx: Context);
13385 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13386 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Val: Target))
13387 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_int_to_enum);
13388
13389 // Diagnose conversions between different enumeration types.
13390 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13391 // type, to give us better diagnostics.
13392 Source = Context.getCanonicalType(T: SourceType).getTypePtr();
13393
13394 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13395 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13396 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13397 TargetEnum->getDecl()->hasNameForLinkage() &&
13398 SourceEnum != TargetEnum) {
13399 if (SourceMgr.isInSystemMacro(loc: CC))
13400 return;
13401
13402 return DiagnoseImpCast(S&: *this, E, SourceType, T, CContext: CC,
13403 diag: diag::warn_impcast_different_enum_types);
13404 }
13405}
13406
13407static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13408 SourceLocation CC, QualType T);
13409
13410static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13411 SourceLocation CC, bool &ICContext) {
13412 E = E->IgnoreParenImpCasts();
13413 // Diagnose incomplete type for second or third operand in C.
13414 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13415 S.RequireCompleteExprType(E, DiagID: diag::err_incomplete_type);
13416
13417 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: E))
13418 return CheckConditionalOperator(S, E: CO, CC, T);
13419
13420 AnalyzeImplicitConversions(S, E, CC);
13421 if (E->getType() != T)
13422 return S.CheckImplicitConversion(E, T, CC, ICContext: &ICContext);
13423}
13424
13425static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13426 SourceLocation CC, QualType T) {
13427 AnalyzeImplicitConversions(S, E: E->getCond(), CC: E->getQuestionLoc());
13428
13429 Expr *TrueExpr = E->getTrueExpr();
13430 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(Val: E))
13431 TrueExpr = BCO->getCommon();
13432
13433 bool Suspicious = false;
13434 CheckConditionalOperand(S, E: TrueExpr, T, CC, ICContext&: Suspicious);
13435 CheckConditionalOperand(S, E: E->getFalseExpr(), T, CC, ICContext&: Suspicious);
13436
13437 if (T->isBooleanType())
13438 DiagnoseIntInBoolContext(S, E);
13439
13440 // If -Wconversion would have warned about either of the candidates
13441 // for a signedness conversion to the context type...
13442 if (!Suspicious) return;
13443
13444 // ...but it's currently ignored...
13445 if (!S.Diags.isIgnored(DiagID: diag::warn_impcast_integer_sign_conditional, Loc: CC))
13446 return;
13447
13448 // ...then check whether it would have warned about either of the
13449 // candidates for a signedness conversion to the condition type.
13450 if (E->getType() == T) return;
13451
13452 Suspicious = false;
13453 S.CheckImplicitConversion(E: TrueExpr->IgnoreParenImpCasts(), T: E->getType(), CC,
13454 ICContext: &Suspicious);
13455 if (!Suspicious)
13456 S.CheckImplicitConversion(E: E->getFalseExpr()->IgnoreParenImpCasts(),
13457 T: E->getType(), CC, ICContext: &Suspicious);
13458}
13459
13460/// Check conversion of given expression to boolean.
13461/// Input argument E is a logical expression.
13462static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13463 // Run the bool-like conversion checks only for C since there bools are
13464 // still not used as the return type from "boolean" operators or as the input
13465 // type for conditional operators.
13466 if (S.getLangOpts().CPlusPlus)
13467 return;
13468 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13469 return;
13470 S.CheckImplicitConversion(E: E->IgnoreParenImpCasts(), T: S.Context.BoolTy, CC);
13471}
13472
13473namespace {
13474struct AnalyzeImplicitConversionsWorkItem {
13475 Expr *E;
13476 SourceLocation CC;
13477 bool IsListInit;
13478};
13479}
13480
13481static void CheckCommaOperand(
13482 Sema &S, Expr *E, QualType T, SourceLocation CC,
13483 bool ExtraCheckForImplicitConversion,
13484 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13485 E = E->IgnoreParenImpCasts();
13486 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: false});
13487
13488 if (ExtraCheckForImplicitConversion && E->getType() != T)
13489 S.CheckImplicitConversion(E, T, CC);
13490}
13491
13492/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13493/// that should be visited are added to WorkList.
13494static void AnalyzeImplicitConversions(
13495 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13496 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13497 Expr *OrigE = Item.E;
13498 SourceLocation CC = Item.CC;
13499
13500 QualType T = OrigE->getType();
13501 Expr *E = OrigE->IgnoreParenImpCasts();
13502
13503 // Propagate whether we are in a C++ list initialization expression.
13504 // If so, we do not issue warnings for implicit int-float conversion
13505 // precision loss, because C++11 narrowing already handles it.
13506 //
13507 // HLSL's initialization lists are special, so they shouldn't observe the C++
13508 // behavior here.
13509 bool IsListInit =
13510 Item.IsListInit || (isa<InitListExpr>(Val: OrigE) &&
13511 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13512
13513 if (E->isTypeDependent() || E->isValueDependent())
13514 return;
13515
13516 Expr *SourceExpr = E;
13517 // Examine, but don't traverse into the source expression of an
13518 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13519 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13520 // evaluate it in the context of checking the specific conversion to T though.
13521 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
13522 if (auto *Src = OVE->getSourceExpr())
13523 SourceExpr = Src;
13524
13525 if (const auto *UO = dyn_cast<UnaryOperator>(Val: SourceExpr))
13526 if (UO->getOpcode() == UO_Not &&
13527 UO->getSubExpr()->isKnownToHaveBooleanValue())
13528 S.Diag(Loc: UO->getBeginLoc(), DiagID: diag::warn_bitwise_negation_bool)
13529 << OrigE->getSourceRange() << T->isBooleanType()
13530 << FixItHint::CreateReplacement(RemoveRange: UO->getBeginLoc(), Code: "!");
13531
13532 if (auto *BO = dyn_cast<BinaryOperator>(Val: SourceExpr)) {
13533 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13534 BO->getLHS()->isKnownToHaveBooleanValue() &&
13535 BO->getRHS()->isKnownToHaveBooleanValue() &&
13536 BO->getLHS()->HasSideEffects(Ctx: S.Context) &&
13537 BO->getRHS()->HasSideEffects(Ctx: S.Context)) {
13538 SourceManager &SM = S.getSourceManager();
13539 const LangOptions &LO = S.getLangOpts();
13540 SourceLocation BLoc = BO->getOperatorLoc();
13541 SourceLocation ELoc = Lexer::getLocForEndOfToken(Loc: BLoc, Offset: 0, SM, LangOpts: LO);
13542 StringRef SR = clang::Lexer::getSourceText(
13543 Range: clang::CharSourceRange::getTokenRange(B: BLoc, E: ELoc), SM, LangOpts: LO);
13544 // To reduce false positives, only issue the diagnostic if the operator
13545 // is explicitly spelled as a punctuator. This suppresses the diagnostic
13546 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
13547 // in C, along with other macro spellings the user might invent.
13548 if (SR.str() == "&" || SR.str() == "|") {
13549
13550 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_bitwise_instead_of_logical)
13551 << (BO->getOpcode() == BO_And ? "&" : "|")
13552 << OrigE->getSourceRange()
13553 << FixItHint::CreateReplacement(
13554 RemoveRange: BO->getOperatorLoc(),
13555 Code: (BO->getOpcode() == BO_And ? "&&" : "||"));
13556 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::note_cast_operand_to_int);
13557 }
13558 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
13559 /// Analyze the given comma operator. The basic idea behind the analysis
13560 /// is to analyze the left and right operands slightly differently. The
13561 /// left operand needs to check whether the operand itself has an implicit
13562 /// conversion, but not whether the left operand induces an implicit
13563 /// conversion for the entire comma expression itself. This is similar to
13564 /// how CheckConditionalOperand behaves; it's as-if the correct operand
13565 /// were directly used for the implicit conversion check.
13566 CheckCommaOperand(S, E: BO->getLHS(), T, CC: BO->getOperatorLoc(),
13567 /*ExtraCheckForImplicitConversion=*/false, WorkList);
13568 CheckCommaOperand(S, E: BO->getRHS(), T, CC: BO->getOperatorLoc(),
13569 /*ExtraCheckForImplicitConversion=*/true, WorkList);
13570 return;
13571 }
13572 }
13573
13574 // For conditional operators, we analyze the arguments as if they
13575 // were being fed directly into the output.
13576 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: SourceExpr)) {
13577 CheckConditionalOperator(S, E: CO, CC, T);
13578 return;
13579 }
13580
13581 // Check implicit argument conversions for function calls.
13582 if (const auto *Call = dyn_cast<CallExpr>(Val: SourceExpr))
13583 CheckImplicitArgumentConversions(S, TheCall: Call, CC);
13584
13585 // Go ahead and check any implicit conversions we might have skipped.
13586 // The non-canonical typecheck is just an optimization;
13587 // CheckImplicitConversion will filter out dead implicit conversions.
13588 if (SourceExpr->getType() != T)
13589 S.CheckImplicitConversion(E: SourceExpr, T, CC, ICContext: nullptr, IsListInit);
13590
13591 // Now continue drilling into this expression.
13592
13593 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E)) {
13594 // The bound subexpressions in a PseudoObjectExpr are not reachable
13595 // as transitive children.
13596 // FIXME: Use a more uniform representation for this.
13597 for (auto *SE : POE->semantics())
13598 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: SE))
13599 WorkList.push_back(Elt: {.E: OVE->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
13600 }
13601
13602 // Skip past explicit casts.
13603 if (auto *CE = dyn_cast<ExplicitCastExpr>(Val: E)) {
13604 E = CE->getSubExpr();
13605 // In the special case of a C++ function-style cast with braces,
13606 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
13607 // initializer. This InitListExpr basically belongs to the cast itself, so
13608 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
13609 if (isa<CXXFunctionalCastExpr>(Val: CE)) {
13610 if (auto *InitListE = dyn_cast<InitListExpr>(Val: E)) {
13611 if (InitListE->getNumInits() == 1) {
13612 E = InitListE->getInit(Init: 0);
13613 }
13614 }
13615 }
13616 E = E->IgnoreParenImpCasts();
13617 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13618 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13619 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: IsListInit});
13620 return;
13621 }
13622
13623 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(Val: E)) {
13624 WorkList.push_back(Elt: {.E: OutArgE->getArgLValue(), .CC: CC, .IsListInit: IsListInit});
13625 // The base expression is only used to initialize the parameter for
13626 // arguments to `inout` parameters, so we only traverse down the base
13627 // expression for `inout` cases.
13628 if (OutArgE->isInOut())
13629 WorkList.push_back(
13630 Elt: {.E: OutArgE->getCastedTemporary()->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
13631 WorkList.push_back(Elt: {.E: OutArgE->getWritebackCast(), .CC: CC, .IsListInit: IsListInit});
13632 return;
13633 }
13634
13635 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
13636 // Do a somewhat different check with comparison operators.
13637 if (BO->isComparisonOp())
13638 return AnalyzeComparison(S, E: BO);
13639
13640 // And with simple assignments.
13641 if (BO->getOpcode() == BO_Assign)
13642 return AnalyzeAssignment(S, E: BO);
13643 // And with compound assignments.
13644 if (BO->isAssignmentOp())
13645 return AnalyzeCompoundAssignment(S, E: BO);
13646 }
13647
13648 // These break the otherwise-useful invariant below. Fortunately,
13649 // we don't really need to recurse into them, because any internal
13650 // expressions should have been analyzed already when they were
13651 // built into statements.
13652 if (isa<StmtExpr>(Val: E)) return;
13653
13654 // Don't descend into unevaluated contexts.
13655 if (isa<UnaryExprOrTypeTraitExpr>(Val: E)) return;
13656
13657 // Now just recurse over the expression's children.
13658 CC = E->getExprLoc();
13659 BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E);
13660 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13661 for (Stmt *SubStmt : E->children()) {
13662 Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: SubStmt);
13663 if (!ChildExpr)
13664 continue;
13665
13666 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(Val: E))
13667 if (ChildExpr == CSE->getOperand())
13668 // Do not recurse over a CoroutineSuspendExpr's operand.
13669 // The operand is also a subexpression of getCommonExpr(), and
13670 // recursing into it directly would produce duplicate diagnostics.
13671 continue;
13672
13673 if (IsLogicalAndOperator &&
13674 isa<StringLiteral>(Val: ChildExpr->IgnoreParenImpCasts()))
13675 // Ignore checking string literals that are in logical and operators.
13676 // This is a common pattern for asserts.
13677 continue;
13678 WorkList.push_back(Elt: {.E: ChildExpr, .CC: CC, .IsListInit: IsListInit});
13679 }
13680
13681 if (BO && BO->isLogicalOp()) {
13682 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13683 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
13684 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
13685
13686 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13687 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
13688 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
13689 }
13690
13691 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(Val: E)) {
13692 if (U->getOpcode() == UO_LNot) {
13693 ::CheckBoolLikeConversion(S, E: U->getSubExpr(), CC);
13694 } else if (U->getOpcode() != UO_AddrOf) {
13695 if (U->getSubExpr()->getType()->isAtomicType())
13696 S.Diag(Loc: U->getSubExpr()->getBeginLoc(),
13697 DiagID: diag::warn_atomic_implicit_seq_cst);
13698 }
13699 }
13700}
13701
13702/// AnalyzeImplicitConversions - Find and report any interesting
13703/// implicit conversions in the given expression. There are a couple
13704/// of competing diagnostics here, -Wconversion and -Wsign-compare.
13705static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13706 bool IsListInit/*= false*/) {
13707 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13708 WorkList.push_back(Elt: {.E: OrigE, .CC: CC, .IsListInit: IsListInit});
13709 while (!WorkList.empty())
13710 AnalyzeImplicitConversions(S, Item: WorkList.pop_back_val(), WorkList);
13711}
13712
13713// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13714// Returns true when emitting a warning about taking the address of a reference.
13715static bool CheckForReference(Sema &SemaRef, const Expr *E,
13716 const PartialDiagnostic &PD) {
13717 E = E->IgnoreParenImpCasts();
13718
13719 const FunctionDecl *FD = nullptr;
13720
13721 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
13722 if (!DRE->getDecl()->getType()->isReferenceType())
13723 return false;
13724 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
13725 if (!M->getMemberDecl()->getType()->isReferenceType())
13726 return false;
13727 } else if (const CallExpr *Call = dyn_cast<CallExpr>(Val: E)) {
13728 if (!Call->getCallReturnType(Ctx: SemaRef.Context)->isReferenceType())
13729 return false;
13730 FD = Call->getDirectCallee();
13731 } else {
13732 return false;
13733 }
13734
13735 SemaRef.Diag(Loc: E->getExprLoc(), PD);
13736
13737 // If possible, point to location of function.
13738 if (FD) {
13739 SemaRef.Diag(Loc: FD->getLocation(), DiagID: diag::note_reference_is_return_value) << FD;
13740 }
13741
13742 return true;
13743}
13744
13745// Returns true if the SourceLocation is expanded from any macro body.
13746// Returns false if the SourceLocation is invalid, is from not in a macro
13747// expansion, or is from expanded from a top-level macro argument.
13748static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13749 if (Loc.isInvalid())
13750 return false;
13751
13752 while (Loc.isMacroID()) {
13753 if (SM.isMacroBodyExpansion(Loc))
13754 return true;
13755 Loc = SM.getImmediateMacroCallerLoc(Loc);
13756 }
13757
13758 return false;
13759}
13760
13761void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13762 Expr::NullPointerConstantKind NullKind,
13763 bool IsEqual, SourceRange Range) {
13764 if (!E)
13765 return;
13766
13767 // Don't warn inside macros.
13768 if (E->getExprLoc().isMacroID()) {
13769 const SourceManager &SM = getSourceManager();
13770 if (IsInAnyMacroBody(SM, Loc: E->getExprLoc()) ||
13771 IsInAnyMacroBody(SM, Loc: Range.getBegin()))
13772 return;
13773 }
13774 E = E->IgnoreImpCasts();
13775
13776 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13777
13778 if (isa<CXXThisExpr>(Val: E)) {
13779 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13780 : diag::warn_this_bool_conversion;
13781 Diag(Loc: E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13782 return;
13783 }
13784
13785 bool IsAddressOf = false;
13786
13787 if (auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParens())) {
13788 if (UO->getOpcode() != UO_AddrOf)
13789 return;
13790 IsAddressOf = true;
13791 E = UO->getSubExpr();
13792 }
13793
13794 if (IsAddressOf) {
13795 unsigned DiagID = IsCompare
13796 ? diag::warn_address_of_reference_null_compare
13797 : diag::warn_address_of_reference_bool_conversion;
13798 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13799 << IsEqual;
13800 if (CheckForReference(SemaRef&: *this, E, PD)) {
13801 return;
13802 }
13803 }
13804
13805 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13806 bool IsParam = isa<NonNullAttr>(Val: NonnullAttr);
13807 std::string Str;
13808 llvm::raw_string_ostream S(Str);
13809 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
13810 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13811 : diag::warn_cast_nonnull_to_bool;
13812 Diag(Loc: E->getExprLoc(), DiagID) << IsParam << S.str()
13813 << E->getSourceRange() << Range << IsEqual;
13814 Diag(Loc: NonnullAttr->getLocation(), DiagID: diag::note_declared_nonnull) << IsParam;
13815 };
13816
13817 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13818 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts())) {
13819 if (auto *Callee = Call->getDirectCallee()) {
13820 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13821 ComplainAboutNonnullParamOrCall(A);
13822 return;
13823 }
13824 }
13825 }
13826
13827 // Complain if we are converting a lambda expression to a boolean value
13828 // outside of instantiation.
13829 if (!inTemplateInstantiation()) {
13830 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(Val: E)) {
13831 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
13832 MRecordDecl && MRecordDecl->isLambda()) {
13833 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_impcast_pointer_to_bool)
13834 << /*LambdaPointerConversionOperatorType=*/3
13835 << MRecordDecl->getSourceRange() << Range << IsEqual;
13836 return;
13837 }
13838 }
13839 }
13840
13841 // Expect to find a single Decl. Skip anything more complicated.
13842 ValueDecl *D = nullptr;
13843 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(Val: E)) {
13844 D = R->getDecl();
13845 } else if (MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
13846 D = M->getMemberDecl();
13847 }
13848
13849 // Weak Decls can be null.
13850 if (!D || D->isWeak())
13851 return;
13852
13853 // Check for parameter decl with nonnull attribute
13854 if (const auto* PV = dyn_cast<ParmVarDecl>(Val: D)) {
13855 if (getCurFunction() &&
13856 !getCurFunction()->ModifiedNonNullParams.count(Ptr: PV)) {
13857 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13858 ComplainAboutNonnullParamOrCall(A);
13859 return;
13860 }
13861
13862 if (const auto *FD = dyn_cast<FunctionDecl>(Val: PV->getDeclContext())) {
13863 // Skip function template not specialized yet.
13864 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13865 return;
13866 auto ParamIter = llvm::find(Range: FD->parameters(), Val: PV);
13867 assert(ParamIter != FD->param_end());
13868 unsigned ParamNo = std::distance(first: FD->param_begin(), last: ParamIter);
13869
13870 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13871 if (!NonNull->args_size()) {
13872 ComplainAboutNonnullParamOrCall(NonNull);
13873 return;
13874 }
13875
13876 for (const ParamIdx &ArgNo : NonNull->args()) {
13877 if (ArgNo.getASTIndex() == ParamNo) {
13878 ComplainAboutNonnullParamOrCall(NonNull);
13879 return;
13880 }
13881 }
13882 }
13883 }
13884 }
13885 }
13886
13887 QualType T = D->getType();
13888 const bool IsArray = T->isArrayType();
13889 const bool IsFunction = T->isFunctionType();
13890
13891 // Address of function is used to silence the function warning.
13892 if (IsAddressOf && IsFunction) {
13893 return;
13894 }
13895
13896 // Found nothing.
13897 if (!IsAddressOf && !IsFunction && !IsArray)
13898 return;
13899
13900 // Pretty print the expression for the diagnostic.
13901 std::string Str;
13902 llvm::raw_string_ostream S(Str);
13903 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
13904
13905 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13906 : diag::warn_impcast_pointer_to_bool;
13907 enum {
13908 AddressOf,
13909 FunctionPointer,
13910 ArrayPointer
13911 } DiagType;
13912 if (IsAddressOf)
13913 DiagType = AddressOf;
13914 else if (IsFunction)
13915 DiagType = FunctionPointer;
13916 else if (IsArray)
13917 DiagType = ArrayPointer;
13918 else
13919 llvm_unreachable("Could not determine diagnostic.");
13920 Diag(Loc: E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13921 << Range << IsEqual;
13922
13923 if (!IsFunction)
13924 return;
13925
13926 // Suggest '&' to silence the function warning.
13927 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_warning_silence)
13928 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "&");
13929
13930 // Check to see if '()' fixit should be emitted.
13931 QualType ReturnType;
13932 UnresolvedSet<4> NonTemplateOverloads;
13933 tryExprAsCall(E&: *E, ZeroArgCallReturnTy&: ReturnType, NonTemplateOverloads);
13934 if (ReturnType.isNull())
13935 return;
13936
13937 if (IsCompare) {
13938 // There are two cases here. If there is null constant, the only suggest
13939 // for a pointer return type. If the null is 0, then suggest if the return
13940 // type is a pointer or an integer type.
13941 if (!ReturnType->isPointerType()) {
13942 if (NullKind == Expr::NPCK_ZeroExpression ||
13943 NullKind == Expr::NPCK_ZeroLiteral) {
13944 if (!ReturnType->isIntegerType())
13945 return;
13946 } else {
13947 return;
13948 }
13949 }
13950 } else { // !IsCompare
13951 // For function to bool, only suggest if the function pointer has bool
13952 // return type.
13953 if (!ReturnType->isSpecificBuiltinType(K: BuiltinType::Bool))
13954 return;
13955 }
13956 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_to_function_call)
13957 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: E->getEndLoc()), Code: "()");
13958}
13959
13960bool Sema::CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
13961 SourceLocation CC) {
13962 QualType Source = E->getType();
13963 QualType Target = T;
13964
13965 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
13966 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
13967 // Overflow behavior type is being stripped - issue warning
13968 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
13969 Target->isUnsignedIntegerType()) {
13970 // For unsigned wrap to unsigned conversions, use pedantic version
13971 unsigned DiagId =
13972 InOverflowBehaviorAssignmentContext
13973 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
13974 : diag::warn_impcast_overflow_behavior_pedantic;
13975 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
13976 } else {
13977 unsigned DiagId = InOverflowBehaviorAssignmentContext
13978 ? diag::warn_impcast_overflow_behavior_assignment
13979 : diag::warn_impcast_overflow_behavior;
13980 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
13981 }
13982 }
13983 }
13984
13985 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13986 if (TargetOBT->isWrapKind()) {
13987 return true;
13988 }
13989 }
13990
13991 return false;
13992}
13993
13994void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13995 // Don't diagnose in unevaluated contexts.
13996 if (isUnevaluatedContext())
13997 return;
13998
13999 // Don't diagnose for value- or type-dependent expressions.
14000 if (E->isTypeDependent() || E->isValueDependent())
14001 return;
14002
14003 // Check for array bounds violations in cases where the check isn't triggered
14004 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14005 // ArraySubscriptExpr is on the RHS of a variable initialization.
14006 CheckArrayAccess(E);
14007
14008 // This is not the right CC for (e.g.) a variable initialization.
14009 AnalyzeImplicitConversions(S&: *this, OrigE: E, CC);
14010}
14011
14012void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14013 ::CheckBoolLikeConversion(S&: *this, E, CC);
14014}
14015
14016void Sema::CheckForIntOverflow (const Expr *E) {
14017 // Use a work list to deal with nested struct initializers.
14018 SmallVector<const Expr *, 2> Exprs(1, E);
14019
14020 do {
14021 const Expr *OriginalE = Exprs.pop_back_val();
14022 const Expr *E = OriginalE->IgnoreParenCasts();
14023
14024 if (isa<BinaryOperator, UnaryOperator>(Val: E)) {
14025 E->EvaluateForOverflow(Ctx: Context);
14026 continue;
14027 }
14028
14029 if (const auto *InitList = dyn_cast<InitListExpr>(Val: OriginalE))
14030 Exprs.append(in_start: InitList->inits().begin(), in_end: InitList->inits().end());
14031 else if (isa<ObjCBoxedExpr>(Val: OriginalE))
14032 E->EvaluateForOverflow(Ctx: Context);
14033 else if (const auto *Call = dyn_cast<CallExpr>(Val: E))
14034 Exprs.append(in_start: Call->arg_begin(), in_end: Call->arg_end());
14035 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(Val: E))
14036 Exprs.append(in_start: Message->arg_begin(), in_end: Message->arg_end());
14037 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(Val: E))
14038 Exprs.append(in_start: Construct->arg_begin(), in_end: Construct->arg_end());
14039 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(Val: E))
14040 Exprs.push_back(Elt: Temporary->getSubExpr());
14041 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(Val: E))
14042 Exprs.push_back(Elt: Array->getIdx());
14043 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(Val: E))
14044 Exprs.push_back(Elt: Compound->getInitializer());
14045 else if (const auto *New = dyn_cast<CXXNewExpr>(Val: E);
14046 New && New->isArray()) {
14047 if (auto ArraySize = New->getArraySize())
14048 Exprs.push_back(Elt: *ArraySize);
14049 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: OriginalE))
14050 Exprs.push_back(Elt: MTE->getSubExpr());
14051 } while (!Exprs.empty());
14052}
14053
14054namespace {
14055
14056/// Visitor for expressions which looks for unsequenced operations on the
14057/// same object.
14058class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14059 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14060
14061 /// A tree of sequenced regions within an expression. Two regions are
14062 /// unsequenced if one is an ancestor or a descendent of the other. When we
14063 /// finish processing an expression with sequencing, such as a comma
14064 /// expression, we fold its tree nodes into its parent, since they are
14065 /// unsequenced with respect to nodes we will visit later.
14066 class SequenceTree {
14067 struct Value {
14068 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14069 unsigned Parent : 31;
14070 LLVM_PREFERRED_TYPE(bool)
14071 unsigned Merged : 1;
14072 };
14073 SmallVector<Value, 8> Values;
14074
14075 public:
14076 /// A region within an expression which may be sequenced with respect
14077 /// to some other region.
14078 class Seq {
14079 friend class SequenceTree;
14080
14081 unsigned Index;
14082
14083 explicit Seq(unsigned N) : Index(N) {}
14084
14085 public:
14086 Seq() : Index(0) {}
14087 };
14088
14089 SequenceTree() { Values.push_back(Elt: Value(0)); }
14090 Seq root() const { return Seq(0); }
14091
14092 /// Create a new sequence of operations, which is an unsequenced
14093 /// subset of \p Parent. This sequence of operations is sequenced with
14094 /// respect to other children of \p Parent.
14095 Seq allocate(Seq Parent) {
14096 Values.push_back(Elt: Value(Parent.Index));
14097 return Seq(Values.size() - 1);
14098 }
14099
14100 /// Merge a sequence of operations into its parent.
14101 void merge(Seq S) {
14102 Values[S.Index].Merged = true;
14103 }
14104
14105 /// Determine whether two operations are unsequenced. This operation
14106 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14107 /// should have been merged into its parent as appropriate.
14108 bool isUnsequenced(Seq Cur, Seq Old) {
14109 unsigned C = representative(K: Cur.Index);
14110 unsigned Target = representative(K: Old.Index);
14111 while (C >= Target) {
14112 if (C == Target)
14113 return true;
14114 C = Values[C].Parent;
14115 }
14116 return false;
14117 }
14118
14119 private:
14120 /// Pick a representative for a sequence.
14121 unsigned representative(unsigned K) {
14122 if (Values[K].Merged)
14123 // Perform path compression as we go.
14124 return Values[K].Parent = representative(K: Values[K].Parent);
14125 return K;
14126 }
14127 };
14128
14129 /// An object for which we can track unsequenced uses.
14130 using Object = const NamedDecl *;
14131
14132 /// Different flavors of object usage which we track. We only track the
14133 /// least-sequenced usage of each kind.
14134 enum UsageKind {
14135 /// A read of an object. Multiple unsequenced reads are OK.
14136 UK_Use,
14137
14138 /// A modification of an object which is sequenced before the value
14139 /// computation of the expression, such as ++n in C++.
14140 UK_ModAsValue,
14141
14142 /// A modification of an object which is not sequenced before the value
14143 /// computation of the expression, such as n++.
14144 UK_ModAsSideEffect,
14145
14146 UK_Count = UK_ModAsSideEffect + 1
14147 };
14148
14149 /// Bundle together a sequencing region and the expression corresponding
14150 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14151 struct Usage {
14152 const Expr *UsageExpr = nullptr;
14153 SequenceTree::Seq Seq;
14154
14155 Usage() = default;
14156 };
14157
14158 struct UsageInfo {
14159 Usage Uses[UK_Count];
14160
14161 /// Have we issued a diagnostic for this object already?
14162 bool Diagnosed = false;
14163
14164 UsageInfo();
14165 };
14166 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14167
14168 Sema &SemaRef;
14169
14170 /// Sequenced regions within the expression.
14171 SequenceTree Tree;
14172
14173 /// Declaration modifications and references which we have seen.
14174 UsageInfoMap UsageMap;
14175
14176 /// The region we are currently within.
14177 SequenceTree::Seq Region;
14178
14179 /// Filled in with declarations which were modified as a side-effect
14180 /// (that is, post-increment operations).
14181 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14182
14183 /// Expressions to check later. We defer checking these to reduce
14184 /// stack usage.
14185 SmallVectorImpl<const Expr *> &WorkList;
14186
14187 /// RAII object wrapping the visitation of a sequenced subexpression of an
14188 /// expression. At the end of this process, the side-effects of the evaluation
14189 /// become sequenced with respect to the value computation of the result, so
14190 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14191 /// UK_ModAsValue.
14192 struct SequencedSubexpression {
14193 SequencedSubexpression(SequenceChecker &Self)
14194 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14195 Self.ModAsSideEffect = &ModAsSideEffect;
14196 }
14197
14198 ~SequencedSubexpression() {
14199 for (const std::pair<Object, Usage> &M : llvm::reverse(C&: ModAsSideEffect)) {
14200 // Add a new usage with usage kind UK_ModAsValue, and then restore
14201 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14202 // the previous one was empty).
14203 UsageInfo &UI = Self.UsageMap[M.first];
14204 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14205 Self.addUsage(O: M.first, UI, UsageExpr: SideEffectUsage.UsageExpr, UK: UK_ModAsValue);
14206 SideEffectUsage = M.second;
14207 }
14208 Self.ModAsSideEffect = OldModAsSideEffect;
14209 }
14210
14211 SequenceChecker &Self;
14212 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14213 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14214 };
14215
14216 /// RAII object wrapping the visitation of a subexpression which we might
14217 /// choose to evaluate as a constant. If any subexpression is evaluated and
14218 /// found to be non-constant, this allows us to suppress the evaluation of
14219 /// the outer expression.
14220 class EvaluationTracker {
14221 public:
14222 EvaluationTracker(SequenceChecker &Self)
14223 : Self(Self), Prev(Self.EvalTracker) {
14224 Self.EvalTracker = this;
14225 }
14226
14227 ~EvaluationTracker() {
14228 Self.EvalTracker = Prev;
14229 if (Prev)
14230 Prev->EvalOK &= EvalOK;
14231 }
14232
14233 bool evaluate(const Expr *E, bool &Result) {
14234 if (!EvalOK || E->isValueDependent())
14235 return false;
14236 EvalOK = E->EvaluateAsBooleanCondition(
14237 Result, Ctx: Self.SemaRef.Context,
14238 InConstantContext: Self.SemaRef.isConstantEvaluatedContext());
14239 return EvalOK;
14240 }
14241
14242 private:
14243 SequenceChecker &Self;
14244 EvaluationTracker *Prev;
14245 bool EvalOK = true;
14246 } *EvalTracker = nullptr;
14247
14248 /// Find the object which is produced by the specified expression,
14249 /// if any.
14250 Object getObject(const Expr *E, bool Mod) const {
14251 E = E->IgnoreParenCasts();
14252 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) {
14253 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14254 return getObject(E: UO->getSubExpr(), Mod);
14255 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
14256 if (BO->getOpcode() == BO_Comma)
14257 return getObject(E: BO->getRHS(), Mod);
14258 if (Mod && BO->isAssignmentOp())
14259 return getObject(E: BO->getLHS(), Mod);
14260 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14261 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14262 if (isa<CXXThisExpr>(Val: ME->getBase()->IgnoreParenCasts()))
14263 return ME->getMemberDecl();
14264 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14265 // FIXME: If this is a reference, map through to its value.
14266 return DRE->getDecl();
14267 return nullptr;
14268 }
14269
14270 /// Note that an object \p O was modified or used by an expression
14271 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14272 /// the object \p O as obtained via the \p UsageMap.
14273 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14274 // Get the old usage for the given object and usage kind.
14275 Usage &U = UI.Uses[UK];
14276 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq)) {
14277 // If we have a modification as side effect and are in a sequenced
14278 // subexpression, save the old Usage so that we can restore it later
14279 // in SequencedSubexpression::~SequencedSubexpression.
14280 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14281 ModAsSideEffect->push_back(Elt: std::make_pair(x&: O, y&: U));
14282 // Then record the new usage with the current sequencing region.
14283 U.UsageExpr = UsageExpr;
14284 U.Seq = Region;
14285 }
14286 }
14287
14288 /// Check whether a modification or use of an object \p O in an expression
14289 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14290 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14291 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14292 /// usage and false we are checking for a mod-use unsequenced usage.
14293 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14294 UsageKind OtherKind, bool IsModMod) {
14295 if (UI.Diagnosed)
14296 return;
14297
14298 const Usage &U = UI.Uses[OtherKind];
14299 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq))
14300 return;
14301
14302 const Expr *Mod = U.UsageExpr;
14303 const Expr *ModOrUse = UsageExpr;
14304 if (OtherKind == UK_Use)
14305 std::swap(a&: Mod, b&: ModOrUse);
14306
14307 SemaRef.DiagRuntimeBehavior(
14308 Loc: Mod->getExprLoc(), Stmts: {Mod, ModOrUse},
14309 PD: SemaRef.PDiag(DiagID: IsModMod ? diag::warn_unsequenced_mod_mod
14310 : diag::warn_unsequenced_mod_use)
14311 << O << SourceRange(ModOrUse->getExprLoc()));
14312 UI.Diagnosed = true;
14313 }
14314
14315 // A note on note{Pre, Post}{Use, Mod}:
14316 //
14317 // (It helps to follow the algorithm with an expression such as
14318 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14319 // operations before C++17 and both are well-defined in C++17).
14320 //
14321 // When visiting a node which uses/modify an object we first call notePreUse
14322 // or notePreMod before visiting its sub-expression(s). At this point the
14323 // children of the current node have not yet been visited and so the eventual
14324 // uses/modifications resulting from the children of the current node have not
14325 // been recorded yet.
14326 //
14327 // We then visit the children of the current node. After that notePostUse or
14328 // notePostMod is called. These will 1) detect an unsequenced modification
14329 // as side effect (as in "k++ + k") and 2) add a new usage with the
14330 // appropriate usage kind.
14331 //
14332 // We also have to be careful that some operation sequences modification as
14333 // side effect as well (for example: || or ,). To account for this we wrap
14334 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14335 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14336 // which record usages which are modifications as side effect, and then
14337 // downgrade them (or more accurately restore the previous usage which was a
14338 // modification as side effect) when exiting the scope of the sequenced
14339 // subexpression.
14340
14341 void notePreUse(Object O, const Expr *UseExpr) {
14342 UsageInfo &UI = UsageMap[O];
14343 // Uses conflict with other modifications.
14344 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14345 }
14346
14347 void notePostUse(Object O, const Expr *UseExpr) {
14348 UsageInfo &UI = UsageMap[O];
14349 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14350 /*IsModMod=*/false);
14351 addUsage(O, UI, UsageExpr: UseExpr, /*UsageKind=*/UK: UK_Use);
14352 }
14353
14354 void notePreMod(Object O, const Expr *ModExpr) {
14355 UsageInfo &UI = UsageMap[O];
14356 // Modifications conflict with other modifications and with uses.
14357 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14358 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14359 }
14360
14361 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14362 UsageInfo &UI = UsageMap[O];
14363 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14364 /*IsModMod=*/true);
14365 addUsage(O, UI, UsageExpr: ModExpr, /*UsageKind=*/UK);
14366 }
14367
14368public:
14369 SequenceChecker(Sema &S, const Expr *E,
14370 SmallVectorImpl<const Expr *> &WorkList)
14371 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14372 Visit(S: E);
14373 // Silence a -Wunused-private-field since WorkList is now unused.
14374 // TODO: Evaluate if it can be used, and if not remove it.
14375 (void)this->WorkList;
14376 }
14377
14378 void VisitStmt(const Stmt *S) {
14379 // Skip all statements which aren't expressions for now.
14380 }
14381
14382 void VisitExpr(const Expr *E) {
14383 // By default, just recurse to evaluated subexpressions.
14384 Base::VisitStmt(S: E);
14385 }
14386
14387 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14388 for (auto *Sub : CSE->children()) {
14389 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: Sub);
14390 if (!ChildExpr)
14391 continue;
14392
14393 if (ChildExpr == CSE->getOperand())
14394 // Do not recurse over a CoroutineSuspendExpr's operand.
14395 // The operand is also a subexpression of getCommonExpr(), and
14396 // recursing into it directly could confuse object management
14397 // for the sake of sequence tracking.
14398 continue;
14399
14400 Visit(S: Sub);
14401 }
14402 }
14403
14404 void VisitCastExpr(const CastExpr *E) {
14405 Object O = Object();
14406 if (E->getCastKind() == CK_LValueToRValue)
14407 O = getObject(E: E->getSubExpr(), Mod: false);
14408
14409 if (O)
14410 notePreUse(O, UseExpr: E);
14411 VisitExpr(E);
14412 if (O)
14413 notePostUse(O, UseExpr: E);
14414 }
14415
14416 void VisitSequencedExpressions(const Expr *SequencedBefore,
14417 const Expr *SequencedAfter) {
14418 SequenceTree::Seq BeforeRegion = Tree.allocate(Parent: Region);
14419 SequenceTree::Seq AfterRegion = Tree.allocate(Parent: Region);
14420 SequenceTree::Seq OldRegion = Region;
14421
14422 {
14423 SequencedSubexpression SeqBefore(*this);
14424 Region = BeforeRegion;
14425 Visit(S: SequencedBefore);
14426 }
14427
14428 Region = AfterRegion;
14429 Visit(S: SequencedAfter);
14430
14431 Region = OldRegion;
14432
14433 Tree.merge(S: BeforeRegion);
14434 Tree.merge(S: AfterRegion);
14435 }
14436
14437 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14438 // C++17 [expr.sub]p1:
14439 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14440 // expression E1 is sequenced before the expression E2.
14441 if (SemaRef.getLangOpts().CPlusPlus17)
14442 VisitSequencedExpressions(SequencedBefore: ASE->getLHS(), SequencedAfter: ASE->getRHS());
14443 else {
14444 Visit(S: ASE->getLHS());
14445 Visit(S: ASE->getRHS());
14446 }
14447 }
14448
14449 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14450 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14451 void VisitBinPtrMem(const BinaryOperator *BO) {
14452 // C++17 [expr.mptr.oper]p4:
14453 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14454 // the expression E1 is sequenced before the expression E2.
14455 if (SemaRef.getLangOpts().CPlusPlus17)
14456 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
14457 else {
14458 Visit(S: BO->getLHS());
14459 Visit(S: BO->getRHS());
14460 }
14461 }
14462
14463 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14464 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14465 void VisitBinShlShr(const BinaryOperator *BO) {
14466 // C++17 [expr.shift]p4:
14467 // The expression E1 is sequenced before the expression E2.
14468 if (SemaRef.getLangOpts().CPlusPlus17)
14469 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
14470 else {
14471 Visit(S: BO->getLHS());
14472 Visit(S: BO->getRHS());
14473 }
14474 }
14475
14476 void VisitBinComma(const BinaryOperator *BO) {
14477 // C++11 [expr.comma]p1:
14478 // Every value computation and side effect associated with the left
14479 // expression is sequenced before every value computation and side
14480 // effect associated with the right expression.
14481 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
14482 }
14483
14484 void VisitBinAssign(const BinaryOperator *BO) {
14485 SequenceTree::Seq RHSRegion;
14486 SequenceTree::Seq LHSRegion;
14487 if (SemaRef.getLangOpts().CPlusPlus17) {
14488 RHSRegion = Tree.allocate(Parent: Region);
14489 LHSRegion = Tree.allocate(Parent: Region);
14490 } else {
14491 RHSRegion = Region;
14492 LHSRegion = Region;
14493 }
14494 SequenceTree::Seq OldRegion = Region;
14495
14496 // C++11 [expr.ass]p1:
14497 // [...] the assignment is sequenced after the value computation
14498 // of the right and left operands, [...]
14499 //
14500 // so check it before inspecting the operands and update the
14501 // map afterwards.
14502 Object O = getObject(E: BO->getLHS(), /*Mod=*/true);
14503 if (O)
14504 notePreMod(O, ModExpr: BO);
14505
14506 if (SemaRef.getLangOpts().CPlusPlus17) {
14507 // C++17 [expr.ass]p1:
14508 // [...] The right operand is sequenced before the left operand. [...]
14509 {
14510 SequencedSubexpression SeqBefore(*this);
14511 Region = RHSRegion;
14512 Visit(S: BO->getRHS());
14513 }
14514
14515 Region = LHSRegion;
14516 Visit(S: BO->getLHS());
14517
14518 if (O && isa<CompoundAssignOperator>(Val: BO))
14519 notePostUse(O, UseExpr: BO);
14520
14521 } else {
14522 // C++11 does not specify any sequencing between the LHS and RHS.
14523 Region = LHSRegion;
14524 Visit(S: BO->getLHS());
14525
14526 if (O && isa<CompoundAssignOperator>(Val: BO))
14527 notePostUse(O, UseExpr: BO);
14528
14529 Region = RHSRegion;
14530 Visit(S: BO->getRHS());
14531 }
14532
14533 // C++11 [expr.ass]p1:
14534 // the assignment is sequenced [...] before the value computation of the
14535 // assignment expression.
14536 // C11 6.5.16/3 has no such rule.
14537 Region = OldRegion;
14538 if (O)
14539 notePostMod(O, ModExpr: BO,
14540 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14541 : UK_ModAsSideEffect);
14542 if (SemaRef.getLangOpts().CPlusPlus17) {
14543 Tree.merge(S: RHSRegion);
14544 Tree.merge(S: LHSRegion);
14545 }
14546 }
14547
14548 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14549 VisitBinAssign(BO: CAO);
14550 }
14551
14552 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14553 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14554 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14555 Object O = getObject(E: UO->getSubExpr(), Mod: true);
14556 if (!O)
14557 return VisitExpr(E: UO);
14558
14559 notePreMod(O, ModExpr: UO);
14560 Visit(S: UO->getSubExpr());
14561 // C++11 [expr.pre.incr]p1:
14562 // the expression ++x is equivalent to x+=1
14563 notePostMod(O, ModExpr: UO,
14564 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14565 : UK_ModAsSideEffect);
14566 }
14567
14568 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14569 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14570 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14571 Object O = getObject(E: UO->getSubExpr(), Mod: true);
14572 if (!O)
14573 return VisitExpr(E: UO);
14574
14575 notePreMod(O, ModExpr: UO);
14576 Visit(S: UO->getSubExpr());
14577 notePostMod(O, ModExpr: UO, UK: UK_ModAsSideEffect);
14578 }
14579
14580 void VisitBinLOr(const BinaryOperator *BO) {
14581 // C++11 [expr.log.or]p2:
14582 // If the second expression is evaluated, every value computation and
14583 // side effect associated with the first expression is sequenced before
14584 // every value computation and side effect associated with the
14585 // second expression.
14586 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
14587 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
14588 SequenceTree::Seq OldRegion = Region;
14589
14590 EvaluationTracker Eval(*this);
14591 {
14592 SequencedSubexpression Sequenced(*this);
14593 Region = LHSRegion;
14594 Visit(S: BO->getLHS());
14595 }
14596
14597 // C++11 [expr.log.or]p1:
14598 // [...] the second operand is not evaluated if the first operand
14599 // evaluates to true.
14600 bool EvalResult = false;
14601 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
14602 bool ShouldVisitRHS = !EvalOK || !EvalResult;
14603 if (ShouldVisitRHS) {
14604 Region = RHSRegion;
14605 Visit(S: BO->getRHS());
14606 }
14607
14608 Region = OldRegion;
14609 Tree.merge(S: LHSRegion);
14610 Tree.merge(S: RHSRegion);
14611 }
14612
14613 void VisitBinLAnd(const BinaryOperator *BO) {
14614 // C++11 [expr.log.and]p2:
14615 // If the second expression is evaluated, every value computation and
14616 // side effect associated with the first expression is sequenced before
14617 // every value computation and side effect associated with the
14618 // second expression.
14619 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
14620 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
14621 SequenceTree::Seq OldRegion = Region;
14622
14623 EvaluationTracker Eval(*this);
14624 {
14625 SequencedSubexpression Sequenced(*this);
14626 Region = LHSRegion;
14627 Visit(S: BO->getLHS());
14628 }
14629
14630 // C++11 [expr.log.and]p1:
14631 // [...] the second operand is not evaluated if the first operand is false.
14632 bool EvalResult = false;
14633 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
14634 bool ShouldVisitRHS = !EvalOK || EvalResult;
14635 if (ShouldVisitRHS) {
14636 Region = RHSRegion;
14637 Visit(S: BO->getRHS());
14638 }
14639
14640 Region = OldRegion;
14641 Tree.merge(S: LHSRegion);
14642 Tree.merge(S: RHSRegion);
14643 }
14644
14645 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14646 // C++11 [expr.cond]p1:
14647 // [...] Every value computation and side effect associated with the first
14648 // expression is sequenced before every value computation and side effect
14649 // associated with the second or third expression.
14650 SequenceTree::Seq ConditionRegion = Tree.allocate(Parent: Region);
14651
14652 // No sequencing is specified between the true and false expression.
14653 // However since exactly one of both is going to be evaluated we can
14654 // consider them to be sequenced. This is needed to avoid warning on
14655 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14656 // both the true and false expressions because we can't evaluate x.
14657 // This will still allow us to detect an expression like (pre C++17)
14658 // "(x ? y += 1 : y += 2) = y".
14659 //
14660 // We don't wrap the visitation of the true and false expression with
14661 // SequencedSubexpression because we don't want to downgrade modifications
14662 // as side effect in the true and false expressions after the visition
14663 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14664 // not warn between the two "y++", but we should warn between the "y++"
14665 // and the "y".
14666 SequenceTree::Seq TrueRegion = Tree.allocate(Parent: Region);
14667 SequenceTree::Seq FalseRegion = Tree.allocate(Parent: Region);
14668 SequenceTree::Seq OldRegion = Region;
14669
14670 EvaluationTracker Eval(*this);
14671 {
14672 SequencedSubexpression Sequenced(*this);
14673 Region = ConditionRegion;
14674 Visit(S: CO->getCond());
14675 }
14676
14677 // C++11 [expr.cond]p1:
14678 // [...] The first expression is contextually converted to bool (Clause 4).
14679 // It is evaluated and if it is true, the result of the conditional
14680 // expression is the value of the second expression, otherwise that of the
14681 // third expression. Only one of the second and third expressions is
14682 // evaluated. [...]
14683 bool EvalResult = false;
14684 bool EvalOK = Eval.evaluate(E: CO->getCond(), Result&: EvalResult);
14685 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
14686 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
14687 if (ShouldVisitTrueExpr) {
14688 Region = TrueRegion;
14689 Visit(S: CO->getTrueExpr());
14690 }
14691 if (ShouldVisitFalseExpr) {
14692 Region = FalseRegion;
14693 Visit(S: CO->getFalseExpr());
14694 }
14695
14696 Region = OldRegion;
14697 Tree.merge(S: ConditionRegion);
14698 Tree.merge(S: TrueRegion);
14699 Tree.merge(S: FalseRegion);
14700 }
14701
14702 void VisitCallExpr(const CallExpr *CE) {
14703 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14704
14705 if (CE->isUnevaluatedBuiltinCall(Ctx: Context))
14706 return;
14707
14708 // C++11 [intro.execution]p15:
14709 // When calling a function [...], every value computation and side effect
14710 // associated with any argument expression, or with the postfix expression
14711 // designating the called function, is sequenced before execution of every
14712 // expression or statement in the body of the function [and thus before
14713 // the value computation of its result].
14714 SequencedSubexpression Sequenced(*this);
14715 SemaRef.runWithSufficientStackSpace(Loc: CE->getExprLoc(), Fn: [&] {
14716 // C++17 [expr.call]p5
14717 // The postfix-expression is sequenced before each expression in the
14718 // expression-list and any default argument. [...]
14719 SequenceTree::Seq CalleeRegion;
14720 SequenceTree::Seq OtherRegion;
14721 if (SemaRef.getLangOpts().CPlusPlus17) {
14722 CalleeRegion = Tree.allocate(Parent: Region);
14723 OtherRegion = Tree.allocate(Parent: Region);
14724 } else {
14725 CalleeRegion = Region;
14726 OtherRegion = Region;
14727 }
14728 SequenceTree::Seq OldRegion = Region;
14729
14730 // Visit the callee expression first.
14731 Region = CalleeRegion;
14732 if (SemaRef.getLangOpts().CPlusPlus17) {
14733 SequencedSubexpression Sequenced(*this);
14734 Visit(S: CE->getCallee());
14735 } else {
14736 Visit(S: CE->getCallee());
14737 }
14738
14739 // Then visit the argument expressions.
14740 Region = OtherRegion;
14741 for (const Expr *Argument : CE->arguments())
14742 Visit(S: Argument);
14743
14744 Region = OldRegion;
14745 if (SemaRef.getLangOpts().CPlusPlus17) {
14746 Tree.merge(S: CalleeRegion);
14747 Tree.merge(S: OtherRegion);
14748 }
14749 });
14750 }
14751
14752 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14753 // C++17 [over.match.oper]p2:
14754 // [...] the operator notation is first transformed to the equivalent
14755 // function-call notation as summarized in Table 12 (where @ denotes one
14756 // of the operators covered in the specified subclause). However, the
14757 // operands are sequenced in the order prescribed for the built-in
14758 // operator (Clause 8).
14759 //
14760 // From the above only overloaded binary operators and overloaded call
14761 // operators have sequencing rules in C++17 that we need to handle
14762 // separately.
14763 if (!SemaRef.getLangOpts().CPlusPlus17 ||
14764 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14765 return VisitCallExpr(CE: CXXOCE);
14766
14767 enum {
14768 NoSequencing,
14769 LHSBeforeRHS,
14770 RHSBeforeLHS,
14771 LHSBeforeRest
14772 } SequencingKind;
14773 switch (CXXOCE->getOperator()) {
14774 case OO_Equal:
14775 case OO_PlusEqual:
14776 case OO_MinusEqual:
14777 case OO_StarEqual:
14778 case OO_SlashEqual:
14779 case OO_PercentEqual:
14780 case OO_CaretEqual:
14781 case OO_AmpEqual:
14782 case OO_PipeEqual:
14783 case OO_LessLessEqual:
14784 case OO_GreaterGreaterEqual:
14785 SequencingKind = RHSBeforeLHS;
14786 break;
14787
14788 case OO_LessLess:
14789 case OO_GreaterGreater:
14790 case OO_AmpAmp:
14791 case OO_PipePipe:
14792 case OO_Comma:
14793 case OO_ArrowStar:
14794 case OO_Subscript:
14795 SequencingKind = LHSBeforeRHS;
14796 break;
14797
14798 case OO_Call:
14799 SequencingKind = LHSBeforeRest;
14800 break;
14801
14802 default:
14803 SequencingKind = NoSequencing;
14804 break;
14805 }
14806
14807 if (SequencingKind == NoSequencing)
14808 return VisitCallExpr(CE: CXXOCE);
14809
14810 // This is a call, so all subexpressions are sequenced before the result.
14811 SequencedSubexpression Sequenced(*this);
14812
14813 SemaRef.runWithSufficientStackSpace(Loc: CXXOCE->getExprLoc(), Fn: [&] {
14814 assert(SemaRef.getLangOpts().CPlusPlus17 &&
14815 "Should only get there with C++17 and above!");
14816 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14817 "Should only get there with an overloaded binary operator"
14818 " or an overloaded call operator!");
14819
14820 if (SequencingKind == LHSBeforeRest) {
14821 assert(CXXOCE->getOperator() == OO_Call &&
14822 "We should only have an overloaded call operator here!");
14823
14824 // This is very similar to VisitCallExpr, except that we only have the
14825 // C++17 case. The postfix-expression is the first argument of the
14826 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14827 // are in the following arguments.
14828 //
14829 // Note that we intentionally do not visit the callee expression since
14830 // it is just a decayed reference to a function.
14831 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Parent: Region);
14832 SequenceTree::Seq ArgsRegion = Tree.allocate(Parent: Region);
14833 SequenceTree::Seq OldRegion = Region;
14834
14835 assert(CXXOCE->getNumArgs() >= 1 &&
14836 "An overloaded call operator must have at least one argument"
14837 " for the postfix-expression!");
14838 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14839 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14840 CXXOCE->getNumArgs() - 1);
14841
14842 // Visit the postfix-expression first.
14843 {
14844 Region = PostfixExprRegion;
14845 SequencedSubexpression Sequenced(*this);
14846 Visit(S: PostfixExpr);
14847 }
14848
14849 // Then visit the argument expressions.
14850 Region = ArgsRegion;
14851 for (const Expr *Arg : Args)
14852 Visit(S: Arg);
14853
14854 Region = OldRegion;
14855 Tree.merge(S: PostfixExprRegion);
14856 Tree.merge(S: ArgsRegion);
14857 } else {
14858 assert(CXXOCE->getNumArgs() == 2 &&
14859 "Should only have two arguments here!");
14860 assert((SequencingKind == LHSBeforeRHS ||
14861 SequencingKind == RHSBeforeLHS) &&
14862 "Unexpected sequencing kind!");
14863
14864 // We do not visit the callee expression since it is just a decayed
14865 // reference to a function.
14866 const Expr *E1 = CXXOCE->getArg(Arg: 0);
14867 const Expr *E2 = CXXOCE->getArg(Arg: 1);
14868 if (SequencingKind == RHSBeforeLHS)
14869 std::swap(a&: E1, b&: E2);
14870
14871 return VisitSequencedExpressions(SequencedBefore: E1, SequencedAfter: E2);
14872 }
14873 });
14874 }
14875
14876 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14877 // This is a call, so all subexpressions are sequenced before the result.
14878 SequencedSubexpression Sequenced(*this);
14879
14880 if (!CCE->isListInitialization())
14881 return VisitExpr(E: CCE);
14882
14883 // In C++11, list initializations are sequenced.
14884 SequenceExpressionsInOrder(
14885 ExpressionList: llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
14886 }
14887
14888 void VisitInitListExpr(const InitListExpr *ILE) {
14889 if (!SemaRef.getLangOpts().CPlusPlus11)
14890 return VisitExpr(E: ILE);
14891
14892 // In C++11, list initializations are sequenced.
14893 SequenceExpressionsInOrder(ExpressionList: ILE->inits());
14894 }
14895
14896 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
14897 // C++20 parenthesized list initializations are sequenced. See C++20
14898 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
14899 SequenceExpressionsInOrder(ExpressionList: PLIE->getInitExprs());
14900 }
14901
14902private:
14903 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
14904 SmallVector<SequenceTree::Seq, 32> Elts;
14905 SequenceTree::Seq Parent = Region;
14906 for (const Expr *E : ExpressionList) {
14907 if (!E)
14908 continue;
14909 Region = Tree.allocate(Parent);
14910 Elts.push_back(Elt: Region);
14911 Visit(S: E);
14912 }
14913
14914 // Forget that the initializers are sequenced.
14915 Region = Parent;
14916 for (unsigned I = 0; I < Elts.size(); ++I)
14917 Tree.merge(S: Elts[I]);
14918 }
14919};
14920
14921SequenceChecker::UsageInfo::UsageInfo() = default;
14922
14923} // namespace
14924
14925void Sema::CheckUnsequencedOperations(const Expr *E) {
14926 SmallVector<const Expr *, 8> WorkList;
14927 WorkList.push_back(Elt: E);
14928 while (!WorkList.empty()) {
14929 const Expr *Item = WorkList.pop_back_val();
14930 SequenceChecker(*this, Item, WorkList);
14931 }
14932}
14933
14934void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14935 bool IsConstexpr) {
14936 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
14937 IsConstexpr || isa<ConstantExpr>(Val: E));
14938 CheckImplicitConversions(E, CC: CheckLoc);
14939 if (!E->isInstantiationDependent())
14940 CheckUnsequencedOperations(E);
14941 if (!IsConstexpr && !E->isValueDependent())
14942 CheckForIntOverflow(E);
14943}
14944
14945void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14946 FieldDecl *BitField,
14947 Expr *Init) {
14948 (void) AnalyzeBitFieldAssignment(S&: *this, Bitfield: BitField, Init, InitLoc);
14949}
14950
14951static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14952 SourceLocation Loc) {
14953 if (!PType->isVariablyModifiedType())
14954 return;
14955 if (const auto *PointerTy = dyn_cast<PointerType>(Val&: PType)) {
14956 diagnoseArrayStarInParamType(S, PType: PointerTy->getPointeeType(), Loc);
14957 return;
14958 }
14959 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(Val&: PType)) {
14960 diagnoseArrayStarInParamType(S, PType: ReferenceTy->getPointeeType(), Loc);
14961 return;
14962 }
14963 if (const auto *ParenTy = dyn_cast<ParenType>(Val&: PType)) {
14964 diagnoseArrayStarInParamType(S, PType: ParenTy->getInnerType(), Loc);
14965 return;
14966 }
14967
14968 const ArrayType *AT = S.Context.getAsArrayType(T: PType);
14969 if (!AT)
14970 return;
14971
14972 if (AT->getSizeModifier() != ArraySizeModifier::Star) {
14973 diagnoseArrayStarInParamType(S, PType: AT->getElementType(), Loc);
14974 return;
14975 }
14976
14977 S.Diag(Loc, DiagID: diag::err_array_star_in_function_definition);
14978}
14979
14980bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14981 bool CheckParameterNames) {
14982 bool HasInvalidParm = false;
14983 for (ParmVarDecl *Param : Parameters) {
14984 assert(Param && "null in a parameter list");
14985 // C99 6.7.5.3p4: the parameters in a parameter type list in a
14986 // function declarator that is part of a function definition of
14987 // that function shall not have incomplete type.
14988 //
14989 // C++23 [dcl.fct.def.general]/p2
14990 // The type of a parameter [...] for a function definition
14991 // shall not be a (possibly cv-qualified) class type that is incomplete
14992 // or abstract within the function body unless the function is deleted.
14993 if (!Param->isInvalidDecl() &&
14994 (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
14995 DiagID: diag::err_typecheck_decl_incomplete_type) ||
14996 RequireNonAbstractType(Loc: Param->getBeginLoc(), T: Param->getOriginalType(),
14997 DiagID: diag::err_abstract_type_in_decl,
14998 Args: AbstractParamType))) {
14999 Param->setInvalidDecl();
15000 HasInvalidParm = true;
15001 }
15002
15003 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15004 // declaration of each parameter shall include an identifier.
15005 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15006 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15007 // Diagnose this as an extension in C17 and earlier.
15008 if (!getLangOpts().C23)
15009 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
15010 }
15011
15012 // C99 6.7.5.3p12:
15013 // If the function declarator is not part of a definition of that
15014 // function, parameters may have incomplete type and may use the [*]
15015 // notation in their sequences of declarator specifiers to specify
15016 // variable length array types.
15017 QualType PType = Param->getOriginalType();
15018 // FIXME: This diagnostic should point the '[*]' if source-location
15019 // information is added for it.
15020 diagnoseArrayStarInParamType(S&: *this, PType, Loc: Param->getLocation());
15021
15022 // If the parameter is a c++ class type and it has to be destructed in the
15023 // callee function, declare the destructor so that it can be called by the
15024 // callee function. Do not perform any direct access check on the dtor here.
15025 if (!Param->isInvalidDecl()) {
15026 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15027 if (!ClassDecl->isInvalidDecl() &&
15028 !ClassDecl->hasIrrelevantDestructor() &&
15029 !ClassDecl->isDependentContext() &&
15030 ClassDecl->isParamDestroyedInCallee()) {
15031 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
15032 MarkFunctionReferenced(Loc: Param->getLocation(), Func: Destructor);
15033 DiagnoseUseOfDecl(D: Destructor, Locs: Param->getLocation());
15034 }
15035 }
15036 }
15037
15038 // Parameters with the pass_object_size attribute only need to be marked
15039 // constant at function definitions. Because we lack information about
15040 // whether we're on a declaration or definition when we're instantiating the
15041 // attribute, we need to check for constness here.
15042 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15043 if (!Param->getType().isConstQualified())
15044 Diag(Loc: Param->getLocation(), DiagID: diag::err_attribute_pointers_only)
15045 << Attr->getSpelling() << 1;
15046
15047 // Check for parameter names shadowing fields from the class.
15048 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15049 // The owning context for the parameter should be the function, but we
15050 // want to see if this function's declaration context is a record.
15051 DeclContext *DC = Param->getDeclContext();
15052 if (DC && DC->isFunctionOrMethod()) {
15053 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC->getParent()))
15054 CheckShadowInheritedFields(Loc: Param->getLocation(), FieldName: Param->getDeclName(),
15055 RD, /*DeclIsField*/ false);
15056 }
15057 }
15058
15059 if (!Param->isInvalidDecl() &&
15060 Param->getOriginalType()->isWebAssemblyTableType()) {
15061 Param->setInvalidDecl();
15062 HasInvalidParm = true;
15063 Diag(Loc: Param->getLocation(), DiagID: diag::err_wasm_table_as_function_parameter);
15064 }
15065 }
15066
15067 return HasInvalidParm;
15068}
15069
15070std::optional<std::pair<
15071 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15072 *E,
15073 ASTContext
15074 &Ctx);
15075
15076/// Compute the alignment and offset of the base class object given the
15077/// derived-to-base cast expression and the alignment and offset of the derived
15078/// class object.
15079static std::pair<CharUnits, CharUnits>
15080getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15081 CharUnits BaseAlignment, CharUnits Offset,
15082 ASTContext &Ctx) {
15083 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15084 ++PathI) {
15085 const CXXBaseSpecifier *Base = *PathI;
15086 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15087 if (Base->isVirtual()) {
15088 // The complete object may have a lower alignment than the non-virtual
15089 // alignment of the base, in which case the base may be misaligned. Choose
15090 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15091 // conservative lower bound of the complete object alignment.
15092 CharUnits NonVirtualAlignment =
15093 Ctx.getASTRecordLayout(D: BaseDecl).getNonVirtualAlignment();
15094 BaseAlignment = std::min(a: BaseAlignment, b: NonVirtualAlignment);
15095 Offset = CharUnits::Zero();
15096 } else {
15097 const ASTRecordLayout &RL =
15098 Ctx.getASTRecordLayout(D: DerivedType->getAsCXXRecordDecl());
15099 Offset += RL.getBaseClassOffset(Base: BaseDecl);
15100 }
15101 DerivedType = Base->getType();
15102 }
15103
15104 return std::make_pair(x&: BaseAlignment, y&: Offset);
15105}
15106
15107/// Compute the alignment and offset of a binary additive operator.
15108static std::optional<std::pair<CharUnits, CharUnits>>
15109getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15110 bool IsSub, ASTContext &Ctx) {
15111 QualType PointeeType = PtrE->getType()->getPointeeType();
15112
15113 if (!PointeeType->isConstantSizeType())
15114 return std::nullopt;
15115
15116 auto P = getBaseAlignmentAndOffsetFromPtr(E: PtrE, Ctx);
15117
15118 if (!P)
15119 return std::nullopt;
15120
15121 CharUnits EltSize = Ctx.getTypeSizeInChars(T: PointeeType);
15122 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15123 CharUnits Offset = EltSize * IdxRes->getExtValue();
15124 if (IsSub)
15125 Offset = -Offset;
15126 return std::make_pair(x&: P->first, y: P->second + Offset);
15127 }
15128
15129 // If the integer expression isn't a constant expression, compute the lower
15130 // bound of the alignment using the alignment and offset of the pointer
15131 // expression and the element size.
15132 return std::make_pair(
15133 x: P->first.alignmentAtOffset(offset: P->second).alignmentAtOffset(offset: EltSize),
15134 y: CharUnits::Zero());
15135}
15136
15137/// This helper function takes an lvalue expression and returns the alignment of
15138/// a VarDecl and a constant offset from the VarDecl.
15139std::optional<std::pair<
15140 CharUnits,
15141 CharUnits>> static getBaseAlignmentAndOffsetFromLValue(const Expr *E,
15142 ASTContext &Ctx) {
15143 E = E->IgnoreParens();
15144 switch (E->getStmtClass()) {
15145 default:
15146 break;
15147 case Stmt::CStyleCastExprClass:
15148 case Stmt::CXXStaticCastExprClass:
15149 case Stmt::ImplicitCastExprClass: {
15150 auto *CE = cast<CastExpr>(Val: E);
15151 const Expr *From = CE->getSubExpr();
15152 switch (CE->getCastKind()) {
15153 default:
15154 break;
15155 case CK_NoOp:
15156 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15157 case CK_UncheckedDerivedToBase:
15158 case CK_DerivedToBase: {
15159 auto P = getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15160 if (!P)
15161 break;
15162 return getDerivedToBaseAlignmentAndOffset(CE, DerivedType: From->getType(), BaseAlignment: P->first,
15163 Offset: P->second, Ctx);
15164 }
15165 }
15166 break;
15167 }
15168 case Stmt::ArraySubscriptExprClass: {
15169 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
15170 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: ASE->getBase(), IntE: ASE->getIdx(),
15171 IsSub: false, Ctx);
15172 }
15173 case Stmt::DeclRefExprClass: {
15174 if (auto *VD = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: E)->getDecl())) {
15175 // FIXME: If VD is captured by copy or is an escaping __block variable,
15176 // use the alignment of VD's type.
15177 if (!VD->getType()->isReferenceType()) {
15178 // Dependent alignment cannot be resolved -> bail out.
15179 if (VD->hasDependentAlignment())
15180 break;
15181 return std::make_pair(x: Ctx.getDeclAlign(D: VD), y: CharUnits::Zero());
15182 }
15183 if (VD->hasInit())
15184 return getBaseAlignmentAndOffsetFromLValue(E: VD->getInit(), Ctx);
15185 }
15186 break;
15187 }
15188 case Stmt::MemberExprClass: {
15189 auto *ME = cast<MemberExpr>(Val: E);
15190 auto *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
15191 if (!FD || FD->getType()->isReferenceType() ||
15192 FD->getParent()->isInvalidDecl())
15193 break;
15194 std::optional<std::pair<CharUnits, CharUnits>> P;
15195 if (ME->isArrow())
15196 P = getBaseAlignmentAndOffsetFromPtr(E: ME->getBase(), Ctx);
15197 else
15198 P = getBaseAlignmentAndOffsetFromLValue(E: ME->getBase(), Ctx);
15199 if (!P)
15200 break;
15201 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(D: FD->getParent());
15202 uint64_t Offset = Layout.getFieldOffset(FieldNo: FD->getFieldIndex());
15203 return std::make_pair(x&: P->first,
15204 y: P->second + CharUnits::fromQuantity(Quantity: Offset));
15205 }
15206 case Stmt::UnaryOperatorClass: {
15207 auto *UO = cast<UnaryOperator>(Val: E);
15208 switch (UO->getOpcode()) {
15209 default:
15210 break;
15211 case UO_Deref:
15212 return getBaseAlignmentAndOffsetFromPtr(E: UO->getSubExpr(), Ctx);
15213 }
15214 break;
15215 }
15216 case Stmt::BinaryOperatorClass: {
15217 auto *BO = cast<BinaryOperator>(Val: E);
15218 auto Opcode = BO->getOpcode();
15219 switch (Opcode) {
15220 default:
15221 break;
15222 case BO_Comma:
15223 return getBaseAlignmentAndOffsetFromLValue(E: BO->getRHS(), Ctx);
15224 }
15225 break;
15226 }
15227 }
15228 return std::nullopt;
15229}
15230
15231/// This helper function takes a pointer expression and returns the alignment of
15232/// a VarDecl and a constant offset from the VarDecl.
15233std::optional<std::pair<
15234 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15235 *E,
15236 ASTContext
15237 &Ctx) {
15238 E = E->IgnoreParens();
15239 switch (E->getStmtClass()) {
15240 default:
15241 break;
15242 case Stmt::CStyleCastExprClass:
15243 case Stmt::CXXStaticCastExprClass:
15244 case Stmt::ImplicitCastExprClass: {
15245 auto *CE = cast<CastExpr>(Val: E);
15246 const Expr *From = CE->getSubExpr();
15247 switch (CE->getCastKind()) {
15248 default:
15249 break;
15250 case CK_NoOp:
15251 return getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15252 case CK_ArrayToPointerDecay:
15253 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15254 case CK_UncheckedDerivedToBase:
15255 case CK_DerivedToBase: {
15256 auto P = getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15257 if (!P)
15258 break;
15259 return getDerivedToBaseAlignmentAndOffset(
15260 CE, DerivedType: From->getType()->getPointeeType(), BaseAlignment: P->first, Offset: P->second, Ctx);
15261 }
15262 }
15263 break;
15264 }
15265 case Stmt::CXXThisExprClass: {
15266 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15267 CharUnits Alignment = Ctx.getASTRecordLayout(D: RD).getNonVirtualAlignment();
15268 return std::make_pair(x&: Alignment, y: CharUnits::Zero());
15269 }
15270 case Stmt::UnaryOperatorClass: {
15271 auto *UO = cast<UnaryOperator>(Val: E);
15272 if (UO->getOpcode() == UO_AddrOf)
15273 return getBaseAlignmentAndOffsetFromLValue(E: UO->getSubExpr(), Ctx);
15274 break;
15275 }
15276 case Stmt::BinaryOperatorClass: {
15277 auto *BO = cast<BinaryOperator>(Val: E);
15278 auto Opcode = BO->getOpcode();
15279 switch (Opcode) {
15280 default:
15281 break;
15282 case BO_Add:
15283 case BO_Sub: {
15284 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15285 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15286 std::swap(a&: LHS, b&: RHS);
15287 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: LHS, IntE: RHS, IsSub: Opcode == BO_Sub,
15288 Ctx);
15289 }
15290 case BO_Comma:
15291 return getBaseAlignmentAndOffsetFromPtr(E: BO->getRHS(), Ctx);
15292 }
15293 break;
15294 }
15295 }
15296 return std::nullopt;
15297}
15298
15299static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15300 // See if we can compute the alignment of a VarDecl and an offset from it.
15301 std::optional<std::pair<CharUnits, CharUnits>> P =
15302 getBaseAlignmentAndOffsetFromPtr(E, Ctx&: S.Context);
15303
15304 if (P)
15305 return P->first.alignmentAtOffset(offset: P->second);
15306
15307 // If that failed, return the type's alignment.
15308 return S.Context.getTypeAlignInChars(T: E->getType()->getPointeeType());
15309}
15310
15311void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15312 // This is actually a lot of work to potentially be doing on every
15313 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15314 if (getDiagnostics().isIgnored(DiagID: diag::warn_cast_align, Loc: TRange.getBegin()))
15315 return;
15316
15317 // Ignore dependent types.
15318 if (T->isDependentType() || Op->getType()->isDependentType())
15319 return;
15320
15321 // Require that the destination be a pointer type.
15322 const PointerType *DestPtr = T->getAs<PointerType>();
15323 if (!DestPtr) return;
15324
15325 // If the destination has alignment 1, we're done.
15326 QualType DestPointee = DestPtr->getPointeeType();
15327 if (DestPointee->isIncompleteType()) return;
15328 CharUnits DestAlign = Context.getTypeAlignInChars(T: DestPointee);
15329 if (DestAlign.isOne()) return;
15330
15331 // Require that the source be a pointer type.
15332 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15333 if (!SrcPtr) return;
15334 QualType SrcPointee = SrcPtr->getPointeeType();
15335
15336 // Explicitly allow casts from cv void*. We already implicitly
15337 // allowed casts to cv void*, since they have alignment 1.
15338 // Also allow casts involving incomplete types, which implicitly
15339 // includes 'void'.
15340 if (SrcPointee->isIncompleteType()) return;
15341
15342 CharUnits SrcAlign = getPresumedAlignmentOfPointer(E: Op, S&: *this);
15343
15344 if (SrcAlign >= DestAlign) return;
15345
15346 Diag(Loc: TRange.getBegin(), DiagID: diag::warn_cast_align)
15347 << Op->getType() << T
15348 << static_cast<unsigned>(SrcAlign.getQuantity())
15349 << static_cast<unsigned>(DestAlign.getQuantity())
15350 << TRange << Op->getSourceRange();
15351}
15352
15353void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15354 const ArraySubscriptExpr *ASE,
15355 bool AllowOnePastEnd, bool IndexNegated) {
15356 // Already diagnosed by the constant evaluator.
15357 if (isConstantEvaluatedContext())
15358 return;
15359
15360 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15361 if (IndexExpr->isValueDependent())
15362 return;
15363
15364 const Type *EffectiveType =
15365 BaseExpr->getType()->getPointeeOrArrayElementType();
15366 BaseExpr = BaseExpr->IgnoreParenCasts();
15367 const ConstantArrayType *ArrayTy =
15368 Context.getAsConstantArrayType(T: BaseExpr->getType());
15369
15370 LangOptions::StrictFlexArraysLevelKind
15371 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15372
15373 const Type *BaseType =
15374 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15375 bool IsUnboundedArray =
15376 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15377 Context, StrictFlexArraysLevel,
15378 /*IgnoreTemplateOrMacroSubstitution=*/true);
15379 if (EffectiveType->isDependentType() ||
15380 (!IsUnboundedArray && BaseType->isDependentType()))
15381 return;
15382
15383 Expr::EvalResult Result;
15384 if (!IndexExpr->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects))
15385 return;
15386
15387 llvm::APSInt index = Result.Val.getInt();
15388 if (IndexNegated) {
15389 index.setIsUnsigned(false);
15390 index = -index;
15391 }
15392
15393 if (IsUnboundedArray) {
15394 if (EffectiveType->isFunctionType())
15395 return;
15396 if (index.isUnsigned() || !index.isNegative()) {
15397 const auto &ASTC = getASTContext();
15398 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15399 AddrSpace: EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15400 if (index.getBitWidth() < AddrBits)
15401 index = index.zext(width: AddrBits);
15402 std::optional<CharUnits> ElemCharUnits =
15403 ASTC.getTypeSizeInCharsIfKnown(Ty: EffectiveType);
15404 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15405 // pointer) bounds-checking isn't meaningful.
15406 if (!ElemCharUnits || ElemCharUnits->isZero())
15407 return;
15408 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15409 // If index has more active bits than address space, we already know
15410 // we have a bounds violation to warn about. Otherwise, compute
15411 // address of (index + 1)th element, and warn about bounds violation
15412 // only if that address exceeds address space.
15413 if (index.getActiveBits() <= AddrBits) {
15414 bool Overflow;
15415 llvm::APInt Product(index);
15416 Product += 1;
15417 Product = Product.umul_ov(RHS: ElemBytes, Overflow);
15418 if (!Overflow && Product.getActiveBits() <= AddrBits)
15419 return;
15420 }
15421
15422 // Need to compute max possible elements in address space, since that
15423 // is included in diag message.
15424 llvm::APInt MaxElems = llvm::APInt::getMaxValue(numBits: AddrBits);
15425 MaxElems = MaxElems.zext(width: std::max(a: AddrBits + 1, b: ElemBytes.getBitWidth()));
15426 MaxElems += 1;
15427 ElemBytes = ElemBytes.zextOrTrunc(width: MaxElems.getBitWidth());
15428 MaxElems = MaxElems.udiv(RHS: ElemBytes);
15429
15430 unsigned DiagID =
15431 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15432 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15433
15434 // Diag message shows element size in bits and in "bytes" (platform-
15435 // dependent CharUnits)
15436 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
15437 PD: PDiag(DiagID) << index << AddrBits
15438 << (unsigned)ASTC.toBits(CharSize: *ElemCharUnits)
15439 << ElemBytes << MaxElems
15440 << MaxElems.getZExtValue()
15441 << IndexExpr->getSourceRange());
15442
15443 const NamedDecl *ND = nullptr;
15444 // Try harder to find a NamedDecl to point at in the note.
15445 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
15446 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15447 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
15448 ND = DRE->getDecl();
15449 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
15450 ND = ME->getMemberDecl();
15451
15452 if (ND)
15453 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
15454 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
15455 }
15456 return;
15457 }
15458
15459 if (index.isUnsigned() || !index.isNegative()) {
15460 // It is possible that the type of the base expression after
15461 // IgnoreParenCasts is incomplete, even though the type of the base
15462 // expression before IgnoreParenCasts is complete (see PR39746 for an
15463 // example). In this case we have no information about whether the array
15464 // access exceeds the array bounds. However we can still diagnose an array
15465 // access which precedes the array bounds.
15466 if (BaseType->isIncompleteType())
15467 return;
15468
15469 llvm::APInt size = ArrayTy->getSize();
15470
15471 if (BaseType != EffectiveType) {
15472 // Make sure we're comparing apples to apples when comparing index to
15473 // size.
15474 uint64_t ptrarith_typesize = Context.getTypeSize(T: EffectiveType);
15475 uint64_t array_typesize = Context.getTypeSize(T: BaseType);
15476
15477 // Handle ptrarith_typesize being zero, such as when casting to void*.
15478 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15479 if (!ptrarith_typesize)
15480 ptrarith_typesize = Context.getCharWidth();
15481
15482 if (ptrarith_typesize != array_typesize) {
15483 // There's a cast to a different size type involved.
15484 uint64_t ratio = array_typesize / ptrarith_typesize;
15485
15486 // TODO: Be smarter about handling cases where array_typesize is not a
15487 // multiple of ptrarith_typesize.
15488 if (ptrarith_typesize * ratio == array_typesize)
15489 size *= llvm::APInt(size.getBitWidth(), ratio);
15490 }
15491 }
15492
15493 if (size.getBitWidth() > index.getBitWidth())
15494 index = index.zext(width: size.getBitWidth());
15495 else if (size.getBitWidth() < index.getBitWidth())
15496 size = size.zext(width: index.getBitWidth());
15497
15498 // For array subscripting the index must be less than size, but for pointer
15499 // arithmetic also allow the index (offset) to be equal to size since
15500 // computing the next address after the end of the array is legal and
15501 // commonly done e.g. in C++ iterators and range-based for loops.
15502 if (AllowOnePastEnd ? index.ule(RHS: size) : index.ult(RHS: size))
15503 return;
15504
15505 // Suppress the warning if the subscript expression (as identified by the
15506 // ']' location) and the index expression are both from macro expansions
15507 // within a system header.
15508 if (ASE) {
15509 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15510 Loc: ASE->getRBracketLoc());
15511 if (SourceMgr.isInSystemHeader(Loc: RBracketLoc)) {
15512 SourceLocation IndexLoc =
15513 SourceMgr.getSpellingLoc(Loc: IndexExpr->getBeginLoc());
15514 if (SourceMgr.isWrittenInSameFile(Loc1: RBracketLoc, Loc2: IndexLoc))
15515 return;
15516 }
15517 }
15518
15519 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15520 : diag::warn_ptr_arith_exceeds_bounds;
15521 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
15522 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
15523
15524 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
15525 PD: PDiag(DiagID)
15526 << index << ArrayTy->desugar() << CastMsg
15527 << CastMsgTy << IndexExpr->getSourceRange());
15528 } else {
15529 unsigned DiagID = diag::warn_array_index_precedes_bounds;
15530 if (!ASE) {
15531 DiagID = diag::warn_ptr_arith_precedes_bounds;
15532 if (index.isNegative()) index = -index;
15533 }
15534
15535 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
15536 PD: PDiag(DiagID) << index << IndexExpr->getSourceRange());
15537 }
15538
15539 const NamedDecl *ND = nullptr;
15540 // Try harder to find a NamedDecl to point at in the note.
15541 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
15542 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15543 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
15544 ND = DRE->getDecl();
15545 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
15546 ND = ME->getMemberDecl();
15547
15548 if (ND)
15549 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
15550 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
15551}
15552
15553void Sema::CheckArrayAccess(const Expr *expr) {
15554 int AllowOnePastEnd = 0;
15555 while (expr) {
15556 expr = expr->IgnoreParenImpCasts();
15557 switch (expr->getStmtClass()) {
15558 case Stmt::ArraySubscriptExprClass: {
15559 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Val: expr);
15560 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getIdx(), ASE,
15561 AllowOnePastEnd: AllowOnePastEnd > 0);
15562 expr = ASE->getBase();
15563 break;
15564 }
15565 case Stmt::MemberExprClass: {
15566 expr = cast<MemberExpr>(Val: expr)->getBase();
15567 break;
15568 }
15569 case Stmt::CXXMemberCallExprClass: {
15570 expr = cast<CXXMemberCallExpr>(Val: expr)->getImplicitObjectArgument();
15571 break;
15572 }
15573 case Stmt::ArraySectionExprClass: {
15574 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(Val: expr);
15575 // FIXME: We should probably be checking all of the elements to the
15576 // 'length' here as well.
15577 if (ASE->getLowerBound())
15578 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getLowerBound(),
15579 /*ASE=*/nullptr, AllowOnePastEnd: AllowOnePastEnd > 0);
15580 return;
15581 }
15582 case Stmt::UnaryOperatorClass: {
15583 // Only unwrap the * and & unary operators
15584 const UnaryOperator *UO = cast<UnaryOperator>(Val: expr);
15585 expr = UO->getSubExpr();
15586 switch (UO->getOpcode()) {
15587 case UO_AddrOf:
15588 AllowOnePastEnd++;
15589 break;
15590 case UO_Deref:
15591 AllowOnePastEnd--;
15592 break;
15593 default:
15594 return;
15595 }
15596 break;
15597 }
15598 case Stmt::ConditionalOperatorClass: {
15599 const ConditionalOperator *cond = cast<ConditionalOperator>(Val: expr);
15600 if (const Expr *lhs = cond->getLHS())
15601 CheckArrayAccess(expr: lhs);
15602 if (const Expr *rhs = cond->getRHS())
15603 CheckArrayAccess(expr: rhs);
15604 return;
15605 }
15606 case Stmt::CXXOperatorCallExprClass: {
15607 const auto *OCE = cast<CXXOperatorCallExpr>(Val: expr);
15608 for (const auto *Arg : OCE->arguments())
15609 CheckArrayAccess(expr: Arg);
15610 return;
15611 }
15612 default:
15613 return;
15614 }
15615 }
15616}
15617
15618static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15619 Expr *RHS, bool isProperty) {
15620 // Check if RHS is an Objective-C object literal, which also can get
15621 // immediately zapped in a weak reference. Note that we explicitly
15622 // allow ObjCStringLiterals, since those are designed to never really die.
15623 RHS = RHS->IgnoreParenImpCasts();
15624
15625 // This enum needs to match with the 'select' in
15626 // warn_objc_arc_literal_assign (off-by-1).
15627 SemaObjC::ObjCLiteralKind Kind = S.ObjC().CheckLiteralKind(FromE: RHS);
15628 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
15629 return false;
15630
15631 S.Diag(Loc, DiagID: diag::warn_arc_literal_assign)
15632 << (unsigned) Kind
15633 << (isProperty ? 0 : 1)
15634 << RHS->getSourceRange();
15635
15636 return true;
15637}
15638
15639static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15640 Qualifiers::ObjCLifetime LT,
15641 Expr *RHS, bool isProperty) {
15642 // Strip off any implicit cast added to get to the one ARC-specific.
15643 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
15644 if (cast->getCastKind() == CK_ARCConsumeObject) {
15645 S.Diag(Loc, DiagID: diag::warn_arc_retained_assign)
15646 << (LT == Qualifiers::OCL_ExplicitNone)
15647 << (isProperty ? 0 : 1)
15648 << RHS->getSourceRange();
15649 return true;
15650 }
15651 RHS = cast->getSubExpr();
15652 }
15653
15654 if (LT == Qualifiers::OCL_Weak &&
15655 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15656 return true;
15657
15658 return false;
15659}
15660
15661bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15662 QualType LHS, Expr *RHS) {
15663 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15664
15665 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15666 return false;
15667
15668 if (checkUnsafeAssignObject(S&: *this, Loc, LT, RHS, isProperty: false))
15669 return true;
15670
15671 return false;
15672}
15673
15674void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15675 Expr *LHS, Expr *RHS) {
15676 QualType LHSType;
15677 // PropertyRef on LHS type need be directly obtained from
15678 // its declaration as it has a PseudoType.
15679 ObjCPropertyRefExpr *PRE
15680 = dyn_cast<ObjCPropertyRefExpr>(Val: LHS->IgnoreParens());
15681 if (PRE && !PRE->isImplicitProperty()) {
15682 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15683 if (PD)
15684 LHSType = PD->getType();
15685 }
15686
15687 if (LHSType.isNull())
15688 LHSType = LHS->getType();
15689
15690 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15691
15692 if (LT == Qualifiers::OCL_Weak) {
15693 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc))
15694 getCurFunction()->markSafeWeakUse(E: LHS);
15695 }
15696
15697 if (checkUnsafeAssigns(Loc, LHS: LHSType, RHS))
15698 return;
15699
15700 // FIXME. Check for other life times.
15701 if (LT != Qualifiers::OCL_None)
15702 return;
15703
15704 if (PRE) {
15705 if (PRE->isImplicitProperty())
15706 return;
15707 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15708 if (!PD)
15709 return;
15710
15711 unsigned Attributes = PD->getPropertyAttributes();
15712 if (Attributes & ObjCPropertyAttribute::kind_assign) {
15713 // when 'assign' attribute was not explicitly specified
15714 // by user, ignore it and rely on property type itself
15715 // for lifetime info.
15716 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15717 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15718 LHSType->isObjCRetainableType())
15719 return;
15720
15721 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
15722 if (cast->getCastKind() == CK_ARCConsumeObject) {
15723 Diag(Loc, DiagID: diag::warn_arc_retained_property_assign)
15724 << RHS->getSourceRange();
15725 return;
15726 }
15727 RHS = cast->getSubExpr();
15728 }
15729 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15730 if (checkUnsafeAssignObject(S&: *this, Loc, LT: Qualifiers::OCL_Weak, RHS, isProperty: true))
15731 return;
15732 }
15733 }
15734}
15735
15736//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15737
15738static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15739 SourceLocation StmtLoc,
15740 const NullStmt *Body) {
15741 // Do not warn if the body is a macro that expands to nothing, e.g:
15742 //
15743 // #define CALL(x)
15744 // if (condition)
15745 // CALL(0);
15746 if (Body->hasLeadingEmptyMacro())
15747 return false;
15748
15749 // Get line numbers of statement and body.
15750 bool StmtLineInvalid;
15751 unsigned StmtLine = SourceMgr.getPresumedLineNumber(Loc: StmtLoc,
15752 Invalid: &StmtLineInvalid);
15753 if (StmtLineInvalid)
15754 return false;
15755
15756 bool BodyLineInvalid;
15757 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Loc: Body->getSemiLoc(),
15758 Invalid: &BodyLineInvalid);
15759 if (BodyLineInvalid)
15760 return false;
15761
15762 // Warn if null statement and body are on the same line.
15763 if (StmtLine != BodyLine)
15764 return false;
15765
15766 return true;
15767}
15768
15769void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15770 const Stmt *Body,
15771 unsigned DiagID) {
15772 // Since this is a syntactic check, don't emit diagnostic for template
15773 // instantiations, this just adds noise.
15774 if (CurrentInstantiationScope)
15775 return;
15776
15777 // The body should be a null statement.
15778 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
15779 if (!NBody)
15780 return;
15781
15782 // Do the usual checks.
15783 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
15784 return;
15785
15786 Diag(Loc: NBody->getSemiLoc(), DiagID);
15787 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
15788}
15789
15790void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15791 const Stmt *PossibleBody) {
15792 assert(!CurrentInstantiationScope); // Ensured by caller
15793
15794 SourceLocation StmtLoc;
15795 const Stmt *Body;
15796 unsigned DiagID;
15797 if (const ForStmt *FS = dyn_cast<ForStmt>(Val: S)) {
15798 StmtLoc = FS->getRParenLoc();
15799 Body = FS->getBody();
15800 DiagID = diag::warn_empty_for_body;
15801 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Val: S)) {
15802 StmtLoc = WS->getRParenLoc();
15803 Body = WS->getBody();
15804 DiagID = diag::warn_empty_while_body;
15805 } else
15806 return; // Neither `for' nor `while'.
15807
15808 // The body should be a null statement.
15809 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
15810 if (!NBody)
15811 return;
15812
15813 // Skip expensive checks if diagnostic is disabled.
15814 if (Diags.isIgnored(DiagID, Loc: NBody->getSemiLoc()))
15815 return;
15816
15817 // Do the usual checks.
15818 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
15819 return;
15820
15821 // `for(...);' and `while(...);' are popular idioms, so in order to keep
15822 // noise level low, emit diagnostics only if for/while is followed by a
15823 // CompoundStmt, e.g.:
15824 // for (int i = 0; i < n; i++);
15825 // {
15826 // a(i);
15827 // }
15828 // or if for/while is followed by a statement with more indentation
15829 // than for/while itself:
15830 // for (int i = 0; i < n; i++);
15831 // a(i);
15832 bool ProbableTypo = isa<CompoundStmt>(Val: PossibleBody);
15833 if (!ProbableTypo) {
15834 bool BodyColInvalid;
15835 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15836 Loc: PossibleBody->getBeginLoc(), Invalid: &BodyColInvalid);
15837 if (BodyColInvalid)
15838 return;
15839
15840 bool StmtColInvalid;
15841 unsigned StmtCol =
15842 SourceMgr.getPresumedColumnNumber(Loc: S->getBeginLoc(), Invalid: &StmtColInvalid);
15843 if (StmtColInvalid)
15844 return;
15845
15846 if (BodyCol > StmtCol)
15847 ProbableTypo = true;
15848 }
15849
15850 if (ProbableTypo) {
15851 Diag(Loc: NBody->getSemiLoc(), DiagID);
15852 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
15853 }
15854}
15855
15856//===--- CHECK: Warn on self move with std::move. -------------------------===//
15857
15858void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15859 SourceLocation OpLoc) {
15860 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess, Loc: OpLoc))
15861 return;
15862
15863 if (inTemplateInstantiation())
15864 return;
15865
15866 // Strip parens and casts away.
15867 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15868 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15869
15870 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
15871 // which we can treat as an inlined std::move
15872 if (const auto *CE = dyn_cast<CallExpr>(Val: RHSExpr);
15873 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
15874 RHSExpr = CE->getArg(Arg: 0);
15875 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(Val: RHSExpr);
15876 CXXSCE && CXXSCE->isXValue())
15877 RHSExpr = CXXSCE->getSubExpr();
15878 else
15879 return;
15880
15881 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
15882 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
15883
15884 // Two DeclRefExpr's, check that the decls are the same.
15885 if (LHSDeclRef && RHSDeclRef) {
15886 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15887 return;
15888 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15889 RHSDeclRef->getDecl()->getCanonicalDecl())
15890 return;
15891
15892 auto D = Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
15893 << LHSExpr->getType() << LHSExpr->getSourceRange()
15894 << RHSExpr->getSourceRange();
15895 if (const FieldDecl *F =
15896 getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDeclRef->getDecl()))
15897 D << 1 << F
15898 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
15899 else
15900 D << 0;
15901 return;
15902 }
15903
15904 // Member variables require a different approach to check for self moves.
15905 // MemberExpr's are the same if every nested MemberExpr refers to the same
15906 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15907 // the base Expr's are CXXThisExpr's.
15908 const Expr *LHSBase = LHSExpr;
15909 const Expr *RHSBase = RHSExpr;
15910 const MemberExpr *LHSME = dyn_cast<MemberExpr>(Val: LHSExpr);
15911 const MemberExpr *RHSME = dyn_cast<MemberExpr>(Val: RHSExpr);
15912 if (!LHSME || !RHSME)
15913 return;
15914
15915 while (LHSME && RHSME) {
15916 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15917 RHSME->getMemberDecl()->getCanonicalDecl())
15918 return;
15919
15920 LHSBase = LHSME->getBase();
15921 RHSBase = RHSME->getBase();
15922 LHSME = dyn_cast<MemberExpr>(Val: LHSBase);
15923 RHSME = dyn_cast<MemberExpr>(Val: RHSBase);
15924 }
15925
15926 LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSBase);
15927 RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSBase);
15928 if (LHSDeclRef && RHSDeclRef) {
15929 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15930 return;
15931 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15932 RHSDeclRef->getDecl()->getCanonicalDecl())
15933 return;
15934
15935 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
15936 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15937 << RHSExpr->getSourceRange();
15938 return;
15939 }
15940
15941 if (isa<CXXThisExpr>(Val: LHSBase) && isa<CXXThisExpr>(Val: RHSBase))
15942 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
15943 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
15944 << RHSExpr->getSourceRange();
15945}
15946
15947//===--- Layout compatibility ----------------------------------------------//
15948
15949static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
15950
15951/// Check if two enumeration types are layout-compatible.
15952static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
15953 const EnumDecl *ED2) {
15954 // C++11 [dcl.enum] p8:
15955 // Two enumeration types are layout-compatible if they have the same
15956 // underlying type.
15957 return ED1->isComplete() && ED2->isComplete() &&
15958 C.hasSameType(T1: ED1->getIntegerType(), T2: ED2->getIntegerType());
15959}
15960
15961/// Check if two fields are layout-compatible.
15962/// Can be used on union members, which are exempt from alignment requirement
15963/// of common initial sequence.
15964static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
15965 const FieldDecl *Field2,
15966 bool AreUnionMembers = false) {
15967#ifndef NDEBUG
15968 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
15969 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
15970 assert(((Field1Parent->isStructureOrClassType() &&
15971 Field2Parent->isStructureOrClassType()) ||
15972 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
15973 "Can't evaluate layout compatibility between a struct field and a "
15974 "union field.");
15975 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
15976 (AreUnionMembers && Field1Parent->isUnionType())) &&
15977 "AreUnionMembers should be 'true' for union fields (only).");
15978#endif
15979
15980 if (!isLayoutCompatible(C, T1: Field1->getType(), T2: Field2->getType()))
15981 return false;
15982
15983 if (Field1->isBitField() != Field2->isBitField())
15984 return false;
15985
15986 if (Field1->isBitField()) {
15987 // Make sure that the bit-fields are the same length.
15988 unsigned Bits1 = Field1->getBitWidthValue();
15989 unsigned Bits2 = Field2->getBitWidthValue();
15990
15991 if (Bits1 != Bits2)
15992 return false;
15993 }
15994
15995 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
15996 Field2->hasAttr<clang::NoUniqueAddressAttr>())
15997 return false;
15998
15999 if (!AreUnionMembers &&
16000 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16001 return false;
16002
16003 return true;
16004}
16005
16006/// Check if two standard-layout structs are layout-compatible.
16007/// (C++11 [class.mem] p17)
16008static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16009 const RecordDecl *RD2) {
16010 // Get to the class where the fields are declared
16011 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(Val: RD1))
16012 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16013
16014 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(Val: RD2))
16015 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16016
16017 // Check the fields.
16018 return llvm::equal(LRange: RD1->fields(), RRange: RD2->fields(),
16019 P: [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16020 return isLayoutCompatible(C, Field1: F1, Field2: F2);
16021 });
16022}
16023
16024/// Check if two standard-layout unions are layout-compatible.
16025/// (C++11 [class.mem] p18)
16026static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16027 const RecordDecl *RD2) {
16028 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16029 RD2->fields());
16030
16031 for (auto *Field1 : RD1->fields()) {
16032 auto I = UnmatchedFields.begin();
16033 auto E = UnmatchedFields.end();
16034
16035 for ( ; I != E; ++I) {
16036 if (isLayoutCompatible(C, Field1, Field2: *I, /*IsUnionMember=*/AreUnionMembers: true)) {
16037 bool Result = UnmatchedFields.erase(Ptr: *I);
16038 (void) Result;
16039 assert(Result);
16040 break;
16041 }
16042 }
16043 if (I == E)
16044 return false;
16045 }
16046
16047 return UnmatchedFields.empty();
16048}
16049
16050static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16051 const RecordDecl *RD2) {
16052 if (RD1->isUnion() != RD2->isUnion())
16053 return false;
16054
16055 if (RD1->isUnion())
16056 return isLayoutCompatibleUnion(C, RD1, RD2);
16057 else
16058 return isLayoutCompatibleStruct(C, RD1, RD2);
16059}
16060
16061/// Check if two types are layout-compatible in C++11 sense.
16062static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16063 if (T1.isNull() || T2.isNull())
16064 return false;
16065
16066 // C++20 [basic.types] p11:
16067 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16068 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16069 // or layout-compatible standard-layout class types (11.4).
16070 T1 = T1.getCanonicalType().getUnqualifiedType();
16071 T2 = T2.getCanonicalType().getUnqualifiedType();
16072
16073 if (C.hasSameType(T1, T2))
16074 return true;
16075
16076 const Type::TypeClass TC1 = T1->getTypeClass();
16077 const Type::TypeClass TC2 = T2->getTypeClass();
16078
16079 if (TC1 != TC2)
16080 return false;
16081
16082 if (TC1 == Type::Enum)
16083 return isLayoutCompatible(C, ED1: T1->castAsEnumDecl(), ED2: T2->castAsEnumDecl());
16084 if (TC1 == Type::Record) {
16085 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16086 return false;
16087
16088 return isLayoutCompatible(C, RD1: T1->castAsRecordDecl(),
16089 RD2: T2->castAsRecordDecl());
16090 }
16091
16092 return false;
16093}
16094
16095bool Sema::IsLayoutCompatible(QualType T1, QualType T2) const {
16096 return isLayoutCompatible(C: getASTContext(), T1, T2);
16097}
16098
16099//===-------------- Pointer interconvertibility ----------------------------//
16100
16101bool Sema::IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
16102 const TypeSourceInfo *Derived) {
16103 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16104 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16105
16106 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16107 getASTContext().hasSameType(T1: BaseT, T2: DerivedT))
16108 return true;
16109
16110 if (!IsDerivedFrom(Loc: Derived->getTypeLoc().getBeginLoc(), Derived: DerivedT, Base: BaseT))
16111 return false;
16112
16113 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16114 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16115 return true;
16116
16117 return false;
16118}
16119
16120//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16121
16122/// Given a type tag expression find the type tag itself.
16123///
16124/// \param TypeExpr Type tag expression, as it appears in user's code.
16125///
16126/// \param VD Declaration of an identifier that appears in a type tag.
16127///
16128/// \param MagicValue Type tag magic value.
16129///
16130/// \param isConstantEvaluated whether the evalaution should be performed in
16131
16132/// constant context.
16133static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16134 const ValueDecl **VD, uint64_t *MagicValue,
16135 bool isConstantEvaluated) {
16136 while(true) {
16137 if (!TypeExpr)
16138 return false;
16139
16140 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16141
16142 switch (TypeExpr->getStmtClass()) {
16143 case Stmt::UnaryOperatorClass: {
16144 const UnaryOperator *UO = cast<UnaryOperator>(Val: TypeExpr);
16145 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16146 TypeExpr = UO->getSubExpr();
16147 continue;
16148 }
16149 return false;
16150 }
16151
16152 case Stmt::DeclRefExprClass: {
16153 const DeclRefExpr *DRE = cast<DeclRefExpr>(Val: TypeExpr);
16154 *VD = DRE->getDecl();
16155 return true;
16156 }
16157
16158 case Stmt::IntegerLiteralClass: {
16159 const IntegerLiteral *IL = cast<IntegerLiteral>(Val: TypeExpr);
16160 llvm::APInt MagicValueAPInt = IL->getValue();
16161 if (MagicValueAPInt.getActiveBits() <= 64) {
16162 *MagicValue = MagicValueAPInt.getZExtValue();
16163 return true;
16164 } else
16165 return false;
16166 }
16167
16168 case Stmt::BinaryConditionalOperatorClass:
16169 case Stmt::ConditionalOperatorClass: {
16170 const AbstractConditionalOperator *ACO =
16171 cast<AbstractConditionalOperator>(Val: TypeExpr);
16172 bool Result;
16173 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16174 InConstantContext: isConstantEvaluated)) {
16175 if (Result)
16176 TypeExpr = ACO->getTrueExpr();
16177 else
16178 TypeExpr = ACO->getFalseExpr();
16179 continue;
16180 }
16181 return false;
16182 }
16183
16184 case Stmt::BinaryOperatorClass: {
16185 const BinaryOperator *BO = cast<BinaryOperator>(Val: TypeExpr);
16186 if (BO->getOpcode() == BO_Comma) {
16187 TypeExpr = BO->getRHS();
16188 continue;
16189 }
16190 return false;
16191 }
16192
16193 default:
16194 return false;
16195 }
16196 }
16197}
16198
16199/// Retrieve the C type corresponding to type tag TypeExpr.
16200///
16201/// \param TypeExpr Expression that specifies a type tag.
16202///
16203/// \param MagicValues Registered magic values.
16204///
16205/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16206/// kind.
16207///
16208/// \param TypeInfo Information about the corresponding C type.
16209///
16210/// \param isConstantEvaluated whether the evalaution should be performed in
16211/// constant context.
16212///
16213/// \returns true if the corresponding C type was found.
16214static bool GetMatchingCType(
16215 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16216 const ASTContext &Ctx,
16217 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16218 *MagicValues,
16219 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16220 bool isConstantEvaluated) {
16221 FoundWrongKind = false;
16222
16223 // Variable declaration that has type_tag_for_datatype attribute.
16224 const ValueDecl *VD = nullptr;
16225
16226 uint64_t MagicValue;
16227
16228 if (!FindTypeTagExpr(TypeExpr, Ctx, VD: &VD, MagicValue: &MagicValue, isConstantEvaluated))
16229 return false;
16230
16231 if (VD) {
16232 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16233 if (I->getArgumentKind() != ArgumentKind) {
16234 FoundWrongKind = true;
16235 return false;
16236 }
16237 TypeInfo.Type = I->getMatchingCType();
16238 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16239 TypeInfo.MustBeNull = I->getMustBeNull();
16240 return true;
16241 }
16242 return false;
16243 }
16244
16245 if (!MagicValues)
16246 return false;
16247
16248 llvm::DenseMap<Sema::TypeTagMagicValue,
16249 Sema::TypeTagData>::const_iterator I =
16250 MagicValues->find(Val: std::make_pair(x&: ArgumentKind, y&: MagicValue));
16251 if (I == MagicValues->end())
16252 return false;
16253
16254 TypeInfo = I->second;
16255 return true;
16256}
16257
16258void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16259 uint64_t MagicValue, QualType Type,
16260 bool LayoutCompatible,
16261 bool MustBeNull) {
16262 if (!TypeTagForDatatypeMagicValues)
16263 TypeTagForDatatypeMagicValues.reset(
16264 p: new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16265
16266 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16267 (*TypeTagForDatatypeMagicValues)[Magic] =
16268 TypeTagData(Type, LayoutCompatible, MustBeNull);
16269}
16270
16271static bool IsSameCharType(QualType T1, QualType T2) {
16272 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16273 if (!BT1)
16274 return false;
16275
16276 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16277 if (!BT2)
16278 return false;
16279
16280 BuiltinType::Kind T1Kind = BT1->getKind();
16281 BuiltinType::Kind T2Kind = BT2->getKind();
16282
16283 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16284 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16285 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16286 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16287}
16288
16289void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16290 const ArrayRef<const Expr *> ExprArgs,
16291 SourceLocation CallSiteLoc) {
16292 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16293 bool IsPointerAttr = Attr->getIsPointer();
16294
16295 // Retrieve the argument representing the 'type_tag'.
16296 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16297 if (TypeTagIdxAST >= ExprArgs.size()) {
16298 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
16299 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16300 return;
16301 }
16302 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16303 bool FoundWrongKind;
16304 TypeTagData TypeInfo;
16305 if (!GetMatchingCType(ArgumentKind, TypeExpr: TypeTagExpr, Ctx: Context,
16306 MagicValues: TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16307 TypeInfo, isConstantEvaluated: isConstantEvaluatedContext())) {
16308 if (FoundWrongKind)
16309 Diag(Loc: TypeTagExpr->getExprLoc(),
16310 DiagID: diag::warn_type_tag_for_datatype_wrong_kind)
16311 << TypeTagExpr->getSourceRange();
16312 return;
16313 }
16314
16315 // Retrieve the argument representing the 'arg_idx'.
16316 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16317 if (ArgumentIdxAST >= ExprArgs.size()) {
16318 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
16319 << 1 << Attr->getArgumentIdx().getSourceIndex();
16320 return;
16321 }
16322 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16323 if (IsPointerAttr) {
16324 // Skip implicit cast of pointer to `void *' (as a function argument).
16325 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgumentExpr))
16326 if (ICE->getType()->isVoidPointerType() &&
16327 ICE->getCastKind() == CK_BitCast)
16328 ArgumentExpr = ICE->getSubExpr();
16329 }
16330 QualType ArgumentType = ArgumentExpr->getType();
16331
16332 // Passing a `void*' pointer shouldn't trigger a warning.
16333 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16334 return;
16335
16336 if (TypeInfo.MustBeNull) {
16337 // Type tag with matching void type requires a null pointer.
16338 if (!ArgumentExpr->isNullPointerConstant(Ctx&: Context,
16339 NPC: Expr::NPC_ValueDependentIsNotNull)) {
16340 Diag(Loc: ArgumentExpr->getExprLoc(),
16341 DiagID: diag::warn_type_safety_null_pointer_required)
16342 << ArgumentKind->getName()
16343 << ArgumentExpr->getSourceRange()
16344 << TypeTagExpr->getSourceRange();
16345 }
16346 return;
16347 }
16348
16349 QualType RequiredType = TypeInfo.Type;
16350 if (IsPointerAttr)
16351 RequiredType = Context.getPointerType(T: RequiredType);
16352
16353 bool mismatch = false;
16354 if (!TypeInfo.LayoutCompatible) {
16355 mismatch = !Context.hasSameType(T1: ArgumentType, T2: RequiredType);
16356
16357 // C++11 [basic.fundamental] p1:
16358 // Plain char, signed char, and unsigned char are three distinct types.
16359 //
16360 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16361 // char' depending on the current char signedness mode.
16362 if (mismatch)
16363 if ((IsPointerAttr && IsSameCharType(T1: ArgumentType->getPointeeType(),
16364 T2: RequiredType->getPointeeType())) ||
16365 (!IsPointerAttr && IsSameCharType(T1: ArgumentType, T2: RequiredType)))
16366 mismatch = false;
16367 } else
16368 if (IsPointerAttr)
16369 mismatch = !isLayoutCompatible(C: Context,
16370 T1: ArgumentType->getPointeeType(),
16371 T2: RequiredType->getPointeeType());
16372 else
16373 mismatch = !isLayoutCompatible(C: Context, T1: ArgumentType, T2: RequiredType);
16374
16375 if (mismatch)
16376 Diag(Loc: ArgumentExpr->getExprLoc(), DiagID: diag::warn_type_safety_type_mismatch)
16377 << ArgumentType << ArgumentKind
16378 << TypeInfo.LayoutCompatible << RequiredType
16379 << ArgumentExpr->getSourceRange()
16380 << TypeTagExpr->getSourceRange();
16381}
16382
16383void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16384 CharUnits Alignment) {
16385 currentEvaluationContext().MisalignedMembers.emplace_back(Args&: E, Args&: RD, Args&: MD,
16386 Args&: Alignment);
16387}
16388
16389void Sema::DiagnoseMisalignedMembers() {
16390 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16391 const NamedDecl *ND = m.RD;
16392 if (ND->getName().empty()) {
16393 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16394 ND = TD;
16395 }
16396 Diag(Loc: m.E->getBeginLoc(), DiagID: diag::warn_taking_address_of_packed_member)
16397 << m.MD << ND << m.E->getSourceRange();
16398 }
16399 currentEvaluationContext().MisalignedMembers.clear();
16400}
16401
16402void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16403 E = E->IgnoreParens();
16404 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16405 return;
16406 if (isa<UnaryOperator>(Val: E) &&
16407 cast<UnaryOperator>(Val: E)->getOpcode() == UO_AddrOf) {
16408 auto *Op = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
16409 if (isa<MemberExpr>(Val: Op)) {
16410 auto &MisalignedMembersForExpr =
16411 currentEvaluationContext().MisalignedMembers;
16412 auto *MA = llvm::find(Range&: MisalignedMembersForExpr, Val: MisalignedMember(Op));
16413 if (MA != MisalignedMembersForExpr.end() &&
16414 (T->isDependentType() || T->isIntegerType() ||
16415 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16416 Context.getTypeAlignInChars(
16417 T: T->getPointeeType()) <= MA->Alignment))))
16418 MisalignedMembersForExpr.erase(CI: MA);
16419 }
16420 }
16421}
16422
16423void Sema::RefersToMemberWithReducedAlignment(
16424 Expr *E,
16425 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16426 Action) {
16427 const auto *ME = dyn_cast<MemberExpr>(Val: E);
16428 if (!ME)
16429 return;
16430
16431 // No need to check expressions with an __unaligned-qualified type.
16432 if (E->getType().getQualifiers().hasUnaligned())
16433 return;
16434
16435 // For a chain of MemberExpr like "a.b.c.d" this list
16436 // will keep FieldDecl's like [d, c, b].
16437 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16438 const MemberExpr *TopME = nullptr;
16439 bool AnyIsPacked = false;
16440 do {
16441 QualType BaseType = ME->getBase()->getType();
16442 if (BaseType->isDependentType())
16443 return;
16444 if (ME->isArrow())
16445 BaseType = BaseType->getPointeeType();
16446 auto *RD = BaseType->castAsRecordDecl();
16447 if (RD->isInvalidDecl())
16448 return;
16449
16450 ValueDecl *MD = ME->getMemberDecl();
16451 auto *FD = dyn_cast<FieldDecl>(Val: MD);
16452 // We do not care about non-data members.
16453 if (!FD || FD->isInvalidDecl())
16454 return;
16455
16456 AnyIsPacked =
16457 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16458 ReverseMemberChain.push_back(Elt: FD);
16459
16460 TopME = ME;
16461 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParens());
16462 } while (ME);
16463 assert(TopME && "We did not compute a topmost MemberExpr!");
16464
16465 // Not the scope of this diagnostic.
16466 if (!AnyIsPacked)
16467 return;
16468
16469 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16470 const auto *DRE = dyn_cast<DeclRefExpr>(Val: TopBase);
16471 // TODO: The innermost base of the member expression may be too complicated.
16472 // For now, just disregard these cases. This is left for future
16473 // improvement.
16474 if (!DRE && !isa<CXXThisExpr>(Val: TopBase))
16475 return;
16476
16477 // Alignment expected by the whole expression.
16478 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(T: E->getType());
16479
16480 // No need to do anything else with this case.
16481 if (ExpectedAlignment.isOne())
16482 return;
16483
16484 // Synthesize offset of the whole access.
16485 CharUnits Offset;
16486 for (const FieldDecl *FD : llvm::reverse(C&: ReverseMemberChain))
16487 Offset += Context.toCharUnitsFromBits(BitSize: Context.getFieldOffset(FD));
16488
16489 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16490 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16491 T: Context.getCanonicalTagType(TD: ReverseMemberChain.back()->getParent()));
16492
16493 // The base expression of the innermost MemberExpr may give
16494 // stronger guarantees than the class containing the member.
16495 if (DRE && !TopME->isArrow()) {
16496 const ValueDecl *VD = DRE->getDecl();
16497 if (!VD->getType()->isReferenceType())
16498 CompleteObjectAlignment =
16499 std::max(a: CompleteObjectAlignment, b: Context.getDeclAlign(D: VD));
16500 }
16501
16502 // Check if the synthesized offset fulfills the alignment.
16503 if (!Offset.isMultipleOf(N: ExpectedAlignment) ||
16504 // It may fulfill the offset it but the effective alignment may still be
16505 // lower than the expected expression alignment.
16506 CompleteObjectAlignment < ExpectedAlignment) {
16507 // If this happens, we want to determine a sensible culprit of this.
16508 // Intuitively, watching the chain of member expressions from right to
16509 // left, we start with the required alignment (as required by the field
16510 // type) but some packed attribute in that chain has reduced the alignment.
16511 // It may happen that another packed structure increases it again. But if
16512 // we are here such increase has not been enough. So pointing the first
16513 // FieldDecl that either is packed or else its RecordDecl is,
16514 // seems reasonable.
16515 FieldDecl *FD = nullptr;
16516 CharUnits Alignment;
16517 for (FieldDecl *FDI : ReverseMemberChain) {
16518 if (FDI->hasAttr<PackedAttr>() ||
16519 FDI->getParent()->hasAttr<PackedAttr>()) {
16520 FD = FDI;
16521 Alignment = std::min(a: Context.getTypeAlignInChars(T: FD->getType()),
16522 b: Context.getTypeAlignInChars(
16523 T: Context.getCanonicalTagType(TD: FD->getParent())));
16524 break;
16525 }
16526 }
16527 assert(FD && "We did not find a packed FieldDecl!");
16528 Action(E, FD->getParent(), FD, Alignment);
16529 }
16530}
16531
16532void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16533 using namespace std::placeholders;
16534
16535 RefersToMemberWithReducedAlignment(
16536 E: rhs, Action: std::bind(f: &Sema::AddPotentialMisalignedMembers, args: std::ref(t&: *this), args: _1,
16537 args: _2, args: _3, args: _4));
16538}
16539
16540bool Sema::PrepareBuiltinElementwiseMathOneArgCall(
16541 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16542 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16543 return true;
16544
16545 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
16546 if (A.isInvalid())
16547 return true;
16548
16549 TheCall->setArg(Arg: 0, ArgExpr: A.get());
16550 QualType TyA = A.get()->getType();
16551
16552 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
16553 ArgTyRestr, ArgOrdinal: 1))
16554 return true;
16555
16556 TheCall->setType(TyA);
16557 return false;
16558}
16559
16560bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
16561 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16562 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
16563 TheCall->setType(*Res);
16564 return false;
16565 }
16566 return true;
16567}
16568
16569bool Sema::BuiltinVectorToScalarMath(CallExpr *TheCall) {
16570 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
16571 if (!Res)
16572 return true;
16573
16574 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
16575 TheCall->setType(VecTy0->getElementType());
16576 else
16577 TheCall->setType(*Res);
16578
16579 return false;
16580}
16581
16582static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS,
16583 SourceLocation Loc) {
16584 QualType L = LHS->getEnumCoercedType(Ctx: S.Context),
16585 R = RHS->getEnumCoercedType(Ctx: S.Context);
16586 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
16587 !S.Context.hasSameUnqualifiedType(T1: L, T2: R)) {
16588 return S.Diag(Loc, DiagID: diag::err_conv_mixed_enum_types)
16589 << LHS->getSourceRange() << RHS->getSourceRange()
16590 << /*Arithmetic Between*/ 0 << L << R;
16591 }
16592 return false;
16593}
16594
16595/// Check if all arguments have the same type. If the types don't match, emit an
16596/// error message and return true. Otherwise return false.
16597///
16598/// For scalars we directly compare their unqualified types. But even if we
16599/// compare unqualified vector types, a difference in qualifiers in the element
16600/// types can make the vector types be considered not equal. For example,
16601/// vector of 4 'const float' values vs vector of 4 'float' values.
16602/// So we compare unqualified types of their elements and number of elements.
16603static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef,
16604 ArrayRef<Expr *> Args) {
16605 assert(!Args.empty() && "Should have at least one argument.");
16606
16607 Expr *Arg0 = Args.front();
16608 QualType Ty0 = Arg0->getType();
16609
16610 auto EmitError = [&](Expr *ArgI) {
16611 SemaRef.Diag(Loc: Arg0->getBeginLoc(),
16612 DiagID: diag::err_typecheck_call_different_arg_types)
16613 << Arg0->getType() << ArgI->getType();
16614 };
16615
16616 // Compare scalar types.
16617 if (!Ty0->isVectorType()) {
16618 for (Expr *ArgI : Args.drop_front())
16619 if (!SemaRef.Context.hasSameUnqualifiedType(T1: Ty0, T2: ArgI->getType())) {
16620 EmitError(ArgI);
16621 return true;
16622 }
16623
16624 return false;
16625 }
16626
16627 // Compare vector types.
16628 const auto *Vec0 = Ty0->castAs<VectorType>();
16629 for (Expr *ArgI : Args.drop_front()) {
16630 const auto *VecI = ArgI->getType()->getAs<VectorType>();
16631 if (!VecI ||
16632 !SemaRef.Context.hasSameUnqualifiedType(T1: Vec0->getElementType(),
16633 T2: VecI->getElementType()) ||
16634 Vec0->getNumElements() != VecI->getNumElements()) {
16635 EmitError(ArgI);
16636 return true;
16637 }
16638 }
16639
16640 return false;
16641}
16642
16643std::optional<QualType>
16644Sema::BuiltinVectorMath(CallExpr *TheCall,
16645 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16646 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
16647 return std::nullopt;
16648
16649 if (checkBuiltinVectorMathMixedEnums(
16650 S&: *this, LHS: TheCall->getArg(Arg: 0), RHS: TheCall->getArg(Arg: 1), Loc: TheCall->getExprLoc()))
16651 return std::nullopt;
16652
16653 Expr *Args[2];
16654 for (int I = 0; I < 2; ++I) {
16655 ExprResult Converted =
16656 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
16657 if (Converted.isInvalid())
16658 return std::nullopt;
16659 Args[I] = Converted.get();
16660 }
16661
16662 SourceLocation LocA = Args[0]->getBeginLoc();
16663 QualType TyA = Args[0]->getType();
16664
16665 if (checkMathBuiltinElementType(S&: *this, Loc: LocA, ArgTy: TyA, ArgTyRestr, ArgOrdinal: 1))
16666 return std::nullopt;
16667
16668 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
16669 return std::nullopt;
16670
16671 TheCall->setArg(Arg: 0, ArgExpr: Args[0]);
16672 TheCall->setArg(Arg: 1, ArgExpr: Args[1]);
16673 return TyA;
16674}
16675
16676bool Sema::BuiltinElementwiseTernaryMath(
16677 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
16678 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
16679 return true;
16680
16681 SourceLocation Loc = TheCall->getExprLoc();
16682 if (checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 0),
16683 RHS: TheCall->getArg(Arg: 1), Loc) ||
16684 checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 1),
16685 RHS: TheCall->getArg(Arg: 2), Loc))
16686 return true;
16687
16688 Expr *Args[3];
16689 for (int I = 0; I < 3; ++I) {
16690 ExprResult Converted =
16691 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
16692 if (Converted.isInvalid())
16693 return true;
16694 Args[I] = Converted.get();
16695 }
16696
16697 int ArgOrdinal = 1;
16698 for (Expr *Arg : Args) {
16699 if (checkMathBuiltinElementType(S&: *this, Loc: Arg->getBeginLoc(), ArgTy: Arg->getType(),
16700 ArgTyRestr, ArgOrdinal: ArgOrdinal++))
16701 return true;
16702 }
16703
16704 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
16705 return true;
16706
16707 for (int I = 0; I < 3; ++I)
16708 TheCall->setArg(Arg: I, ArgExpr: Args[I]);
16709
16710 TheCall->setType(Args[0]->getType());
16711 return false;
16712}
16713
16714bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
16715 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16716 return true;
16717
16718 ExprResult A = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
16719 if (A.isInvalid())
16720 return true;
16721
16722 TheCall->setArg(Arg: 0, ArgExpr: A.get());
16723 return false;
16724}
16725
16726bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
16727 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16728 return true;
16729
16730 ExprResult Arg = TheCall->getArg(Arg: 0);
16731 QualType TyArg = Arg.get()->getType();
16732
16733 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
16734 return Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
16735 DiagID: diag::err_builtin_invalid_arg_type)
16736 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
16737
16738 TheCall->setType(TyArg);
16739 return false;
16740}
16741
16742ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
16743 ExprResult CallResult) {
16744 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
16745 return ExprError();
16746
16747 ExprResult MatrixArg = DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
16748 if (MatrixArg.isInvalid())
16749 return MatrixArg;
16750 Expr *Matrix = MatrixArg.get();
16751
16752 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16753 if (!MType) {
16754 Diag(Loc: Matrix->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16755 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
16756 << Matrix->getType();
16757 return ExprError();
16758 }
16759
16760 // Create returned matrix type by swapping rows and columns of the argument
16761 // matrix type.
16762 QualType ResultType = Context.getConstantMatrixType(
16763 ElementType: MType->getElementType(), NumRows: MType->getNumColumns(), NumColumns: MType->getNumRows());
16764
16765 // Change the return type to the type of the returned matrix.
16766 TheCall->setType(ResultType);
16767
16768 // Update call argument to use the possibly converted matrix argument.
16769 TheCall->setArg(Arg: 0, ArgExpr: Matrix);
16770 return CallResult;
16771}
16772
16773// Get and verify the matrix dimensions.
16774static std::optional<unsigned>
16775getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16776 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(Ctx: S.Context);
16777 if (!Value) {
16778 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_scalar_unsigned_arg)
16779 << Name;
16780 return {};
16781 }
16782 uint64_t Dim = Value->getZExtValue();
16783 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
16784 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_invalid_dimension)
16785 << Name << S.Context.getLangOpts().MaxMatrixDimension;
16786 return {};
16787 }
16788 return Dim;
16789}
16790
16791ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16792 ExprResult CallResult) {
16793 if (!getLangOpts().MatrixTypes) {
16794 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
16795 return ExprError();
16796 }
16797
16798 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16799 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
16800 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
16801 << /*column*/ 1 << /*load*/ 0;
16802 return ExprError();
16803 }
16804
16805 if (checkArgCount(Call: TheCall, DesiredArgCount: 4))
16806 return ExprError();
16807
16808 unsigned PtrArgIdx = 0;
16809 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
16810 Expr *RowsExpr = TheCall->getArg(Arg: 1);
16811 Expr *ColumnsExpr = TheCall->getArg(Arg: 2);
16812 Expr *StrideExpr = TheCall->getArg(Arg: 3);
16813
16814 bool ArgError = false;
16815
16816 // Check pointer argument.
16817 {
16818 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
16819 if (PtrConv.isInvalid())
16820 return PtrConv;
16821 PtrExpr = PtrConv.get();
16822 TheCall->setArg(Arg: 0, ArgExpr: PtrExpr);
16823 if (PtrExpr->isTypeDependent()) {
16824 TheCall->setType(Context.DependentTy);
16825 return TheCall;
16826 }
16827 }
16828
16829 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16830 QualType ElementTy;
16831 if (!PtrTy) {
16832 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16833 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
16834 << PtrExpr->getType();
16835 ArgError = true;
16836 } else {
16837 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16838
16839 if (!ConstantMatrixType::isValidElementType(T: ElementTy, LangOpts: getLangOpts())) {
16840 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16841 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
16842 << /* no fp */ 0 << PtrExpr->getType();
16843 ArgError = true;
16844 }
16845 }
16846
16847 // Apply default Lvalue conversions and convert the expression to size_t.
16848 auto ApplyArgumentConversions = [this](Expr *E) {
16849 ExprResult Conv = DefaultLvalueConversion(E);
16850 if (Conv.isInvalid())
16851 return Conv;
16852
16853 return tryConvertExprToType(E: Conv.get(), Ty: Context.getSizeType());
16854 };
16855
16856 // Apply conversion to row and column expressions.
16857 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16858 if (!RowsConv.isInvalid()) {
16859 RowsExpr = RowsConv.get();
16860 TheCall->setArg(Arg: 1, ArgExpr: RowsExpr);
16861 } else
16862 RowsExpr = nullptr;
16863
16864 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16865 if (!ColumnsConv.isInvalid()) {
16866 ColumnsExpr = ColumnsConv.get();
16867 TheCall->setArg(Arg: 2, ArgExpr: ColumnsExpr);
16868 } else
16869 ColumnsExpr = nullptr;
16870
16871 // If any part of the result matrix type is still pending, just use
16872 // Context.DependentTy, until all parts are resolved.
16873 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16874 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16875 TheCall->setType(Context.DependentTy);
16876 return CallResult;
16877 }
16878
16879 // Check row and column dimensions.
16880 std::optional<unsigned> MaybeRows;
16881 if (RowsExpr)
16882 MaybeRows = getAndVerifyMatrixDimension(Expr: RowsExpr, Name: "row", S&: *this);
16883
16884 std::optional<unsigned> MaybeColumns;
16885 if (ColumnsExpr)
16886 MaybeColumns = getAndVerifyMatrixDimension(Expr: ColumnsExpr, Name: "column", S&: *this);
16887
16888 // Check stride argument.
16889 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16890 if (StrideConv.isInvalid())
16891 return ExprError();
16892 StrideExpr = StrideConv.get();
16893 TheCall->setArg(Arg: 3, ArgExpr: StrideExpr);
16894
16895 if (MaybeRows) {
16896 if (std::optional<llvm::APSInt> Value =
16897 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
16898 uint64_t Stride = Value->getZExtValue();
16899 if (Stride < *MaybeRows) {
16900 Diag(Loc: StrideExpr->getBeginLoc(),
16901 DiagID: diag::err_builtin_matrix_stride_too_small);
16902 ArgError = true;
16903 }
16904 }
16905 }
16906
16907 if (ArgError || !MaybeRows || !MaybeColumns)
16908 return ExprError();
16909
16910 TheCall->setType(
16911 Context.getConstantMatrixType(ElementType: ElementTy, NumRows: *MaybeRows, NumColumns: *MaybeColumns));
16912 return CallResult;
16913}
16914
16915ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16916 ExprResult CallResult) {
16917 if (!getLangOpts().MatrixTypes) {
16918 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
16919 return ExprError();
16920 }
16921
16922 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
16923 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
16924 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
16925 << /*column*/ 1 << /*store*/ 1;
16926 return ExprError();
16927 }
16928
16929 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
16930 return ExprError();
16931
16932 unsigned PtrArgIdx = 1;
16933 Expr *MatrixExpr = TheCall->getArg(Arg: 0);
16934 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
16935 Expr *StrideExpr = TheCall->getArg(Arg: 2);
16936
16937 bool ArgError = false;
16938
16939 {
16940 ExprResult MatrixConv = DefaultLvalueConversion(E: MatrixExpr);
16941 if (MatrixConv.isInvalid())
16942 return MatrixConv;
16943 MatrixExpr = MatrixConv.get();
16944 TheCall->setArg(Arg: 0, ArgExpr: MatrixExpr);
16945 }
16946 if (MatrixExpr->isTypeDependent()) {
16947 TheCall->setType(Context.DependentTy);
16948 return TheCall;
16949 }
16950
16951 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16952 if (!MatrixTy) {
16953 Diag(Loc: MatrixExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16954 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
16955 ArgError = true;
16956 }
16957
16958 {
16959 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
16960 if (PtrConv.isInvalid())
16961 return PtrConv;
16962 PtrExpr = PtrConv.get();
16963 TheCall->setArg(Arg: 1, ArgExpr: PtrExpr);
16964 if (PtrExpr->isTypeDependent()) {
16965 TheCall->setType(Context.DependentTy);
16966 return TheCall;
16967 }
16968 }
16969
16970 // Check pointer argument.
16971 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16972 if (!PtrTy) {
16973 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
16974 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
16975 << PtrExpr->getType();
16976 ArgError = true;
16977 } else {
16978 QualType ElementTy = PtrTy->getPointeeType();
16979 if (ElementTy.isConstQualified()) {
16980 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_matrix_store_to_const);
16981 ArgError = true;
16982 }
16983 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16984 if (MatrixTy &&
16985 !Context.hasSameType(T1: ElementTy, T2: MatrixTy->getElementType())) {
16986 Diag(Loc: PtrExpr->getBeginLoc(),
16987 DiagID: diag::err_builtin_matrix_pointer_arg_mismatch)
16988 << ElementTy << MatrixTy->getElementType();
16989 ArgError = true;
16990 }
16991 }
16992
16993 // Apply default Lvalue conversions and convert the stride expression to
16994 // size_t.
16995 {
16996 ExprResult StrideConv = DefaultLvalueConversion(E: StrideExpr);
16997 if (StrideConv.isInvalid())
16998 return StrideConv;
16999
17000 StrideConv = tryConvertExprToType(E: StrideConv.get(), Ty: Context.getSizeType());
17001 if (StrideConv.isInvalid())
17002 return StrideConv;
17003 StrideExpr = StrideConv.get();
17004 TheCall->setArg(Arg: 2, ArgExpr: StrideExpr);
17005 }
17006
17007 // Check stride argument.
17008 if (MatrixTy) {
17009 if (std::optional<llvm::APSInt> Value =
17010 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
17011 uint64_t Stride = Value->getZExtValue();
17012 if (Stride < MatrixTy->getNumRows()) {
17013 Diag(Loc: StrideExpr->getBeginLoc(),
17014 DiagID: diag::err_builtin_matrix_stride_too_small);
17015 ArgError = true;
17016 }
17017 }
17018 }
17019
17020 if (ArgError)
17021 return ExprError();
17022
17023 return CallResult;
17024}
17025
17026void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
17027 const NamedDecl *Callee) {
17028 // This warning does not make sense in code that has no runtime behavior.
17029 if (isUnevaluatedContext())
17030 return;
17031
17032 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17033
17034 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17035 return;
17036
17037 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17038 // all TCBs the callee is a part of.
17039 llvm::StringSet<> CalleeTCBs;
17040 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17041 CalleeTCBs.insert(key: A->getTCBName());
17042 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17043 CalleeTCBs.insert(key: A->getTCBName());
17044
17045 // Go through the TCBs the caller is a part of and emit warnings if Caller
17046 // is in a TCB that the Callee is not.
17047 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17048 StringRef CallerTCB = A->getTCBName();
17049 if (CalleeTCBs.count(Key: CallerTCB) == 0) {
17050 this->Diag(Loc: CallExprLoc, DiagID: diag::warn_tcb_enforcement_violation)
17051 << Callee << CallerTCB;
17052 }
17053 }
17054}
17055