1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CheckExprLifetime.h"
15#include "clang/AST/APValue.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTDiagnostic.h"
18#include "clang/AST/Attr.h"
19#include "clang/AST/AttrIterator.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
25#include "clang/AST/DeclarationName.h"
26#include "clang/AST/EvaluatedExprVisitor.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
30#include "clang/AST/FormatString.h"
31#include "clang/AST/IgnoreExpr.h"
32#include "clang/AST/NSAPI.h"
33#include "clang/AST/NonTrivialTypeVisitor.h"
34#include "clang/AST/OperationKinds.h"
35#include "clang/AST/RecordLayout.h"
36#include "clang/AST/Stmt.h"
37#include "clang/AST/TemplateBase.h"
38#include "clang/AST/TemplateName.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeBase.h"
41#include "clang/AST/TypeLoc.h"
42#include "clang/AST/UnresolvedSet.h"
43#include "clang/Basic/AddressSpaces.h"
44#include "clang/Basic/BuiltinTraits.h"
45#include "clang/Basic/Diagnostic.h"
46#include "clang/Basic/DiagnosticSema.h"
47#include "clang/Basic/IdentifierTable.h"
48#include "clang/Basic/LLVM.h"
49#include "clang/Basic/LangOptions.h"
50#include "clang/Basic/OpenCLOptions.h"
51#include "clang/Basic/OperatorKinds.h"
52#include "clang/Basic/PartialDiagnostic.h"
53#include "clang/Basic/SourceLocation.h"
54#include "clang/Basic/SourceManager.h"
55#include "clang/Basic/Specifiers.h"
56#include "clang/Basic/SyncScope.h"
57#include "clang/Basic/TargetInfo.h"
58#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
59#include "clang/Sema/Initialization.h"
60#include "clang/Sema/Lookup.h"
61#include "clang/Sema/Ownership.h"
62#include "clang/Sema/Scope.h"
63#include "clang/Sema/ScopeInfo.h"
64#include "clang/Sema/Sema.h"
65#include "clang/Sema/SemaAMDGPU.h"
66#include "clang/Sema/SemaARM.h"
67#include "clang/Sema/SemaBPF.h"
68#include "clang/Sema/SemaDirectX.h"
69#include "clang/Sema/SemaHLSL.h"
70#include "clang/Sema/SemaHexagon.h"
71#include "clang/Sema/SemaLoongArch.h"
72#include "clang/Sema/SemaMIPS.h"
73#include "clang/Sema/SemaNVPTX.h"
74#include "clang/Sema/SemaObjC.h"
75#include "clang/Sema/SemaOpenCL.h"
76#include "clang/Sema/SemaPPC.h"
77#include "clang/Sema/SemaRISCV.h"
78#include "clang/Sema/SemaSPIRV.h"
79#include "clang/Sema/SemaSYCL.h"
80#include "clang/Sema/SemaSystemZ.h"
81#include "clang/Sema/SemaWasm.h"
82#include "clang/Sema/SemaX86.h"
83#include "llvm/ADT/APFloat.h"
84#include "llvm/ADT/APInt.h"
85#include "llvm/ADT/APSInt.h"
86#include "llvm/ADT/ArrayRef.h"
87#include "llvm/ADT/DenseMap.h"
88#include "llvm/ADT/FoldingSet.h"
89#include "llvm/ADT/STLExtras.h"
90#include "llvm/ADT/STLForwardCompat.h"
91#include "llvm/ADT/SmallBitVector.h"
92#include "llvm/ADT/SmallPtrSet.h"
93#include "llvm/ADT/SmallString.h"
94#include "llvm/ADT/SmallVector.h"
95#include "llvm/ADT/StringExtras.h"
96#include "llvm/ADT/StringRef.h"
97#include "llvm/ADT/StringSet.h"
98#include "llvm/ADT/StringSwitch.h"
99#include "llvm/Support/AtomicOrdering.h"
100#include "llvm/Support/Compiler.h"
101#include "llvm/Support/ConvertUTF.h"
102#include "llvm/Support/ErrorHandling.h"
103#include "llvm/Support/Format.h"
104#include "llvm/Support/Locale.h"
105#include "llvm/Support/MathExtras.h"
106#include "llvm/Support/SaveAndRestore.h"
107#include "llvm/Support/raw_ostream.h"
108#include "llvm/TargetParser/RISCVTargetParser.h"
109#include "llvm/TargetParser/Triple.h"
110#include <algorithm>
111#include <cassert>
112#include <cctype>
113#include <cstddef>
114#include <cstdint>
115#include <functional>
116#include <limits>
117#include <optional>
118#include <string>
119#include <tuple>
120#include <utility>
121
122using namespace clang;
123using namespace sema;
124
125SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
126 unsigned ByteNo) const {
127 return SL->getLocationOfByte(ByteNo, SM: getSourceManager(), Features: LangOpts,
128 Target: Context.getTargetInfo());
129}
130
131static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A,
132 Sema::FormatArgumentPassingKind B) {
133 return (A << 8) | B;
134}
135
136bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) {
137 unsigned ArgCount = Call->getNumArgs();
138 if (ArgCount >= MinArgCount)
139 return false;
140
141 return Diag(Loc: Call->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args)
142 << 0 /*function call*/ << MinArgCount << ArgCount
143 << /*is non object*/ 0 << Call->getSourceRange();
144}
145
146bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) {
147 unsigned ArgCount = Call->getNumArgs();
148 if (ArgCount <= MaxArgCount)
149 return false;
150 return Diag(Loc: Call->getEndLoc(), DiagID: diag::err_typecheck_call_too_many_args_at_most)
151 << 0 /*function call*/ << MaxArgCount << ArgCount
152 << /*is non object*/ 0 << Call->getSourceRange();
153}
154
155bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount,
156 unsigned MaxArgCount) {
157 return checkArgCountAtLeast(Call, MinArgCount) ||
158 checkArgCountAtMost(Call, MaxArgCount);
159}
160
161bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) {
162 unsigned ArgCount = Call->getNumArgs();
163 if (ArgCount == DesiredArgCount)
164 return false;
165
166 if (checkArgCountAtLeast(Call, MinArgCount: DesiredArgCount))
167 return true;
168 assert(ArgCount > DesiredArgCount && "should have diagnosed this");
169
170 // Highlight all the excess arguments.
171 SourceRange Range(Call->getArg(Arg: DesiredArgCount)->getBeginLoc(),
172 Call->getArg(Arg: ArgCount - 1)->getEndLoc());
173
174 return Diag(Loc: Range.getBegin(), DiagID: diag::err_typecheck_call_too_many_args)
175 << 0 /*function call*/ << DesiredArgCount << ArgCount
176 << /*is non object*/ 0 << Range;
177}
178
179static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S) {
180 bool HasError = false;
181
182 for (const Expr *Arg : Call->arguments()) {
183 if (Arg->isValueDependent())
184 continue;
185
186 std::optional<std::string> ArgString = Arg->tryEvaluateString(Ctx&: S.Context);
187 int DiagMsgKind = -1;
188 // Arguments must be pointers to constant strings and cannot use '$'.
189 if (!ArgString.has_value())
190 DiagMsgKind = 0;
191 else if (ArgString->find(c: '$') != std::string::npos)
192 DiagMsgKind = 1;
193
194 if (DiagMsgKind >= 0) {
195 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_verbose_trap_arg)
196 << DiagMsgKind << Arg->getSourceRange();
197 HasError = true;
198 }
199 }
200
201 return !HasError;
202}
203
204bool Sema::convertArgumentToType(Expr *&Value, QualType Ty) {
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
209 InitializedEntity::InitializeParameter(Context, Type: Ty, Consumed: false);
210 ExprResult Result =
211 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Value);
212 if (Result.isInvalid())
213 return true;
214 Value = Result.get();
215 return false;
216}
217
218/// Check that the first argument to __builtin_annotation is an integer
219/// and the second argument is a non-wide string literal.
220static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) {
221 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
222 return true;
223
224 // First argument should be an integer.
225 Expr *ValArg = TheCall->getArg(Arg: 0);
226 QualType Ty = ValArg->getType();
227 if (!Ty->isIntegerType()) {
228 S.Diag(Loc: ValArg->getBeginLoc(), DiagID: diag::err_builtin_annotation_first_arg)
229 << ValArg->getSourceRange();
230 return true;
231 }
232
233 // Second argument should be a constant string.
234 Expr *StrArg = TheCall->getArg(Arg: 1)->IgnoreParenCasts();
235 StringLiteral *Literal = dyn_cast<StringLiteral>(Val: StrArg);
236 if (!Literal || !Literal->isOrdinary()) {
237 S.Diag(Loc: StrArg->getBeginLoc(), DiagID: diag::err_builtin_annotation_second_arg)
238 << StrArg->getSourceRange();
239 return true;
240 }
241
242 TheCall->setType(Ty);
243 return false;
244}
245
246static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
247 // We need at least one argument.
248 if (TheCall->getNumArgs() < 1) {
249 S.Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
250 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
251 << TheCall->getCallee()->getSourceRange();
252 return true;
253 }
254
255 // All arguments should be wide string literals.
256 for (Expr *Arg : TheCall->arguments()) {
257 auto *Literal = dyn_cast<StringLiteral>(Val: Arg->IgnoreParenCasts());
258 if (!Literal || !Literal->isWide()) {
259 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_msvc_annotation_wide_str)
260 << Arg->getSourceRange();
261 return true;
262 }
263 }
264
265 return false;
266}
267
268/// Check that the argument to __builtin_addressof is a glvalue, and set the
269/// result type to the corresponding pointer type.
270static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) {
271 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
272 return true;
273
274 ExprResult Arg(TheCall->getArg(Arg: 0));
275 QualType ResultType = S.CheckAddressOfOperand(Operand&: Arg, OpLoc: TheCall->getBeginLoc());
276 if (ResultType.isNull())
277 return true;
278
279 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
280 TheCall->setType(ResultType);
281 return false;
282}
283
284/// Check that the argument to __builtin_function_start is a function.
285static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) {
286 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
287 return true;
288
289 if (TheCall->getArg(Arg: 0)->containsErrors())
290 return true;
291
292 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
293 if (Arg.isInvalid())
294 return true;
295
296 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
297 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
298 Val: Arg.get()->getAsBuiltinConstantDeclRef(Context: S.getASTContext()));
299
300 if (!FD) {
301 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_function_start_invalid_type)
302 << TheCall->getSourceRange();
303 return true;
304 }
305
306 return !S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
307 Loc: TheCall->getBeginLoc());
308}
309
310/// Check the number of arguments and set the result type to
311/// the argument type.
312static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
313 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
314 return true;
315
316 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
317 return false;
318}
319
320/// Check that the value argument for __builtin_is_aligned(value, alignment) and
321/// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
322/// type (but not a function pointer) and that the alignment is a power-of-two.
323static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
324 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
325 return true;
326
327 clang::Expr *Source = TheCall->getArg(Arg: 0);
328 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
329
330 auto IsValidIntegerType = [](QualType Ty) {
331 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
332 };
333 QualType SrcTy = Source->getType();
334 // We should also be able to use it with arrays (but not functions!).
335 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
336 SrcTy = S.Context.getDecayedType(T: SrcTy);
337 }
338 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
339 SrcTy->isFunctionPointerType()) {
340 S.Diag(Loc: Source->getExprLoc(), DiagID: diag::err_typecheck_expect_scalar_operand)
341 << SrcTy;
342 if (SrcTy->isFloatingType())
343 S.Diag(Loc: Source->getExprLoc(), DiagID: diag::note_alignment_invalid_type);
344 else if (SrcTy->isMemberPointerType())
345 S.Diag(Loc: Source->getExprLoc(), DiagID: diag::note_alignment_invalid_member_pointer);
346 else if (SrcTy->isFunctionPointerType())
347 S.Diag(Loc: Source->getExprLoc(),
348 DiagID: diag::note_alignment_invalid_function_pointer);
349 return true;
350 }
351
352 clang::Expr *AlignOp = TheCall->getArg(Arg: 1);
353 if (!IsValidIntegerType(AlignOp->getType())) {
354 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_typecheck_expect_int)
355 << AlignOp->getType();
356 return true;
357 }
358 Expr::EvalResult AlignResult;
359 unsigned MaxAlignmentBits = S.Context.getIntWidth(T: SrcTy) - 1;
360 // We can't check validity of alignment if it is value dependent.
361 if (!AlignOp->isValueDependent() &&
362 AlignOp->EvaluateAsInt(Result&: AlignResult, Ctx: S.Context,
363 AllowSideEffects: Expr::SE_AllowSideEffects)) {
364 llvm::APSInt AlignValue = AlignResult.Val.getInt();
365 llvm::APSInt MaxValue(
366 llvm::APInt::getOneBitSet(numBits: MaxAlignmentBits + 1, BitNo: MaxAlignmentBits));
367 if (AlignValue < 1) {
368 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_too_small) << 1;
369 return true;
370 }
371 if (llvm::APSInt::compareValues(I1: AlignValue, I2: MaxValue) > 0) {
372 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_too_big)
373 << toString(I: MaxValue, Radix: 10);
374 return true;
375 }
376 if (!AlignValue.isPowerOf2()) {
377 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::err_alignment_not_power_of_two);
378 return true;
379 }
380 if (AlignValue == 1) {
381 S.Diag(Loc: AlignOp->getExprLoc(), DiagID: diag::warn_alignment_builtin_useless)
382 << IsBooleanAlignBuiltin;
383 }
384 }
385
386 ExprResult SrcArg = S.PerformCopyInitialization(
387 Entity: InitializedEntity::InitializeParameter(Context&: S.Context, Type: SrcTy, Consumed: false),
388 EqualLoc: SourceLocation(), Init: Source);
389 if (SrcArg.isInvalid())
390 return true;
391 TheCall->setArg(Arg: 0, ArgExpr: SrcArg.get());
392 ExprResult AlignArg =
393 S.PerformCopyInitialization(Entity: InitializedEntity::InitializeParameter(
394 Context&: S.Context, Type: AlignOp->getType(), Consumed: false),
395 EqualLoc: SourceLocation(), Init: AlignOp);
396 if (AlignArg.isInvalid())
397 return true;
398 TheCall->setArg(Arg: 1, ArgExpr: AlignArg.get());
399 // For align_up/align_down, the return type is the same as the (potentially
400 // decayed) argument type including qualifiers. For is_aligned(), the result
401 // is always bool.
402 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
403 return false;
404}
405
406static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) {
407 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
408 return true;
409
410 std::pair<unsigned, const char *> Builtins[] = {
411 { Builtin::BI__builtin_add_overflow, "ckd_add" },
412 { Builtin::BI__builtin_sub_overflow, "ckd_sub" },
413 { Builtin::BI__builtin_mul_overflow, "ckd_mul" },
414 };
415
416 bool CkdOperation = llvm::any_of(Range&: Builtins, P: [&](const std::pair<unsigned,
417 const char *> &P) {
418 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() &&
419 Lexer::getImmediateMacroName(Loc: TheCall->getExprLoc(),
420 SM: S.getSourceManager(), LangOpts: S.getLangOpts()) == P.second;
421 });
422
423 auto ValidCkdIntType = [](QualType QT) {
424 // A valid checked integer type is an integer type other than a plain char,
425 // bool, a bit-precise type, or an enumeration type.
426 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>())
427 return (BT->getKind() >= BuiltinType::Short &&
428 BT->getKind() <= BuiltinType::Int128) || (
429 BT->getKind() >= BuiltinType::UShort &&
430 BT->getKind() <= BuiltinType::UInt128) ||
431 BT->getKind() == BuiltinType::UChar ||
432 BT->getKind() == BuiltinType::SChar;
433 return false;
434 };
435
436 // First two arguments should be integers.
437 for (unsigned I = 0; I < 2; ++I) {
438 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: I));
439 if (Arg.isInvalid()) return true;
440 TheCall->setArg(Arg: I, ArgExpr: Arg.get());
441
442 QualType Ty = Arg.get()->getType();
443 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType();
444 if (!IsValid) {
445 S.Diag(Loc: Arg.get()->getBeginLoc(), DiagID: diag::err_overflow_builtin_must_be_int)
446 << CkdOperation << Ty << Arg.get()->getSourceRange();
447 return true;
448 }
449 }
450
451 // Third argument should be a pointer to a non-const integer.
452 // IRGen correctly handles volatile, restrict, and address spaces, and
453 // the other qualifiers aren't possible.
454 {
455 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 2));
456 if (Arg.isInvalid()) return true;
457 TheCall->setArg(Arg: 2, ArgExpr: Arg.get());
458
459 QualType Ty = Arg.get()->getType();
460 const auto *PtrTy = Ty->getAs<PointerType>();
461 if (!PtrTy ||
462 !PtrTy->getPointeeType()->isIntegerType() ||
463 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
464 PtrTy->getPointeeType().isConstQualified()) {
465 S.Diag(Loc: Arg.get()->getBeginLoc(),
466 DiagID: diag::err_overflow_builtin_must_be_ptr_int)
467 << CkdOperation << Ty << Arg.get()->getSourceRange();
468 return true;
469 }
470 }
471
472 // Disallow signed bit-precise integer args larger than 128 bits to mul
473 // function until we improve backend support.
474 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
475 for (unsigned I = 0; I < 3; ++I) {
476 const auto Arg = TheCall->getArg(Arg: I);
477 // Third argument will be a pointer.
478 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
479 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
480 S.getASTContext().getIntWidth(T: Ty) > 128)
481 return S.Diag(Loc: Arg->getBeginLoc(),
482 DiagID: diag::err_overflow_builtin_bit_int_max_size)
483 << 128;
484 }
485 }
486
487 return false;
488}
489
490namespace {
491struct BuiltinDumpStructGenerator {
492 Sema &S;
493 CallExpr *TheCall;
494 SourceLocation Loc = TheCall->getBeginLoc();
495 SmallVector<Expr *, 32> Actions;
496 DiagnosticErrorTrap ErrorTracker;
497 PrintingPolicy Policy;
498
499 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
500 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
501 Policy(S.Context.getPrintingPolicy()) {
502 Policy.AnonymousTagNameStyle =
503 llvm::to_underlying(E: PrintingPolicy::AnonymousTagMode::Plain);
504 }
505
506 Expr *makeOpaqueValueExpr(Expr *Inner) {
507 auto *OVE = new (S.Context)
508 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(),
509 Inner->getObjectKind(), Inner);
510 Actions.push_back(Elt: OVE);
511 return OVE;
512 }
513
514 Expr *getStringLiteral(llvm::StringRef Str) {
515 Expr *Lit = S.Context.getPredefinedStringLiteralFromCache(Key: Str);
516 // Wrap the literal in parentheses to attach a source location.
517 return new (S.Context) ParenExpr(Loc, Loc, Lit);
518 }
519
520 bool callPrintFunction(llvm::StringRef Format,
521 llvm::ArrayRef<Expr *> Exprs = {}) {
522 SmallVector<Expr *, 8> Args;
523 assert(TheCall->getNumArgs() >= 2);
524 Args.reserve(N: (TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size());
525 Args.assign(in_start: TheCall->arg_begin() + 2, in_end: TheCall->arg_end());
526 Args.push_back(Elt: getStringLiteral(Str: Format));
527 llvm::append_range(C&: Args, R&: Exprs);
528
529 // Register a note to explain why we're performing the call.
530 Sema::CodeSynthesisContext Ctx;
531 Ctx.Kind = Sema::CodeSynthesisContext::BuildingBuiltinDumpStructCall;
532 Ctx.PointOfInstantiation = Loc;
533 Ctx.CallArgs = Args.data();
534 Ctx.NumCallArgs = Args.size();
535 S.pushCodeSynthesisContext(Ctx);
536
537 ExprResult RealCall =
538 S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: TheCall->getArg(Arg: 1),
539 LParenLoc: TheCall->getBeginLoc(), ArgExprs: Args, RParenLoc: TheCall->getRParenLoc());
540
541 S.popCodeSynthesisContext();
542 if (!RealCall.isInvalid())
543 Actions.push_back(Elt: RealCall.get());
544 // Bail out if we've hit any unrecoverable errors, even if we managed
545 // to build the call.
546 return RealCall.isInvalid() || ErrorTracker.hasUnrecoverableErrorOccurred();
547 }
548
549 Expr *getIndentString(unsigned Depth) {
550 if (!Depth)
551 return nullptr;
552
553 llvm::SmallString<32> Indent;
554 Indent.resize(N: Depth * Policy.Indentation, NV: ' ');
555 return getStringLiteral(Str: Indent);
556 }
557
558 Expr *getTypeString(QualType T) {
559 return getStringLiteral(Str: T.getAsString(Policy));
560 }
561
562 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) {
563 llvm::raw_svector_ostream OS(Str);
564
565 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather
566 // than trying to print a single character.
567 if (auto *BT = T->getAs<BuiltinType>()) {
568 switch (BT->getKind()) {
569 case BuiltinType::Bool:
570 OS << "%d";
571 return true;
572 case BuiltinType::Char_U:
573 case BuiltinType::UChar:
574 OS << "%hhu";
575 return true;
576 case BuiltinType::Char_S:
577 case BuiltinType::SChar:
578 OS << "%hhd";
579 return true;
580 default:
581 break;
582 }
583 }
584
585 analyze_printf::PrintfSpecifier Specifier;
586 if (Specifier.fixType(QT: T, LangOpt: S.getLangOpts(), Ctx&: S.Context, /*IsObjCLiteral=*/false)) {
587 // We were able to guess how to format this.
588 if (Specifier.getConversionSpecifier().getKind() ==
589 analyze_printf::PrintfConversionSpecifier::sArg) {
590 // Wrap double-quotes around a '%s' specifier and limit its maximum
591 // length. Ideally we'd also somehow escape special characters in the
592 // contents but printf doesn't support that.
593 // FIXME: '%s' formatting is not safe in general.
594 OS << '"';
595 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
596 Specifier.toString(os&: OS);
597 OS << '"';
598 // FIXME: It would be nice to include a '...' if the string doesn't fit
599 // in the length limit.
600 } else {
601 Specifier.toString(os&: OS);
602 }
603 return true;
604 }
605
606 if (T->isPointerType()) {
607 // Format all pointers with '%p'.
608 OS << "%p";
609 return true;
610 }
611
612 return false;
613 }
614
615 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) {
616 Expr *IndentLit = getIndentString(Depth);
617 Expr *TypeLit = getTypeString(T: S.Context.getCanonicalTagType(TD: RD));
618 if (IndentLit ? callPrintFunction(Format: "%s%s", Exprs: {IndentLit, TypeLit})
619 : callPrintFunction(Format: "%s", Exprs: {TypeLit}))
620 return true;
621
622 return dumpRecordValue(RD, E, RecordIndent: IndentLit, Depth);
623 }
624
625 // Dump a record value. E should be a pointer or lvalue referring to an RD.
626 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent,
627 unsigned Depth) {
628 // FIXME: Decide what to do if RD is a union. At least we should probably
629 // turn off printing `const char*` members with `%s`, because that is very
630 // likely to crash if that's not the active member. Whatever we decide, we
631 // should document it.
632
633 // Build an OpaqueValueExpr so we can refer to E more than once without
634 // triggering re-evaluation.
635 Expr *RecordArg = makeOpaqueValueExpr(Inner: E);
636 bool RecordArgIsPtr = RecordArg->getType()->isPointerType();
637
638 if (callPrintFunction(Format: " {\n"))
639 return true;
640
641 // Dump each base class, regardless of whether they're aggregates.
642 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) {
643 for (const auto &Base : CXXRD->bases()) {
644 QualType BaseType =
645 RecordArgIsPtr ? S.Context.getPointerType(T: Base.getType())
646 : S.Context.getLValueReferenceType(T: Base.getType());
647 ExprResult BasePtr = S.BuildCStyleCastExpr(
648 LParenLoc: Loc, Ty: S.Context.getTrivialTypeSourceInfo(T: BaseType, Loc), RParenLoc: Loc,
649 Op: RecordArg);
650 if (BasePtr.isInvalid() ||
651 dumpUnnamedRecord(RD: Base.getType()->getAsRecordDecl(), E: BasePtr.get(),
652 Depth: Depth + 1))
653 return true;
654 }
655 }
656
657 Expr *FieldIndentArg = getIndentString(Depth: Depth + 1);
658
659 // Dump each field.
660 for (auto *D : RD->decls()) {
661 auto *IFD = dyn_cast<IndirectFieldDecl>(Val: D);
662 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(Val: D);
663 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
664 continue;
665
666 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s ");
667 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
668 getTypeString(T: FD->getType()),
669 getStringLiteral(Str: FD->getName())};
670
671 if (FD->isBitField()) {
672 Format += ": %zu ";
673 QualType SizeT = S.Context.getSizeType();
674 llvm::APInt BitWidth(S.Context.getIntWidth(T: SizeT),
675 FD->getBitWidthValue());
676 Args.push_back(Elt: IntegerLiteral::Create(C: S.Context, V: BitWidth, type: SizeT, l: Loc));
677 }
678
679 Format += "=";
680
681 ExprResult Field =
682 IFD ? S.BuildAnonymousStructUnionMemberReference(
683 SS: CXXScopeSpec(), nameLoc: Loc, indirectField: IFD,
684 FoundDecl: DeclAccessPair::make(D: IFD, AS: AS_public), baseObjectExpr: RecordArg, opLoc: Loc)
685 : S.BuildFieldReferenceExpr(
686 BaseExpr: RecordArg, IsArrow: RecordArgIsPtr, OpLoc: Loc, SS: CXXScopeSpec(), Field: FD,
687 FoundDecl: DeclAccessPair::make(D: FD, AS: AS_public),
688 MemberNameInfo: DeclarationNameInfo(FD->getDeclName(), Loc));
689 if (Field.isInvalid())
690 return true;
691
692 auto *InnerRD = FD->getType()->getAsRecordDecl();
693 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(Val: InnerRD);
694 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
695 // Recursively print the values of members of aggregate record type.
696 if (callPrintFunction(Format, Exprs: Args) ||
697 dumpRecordValue(RD: InnerRD, E: Field.get(), RecordIndent: FieldIndentArg, Depth: Depth + 1))
698 return true;
699 } else {
700 Format += " ";
701 if (appendFormatSpecifier(T: FD->getType(), Str&: Format)) {
702 // We know how to print this field.
703 Args.push_back(Elt: Field.get());
704 } else {
705 // We don't know how to print this field. Print out its address
706 // with a format specifier that a smart tool will be able to
707 // recognize and treat specially.
708 Format += "*%p";
709 ExprResult FieldAddr =
710 S.BuildUnaryOp(S: nullptr, OpLoc: Loc, Opc: UO_AddrOf, Input: Field.get());
711 if (FieldAddr.isInvalid())
712 return true;
713 Args.push_back(Elt: FieldAddr.get());
714 }
715 Format += "\n";
716 if (callPrintFunction(Format, Exprs: Args))
717 return true;
718 }
719 }
720
721 return RecordIndent ? callPrintFunction(Format: "%s}\n", Exprs: RecordIndent)
722 : callPrintFunction(Format: "}\n");
723 }
724
725 Expr *buildWrapper() {
726 auto *Wrapper = PseudoObjectExpr::Create(Context: S.Context, syntactic: TheCall, semantic: Actions,
727 resultIndex: PseudoObjectExpr::NoResult);
728 TheCall->setType(Wrapper->getType());
729 TheCall->setValueKind(Wrapper->getValueKind());
730 return Wrapper;
731 }
732};
733} // namespace
734
735static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall) {
736 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 2))
737 return ExprError();
738
739 ExprResult PtrArgResult = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
740 if (PtrArgResult.isInvalid())
741 return ExprError();
742 TheCall->setArg(Arg: 0, ArgExpr: PtrArgResult.get());
743
744 // First argument should be a pointer to a struct.
745 QualType PtrArgType = PtrArgResult.get()->getType();
746 if (!PtrArgType->isPointerType() ||
747 !PtrArgType->getPointeeType()->isRecordType()) {
748 S.Diag(Loc: PtrArgResult.get()->getBeginLoc(),
749 DiagID: diag::err_expected_struct_pointer_argument)
750 << 1 << TheCall->getDirectCallee() << PtrArgType;
751 return ExprError();
752 }
753 QualType Pointee = PtrArgType->getPointeeType();
754 const RecordDecl *RD = Pointee->getAsRecordDecl();
755 // Try to instantiate the class template as appropriate; otherwise, access to
756 // its data() may lead to a crash.
757 if (S.RequireCompleteType(Loc: PtrArgResult.get()->getBeginLoc(), T: Pointee,
758 DiagID: diag::err_incomplete_type))
759 return ExprError();
760 // Second argument is a callable, but we can't fully validate it until we try
761 // calling it.
762 QualType FnArgType = TheCall->getArg(Arg: 1)->getType();
763 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() &&
764 !FnArgType->isBlockPointerType() &&
765 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) {
766 auto *BT = FnArgType->getAs<BuiltinType>();
767 switch (BT ? BT->getKind() : BuiltinType::Void) {
768 case BuiltinType::Dependent:
769 case BuiltinType::Overload:
770 case BuiltinType::BoundMember:
771 case BuiltinType::PseudoObject:
772 case BuiltinType::UnknownAny:
773 case BuiltinType::BuiltinFn:
774 // This might be a callable.
775 break;
776
777 default:
778 S.Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
779 DiagID: diag::err_expected_callable_argument)
780 << 2 << TheCall->getDirectCallee() << FnArgType;
781 return ExprError();
782 }
783 }
784
785 BuiltinDumpStructGenerator Generator(S, TheCall);
786
787 // Wrap parentheses around the given pointer. This is not necessary for
788 // correct code generation, but it means that when we pretty-print the call
789 // arguments in our diagnostics we will produce '(&s)->n' instead of the
790 // incorrect '&s->n'.
791 Expr *PtrArg = PtrArgResult.get();
792 PtrArg = new (S.Context)
793 ParenExpr(PtrArg->getBeginLoc(),
794 S.getLocForEndOfToken(Loc: PtrArg->getEndLoc()), PtrArg);
795 if (Generator.dumpUnnamedRecord(RD, E: PtrArg, Depth: 0))
796 return ExprError();
797
798 return Generator.buildWrapper();
799}
800
801static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
802 if (S.checkArgCount(Call: BuiltinCall, DesiredArgCount: 2))
803 return true;
804
805 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
806 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
807 Expr *Call = BuiltinCall->getArg(Arg: 0);
808 Expr *Chain = BuiltinCall->getArg(Arg: 1);
809
810 if (Call->getStmtClass() != Stmt::CallExprClass) {
811 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_not_call)
812 << Call->getSourceRange();
813 return true;
814 }
815
816 auto CE = cast<CallExpr>(Val: Call);
817 if (CE->getCallee()->getType()->isBlockPointerType()) {
818 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_block_call)
819 << Call->getSourceRange();
820 return true;
821 }
822
823 const Decl *TargetDecl = CE->getCalleeDecl();
824 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: TargetDecl))
825 if (FD->getBuiltinID()) {
826 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_builtin_call)
827 << Call->getSourceRange();
828 return true;
829 }
830
831 if (isa<CXXPseudoDestructorExpr>(Val: CE->getCallee()->IgnoreParens())) {
832 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_first_argument_to_cwsc_pdtor_call)
833 << Call->getSourceRange();
834 return true;
835 }
836
837 ExprResult ChainResult = S.UsualUnaryConversions(E: Chain);
838 if (ChainResult.isInvalid())
839 return true;
840 if (!ChainResult.get()->getType()->isPointerType()) {
841 S.Diag(Loc: BuiltinLoc, DiagID: diag::err_second_argument_to_cwsc_not_pointer)
842 << Chain->getSourceRange();
843 return true;
844 }
845
846 QualType ReturnTy = CE->getCallReturnType(Ctx: S.Context);
847 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
848 QualType BuiltinTy = S.Context.getFunctionType(
849 ResultTy: ReturnTy, Args: ArgTys, EPI: FunctionProtoType::ExtProtoInfo());
850 QualType BuiltinPtrTy = S.Context.getPointerType(T: BuiltinTy);
851
852 Builtin =
853 S.ImpCastExprToType(E: Builtin, Type: BuiltinPtrTy, CK: CK_BuiltinFnToFnPtr).get();
854
855 BuiltinCall->setType(CE->getType());
856 BuiltinCall->setValueKind(CE->getValueKind());
857 BuiltinCall->setObjectKind(CE->getObjectKind());
858 BuiltinCall->setCallee(Builtin);
859 BuiltinCall->setArg(Arg: 1, ArgExpr: ChainResult.get());
860
861 return false;
862}
863
864namespace {
865
866class ScanfDiagnosticFormatHandler
867 : public analyze_format_string::FormatStringHandler {
868 // Accepts the argument index (relative to the first destination index) of the
869 // argument whose size we want.
870 using ComputeSizeFunction =
871 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>;
872
873 // Accepts the argument index (relative to the first destination index), the
874 // destination size, and the source size).
875 using DiagnoseFunction =
876 llvm::function_ref<void(unsigned, unsigned, unsigned)>;
877
878 ComputeSizeFunction ComputeSizeArgument;
879 DiagnoseFunction Diagnose;
880
881public:
882 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
883 DiagnoseFunction Diagnose)
884 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
885
886 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
887 const char *StartSpecifier,
888 unsigned specifierLen) override {
889 if (!FS.consumesDataArgument())
890 return true;
891
892 unsigned NulByte = 0;
893 switch ((FS.getConversionSpecifier().getKind())) {
894 default:
895 return true;
896 case analyze_format_string::ConversionSpecifier::sArg:
897 case analyze_format_string::ConversionSpecifier::ScanListArg:
898 NulByte = 1;
899 break;
900 case analyze_format_string::ConversionSpecifier::cArg:
901 break;
902 }
903
904 analyze_format_string::OptionalAmount FW = FS.getFieldWidth();
905 if (FW.getHowSpecified() !=
906 analyze_format_string::OptionalAmount::HowSpecified::Constant)
907 return true;
908
909 unsigned SourceSize = FW.getConstantAmount() + NulByte;
910
911 std::optional<llvm::APSInt> DestSizeAPS =
912 ComputeSizeArgument(FS.getArgIndex());
913 if (!DestSizeAPS)
914 return true;
915
916 unsigned DestSize = DestSizeAPS->getZExtValue();
917
918 if (DestSize < SourceSize)
919 Diagnose(FS.getArgIndex(), DestSize, SourceSize);
920
921 return true;
922 }
923};
924
925class EstimateSizeFormatHandler
926 : public analyze_format_string::FormatStringHandler {
927 size_t Size;
928 /// Whether the format string contains Linux kernel's format specifier
929 /// extension.
930 bool IsKernelCompatible = true;
931
932public:
933 EstimateSizeFormatHandler(StringRef Format)
934 : Size(std::min(a: Format.find(C: 0), b: Format.size()) +
935 1 /* null byte always written by sprintf */) {}
936
937 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
938 const char *, unsigned SpecifierLen,
939 const TargetInfo &) override {
940
941 const size_t FieldWidth = computeFieldWidth(FS);
942 const size_t Precision = computePrecision(FS);
943
944 // The actual format.
945 switch (FS.getConversionSpecifier().getKind()) {
946 // Just a char.
947 case analyze_format_string::ConversionSpecifier::cArg:
948 case analyze_format_string::ConversionSpecifier::CArg:
949 Size += std::max(a: FieldWidth, b: (size_t)1);
950 break;
951 // Just an integer.
952 case analyze_format_string::ConversionSpecifier::dArg:
953 case analyze_format_string::ConversionSpecifier::DArg:
954 case analyze_format_string::ConversionSpecifier::iArg:
955 case analyze_format_string::ConversionSpecifier::oArg:
956 case analyze_format_string::ConversionSpecifier::OArg:
957 case analyze_format_string::ConversionSpecifier::uArg:
958 case analyze_format_string::ConversionSpecifier::UArg:
959 case analyze_format_string::ConversionSpecifier::xArg:
960 case analyze_format_string::ConversionSpecifier::XArg:
961 Size += std::max(a: FieldWidth, b: Precision);
962 break;
963
964 // %g style conversion switches between %f or %e style dynamically.
965 // %g removes trailing zeros, and does not print decimal point if there are
966 // no digits that follow it. Thus %g can print a single digit.
967 // FIXME: If it is alternative form:
968 // For g and G conversions, trailing zeros are not removed from the result.
969 case analyze_format_string::ConversionSpecifier::gArg:
970 case analyze_format_string::ConversionSpecifier::GArg:
971 Size += 1;
972 break;
973
974 // Floating point number in the form '[+]ddd.ddd'.
975 case analyze_format_string::ConversionSpecifier::fArg:
976 case analyze_format_string::ConversionSpecifier::FArg:
977 Size += std::max(a: FieldWidth, b: 1 /* integer part */ +
978 (Precision ? 1 + Precision
979 : 0) /* period + decimal */);
980 break;
981
982 // Floating point number in the form '[-]d.ddde[+-]dd'.
983 case analyze_format_string::ConversionSpecifier::eArg:
984 case analyze_format_string::ConversionSpecifier::EArg:
985 Size +=
986 std::max(a: FieldWidth,
987 b: 1 /* integer part */ +
988 (Precision ? 1 + Precision : 0) /* period + decimal */ +
989 1 /* e or E letter */ + 2 /* exponent */);
990 break;
991
992 // Floating point number in the form '[-]0xh.hhhhp±dd'.
993 case analyze_format_string::ConversionSpecifier::aArg:
994 case analyze_format_string::ConversionSpecifier::AArg:
995 Size +=
996 std::max(a: FieldWidth,
997 b: 2 /* 0x */ + 1 /* integer part */ +
998 (Precision ? 1 + Precision : 0) /* period + decimal */ +
999 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
1000 break;
1001
1002 // Just a string.
1003 case analyze_format_string::ConversionSpecifier::sArg:
1004 case analyze_format_string::ConversionSpecifier::SArg:
1005 Size += FieldWidth;
1006 break;
1007
1008 // Just a pointer in the form '0xddd'.
1009 case analyze_format_string::ConversionSpecifier::pArg:
1010 // Linux kernel has its own extesion for `%p` specifier.
1011 // Kernel Document:
1012 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types
1013 IsKernelCompatible = false;
1014 Size += std::max(a: FieldWidth, b: 2 /* leading 0x */ + Precision);
1015 break;
1016
1017 // A plain percent.
1018 case analyze_format_string::ConversionSpecifier::PercentArg:
1019 Size += 1;
1020 break;
1021
1022 default:
1023 break;
1024 }
1025
1026 // If field width is specified, the sign/space is already accounted for
1027 // within the field width, so no additional size is needed.
1028 if ((FS.hasPlusPrefix() || FS.hasSpacePrefix()) && FieldWidth == 0)
1029 Size += 1;
1030
1031 if (FS.hasAlternativeForm()) {
1032 switch (FS.getConversionSpecifier().getKind()) {
1033 // For o conversion, it increases the precision, if and only if necessary,
1034 // to force the first digit of the result to be a zero
1035 // (if the value and precision are both 0, a single 0 is printed)
1036 case analyze_format_string::ConversionSpecifier::oArg:
1037 // For b conversion, a nonzero result has 0b prefixed to it.
1038 case analyze_format_string::ConversionSpecifier::bArg:
1039 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to
1040 // it.
1041 case analyze_format_string::ConversionSpecifier::xArg:
1042 case analyze_format_string::ConversionSpecifier::XArg:
1043 // Note: even when the prefix is added, if
1044 // (prefix_width <= FieldWidth - formatted_length) holds,
1045 // the prefix does not increase the format
1046 // size. e.g.(("%#3x", 0xf) is "0xf")
1047
1048 // If the result is zero, o, b, x, X adds nothing.
1049 break;
1050 // For a, A, e, E, f, F, g, and G conversions,
1051 // the result of converting a floating-point number always contains a
1052 // decimal-point
1053 case analyze_format_string::ConversionSpecifier::aArg:
1054 case analyze_format_string::ConversionSpecifier::AArg:
1055 case analyze_format_string::ConversionSpecifier::eArg:
1056 case analyze_format_string::ConversionSpecifier::EArg:
1057 case analyze_format_string::ConversionSpecifier::fArg:
1058 case analyze_format_string::ConversionSpecifier::FArg:
1059 case analyze_format_string::ConversionSpecifier::gArg:
1060 case analyze_format_string::ConversionSpecifier::GArg:
1061 Size += (Precision ? 0 : 1);
1062 break;
1063 // For other conversions, the behavior is undefined.
1064 default:
1065 break;
1066 }
1067 }
1068 assert(SpecifierLen <= Size && "no underflow");
1069 Size -= SpecifierLen;
1070 return true;
1071 }
1072
1073 size_t getSizeLowerBound() const { return Size; }
1074 bool isKernelCompatible() const { return IsKernelCompatible; }
1075
1076private:
1077 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
1078 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
1079 size_t FieldWidth = 0;
1080 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
1081 FieldWidth = FW.getConstantAmount();
1082 return FieldWidth;
1083 }
1084
1085 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
1086 const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
1087 size_t Precision = 0;
1088
1089 // See man 3 printf for default precision value based on the specifier.
1090 switch (FW.getHowSpecified()) {
1091 case analyze_format_string::OptionalAmount::NotSpecified:
1092 switch (FS.getConversionSpecifier().getKind()) {
1093 default:
1094 break;
1095 case analyze_format_string::ConversionSpecifier::dArg: // %d
1096 case analyze_format_string::ConversionSpecifier::DArg: // %D
1097 case analyze_format_string::ConversionSpecifier::iArg: // %i
1098 Precision = 1;
1099 break;
1100 case analyze_format_string::ConversionSpecifier::oArg: // %d
1101 case analyze_format_string::ConversionSpecifier::OArg: // %D
1102 case analyze_format_string::ConversionSpecifier::uArg: // %d
1103 case analyze_format_string::ConversionSpecifier::UArg: // %D
1104 case analyze_format_string::ConversionSpecifier::xArg: // %d
1105 case analyze_format_string::ConversionSpecifier::XArg: // %D
1106 Precision = 1;
1107 break;
1108 case analyze_format_string::ConversionSpecifier::fArg: // %f
1109 case analyze_format_string::ConversionSpecifier::FArg: // %F
1110 case analyze_format_string::ConversionSpecifier::eArg: // %e
1111 case analyze_format_string::ConversionSpecifier::EArg: // %E
1112 case analyze_format_string::ConversionSpecifier::gArg: // %g
1113 case analyze_format_string::ConversionSpecifier::GArg: // %G
1114 Precision = 6;
1115 break;
1116 case analyze_format_string::ConversionSpecifier::pArg: // %d
1117 Precision = 1;
1118 break;
1119 }
1120 break;
1121 case analyze_format_string::OptionalAmount::Constant:
1122 Precision = FW.getConstantAmount();
1123 break;
1124 default:
1125 break;
1126 }
1127 return Precision;
1128 }
1129};
1130
1131} // namespace
1132
1133static bool ProcessFormatStringLiteral(const Expr *FormatExpr,
1134 StringRef &FormatStrRef, size_t &StrLen,
1135 ASTContext &Context) {
1136 if (const auto *Format = dyn_cast<StringLiteral>(Val: FormatExpr);
1137 Format && (Format->isOrdinary() || Format->isUTF8())) {
1138 FormatStrRef = Format->getString();
1139 const ConstantArrayType *T =
1140 Context.getAsConstantArrayType(T: Format->getType());
1141 assert(T && "String literal not of constant array type!");
1142 size_t TypeSize = T->getZExtSize();
1143 // In case there's a null byte somewhere.
1144 StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: FormatStrRef.find(C: 0));
1145 return true;
1146 }
1147 return false;
1148}
1149
1150namespace {
1151/// Helper class for buffer overflow/overread checking in fortified functions.
1152class FortifiedBufferChecker {
1153public:
1154 FortifiedBufferChecker(Sema &S, FunctionDecl *FD, CallExpr *TheCall)
1155 : S(S), TheCall(TheCall), FD(FD),
1156 DABAttr(FD ? FD->getAttr<DiagnoseAsBuiltinAttr>() : nullptr) {
1157 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1158 SizeTypeWidth = TI.getTypeWidth(T: TI.getSizeType());
1159 }
1160
1161 std::optional<unsigned> TranslateIndex(unsigned Index) {
1162 // If we refer to a diagnose_as_builtin attribute, we need to change the
1163 // argument index to refer to the arguments of the called function. Unless
1164 // the index is out of bounds, which presumably means it's a variadic
1165 // function.
1166 unsigned NewIndex = Index;
1167 if (DABAttr) {
1168 unsigned DABIndices = DABAttr->argIndices_size();
1169 NewIndex = Index < DABIndices ? DABAttr->argIndices_begin()[Index]
1170 : Index - DABIndices + FD->getNumParams();
1171 }
1172 if (NewIndex >= TheCall->getNumArgs())
1173 return std::nullopt;
1174 return NewIndex;
1175 }
1176
1177 /// Evaluate the argument at Index as an integer constant while preserving
1178 /// its signedness, or return std::nullopt if it cannot be evaluated.
1179 std::optional<llvm::APSInt> EvaluateIntegerArgument(unsigned Index) {
1180 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1181 if (!IndexOptional)
1182 return std::nullopt;
1183 Expr::EvalResult Result;
1184 Expr *Arg = TheCall->getArg(Arg: *IndexOptional);
1185 if (!Arg->EvaluateAsInt(Result, Ctx: S.getASTContext()))
1186 return std::nullopt;
1187
1188 return Result.Val.getInt();
1189 }
1190
1191 std::optional<llvm::APSInt>
1192 ComputeExplicitObjectSizeArgument(unsigned Index) {
1193 std::optional<llvm::APSInt> Integer = EvaluateIntegerArgument(Index);
1194 if (!Integer)
1195 return std::nullopt;
1196 *Integer = Integer->extOrTrunc(width: SizeTypeWidth);
1197 Integer->setIsUnsigned(true);
1198 return Integer;
1199 }
1200
1201 std::optional<llvm::APSInt> ComputeSizeArgument(unsigned Index) {
1202 // If the parameter has a pass_object_size attribute, then we should use its
1203 // (potentially) more strict checking mode. Otherwise, conservatively assume
1204 // type 0.
1205 int BOSType = 0;
1206 // This check can fail for variadic functions.
1207 if (Index < FD->getNumParams()) {
1208 if (const auto *POS =
1209 FD->getParamDecl(i: Index)->getAttr<PassObjectSizeAttr>())
1210 BOSType = POS->getType();
1211 }
1212
1213 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1214 if (!IndexOptional)
1215 return std::nullopt;
1216
1217 const Expr *ObjArg = TheCall->getArg(Arg: *IndexOptional);
1218 if (std::optional<uint64_t> ObjSize =
1219 ObjArg->tryEvaluateObjectSize(Ctx: S.getASTContext(), Type: BOSType)) {
1220 // Get the object size in the target's size_t width.
1221 return llvm::APSInt::getUnsigned(X: *ObjSize).extOrTrunc(width: SizeTypeWidth);
1222 }
1223 return std::nullopt;
1224 }
1225
1226 std::optional<llvm::APSInt>
1227 ComputeExplicitObjectSizeArgumentProduct(unsigned LIndex, unsigned RIndex) {
1228 auto L = ComputeExplicitObjectSizeArgument(Index: LIndex);
1229 auto R = ComputeExplicitObjectSizeArgument(Index: RIndex);
1230 if (!L || !R)
1231 return std::nullopt;
1232
1233 unsigned W =
1234 2 * std::max(l: {L->getBitWidth(), R->getBitWidth(), SizeTypeWidth});
1235
1236 llvm::APSInt LE = L->extOrTrunc(width: W);
1237 llvm::APSInt RE = R->extOrTrunc(width: W);
1238
1239 return LE * RE;
1240 }
1241
1242 std::optional<llvm::APSInt> ComputeStrLenArgument(unsigned Index) {
1243 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1244 if (!IndexOptional)
1245 return std::nullopt;
1246 unsigned NewIndex = *IndexOptional;
1247
1248 const Expr *ObjArg = TheCall->getArg(Arg: NewIndex);
1249
1250 if (std::optional<uint64_t> Result =
1251 ObjArg->tryEvaluateStrLen(Ctx: S.getASTContext())) {
1252 // Add 1 for null byte.
1253 return llvm::APSInt::getUnsigned(X: *Result + 1).extOrTrunc(width: SizeTypeWidth);
1254 }
1255 return std::nullopt;
1256 }
1257
1258 unsigned getSizeTypeWidth() const { return SizeTypeWidth; }
1259
1260 unsigned getBuiltinID() const {
1261 const FunctionDecl *UseDecl = FD;
1262 if (DABAttr) {
1263 UseDecl = DABAttr->getFunction();
1264 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1265 }
1266 return UseDecl->getBuiltinID(/*ConsiderWrappers=*/ConsiderWrapperFunctions: true);
1267 }
1268
1269 /// Return function name after stripping __builtin_ and _chk affixes.
1270 std::string getFunctionName() const {
1271 unsigned ID = getBuiltinID();
1272 if (!ID) {
1273 // Use callee name directly if not a builtin.
1274 const FunctionDecl *Callee = TheCall->getDirectCallee();
1275 assert(Callee && "expected callee");
1276 return Callee->getName().str();
1277 }
1278 std::string Name = S.getASTContext().BuiltinInfo.getName(ID);
1279 StringRef Ref = Name;
1280 // Strip __builtin___*_chk or __builtin_ prefix.
1281 if (!(Ref.consume_front(Prefix: "__builtin___") && Ref.consume_back(Suffix: "_chk")))
1282 Ref.consume_front(Prefix: "__builtin_");
1283 assert(!Ref.empty() && "expected non-empty function name");
1284 return Ref.str();
1285 }
1286
1287 /// Check for source buffer overread in memory functions.
1288 void checkSourceOverread(unsigned SrcArgIdx, unsigned SizeArgIdx) {
1289 if (S.isConstantEvaluatedContext())
1290 return;
1291
1292 const Expr *SrcArg = TheCall->getArg(Arg: SrcArgIdx);
1293 const Expr *SizeArg = TheCall->getArg(Arg: SizeArgIdx);
1294 if (SrcArg->isInstantiationDependent() ||
1295 SizeArg->isInstantiationDependent())
1296 return;
1297
1298 std::optional<llvm::APSInt> CopyLen =
1299 ComputeExplicitObjectSizeArgument(Index: SizeArgIdx);
1300 std::optional<llvm::APSInt> SrcBufSize = ComputeSizeArgument(Index: SrcArgIdx);
1301
1302 if (!CopyLen || !SrcBufSize)
1303 return;
1304
1305 // Warn only if copy length exceeds source buffer size.
1306 if (llvm::APSInt::compareValues(I1: *CopyLen, I2: *SrcBufSize) <= 0)
1307 return;
1308
1309 S.DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1310 PD: S.PDiag(DiagID: diag::warn_stringop_overread)
1311 << getFunctionName() << CopyLen->getZExtValue()
1312 << SrcBufSize->getZExtValue());
1313 }
1314
1315private:
1316 Sema &S;
1317 CallExpr *TheCall;
1318 FunctionDecl *FD;
1319 const DiagnoseAsBuiltinAttr *DABAttr;
1320 unsigned SizeTypeWidth;
1321};
1322} // anonymous namespace
1323
1324void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1325 CallExpr *TheCall) {
1326 if (TheCall->isInstantiationDependent() || isConstantEvaluatedContext())
1327 return;
1328
1329 FortifiedBufferChecker Checker(*this, FD, TheCall);
1330
1331 unsigned BuiltinID = Checker.getBuiltinID();
1332 if (!BuiltinID)
1333 return;
1334
1335 unsigned SizeTypeWidth = Checker.getSizeTypeWidth();
1336
1337 std::optional<llvm::APSInt> AccessSize;
1338 std::optional<llvm::APSInt> BufferSize;
1339 unsigned DiagID = 0;
1340
1341 switch (BuiltinID) {
1342 default:
1343 return;
1344 case Builtin::BI__builtin_strcat:
1345 case Builtin::BIstrcat:
1346 case Builtin::BI__builtin_stpcpy:
1347 case Builtin::BIstpcpy:
1348 case Builtin::BI__builtin_strcpy:
1349 case Builtin::BIstrcpy: {
1350 DiagID = diag::warn_fortify_strlen_overflow;
1351 AccessSize = Checker.ComputeStrLenArgument(Index: 1);
1352 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1353 break;
1354 }
1355
1356 case Builtin::BI__builtin___strcat_chk:
1357 case Builtin::BI__builtin___stpcpy_chk:
1358 case Builtin::BI__builtin___strcpy_chk: {
1359 DiagID = diag::warn_fortify_strlen_overflow;
1360 AccessSize = Checker.ComputeStrLenArgument(Index: 1);
1361 BufferSize = Checker.ComputeExplicitObjectSizeArgument(Index: 2);
1362 break;
1363 }
1364
1365 case Builtin::BIscanf:
1366 case Builtin::BIfscanf:
1367 case Builtin::BIsscanf: {
1368 unsigned FormatIndex = 1;
1369 unsigned DataIndex = 2;
1370 if (BuiltinID == Builtin::BIscanf) {
1371 FormatIndex = 0;
1372 DataIndex = 1;
1373 }
1374
1375 const auto *FormatExpr =
1376 TheCall->getArg(Arg: FormatIndex)->IgnoreParenImpCasts();
1377
1378 StringRef FormatStrRef;
1379 size_t StrLen;
1380 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1381 return;
1382
1383 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1384 unsigned SourceSize) {
1385 DiagID = diag::warn_fortify_scanf_overflow;
1386 unsigned Index = ArgIndex + DataIndex;
1387 std::string FunctionName = Checker.getFunctionName();
1388 DiagRuntimeBehavior(Loc: TheCall->getArg(Arg: Index)->getBeginLoc(), Statement: TheCall,
1389 PD: PDiag(DiagID) << FunctionName << (Index + 1)
1390 << DestSize << SourceSize);
1391 };
1392
1393 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1394 return Checker.ComputeSizeArgument(Index: Index + DataIndex);
1395 };
1396 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1397 const char *FormatBytes = FormatStrRef.data();
1398 analyze_format_string::ParseScanfString(H, beg: FormatBytes,
1399 end: FormatBytes + StrLen, LO: getLangOpts(),
1400 Target: Context.getTargetInfo());
1401
1402 // Unlike the other cases, in this one we have already issued the diagnostic
1403 // here, so no need to continue (because unlike the other cases, here the
1404 // diagnostic refers to the argument number).
1405 return;
1406 }
1407
1408 case Builtin::BIsprintf:
1409 case Builtin::BI__builtin_sprintf:
1410 case Builtin::BI__builtin___sprintf_chk:
1411 case Builtin::BIvsprintf:
1412 case Builtin::BI__builtin_vsprintf:
1413 case Builtin::BI__builtin___vsprintf_chk: {
1414 bool IsChk = BuiltinID == Builtin::BI__builtin___sprintf_chk ||
1415 BuiltinID == Builtin::BI__builtin___vsprintf_chk;
1416 std::optional<unsigned> FormatIndex = Checker.TranslateIndex(Index: IsChk ? 3 : 1);
1417 if (!FormatIndex)
1418 return;
1419 const auto *FormatExpr =
1420 TheCall->getArg(Arg: *FormatIndex)->IgnoreParenImpCasts();
1421
1422 StringRef FormatStrRef;
1423 size_t StrLen;
1424 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1425 EstimateSizeFormatHandler H(FormatStrRef);
1426 const char *FormatBytes = FormatStrRef.data();
1427 if (!analyze_format_string::ParsePrintfString(
1428 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1429 Target: Context.getTargetInfo(), isFreeBSDKPrintf: false)) {
1430 DiagID = H.isKernelCompatible()
1431 ? diag::warn_format_overflow
1432 : diag::warn_format_overflow_non_kprintf;
1433 AccessSize = llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1434 .extOrTrunc(width: SizeTypeWidth);
1435 if (IsChk) {
1436 BufferSize = Checker.ComputeExplicitObjectSizeArgument(Index: 2);
1437 } else {
1438 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1439 }
1440 break;
1441 }
1442 }
1443 return;
1444 }
1445 case Builtin::BI__builtin___memcpy_chk:
1446 case Builtin::BI__builtin___memmove_chk:
1447 case Builtin::BI__builtin___memset_chk:
1448 case Builtin::BI__builtin___strlcat_chk:
1449 case Builtin::BI__builtin___strlcpy_chk:
1450 case Builtin::BI__builtin___strncat_chk:
1451 case Builtin::BI__builtin___strncpy_chk:
1452 case Builtin::BI__builtin___stpncpy_chk:
1453 case Builtin::BI__builtin___memccpy_chk:
1454 case Builtin::BI__builtin___mempcpy_chk: {
1455 DiagID = diag::warn_builtin_chk_overflow;
1456 AccessSize =
1457 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 2);
1458 BufferSize =
1459 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1460
1461 if (BuiltinID == Builtin::BI__builtin___memcpy_chk ||
1462 BuiltinID == Builtin::BI__builtin___memmove_chk ||
1463 BuiltinID == Builtin::BI__builtin___mempcpy_chk) {
1464 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1465 }
1466 break;
1467 }
1468
1469 case Builtin::BI__builtin___snprintf_chk:
1470 case Builtin::BI__builtin___vsnprintf_chk: {
1471 DiagID = diag::warn_builtin_chk_overflow;
1472 AccessSize = Checker.ComputeExplicitObjectSizeArgument(Index: 1);
1473 BufferSize = Checker.ComputeExplicitObjectSizeArgument(Index: 3);
1474 break;
1475 }
1476
1477 case Builtin::BIstrncat:
1478 case Builtin::BI__builtin_strncat:
1479 case Builtin::BIstrncpy:
1480 case Builtin::BI__builtin_strncpy:
1481 case Builtin::BIstpncpy:
1482 case Builtin::BI__builtin_stpncpy:
1483 case Builtin::BIstrlcat:
1484 case Builtin::BI__builtin_strlcat:
1485 case Builtin::BIstrlcpy:
1486 case Builtin::BI__builtin_strlcpy: {
1487 // Whether these functions overflow depends on the runtime strlen of the
1488 // string, not just the buffer size, so emitting the "always overflow"
1489 // diagnostic isn't quite right. We should still diagnose passing a buffer
1490 // size larger than the destination buffer though; this is a runtime abort
1491 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1492 DiagID = diag::warn_fortify_source_size_mismatch;
1493 AccessSize =
1494 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1495 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1496 break;
1497 }
1498
1499 case Builtin::BIrecv:
1500 case Builtin::BIrecvfrom: {
1501 unsigned ExpectedArgs = BuiltinID == Builtin::BIrecv ? 4 : 6;
1502 if (TheCall->getNumArgs() != ExpectedArgs ||
1503 !TheCall->getArg(Arg: 1)->getType()->isPointerType() ||
1504 !TheCall->getArg(Arg: 2)->getType()->isIntegerType())
1505 return;
1506 DiagID = diag::warn_fortify_source_size_mismatch;
1507 AccessSize = Checker.ComputeExplicitObjectSizeArgument(Index: 2);
1508 BufferSize = Checker.ComputeSizeArgument(Index: 1);
1509 break;
1510 }
1511
1512 case Builtin::BIpoll:
1513 case Builtin::BIppoll:
1514 case Builtin::BIppoll64: {
1515 unsigned ExpectedArgs = BuiltinID == Builtin::BIpoll ? 3 : 4;
1516 if (TheCall->getNumArgs() != ExpectedArgs ||
1517 !TheCall->getArg(Arg: 1)->getType()->isIntegerType())
1518 return;
1519 QualType PointeeTy = TheCall->getArg(Arg: 0)->getType()->getPointeeType();
1520 if (PointeeTy.isNull())
1521 return;
1522 const RecordDecl *RD = PointeeTy->getAsRecordDecl();
1523 if (!RD || !RD->getIdentifier() || RD->getName() != "pollfd")
1524 return;
1525 if (BuiltinID == Builtin::BIpoll) {
1526 if (!TheCall->getArg(Arg: 2)->getType()->isIntegerType())
1527 return;
1528 } else {
1529 QualType TmoPointeeTy = TheCall->getArg(Arg: 2)->getType()->getPointeeType();
1530 if (TmoPointeeTy.isNull())
1531 return;
1532 const RecordDecl *TmoRD = TmoPointeeTy->getAsRecordDecl();
1533 if (!TmoRD || !TmoRD->getIdentifier() || TmoRD->getName() != "timespec" ||
1534 !TheCall->getArg(Arg: 3)->getType()->isPointerType())
1535 return;
1536 }
1537 std::optional<CharUnits> ElemSize =
1538 Context.getTypeSizeInCharsIfKnown(Ty: PointeeTy);
1539 if (!ElemSize)
1540 return;
1541 std::optional<llvm::APSInt> Count =
1542 Checker.ComputeExplicitObjectSizeArgument(Index: 1);
1543 if (!Count)
1544 return;
1545 DiagID = diag::warn_fortify_source_size_mismatch;
1546 unsigned WideWidth = SizeTypeWidth * 2;
1547 AccessSize = Count->extOrTrunc(width: WideWidth) *
1548 llvm::APSInt(llvm::APInt(WideWidth, ElemSize->getQuantity()),
1549 /*isUnsigned=*/true);
1550 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1551 break;
1552 }
1553
1554 case Builtin::BIbzero:
1555 case Builtin::BI__builtin_bzero:
1556 case Builtin::BImemcpy:
1557 case Builtin::BI__builtin_memcpy:
1558 case Builtin::BImemmove:
1559 case Builtin::BI__builtin_memmove:
1560 case Builtin::BImemset:
1561 case Builtin::BI__builtin_memset:
1562 case Builtin::BImempcpy:
1563 case Builtin::BI__builtin_mempcpy: {
1564 DiagID = diag::warn_fortify_source_overflow;
1565 AccessSize =
1566 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1567 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1568
1569 // Buffer overread doesn't make sense for memset/bzero.
1570 if (BuiltinID != Builtin::BImemset &&
1571 BuiltinID != Builtin::BI__builtin_memset &&
1572 BuiltinID != Builtin::BIbzero &&
1573 BuiltinID != Builtin::BI__builtin_bzero) {
1574 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1575 }
1576 break;
1577 }
1578 case Builtin::BIbcopy:
1579 case Builtin::BI__builtin_bcopy: {
1580 DiagID = diag::warn_fortify_source_overflow;
1581 AccessSize =
1582 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1583 BufferSize = Checker.ComputeSizeArgument(Index: 1);
1584 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1585 break;
1586 }
1587 case Builtin::BIfread: {
1588 DiagID = diag::warn_fortify_source_overflow;
1589 AccessSize = Checker.ComputeExplicitObjectSizeArgumentProduct(LIndex: 1, RIndex: 2);
1590 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1591 break;
1592 }
1593 case Builtin::BIfwrite: {
1594 DiagID = diag::warn_fortify_source_overread;
1595 AccessSize = Checker.ComputeExplicitObjectSizeArgumentProduct(LIndex: 1, RIndex: 2);
1596 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1597 break;
1598 }
1599 case Builtin::BIfgets: {
1600 AccessSize = Checker.EvaluateIntegerArgument(Index: 1);
1601
1602 if (AccessSize && AccessSize->isNegative()) {
1603 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1604 PD: PDiag(DiagID: diag::warn_fortify_source_negative_size)
1605 << Checker.getFunctionName());
1606 return;
1607 }
1608
1609 DiagID = diag::warn_fortify_source_size_mismatch;
1610 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1611 break;
1612 }
1613 // memchr(buf, val, size)
1614 case Builtin::BImemchr:
1615 case Builtin::BI__builtin_memchr: {
1616 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1617 return;
1618 }
1619
1620 // memcmp/bcmp(buf0, buf1, size)
1621 // Two checks since each buffer is read
1622 case Builtin::BImemcmp:
1623 case Builtin::BI__builtin_memcmp:
1624 case Builtin::BIbcmp:
1625 case Builtin::BI__builtin_bcmp: {
1626 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1627 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1628 return;
1629 }
1630 case Builtin::BIsnprintf:
1631 case Builtin::BI__builtin_snprintf:
1632 case Builtin::BIvsnprintf:
1633 case Builtin::BI__builtin_vsnprintf: {
1634 DiagID = diag::warn_fortify_source_size_mismatch;
1635 AccessSize = Checker.ComputeExplicitObjectSizeArgument(Index: 1);
1636 const auto *FormatExpr = TheCall->getArg(Arg: 2)->IgnoreParenImpCasts();
1637 StringRef FormatStrRef;
1638 size_t StrLen;
1639 if (AccessSize &&
1640 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1641 EstimateSizeFormatHandler H(FormatStrRef);
1642 const char *FormatBytes = FormatStrRef.data();
1643 if (!analyze_format_string::ParsePrintfString(
1644 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1645 Target: Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1646 llvm::APSInt FormatSize =
1647 llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1648 .extOrTrunc(width: SizeTypeWidth);
1649 if (FormatSize > *AccessSize && *AccessSize != 0) {
1650 unsigned TruncationDiagID =
1651 H.isKernelCompatible() ? diag::warn_format_truncation
1652 : diag::warn_format_truncation_non_kprintf;
1653 SmallString<16> SpecifiedSizeStr;
1654 SmallString<16> FormatSizeStr;
1655 AccessSize->toString(Str&: SpecifiedSizeStr, /*Radix=*/10);
1656 FormatSize.toString(Str&: FormatSizeStr, /*Radix=*/10);
1657 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1658 PD: PDiag(DiagID: TruncationDiagID)
1659 << Checker.getFunctionName()
1660 << SpecifiedSizeStr << FormatSizeStr);
1661 }
1662 }
1663 }
1664 BufferSize = Checker.ComputeSizeArgument(Index: 0);
1665 const Expr *LenArg = TheCall->getArg(Arg: 1)->IgnoreCasts();
1666 const Expr *Dest = TheCall->getArg(Arg: 0)->IgnoreCasts();
1667 IdentifierInfo *FnInfo = FD->getIdentifier();
1668 CheckSizeofMemaccessArgument(SizeOfArg: LenArg, Dest, FnName: FnInfo);
1669 }
1670 }
1671
1672 if (!AccessSize || !BufferSize ||
1673 llvm::APSInt::compareValues(I1: *AccessSize, I2: *BufferSize) <= 0)
1674 return;
1675
1676 std::string FunctionName = Checker.getFunctionName();
1677
1678 SmallString<16> BufferSizeStr;
1679 SmallString<16> AccessSizeStr;
1680 BufferSize->toString(Str&: BufferSizeStr, /*Radix=*/10);
1681 AccessSize->toString(Str&: AccessSizeStr, /*Radix=*/10);
1682 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1683 PD: PDiag(DiagID)
1684 << FunctionName << BufferSizeStr << AccessSizeStr);
1685}
1686
1687void Sema::checkFortifiedLibcArgument(FunctionDecl *FD, CallExpr *TheCall) {
1688 if (TheCall->isValueDependent() || TheCall->isTypeDependent())
1689 return;
1690
1691 // Recognize the libc function by builtin identity rather than by name and
1692 // system-header origin. umask is a LibBuiltin marked IgnoreSignature, so the
1693 // builtin id is attached to any file-scope, C-linkage declaration of umask
1694 // regardless of the libc's mode_t spelling -- including a hand-written
1695 // forward declaration without <sys/stat.h>. A static/local lookalike or a
1696 // C++ (non-extern-"C") declaration keeps a zero builtin id and is ignored.
1697 if (FD->getBuiltinID() != Builtin::BIumask)
1698 return;
1699
1700 // umask(mode_t): warn when the constant-evaluated argument has bits set
1701 // outside the file-permission mask (0777). Those bits are ignored.
1702 if (TheCall->getNumArgs() != 1)
1703 return;
1704 Expr *Arg = TheCall->getArg(Arg: 0);
1705 if (!Arg->getType()->isIntegerType())
1706 return;
1707 Expr::EvalResult R;
1708 if (!Arg->EvaluateAsInt(Result&: R, Ctx: getASTContext()))
1709 return;
1710 // Operate on the raw two's-complement bit pattern so that negative literals
1711 // (which convert to large unsigned mode_t values) are caught.
1712 llvm::APInt RawValue = R.Val.getInt();
1713 llvm::APInt Mask(RawValue.getBitWidth(), 0777);
1714 llvm::APInt Extra = RawValue & ~Mask;
1715 if (Extra == 0)
1716 return;
1717 SmallString<16> ExtraStr;
1718 Extra.toString(Str&: ExtraStr, /*Radix=*/8, /*Signed=*/false);
1719 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fortify_umask_unused_bits)
1720 << ExtraStr;
1721}
1722
1723static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1724 Scope::ScopeFlags NeededScopeFlags,
1725 unsigned DiagID) {
1726 // Scopes aren't available during instantiation. Fortunately, builtin
1727 // functions cannot be template args so they cannot be formed through template
1728 // instantiation. Therefore checking once during the parse is sufficient.
1729 if (SemaRef.inTemplateInstantiation())
1730 return false;
1731
1732 Scope *S = SemaRef.getCurScope();
1733 while (S && !S->isSEHExceptScope())
1734 S = S->getParent();
1735 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1736 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
1737 SemaRef.Diag(Loc: TheCall->getExprLoc(), DiagID)
1738 << DRE->getDecl()->getIdentifier();
1739 return true;
1740 }
1741
1742 return false;
1743}
1744
1745// In OpenCL, __builtin_alloca_* should return a pointer to address space
1746// that corresponds to the stack address space i.e private address space.
1747static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1748 QualType RT = TheCall->getType();
1749 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1750 "__builtin_alloca has invalid address space");
1751
1752 RT = RT->getPointeeType();
1753 RT = S.Context.getAddrSpaceQualType(T: RT, AddressSpace: LangAS::opencl_private);
1754 TheCall->setType(S.Context.getPointerType(T: RT));
1755}
1756
1757static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1758 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 1))
1759 return true;
1760
1761 for (Expr *Arg : TheCall->arguments()) {
1762 // If argument is dependent on a template parameter, we can't resolve now.
1763 if (Arg->isTypeDependent() || Arg->isValueDependent())
1764 continue;
1765 // Reject void types.
1766 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1767 if (ArgTy->isVoidType())
1768 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_param_with_void_type);
1769 }
1770
1771 TheCall->setType(S.Context.getSizeType());
1772 return false;
1773}
1774
1775namespace {
1776enum PointerAuthOpKind {
1777 PAO_Strip,
1778 PAO_Sign,
1779 PAO_Auth,
1780 PAO_SignGeneric,
1781 PAO_Discriminator,
1782 PAO_BlendPointer,
1783 PAO_BlendInteger,
1784 PAO_BlendPC
1785};
1786}
1787
1788bool Sema::checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range) {
1789 if (getLangOpts().PointerAuthIntrinsics)
1790 return false;
1791
1792 Diag(Loc, DiagID: diag::err_ptrauth_disabled) << Range;
1793 return true;
1794}
1795
1796static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1797 return S.checkPointerAuthEnabled(Loc: E->getExprLoc(), Range: E->getSourceRange());
1798}
1799
1800static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1801 // Convert it to type 'int'.
1802 if (S.convertArgumentToType(Value&: Arg, Ty: S.Context.IntTy))
1803 return true;
1804
1805 // Value-dependent expressions are okay; wait for template instantiation.
1806 if (Arg->isValueDependent())
1807 return false;
1808
1809 unsigned KeyValue;
1810 return S.checkConstantPointerAuthKey(keyExpr: Arg, key&: KeyValue);
1811}
1812
1813bool Sema::checkConstantPointerAuthKey(Expr *Arg, unsigned &Result) {
1814 // Attempt to constant-evaluate the expression.
1815 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Ctx: Context);
1816 if (!KeyValue) {
1817 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_expr_not_ice)
1818 << 0 << Arg->getSourceRange();
1819 return true;
1820 }
1821
1822 // Ask the target to validate the key parameter.
1823 if (!Context.getTargetInfo().validatePointerAuthKey(value: *KeyValue)) {
1824 llvm::SmallString<32> Value;
1825 {
1826 llvm::raw_svector_ostream Str(Value);
1827 Str << *KeyValue;
1828 }
1829
1830 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_invalid_key)
1831 << Value << Arg->getSourceRange();
1832 return true;
1833 }
1834
1835 Result = KeyValue->getZExtValue();
1836 return false;
1837}
1838
1839bool Sema::checkPointerAuthDiscriminatorArg(Expr *Arg,
1840 PointerAuthDiscArgKind Kind,
1841 unsigned &IntVal) {
1842 if (!Arg) {
1843 IntVal = 0;
1844 return true;
1845 }
1846
1847 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
1848 if (!Result) {
1849 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_arg_not_ice);
1850 return false;
1851 }
1852
1853 unsigned Max;
1854 bool IsAddrDiscArg = false;
1855
1856 switch (Kind) {
1857 case PointerAuthDiscArgKind::Addr:
1858 Max = 1;
1859 IsAddrDiscArg = true;
1860 break;
1861 case PointerAuthDiscArgKind::Extra:
1862 Max = PointerAuthQualifier::MaxDiscriminator;
1863 break;
1864 };
1865
1866 if (*Result < 0 || *Result > Max) {
1867 if (IsAddrDiscArg)
1868 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_address_discrimination_invalid)
1869 << Result->getExtValue();
1870 else
1871 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_extra_discriminator_invalid)
1872 << Result->getExtValue() << Max;
1873
1874 return false;
1875 };
1876
1877 IntVal = Result->getZExtValue();
1878 return true;
1879}
1880
1881static std::pair<const ValueDecl *, CharUnits>
1882findConstantBaseAndOffset(Sema &S, Expr *E) {
1883 // Must evaluate as a pointer.
1884 Expr::EvalResult Result;
1885 if (!E->EvaluateAsRValue(Result, Ctx: S.Context) || !Result.Val.isLValue())
1886 return {nullptr, CharUnits()};
1887
1888 const auto *BaseDecl =
1889 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1890 if (!BaseDecl)
1891 return {nullptr, CharUnits()};
1892
1893 return {BaseDecl, Result.Val.getLValueOffset()};
1894}
1895
1896static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1897 bool RequireConstant = false) {
1898 if (Arg->hasPlaceholderType()) {
1899 ExprResult R = S.CheckPlaceholderExpr(E: Arg);
1900 if (R.isInvalid())
1901 return true;
1902 Arg = R.get();
1903 }
1904
1905 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1906 return OpKind != PAO_BlendInteger;
1907 };
1908 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1909 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1910 OpKind == PAO_SignGeneric || OpKind == PAO_BlendPC;
1911 };
1912
1913 // Require the value to have the right range of type.
1914 QualType ExpectedTy;
1915 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1916 ExpectedTy = Arg->getType().getUnqualifiedType();
1917 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1918 ExpectedTy = S.Context.VoidPtrTy;
1919 } else if (AllowsInteger(OpKind) &&
1920 Arg->getType()->isIntegralOrUnscopedEnumerationType()) {
1921 ExpectedTy = S.Context.getUIntPtrType();
1922
1923 } else {
1924 // Diagnose the failures.
1925 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_value_bad_type)
1926 << unsigned(OpKind == PAO_Discriminator ? 1
1927 : OpKind == PAO_BlendPointer ? 2
1928 : OpKind == PAO_BlendInteger ? 3
1929 : OpKind == PAO_BlendPC ? 4
1930 : 0)
1931 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1932 << Arg->getType() << Arg->getSourceRange();
1933 return true;
1934 }
1935
1936 // Convert to that type. This should just be an lvalue-to-rvalue
1937 // conversion.
1938 if (S.convertArgumentToType(Value&: Arg, Ty: ExpectedTy))
1939 return true;
1940
1941 if (!RequireConstant) {
1942 // Warn about null pointers for non-generic sign and auth operations.
1943 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1944 Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNull)) {
1945 S.Diag(Loc: Arg->getExprLoc(), DiagID: OpKind == PAO_Sign
1946 ? diag::warn_ptrauth_sign_null_pointer
1947 : diag::warn_ptrauth_auth_null_pointer)
1948 << Arg->getSourceRange();
1949 }
1950
1951 return false;
1952 }
1953
1954 // Perform special checking on the arguments to ptrauth_sign_constant.
1955
1956 // The main argument.
1957 if (OpKind == PAO_Sign) {
1958 // Require the value we're signing to have a special form.
1959 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Arg);
1960 bool Invalid;
1961
1962 // Must be rooted in a declaration reference.
1963 if (!BaseDecl)
1964 Invalid = true;
1965
1966 // If it's a function declaration, we can't have an offset.
1967 else if (isa<FunctionDecl>(Val: BaseDecl))
1968 Invalid = !Offset.isZero();
1969
1970 // Otherwise we're fine.
1971 else
1972 Invalid = false;
1973
1974 if (Invalid)
1975 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_pointer);
1976 return Invalid;
1977 }
1978
1979 // The discriminator argument.
1980 assert(OpKind == PAO_Discriminator);
1981
1982 // Must be a pointer or integer or blend thereof.
1983 Expr *Pointer = nullptr;
1984 Expr *Integer = nullptr;
1985 if (auto *Call = dyn_cast<CallExpr>(Val: Arg->IgnoreParens())) {
1986 if (Call->getBuiltinCallee() ==
1987 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1988 Pointer = Call->getArg(Arg: 0);
1989 Integer = Call->getArg(Arg: 1);
1990 }
1991 }
1992 if (!Pointer && !Integer) {
1993 if (Arg->getType()->isPointerType())
1994 Pointer = Arg;
1995 else
1996 Integer = Arg;
1997 }
1998
1999 // Check the pointer.
2000 bool Invalid = false;
2001 if (Pointer) {
2002 assert(Pointer->getType()->isPointerType());
2003
2004 // TODO: if we're initializing a global, check that the address is
2005 // somehow related to what we're initializing. This probably will
2006 // never really be feasible and we'll have to catch it at link-time.
2007 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Pointer);
2008 if (!BaseDecl || !isa<VarDecl>(Val: BaseDecl))
2009 Invalid = true;
2010 }
2011
2012 // Check the integer.
2013 if (Integer) {
2014 assert(Integer->getType()->isIntegerType());
2015 if (!Integer->isEvaluatable(Ctx: S.Context))
2016 Invalid = true;
2017 }
2018
2019 if (Invalid)
2020 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_discriminator);
2021 return Invalid;
2022}
2023
2024static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call) {
2025 if (S.checkArgCount(Call, DesiredArgCount: 2))
2026 return ExprError();
2027 if (checkPointerAuthEnabled(S, E: Call))
2028 return ExprError();
2029 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Strip) ||
2030 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]))
2031 return ExprError();
2032
2033 Call->setType(Call->getArgs()[0]->getType());
2034 return Call;
2035}
2036
2037static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call) {
2038 if (S.checkArgCount(Call, DesiredArgCount: 2))
2039 return ExprError();
2040 if (checkPointerAuthEnabled(S, E: Call))
2041 return ExprError();
2042 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_BlendPointer) ||
2043 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_BlendInteger))
2044 return ExprError();
2045
2046 Call->setType(S.Context.getUIntPtrType());
2047 return Call;
2048}
2049
2050static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call) {
2051 if (S.checkArgCount(Call, DesiredArgCount: 2))
2052 return ExprError();
2053 if (checkPointerAuthEnabled(S, E: Call))
2054 return ExprError();
2055 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_SignGeneric) ||
2056 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_Discriminator))
2057 return ExprError();
2058
2059 Call->setType(S.Context.getUIntPtrType());
2060 return Call;
2061}
2062
2063static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call,
2064 PointerAuthOpKind OpKind,
2065 bool RequireConstant) {
2066 if (S.checkArgCount(Call, DesiredArgCount: 3))
2067 return ExprError();
2068 if (checkPointerAuthEnabled(S, E: Call))
2069 return ExprError();
2070 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind, RequireConstant) ||
2071 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
2072 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator,
2073 RequireConstant))
2074 return ExprError();
2075
2076 Call->setType(Call->getArgs()[0]->getType());
2077 return Call;
2078}
2079
2080static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call) {
2081 if (S.checkArgCount(Call, DesiredArgCount: 5))
2082 return ExprError();
2083 if (checkPointerAuthEnabled(S, E: Call))
2084 return ExprError();
2085 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
2086 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
2087 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
2088 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
2089 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator))
2090 return ExprError();
2091
2092 Call->setType(Call->getArgs()[0]->getType());
2093 return Call;
2094}
2095
2096static ExprResult PointerAuthAuthWithPCAndResign(Sema &S, CallExpr *Call) {
2097 if (S.checkArgCount(Call, DesiredArgCount: 6))
2098 return ExprError();
2099 if (checkPointerAuthEnabled(S, E: Call))
2100 return ExprError();
2101 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
2102 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
2103 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
2104 checkPointerAuthValue(S, Arg&: Call->getArgs()[3], OpKind: PAO_BlendPC) ||
2105 checkPointerAuthKey(S, Arg&: Call->getArgs()[4]) ||
2106 checkPointerAuthValue(S, Arg&: Call->getArgs()[5], OpKind: PAO_Discriminator))
2107 return ExprError();
2108
2109 // Validate that the oldKey is IA or IB, not DA or DB.
2110 // This enforces the constraint that auth_with_pc_and_resign only supports
2111 // IA/IB keys for authentication, as only those keys support the PC-based
2112 // signing instructions (paciasppc/pacibsppc).
2113 unsigned OldKey = 0;
2114 if (!S.checkConstantPointerAuthKey(Arg: Call->getArgs()[1], Result&: OldKey)) {
2115 using AK = PointerAuthSchema::ARM8_3Key;
2116 if (OldKey != static_cast<unsigned>(AK::ASIA) &&
2117 OldKey != static_cast<unsigned>(AK::ASIB)) {
2118 S.Diag(Loc: Call->getArgs()[1]->getExprLoc(),
2119 DiagID: diag::err_ptrauth_auth_with_pc_and_resign_invalid_key)
2120 << OldKey << Call->getArgs()[1]->getSourceRange();
2121 return ExprError();
2122 }
2123 }
2124
2125 Call->setType(Call->getArgs()[0]->getType());
2126 return Call;
2127}
2128
2129static ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call) {
2130 if (S.checkArgCount(Call, DesiredArgCount: 6))
2131 return ExprError();
2132 if (checkPointerAuthEnabled(S, E: Call))
2133 return ExprError();
2134 const Expr *AddendExpr = Call->getArg(Arg: 5);
2135 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(Ctx: S.Context);
2136 if (!AddendIsConstInt) {
2137 const Expr *Arg = Call->getArg(Arg: 5)->IgnoreParenImpCasts();
2138 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreParenCasts());
2139 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
2140 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_constant_integer_last_arg_type)
2141 << FDecl->getDeclName() << Arg->getSourceRange();
2142 }
2143 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
2144 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
2145 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
2146 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
2147 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator) ||
2148 !AddendIsConstInt)
2149 return ExprError();
2150
2151 Call->setType(Call->getArgs()[0]->getType());
2152 return Call;
2153}
2154
2155static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call) {
2156 if (checkPointerAuthEnabled(S, E: Call))
2157 return ExprError();
2158
2159 // We've already performed normal call type-checking.
2160 const Expr *Arg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
2161
2162 // Operand must be an ordinary or UTF-8 string literal.
2163 const auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
2164 if (!Literal || Literal->getCharByteWidth() != 1) {
2165 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_string_not_literal)
2166 << (Literal ? 1 : 0) << Arg->getSourceRange();
2167 return ExprError();
2168 }
2169
2170 return Call;
2171}
2172
2173static ExprResult GetVTablePointer(Sema &S, CallExpr *Call) {
2174 if (S.checkArgCount(Call, DesiredArgCount: 1))
2175 return ExprError();
2176 Expr *FirstArg = Call->getArg(Arg: 0);
2177 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(E: FirstArg);
2178 if (FirstValue.isInvalid())
2179 return ExprError();
2180 Call->setArg(Arg: 0, ArgExpr: FirstValue.get());
2181 QualType FirstArgType = FirstArg->getType();
2182 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
2183 FirstArgType = S.Context.getDecayedType(T: FirstArgType);
2184
2185 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
2186 if (!FirstArgRecord) {
2187 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
2188 << /*isPolymorphic=*/0 << FirstArgType;
2189 return ExprError();
2190 }
2191 if (S.RequireCompleteType(
2192 Loc: FirstArg->getBeginLoc(), T: FirstArgType->getPointeeType(),
2193 DiagID: diag::err_get_vtable_pointer_requires_complete_type)) {
2194 return ExprError();
2195 }
2196
2197 if (!FirstArgRecord->isPolymorphic()) {
2198 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
2199 << /*isPolymorphic=*/1 << FirstArgRecord;
2200 return ExprError();
2201 }
2202 QualType ReturnType = S.Context.getPointerType(T: S.Context.VoidTy.withConst());
2203 Call->setType(ReturnType);
2204 return Call;
2205}
2206
2207static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) {
2208 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2209 return ExprError();
2210
2211 // Compute __builtin_launder's parameter type from the argument.
2212 // The parameter type is:
2213 // * The type of the argument if it's not an array or function type,
2214 // Otherwise,
2215 // * The decayed argument type.
2216 QualType ParamTy = [&]() {
2217 QualType ArgTy = TheCall->getArg(Arg: 0)->getType();
2218 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
2219 return S.Context.getPointerType(T: Ty->getElementType());
2220 if (ArgTy->isFunctionType()) {
2221 return S.Context.getPointerType(T: ArgTy);
2222 }
2223 return ArgTy;
2224 }();
2225
2226 TheCall->setType(ParamTy);
2227
2228 auto DiagSelect = [&]() -> std::optional<unsigned> {
2229 if (!ParamTy->isPointerType())
2230 return 0;
2231 if (ParamTy->isFunctionPointerType())
2232 return 1;
2233 if (ParamTy->isVoidPointerType())
2234 return 2;
2235 return std::optional<unsigned>{};
2236 }();
2237 if (DiagSelect) {
2238 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_launder_invalid_arg)
2239 << *DiagSelect << TheCall->getSourceRange();
2240 return ExprError();
2241 }
2242
2243 // We either have an incomplete class type, or we have a class template
2244 // whose instantiation has not been forced. Example:
2245 //
2246 // template <class T> struct Foo { T value; };
2247 // Foo<int> *p = nullptr;
2248 // auto *d = __builtin_launder(p);
2249 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T: ParamTy->getPointeeType(),
2250 DiagID: diag::err_incomplete_type))
2251 return ExprError();
2252
2253 assert(ParamTy->getPointeeType()->isObjectType() &&
2254 "Unhandled non-object pointer case");
2255
2256 InitializedEntity Entity =
2257 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ParamTy, Consumed: false);
2258 ExprResult Arg =
2259 S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: TheCall->getArg(Arg: 0));
2260 if (Arg.isInvalid())
2261 return ExprError();
2262 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
2263
2264 return TheCall;
2265}
2266
2267static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall) {
2268 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2269 return ExprError();
2270
2271 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
2272 if (Arg.isInvalid())
2273 return ExprError();
2274 QualType ParamTy = Arg.get()->getType();
2275 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
2276 TheCall->setType(S.Context.BoolTy);
2277
2278 // Only accept pointers to objects as arguments, which should have object
2279 // pointer or void pointer types.
2280 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2281 // LWG4138: Function pointer types not allowed
2282 if (PT->getPointeeType()->isFunctionType()) {
2283 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2284 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2285 << 1;
2286 return ExprError();
2287 }
2288 // Disallow VLAs too since those shouldn't be able to
2289 // be a template parameter for `std::is_within_lifetime`
2290 if (PT->getPointeeType()->isVariableArrayType()) {
2291 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(), DiagID: diag::err_vla_unsupported)
2292 << 1 << "__builtin_is_within_lifetime";
2293 return ExprError();
2294 }
2295 } else {
2296 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2297 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2298 << 0;
2299 return ExprError();
2300 }
2301 return TheCall;
2302}
2303
2304static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall) {
2305 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2306 return ExprError();
2307
2308 QualType Dest = TheCall->getArg(Arg: 0)->getType();
2309 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2310 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2311 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2312 << /*a pointer*/ 0;
2313 return ExprError();
2314 }
2315
2316 QualType T = Dest->getPointeeType();
2317 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T,
2318 DiagID: diag::err_incomplete_type))
2319 return ExprError();
2320
2321 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2322 T->isIncompleteArrayType()) {
2323 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2324 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2325 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2326 return ExprError();
2327 }
2328
2329 TheCall->setType(Dest);
2330
2331 QualType Src = TheCall->getArg(Arg: 1)->getType();
2332 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2333 S.Diag(Loc: TheCall->getArg(Arg: 1)->getExprLoc(),
2334 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2335 << /*the same*/ 3;
2336 return ExprError();
2337 }
2338
2339 Expr *SizeExpr = TheCall->getArg(Arg: 2);
2340 ExprResult Size = S.DefaultLvalueConversion(E: SizeExpr);
2341 if (Size.isInvalid())
2342 return ExprError();
2343
2344 Size = S.tryConvertExprToType(E: Size.get(), Ty: S.getASTContext().getSizeType());
2345 if (Size.isInvalid())
2346 return ExprError();
2347 SizeExpr = Size.get();
2348 TheCall->setArg(Arg: 2, ArgExpr: SizeExpr);
2349
2350 return TheCall;
2351}
2352
2353// Emit an error and return true if the current object format type is in the
2354// list of unsupported types.
2355static bool CheckBuiltinTargetNotInUnsupported(
2356 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2357 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2358 llvm::Triple::ObjectFormatType CurObjFormat =
2359 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2360 if (llvm::is_contained(Range&: UnsupportedObjectFormatTypes, Element: CurObjFormat)) {
2361 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2362 << TheCall->getSourceRange();
2363 return true;
2364 }
2365 return false;
2366}
2367
2368// Emit an error and return true if the current architecture is not in the list
2369// of supported architectures.
2370static bool
2371CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall,
2372 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2373 llvm::Triple::ArchType CurArch =
2374 S.getASTContext().getTargetInfo().getTriple().getArch();
2375 if (llvm::is_contained(Range&: SupportedArchs, Element: CurArch))
2376 return false;
2377 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2378 << TheCall->getSourceRange();
2379 return true;
2380}
2381
2382static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2383 SourceLocation CallSiteLoc);
2384
2385bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2386 CallExpr *TheCall) {
2387 switch (TI.getTriple().getArch()) {
2388 default:
2389 // Some builtins don't require additional checking, so just consider these
2390 // acceptable.
2391 return false;
2392 case llvm::Triple::arm:
2393 case llvm::Triple::armeb:
2394 case llvm::Triple::thumb:
2395 case llvm::Triple::thumbeb:
2396 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2397 case llvm::Triple::aarch64:
2398 case llvm::Triple::aarch64_32:
2399 case llvm::Triple::aarch64_be:
2400 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2401 case llvm::Triple::bpfeb:
2402 case llvm::Triple::bpfel:
2403 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2404 case llvm::Triple::dxil:
2405 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2406 case llvm::Triple::hexagon:
2407 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2408 case llvm::Triple::mips:
2409 case llvm::Triple::mipsel:
2410 case llvm::Triple::mips64:
2411 case llvm::Triple::mips64el:
2412 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2413 case llvm::Triple::spirv:
2414 case llvm::Triple::spirv32:
2415 case llvm::Triple::spirv64:
2416 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2417 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2418 return false;
2419 case llvm::Triple::systemz:
2420 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2421 case llvm::Triple::x86:
2422 case llvm::Triple::x86_64:
2423 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2424 case llvm::Triple::ppc:
2425 case llvm::Triple::ppcle:
2426 case llvm::Triple::ppc64:
2427 case llvm::Triple::ppc64le:
2428 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2429 case llvm::Triple::amdgpu:
2430 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(TI, BuiltinID, TheCall);
2431 case llvm::Triple::riscv32:
2432 case llvm::Triple::riscv64:
2433 case llvm::Triple::riscv32be:
2434 case llvm::Triple::riscv64be:
2435 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2436 case llvm::Triple::loongarch32:
2437 case llvm::Triple::loongarch64:
2438 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2439 TheCall);
2440 case llvm::Triple::wasm32:
2441 case llvm::Triple::wasm64:
2442 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2443 case llvm::Triple::nvptx:
2444 case llvm::Triple::nvptx64:
2445 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2446 }
2447}
2448
2449static bool isValidMathElementType(QualType T) {
2450 return T->isDependentType() ||
2451 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2452}
2453
2454// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2455// not a valid type, emit an error message and return true. Otherwise return
2456// false.
2457static bool
2458checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy,
2459 Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr,
2460 int ArgOrdinal) {
2461 clang::QualType EltTy =
2462 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2463 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2464 : ArgTy;
2465
2466 switch (ArgTyRestr) {
2467 case Sema::EltwiseBuiltinArgTyRestriction::None:
2468 if (!ArgTy->getAs<VectorType>() && !ArgTy->getAs<MatrixType>() &&
2469 !isValidMathElementType(T: ArgTy)) {
2470 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2471 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2472 << ArgTy;
2473 }
2474 break;
2475 case Sema::EltwiseBuiltinArgTyRestriction::FloatTy:
2476 if (!EltTy->isRealFloatingType()) {
2477 // FIXME: make diagnostic's wording correct for matrices
2478 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2479 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2480 << /* floating-point */ 1 << ArgTy;
2481 }
2482 break;
2483 case Sema::EltwiseBuiltinArgTyRestriction::IntegerTy:
2484 if (!EltTy->isIntegerType()) {
2485 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2486 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2487 << /* no fp */ 0 << ArgTy;
2488 }
2489 break;
2490 case Sema::EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy:
2491 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2492 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2493 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2494 << /* or fp */ 1 << ArgTy;
2495 }
2496 break;
2497 }
2498
2499 return false;
2500}
2501
2502/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2503/// This checks that the target supports the builtin and that the string
2504/// argument is constant and valid.
2505static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2506 const TargetInfo *AuxTI, unsigned BuiltinID) {
2507 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2508 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2509 "Expecting __builtin_cpu_...");
2510
2511 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2512 const TargetInfo *TheTI = &TI;
2513 auto SupportsBI = [=](const TargetInfo *TInfo) {
2514 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2515 (!IsCPUSupports && TInfo->supportsCpuIs()));
2516 };
2517 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2518 TheTI = AuxTI;
2519
2520 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2521 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2522 return S.Diag(Loc: TheCall->getBeginLoc(),
2523 DiagID: TI.getTriple().isOSAIX()
2524 ? diag::err_builtin_aix_os_unsupported
2525 : diag::err_builtin_target_unsupported)
2526 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2527
2528 Expr *Arg = TheCall->getArg(Arg: 0)->IgnoreParenImpCasts();
2529 // Check if the argument is a string literal.
2530 if (!isa<StringLiteral>(Val: Arg))
2531 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
2532 << Arg->getSourceRange();
2533
2534 // Check the contents of the string.
2535 StringRef Feature = cast<StringLiteral>(Val: Arg)->getString();
2536 if (IsCPUSupports && !TheTI->validateCpuSupports(Name: Feature)) {
2537 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_invalid_cpu_supports)
2538 << Arg->getSourceRange();
2539 return false;
2540 }
2541 if (!IsCPUSupports && !TheTI->validateCpuIs(Name: Feature))
2542 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_cpu_is)
2543 << Arg->getSourceRange();
2544 return false;
2545}
2546
2547/// Checks that __builtin_bswapg was called with a single argument, which is an
2548/// unsigned integer, and overrides the return value type to the integer type.
2549static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2550 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2551 return true;
2552 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2553 if (ArgRes.isInvalid())
2554 return true;
2555
2556 Expr *Arg = ArgRes.get();
2557 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2558 if (Arg->isTypeDependent())
2559 return false;
2560
2561 QualType ArgTy = Arg->getType();
2562
2563 if (!ArgTy->isIntegerType()) {
2564 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2565 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2566 << ArgTy;
2567 return true;
2568 }
2569 if (const auto *BT = dyn_cast<BitIntType>(Val&: ArgTy)) {
2570 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2571 BT->getNumBits() != 1) {
2572 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_bswapg_invalid_bit_width)
2573 << ArgTy << BT->getNumBits();
2574 return true;
2575 }
2576 }
2577 TheCall->setType(ArgTy);
2578 return false;
2579}
2580
2581/// Checks that __builtin_bitreverseg was called with a single argument, which
2582/// is an integer
2583static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2584 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2585 return true;
2586 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2587 if (ArgRes.isInvalid())
2588 return true;
2589
2590 Expr *Arg = ArgRes.get();
2591 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2592 if (Arg->isTypeDependent())
2593 return false;
2594
2595 QualType ArgTy = Arg->getType();
2596
2597 if (!ArgTy->isIntegerType()) {
2598 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2599 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2600 << ArgTy;
2601 return true;
2602 }
2603 TheCall->setType(ArgTy);
2604 return false;
2605}
2606
2607/// Checks that __builtin_popcountg was called with a single argument, which is
2608/// an unsigned integer.
2609static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2610 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2611 return true;
2612
2613 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2614 if (ArgRes.isInvalid())
2615 return true;
2616
2617 Expr *Arg = ArgRes.get();
2618 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2619
2620 QualType ArgTy = Arg->getType();
2621
2622 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2623 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2624 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2625 << ArgTy;
2626 return true;
2627 }
2628 return false;
2629}
2630
2631/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2632/// argument and return either int, bool, or the argument type.
2633static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2634 QualType ReturnType) {
2635 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2636 return true;
2637
2638 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2639 if (ArgRes.isInvalid())
2640 return true;
2641
2642 Expr *Arg = ArgRes.get();
2643 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2644
2645 QualType ArgTy = Arg->getType();
2646 // C23 stdbit.h functions do not permit bool or enumeration types.
2647 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2648 return S.Diag(Loc: Arg->getBeginLoc(),
2649 DiagID: diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2650 << 1 /*1st argument*/ << ArgTy;
2651 if (!ArgTy->isUnsignedIntegerType())
2652 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_stdc_invalid_arg_type)
2653 << 1 /*1st argument*/ << ArgTy;
2654
2655 // For builtins returning unsigned int, verify the argument's bit width fits.
2656 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2657 // produce a count that overflows the return type.
2658 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2659 uint64_t ArgWidth = S.Context.getIntWidth(T: ArgTy);
2660 uint64_t ReturnTypeWidth = S.Context.getIntWidth(T: S.Context.UnsignedIntTy);
2661 if (!llvm::isUIntN(N: ReturnTypeWidth, x: ArgWidth))
2662 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_stdc_result_overflow)
2663 << ArgTy;
2664 }
2665
2666 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2667 return false;
2668}
2669
2670/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2671/// an unsigned integer, and an optional second argument, which is promoted to
2672/// an 'int'.
2673static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2674 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
2675 return true;
2676
2677 ExprResult Arg0Res = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2678 if (Arg0Res.isInvalid())
2679 return true;
2680
2681 Expr *Arg0 = Arg0Res.get();
2682 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2683
2684 QualType Arg0Ty = Arg0->getType();
2685
2686 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2687 S.Diag(Loc: Arg0->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2688 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2689 << Arg0Ty;
2690 return true;
2691 }
2692
2693 if (TheCall->getNumArgs() > 1) {
2694 ExprResult Arg1Res = S.UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
2695 if (Arg1Res.isInvalid())
2696 return true;
2697
2698 Expr *Arg1 = Arg1Res.get();
2699 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2700
2701 QualType Arg1Ty = Arg1->getType();
2702
2703 if (!Arg1Ty->isSpecificBuiltinType(K: BuiltinType::Int)) {
2704 S.Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2705 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2706 return true;
2707 }
2708 }
2709
2710 return false;
2711}
2712
2713class RotateIntegerConverter : public Sema::ContextualImplicitConverter {
2714 unsigned ArgIndex;
2715 bool OnlyUnsigned;
2716
2717 Sema::SemaDiagnosticBuilder emitError(Sema &S, SourceLocation Loc,
2718 QualType T) {
2719 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2720 << ArgIndex << /*scalar*/ 1
2721 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2722 << /*no fp*/ 0 << T;
2723 }
2724
2725public:
2726 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2727 : ContextualImplicitConverter(/*Suppress=*/false,
2728 /*SuppressConversion=*/true),
2729 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2730
2731 bool match(QualType T) override {
2732 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2733 }
2734
2735 Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2736 QualType T) override {
2737 return emitError(S, Loc, T);
2738 }
2739
2740 Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2741 QualType T) override {
2742 return emitError(S, Loc, T);
2743 }
2744
2745 Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2746 QualType T,
2747 QualType ConvTy) override {
2748 return emitError(S, Loc, T);
2749 }
2750
2751 Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2752 QualType ConvTy) override {
2753 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2754 }
2755
2756 Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2757 QualType T) override {
2758 return emitError(S, Loc, T);
2759 }
2760
2761 Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2762 QualType ConvTy) override {
2763 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2764 }
2765
2766 Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2767 QualType T,
2768 QualType ConvTy) override {
2769 llvm_unreachable("conversion functions are permitted");
2770 }
2771};
2772
2773/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2774/// arguments, that the first argument is an unsigned integer type, and that
2775/// the second argument is an integer type.
2776static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2777 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
2778 return true;
2779
2780 // First argument (value to rotate) must be unsigned integer type.
2781 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2782 ExprResult Arg0Res = S.PerformContextualImplicitConversion(
2783 Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), FromE: TheCall->getArg(Arg: 0), Converter&: Arg0Converter);
2784 if (Arg0Res.isInvalid())
2785 return true;
2786
2787 Expr *Arg0 = Arg0Res.get();
2788 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2789
2790 QualType Arg0Ty = Arg0->getType();
2791 if (!Arg0Ty->isUnsignedIntegerType())
2792 return true;
2793
2794 // Second argument (rotation count) must be integer type.
2795 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2796 ExprResult Arg1Res = S.PerformContextualImplicitConversion(
2797 Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), FromE: TheCall->getArg(Arg: 1), Converter&: Arg1Converter);
2798 if (Arg1Res.isInvalid())
2799 return true;
2800
2801 Expr *Arg1 = Arg1Res.get();
2802 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2803
2804 QualType Arg1Ty = Arg1->getType();
2805 if (!Arg1Ty->isIntegerType())
2806 return true;
2807
2808 TheCall->setType(Arg0Ty);
2809 return false;
2810}
2811
2812static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2813 unsigned Pos, bool AllowConst,
2814 bool AllowAS) {
2815 QualType MaskTy = MaskArg->getType();
2816 if (!MaskTy->isExtVectorBoolType())
2817 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2818 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2819 << MaskTy;
2820
2821 QualType PtrTy = PtrArg->getType();
2822 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2823 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2824 << Pos << "scalar pointer";
2825
2826 QualType PointeeTy = PtrTy->getPointeeType();
2827 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2828 (!AllowConst && PointeeTy.isConstQualified()) ||
2829 (!AllowAS && PointeeTy.hasAddressSpace())) {
2830 QualType Target =
2831 S.Context.getPointerType(T: PointeeTy.getAtomicUnqualifiedType());
2832 return S.Diag(Loc: PtrArg->getExprLoc(),
2833 DiagID: diag::err_typecheck_convert_incompatible)
2834 << PtrTy << Target << /*different qualifiers=*/5
2835 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2836 << PtrTy << Target;
2837 }
2838 return false;
2839}
2840
2841static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2842 bool TypeDependent = false;
2843 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2844 ExprResult Converted =
2845 S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg));
2846 if (Converted.isInvalid())
2847 return true;
2848 TheCall->setArg(Arg, ArgExpr: Converted.get());
2849 TypeDependent |= Converted.get()->isTypeDependent();
2850 }
2851
2852 if (TypeDependent)
2853 TheCall->setType(S.Context.DependentTy);
2854 return false;
2855}
2856
2857static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall) {
2858 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
2859 return ExprError();
2860
2861 if (ConvertMaskedBuiltinArgs(S, TheCall))
2862 return ExprError();
2863
2864 Expr *MaskArg = TheCall->getArg(Arg: 0);
2865 Expr *PtrArg = TheCall->getArg(Arg: 1);
2866 if (TheCall->isTypeDependent())
2867 return TheCall;
2868
2869 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 2, /*AllowConst=*/true,
2870 AllowAS: TheCall->getBuiltinCallee() ==
2871 Builtin::BI__builtin_masked_load))
2872 return ExprError();
2873
2874 QualType MaskTy = MaskArg->getType();
2875 QualType PtrTy = PtrArg->getType();
2876 QualType PointeeTy = PtrTy->getPointeeType();
2877 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2878
2879 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2880 NumElts: MaskVecTy->getNumElements());
2881 if (TheCall->getNumArgs() == 3) {
2882 Expr *PassThruArg = TheCall->getArg(Arg: 2);
2883 QualType PassThruTy = PassThruArg->getType();
2884 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2885 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2886 << /* third argument */ 3 << RetTy;
2887 }
2888
2889 TheCall->setType(RetTy);
2890 return TheCall;
2891}
2892
2893static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall) {
2894 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2895 return ExprError();
2896
2897 if (ConvertMaskedBuiltinArgs(S, TheCall))
2898 return ExprError();
2899
2900 Expr *MaskArg = TheCall->getArg(Arg: 0);
2901 Expr *ValArg = TheCall->getArg(Arg: 1);
2902 Expr *PtrArg = TheCall->getArg(Arg: 2);
2903 if (TheCall->isTypeDependent())
2904 return TheCall;
2905
2906 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/false,
2907 AllowAS: TheCall->getBuiltinCallee() ==
2908 Builtin::BI__builtin_masked_store))
2909 return ExprError();
2910
2911 QualType MaskTy = MaskArg->getType();
2912 QualType PtrTy = PtrArg->getType();
2913 QualType ValTy = ValArg->getType();
2914 if (!ValTy->isVectorType())
2915 return ExprError(
2916 S.Diag(Loc: ValArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2917 << 2 << "vector");
2918
2919 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2920 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2921
2922 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2923 return ExprError(
2924 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2925 << S.getASTContext().BuiltinInfo.getQuotedName(
2926 ID: TheCall->getBuiltinCallee())
2927 << MaskTy << ValTy);
2928 }
2929
2930 if (!S.Context.hasSameType(T1: ValVecTy->getElementType().getUnqualifiedType(),
2931 T2: PtrTy->getPointeeType().getUnqualifiedType()))
2932 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
2933 DiagID: diag::err_vec_builtin_incompatible_vector)
2934 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2935 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
2936 TheCall->getArg(Arg: 1)->getEndLoc()));
2937
2938 TheCall->setType(S.Context.VoidTy);
2939 return TheCall;
2940}
2941
2942static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall) {
2943 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 3, MaxArgCount: 4))
2944 return ExprError();
2945
2946 if (ConvertMaskedBuiltinArgs(S, TheCall))
2947 return ExprError();
2948
2949 Expr *MaskArg = TheCall->getArg(Arg: 0);
2950 Expr *IdxArg = TheCall->getArg(Arg: 1);
2951 Expr *PtrArg = TheCall->getArg(Arg: 2);
2952 if (TheCall->isTypeDependent())
2953 return TheCall;
2954
2955 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/true,
2956 /*AllowAS=*/true))
2957 return ExprError();
2958
2959 QualType IdxTy = IdxArg->getType();
2960 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2961 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2962 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2963 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2964 << IdxTy;
2965
2966 QualType MaskTy = MaskArg->getType();
2967 QualType PtrTy = PtrArg->getType();
2968 QualType PointeeTy = PtrTy->getPointeeType();
2969 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2970 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2971 return ExprError(
2972 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2973 << S.getASTContext().BuiltinInfo.getQuotedName(
2974 ID: TheCall->getBuiltinCallee())
2975 << MaskTy << IdxTy);
2976
2977 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2978 NumElts: MaskVecTy->getNumElements());
2979 if (TheCall->getNumArgs() == 4) {
2980 Expr *PassThruArg = TheCall->getArg(Arg: 3);
2981 QualType PassThruTy = PassThruArg->getType();
2982 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2983 return S.Diag(Loc: PassThruArg->getExprLoc(),
2984 DiagID: diag::err_vec_masked_load_store_ptr)
2985 << /* fourth argument */ 4 << RetTy;
2986 }
2987
2988 TheCall->setType(RetTy);
2989 return TheCall;
2990}
2991
2992static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall) {
2993 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 4))
2994 return ExprError();
2995
2996 if (ConvertMaskedBuiltinArgs(S, TheCall))
2997 return ExprError();
2998
2999 Expr *MaskArg = TheCall->getArg(Arg: 0);
3000 Expr *IdxArg = TheCall->getArg(Arg: 1);
3001 Expr *ValArg = TheCall->getArg(Arg: 2);
3002 Expr *PtrArg = TheCall->getArg(Arg: 3);
3003 if (TheCall->isTypeDependent())
3004 return TheCall;
3005
3006 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 4, /*AllowConst=*/false,
3007 /*AllowAS=*/true))
3008 return ExprError();
3009
3010 QualType IdxTy = IdxArg->getType();
3011 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
3012 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
3013 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3014 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
3015 << IdxTy;
3016
3017 QualType ValTy = ValArg->getType();
3018 QualType MaskTy = MaskArg->getType();
3019 QualType PtrTy = PtrArg->getType();
3020
3021 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
3022 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
3023 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
3024 return ExprError(
3025 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
3026 << S.getASTContext().BuiltinInfo.getQuotedName(
3027 ID: TheCall->getBuiltinCallee())
3028 << MaskTy << IdxTy);
3029 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
3030 return ExprError(
3031 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
3032 << S.getASTContext().BuiltinInfo.getQuotedName(
3033 ID: TheCall->getBuiltinCallee())
3034 << MaskTy << ValTy);
3035
3036 if (!S.Context.hasSameType(T1: ValVecTy->getElementType().getUnqualifiedType(),
3037 T2: PtrTy->getPointeeType().getUnqualifiedType()))
3038 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
3039 DiagID: diag::err_vec_builtin_incompatible_vector)
3040 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
3041 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
3042 TheCall->getArg(Arg: 1)->getEndLoc()));
3043
3044 TheCall->setType(S.Context.VoidTy);
3045 return TheCall;
3046}
3047
3048static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall) {
3049 SourceLocation Loc = TheCall->getBeginLoc();
3050 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
3051 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
3052
3053 if (Args.size() == 0) {
3054 S.Diag(Loc: TheCall->getBeginLoc(),
3055 DiagID: diag::err_typecheck_call_too_few_args_at_least)
3056 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
3057 << /*is_non_object=*/0 << TheCall->getSourceRange();
3058 return ExprError();
3059 }
3060
3061 QualType FuncT = Args[0]->getType();
3062
3063 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
3064 if (Args.size() < 2) {
3065 S.Diag(Loc: TheCall->getBeginLoc(),
3066 DiagID: diag::err_typecheck_call_too_few_args_at_least)
3067 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
3068 << /*is_non_object=*/0 << TheCall->getSourceRange();
3069 return ExprError();
3070 }
3071
3072 const Type *MemPtrClass = MPT->getQualifier().getAsType();
3073 QualType ObjectT = Args[1]->getType();
3074
3075 if (MPT->isMemberDataPointer() && S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
3076 return ExprError();
3077
3078 ExprResult ObjectArg = [&]() -> ExprResult {
3079 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
3080 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
3081 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
3082 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
3083 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
3084 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
3085 if (S.Context.hasSameType(T1: QualType(MemPtrClass, 0),
3086 T2: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc)) ||
3087 S.BuiltinIsBaseOf(RhsTLoc: Args[1]->getBeginLoc(), LhsT: QualType(MemPtrClass, 0),
3088 RhsT: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc))) {
3089 return Args[1];
3090 }
3091
3092 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
3093 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
3094 // reference_wrapper;
3095 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
3096 if (RD->isInStdNamespace() &&
3097 RD->getDeclName().getAsString() == "reference_wrapper") {
3098 CXXScopeSpec SS;
3099 IdentifierInfo *GetName = &S.Context.Idents.get(Name: "get");
3100 UnqualifiedId GetID;
3101 GetID.setIdentifier(Id: GetName, IdLoc: Loc);
3102
3103 ExprResult MemExpr = S.ActOnMemberAccessExpr(
3104 S: S.getCurScope(), Base: Args[1], OpLoc: Loc, OpKind: tok::period, SS,
3105 /*TemplateKWLoc=*/SourceLocation(), Member&: GetID, ObjCImpDecl: nullptr);
3106
3107 if (MemExpr.isInvalid())
3108 return ExprError();
3109
3110 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemExpr.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
3111 }
3112 }
3113
3114 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
3115 // class T and t1 does not satisfy the previous two items;
3116
3117 return S.ActOnUnaryOp(S: S.getCurScope(), OpLoc: Loc, Op: tok::star, Input: Args[1]);
3118 }();
3119
3120 if (ObjectArg.isInvalid())
3121 return ExprError();
3122
3123 ExprResult BinOp = S.ActOnBinOp(S: S.getCurScope(), TokLoc: TheCall->getBeginLoc(),
3124 Kind: tok::periodstar, LHSExpr: ObjectArg.get(), RHSExpr: Args[0]);
3125 if (BinOp.isInvalid())
3126 return ExprError();
3127
3128 if (MPT->isMemberDataPointer())
3129 return BinOp;
3130
3131 // Give the synthesized expression a valid source range for diagnostics.
3132 auto *MemCall = new (S.Context)
3133 ParenExpr(TheCall->getBeginLoc(), TheCall->getRParenLoc(), BinOp.get());
3134
3135 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemCall, LParenLoc: TheCall->getBeginLoc(),
3136 ArgExprs: Args.drop_front(N: 2), RParenLoc: TheCall->getRParenLoc());
3137 }
3138 return S.ActOnCallExpr(S: S.getCurScope(), Fn: Args.front(), LParenLoc: TheCall->getBeginLoc(),
3139 ArgExprs: Args.drop_front(), RParenLoc: TheCall->getRParenLoc());
3140}
3141
3142// Performs a similar job to Sema::UsualUnaryConversions, but without any
3143// implicit promotion of integral/enumeration types.
3144static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E) {
3145 // First, convert to an r-value.
3146 ExprResult Res = S.DefaultFunctionArrayLvalueConversion(E);
3147 if (Res.isInvalid())
3148 return ExprError();
3149
3150 // Promote floating-point types.
3151 return S.UsualUnaryFPConversions(E: Res.get());
3152}
3153
3154static QualType getVectorElementType(ASTContext &Context, QualType VecTy) {
3155 if (const auto *TyA = VecTy->getAs<VectorType>())
3156 return TyA->getElementType();
3157 if (VecTy->isSizelessVectorType())
3158 return VecTy->getSizelessVectorEltType(Ctx: Context);
3159 return QualType();
3160}
3161
3162ExprResult
3163Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
3164 CallExpr *TheCall) {
3165 ExprResult TheCallResult(TheCall);
3166
3167 // Find out if any arguments are required to be integer constant expressions.
3168 unsigned ICEArguments = 0;
3169 ASTContext::GetBuiltinTypeError Error;
3170 Context.GetBuiltinType(ID: BuiltinID, Error, IntegerConstantArgs: &ICEArguments);
3171 if (Error != ASTContext::GE_None)
3172 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
3173
3174 // If any arguments are required to be ICE's, check and diagnose.
3175 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
3176 // Skip arguments not required to be ICE's.
3177 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
3178
3179 llvm::APSInt Result;
3180 // If we don't have enough arguments, continue so we can issue better
3181 // diagnostic in checkArgCount(...)
3182 if (ArgNo < TheCall->getNumArgs() &&
3183 BuiltinConstantArg(TheCall, ArgNum: ArgNo, Result))
3184 return true;
3185 ICEArguments &= ~(1 << ArgNo);
3186 }
3187
3188 FPOptions FPO;
3189 switch (BuiltinID) {
3190 case Builtin::BI__builtin___get_unsafe_stack_start:
3191 case Builtin::BI__builtin___get_unsafe_stack_bottom:
3192 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3193 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3194 << "__safestack_get_unsafe_stack_bottom";
3195 break;
3196 case Builtin::BI__builtin___get_unsafe_stack_top:
3197 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3198 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3199 << "__safestack_get_unsafe_stack_top";
3200 break;
3201 case Builtin::BI__builtin___get_unsafe_stack_ptr:
3202 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3203 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3204 << "__safestack_get_unsafe_stack_ptr";
3205 break;
3206 case Builtin::BI__builtin_cpu_supports:
3207 case Builtin::BI__builtin_cpu_is:
3208 if (BuiltinCpu(S&: *this, TI: Context.getTargetInfo(), TheCall,
3209 AuxTI: Context.getAuxTargetInfo(), BuiltinID))
3210 return ExprError();
3211 break;
3212 case Builtin::BI__builtin_cpu_init:
3213 if (!Context.getTargetInfo().supportsCpuInit()) {
3214 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
3215 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
3216 return ExprError();
3217 }
3218 break;
3219 case Builtin::BI__builtin___CFStringMakeConstantString:
3220 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
3221 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
3222 if (CheckBuiltinTargetNotInUnsupported(
3223 S&: *this, BuiltinID, TheCall,
3224 UnsupportedObjectFormatTypes: {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
3225 return ExprError();
3226 assert(TheCall->getNumArgs() == 1 &&
3227 "Wrong # arguments to builtin CFStringMakeConstantString");
3228 if (ObjC().CheckObjCString(Arg: TheCall->getArg(Arg: 0)))
3229 return ExprError();
3230 break;
3231 case Builtin::BI__builtin_ms_va_start:
3232 case Builtin::BI__builtin_zos_va_start:
3233 case Builtin::BI__builtin_stdarg_start:
3234 case Builtin::BI__builtin_va_start:
3235 case Builtin::BI__builtin_c23_va_start:
3236 if (BuiltinVAStart(BuiltinID, TheCall))
3237 return ExprError();
3238 break;
3239 case Builtin::BI__va_start: {
3240 switch (Context.getTargetInfo().getTriple().getArch()) {
3241 case llvm::Triple::aarch64:
3242 case llvm::Triple::arm:
3243 case llvm::Triple::thumb:
3244 if (BuiltinVAStartARMMicrosoft(Call: TheCall))
3245 return ExprError();
3246 break;
3247 default:
3248 if (BuiltinVAStart(BuiltinID, TheCall))
3249 return ExprError();
3250 break;
3251 }
3252 break;
3253 }
3254
3255 // The acquire, release, and no fence variants are ARM and AArch64 only.
3256 case Builtin::BI_interlockedbittestandset_acq:
3257 case Builtin::BI_interlockedbittestandset_rel:
3258 case Builtin::BI_interlockedbittestandset_nf:
3259 case Builtin::BI_interlockedbittestandreset_acq:
3260 case Builtin::BI_interlockedbittestandreset_rel:
3261 case Builtin::BI_interlockedbittestandreset_nf:
3262 if (CheckBuiltinTargetInSupported(
3263 S&: *this, TheCall,
3264 SupportedArchs: {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
3265 return ExprError();
3266 break;
3267
3268 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
3269 case Builtin::BI_bittest64:
3270 case Builtin::BI_bittestandcomplement64:
3271 case Builtin::BI_bittestandreset64:
3272 case Builtin::BI_bittestandset64:
3273 case Builtin::BI_interlockedbittestandreset64:
3274 case Builtin::BI_interlockedbittestandset64:
3275 if (CheckBuiltinTargetInSupported(
3276 S&: *this, TheCall,
3277 SupportedArchs: {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3278 llvm::Triple::aarch64, llvm::Triple::amdgpu}))
3279 return ExprError();
3280 break;
3281
3282 // The 64-bit acquire, release, and no fence variants are AArch64 only.
3283 case Builtin::BI_interlockedbittestandreset64_acq:
3284 case Builtin::BI_interlockedbittestandreset64_rel:
3285 case Builtin::BI_interlockedbittestandreset64_nf:
3286 case Builtin::BI_interlockedbittestandset64_acq:
3287 case Builtin::BI_interlockedbittestandset64_rel:
3288 case Builtin::BI_interlockedbittestandset64_nf:
3289 if (CheckBuiltinTargetInSupported(S&: *this, TheCall, SupportedArchs: {llvm::Triple::aarch64}))
3290 return ExprError();
3291 break;
3292
3293 case Builtin::BI__builtin_set_flt_rounds:
3294 if (CheckBuiltinTargetInSupported(
3295 S&: *this, TheCall,
3296 SupportedArchs: {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3297 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgpu,
3298 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3299 llvm::Triple::ppc64le}))
3300 return ExprError();
3301 break;
3302
3303 case Builtin::BI__builtin_isgreater:
3304 case Builtin::BI__builtin_isgreaterequal:
3305 case Builtin::BI__builtin_isless:
3306 case Builtin::BI__builtin_islessequal:
3307 case Builtin::BI__builtin_islessgreater:
3308 case Builtin::BI__builtin_isunordered:
3309 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3310 return ExprError();
3311 break;
3312 case Builtin::BI__builtin_fpclassify:
3313 if (BuiltinFPClassification(TheCall, NumArgs: 6, BuiltinID))
3314 return ExprError();
3315 break;
3316 case Builtin::BI__builtin_isfpclass:
3317 if (BuiltinFPClassification(TheCall, NumArgs: 2, BuiltinID))
3318 return ExprError();
3319 break;
3320 case Builtin::BI__builtin_isfinite:
3321 case Builtin::BI__builtin_isinf:
3322 case Builtin::BI__builtin_isinf_sign:
3323 case Builtin::BI__builtin_isnan:
3324 case Builtin::BI__builtin_issignaling:
3325 case Builtin::BI__builtin_isnormal:
3326 case Builtin::BI__builtin_issubnormal:
3327 case Builtin::BI__builtin_iszero:
3328 case Builtin::BI__builtin_signbit:
3329 case Builtin::BI__builtin_signbitf:
3330 case Builtin::BI__builtin_signbitl:
3331 if (BuiltinFPClassification(TheCall, NumArgs: 1, BuiltinID))
3332 return ExprError();
3333 break;
3334 case Builtin::BI__builtin_shufflevector:
3335 return BuiltinShuffleVector(TheCall);
3336 // TheCall will be freed by the smart pointer here, but that's fine, since
3337 // BuiltinShuffleVector guts it, but then doesn't release it.
3338 case Builtin::BI__builtin_masked_load:
3339 case Builtin::BI__builtin_masked_expand_load:
3340 return BuiltinMaskedLoad(S&: *this, TheCall);
3341 case Builtin::BI__builtin_masked_store:
3342 case Builtin::BI__builtin_masked_compress_store:
3343 return BuiltinMaskedStore(S&: *this, TheCall);
3344 case Builtin::BI__builtin_masked_gather:
3345 return BuiltinMaskedGather(S&: *this, TheCall);
3346 case Builtin::BI__builtin_masked_scatter:
3347 return BuiltinMaskedScatter(S&: *this, TheCall);
3348 case Builtin::BI__builtin_invoke:
3349 return BuiltinInvoke(S&: *this, TheCall);
3350 case Builtin::BI__builtin_prefetch:
3351 if (BuiltinPrefetch(TheCall))
3352 return ExprError();
3353 break;
3354 case Builtin::BI__builtin_alloca_with_align:
3355 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3356 if (BuiltinAllocaWithAlign(TheCall))
3357 return ExprError();
3358 [[fallthrough]];
3359 case Builtin::BI__builtin_alloca:
3360 case Builtin::BI__builtin_alloca_uninitialized:
3361 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca)
3362 << TheCall->getDirectCallee();
3363 if (getLangOpts().OpenCL) {
3364 builtinAllocaAddrSpace(S&: *this, TheCall);
3365 }
3366 break;
3367 case Builtin::BI__builtin_infer_alloc_token:
3368 if (checkBuiltinInferAllocToken(S&: *this, TheCall))
3369 return ExprError();
3370 break;
3371 case Builtin::BI__arithmetic_fence:
3372 if (BuiltinArithmeticFence(TheCall))
3373 return ExprError();
3374 break;
3375 case Builtin::BI__assume:
3376 case Builtin::BI__builtin_assume:
3377 if (BuiltinAssume(TheCall))
3378 return ExprError();
3379 break;
3380 case Builtin::BI__builtin_assume_aligned:
3381 if (BuiltinAssumeAligned(TheCall))
3382 return ExprError();
3383 break;
3384 case Builtin::BI__builtin_dynamic_object_size:
3385 case Builtin::BI__builtin_object_size:
3386 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: 3))
3387 return ExprError();
3388 break;
3389 case Builtin::BI__builtin_longjmp:
3390 if (BuiltinLongjmp(TheCall))
3391 return ExprError();
3392 break;
3393 case Builtin::BI__builtin_setjmp:
3394 if (BuiltinSetjmp(TheCall))
3395 return ExprError();
3396 break;
3397 case Builtin::BI__builtin_complex:
3398 if (BuiltinComplex(TheCall))
3399 return ExprError();
3400 break;
3401 case Builtin::BI__builtin_classify_type:
3402 case Builtin::BI__builtin_constant_p: {
3403 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3404 return true;
3405 ExprResult Arg = DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
3406 if (Arg.isInvalid()) return true;
3407 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
3408 TheCall->setType(Context.IntTy);
3409 break;
3410 }
3411 case Builtin::BI__builtin_launder:
3412 return BuiltinLaunder(S&: *this, TheCall);
3413 case Builtin::BI__builtin_is_within_lifetime:
3414 return BuiltinIsWithinLifetime(S&: *this, TheCall);
3415 case Builtin::BI__builtin_trivially_relocate:
3416 return BuiltinTriviallyRelocate(S&: *this, TheCall);
3417 case Builtin::BI__builtin_clear_padding: {
3418 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3419 return ExprError();
3420
3421 const Expr *PtrArg = TheCall->getArg(Arg: 0);
3422 const QualType PtrArgType = PtrArg->getType();
3423 if (!PtrArgType->isPointerType()) {
3424 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
3425 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3426 << "pointer";
3427 return ExprError();
3428 }
3429 QualType PointeeType = PtrArgType->getPointeeType();
3430 if (PointeeType.isConstQualified()) {
3431 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_typecheck_assign_const)
3432 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3433 return ExprError();
3434 }
3435 if (RequireCompleteType(Loc: PtrArg->getBeginLoc(), T: PointeeType,
3436 DiagID: diag::err_typecheck_decl_incomplete_type))
3437 return ExprError();
3438
3439 // For non trivially copyable types, we try to match gcc's behaviour.
3440 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3441 // object, either a local variable or a function parameter passed by value
3442 auto IsAddrOfDeclExpr = [&]() {
3443 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Ctx: Context);
3444 const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: Inner);
3445 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3446 return false;
3447
3448 const Expr *Operand =
3449 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Ctx: Context);
3450 const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: Operand);
3451 if (!DeclRef)
3452 return false;
3453
3454 const auto *VarDecl = dyn_cast<::clang::VarDecl>(Val: DeclRef->getDecl());
3455 if (!VarDecl || VarDecl->getType()->isReferenceType())
3456 return false;
3457
3458 // matching GCC behaviour
3459 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3460 QualType VarQType = VarDecl->getType();
3461 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3462 Context.hasSameUnqualifiedType(T1: PointeeType, T2: VarQType);
3463 };
3464
3465 if (!PointeeType.isTriviallyCopyableType(Context) &&
3466 !PointeeType->isAtomicType() // _Atomic is not copyable
3467 && !IsAddrOfDeclExpr()) {
3468 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_clear_padding_needs_trivial_copy)
3469 << PtrArg->getType() << PtrArg->getSourceRange();
3470 return ExprError();
3471 }
3472
3473 if (auto *Record = PointeeType->getAsRecordDecl();
3474 Record && Record->hasFlexibleArrayMember()) {
3475 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_clear_padding_no_flexible_array)
3476 << PointeeType << PtrArg->getSourceRange();
3477 return ExprError();
3478 }
3479
3480 break;
3481 }
3482 case Builtin::BI__sync_fetch_and_add:
3483 case Builtin::BI__sync_fetch_and_add_1:
3484 case Builtin::BI__sync_fetch_and_add_2:
3485 case Builtin::BI__sync_fetch_and_add_4:
3486 case Builtin::BI__sync_fetch_and_add_8:
3487 case Builtin::BI__sync_fetch_and_add_16:
3488 case Builtin::BI__sync_fetch_and_sub:
3489 case Builtin::BI__sync_fetch_and_sub_1:
3490 case Builtin::BI__sync_fetch_and_sub_2:
3491 case Builtin::BI__sync_fetch_and_sub_4:
3492 case Builtin::BI__sync_fetch_and_sub_8:
3493 case Builtin::BI__sync_fetch_and_sub_16:
3494 case Builtin::BI__sync_fetch_and_or:
3495 case Builtin::BI__sync_fetch_and_or_1:
3496 case Builtin::BI__sync_fetch_and_or_2:
3497 case Builtin::BI__sync_fetch_and_or_4:
3498 case Builtin::BI__sync_fetch_and_or_8:
3499 case Builtin::BI__sync_fetch_and_or_16:
3500 case Builtin::BI__sync_fetch_and_and:
3501 case Builtin::BI__sync_fetch_and_and_1:
3502 case Builtin::BI__sync_fetch_and_and_2:
3503 case Builtin::BI__sync_fetch_and_and_4:
3504 case Builtin::BI__sync_fetch_and_and_8:
3505 case Builtin::BI__sync_fetch_and_and_16:
3506 case Builtin::BI__sync_fetch_and_xor:
3507 case Builtin::BI__sync_fetch_and_xor_1:
3508 case Builtin::BI__sync_fetch_and_xor_2:
3509 case Builtin::BI__sync_fetch_and_xor_4:
3510 case Builtin::BI__sync_fetch_and_xor_8:
3511 case Builtin::BI__sync_fetch_and_xor_16:
3512 case Builtin::BI__sync_fetch_and_nand:
3513 case Builtin::BI__sync_fetch_and_nand_1:
3514 case Builtin::BI__sync_fetch_and_nand_2:
3515 case Builtin::BI__sync_fetch_and_nand_4:
3516 case Builtin::BI__sync_fetch_and_nand_8:
3517 case Builtin::BI__sync_fetch_and_nand_16:
3518 case Builtin::BI__sync_add_and_fetch:
3519 case Builtin::BI__sync_add_and_fetch_1:
3520 case Builtin::BI__sync_add_and_fetch_2:
3521 case Builtin::BI__sync_add_and_fetch_4:
3522 case Builtin::BI__sync_add_and_fetch_8:
3523 case Builtin::BI__sync_add_and_fetch_16:
3524 case Builtin::BI__sync_sub_and_fetch:
3525 case Builtin::BI__sync_sub_and_fetch_1:
3526 case Builtin::BI__sync_sub_and_fetch_2:
3527 case Builtin::BI__sync_sub_and_fetch_4:
3528 case Builtin::BI__sync_sub_and_fetch_8:
3529 case Builtin::BI__sync_sub_and_fetch_16:
3530 case Builtin::BI__sync_and_and_fetch:
3531 case Builtin::BI__sync_and_and_fetch_1:
3532 case Builtin::BI__sync_and_and_fetch_2:
3533 case Builtin::BI__sync_and_and_fetch_4:
3534 case Builtin::BI__sync_and_and_fetch_8:
3535 case Builtin::BI__sync_and_and_fetch_16:
3536 case Builtin::BI__sync_or_and_fetch:
3537 case Builtin::BI__sync_or_and_fetch_1:
3538 case Builtin::BI__sync_or_and_fetch_2:
3539 case Builtin::BI__sync_or_and_fetch_4:
3540 case Builtin::BI__sync_or_and_fetch_8:
3541 case Builtin::BI__sync_or_and_fetch_16:
3542 case Builtin::BI__sync_xor_and_fetch:
3543 case Builtin::BI__sync_xor_and_fetch_1:
3544 case Builtin::BI__sync_xor_and_fetch_2:
3545 case Builtin::BI__sync_xor_and_fetch_4:
3546 case Builtin::BI__sync_xor_and_fetch_8:
3547 case Builtin::BI__sync_xor_and_fetch_16:
3548 case Builtin::BI__sync_nand_and_fetch:
3549 case Builtin::BI__sync_nand_and_fetch_1:
3550 case Builtin::BI__sync_nand_and_fetch_2:
3551 case Builtin::BI__sync_nand_and_fetch_4:
3552 case Builtin::BI__sync_nand_and_fetch_8:
3553 case Builtin::BI__sync_nand_and_fetch_16:
3554 case Builtin::BI__sync_val_compare_and_swap:
3555 case Builtin::BI__sync_val_compare_and_swap_1:
3556 case Builtin::BI__sync_val_compare_and_swap_2:
3557 case Builtin::BI__sync_val_compare_and_swap_4:
3558 case Builtin::BI__sync_val_compare_and_swap_8:
3559 case Builtin::BI__sync_val_compare_and_swap_16:
3560 case Builtin::BI__sync_bool_compare_and_swap:
3561 case Builtin::BI__sync_bool_compare_and_swap_1:
3562 case Builtin::BI__sync_bool_compare_and_swap_2:
3563 case Builtin::BI__sync_bool_compare_and_swap_4:
3564 case Builtin::BI__sync_bool_compare_and_swap_8:
3565 case Builtin::BI__sync_bool_compare_and_swap_16:
3566 case Builtin::BI__sync_lock_test_and_set:
3567 case Builtin::BI__sync_lock_test_and_set_1:
3568 case Builtin::BI__sync_lock_test_and_set_2:
3569 case Builtin::BI__sync_lock_test_and_set_4:
3570 case Builtin::BI__sync_lock_test_and_set_8:
3571 case Builtin::BI__sync_lock_test_and_set_16:
3572 case Builtin::BI__sync_lock_release:
3573 case Builtin::BI__sync_lock_release_1:
3574 case Builtin::BI__sync_lock_release_2:
3575 case Builtin::BI__sync_lock_release_4:
3576 case Builtin::BI__sync_lock_release_8:
3577 case Builtin::BI__sync_lock_release_16:
3578 case Builtin::BI__sync_swap:
3579 case Builtin::BI__sync_swap_1:
3580 case Builtin::BI__sync_swap_2:
3581 case Builtin::BI__sync_swap_4:
3582 case Builtin::BI__sync_swap_8:
3583 case Builtin::BI__sync_swap_16:
3584 return BuiltinAtomicOverloaded(TheCallResult);
3585 case Builtin::BI__sync_synchronize:
3586 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
3587 << TheCall->getCallee()->getSourceRange();
3588 break;
3589 case Builtin::BI__builtin_nontemporal_load:
3590 case Builtin::BI__builtin_nontemporal_store:
3591 return BuiltinNontemporalOverloaded(TheCallResult);
3592 case Builtin::BI__builtin_memcpy_inline: {
3593 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3594 // We warn about copying to or from `nullptr` pointers when `size` is
3595 // greater than 0. When `size` is value dependent we cannot evaluate its
3596 // value so we bail out.
3597 if (SizeOp->isValueDependent())
3598 break;
3599 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero()) {
3600 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3601 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 1), CallSiteLoc: TheCall->getExprLoc());
3602 }
3603 break;
3604 }
3605 case Builtin::BI__builtin_memset_inline: {
3606 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3607 // We warn about filling to `nullptr` pointers when `size` is greater than
3608 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3609 // out.
3610 if (SizeOp->isValueDependent())
3611 break;
3612 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero())
3613 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3614 break;
3615 }
3616#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3617 case Builtin::BI##ID: \
3618 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3619#include "clang/Basic/Builtins.inc"
3620 case Builtin::BI__annotation: {
3621 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3622 if (!TT.isOSWindows() && !TT.isUEFI()) {
3623 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
3624 << TheCall->getSourceRange();
3625 return ExprError();
3626 }
3627 if (BuiltinMSVCAnnotation(S&: *this, TheCall))
3628 return ExprError();
3629 break;
3630 }
3631 case Builtin::BI__builtin_annotation:
3632 if (BuiltinAnnotation(S&: *this, TheCall))
3633 return ExprError();
3634 break;
3635 case Builtin::BI__builtin_addressof:
3636 if (BuiltinAddressof(S&: *this, TheCall))
3637 return ExprError();
3638 break;
3639 case Builtin::BI__builtin_function_start:
3640 if (BuiltinFunctionStart(S&: *this, TheCall))
3641 return ExprError();
3642 break;
3643 case Builtin::BI__builtin_is_aligned:
3644 case Builtin::BI__builtin_align_up:
3645 case Builtin::BI__builtin_align_down:
3646 if (BuiltinAlignment(S&: *this, TheCall, ID: BuiltinID))
3647 return ExprError();
3648 break;
3649 case Builtin::BI__builtin_add_overflow:
3650 case Builtin::BI__builtin_sub_overflow:
3651 case Builtin::BI__builtin_mul_overflow:
3652 if (BuiltinOverflow(S&: *this, TheCall, BuiltinID))
3653 return ExprError();
3654 break;
3655 case Builtin::BI__builtin_operator_new:
3656 case Builtin::BI__builtin_operator_delete: {
3657 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3658 ExprResult Res =
3659 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3660 return Res;
3661 }
3662 case Builtin::BI__builtin_dump_struct:
3663 return BuiltinDumpStruct(S&: *this, TheCall);
3664 case Builtin::BI__builtin_expect_with_probability: {
3665 // We first want to ensure we are called with 3 arguments
3666 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
3667 return ExprError();
3668 // then check probability is constant float in range [0.0, 1.0]
3669 const Expr *ProbArg = TheCall->getArg(Arg: 2);
3670 SmallVector<PartialDiagnosticAt, 8> Notes;
3671 Expr::EvalResult Eval;
3672 Eval.Diag = &Notes;
3673 if ((!ProbArg->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context)) ||
3674 !Eval.Val.isFloat()) {
3675 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_not_constant_float)
3676 << ProbArg->getSourceRange();
3677 for (const PartialDiagnosticAt &PDiag : Notes)
3678 Diag(Loc: PDiag.first, PD: PDiag.second);
3679 return ExprError();
3680 }
3681 llvm::APFloat Probability = Eval.Val.getFloat();
3682 bool LoseInfo = false;
3683 Probability.convert(ToSemantics: llvm::APFloat::IEEEdouble(),
3684 RM: llvm::RoundingMode::Dynamic, losesInfo: &LoseInfo);
3685 if (!(Probability >= llvm::APFloat(0.0) &&
3686 Probability <= llvm::APFloat(1.0))) {
3687 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_out_of_range)
3688 << ProbArg->getSourceRange();
3689 return ExprError();
3690 }
3691 break;
3692 }
3693 case Builtin::BI__builtin_preserve_access_index:
3694 if (BuiltinPreserveAI(S&: *this, TheCall))
3695 return ExprError();
3696 break;
3697 case Builtin::BI__builtin_call_with_static_chain:
3698 if (BuiltinCallWithStaticChain(S&: *this, BuiltinCall: TheCall))
3699 return ExprError();
3700 break;
3701 case Builtin::BI__exception_code:
3702 case Builtin::BI_exception_code:
3703 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHExceptScope,
3704 DiagID: diag::err_seh___except_block))
3705 return ExprError();
3706 break;
3707 case Builtin::BI__exception_info:
3708 case Builtin::BI_exception_info:
3709 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHFilterScope,
3710 DiagID: diag::err_seh___except_filter))
3711 return ExprError();
3712 break;
3713 case Builtin::BI__GetExceptionInfo:
3714 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3715 return ExprError();
3716
3717 if (CheckCXXThrowOperand(
3718 ThrowLoc: TheCall->getBeginLoc(),
3719 ThrowTy: Context.getExceptionObjectType(T: FDecl->getParamDecl(i: 0)->getType()),
3720 E: TheCall))
3721 return ExprError();
3722
3723 TheCall->setType(Context.VoidPtrTy);
3724 break;
3725 case Builtin::BIaddressof:
3726 case Builtin::BI__addressof:
3727 case Builtin::BIforward:
3728 case Builtin::BIforward_like:
3729 case Builtin::BImove:
3730 case Builtin::BImove_if_noexcept:
3731 case Builtin::BIas_const: {
3732 // These are all expected to be of the form
3733 // T &/&&/* f(U &/&&)
3734 // where T and U only differ in qualification.
3735 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3736 return ExprError();
3737 QualType Param = FDecl->getParamDecl(i: 0)->getType();
3738 QualType Result = FDecl->getReturnType();
3739 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3740 BuiltinID == Builtin::BI__addressof;
3741 if (!(Param->isReferenceType() &&
3742 (ReturnsPointer ? Result->isAnyPointerType()
3743 : Result->isReferenceType()) &&
3744 Context.hasSameUnqualifiedType(T1: Param->getPointeeType(),
3745 T2: Result->getPointeeType()))) {
3746 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_move_forward_unsupported)
3747 << FDecl;
3748 return ExprError();
3749 }
3750 break;
3751 }
3752 case Builtin::BI__builtin_ptrauth_strip:
3753 return PointerAuthStrip(S&: *this, Call: TheCall);
3754 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3755 return PointerAuthBlendDiscriminator(S&: *this, Call: TheCall);
3756 case Builtin::BI__builtin_ptrauth_sign_constant:
3757 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3758 /*RequireConstant=*/true);
3759 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3760 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3761 /*RequireConstant=*/false);
3762 case Builtin::BI__builtin_ptrauth_auth:
3763 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Auth,
3764 /*RequireConstant=*/false);
3765 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3766 return PointerAuthSignGenericData(S&: *this, Call: TheCall);
3767 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3768 return PointerAuthAuthAndResign(S&: *this, Call: TheCall);
3769 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
3770 return PointerAuthAuthWithPCAndResign(S&: *this, Call: TheCall);
3771 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3772 return PointerAuthAuthLoadRelativeAndSign(S&: *this, Call: TheCall);
3773 case Builtin::BI__builtin_ptrauth_string_discriminator:
3774 return PointerAuthStringDiscriminator(S&: *this, Call: TheCall);
3775
3776 case Builtin::BI__builtin_get_vtable_pointer:
3777 return GetVTablePointer(S&: *this, Call: TheCall);
3778
3779 // OpenCL v2.0, s6.13.16 - Pipe functions
3780 case Builtin::BIread_pipe:
3781 case Builtin::BIwrite_pipe:
3782 // Since those two functions are declared with var args, we need a semantic
3783 // check for the argument.
3784 if (OpenCL().checkBuiltinRWPipe(Call: TheCall))
3785 return ExprError();
3786 break;
3787 case Builtin::BIreserve_read_pipe:
3788 case Builtin::BIreserve_write_pipe:
3789 case Builtin::BIwork_group_reserve_read_pipe:
3790 case Builtin::BIwork_group_reserve_write_pipe:
3791 if (OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3792 return ExprError();
3793 break;
3794 case Builtin::BIsub_group_reserve_read_pipe:
3795 case Builtin::BIsub_group_reserve_write_pipe:
3796 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3797 OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3798 return ExprError();
3799 break;
3800 case Builtin::BIcommit_read_pipe:
3801 case Builtin::BIcommit_write_pipe:
3802 case Builtin::BIwork_group_commit_read_pipe:
3803 case Builtin::BIwork_group_commit_write_pipe:
3804 if (OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3805 return ExprError();
3806 break;
3807 case Builtin::BIsub_group_commit_read_pipe:
3808 case Builtin::BIsub_group_commit_write_pipe:
3809 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3810 OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3811 return ExprError();
3812 break;
3813 case Builtin::BIget_pipe_num_packets:
3814 case Builtin::BIget_pipe_max_packets:
3815 if (OpenCL().checkBuiltinPipePackets(Call: TheCall))
3816 return ExprError();
3817 break;
3818 case Builtin::BIto_global:
3819 case Builtin::BIto_local:
3820 case Builtin::BIto_private:
3821 if (OpenCL().checkBuiltinToAddr(BuiltinID, Call: TheCall))
3822 return ExprError();
3823 break;
3824 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3825 case Builtin::BIenqueue_kernel:
3826 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3827 return ExprError();
3828 break;
3829 case Builtin::BIget_kernel_work_group_size:
3830 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3831 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3832 return ExprError();
3833 break;
3834 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3835 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3836 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3837 return ExprError();
3838 break;
3839 case Builtin::BI__builtin_os_log_format:
3840 Cleanup.setExprNeedsCleanups(true);
3841 [[fallthrough]];
3842 case Builtin::BI__builtin_os_log_format_buffer_size:
3843 if (BuiltinOSLogFormat(TheCall))
3844 return ExprError();
3845 break;
3846 case Builtin::BI__builtin_frame_address:
3847 case Builtin::BI__builtin_return_address: {
3848 if (BuiltinConstantArgRange(TheCall, ArgNum: 0, Low: 0, High: 0xFFFF))
3849 return ExprError();
3850
3851 // -Wframe-address warning if non-zero passed to builtin
3852 // return/frame address.
3853 Expr::EvalResult Result;
3854 if (!TheCall->getArg(Arg: 0)->isValueDependent() &&
3855 TheCall->getArg(Arg: 0)->EvaluateAsInt(Result, Ctx: getASTContext()) &&
3856 Result.Val.getInt() != 0)
3857 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_frame_address)
3858 << ((BuiltinID == Builtin::BI__builtin_return_address)
3859 ? "__builtin_return_address"
3860 : "__builtin_frame_address")
3861 << TheCall->getSourceRange();
3862 break;
3863 }
3864
3865 case Builtin::BI__builtin_nondeterministic_value: {
3866 if (BuiltinNonDeterministicValue(TheCall))
3867 return ExprError();
3868 break;
3869 }
3870
3871 // __builtin_elementwise_abs restricts the element type to signed integers or
3872 // floating point types only.
3873 case Builtin::BI__builtin_elementwise_abs:
3874 if (PrepareBuiltinElementwiseMathOneArgCall(
3875 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy))
3876 return ExprError();
3877 break;
3878
3879 // These builtins restrict the element type to floating point
3880 // types only.
3881 case Builtin::BI__builtin_elementwise_acos:
3882 case Builtin::BI__builtin_elementwise_asin:
3883 case Builtin::BI__builtin_elementwise_atan:
3884 case Builtin::BI__builtin_elementwise_ceil:
3885 case Builtin::BI__builtin_elementwise_cos:
3886 case Builtin::BI__builtin_elementwise_cosh:
3887 case Builtin::BI__builtin_elementwise_exp:
3888 case Builtin::BI__builtin_elementwise_exp2:
3889 case Builtin::BI__builtin_elementwise_exp10:
3890 case Builtin::BI__builtin_elementwise_floor:
3891 case Builtin::BI__builtin_elementwise_log:
3892 case Builtin::BI__builtin_elementwise_log2:
3893 case Builtin::BI__builtin_elementwise_log10:
3894 case Builtin::BI__builtin_elementwise_roundeven:
3895 case Builtin::BI__builtin_elementwise_round:
3896 case Builtin::BI__builtin_elementwise_rint:
3897 case Builtin::BI__builtin_elementwise_nearbyint:
3898 case Builtin::BI__builtin_elementwise_sin:
3899 case Builtin::BI__builtin_elementwise_sinh:
3900 case Builtin::BI__builtin_elementwise_sqrt:
3901 case Builtin::BI__builtin_elementwise_tan:
3902 case Builtin::BI__builtin_elementwise_tanh:
3903 case Builtin::BI__builtin_elementwise_trunc:
3904 case Builtin::BI__builtin_elementwise_canonicalize:
3905 if (PrepareBuiltinElementwiseMathOneArgCall(
3906 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3907 return ExprError();
3908 break;
3909 case Builtin::BI__builtin_elementwise_fma:
3910 if (BuiltinElementwiseTernaryMath(TheCall))
3911 return ExprError();
3912 break;
3913
3914 case Builtin::BI__builtin_elementwise_ldexp: {
3915 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3916 return ExprError();
3917
3918 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
3919 if (A.isInvalid())
3920 return ExprError();
3921 QualType TyA = A.get()->getType();
3922 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
3923 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1))
3924 return ExprError();
3925
3926 ExprResult Exp = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3927 if (Exp.isInvalid())
3928 return ExprError();
3929 QualType TyExp = Exp.get()->getType();
3930 if (checkMathBuiltinElementType(S&: *this, Loc: Exp.get()->getBeginLoc(), ArgTy: TyExp,
3931 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy,
3932 ArgOrdinal: 2))
3933 return ExprError();
3934
3935 // Check the two arguments are either scalars or vectors of equal length.
3936 const auto *Vec0 = TyA->getAs<VectorType>();
3937 const auto *Vec1 = TyExp->getAs<VectorType>();
3938 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3939 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3940 if (Arg0Length != Arg1Length) {
3941 Diag(Loc: Exp.get()->getBeginLoc(),
3942 DiagID: diag::err_typecheck_vector_lengths_not_equal)
3943 << TyA << TyExp << A.get()->getSourceRange()
3944 << Exp.get()->getSourceRange();
3945 return ExprError();
3946 }
3947
3948 TheCall->setArg(Arg: 0, ArgExpr: A.get());
3949 TheCall->setArg(Arg: 1, ArgExpr: Exp.get());
3950 TheCall->setType(TyA);
3951 break;
3952 }
3953
3954 // These builtins restrict the element type to floating point
3955 // types only, and take in two arguments.
3956 case Builtin::BI__builtin_elementwise_minnum:
3957 case Builtin::BI__builtin_elementwise_maxnum:
3958 case Builtin::BI__builtin_elementwise_minimum:
3959 case Builtin::BI__builtin_elementwise_maximum:
3960 case Builtin::BI__builtin_elementwise_minimumnum:
3961 case Builtin::BI__builtin_elementwise_maximumnum:
3962 case Builtin::BI__builtin_elementwise_atan2:
3963 case Builtin::BI__builtin_elementwise_fmod:
3964 case Builtin::BI__builtin_elementwise_pow:
3965 if (BuiltinElementwiseMath(TheCall,
3966 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3967 return ExprError();
3968 break;
3969 // These builtins restrict the element type to integer
3970 // types only.
3971 case Builtin::BI__builtin_elementwise_add_sat:
3972 case Builtin::BI__builtin_elementwise_sub_sat:
3973 case Builtin::BI__builtin_elementwise_clmul:
3974 case Builtin::BI__builtin_elementwise_pext:
3975 case Builtin::BI__builtin_elementwise_pdep:
3976 if (BuiltinElementwiseMath(TheCall,
3977 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3978 return ExprError();
3979 break;
3980 case Builtin::BI__builtin_elementwise_fshl:
3981 case Builtin::BI__builtin_elementwise_fshr:
3982 if (BuiltinElementwiseTernaryMath(
3983 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3984 return ExprError();
3985 break;
3986 case Builtin::BI__builtin_elementwise_min:
3987 case Builtin::BI__builtin_elementwise_max: {
3988 if (BuiltinElementwiseMath(TheCall))
3989 return ExprError();
3990 Expr *Arg0 = TheCall->getArg(Arg: 0);
3991 Expr *Arg1 = TheCall->getArg(Arg: 1);
3992 QualType Ty0 = Arg0->getType();
3993 QualType Ty1 = Arg1->getType();
3994 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3995 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3996 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3997 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3998 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3999 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin_no_suggestion)
4000 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID);
4001 break;
4002 }
4003 case Builtin::BI__builtin_elementwise_popcount:
4004 case Builtin::BI__builtin_elementwise_bitreverse:
4005 if (PrepareBuiltinElementwiseMathOneArgCall(
4006 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
4007 return ExprError();
4008 break;
4009 case Builtin::BI__builtin_elementwise_copysign: {
4010 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
4011 return ExprError();
4012
4013 ExprResult Magnitude = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
4014 ExprResult Sign = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
4015 if (Magnitude.isInvalid() || Sign.isInvalid())
4016 return ExprError();
4017
4018 QualType MagnitudeTy = Magnitude.get()->getType();
4019 QualType SignTy = Sign.get()->getType();
4020 if (checkMathBuiltinElementType(
4021 S&: *this, Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), ArgTy: MagnitudeTy,
4022 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1) ||
4023 checkMathBuiltinElementType(
4024 S&: *this, Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), ArgTy: SignTy,
4025 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 2)) {
4026 return ExprError();
4027 }
4028
4029 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
4030 return Diag(Loc: Sign.get()->getBeginLoc(),
4031 DiagID: diag::err_typecheck_call_different_arg_types)
4032 << MagnitudeTy << SignTy;
4033 }
4034
4035 TheCall->setArg(Arg: 0, ArgExpr: Magnitude.get());
4036 TheCall->setArg(Arg: 1, ArgExpr: Sign.get());
4037 TheCall->setType(Magnitude.get()->getType());
4038 break;
4039 }
4040 case Builtin::BI__builtin_elementwise_clzg:
4041 case Builtin::BI__builtin_elementwise_ctzg:
4042 // These builtins can be unary or binary. Note for empty calls we call the
4043 // unary checker in order to not emit an error that says the function
4044 // expects 2 arguments, which would be misleading.
4045 if (TheCall->getNumArgs() <= 1) {
4046 if (PrepareBuiltinElementwiseMathOneArgCall(
4047 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
4048 return ExprError();
4049 } else if (BuiltinElementwiseMath(
4050 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
4051 return ExprError();
4052 break;
4053 case Builtin::BI__builtin_reduce_max:
4054 case Builtin::BI__builtin_reduce_min: {
4055 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4056 return ExprError();
4057
4058 const Expr *Arg = TheCall->getArg(Arg: 0);
4059 const auto *TyA = Arg->getType()->getAs<VectorType>();
4060
4061 QualType ElTy;
4062 if (TyA)
4063 ElTy = TyA->getElementType();
4064 else if (Arg->getType()->isSizelessVectorType())
4065 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
4066
4067 if (ElTy.isNull()) {
4068 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4069 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
4070 << Arg->getType();
4071 return ExprError();
4072 }
4073
4074 TheCall->setType(ElTy);
4075 break;
4076 }
4077 case Builtin::BI__builtin_reduce_maximum:
4078 case Builtin::BI__builtin_reduce_minimum: {
4079 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4080 return ExprError();
4081
4082 const Expr *Arg = TheCall->getArg(Arg: 0);
4083 const auto *TyA = Arg->getType()->getAs<VectorType>();
4084
4085 QualType ElTy;
4086 if (TyA)
4087 ElTy = TyA->getElementType();
4088 else if (Arg->getType()->isSizelessVectorType())
4089 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
4090
4091 if (ElTy.isNull() || !ElTy->isFloatingType()) {
4092 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4093 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4094 << Arg->getType();
4095 return ExprError();
4096 }
4097
4098 TheCall->setType(ElTy);
4099 break;
4100 }
4101
4102 // These builtins support vectors of integers only.
4103 // TODO: ADD/MUL should support floating-point types.
4104 case Builtin::BI__builtin_reduce_add:
4105 case Builtin::BI__builtin_reduce_mul:
4106 case Builtin::BI__builtin_reduce_xor:
4107 case Builtin::BI__builtin_reduce_or:
4108 case Builtin::BI__builtin_reduce_and: {
4109 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4110 return ExprError();
4111
4112 const Expr *Arg = TheCall->getArg(Arg: 0);
4113
4114 QualType ElTy = getVectorElementType(Context, VecTy: Arg->getType());
4115 if (ElTy.isNull() || !ElTy->isIntegerType()) {
4116 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4117 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
4118 << Arg->getType();
4119 return ExprError();
4120 }
4121
4122 TheCall->setType(ElTy);
4123 break;
4124 }
4125
4126 case Builtin::BI__builtin_reduce_assoc_fadd:
4127 case Builtin::BI__builtin_reduce_in_order_fadd: {
4128 // For in-order reductions require the user to specify the start value.
4129 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
4130 if (InOrder ? checkArgCount(Call: TheCall, DesiredArgCount: 2) : checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
4131 return ExprError();
4132
4133 ExprResult Vec = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
4134 if (Vec.isInvalid())
4135 return ExprError();
4136
4137 TheCall->setArg(Arg: 0, ArgExpr: Vec.get());
4138
4139 QualType ElTy = getVectorElementType(Context, VecTy: Vec.get()->getType());
4140 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
4141 Diag(Loc: Vec.get()->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
4142 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
4143 << Vec.get()->getType();
4144 return ExprError();
4145 }
4146
4147 if (TheCall->getNumArgs() == 2) {
4148 ExprResult StartValue = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
4149 if (StartValue.isInvalid())
4150 return ExprError();
4151
4152 if (!StartValue.get()->getType()->isRealFloatingType()) {
4153 Diag(Loc: StartValue.get()->getBeginLoc(),
4154 DiagID: diag::err_builtin_invalid_arg_type)
4155 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
4156 << StartValue.get()->getType();
4157 return ExprError();
4158 }
4159 TheCall->setArg(Arg: 1, ArgExpr: StartValue.get());
4160 }
4161
4162 TheCall->setType(ElTy);
4163 break;
4164 }
4165
4166 case Builtin::BI__builtin_matrix_transpose:
4167 return BuiltinMatrixTranspose(TheCall, CallResult: TheCallResult);
4168
4169 case Builtin::BI__builtin_matrix_column_major_load:
4170 return BuiltinMatrixColumnMajorLoad(TheCall, CallResult: TheCallResult);
4171
4172 case Builtin::BI__builtin_matrix_column_major_store:
4173 return BuiltinMatrixColumnMajorStore(TheCall, CallResult: TheCallResult);
4174
4175 case Builtin::BI__builtin_verbose_trap:
4176 if (!checkBuiltinVerboseTrap(Call: TheCall, S&: *this))
4177 return ExprError();
4178 break;
4179
4180 case Builtin::BI__builtin_get_device_side_mangled_name: {
4181 auto Check = [](CallExpr *TheCall) {
4182 if (TheCall->getNumArgs() != 1)
4183 return false;
4184 auto *DRE = dyn_cast<DeclRefExpr>(Val: TheCall->getArg(Arg: 0)->IgnoreImpCasts());
4185 if (!DRE)
4186 return false;
4187 auto *D = DRE->getDecl();
4188 if (!isa<FunctionDecl>(Val: D) && !isa<VarDecl>(Val: D))
4189 return false;
4190 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4191 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
4192 };
4193 if (!Check(TheCall)) {
4194 Diag(Loc: TheCall->getBeginLoc(),
4195 DiagID: diag::err_hip_invalid_args_builtin_mangled_name);
4196 return ExprError();
4197 }
4198 break;
4199 }
4200 case Builtin::BI__builtin_bswapg:
4201 if (BuiltinBswapg(S&: *this, TheCall))
4202 return ExprError();
4203 break;
4204 case Builtin::BI__builtin_bitreverseg:
4205 if (BuiltinBitreverseg(S&: *this, TheCall))
4206 return ExprError();
4207 break;
4208 case Builtin::BI__builtin_popcountg:
4209 if (BuiltinPopcountg(S&: *this, TheCall))
4210 return ExprError();
4211 break;
4212 case Builtin::BI__builtin_clzg:
4213 case Builtin::BI__builtin_ctzg:
4214 if (BuiltinCountZeroBitsGeneric(S&: *this, TheCall))
4215 return ExprError();
4216 break;
4217
4218 case Builtin::BI__builtin_stdc_rotate_left:
4219 case Builtin::BI__builtin_stdc_rotate_right:
4220 if (BuiltinRotateGeneric(S&: *this, TheCall))
4221 return ExprError();
4222 break;
4223
4224 case Builtin::BI__builtin_stdc_memreverse8:
4225 case Builtin::BIstdc_memreverse8:
4226 case Builtin::BIstdc_memreverse8u8:
4227 case Builtin::BIstdc_memreverse8u16:
4228 case Builtin::BIstdc_memreverse8u32:
4229 case Builtin::BIstdc_memreverse8u64:
4230 case Builtin::BIstdc_load8_leu8:
4231 case Builtin::BIstdc_load8_leu16:
4232 case Builtin::BIstdc_load8_leu32:
4233 case Builtin::BIstdc_load8_leu64:
4234 case Builtin::BIstdc_load8_les8:
4235 case Builtin::BIstdc_load8_les16:
4236 case Builtin::BIstdc_load8_les32:
4237 case Builtin::BIstdc_load8_les64:
4238 case Builtin::BIstdc_load8_beu8:
4239 case Builtin::BIstdc_load8_beu16:
4240 case Builtin::BIstdc_load8_beu32:
4241 case Builtin::BIstdc_load8_beu64:
4242 case Builtin::BIstdc_load8_bes8:
4243 case Builtin::BIstdc_load8_bes16:
4244 case Builtin::BIstdc_load8_bes32:
4245 case Builtin::BIstdc_load8_bes64:
4246 case Builtin::BIstdc_load8_aligned_leu8:
4247 case Builtin::BIstdc_load8_aligned_leu16:
4248 case Builtin::BIstdc_load8_aligned_leu32:
4249 case Builtin::BIstdc_load8_aligned_leu64:
4250 case Builtin::BIstdc_load8_aligned_les8:
4251 case Builtin::BIstdc_load8_aligned_les16:
4252 case Builtin::BIstdc_load8_aligned_les32:
4253 case Builtin::BIstdc_load8_aligned_les64:
4254 case Builtin::BIstdc_load8_aligned_beu8:
4255 case Builtin::BIstdc_load8_aligned_beu16:
4256 case Builtin::BIstdc_load8_aligned_beu32:
4257 case Builtin::BIstdc_load8_aligned_beu64:
4258 case Builtin::BIstdc_load8_aligned_bes8:
4259 case Builtin::BIstdc_load8_aligned_bes16:
4260 case Builtin::BIstdc_load8_aligned_bes32:
4261 case Builtin::BIstdc_load8_aligned_bes64:
4262 if (Context.getTargetInfo().getCharWidth() != 8) {
4263 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_requires_char_bit_8)
4264 << TheCall->getDirectCallee()->getName();
4265 return ExprError();
4266 }
4267 break;
4268
4269 case Builtin::BI__builtin_stdc_bit_floor:
4270 case Builtin::BI__builtin_stdc_bit_ceil:
4271 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: QualType()))
4272 return ExprError();
4273 break;
4274 case Builtin::BI__builtin_stdc_has_single_bit:
4275 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: Context.BoolTy))
4276 return ExprError();
4277 break;
4278 case Builtin::BI__builtin_stdc_leading_zeros:
4279 case Builtin::BI__builtin_stdc_leading_ones:
4280 case Builtin::BI__builtin_stdc_trailing_zeros:
4281 case Builtin::BI__builtin_stdc_trailing_ones:
4282 case Builtin::BI__builtin_stdc_first_leading_zero:
4283 case Builtin::BI__builtin_stdc_first_leading_one:
4284 case Builtin::BI__builtin_stdc_first_trailing_zero:
4285 case Builtin::BI__builtin_stdc_first_trailing_one:
4286 case Builtin::BI__builtin_stdc_count_zeros:
4287 case Builtin::BI__builtin_stdc_count_ones:
4288 case Builtin::BI__builtin_stdc_bit_width:
4289 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: Context.UnsignedIntTy))
4290 return ExprError();
4291 break;
4292
4293 case Builtin::BI__builtin_allow_runtime_check: {
4294 Expr *Arg = TheCall->getArg(Arg: 0);
4295 // Check if the argument is a string literal.
4296 if (!isa<StringLiteral>(Val: Arg->IgnoreParenImpCasts())) {
4297 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
4298 << Arg->getSourceRange();
4299 return ExprError();
4300 }
4301 break;
4302 }
4303
4304 case Builtin::BI__builtin_allow_sanitize_check: {
4305 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
4306 return ExprError();
4307
4308 Expr *Arg = TheCall->getArg(Arg: 0);
4309 // Check if the argument is a string literal.
4310 const StringLiteral *SanitizerName =
4311 dyn_cast<StringLiteral>(Val: Arg->IgnoreParenImpCasts());
4312 if (!SanitizerName) {
4313 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
4314 << Arg->getSourceRange();
4315 return ExprError();
4316 }
4317 // Validate the sanitizer name.
4318 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
4319 .Cases(CaseStrings: {"address", "thread", "memory", "hwaddress",
4320 "kernel-address", "kernel-memory", "kernel-hwaddress"},
4321 Value: true)
4322 .Default(Value: false)) {
4323 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_builtin_argument)
4324 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
4325 << Arg->getSourceRange();
4326 return ExprError();
4327 }
4328 break;
4329 }
4330 case Builtin::BI__builtin_counted_by_ref:
4331 if (BuiltinCountedByRef(TheCall))
4332 return ExprError();
4333 break;
4334 }
4335
4336 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4337 return ExprError();
4338
4339 // Since the target specific builtins for each arch overlap, only check those
4340 // of the arch we are compiling for.
4341 if (Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID)) {
4342 if (Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID)) {
4343 assert(Context.getAuxTargetInfo() &&
4344 "Aux Target Builtin, but not an aux target?");
4345
4346 if (CheckTSBuiltinFunctionCall(
4347 TI: *Context.getAuxTargetInfo(),
4348 BuiltinID: Context.BuiltinInfo.getAuxBuiltinID(ID: BuiltinID), TheCall))
4349 return ExprError();
4350 } else {
4351 if (CheckTSBuiltinFunctionCall(TI: Context.getTargetInfo(), BuiltinID,
4352 TheCall))
4353 return ExprError();
4354 }
4355 }
4356
4357 return TheCallResult;
4358}
4359
4360bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4361 llvm::APSInt Result;
4362 // We can't check the value of a dependent argument.
4363 Expr *Arg = TheCall->getArg(Arg: ArgNum);
4364 if (Arg->isTypeDependent() || Arg->isValueDependent())
4365 return false;
4366
4367 // Check constant-ness first.
4368 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4369 return true;
4370
4371 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4372 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4373 return false;
4374
4375 return Diag(Loc: TheCall->getBeginLoc(),
4376 DiagID: diag::err_argument_not_contiguous_bit_field)
4377 << ArgNum << Arg->getSourceRange();
4378}
4379
4380bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4381 unsigned FirstArg, FormatStringInfo *FSI) {
4382 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4383 bool IsVariadic = false;
4384 if (const FunctionType *FnTy = D->getFunctionType())
4385 IsVariadic = cast<FunctionProtoType>(Val: FnTy)->isVariadic();
4386 else if (const auto *BD = dyn_cast<BlockDecl>(Val: D))
4387 IsVariadic = BD->isVariadic();
4388 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D))
4389 IsVariadic = OMD->isVariadic();
4390
4391 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4392 IsVariadic, FSI);
4393}
4394
4395bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4396 bool HasImplicitThisParam, bool IsVariadic,
4397 FormatStringInfo *FSI) {
4398 if (FirstArg == 0)
4399 FSI->ArgPassingKind = FAPK_VAList;
4400 else if (IsVariadic)
4401 FSI->ArgPassingKind = FAPK_Variadic;
4402 else
4403 FSI->ArgPassingKind = FAPK_Fixed;
4404 FSI->FormatIdx = FormatIdx - 1;
4405 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4406
4407 // The way the format attribute works in GCC, the implicit this argument
4408 // of member functions is counted. However, it doesn't appear in our own
4409 // lists, so decrement format_idx in that case.
4410 if (HasImplicitThisParam) {
4411 if(FSI->FormatIdx == 0)
4412 return false;
4413 --FSI->FormatIdx;
4414 if (FSI->FirstDataArg != 0)
4415 --FSI->FirstDataArg;
4416 }
4417 return true;
4418}
4419
4420/// Checks if a the given expression evaluates to null.
4421///
4422/// Returns true if the value evaluates to null.
4423static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4424 // Treat (smart) pointers constructed from nullptr as null, whether we can
4425 // const-evaluate them or not.
4426 // This must happen first: the smart pointer expr might have _Nonnull type!
4427 if (isa<CXXNullPtrLiteralExpr>(
4428 Val: IgnoreExprNodes(E: Expr, Fns&: IgnoreImplicitAsWrittenSingleStep,
4429 Fns&: IgnoreElidableImplicitConstructorSingleStep)))
4430 return true;
4431
4432 // If the expression has non-null type, it doesn't evaluate to null.
4433 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4434 if (*nullability == NullabilityKind::NonNull)
4435 return false;
4436 }
4437
4438 // As a special case, transparent unions initialized with zero are
4439 // considered null for the purposes of the nonnull attribute.
4440 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4441 UT &&
4442 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4443 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Val: Expr))
4444 if (const auto *ILE = dyn_cast<InitListExpr>(Val: CLE->getInitializer()))
4445 Expr = ILE->getInit(Init: 0);
4446 }
4447
4448 bool Result;
4449 return (!Expr->isValueDependent() &&
4450 Expr->EvaluateAsBooleanCondition(Result, Ctx: S.Context) &&
4451 !Result);
4452}
4453
4454static void CheckNonNullArgument(Sema &S,
4455 const Expr *ArgExpr,
4456 SourceLocation CallSiteLoc) {
4457 if (CheckNonNullExpr(S, Expr: ArgExpr))
4458 S.DiagRuntimeBehavior(Loc: CallSiteLoc, Statement: ArgExpr,
4459 PD: S.PDiag(DiagID: diag::warn_null_arg)
4460 << ArgExpr->getSourceRange());
4461}
4462
4463/// Determine whether the given type has a non-null nullability annotation.
4464static bool isNonNullType(QualType type) {
4465 if (auto nullability = type->getNullability())
4466 return *nullability == NullabilityKind::NonNull;
4467
4468 return false;
4469}
4470
4471static void CheckNonNullArguments(Sema &S,
4472 const NamedDecl *FDecl,
4473 const FunctionProtoType *Proto,
4474 ArrayRef<const Expr *> Args,
4475 SourceLocation CallSiteLoc) {
4476 assert((FDecl || Proto) && "Need a function declaration or prototype");
4477
4478 // Already checked by constant evaluator.
4479 if (S.isConstantEvaluatedContext())
4480 return;
4481 // Check the attributes attached to the method/function itself.
4482 llvm::SmallBitVector NonNullArgs;
4483 if (FDecl) {
4484 // Handle the nonnull attribute on the function/method declaration itself.
4485 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4486 if (!NonNull->args_size()) {
4487 // Easy case: all pointer arguments are nonnull.
4488 for (const auto *Arg : Args)
4489 if (S.isValidPointerAttrType(T: Arg->getType()))
4490 CheckNonNullArgument(S, ArgExpr: Arg, CallSiteLoc);
4491 return;
4492 }
4493
4494 for (const ParamIdx &Idx : NonNull->args()) {
4495 unsigned IdxAST = Idx.getASTIndex();
4496 if (IdxAST >= Args.size())
4497 continue;
4498 if (NonNullArgs.empty())
4499 NonNullArgs.resize(N: Args.size());
4500 NonNullArgs.set(IdxAST);
4501 }
4502 }
4503 }
4504
4505 if (FDecl && (isa<FunctionDecl>(Val: FDecl) || isa<ObjCMethodDecl>(Val: FDecl))) {
4506 // Handle the nonnull attribute on the parameters of the
4507 // function/method.
4508 ArrayRef<ParmVarDecl*> parms;
4509 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: FDecl))
4510 parms = FD->parameters();
4511 else
4512 parms = cast<ObjCMethodDecl>(Val: FDecl)->parameters();
4513
4514 unsigned ParamIndex = 0;
4515 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4516 I != E; ++I, ++ParamIndex) {
4517 const ParmVarDecl *PVD = *I;
4518 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(type: PVD->getType())) {
4519 if (NonNullArgs.empty())
4520 NonNullArgs.resize(N: Args.size());
4521
4522 NonNullArgs.set(ParamIndex);
4523 }
4524 }
4525 } else {
4526 // If we have a non-function, non-method declaration but no
4527 // function prototype, try to dig out the function prototype.
4528 if (!Proto) {
4529 if (const ValueDecl *VD = dyn_cast<ValueDecl>(Val: FDecl)) {
4530 QualType type = VD->getType().getNonReferenceType();
4531 if (auto pointerType = type->getAs<PointerType>())
4532 type = pointerType->getPointeeType();
4533 else if (auto blockType = type->getAs<BlockPointerType>())
4534 type = blockType->getPointeeType();
4535 // FIXME: data member pointers?
4536
4537 // Dig out the function prototype, if there is one.
4538 Proto = type->getAs<FunctionProtoType>();
4539 }
4540 }
4541
4542 // Fill in non-null argument information from the nullability
4543 // information on the parameter types (if we have them).
4544 if (Proto) {
4545 unsigned Index = 0;
4546 for (auto paramType : Proto->getParamTypes()) {
4547 if (isNonNullType(type: paramType)) {
4548 if (NonNullArgs.empty())
4549 NonNullArgs.resize(N: Args.size());
4550
4551 NonNullArgs.set(Index);
4552 }
4553
4554 ++Index;
4555 }
4556 }
4557 }
4558
4559 // Check for non-null arguments.
4560 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4561 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4562 if (NonNullArgs[ArgIndex])
4563 CheckNonNullArgument(S, ArgExpr: Args[ArgIndex], CallSiteLoc: Args[ArgIndex]->getExprLoc());
4564 }
4565}
4566
4567void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4568 StringRef ParamName, QualType ArgTy,
4569 QualType ParamTy) {
4570
4571 // If a function accepts a pointer or reference type
4572 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4573 return;
4574
4575 // If the parameter is a pointer type, get the pointee type for the
4576 // argument too. If the parameter is a reference type, don't try to get
4577 // the pointee type for the argument.
4578 if (ParamTy->isPointerType())
4579 ArgTy = ArgTy->getPointeeType();
4580
4581 // Remove reference or pointer
4582 ParamTy = ParamTy->getPointeeType();
4583
4584 // Find expected alignment, and the actual alignment of the passed object.
4585 // getTypeAlignInChars requires complete types
4586 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4587 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4588 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4589 return;
4590
4591 CharUnits ParamAlign = Context.getTypeAlignInChars(T: ParamTy);
4592 CharUnits ArgAlign = Context.getTypeAlignInChars(T: ArgTy);
4593
4594 // If the argument is less aligned than the parameter, there is a
4595 // potential alignment issue.
4596 if (ArgAlign < ParamAlign)
4597 Diag(Loc, DiagID: diag::warn_param_mismatched_alignment)
4598 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4599 << ParamName << (FDecl != nullptr) << FDecl;
4600}
4601
4602void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4603 const Expr *ThisArg,
4604 ArrayRef<const Expr *> Args) {
4605 if (!FD || Args.empty())
4606 return;
4607 auto GetArgAt = [&](int Idx) -> const Expr * {
4608 if (Idx == LifetimeCaptureByAttr::Global ||
4609 Idx == LifetimeCaptureByAttr::Unknown)
4610 return nullptr;
4611 if (IsMemberFunction && Idx == 0)
4612 return ThisArg;
4613 return Args[Idx - IsMemberFunction];
4614 };
4615 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4616 unsigned ArgIdx) {
4617 if (!Attr)
4618 return;
4619
4620 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4621 for (int CapturingParamIdx : Attr->params()) {
4622 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4623 continue;
4624 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4625 // initialization codepath.
4626 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4627 isa<CXXConstructorDecl>(Val: FD))
4628 continue;
4629 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4630 CapturingEntity CE{.Entity: Capturing};
4631 // Ensure that 'Captured' outlives the 'Capturing' entity.
4632 checkCaptureByLifetime(SemaRef&: *this, Entity: CE, Init: Captured);
4633 }
4634 };
4635 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4636 for (const auto *A :
4637 FD->getParamDecl(i: I)->specific_attrs<LifetimeCaptureByAttr>())
4638 HandleCaptureByAttr(A, I + IsMemberFunction);
4639 // Check when the implicit object param is captured.
4640 if (IsMemberFunction) {
4641 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4642 if (!TSI)
4643 return;
4644 AttributedTypeLoc ATL;
4645 for (TypeLoc TL = TSI->getTypeLoc();
4646 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4647 TL = ATL.getModifiedLoc())
4648 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4649 }
4650}
4651
4652void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4653 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4654 bool IsMemberFunction, SourceLocation Loc,
4655 SourceRange Range, VariadicCallType CallType) {
4656
4657 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4658 llvm::any_of(Range&: Args, P: [](const Expr *E) {
4659 return E && E->isInstantiationDependent();
4660 }))
4661 return;
4662
4663 // Printf and scanf checking.
4664 llvm::SmallBitVector CheckedVarArgs;
4665 if (FDecl) {
4666 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4667 // Only create vector if there are format attributes.
4668 CheckedVarArgs.resize(N: Args.size());
4669 CheckFormatString(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4670 CheckedVarArgs);
4671 }
4672
4673 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4674 CheckedVarArgs.resize(N: Args.size());
4675 CheckFormatArguments(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4676 CheckedVarArgs);
4677 }
4678 }
4679
4680 // Refuse POD arguments that weren't caught by the format string
4681 // checks above.
4682 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: FDecl);
4683 if (CallType != VariadicCallType::DoesNotApply &&
4684 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4685 unsigned NumParams = Proto ? Proto->getNumParams()
4686 : isa_and_nonnull<FunctionDecl>(Val: FDecl)
4687 ? cast<FunctionDecl>(Val: FDecl)->getNumParams()
4688 : isa_and_nonnull<ObjCMethodDecl>(Val: FDecl)
4689 ? cast<ObjCMethodDecl>(Val: FDecl)->param_size()
4690 : 0;
4691
4692 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4693 // Args[ArgIdx] can be null in malformed code.
4694 if (const Expr *Arg = Args[ArgIdx]) {
4695 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4696 checkVariadicArgument(E: Arg, CT: CallType);
4697 }
4698 }
4699 }
4700 if (FD)
4701 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4702 if (FDecl || Proto) {
4703 CheckNonNullArguments(S&: *this, FDecl, Proto, Args, CallSiteLoc: Loc);
4704
4705 // Type safety checking.
4706 if (FDecl) {
4707 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4708 CheckArgumentWithTypeTag(Attr: I, ExprArgs: Args, CallSiteLoc: Loc);
4709 }
4710 }
4711
4712 // Check that passed arguments match the alignment of original arguments.
4713 // Try to get the missing prototype from the declaration.
4714 if (!Proto && FDecl) {
4715 const auto *FT = FDecl->getFunctionType();
4716 if (isa_and_nonnull<FunctionProtoType>(Val: FT))
4717 Proto = cast<FunctionProtoType>(Val: FDecl->getFunctionType());
4718 }
4719 if (Proto) {
4720 // For variadic functions, we may have more args than parameters.
4721 // For some K&R functions, we may have less args than parameters.
4722 const auto N = std::min<unsigned>(a: Proto->getNumParams(), b: Args.size());
4723 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4724 bool IsScalableArg = false;
4725 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4726 // Args[ArgIdx] can be null in malformed code.
4727 if (const Expr *Arg = Args[ArgIdx]) {
4728 if (Arg->containsErrors())
4729 continue;
4730
4731 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4732 FDecl->hasLinkage() &&
4733 FDecl->getFormalLinkage() != Linkage::Internal &&
4734 CallType == VariadicCallType::DoesNotApply)
4735 PPC().checkAIXMemberAlignment(Loc: (Arg->getExprLoc()), Arg);
4736
4737 QualType ParamTy = Proto->getParamType(i: ArgIdx);
4738 if (ParamTy->isSizelessVectorType())
4739 IsScalableArg = true;
4740 QualType ArgTy = Arg->getType();
4741 CheckArgAlignment(Loc: Arg->getExprLoc(), FDecl, ParamName: std::to_string(val: ArgIdx + 1),
4742 ArgTy, ParamTy);
4743 }
4744 }
4745
4746 // If the callee has an AArch64 SME attribute to indicate that it is an
4747 // __arm_streaming function, then the caller requires SME to be available.
4748 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
4749 if (ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask) {
4750 if (auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext)) {
4751 llvm::StringMap<bool> CallerFeatureMap;
4752 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, CallerFD);
4753 if (!CallerFeatureMap.contains(Key: "sme"))
4754 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4755 } else if (!Context.getTargetInfo().hasFeature(Feature: "sme")) {
4756 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4757 }
4758 }
4759
4760 // If the call requires a streaming-mode change and has scalable vector
4761 // arguments or return values, then warn the user that the streaming and
4762 // non-streaming vector lengths may be different.
4763 // When both streaming and non-streaming vector lengths are defined and
4764 // mismatched, produce an error.
4765 const auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext);
4766 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4767 (IsScalableArg || IsScalableRet)) {
4768 bool IsCalleeStreaming =
4769 ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
4770 bool IsCalleeStreamingCompatible =
4771 ExtInfo.AArch64SMEAttributes &
4772 FunctionType::SME_PStateSMCompatibleMask;
4773 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(FD: CallerFD);
4774 if (!IsCalleeStreamingCompatible &&
4775 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4776 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4777 const LangOptions &LO = getLangOpts();
4778 unsigned VL = LO.VScaleMin * 128;
4779 unsigned SVL = LO.VScaleStreamingMin * 128;
4780 bool IsVLMismatch = VL && SVL && VL != SVL;
4781
4782 auto EmitDiag = [&](bool IsArg) {
4783 if (IsVLMismatch) {
4784 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4785 // Emit warning for streaming-compatible callers
4786 Diag(Loc, DiagID: diag::warn_sme_streaming_compatible_vl_mismatch)
4787 << IsArg << IsCalleeStreaming << SVL << VL;
4788 else
4789 // Emit error otherwise
4790 Diag(Loc, DiagID: diag::err_sme_streaming_transition_vl_mismatch)
4791 << IsArg << SVL << VL;
4792 } else
4793 Diag(Loc, DiagID: diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4794 << IsArg;
4795 };
4796
4797 if (IsScalableArg)
4798 EmitDiag(true);
4799 if (IsScalableRet)
4800 EmitDiag(false);
4801 }
4802 }
4803
4804 FunctionType::ArmStateValue CalleeArmZAState =
4805 FunctionType::getArmZAState(AttrBits: ExtInfo.AArch64SMEAttributes);
4806 FunctionType::ArmStateValue CalleeArmZT0State =
4807 FunctionType::getArmZT0State(AttrBits: ExtInfo.AArch64SMEAttributes);
4808 if (CalleeArmZAState != FunctionType::ARM_None ||
4809 CalleeArmZT0State != FunctionType::ARM_None) {
4810 bool CallerHasZAState = false;
4811 bool CallerHasZT0State = false;
4812 if (CallerFD) {
4813 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4814 if (Attr && Attr->isNewZA())
4815 CallerHasZAState = true;
4816 if (Attr && Attr->isNewZT0())
4817 CallerHasZT0State = true;
4818 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4819 CallerHasZAState |=
4820 FunctionType::getArmZAState(
4821 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4822 FunctionType::ARM_None;
4823 CallerHasZT0State |=
4824 FunctionType::getArmZT0State(
4825 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4826 FunctionType::ARM_None;
4827 }
4828 }
4829
4830 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4831 Diag(Loc, DiagID: diag::err_sme_za_call_no_za_state);
4832
4833 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4834 Diag(Loc, DiagID: diag::err_sme_zt0_call_no_zt0_state);
4835
4836 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4837 CalleeArmZT0State != FunctionType::ARM_None) {
4838 Diag(Loc, DiagID: diag::err_sme_unimplemented_za_save_restore);
4839 Diag(Loc, DiagID: diag::note_sme_use_preserves_za);
4840 }
4841 }
4842 }
4843
4844 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4845 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4846 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4847 if (!Arg->isValueDependent()) {
4848 Expr::EvalResult Align;
4849 if (Arg->EvaluateAsInt(Result&: Align, Ctx: Context)) {
4850 const llvm::APSInt &I = Align.Val.getInt();
4851 if (!I.isPowerOf2())
4852 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_alignment_not_power_of_two)
4853 << Arg->getSourceRange();
4854
4855 if (I > Sema::MaximumAlignment)
4856 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_assume_aligned_too_great)
4857 << Arg->getSourceRange() << Sema::MaximumAlignment;
4858 }
4859 }
4860 }
4861
4862 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4863 !isUnevaluatedContext())
4864 SYCL().DiagIfDeviceCode(Loc, DiagID: diag::err_variadic_device_fn)
4865 << diag::OffloadLang::SYCL;
4866
4867 if (FD)
4868 diagnoseArgDependentDiagnoseIfAttrs(Function: FD, ThisArg, Args, Loc);
4869}
4870
4871void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4872 if (TemplateDecl *Decl =
4873 AutoT->getTypeConstraintConcept().getAsTemplateDecl()) {
4874 DiagnoseUseOfDecl(D: Decl, Locs: Loc);
4875 }
4876}
4877
4878void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4879 ArrayRef<const Expr *> Args,
4880 const FunctionProtoType *Proto,
4881 SourceLocation Loc) {
4882 VariadicCallType CallType = Proto->isVariadic()
4883 ? VariadicCallType::Constructor
4884 : VariadicCallType::DoesNotApply;
4885
4886 auto *Ctor = cast<CXXConstructorDecl>(Val: FDecl);
4887 CheckArgAlignment(
4888 Loc, FDecl, ParamName: "'this'", ArgTy: Context.getPointerType(T: ThisType),
4889 ParamTy: Context.getPointerType(T: Ctor->getFunctionObjectParameterType()));
4890
4891 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4892 Loc, Range: SourceRange(), CallType);
4893}
4894
4895bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4896 const FunctionProtoType *Proto) {
4897 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(Val: TheCall) &&
4898 isa<CXXMethodDecl>(Val: FDecl);
4899 bool IsMemberFunction = isa<CXXMemberCallExpr>(Val: TheCall) ||
4900 IsMemberOperatorCall;
4901 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4902 Fn: TheCall->getCallee());
4903 Expr** Args = TheCall->getArgs();
4904 unsigned NumArgs = TheCall->getNumArgs();
4905
4906 Expr *ImplicitThis = nullptr;
4907 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4908 // If this is a call to a member operator, hide the first
4909 // argument from checkCall.
4910 // FIXME: Our choice of AST representation here is less than ideal.
4911 ImplicitThis = Args[0];
4912 ++Args;
4913 --NumArgs;
4914 } else if (IsMemberFunction && !FDecl->isStatic() &&
4915 !FDecl->hasCXXExplicitFunctionObjectParameter())
4916 ImplicitThis =
4917 cast<CXXMemberCallExpr>(Val: TheCall)->getImplicitObjectArgument();
4918
4919 if (ImplicitThis) {
4920 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4921 // used.
4922 QualType ThisType = ImplicitThis->getType();
4923 if (!ThisType->isPointerType()) {
4924 assert(!ThisType->isReferenceType());
4925 ThisType = Context.getPointerType(T: ThisType);
4926 }
4927
4928 QualType ThisTypeFromDecl = Context.getPointerType(
4929 T: cast<CXXMethodDecl>(Val: FDecl)->getFunctionObjectParameterType());
4930
4931 CheckArgAlignment(Loc: TheCall->getRParenLoc(), FDecl, ParamName: "'this'", ArgTy: ThisType,
4932 ParamTy: ThisTypeFromDecl);
4933 }
4934
4935 checkCall(FDecl, Proto, ThisArg: ImplicitThis, Args: llvm::ArrayRef(Args, NumArgs),
4936 IsMemberFunction, Loc: TheCall->getRParenLoc(),
4937 Range: TheCall->getCallee()->getSourceRange(), CallType);
4938
4939 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4940 // None of the checks below are needed for functions that don't have
4941 // simple names (e.g., C++ conversion functions).
4942 if (!FnInfo)
4943 return false;
4944
4945 // Enforce TCB except for builtin calls, which are always allowed.
4946 if (FDecl->getBuiltinID() == 0)
4947 CheckTCBEnforcement(CallExprLoc: TheCall->getExprLoc(), Callee: FDecl);
4948
4949 CheckAbsoluteValueFunction(Call: TheCall, FDecl);
4950 CheckMaxUnsignedZero(Call: TheCall, FDecl);
4951 CheckInfNaNFunction(Call: TheCall, FDecl);
4952
4953 if (getLangOpts().ObjC)
4954 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4955
4956 unsigned CMId = FDecl->getMemoryFunctionKind();
4957
4958 // Handle memory setting and copying functions.
4959 switch (CMId) {
4960 case 0:
4961 return false;
4962 case Builtin::BIstrlcpy: // fallthrough
4963 case Builtin::BIstrlcat:
4964 CheckStrlcpycatArguments(Call: TheCall, FnName: FnInfo);
4965 break;
4966 case Builtin::BIstrncat:
4967 CheckStrncatArguments(Call: TheCall, FnName: FnInfo);
4968 break;
4969 case Builtin::BIfree:
4970 CheckFreeArguments(E: TheCall);
4971 break;
4972 default:
4973 CheckMemaccessArguments(Call: TheCall, BId: CMId, FnName: FnInfo);
4974 }
4975
4976 return false;
4977}
4978
4979bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4980 const FunctionProtoType *Proto) {
4981 QualType Ty;
4982 if (const auto *V = dyn_cast<VarDecl>(Val: NDecl))
4983 Ty = V->getType().getNonReferenceType();
4984 else if (const auto *F = dyn_cast<FieldDecl>(Val: NDecl))
4985 Ty = F->getType().getNonReferenceType();
4986 else
4987 return false;
4988
4989 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4990 !Ty->isFunctionProtoType())
4991 return false;
4992
4993 VariadicCallType CallType;
4994 if (!Proto || !Proto->isVariadic()) {
4995 CallType = VariadicCallType::DoesNotApply;
4996 } else if (Ty->isBlockPointerType()) {
4997 CallType = VariadicCallType::Block;
4998 } else { // Ty->isFunctionPointerType()
4999 CallType = VariadicCallType::Function;
5000 }
5001
5002 checkCall(FDecl: NDecl, Proto, /*ThisArg=*/nullptr,
5003 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5004 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
5005 Range: TheCall->getCallee()->getSourceRange(), CallType);
5006
5007 return false;
5008}
5009
5010bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5011 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5012 Fn: TheCall->getCallee());
5013 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5014 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5015 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
5016 Range: TheCall->getCallee()->getSourceRange(), CallType);
5017
5018 return false;
5019}
5020
5021static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5022 if (!llvm::isValidAtomicOrderingCABI(I: Ordering))
5023 return false;
5024
5025 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5026 switch (Op) {
5027 case AtomicExpr::AO__c11_atomic_init:
5028 case AtomicExpr::AO__opencl_atomic_init:
5029 llvm_unreachable("There is no ordering argument for an init");
5030
5031 case AtomicExpr::AO__c11_atomic_load:
5032 case AtomicExpr::AO__opencl_atomic_load:
5033 case AtomicExpr::AO__hip_atomic_load:
5034 case AtomicExpr::AO__atomic_load_n:
5035 case AtomicExpr::AO__atomic_load:
5036 case AtomicExpr::AO__scoped_atomic_load_n:
5037 case AtomicExpr::AO__scoped_atomic_load:
5038 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5039 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5040
5041 case AtomicExpr::AO__c11_atomic_store:
5042 case AtomicExpr::AO__opencl_atomic_store:
5043 case AtomicExpr::AO__hip_atomic_store:
5044 case AtomicExpr::AO__atomic_store:
5045 case AtomicExpr::AO__atomic_store_n:
5046 case AtomicExpr::AO__scoped_atomic_store:
5047 case AtomicExpr::AO__scoped_atomic_store_n:
5048 case AtomicExpr::AO__atomic_clear:
5049 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5050 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5051 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5052
5053 default:
5054 return true;
5055 }
5056}
5057
5058ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
5059 AtomicExpr::AtomicOp Op) {
5060 CallExpr *TheCall = cast<CallExpr>(Val: TheCallResult.get());
5061 DeclRefExpr *DRE =cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
5062 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5063 return BuildAtomicExpr(CallRange: {TheCall->getBeginLoc(), TheCall->getEndLoc()},
5064 ExprRange: DRE->getSourceRange(), RParenLoc: TheCall->getRParenLoc(), Args,
5065 Op);
5066}
5067
5068/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
5069/// equivalents. Provide a fixit when the scope is a compile-time constant and
5070/// there is a direct mapping from the HIP builtin to a Clang builtin. The
5071/// compare_exchange builtins differ in how they accept the desired value, so
5072/// only a warning (without a fixit) is emitted for those.
5073static void DiagnoseDeprecatedHIPAtomic(Sema &S, SourceRange ExprRange,
5074 MultiExprArg Args,
5075 AtomicExpr::AtomicOp Op) {
5076 StringRef OldName;
5077 StringRef NewName;
5078 bool CanFixIt;
5079
5080 switch (Op) {
5081#define HIP_ATOMIC_FIXABLE(hip, scoped) \
5082 case AtomicExpr::AO__hip_atomic_##hip: \
5083 OldName = "__hip_atomic_" #hip; \
5084 NewName = "__scoped_atomic_" #scoped; \
5085 CanFixIt = true; \
5086 break;
5087 HIP_ATOMIC_FIXABLE(load, load_n)
5088 HIP_ATOMIC_FIXABLE(store, store_n)
5089 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
5090 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
5091 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
5092 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
5093 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
5094 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
5095 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
5096 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
5097#undef HIP_ATOMIC_FIXABLE
5098 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5099 OldName = "__hip_atomic_compare_exchange_weak";
5100 NewName = "__scoped_atomic_compare_exchange";
5101 CanFixIt = false;
5102 break;
5103 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5104 OldName = "__hip_atomic_compare_exchange_strong";
5105 NewName = "__scoped_atomic_compare_exchange";
5106 CanFixIt = false;
5107 break;
5108 default:
5109 llvm_unreachable("unhandled HIP atomic op");
5110 }
5111
5112 auto DB = S.Diag(Loc: ExprRange.getBegin(), DiagID: diag::warn_hip_deprecated_builtin)
5113 << OldName << NewName;
5114 if (!CanFixIt)
5115 return;
5116
5117 DB << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: NewName);
5118
5119 Expr *Scope = Args[Args.size() - 1];
5120 std::optional<llvm::APSInt> ScopeVal =
5121 Scope->getIntegerConstantExpr(Ctx: S.Context);
5122 if (!ScopeVal)
5123 return;
5124
5125 StringRef ScopeName;
5126 switch (ScopeVal->getZExtValue()) {
5127 case AtomicScopeHIPModel::SingleThread:
5128 ScopeName = "__MEMORY_SCOPE_SINGLE";
5129 break;
5130 case AtomicScopeHIPModel::Wavefront:
5131 ScopeName = "__MEMORY_SCOPE_WVFRNT";
5132 break;
5133 case AtomicScopeHIPModel::Workgroup:
5134 ScopeName = "__MEMORY_SCOPE_WRKGRP";
5135 break;
5136 case AtomicScopeHIPModel::Agent:
5137 ScopeName = "__MEMORY_SCOPE_DEVICE";
5138 break;
5139 case AtomicScopeHIPModel::System:
5140 ScopeName = "__MEMORY_SCOPE_SYSTEM";
5141 break;
5142 case AtomicScopeHIPModel::Cluster:
5143 ScopeName = "__MEMORY_SCOPE_CLUSTR";
5144 break;
5145 default:
5146 return;
5147 }
5148
5149 DB << FixItHint::CreateReplacement(
5150 RemoveRange: CharSourceRange::getTokenRange(R: Scope->getSourceRange()), Code: ScopeName);
5151}
5152
5153ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5154 SourceLocation RParenLoc, MultiExprArg Args,
5155 AtomicExpr::AtomicOp Op,
5156 AtomicArgumentOrder ArgOrder) {
5157 // All the non-OpenCL operations take one of the following forms.
5158 // The OpenCL operations take the __c11 forms with one extra argument for
5159 // synchronization scope.
5160 enum {
5161 // C __c11_atomic_init(A *, C)
5162 Init,
5163
5164 // C __c11_atomic_load(A *, int)
5165 Load,
5166
5167 // void __atomic_load(A *, CP, int)
5168 LoadCopy,
5169
5170 // void __atomic_store(A *, CP, int)
5171 Copy,
5172
5173 // C __c11_atomic_add(A *, M, int)
5174 Arithmetic,
5175
5176 // C __atomic_exchange_n(A *, CP, int)
5177 Xchg,
5178
5179 // void __atomic_exchange(A *, C *, CP, int)
5180 GNUXchg,
5181
5182 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5183 C11CmpXchg,
5184
5185 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5186 GNUCmpXchg,
5187
5188 // bool __atomic_test_and_set(A *, int)
5189 TestAndSetByte,
5190
5191 // void __atomic_clear(A *, int)
5192 ClearByte,
5193 } Form = Init;
5194
5195 const unsigned NumForm = ClearByte + 1;
5196 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
5197 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
5198 // where:
5199 // C is an appropriate type,
5200 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5201 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5202 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5203 // the int parameters are for orderings.
5204
5205 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5206 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5207 "need to update code for modified forms");
5208 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
5209 AtomicExpr::AO__atomic_xor_fetch + 1 ==
5210 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
5211 "need to update code for modified C11 atomics");
5212 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
5213 Op <= AtomicExpr::AO__opencl_atomic_store;
5214 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
5215 Op <= AtomicExpr::AO__hip_atomic_store;
5216 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
5217 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
5218 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
5219 Op <= AtomicExpr::AO__c11_atomic_store) ||
5220 IsOpenCL;
5221 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5222 Op == AtomicExpr::AO__atomic_store_n ||
5223 Op == AtomicExpr::AO__atomic_exchange_n ||
5224 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
5225 Op == AtomicExpr::AO__scoped_atomic_load_n ||
5226 Op == AtomicExpr::AO__scoped_atomic_store_n ||
5227 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
5228 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
5229 // Bit mask for extra allowed value types other than integers for atomic
5230 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
5231 // allow floating point.
5232 enum ArithOpExtraValueType {
5233 AOEVT_None = 0,
5234 AOEVT_Pointer = 1,
5235 AOEVT_FP = 2,
5236 AOEVT_Int = 4,
5237 };
5238 unsigned ArithAllows = AOEVT_None;
5239
5240 switch (Op) {
5241 case AtomicExpr::AO__c11_atomic_init:
5242 case AtomicExpr::AO__opencl_atomic_init:
5243 Form = Init;
5244 break;
5245
5246 case AtomicExpr::AO__c11_atomic_load:
5247 case AtomicExpr::AO__opencl_atomic_load:
5248 case AtomicExpr::AO__hip_atomic_load:
5249 case AtomicExpr::AO__atomic_load_n:
5250 case AtomicExpr::AO__scoped_atomic_load_n:
5251 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5252 Form = Load;
5253 break;
5254
5255 case AtomicExpr::AO__atomic_load:
5256 case AtomicExpr::AO__scoped_atomic_load:
5257 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5258 Form = LoadCopy;
5259 break;
5260
5261 case AtomicExpr::AO__c11_atomic_store:
5262 case AtomicExpr::AO__opencl_atomic_store:
5263 case AtomicExpr::AO__hip_atomic_store:
5264 case AtomicExpr::AO__atomic_store:
5265 case AtomicExpr::AO__atomic_store_n:
5266 case AtomicExpr::AO__scoped_atomic_store:
5267 case AtomicExpr::AO__scoped_atomic_store_n:
5268 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5269 Form = Copy;
5270 break;
5271 case AtomicExpr::AO__atomic_fetch_add:
5272 case AtomicExpr::AO__atomic_fetch_sub:
5273 case AtomicExpr::AO__atomic_add_fetch:
5274 case AtomicExpr::AO__atomic_sub_fetch:
5275 case AtomicExpr::AO__scoped_atomic_fetch_add:
5276 case AtomicExpr::AO__scoped_atomic_fetch_sub:
5277 case AtomicExpr::AO__scoped_atomic_add_fetch:
5278 case AtomicExpr::AO__scoped_atomic_sub_fetch:
5279 case AtomicExpr::AO__c11_atomic_fetch_add:
5280 case AtomicExpr::AO__c11_atomic_fetch_sub:
5281 case AtomicExpr::AO__opencl_atomic_fetch_add:
5282 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5283 case AtomicExpr::AO__hip_atomic_fetch_add:
5284 case AtomicExpr::AO__hip_atomic_fetch_sub:
5285 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5286 Form = Arithmetic;
5287 break;
5288 case AtomicExpr::AO__atomic_fetch_fminimum:
5289 case AtomicExpr::AO__atomic_fetch_fmaximum:
5290 case AtomicExpr::AO__atomic_fetch_fminimum_num:
5291 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
5292 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
5293 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
5294 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
5295 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
5296 ArithAllows = AOEVT_FP;
5297 Form = Arithmetic;
5298 break;
5299 case AtomicExpr::AO__atomic_fetch_max:
5300 case AtomicExpr::AO__atomic_fetch_min:
5301 case AtomicExpr::AO__atomic_max_fetch:
5302 case AtomicExpr::AO__atomic_min_fetch:
5303 case AtomicExpr::AO__scoped_atomic_fetch_max:
5304 case AtomicExpr::AO__scoped_atomic_fetch_min:
5305 case AtomicExpr::AO__scoped_atomic_max_fetch:
5306 case AtomicExpr::AO__scoped_atomic_min_fetch:
5307 case AtomicExpr::AO__c11_atomic_fetch_max:
5308 case AtomicExpr::AO__c11_atomic_fetch_min:
5309 case AtomicExpr::AO__opencl_atomic_fetch_max:
5310 case AtomicExpr::AO__opencl_atomic_fetch_min:
5311 case AtomicExpr::AO__hip_atomic_fetch_max:
5312 case AtomicExpr::AO__hip_atomic_fetch_min:
5313 ArithAllows = AOEVT_Int | AOEVT_FP;
5314 Form = Arithmetic;
5315 break;
5316 case AtomicExpr::AO__c11_atomic_fetch_and:
5317 case AtomicExpr::AO__c11_atomic_fetch_or:
5318 case AtomicExpr::AO__c11_atomic_fetch_xor:
5319 case AtomicExpr::AO__hip_atomic_fetch_and:
5320 case AtomicExpr::AO__hip_atomic_fetch_or:
5321 case AtomicExpr::AO__hip_atomic_fetch_xor:
5322 case AtomicExpr::AO__c11_atomic_fetch_nand:
5323 case AtomicExpr::AO__opencl_atomic_fetch_and:
5324 case AtomicExpr::AO__opencl_atomic_fetch_or:
5325 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5326 case AtomicExpr::AO__atomic_fetch_and:
5327 case AtomicExpr::AO__atomic_fetch_or:
5328 case AtomicExpr::AO__atomic_fetch_xor:
5329 case AtomicExpr::AO__atomic_fetch_nand:
5330 case AtomicExpr::AO__atomic_and_fetch:
5331 case AtomicExpr::AO__atomic_or_fetch:
5332 case AtomicExpr::AO__atomic_xor_fetch:
5333 case AtomicExpr::AO__atomic_nand_fetch:
5334 case AtomicExpr::AO__atomic_fetch_uinc:
5335 case AtomicExpr::AO__atomic_fetch_udec:
5336 case AtomicExpr::AO__scoped_atomic_fetch_and:
5337 case AtomicExpr::AO__scoped_atomic_fetch_or:
5338 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5339 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5340 case AtomicExpr::AO__scoped_atomic_and_fetch:
5341 case AtomicExpr::AO__scoped_atomic_or_fetch:
5342 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5343 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5344 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5345 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5346 Form = Arithmetic;
5347 break;
5348
5349 case AtomicExpr::AO__c11_atomic_exchange:
5350 case AtomicExpr::AO__hip_atomic_exchange:
5351 case AtomicExpr::AO__opencl_atomic_exchange:
5352 case AtomicExpr::AO__atomic_exchange_n:
5353 case AtomicExpr::AO__scoped_atomic_exchange_n:
5354 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5355 Form = Xchg;
5356 break;
5357
5358 case AtomicExpr::AO__atomic_exchange:
5359 case AtomicExpr::AO__scoped_atomic_exchange:
5360 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5361 Form = GNUXchg;
5362 break;
5363
5364 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5365 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5366 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5367 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5368 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5369 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5370 Form = C11CmpXchg;
5371 break;
5372
5373 case AtomicExpr::AO__atomic_compare_exchange:
5374 case AtomicExpr::AO__atomic_compare_exchange_n:
5375 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5376 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5377 ArithAllows = AOEVT_Pointer;
5378 Form = GNUCmpXchg;
5379 break;
5380
5381 case AtomicExpr::AO__atomic_test_and_set:
5382 Form = TestAndSetByte;
5383 break;
5384
5385 case AtomicExpr::AO__atomic_clear:
5386 Form = ClearByte;
5387 break;
5388 }
5389
5390 unsigned AdjustedNumArgs = NumArgs[Form];
5391 if ((IsOpenCL || IsHIP || IsScoped) &&
5392 Op != AtomicExpr::AO__opencl_atomic_init)
5393 ++AdjustedNumArgs;
5394 // Check we have the right number of arguments.
5395 if (Args.size() < AdjustedNumArgs) {
5396 Diag(Loc: CallRange.getEnd(), DiagID: diag::err_typecheck_call_too_few_args)
5397 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5398 << /*is non object*/ 0 << ExprRange;
5399 return ExprError();
5400 } else if (Args.size() > AdjustedNumArgs) {
5401 Diag(Loc: Args[AdjustedNumArgs]->getBeginLoc(),
5402 DiagID: diag::err_typecheck_call_too_many_args)
5403 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5404 << /*is non object*/ 0 << ExprRange;
5405 return ExprError();
5406 }
5407
5408 // Inspect the first argument of the atomic operation.
5409 Expr *Ptr = Args[0];
5410 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(E: Ptr);
5411 if (ConvertedPtr.isInvalid())
5412 return ExprError();
5413
5414 Ptr = ConvertedPtr.get();
5415 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5416 if (!pointerType) {
5417 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5418 << Ptr->getType() << 0 << Ptr->getSourceRange();
5419 return ExprError();
5420 }
5421
5422 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5423 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5424 QualType ValType = AtomTy; // 'C'
5425 if (IsC11) {
5426 if (!AtomTy->isAtomicType()) {
5427 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_atomic)
5428 << Ptr->getType() << Ptr->getSourceRange();
5429 return ExprError();
5430 }
5431 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5432 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5433 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_atomic)
5434 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5435 << Ptr->getSourceRange();
5436 return ExprError();
5437 }
5438 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5439 } else if (Form != Load && Form != LoadCopy) {
5440 if (ValType.isConstQualified()) {
5441 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_pointer)
5442 << Ptr->getType() << Ptr->getSourceRange();
5443 return ExprError();
5444 }
5445 }
5446
5447 if (Form != TestAndSetByte && Form != ClearByte) {
5448 // Pointer to object of size zero is not allowed.
5449 if (RequireCompleteType(Loc: Ptr->getBeginLoc(), T: AtomTy,
5450 DiagID: diag::err_incomplete_type))
5451 return ExprError();
5452
5453 if (Context.getTypeInfoInChars(T: AtomTy).Width.isZero()) {
5454 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5455 << Ptr->getType() << 1 << Ptr->getSourceRange();
5456 return ExprError();
5457 }
5458 } else {
5459 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5460 // non-const pointer type, including void* and pointers to incomplete
5461 // structs, but only access the first byte.
5462 AtomTy = Context.CharTy;
5463 AtomTy = AtomTy.withCVRQualifiers(
5464 CVR: pointerType->getPointeeType().getCVRQualifiers());
5465 QualType PointerQT = Context.getPointerType(T: AtomTy);
5466 pointerType = PointerQT->getAs<PointerType>();
5467 Ptr = ImpCastExprToType(E: Ptr, Type: PointerQT, CK: CK_BitCast).get();
5468 ValType = AtomTy;
5469 }
5470
5471 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5472 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5473 Diag(Loc: ExprRange.getBegin(),
5474 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5475 << 0 << Ptr->getType() << Ptr->getSourceRange();
5476 return ExprError();
5477 }
5478
5479 // For an arithmetic operation, the implied arithmetic must be well-formed.
5480 // For _n operations, the value type must also be a valid atomic type.
5481 if (Form == Arithmetic || IsN) {
5482 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5483 // trivial type errors.
5484 auto IsAllowedValueType = [&](QualType ValType,
5485 unsigned AllowedType) -> bool {
5486 bool IsX87LongDouble =
5487 ValType->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
5488 &Context.getTargetInfo().getLongDoubleFormat() ==
5489 &llvm::APFloat::x87DoubleExtended();
5490 if (ValType->isIntegerType())
5491 // Special case: f-prefixed operations (AOEVT_FP exactly) reject
5492 // integers. Explicit AOEVT_Int or other combinations allow integers.
5493 return (AllowedType & AOEVT_Int) || AllowedType != AOEVT_FP;
5494 if (ValType->isPointerType())
5495 return AllowedType & AOEVT_Pointer;
5496 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5497 return false;
5498 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5499 if (IsX87LongDouble)
5500 return false;
5501 return true;
5502 };
5503 if (!IsAllowedValueType(ValType, ArithAllows)) {
5504 auto DID =
5505 ArithAllows == AOEVT_FP
5506 ? diag::err_atomic_op_needs_atomic_fp
5507 : (ArithAllows & AOEVT_FP
5508 ? (ArithAllows & AOEVT_Pointer
5509 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5510 : diag::err_atomic_op_needs_atomic_int_or_fp)
5511 : (ArithAllows & AOEVT_Pointer
5512 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5513 : diag::err_atomic_op_needs_atomic_int));
5514 Diag(Loc: ExprRange.getBegin(), DiagID: DID)
5515 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5516 return ExprError();
5517 }
5518 if (IsC11 && ValType->isPointerType() &&
5519 RequireCompleteType(Loc: Ptr->getBeginLoc(), T: ValType->getPointeeType(),
5520 DiagID: diag::err_incomplete_type)) {
5521 return ExprError();
5522 }
5523 }
5524
5525 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5526 !AtomTy->isScalarType()) {
5527 // For GNU atomics, require a trivially-copyable type. This is not part of
5528 // the GNU atomics specification but we enforce it for consistency with
5529 // other atomics which generally all require a trivially-copyable type. This
5530 // is because atomics just copy bits.
5531 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_trivial_copy)
5532 << Ptr->getType() << Ptr->getSourceRange();
5533 return ExprError();
5534 }
5535
5536 switch (ValType.getObjCLifetime()) {
5537 case Qualifiers::OCL_None:
5538 case Qualifiers::OCL_ExplicitNone:
5539 // okay
5540 break;
5541
5542 case Qualifiers::OCL_Weak:
5543 case Qualifiers::OCL_Strong:
5544 case Qualifiers::OCL_Autoreleasing:
5545 // FIXME: Can this happen? By this point, ValType should be known
5546 // to be trivially copyable.
5547 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_arc_atomic_ownership)
5548 << ValType << Ptr->getSourceRange();
5549 return ExprError();
5550 }
5551
5552 // All atomic operations have an overload which takes a pointer to a volatile
5553 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5554 // into the result or the other operands. Similarly atomic_load takes a
5555 // pointer to a const 'A'.
5556 ValType.removeLocalVolatile();
5557 ValType.removeLocalConst();
5558 QualType ResultType = ValType;
5559 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5560 Form == ClearByte)
5561 ResultType = Context.VoidTy;
5562 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5563 ResultType = Context.BoolTy;
5564
5565 // The type of a parameter passed 'by value'. In the GNU atomics, such
5566 // arguments are actually passed as pointers.
5567 QualType ByValType = ValType; // 'CP'
5568 bool IsPassedByAddress = false;
5569 if (!IsC11 && !IsHIP && !IsN) {
5570 ByValType = Ptr->getType();
5571 IsPassedByAddress = true;
5572 }
5573
5574 SmallVector<Expr *, 5> APIOrderedArgs;
5575 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5576 APIOrderedArgs.push_back(Elt: Args[0]);
5577 switch (Form) {
5578 case Init:
5579 case Load:
5580 APIOrderedArgs.push_back(Elt: Args[1]); // Val1/Order
5581 break;
5582 case LoadCopy:
5583 case Copy:
5584 case Arithmetic:
5585 case Xchg:
5586 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5587 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5588 break;
5589 case GNUXchg:
5590 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5591 APIOrderedArgs.push_back(Elt: Args[3]); // Val2
5592 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5593 break;
5594 case C11CmpXchg:
5595 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5596 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
5597 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5598 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
5599 break;
5600 case GNUCmpXchg:
5601 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5602 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
5603 APIOrderedArgs.push_back(Elt: Args[5]); // Weak
5604 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5605 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
5606 break;
5607 case TestAndSetByte:
5608 case ClearByte:
5609 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5610 break;
5611 }
5612 } else
5613 APIOrderedArgs.append(in_start: Args.begin(), in_end: Args.end());
5614
5615 // The first argument's non-CV pointer type is used to deduce the type of
5616 // subsequent arguments, except for:
5617 // - weak flag (always converted to bool)
5618 // - memory order (always converted to int)
5619 // - scope (always converted to int)
5620 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5621 QualType Ty;
5622 if (i < NumVals[Form] + 1) {
5623 switch (i) {
5624 case 0:
5625 // The first argument is always a pointer. It has a fixed type.
5626 // It is always dereferenced, a nullptr is undefined.
5627 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5628 // Nothing else to do: we already know all we want about this pointer.
5629 continue;
5630 case 1:
5631 // The second argument is the non-atomic operand. For arithmetic, this
5632 // is always passed by value, and for a compare_exchange it is always
5633 // passed by address. For the rest, GNU uses by-address and C11 uses
5634 // by-value.
5635 assert(Form != Load);
5636 if (Form == Arithmetic && ValType->isPointerType())
5637 Ty = Context.getPointerDiffType();
5638 else if (Form == Init || Form == Arithmetic)
5639 Ty = ValType;
5640 else if (Form == Copy || Form == Xchg) {
5641 if (IsPassedByAddress) {
5642 // The value pointer is always dereferenced, a nullptr is undefined.
5643 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i],
5644 CallSiteLoc: ExprRange.getBegin());
5645 }
5646 Ty = ByValType;
5647 } else {
5648 Expr *ValArg = APIOrderedArgs[i];
5649 // The value pointer is always dereferenced, a nullptr is undefined.
5650 CheckNonNullArgument(S&: *this, ArgExpr: ValArg, CallSiteLoc: ExprRange.getBegin());
5651 LangAS AS = LangAS::Default;
5652 // Keep address space of non-atomic pointer type.
5653 if (const PointerType *PtrTy =
5654 ValArg->getType()->getAs<PointerType>()) {
5655 AS = PtrTy->getPointeeType().getAddressSpace();
5656 }
5657 Ty = Context.getPointerType(
5658 T: Context.getAddrSpaceQualType(T: ValType.getUnqualifiedType(), AddressSpace: AS));
5659 }
5660 break;
5661 case 2:
5662 // The third argument to compare_exchange / GNU exchange is the desired
5663 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5664 if (IsPassedByAddress)
5665 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5666 Ty = ByValType;
5667 break;
5668 case 3:
5669 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5670 Ty = Context.BoolTy;
5671 break;
5672 }
5673 } else {
5674 // The order(s) and scope are always converted to int.
5675 Ty = Context.IntTy;
5676 }
5677
5678 InitializedEntity Entity =
5679 InitializedEntity::InitializeParameter(Context, Type: Ty, Consumed: false);
5680 ExprResult Arg = APIOrderedArgs[i];
5681 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5682 if (Arg.isInvalid())
5683 return true;
5684 APIOrderedArgs[i] = Arg.get();
5685 }
5686
5687 // Permute the arguments into a 'consistent' order.
5688 SmallVector<Expr*, 5> SubExprs;
5689 SubExprs.push_back(Elt: Ptr);
5690 switch (Form) {
5691 case Init:
5692 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5693 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5694 break;
5695 case Load:
5696 case TestAndSetByte:
5697 case ClearByte:
5698 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Order
5699 break;
5700 case LoadCopy:
5701 case Copy:
5702 case Arithmetic:
5703 case Xchg:
5704 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Order
5705 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5706 break;
5707 case GNUXchg:
5708 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5709 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5710 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5711 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5712 break;
5713 case C11CmpXchg:
5714 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5715 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5716 SubExprs.push_back(Elt: APIOrderedArgs[4]); // OrderFail
5717 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5718 break;
5719 case GNUCmpXchg:
5720 SubExprs.push_back(Elt: APIOrderedArgs[4]); // Order
5721 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5722 SubExprs.push_back(Elt: APIOrderedArgs[5]); // OrderFail
5723 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5724 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Weak
5725 break;
5726 }
5727
5728 // If the memory orders are constants, check they are valid.
5729 if (SubExprs.size() >= 2 && Form != Init) {
5730 std::optional<llvm::APSInt> Success =
5731 SubExprs[1]->getIntegerConstantExpr(Ctx: Context);
5732 if (Success && !isValidOrderingForOp(Ordering: Success->getSExtValue(), Op)) {
5733 Diag(Loc: SubExprs[1]->getBeginLoc(),
5734 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5735 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5736 << SubExprs[1]->getSourceRange();
5737 }
5738 if (SubExprs.size() >= 5) {
5739 if (std::optional<llvm::APSInt> Failure =
5740 SubExprs[3]->getIntegerConstantExpr(Ctx: Context)) {
5741 if (!llvm::is_contained(
5742 Set: {llvm::AtomicOrderingCABI::relaxed,
5743 llvm::AtomicOrderingCABI::consume,
5744 llvm::AtomicOrderingCABI::acquire,
5745 llvm::AtomicOrderingCABI::seq_cst},
5746 Element: (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5747 Diag(Loc: SubExprs[3]->getBeginLoc(),
5748 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5749 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5750 }
5751 }
5752 }
5753 }
5754
5755 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5756 auto *Scope = Args[Args.size() - 1];
5757 if (std::optional<llvm::APSInt> Result =
5758 Scope->getIntegerConstantExpr(Ctx: Context)) {
5759 if (!ScopeModel->isValid(S: Result->getZExtValue()))
5760 Diag(Loc: Scope->getBeginLoc(), DiagID: diag::err_atomic_op_has_invalid_sync_scope)
5761 << Scope->getSourceRange();
5762 }
5763 SubExprs.push_back(Elt: Scope);
5764 }
5765
5766 if (IsHIP)
5767 DiagnoseDeprecatedHIPAtomic(S&: *this, ExprRange, Args, Op);
5768
5769 AtomicExpr *AE = new (Context)
5770 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5771
5772 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5773 Op == AtomicExpr::AO__c11_atomic_store ||
5774 Op == AtomicExpr::AO__opencl_atomic_load ||
5775 Op == AtomicExpr::AO__hip_atomic_load ||
5776 Op == AtomicExpr::AO__opencl_atomic_store ||
5777 Op == AtomicExpr::AO__hip_atomic_store) &&
5778 Context.AtomicUsesUnsupportedLibcall(E: AE))
5779 Diag(Loc: AE->getBeginLoc(), DiagID: diag::err_atomic_load_store_uses_lib)
5780 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5781 Op == AtomicExpr::AO__opencl_atomic_load ||
5782 Op == AtomicExpr::AO__hip_atomic_load)
5783 ? 0
5784 : 1);
5785
5786 if (ValType->isBitIntType()) {
5787 Diag(Loc: Ptr->getExprLoc(), DiagID: diag::err_atomic_builtin_bit_int_prohibit);
5788 return ExprError();
5789 }
5790
5791 return AE;
5792}
5793
5794/// checkBuiltinArgument - Given a call to a builtin function, perform
5795/// normal type-checking on the given argument, updating the call in
5796/// place. This is useful when a builtin function requires custom
5797/// type-checking for some of its arguments but not necessarily all of
5798/// them.
5799///
5800/// Returns true on error.
5801static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5802 FunctionDecl *Fn = E->getDirectCallee();
5803 assert(Fn && "builtin call without direct callee!");
5804
5805 ParmVarDecl *Param = Fn->getParamDecl(i: ArgIndex);
5806 InitializedEntity Entity =
5807 InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Param);
5808
5809 ExprResult Arg = E->getArg(Arg: ArgIndex);
5810 Arg = S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5811 if (Arg.isInvalid())
5812 return true;
5813
5814 E->setArg(Arg: ArgIndex, ArgExpr: Arg.get());
5815 return false;
5816}
5817
5818ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5819 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5820 Expr *Callee = TheCall->getCallee();
5821 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Callee->IgnoreParenCasts());
5822 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
5823
5824 // Ensure that we have at least one argument to do type inference from.
5825 if (TheCall->getNumArgs() < 1) {
5826 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5827 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5828 << Callee->getSourceRange();
5829 return ExprError();
5830 }
5831
5832 // Inspect the first argument of the atomic builtin. This should always be
5833 // a pointer type, whose element is an integral scalar or pointer type.
5834 // Because it is a pointer type, we don't have to worry about any implicit
5835 // casts here.
5836 // FIXME: We don't allow floating point scalars as input.
5837 Expr *FirstArg = TheCall->getArg(Arg: 0);
5838 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(E: FirstArg);
5839 if (FirstArgResult.isInvalid())
5840 return ExprError();
5841 FirstArg = FirstArgResult.get();
5842 TheCall->setArg(Arg: 0, ArgExpr: FirstArg);
5843
5844 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5845 if (!pointerType) {
5846 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5847 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5848 return ExprError();
5849 }
5850
5851 QualType ValType = pointerType->getPointeeType();
5852 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5853 !ValType->isBlockPointerType()) {
5854 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer_intptr)
5855 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5856 return ExprError();
5857 }
5858 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5859 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5860 Diag(Loc: FirstArg->getBeginLoc(),
5861 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5862 << 1 << ValType << FirstArg->getSourceRange();
5863 return ExprError();
5864 }
5865
5866 if (ValType.isConstQualified()) {
5867 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_cannot_be_const)
5868 << FirstArg->getType() << FirstArg->getSourceRange();
5869 return ExprError();
5870 }
5871
5872 switch (ValType.getObjCLifetime()) {
5873 case Qualifiers::OCL_None:
5874 case Qualifiers::OCL_ExplicitNone:
5875 // okay
5876 break;
5877
5878 case Qualifiers::OCL_Weak:
5879 case Qualifiers::OCL_Strong:
5880 case Qualifiers::OCL_Autoreleasing:
5881 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_arc_atomic_ownership)
5882 << ValType << FirstArg->getSourceRange();
5883
5884 return ExprError();
5885 }
5886
5887 // Strip any qualifiers off ValType.
5888 ValType = ValType.getUnqualifiedType();
5889
5890 // The majority of builtins return a value, but a few have special return
5891 // types, so allow them to override appropriately below.
5892 QualType ResultType = ValType;
5893
5894 // We need to figure out which concrete builtin this maps onto. For example,
5895 // __sync_fetch_and_add with a 2 byte object turns into
5896 // __sync_fetch_and_add_2.
5897#define BUILTIN_ROW(x) \
5898 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5899 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5900
5901 static const unsigned BuiltinIndices[][5] = {
5902 BUILTIN_ROW(__sync_fetch_and_add),
5903 BUILTIN_ROW(__sync_fetch_and_sub),
5904 BUILTIN_ROW(__sync_fetch_and_or),
5905 BUILTIN_ROW(__sync_fetch_and_and),
5906 BUILTIN_ROW(__sync_fetch_and_xor),
5907 BUILTIN_ROW(__sync_fetch_and_nand),
5908
5909 BUILTIN_ROW(__sync_add_and_fetch),
5910 BUILTIN_ROW(__sync_sub_and_fetch),
5911 BUILTIN_ROW(__sync_and_and_fetch),
5912 BUILTIN_ROW(__sync_or_and_fetch),
5913 BUILTIN_ROW(__sync_xor_and_fetch),
5914 BUILTIN_ROW(__sync_nand_and_fetch),
5915
5916 BUILTIN_ROW(__sync_val_compare_and_swap),
5917 BUILTIN_ROW(__sync_bool_compare_and_swap),
5918 BUILTIN_ROW(__sync_lock_test_and_set),
5919 BUILTIN_ROW(__sync_lock_release),
5920 BUILTIN_ROW(__sync_swap)
5921 };
5922#undef BUILTIN_ROW
5923
5924 // Determine the index of the size.
5925 unsigned SizeIndex;
5926 switch (Context.getTypeSizeInChars(T: ValType).getQuantity()) {
5927 case 1: SizeIndex = 0; break;
5928 case 2: SizeIndex = 1; break;
5929 case 4: SizeIndex = 2; break;
5930 case 8: SizeIndex = 3; break;
5931 case 16: SizeIndex = 4; break;
5932 default:
5933 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_pointer_size)
5934 << FirstArg->getType() << FirstArg->getSourceRange();
5935 return ExprError();
5936 }
5937
5938 // Each of these builtins has one pointer argument, followed by some number of
5939 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5940 // that we ignore. Find out which row of BuiltinIndices to read from as well
5941 // as the number of fixed args.
5942 unsigned BuiltinID = FDecl->getBuiltinID();
5943 unsigned BuiltinIndex, NumFixed = 1;
5944 bool WarnAboutSemanticsChange = false;
5945 switch (BuiltinID) {
5946 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5947 case Builtin::BI__sync_fetch_and_add:
5948 case Builtin::BI__sync_fetch_and_add_1:
5949 case Builtin::BI__sync_fetch_and_add_2:
5950 case Builtin::BI__sync_fetch_and_add_4:
5951 case Builtin::BI__sync_fetch_and_add_8:
5952 case Builtin::BI__sync_fetch_and_add_16:
5953 BuiltinIndex = 0;
5954 break;
5955
5956 case Builtin::BI__sync_fetch_and_sub:
5957 case Builtin::BI__sync_fetch_and_sub_1:
5958 case Builtin::BI__sync_fetch_and_sub_2:
5959 case Builtin::BI__sync_fetch_and_sub_4:
5960 case Builtin::BI__sync_fetch_and_sub_8:
5961 case Builtin::BI__sync_fetch_and_sub_16:
5962 BuiltinIndex = 1;
5963 break;
5964
5965 case Builtin::BI__sync_fetch_and_or:
5966 case Builtin::BI__sync_fetch_and_or_1:
5967 case Builtin::BI__sync_fetch_and_or_2:
5968 case Builtin::BI__sync_fetch_and_or_4:
5969 case Builtin::BI__sync_fetch_and_or_8:
5970 case Builtin::BI__sync_fetch_and_or_16:
5971 BuiltinIndex = 2;
5972 break;
5973
5974 case Builtin::BI__sync_fetch_and_and:
5975 case Builtin::BI__sync_fetch_and_and_1:
5976 case Builtin::BI__sync_fetch_and_and_2:
5977 case Builtin::BI__sync_fetch_and_and_4:
5978 case Builtin::BI__sync_fetch_and_and_8:
5979 case Builtin::BI__sync_fetch_and_and_16:
5980 BuiltinIndex = 3;
5981 break;
5982
5983 case Builtin::BI__sync_fetch_and_xor:
5984 case Builtin::BI__sync_fetch_and_xor_1:
5985 case Builtin::BI__sync_fetch_and_xor_2:
5986 case Builtin::BI__sync_fetch_and_xor_4:
5987 case Builtin::BI__sync_fetch_and_xor_8:
5988 case Builtin::BI__sync_fetch_and_xor_16:
5989 BuiltinIndex = 4;
5990 break;
5991
5992 case Builtin::BI__sync_fetch_and_nand:
5993 case Builtin::BI__sync_fetch_and_nand_1:
5994 case Builtin::BI__sync_fetch_and_nand_2:
5995 case Builtin::BI__sync_fetch_and_nand_4:
5996 case Builtin::BI__sync_fetch_and_nand_8:
5997 case Builtin::BI__sync_fetch_and_nand_16:
5998 BuiltinIndex = 5;
5999 WarnAboutSemanticsChange = true;
6000 break;
6001
6002 case Builtin::BI__sync_add_and_fetch:
6003 case Builtin::BI__sync_add_and_fetch_1:
6004 case Builtin::BI__sync_add_and_fetch_2:
6005 case Builtin::BI__sync_add_and_fetch_4:
6006 case Builtin::BI__sync_add_and_fetch_8:
6007 case Builtin::BI__sync_add_and_fetch_16:
6008 BuiltinIndex = 6;
6009 break;
6010
6011 case Builtin::BI__sync_sub_and_fetch:
6012 case Builtin::BI__sync_sub_and_fetch_1:
6013 case Builtin::BI__sync_sub_and_fetch_2:
6014 case Builtin::BI__sync_sub_and_fetch_4:
6015 case Builtin::BI__sync_sub_and_fetch_8:
6016 case Builtin::BI__sync_sub_and_fetch_16:
6017 BuiltinIndex = 7;
6018 break;
6019
6020 case Builtin::BI__sync_and_and_fetch:
6021 case Builtin::BI__sync_and_and_fetch_1:
6022 case Builtin::BI__sync_and_and_fetch_2:
6023 case Builtin::BI__sync_and_and_fetch_4:
6024 case Builtin::BI__sync_and_and_fetch_8:
6025 case Builtin::BI__sync_and_and_fetch_16:
6026 BuiltinIndex = 8;
6027 break;
6028
6029 case Builtin::BI__sync_or_and_fetch:
6030 case Builtin::BI__sync_or_and_fetch_1:
6031 case Builtin::BI__sync_or_and_fetch_2:
6032 case Builtin::BI__sync_or_and_fetch_4:
6033 case Builtin::BI__sync_or_and_fetch_8:
6034 case Builtin::BI__sync_or_and_fetch_16:
6035 BuiltinIndex = 9;
6036 break;
6037
6038 case Builtin::BI__sync_xor_and_fetch:
6039 case Builtin::BI__sync_xor_and_fetch_1:
6040 case Builtin::BI__sync_xor_and_fetch_2:
6041 case Builtin::BI__sync_xor_and_fetch_4:
6042 case Builtin::BI__sync_xor_and_fetch_8:
6043 case Builtin::BI__sync_xor_and_fetch_16:
6044 BuiltinIndex = 10;
6045 break;
6046
6047 case Builtin::BI__sync_nand_and_fetch:
6048 case Builtin::BI__sync_nand_and_fetch_1:
6049 case Builtin::BI__sync_nand_and_fetch_2:
6050 case Builtin::BI__sync_nand_and_fetch_4:
6051 case Builtin::BI__sync_nand_and_fetch_8:
6052 case Builtin::BI__sync_nand_and_fetch_16:
6053 BuiltinIndex = 11;
6054 WarnAboutSemanticsChange = true;
6055 break;
6056
6057 case Builtin::BI__sync_val_compare_and_swap:
6058 case Builtin::BI__sync_val_compare_and_swap_1:
6059 case Builtin::BI__sync_val_compare_and_swap_2:
6060 case Builtin::BI__sync_val_compare_and_swap_4:
6061 case Builtin::BI__sync_val_compare_and_swap_8:
6062 case Builtin::BI__sync_val_compare_and_swap_16:
6063 BuiltinIndex = 12;
6064 NumFixed = 2;
6065 break;
6066
6067 case Builtin::BI__sync_bool_compare_and_swap:
6068 case Builtin::BI__sync_bool_compare_and_swap_1:
6069 case Builtin::BI__sync_bool_compare_and_swap_2:
6070 case Builtin::BI__sync_bool_compare_and_swap_4:
6071 case Builtin::BI__sync_bool_compare_and_swap_8:
6072 case Builtin::BI__sync_bool_compare_and_swap_16:
6073 BuiltinIndex = 13;
6074 NumFixed = 2;
6075 ResultType = Context.BoolTy;
6076 break;
6077
6078 case Builtin::BI__sync_lock_test_and_set:
6079 case Builtin::BI__sync_lock_test_and_set_1:
6080 case Builtin::BI__sync_lock_test_and_set_2:
6081 case Builtin::BI__sync_lock_test_and_set_4:
6082 case Builtin::BI__sync_lock_test_and_set_8:
6083 case Builtin::BI__sync_lock_test_and_set_16:
6084 BuiltinIndex = 14;
6085 break;
6086
6087 case Builtin::BI__sync_lock_release:
6088 case Builtin::BI__sync_lock_release_1:
6089 case Builtin::BI__sync_lock_release_2:
6090 case Builtin::BI__sync_lock_release_4:
6091 case Builtin::BI__sync_lock_release_8:
6092 case Builtin::BI__sync_lock_release_16:
6093 BuiltinIndex = 15;
6094 NumFixed = 0;
6095 ResultType = Context.VoidTy;
6096 break;
6097
6098 case Builtin::BI__sync_swap:
6099 case Builtin::BI__sync_swap_1:
6100 case Builtin::BI__sync_swap_2:
6101 case Builtin::BI__sync_swap_4:
6102 case Builtin::BI__sync_swap_8:
6103 case Builtin::BI__sync_swap_16:
6104 BuiltinIndex = 16;
6105 break;
6106 }
6107
6108 // Now that we know how many fixed arguments we expect, first check that we
6109 // have at least that many.
6110 if (TheCall->getNumArgs() < 1+NumFixed) {
6111 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
6112 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
6113 << Callee->getSourceRange();
6114 return ExprError();
6115 }
6116
6117 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
6118 << Callee->getSourceRange();
6119
6120 if (WarnAboutSemanticsChange) {
6121 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_sync_fetch_and_nand_semantics_change)
6122 << Callee->getSourceRange();
6123 }
6124
6125 // Get the decl for the concrete builtin from this, we can tell what the
6126 // concrete integer type we should convert to is.
6127 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6128 std::string NewBuiltinName = Context.BuiltinInfo.getName(ID: NewBuiltinID);
6129 FunctionDecl *NewBuiltinDecl;
6130 if (NewBuiltinID == BuiltinID)
6131 NewBuiltinDecl = FDecl;
6132 else {
6133 // Perform builtin lookup to avoid redeclaring it.
6134 DeclarationName DN(&Context.Idents.get(Name: NewBuiltinName));
6135 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6136 LookupName(R&: Res, S: TUScope, /*AllowBuiltinCreation=*/true);
6137 assert(Res.getFoundDecl());
6138 NewBuiltinDecl = dyn_cast<FunctionDecl>(Val: Res.getFoundDecl());
6139 if (!NewBuiltinDecl)
6140 return ExprError();
6141 }
6142
6143 // The first argument --- the pointer --- has a fixed type; we
6144 // deduce the types of the rest of the arguments accordingly. Walk
6145 // the remaining arguments, converting them to the deduced value type.
6146 for (unsigned i = 0; i != NumFixed; ++i) {
6147 ExprResult Arg = TheCall->getArg(Arg: i+1);
6148
6149 // GCC does an implicit conversion to the pointer or integer ValType. This
6150 // can fail in some cases (1i -> int**), check for this error case now.
6151 // Initialize the argument.
6152 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6153 Type: ValType, /*consume*/ Consumed: false);
6154 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
6155 if (Arg.isInvalid())
6156 return ExprError();
6157
6158 // Okay, we have something that *can* be converted to the right type. Check
6159 // to see if there is a potentially weird extension going on here. This can
6160 // happen when you do an atomic operation on something like an char* and
6161 // pass in 42. The 42 gets converted to char. This is even more strange
6162 // for things like 45.123 -> char, etc.
6163 // FIXME: Do this check.
6164 TheCall->setArg(Arg: i+1, ArgExpr: Arg.get());
6165 }
6166
6167 // Create a new DeclRefExpr to refer to the new decl.
6168 DeclRefExpr *NewDRE = DeclRefExpr::Create(
6169 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: NewBuiltinDecl,
6170 /*enclosing*/ RefersToEnclosingVariableOrCapture: false, NameLoc: DRE->getLocation(), T: Context.BuiltinFnTy,
6171 VK: DRE->getValueKind(), FoundD: nullptr, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
6172
6173 // Set the callee in the CallExpr.
6174 // FIXME: This loses syntactic information.
6175 QualType CalleePtrTy = Context.getPointerType(T: NewBuiltinDecl->getType());
6176 ExprResult PromotedCall = ImpCastExprToType(E: NewDRE, Type: CalleePtrTy,
6177 CK: CK_BuiltinFnToFnPtr);
6178 TheCall->setCallee(PromotedCall.get());
6179
6180 // Change the result type of the call to match the original value type. This
6181 // is arbitrary, but the codegen for these builtins ins design to handle it
6182 // gracefully.
6183 TheCall->setType(ResultType);
6184
6185 // Prohibit problematic uses of bit-precise integer types with atomic
6186 // builtins. The arguments would have already been converted to the first
6187 // argument's type, so only need to check the first argument.
6188 const auto *BitIntValType = ValType->getAs<BitIntType>();
6189 if (BitIntValType && !llvm::isPowerOf2_64(Value: BitIntValType->getNumBits())) {
6190 Diag(Loc: FirstArg->getExprLoc(), DiagID: diag::err_atomic_builtin_ext_int_size);
6191 return ExprError();
6192 }
6193
6194 return TheCallResult;
6195}
6196
6197ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6198 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6199 DeclRefExpr *DRE =
6200 cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
6201 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
6202 unsigned BuiltinID = FDecl->getBuiltinID();
6203 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6204 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6205 "Unexpected nontemporal load/store builtin!");
6206 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6207 unsigned numArgs = isStore ? 2 : 1;
6208
6209 // Ensure that we have the proper number of arguments.
6210 if (checkArgCount(Call: TheCall, DesiredArgCount: numArgs))
6211 return ExprError();
6212
6213 // Inspect the last argument of the nontemporal builtin. This should always
6214 // be a pointer type, from which we imply the type of the memory access.
6215 // Because it is a pointer type, we don't have to worry about any implicit
6216 // casts here.
6217 Expr *PointerArg = TheCall->getArg(Arg: numArgs - 1);
6218 ExprResult PointerArgResult =
6219 DefaultFunctionArrayLvalueConversion(E: PointerArg);
6220
6221 if (PointerArgResult.isInvalid())
6222 return ExprError();
6223 PointerArg = PointerArgResult.get();
6224 TheCall->setArg(Arg: numArgs - 1, ArgExpr: PointerArg);
6225
6226 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6227 if (!pointerType) {
6228 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_nontemporal_builtin_must_be_pointer)
6229 << PointerArg->getType() << PointerArg->getSourceRange();
6230 return ExprError();
6231 }
6232
6233 QualType ValType = pointerType->getPointeeType();
6234
6235 // Strip any qualifiers off ValType.
6236 ValType = ValType.getUnqualifiedType();
6237 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6238 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6239 !ValType->isVectorType()) {
6240 Diag(Loc: DRE->getBeginLoc(),
6241 DiagID: diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6242 << PointerArg->getType() << PointerArg->getSourceRange();
6243 return ExprError();
6244 }
6245
6246 if (!isStore) {
6247 TheCall->setType(ValType);
6248 return TheCallResult;
6249 }
6250
6251 ExprResult ValArg = TheCall->getArg(Arg: 0);
6252 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6253 Context, Type: ValType, /*consume*/ Consumed: false);
6254 ValArg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: ValArg);
6255 if (ValArg.isInvalid())
6256 return ExprError();
6257
6258 TheCall->setArg(Arg: 0, ArgExpr: ValArg.get());
6259 TheCall->setType(Context.VoidTy);
6260 return TheCallResult;
6261}
6262
6263/// CheckObjCString - Checks that the format string argument to the os_log()
6264/// and os_trace() functions is correct, and converts it to const char *.
6265ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6266 Arg = Arg->IgnoreParenCasts();
6267 auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
6268 if (!Literal) {
6269 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Val: Arg)) {
6270 Literal = ObjcLiteral->getString();
6271 }
6272 }
6273
6274 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
6275 return ExprError(
6276 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_os_log_format_not_string_constant)
6277 << Arg->getSourceRange());
6278 }
6279
6280 ExprResult Result(Literal);
6281 QualType ResultTy = Context.getPointerType(T: Context.CharTy.withConst());
6282 InitializedEntity Entity =
6283 InitializedEntity::InitializeParameter(Context, Type: ResultTy, Consumed: false);
6284 Result = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Result);
6285 return Result;
6286}
6287
6288/// Check that the user is calling the appropriate va_start builtin for the
6289/// target and calling convention.
6290static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6291 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6292 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6293 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6294 TT.getArch() == llvm::Triple::aarch64_32);
6295 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
6296 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6297 if (IsX64 || IsAArch64) {
6298 CallingConv CC = CC_C;
6299 if (const FunctionDecl *FD = S.getCurFunctionDecl())
6300 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6301 if (IsMSVAStart) {
6302 // Don't allow this in System V ABI functions.
6303 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
6304 return S.Diag(Loc: Fn->getBeginLoc(),
6305 DiagID: diag::err_ms_va_start_used_in_sysv_function);
6306 } else {
6307 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6308 // On x64 Windows, don't allow this in System V ABI functions.
6309 // (Yes, that means there's no corresponding way to support variadic
6310 // System V ABI functions on Windows.)
6311 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
6312 (!IsWindowsOrUEFI && CC == CC_Win64))
6313 return S.Diag(Loc: Fn->getBeginLoc(),
6314 DiagID: diag::err_va_start_used_in_wrong_abi_function)
6315 << !IsWindowsOrUEFI;
6316 }
6317 return false;
6318 }
6319
6320 if (IsMSVAStart)
6321 return S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_builtin_x64_aarch64_only);
6322 return false;
6323}
6324
6325static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6326 ParmVarDecl **LastParam = nullptr) {
6327 // Determine whether the current function, block, or obj-c method is variadic
6328 // and get its parameter list.
6329 bool IsVariadic = false;
6330 ArrayRef<ParmVarDecl *> Params;
6331 DeclContext *Caller =
6332 S.CurContext->getEnclosingNonExpansionStatementContext();
6333 if (auto *Block = dyn_cast<BlockDecl>(Val: Caller)) {
6334 IsVariadic = Block->isVariadic();
6335 Params = Block->parameters();
6336 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: Caller)) {
6337 IsVariadic = FD->isVariadic();
6338 Params = FD->parameters();
6339 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Val: Caller)) {
6340 IsVariadic = MD->isVariadic();
6341 // FIXME: This isn't correct for methods (results in bogus warning).
6342 Params = MD->parameters();
6343 } else if (isa<CapturedDecl>(Val: Caller)) {
6344 // We don't support va_start in a CapturedDecl.
6345 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_captured_stmt);
6346 return true;
6347 } else {
6348 // This must be some other declcontext that parses exprs.
6349 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_outside_function);
6350 return true;
6351 }
6352
6353 if (!IsVariadic) {
6354 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_fixed_function);
6355 return true;
6356 }
6357
6358 if (LastParam)
6359 *LastParam = Params.empty() ? nullptr : Params.back();
6360
6361 return false;
6362}
6363
6364bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6365 Expr *Fn = TheCall->getCallee();
6366 if (checkVAStartABI(S&: *this, BuiltinID, Fn))
6367 return true;
6368
6369 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6370 // This builtin requires one argument (the va_list), allows two arguments,
6371 // but diagnoses more than two arguments. e.g.,
6372 // __builtin_c23_va_start(); // error
6373 // __builtin_c23_va_start(list); // ok
6374 // __builtin_c23_va_start(list, param); // ok
6375 // __builtin_c23_va_start(list, anything, anything); // error
6376 // This differs from the GCC behavior in that they accept the last case
6377 // with a warning, but it doesn't seem like a useful behavior to allow.
6378 if (checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
6379 return true;
6380 } else {
6381 // In C23 mode, va_start only needs one argument. However, the builtin still
6382 // requires two arguments (which matches the behavior of the GCC builtin),
6383 // <stdarg.h> passes `0` as the second argument in C23 mode.
6384 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6385 return true;
6386 }
6387
6388 // Type-check the first argument normally.
6389 if (checkBuiltinArgument(S&: *this, E: TheCall, ArgIndex: 0))
6390 return true;
6391
6392 // Check that the current function is variadic, and get its last parameter.
6393 ParmVarDecl *LastParam;
6394 if (checkVAStartIsInVariadicFunction(S&: *this, Fn, LastParam: &LastParam))
6395 return true;
6396
6397 // Verify that the second argument to the builtin is the last non-variadic
6398 // argument of the current function or method. In C23 mode, if the call is
6399 // not to __builtin_c23_va_start, and the second argument is an integer
6400 // constant expression with value 0, then we don't bother with this check.
6401 // For __builtin_c23_va_start, we only perform the check for the second
6402 // argument being the last argument to the current function if there is a
6403 // second argument present.
6404 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6405 TheCall->getNumArgs() < 2) {
6406 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
6407 return false;
6408 }
6409
6410 const Expr *Arg = TheCall->getArg(Arg: 1)->IgnoreParenCasts();
6411 if (std::optional<llvm::APSInt> Val =
6412 TheCall->getArg(Arg: 1)->getIntegerConstantExpr(Ctx: Context);
6413 Val && LangOpts.C23 && *Val == 0 &&
6414 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6415 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
6416 return false;
6417 }
6418
6419 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6420 // next block.
6421 QualType Type;
6422 SourceLocation ParamLoc;
6423 bool IsCRegister = false;
6424 bool SecondArgIsLastNonVariadicArgument = false;
6425 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: Arg)) {
6426 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: DR->getDecl())) {
6427 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6428
6429 Type = PV->getType();
6430 ParamLoc = PV->getLocation();
6431 IsCRegister =
6432 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6433 }
6434 }
6435
6436 if (!SecondArgIsLastNonVariadicArgument)
6437 Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
6438 DiagID: diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6439 else if (IsCRegister || Type->isReferenceType() ||
6440 Type->isSpecificBuiltinType(K: BuiltinType::Float) || [=] {
6441 // Promotable integers are UB, but enumerations need a bit of
6442 // extra checking to see what their promotable type actually is.
6443 if (!Context.isPromotableIntegerType(T: Type))
6444 return false;
6445 const auto *ED = Type->getAsEnumDecl();
6446 if (!ED)
6447 return true;
6448 return !Context.typesAreCompatible(T1: ED->getPromotionType(), T2: Type);
6449 }()) {
6450 unsigned Reason = 0;
6451 if (Type->isReferenceType()) Reason = 1;
6452 else if (IsCRegister) Reason = 2;
6453 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_va_start_type_is_undefined) << Reason;
6454 Diag(Loc: ParamLoc, DiagID: diag::note_parameter_type) << Type;
6455 }
6456
6457 return false;
6458}
6459
6460bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6461 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6462 const LangOptions &LO = getLangOpts();
6463
6464 if (LO.CPlusPlus)
6465 return Arg->getType()
6466 .getCanonicalType()
6467 .getTypePtr()
6468 ->getPointeeType()
6469 .withoutLocalFastQualifiers() == Context.CharTy;
6470
6471 // In C, allow aliasing through `char *`, this is required for AArch64 at
6472 // least.
6473 return true;
6474 };
6475
6476 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6477 // const char *named_addr);
6478
6479 Expr *Func = Call->getCallee();
6480
6481 if (Call->getNumArgs() < 3)
6482 return Diag(Loc: Call->getEndLoc(),
6483 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6484 << 0 /*function call*/ << 3 << Call->getNumArgs()
6485 << /*is non object*/ 0;
6486
6487 // Type-check the first argument normally.
6488 if (checkBuiltinArgument(S&: *this, E: Call, ArgIndex: 0))
6489 return true;
6490
6491 // Check that the current function is variadic.
6492 if (checkVAStartIsInVariadicFunction(S&: *this, Fn: Func))
6493 return true;
6494
6495 // __va_start on Windows does not validate the parameter qualifiers
6496
6497 const Expr *Arg1 = Call->getArg(Arg: 1)->IgnoreParens();
6498 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6499
6500 const Expr *Arg2 = Call->getArg(Arg: 2)->IgnoreParens();
6501 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6502
6503 const QualType &ConstCharPtrTy =
6504 Context.getPointerType(T: Context.CharTy.withConst());
6505 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6506 Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
6507 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6508 << 0 /* qualifier difference */
6509 << 3 /* parameter mismatch */
6510 << 2 << Arg1->getType() << ConstCharPtrTy;
6511
6512 const QualType SizeTy = Context.getSizeType();
6513 if (!Context.hasSameType(
6514 T1: Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers(),
6515 T2: SizeTy))
6516 Diag(Loc: Arg2->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
6517 << Arg2->getType() << SizeTy << 1 /* different class */
6518 << 0 /* qualifier difference */
6519 << 3 /* parameter mismatch */
6520 << 3 << Arg2->getType() << SizeTy;
6521
6522 return false;
6523}
6524
6525bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6526 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6527 return true;
6528
6529 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6530 TheCall->getFPFeaturesInEffect(LO: getLangOpts()).getNoHonorNaNs())
6531 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6532 << 1 << 0 << TheCall->getSourceRange();
6533
6534 ExprResult OrigArg0 = TheCall->getArg(Arg: 0);
6535 ExprResult OrigArg1 = TheCall->getArg(Arg: 1);
6536
6537 // Do standard promotions between the two arguments, returning their common
6538 // type.
6539 QualType Res = UsualArithmeticConversions(
6540 LHS&: OrigArg0, RHS&: OrigArg1, Loc: TheCall->getExprLoc(), ACK: ArithConvKind::Comparison);
6541 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6542 return true;
6543
6544 // Make sure any conversions are pushed back into the call; this is
6545 // type safe since unordered compare builtins are declared as "_Bool
6546 // foo(...)".
6547 TheCall->setArg(Arg: 0, ArgExpr: OrigArg0.get());
6548 TheCall->setArg(Arg: 1, ArgExpr: OrigArg1.get());
6549
6550 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6551 return false;
6552
6553 // If the common type isn't a real floating type, then the arguments were
6554 // invalid for this operation.
6555 if (Res.isNull() || !Res->isRealFloatingType())
6556 return Diag(Loc: OrigArg0.get()->getBeginLoc(),
6557 DiagID: diag::err_typecheck_call_invalid_ordered_compare)
6558 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6559 << SourceRange(OrigArg0.get()->getBeginLoc(),
6560 OrigArg1.get()->getEndLoc());
6561
6562 return false;
6563}
6564
6565bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6566 unsigned BuiltinID) {
6567 if (checkArgCount(Call: TheCall, DesiredArgCount: NumArgs))
6568 return true;
6569
6570 FPOptions FPO = TheCall->getFPFeaturesInEffect(LO: getLangOpts());
6571 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6572 BuiltinID == Builtin::BI__builtin_isinf ||
6573 BuiltinID == Builtin::BI__builtin_isinf_sign))
6574 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6575 << 0 << 0 << TheCall->getSourceRange();
6576
6577 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6578 BuiltinID == Builtin::BI__builtin_isunordered))
6579 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6580 << 1 << 0 << TheCall->getSourceRange();
6581
6582 bool IsFPClass = NumArgs == 2;
6583
6584 // Find out position of floating-point argument.
6585 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6586
6587 // We can count on all parameters preceding the floating-point just being int.
6588 // Try all of those.
6589 for (unsigned i = 0; i < FPArgNo; ++i) {
6590 Expr *Arg = TheCall->getArg(Arg: i);
6591
6592 if (Arg->isTypeDependent())
6593 return false;
6594
6595 ExprResult Res = PerformImplicitConversion(From: Arg, ToType: Context.IntTy,
6596 Action: AssignmentAction::Passing);
6597
6598 if (Res.isInvalid())
6599 return true;
6600 TheCall->setArg(Arg: i, ArgExpr: Res.get());
6601 }
6602
6603 Expr *OrigArg = TheCall->getArg(Arg: FPArgNo);
6604
6605 if (OrigArg->isTypeDependent())
6606 return false;
6607
6608 // We want to leave the type how it is, but do normal L->Rvalue conversions.
6609 ExprResult Res = DefaultFunctionArrayLvalueConversion(E: OrigArg);
6610 if (!Res.isUsable())
6611 return true;
6612 OrigArg = Res.get();
6613
6614 TheCall->setArg(Arg: FPArgNo, ArgExpr: OrigArg);
6615
6616 QualType VectorResultTy;
6617 QualType ElementTy = OrigArg->getType();
6618 // TODO: When all classification function are implemented with is_fpclass,
6619 // vector argument can be supported in all of them.
6620 if (ElementTy->isVectorType() && IsFPClass) {
6621 VectorResultTy = GetSignedVectorType(V: ElementTy);
6622 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6623 }
6624
6625 // This operation requires a non-_Complex floating-point number.
6626 if (!ElementTy->isRealFloatingType())
6627 return Diag(Loc: OrigArg->getBeginLoc(),
6628 DiagID: diag::err_typecheck_call_invalid_unary_fp)
6629 << OrigArg->getType() << OrigArg->getSourceRange();
6630
6631 // __builtin_isfpclass has integer parameter that specify test mask. It is
6632 // passed in (...), so it should be analyzed completely here.
6633 if (IsFPClass) {
6634 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: llvm::fcAllFlags))
6635 return true;
6636
6637 ExprResult MaskRes = PerformImplicitConversion(
6638 From: TheCall->getArg(Arg: NumArgs - 1), ToType: Context.IntTy, Action: AssignmentAction::Passing);
6639 if (!MaskRes.isUsable())
6640 return true;
6641 TheCall->setArg(Arg: NumArgs - 1, ArgExpr: MaskRes.get());
6642 }
6643
6644 // TODO: enable this code to all classification functions.
6645 if (IsFPClass) {
6646 QualType ResultTy;
6647 if (!VectorResultTy.isNull())
6648 ResultTy = VectorResultTy;
6649 else
6650 ResultTy = Context.IntTy;
6651 TheCall->setType(ResultTy);
6652 }
6653
6654 return false;
6655}
6656
6657bool Sema::BuiltinComplex(CallExpr *TheCall) {
6658 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6659 return true;
6660
6661 bool Dependent = false;
6662 for (unsigned I = 0; I != 2; ++I) {
6663 Expr *Arg = TheCall->getArg(Arg: I);
6664 QualType T = Arg->getType();
6665 if (T->isDependentType()) {
6666 Dependent = true;
6667 continue;
6668 }
6669
6670 // Despite supporting _Complex int, GCC requires a real floating point type
6671 // for the operands of __builtin_complex.
6672 if (!T->isRealFloatingType()) {
6673 return Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_typecheck_call_requires_real_fp)
6674 << Arg->getType() << Arg->getSourceRange();
6675 }
6676
6677 ExprResult Converted = DefaultLvalueConversion(E: Arg);
6678 if (Converted.isInvalid())
6679 return true;
6680 TheCall->setArg(Arg: I, ArgExpr: Converted.get());
6681 }
6682
6683 if (Dependent) {
6684 TheCall->setType(Context.DependentTy);
6685 return false;
6686 }
6687
6688 Expr *Real = TheCall->getArg(Arg: 0);
6689 Expr *Imag = TheCall->getArg(Arg: 1);
6690 if (!Context.hasSameType(T1: Real->getType(), T2: Imag->getType())) {
6691 return Diag(Loc: Real->getBeginLoc(),
6692 DiagID: diag::err_typecheck_call_different_arg_types)
6693 << Real->getType() << Imag->getType()
6694 << Real->getSourceRange() << Imag->getSourceRange();
6695 }
6696
6697 TheCall->setType(Context.getComplexType(T: Real->getType()));
6698 return false;
6699}
6700
6701/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6702// This is declared to take (...), so we have to check everything.
6703ExprResult Sema::BuiltinShuffleVector(CallExpr *TheCall) {
6704 unsigned NumArgs = TheCall->getNumArgs();
6705 if (NumArgs < 2)
6706 return ExprError(Diag(Loc: TheCall->getEndLoc(),
6707 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6708 << 0 /*function call*/ << 2 << NumArgs
6709 << /*is non object*/ 0 << TheCall->getSourceRange());
6710
6711 // Determine which of the following types of shufflevector we're checking:
6712 // 1) unary, vector mask: (lhs, mask)
6713 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6714 QualType ResType = TheCall->getArg(Arg: 0)->getType();
6715 unsigned NumElements = 0;
6716
6717 if (!TheCall->getArg(Arg: 0)->isTypeDependent() &&
6718 !TheCall->getArg(Arg: 1)->isTypeDependent()) {
6719 QualType LHSType = TheCall->getArg(Arg: 0)->getType();
6720 QualType RHSType = TheCall->getArg(Arg: 1)->getType();
6721
6722 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6723 return ExprError(
6724 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_builtin_non_vector)
6725 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6726 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6727 TheCall->getArg(Arg: 1)->getEndLoc()));
6728
6729 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6730 unsigned NumResElements = NumArgs - 2;
6731
6732 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6733 // with mask. If so, verify that RHS is an integer vector type with the
6734 // same number of elts as lhs.
6735 if (NumArgs == 2) {
6736 auto *RHSVecType = RHSType->castAs<VectorType>();
6737 if (RHSVecType->getElementType()->isBooleanType() ||
6738 !RHSVecType->getElementType()->isIntegerType()) {
6739 return ExprError(
6740 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
6741 << /* Arg ordinal */ 2 << /*vector of*/ 4 << /*integer*/ 1
6742 << /*no fp*/ 0 << RHSType
6743 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6744 TheCall->getArg(Arg: 1)->getEndLoc()));
6745 }
6746
6747 if (RHSVecType->getNumElements() != NumElements)
6748 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6749 DiagID: diag::err_typecheck_vector_lengths_not_equal)
6750 << LHSType << RHSType << /*isMoreThanTwoArgs*/ false
6751 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
6752 TheCall->getArg(Arg: 1)->getEndLoc()));
6753 } else if (!Context.hasSameUnqualifiedType(T1: LHSType, T2: RHSType)) {
6754 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6755 DiagID: diag::err_vec_builtin_incompatible_vector)
6756 << TheCall->getDirectCallee()
6757 << /*isMoreThanTwoArgs*/ false
6758 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6759 TheCall->getArg(Arg: 1)->getEndLoc()));
6760 } else if (NumElements != NumResElements) {
6761 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6762 ResType = ResType->isExtVectorType()
6763 ? Context.getExtVectorType(VectorType: EltType, NumElts: NumResElements)
6764 : Context.getVectorType(VectorType: EltType, NumElts: NumResElements,
6765 VecKind: VectorKind::Generic);
6766 }
6767 }
6768
6769 for (unsigned I = 2; I != NumArgs; ++I) {
6770 Expr *Arg = TheCall->getArg(Arg: I);
6771 if (Arg->isTypeDependent() || Arg->isValueDependent())
6772 continue;
6773
6774 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
6775 if (!Result)
6776 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6777 DiagID: diag::err_shufflevector_nonconstant_argument)
6778 << Arg->getSourceRange());
6779
6780 // Allow -1 which will be translated to undef in the IR.
6781 if (Result->isSigned() && Result->isAllOnes())
6782 ;
6783 else if (Result->getActiveBits() > 64 ||
6784 Result->getZExtValue() >= NumElements * 2)
6785 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6786 DiagID: diag::err_shufflevector_argument_too_large)
6787 << Arg->getSourceRange());
6788
6789 TheCall->setArg(Arg: I, ArgExpr: ConstantExpr::Create(Context, E: Arg, Result: APValue(*Result)));
6790 }
6791
6792 auto *Result = new (Context) ShuffleVectorExpr(
6793 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6794 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6795
6796 // All moved to Result.
6797 TheCall->shrinkNumArgs(NewNumArgs: 0);
6798 return Result;
6799}
6800
6801ExprResult Sema::ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6802 SourceLocation BuiltinLoc,
6803 SourceLocation RParenLoc) {
6804 ExprValueKind VK = VK_PRValue;
6805 ExprObjectKind OK = OK_Ordinary;
6806 QualType DstTy = TInfo->getType();
6807 QualType SrcTy = E->getType();
6808
6809 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6810 return ExprError(Diag(Loc: BuiltinLoc,
6811 DiagID: diag::err_convertvector_non_vector)
6812 << E->getSourceRange());
6813 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6814 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_builtin_non_vector_type)
6815 << "second"
6816 << "__builtin_convertvector");
6817
6818 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6819 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6820 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6821 if (SrcElts != DstElts)
6822 return ExprError(Diag(Loc: BuiltinLoc,
6823 DiagID: diag::err_convertvector_incompatible_vector)
6824 << E->getSourceRange());
6825 }
6826
6827 return ConvertVectorExpr::Create(C: Context, SrcExpr: E, TI: TInfo, DstType: DstTy, VK, OK, BuiltinLoc,
6828 RParenLoc, FPFeatures: CurFPFeatureOverrides());
6829}
6830
6831bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6832 unsigned NumArgs = TheCall->getNumArgs();
6833
6834 if (NumArgs > 3)
6835 return Diag(Loc: TheCall->getEndLoc(),
6836 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6837 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6838 << TheCall->getSourceRange();
6839
6840 // Argument 0 is checked for us and the remaining arguments must be
6841 // constant integers.
6842 for (unsigned i = 1; i != NumArgs; ++i) {
6843 if (convertArgumentToType(Value&: TheCall->getArgs()[i], Ty: Context.IntTy))
6844 return true;
6845 if (BuiltinConstantArgRange(TheCall, ArgNum: i, Low: 0, High: i == 1 ? 1 : 3))
6846 return true;
6847 }
6848
6849 return false;
6850}
6851
6852bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6853 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6854 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
6855 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6856 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
6857 return true;
6858 Expr *Arg = TheCall->getArg(Arg: 0);
6859 if (Arg->isInstantiationDependent())
6860 return false;
6861
6862 QualType ArgTy = Arg->getType();
6863 if (!ArgTy->hasFloatingRepresentation())
6864 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_expect_flt_or_vector)
6865 << ArgTy;
6866 if (Arg->isLValue()) {
6867 ExprResult FirstArg = DefaultLvalueConversion(E: Arg);
6868 TheCall->setArg(Arg: 0, ArgExpr: FirstArg.get());
6869 }
6870 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
6871 return false;
6872}
6873
6874bool Sema::BuiltinAssume(CallExpr *TheCall) {
6875 Expr *Arg = TheCall->getArg(Arg: 0);
6876 if (Arg->isInstantiationDependent()) return false;
6877
6878 if (Arg->HasSideEffects(Ctx: Context))
6879 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_assume_side_effects)
6880 << Arg->getSourceRange()
6881 << cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getIdentifier();
6882
6883 return false;
6884}
6885
6886bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6887 // The alignment must be a constant integer.
6888 Expr *Arg = TheCall->getArg(Arg: 1);
6889
6890 // We can't check the value of a dependent argument.
6891 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6892 if (const auto *UE =
6893 dyn_cast<UnaryExprOrTypeTraitExpr>(Val: Arg->IgnoreParenImpCasts()))
6894 if (UE->getKind() == UETT_AlignOf ||
6895 UE->getKind() == UETT_PreferredAlignOf)
6896 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca_align_alignof)
6897 << Arg->getSourceRange();
6898
6899 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Ctx: Context);
6900
6901 if (!Result.isPowerOf2())
6902 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6903 << Arg->getSourceRange();
6904
6905 if (Result < Context.getCharWidth())
6906 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_small)
6907 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6908
6909 if (Result > std::numeric_limits<int32_t>::max())
6910 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_big)
6911 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6912 }
6913
6914 return false;
6915}
6916
6917bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6918 if (checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
6919 return true;
6920
6921 unsigned NumArgs = TheCall->getNumArgs();
6922 Expr *FirstArg = TheCall->getArg(Arg: 0);
6923
6924 {
6925 ExprResult FirstArgResult =
6926 DefaultFunctionArrayLvalueConversion(E: FirstArg);
6927 if (FirstArgResult.isInvalid())
6928 return true;
6929 if (!FirstArgResult.get()->getType()->isPointerType()) {
6930 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_assume_aligned_invalid_arg)
6931 << TheCall->getSourceRange();
6932 return true;
6933 }
6934 TheCall->setArg(Arg: 0, ArgExpr: FirstArgResult.get());
6935 }
6936
6937 // The alignment must be a constant integer.
6938 Expr *SecondArg = TheCall->getArg(Arg: 1);
6939
6940 // We can't check the value of a dependent argument.
6941 if (!SecondArg->isValueDependent()) {
6942 llvm::APSInt Result;
6943 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
6944 return true;
6945
6946 if (!Result.isPowerOf2())
6947 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6948 << SecondArg->getSourceRange();
6949
6950 if (Result > Sema::MaximumAlignment)
6951 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_assume_aligned_too_great)
6952 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6953
6954 TheCall->setArg(Arg: 1,
6955 ArgExpr: ConstantExpr::Create(Context, E: SecondArg, Result: APValue(Result)));
6956 }
6957
6958 if (NumArgs > 2) {
6959 Expr *ThirdArg = TheCall->getArg(Arg: 2);
6960 if (convertArgumentToType(Value&: ThirdArg, Ty: Context.getSizeType()))
6961 return true;
6962 TheCall->setArg(Arg: 2, ArgExpr: ThirdArg);
6963 }
6964
6965 return false;
6966}
6967
6968bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6969 unsigned BuiltinID =
6970 cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getBuiltinID();
6971 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6972
6973 unsigned NumArgs = TheCall->getNumArgs();
6974 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6975 if (NumArgs < NumRequiredArgs) {
6976 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args)
6977 << 0 /* function call */ << NumRequiredArgs << NumArgs
6978 << /*is non object*/ 0 << TheCall->getSourceRange();
6979 }
6980 if (NumArgs >= NumRequiredArgs + 0x100) {
6981 return Diag(Loc: TheCall->getEndLoc(),
6982 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6983 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6984 << /*is non object*/ 0 << TheCall->getSourceRange();
6985 }
6986 unsigned i = 0;
6987
6988 // For formatting call, check buffer arg.
6989 if (!IsSizeCall) {
6990 ExprResult Arg(TheCall->getArg(Arg: i));
6991 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6992 Context, Type: Context.VoidPtrTy, Consumed: false);
6993 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
6994 if (Arg.isInvalid())
6995 return true;
6996 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6997 i++;
6998 }
6999
7000 // Check string literal arg.
7001 unsigned FormatIdx = i;
7002 {
7003 ExprResult Arg = CheckOSLogFormatStringArg(Arg: TheCall->getArg(Arg: i));
7004 if (Arg.isInvalid())
7005 return true;
7006 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
7007 i++;
7008 }
7009
7010 // Make sure variadic args are scalar.
7011 unsigned FirstDataArg = i;
7012 while (i < NumArgs) {
7013 ExprResult Arg = DefaultVariadicArgumentPromotion(
7014 E: TheCall->getArg(Arg: i), CT: VariadicCallType::Function, FDecl: nullptr);
7015 if (Arg.isInvalid())
7016 return true;
7017 CharUnits ArgSize = Context.getTypeSizeInChars(T: Arg.get()->getType());
7018 if (ArgSize.getQuantity() >= 0x100) {
7019 return Diag(Loc: Arg.get()->getEndLoc(), DiagID: diag::err_os_log_argument_too_big)
7020 << i << (int)ArgSize.getQuantity() << 0xff
7021 << TheCall->getSourceRange();
7022 }
7023 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
7024 i++;
7025 }
7026
7027 // Check formatting specifiers. NOTE: We're only doing this for the non-size
7028 // call to avoid duplicate diagnostics.
7029 if (!IsSizeCall) {
7030 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7031 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7032 bool Success = CheckFormatArguments(
7033 Args, FAPK: FAPK_Variadic, ReferenceFormatString: nullptr, format_idx: FormatIdx, firstDataArg: FirstDataArg,
7034 Type: FormatStringType::OSLog, CallType: VariadicCallType::Function,
7035 Loc: TheCall->getBeginLoc(), range: SourceRange(), CheckedVarArgs);
7036 if (!Success)
7037 return true;
7038 }
7039
7040 if (IsSizeCall) {
7041 TheCall->setType(Context.getSizeType());
7042 } else {
7043 TheCall->setType(Context.VoidPtrTy);
7044 }
7045 return false;
7046}
7047
7048bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
7049 llvm::APSInt &Result) {
7050 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7051
7052 if (Arg->isTypeDependent() || Arg->isValueDependent())
7053 return false;
7054
7055 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Ctx: Context);
7056 if (!R) {
7057 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
7058 auto *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
7059 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_constant_integer_arg_type)
7060 << FDecl->getDeclName() << Arg->getSourceRange();
7061 }
7062 Result = *R;
7063
7064 return false;
7065}
7066
7067bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
7068 int High, bool RangeIsError) {
7069 if (isConstantEvaluatedContext())
7070 return false;
7071 llvm::APSInt Result;
7072
7073 // We can't check the value of a dependent argument.
7074 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7075 if (Arg->isTypeDependent() || Arg->isValueDependent())
7076 return false;
7077
7078 // Check constant-ness first.
7079 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7080 return true;
7081
7082 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7083 if (RangeIsError)
7084 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_invalid_range)
7085 << toString(I: Result, Radix: 10) << Low << High << Arg->getSourceRange();
7086 else
7087 // Defer the warning until we know if the code will be emitted so that
7088 // dead code can ignore this.
7089 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
7090 PD: PDiag(DiagID: diag::warn_argument_invalid_range)
7091 << toString(I: Result, Radix: 10) << Low << High
7092 << Arg->getSourceRange());
7093 }
7094
7095 return false;
7096}
7097
7098bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
7099 unsigned Num) {
7100 llvm::APSInt Result;
7101
7102 // We can't check the value of a dependent argument.
7103 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7104 if (Arg->isTypeDependent() || Arg->isValueDependent())
7105 return false;
7106
7107 // Check constant-ness first.
7108 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7109 return true;
7110
7111 if (Result.getSExtValue() % Num != 0)
7112 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_multiple)
7113 << Num << Arg->getSourceRange();
7114
7115 return false;
7116}
7117
7118bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
7119 llvm::APSInt Result;
7120
7121 // We can't check the value of a dependent argument.
7122 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7123 if (Arg->isTypeDependent() || Arg->isValueDependent())
7124 return false;
7125
7126 // Check constant-ness first.
7127 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7128 return true;
7129
7130 if (Result.isPowerOf2())
7131 return false;
7132
7133 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_power_of_2)
7134 << Arg->getSourceRange();
7135}
7136
7137static bool IsShiftedByte(llvm::APSInt Value) {
7138 if (Value.isNegative())
7139 return false;
7140
7141 // Check if it's a shifted byte, by shifting it down
7142 while (true) {
7143 // If the value fits in the bottom byte, the check passes.
7144 if (Value < 0x100)
7145 return true;
7146
7147 // Otherwise, if the value has _any_ bits in the bottom byte, the check
7148 // fails.
7149 if ((Value & 0xFF) != 0)
7150 return false;
7151
7152 // If the bottom 8 bits are all 0, but something above that is nonzero,
7153 // then shifting the value right by 8 bits won't affect whether it's a
7154 // shifted byte or not. So do that, and go round again.
7155 Value >>= 8;
7156 }
7157}
7158
7159bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
7160 unsigned ArgBits) {
7161 llvm::APSInt Result;
7162
7163 // We can't check the value of a dependent argument.
7164 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7165 if (Arg->isTypeDependent() || Arg->isValueDependent())
7166 return false;
7167
7168 // Check constant-ness first.
7169 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7170 return true;
7171
7172 // Truncate to the given size.
7173 Result = Result.getLoBits(numBits: ArgBits);
7174 Result.setIsUnsigned(true);
7175
7176 if (IsShiftedByte(Value: Result))
7177 return false;
7178
7179 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_shifted_byte)
7180 << Arg->getSourceRange();
7181}
7182
7183bool Sema::BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7184 unsigned ArgNum,
7185 unsigned ArgBits) {
7186 llvm::APSInt Result;
7187
7188 // We can't check the value of a dependent argument.
7189 Expr *Arg = TheCall->getArg(Arg: ArgNum);
7190 if (Arg->isTypeDependent() || Arg->isValueDependent())
7191 return false;
7192
7193 // Check constant-ness first.
7194 if (BuiltinConstantArg(TheCall, ArgNum, Result))
7195 return true;
7196
7197 // Truncate to the given size.
7198 Result = Result.getLoBits(numBits: ArgBits);
7199 Result.setIsUnsigned(true);
7200
7201 // Check to see if it's in either of the required forms.
7202 if (IsShiftedByte(Value: Result) ||
7203 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7204 return false;
7205
7206 return Diag(Loc: TheCall->getBeginLoc(),
7207 DiagID: diag::err_argument_not_shifted_byte_or_xxff)
7208 << Arg->getSourceRange();
7209}
7210
7211bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
7212 if (!Context.getTargetInfo().hasSjLjLowering())
7213 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_unsupported)
7214 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7215
7216 Expr *Arg = TheCall->getArg(Arg: 1);
7217 llvm::APSInt Result;
7218
7219 // TODO: This is less than ideal. Overload this to take a value.
7220 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
7221 return true;
7222
7223 if (Result != 1)
7224 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_invalid_val)
7225 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7226
7227 return false;
7228}
7229
7230bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
7231 if (!Context.getTargetInfo().hasSjLjLowering())
7232 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_setjmp_unsupported)
7233 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7234 return false;
7235}
7236
7237bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
7238 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
7239 return true;
7240
7241 ExprResult ArgRes = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
7242 if (ArgRes.isInvalid())
7243 return true;
7244
7245 // For simplicity, we support only limited expressions for the argument.
7246 // Specifically a flexible array member or a pointer with counted_by:
7247 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
7248 // complex casting, which really shouldn't be a huge problem.
7249 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
7250 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
7251 return Diag(Loc: Arg->getBeginLoc(),
7252 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7253 << Arg->getSourceRange();
7254
7255 if (Arg->HasSideEffects(Ctx: Context))
7256 return Diag(Loc: Arg->getBeginLoc(),
7257 DiagID: diag::err_builtin_counted_by_ref_has_side_effects)
7258 << Arg->getSourceRange();
7259
7260 if (const auto *ME = dyn_cast<MemberExpr>(Val: Arg)) {
7261 const auto *CATy =
7262 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
7263
7264 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
7265 // Member has counted_by attribute - return pointer to count field
7266 const auto *MemberDecl = cast<FieldDecl>(Val: ME->getMemberDecl());
7267 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
7268 if (CountFD->isBitField()) {
7269 Diag(Loc: ME->getBeginLoc(),
7270 DiagID: diag::err_builtin_counted_by_ref_counter_field_is_bitfield)
7271 << Arg << CountFD << ME->getSourceRange();
7272 return Diag(Loc: CountFD->getBeginLoc(),
7273 DiagID: diag::note_counted_by_counter_field)
7274 << CountFD << CountFD->getSourceRange();
7275 }
7276
7277 TheCall->setType(Context.getPointerType(T: CountFD->getType()));
7278 return false;
7279 }
7280 }
7281
7282 // FAMs and pointers without counted_by return void*
7283 QualType MemberTy = ME->getMemberDecl()->getType();
7284 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
7285 return Diag(Loc: Arg->getBeginLoc(),
7286 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7287 << Arg->getSourceRange();
7288 } else {
7289 return Diag(Loc: Arg->getBeginLoc(),
7290 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7291 << Arg->getSourceRange();
7292 }
7293
7294 TheCall->setType(Context.getPointerType(T: Context.VoidTy));
7295 return false;
7296}
7297
7298/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
7299/// It allows leaking and modification of bounds safety information.
7300bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
7301 BuiltinCountedByRefKind K) {
7302 const CallExpr *CE =
7303 E ? dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts()) : nullptr;
7304 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
7305 return false;
7306
7307 switch (K) {
7308 case BuiltinCountedByRefKind::Assignment:
7309 case BuiltinCountedByRefKind::Initializer:
7310 Diag(Loc: E->getExprLoc(),
7311 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7312 << 0 << E->getSourceRange();
7313 break;
7314 case BuiltinCountedByRefKind::FunctionArg:
7315 Diag(Loc: E->getExprLoc(),
7316 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7317 << 1 << E->getSourceRange();
7318 break;
7319 case BuiltinCountedByRefKind::ReturnArg:
7320 Diag(Loc: E->getExprLoc(),
7321 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7322 << 2 << E->getSourceRange();
7323 break;
7324 case BuiltinCountedByRefKind::ArraySubscript:
7325 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
7326 << 0 << E->getSourceRange();
7327 break;
7328 case BuiltinCountedByRefKind::BinaryExpr:
7329 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
7330 << 1 << E->getSourceRange();
7331 break;
7332 }
7333
7334 return true;
7335}
7336
7337namespace {
7338
7339class UncoveredArgHandler {
7340 enum { Unknown = -1, AllCovered = -2 };
7341
7342 signed FirstUncoveredArg = Unknown;
7343 SmallVector<const Expr *, 4> DiagnosticExprs;
7344
7345public:
7346 UncoveredArgHandler() = default;
7347
7348 bool hasUncoveredArg() const {
7349 return (FirstUncoveredArg >= 0);
7350 }
7351
7352 unsigned getUncoveredArg() const {
7353 assert(hasUncoveredArg() && "no uncovered argument");
7354 return FirstUncoveredArg;
7355 }
7356
7357 void setAllCovered() {
7358 // A string has been found with all arguments covered, so clear out
7359 // the diagnostics.
7360 DiagnosticExprs.clear();
7361 FirstUncoveredArg = AllCovered;
7362 }
7363
7364 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7365 assert(NewFirstUncoveredArg >= 0 && "Outside range");
7366
7367 // Don't update if a previous string covers all arguments.
7368 if (FirstUncoveredArg == AllCovered)
7369 return;
7370
7371 // UncoveredArgHandler tracks the highest uncovered argument index
7372 // and with it all the strings that match this index.
7373 if (NewFirstUncoveredArg == FirstUncoveredArg)
7374 DiagnosticExprs.push_back(Elt: StrExpr);
7375 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7376 DiagnosticExprs.clear();
7377 DiagnosticExprs.push_back(Elt: StrExpr);
7378 FirstUncoveredArg = NewFirstUncoveredArg;
7379 }
7380 }
7381
7382 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7383};
7384
7385enum StringLiteralCheckType {
7386 SLCT_NotALiteral,
7387 SLCT_UncheckedLiteral,
7388 SLCT_CheckedLiteral
7389};
7390
7391} // namespace
7392
7393static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7394 BinaryOperatorKind BinOpKind,
7395 bool AddendIsRight) {
7396 unsigned BitWidth = Offset.getBitWidth();
7397 unsigned AddendBitWidth = Addend.getBitWidth();
7398 // There might be negative interim results.
7399 if (Addend.isUnsigned()) {
7400 Addend = Addend.zext(width: ++AddendBitWidth);
7401 Addend.setIsSigned(true);
7402 }
7403 // Adjust the bit width of the APSInts.
7404 if (AddendBitWidth > BitWidth) {
7405 Offset = Offset.sext(width: AddendBitWidth);
7406 BitWidth = AddendBitWidth;
7407 } else if (BitWidth > AddendBitWidth) {
7408 Addend = Addend.sext(width: BitWidth);
7409 }
7410
7411 bool Ov = false;
7412 llvm::APSInt ResOffset = Offset;
7413 if (BinOpKind == BO_Add)
7414 ResOffset = Offset.sadd_ov(RHS: Addend, Overflow&: Ov);
7415 else {
7416 assert(AddendIsRight && BinOpKind == BO_Sub &&
7417 "operator must be add or sub with addend on the right");
7418 ResOffset = Offset.ssub_ov(RHS: Addend, Overflow&: Ov);
7419 }
7420
7421 // We add an offset to a pointer here so we should support an offset as big as
7422 // possible.
7423 if (Ov) {
7424 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7425 "index (intermediate) result too big");
7426 Offset = Offset.sext(width: 2 * BitWidth);
7427 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7428 return;
7429 }
7430
7431 Offset = std::move(ResOffset);
7432}
7433
7434namespace {
7435
7436// This is a wrapper class around StringLiteral to support offsetted string
7437// literals as format strings. It takes the offset into account when returning
7438// the string and its length or the source locations to display notes correctly.
7439class FormatStringLiteral {
7440 const StringLiteral *FExpr;
7441 int64_t Offset;
7442
7443public:
7444 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7445 : FExpr(fexpr), Offset(Offset) {}
7446
7447 const StringLiteral *getFormatString() const { return FExpr; }
7448
7449 StringRef getString() const { return FExpr->getString().drop_front(N: Offset); }
7450
7451 unsigned getByteLength() const {
7452 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7453 }
7454
7455 unsigned getLength() const { return FExpr->getLength() - Offset; }
7456 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7457
7458 StringLiteralKind getKind() const { return FExpr->getKind(); }
7459
7460 QualType getType() const { return FExpr->getType(); }
7461
7462 bool isAscii() const { return FExpr->isOrdinary(); }
7463 bool isWide() const { return FExpr->isWide(); }
7464 bool isUTF8() const { return FExpr->isUTF8(); }
7465 bool isUTF16() const { return FExpr->isUTF16(); }
7466 bool isUTF32() const { return FExpr->isUTF32(); }
7467 bool isPascal() const { return FExpr->isPascal(); }
7468
7469 SourceLocation getLocationOfByte(
7470 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7471 const TargetInfo &Target, unsigned *StartToken = nullptr,
7472 unsigned *StartTokenByteOffset = nullptr) const {
7473 return FExpr->getLocationOfByte(ByteNo: ByteNo + Offset, SM, Features, Target,
7474 StartToken, StartTokenByteOffset);
7475 }
7476
7477 SourceLocation getBeginLoc() const LLVM_READONLY {
7478 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7479 }
7480
7481 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7482};
7483
7484} // namespace
7485
7486static void CheckFormatString(
7487 Sema &S, const FormatStringLiteral *FExpr,
7488 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7489 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
7490 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7491 bool inFunctionCall, VariadicCallType CallType,
7492 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7493 bool IgnoreStringsWithoutSpecifiers);
7494
7495static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7496 const Expr *E);
7497
7498// Determine if an expression is a string literal or constant string.
7499// If this function returns false on the arguments to a function expecting a
7500// format string, we will usually need to emit a warning.
7501// True string literals are then checked by CheckFormatString.
7502static StringLiteralCheckType
7503checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7504 const Expr *E, ArrayRef<const Expr *> Args,
7505 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7506 unsigned firstDataArg, FormatStringType Type,
7507 VariadicCallType CallType, bool InFunctionCall,
7508 llvm::SmallBitVector &CheckedVarArgs,
7509 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7510 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7511 bool IgnoreStringsWithoutSpecifiers = false) {
7512 if (S.isConstantEvaluatedContext())
7513 return SLCT_NotALiteral;
7514tryAgain:
7515 assert(Offset.isSigned() && "invalid offset");
7516
7517 if (E->isTypeDependent() || E->isValueDependent())
7518 return SLCT_NotALiteral;
7519
7520 E = E->IgnoreParenCasts();
7521
7522 if (E->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull))
7523 // Technically -Wformat-nonliteral does not warn about this case.
7524 // The behavior of printf and friends in this case is implementation
7525 // dependent. Ideally if the format string cannot be null then
7526 // it should have a 'nonnull' attribute in the function prototype.
7527 return SLCT_UncheckedLiteral;
7528
7529 switch (E->getStmtClass()) {
7530 case Stmt::InitListExprClass:
7531 // Handle expressions like {"foobar"}.
7532 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E)) {
7533 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7534 format_idx, firstDataArg, Type, CallType,
7535 /*InFunctionCall*/ false, CheckedVarArgs,
7536 UncoveredArg, Offset, CallerFormatParamIdx,
7537 IgnoreStringsWithoutSpecifiers);
7538 }
7539 return SLCT_NotALiteral;
7540 case Stmt::BinaryConditionalOperatorClass:
7541 case Stmt::ConditionalOperatorClass: {
7542 // The expression is a literal if both sub-expressions were, and it was
7543 // completely checked only if both sub-expressions were checked.
7544 const AbstractConditionalOperator *C =
7545 cast<AbstractConditionalOperator>(Val: E);
7546
7547 // Determine whether it is necessary to check both sub-expressions, for
7548 // example, because the condition expression is a constant that can be
7549 // evaluated at compile time.
7550 bool CheckLeft = true, CheckRight = true;
7551
7552 bool Cond;
7553 if (C->getCond()->EvaluateAsBooleanCondition(
7554 Result&: Cond, Ctx: S.getASTContext(), InConstantContext: S.isConstantEvaluatedContext())) {
7555 if (Cond)
7556 CheckRight = false;
7557 else
7558 CheckLeft = false;
7559 }
7560
7561 // We need to maintain the offsets for the right and the left hand side
7562 // separately to check if every possible indexed expression is a valid
7563 // string literal. They might have different offsets for different string
7564 // literals in the end.
7565 StringLiteralCheckType Left;
7566 if (!CheckLeft)
7567 Left = SLCT_UncheckedLiteral;
7568 else {
7569 Left = checkFormatStringExpr(S, ReferenceFormatString, E: C->getTrueExpr(),
7570 Args, APK, format_idx, firstDataArg, Type,
7571 CallType, InFunctionCall, CheckedVarArgs,
7572 UncoveredArg, Offset, CallerFormatParamIdx,
7573 IgnoreStringsWithoutSpecifiers);
7574 if (Left == SLCT_NotALiteral || !CheckRight) {
7575 return Left;
7576 }
7577 }
7578
7579 StringLiteralCheckType Right = checkFormatStringExpr(
7580 S, ReferenceFormatString, E: C->getFalseExpr(), Args, APK, format_idx,
7581 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7582 UncoveredArg, Offset, CallerFormatParamIdx,
7583 IgnoreStringsWithoutSpecifiers);
7584
7585 return (CheckLeft && Left < Right) ? Left : Right;
7586 }
7587
7588 case Stmt::ImplicitCastExprClass:
7589 E = cast<ImplicitCastExpr>(Val: E)->getSubExpr();
7590 goto tryAgain;
7591
7592 case Stmt::OpaqueValueExprClass:
7593 if (const Expr *src = cast<OpaqueValueExpr>(Val: E)->getSourceExpr()) {
7594 E = src;
7595 goto tryAgain;
7596 }
7597 return SLCT_NotALiteral;
7598
7599 case Stmt::PredefinedExprClass:
7600 // While __func__, etc., are technically not string literals, they
7601 // cannot contain format specifiers and thus are not a security
7602 // liability.
7603 return SLCT_UncheckedLiteral;
7604
7605 case Stmt::DeclRefExprClass: {
7606 const DeclRefExpr *DR = cast<DeclRefExpr>(Val: E);
7607
7608 // As an exception, do not flag errors for variables binding to
7609 // const string literals.
7610 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: DR->getDecl())) {
7611 bool isConstant = false;
7612 QualType T = DR->getType();
7613
7614 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7615 isConstant = AT->getElementType().isConstant(Ctx: S.Context);
7616 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7617 isConstant = T.isConstant(Ctx: S.Context) &&
7618 PT->getPointeeType().isConstant(Ctx: S.Context);
7619 } else if (T->isObjCObjectPointerType()) {
7620 // In ObjC, there is usually no "const ObjectPointer" type,
7621 // so don't check if the pointee type is constant.
7622 isConstant = T.isConstant(Ctx: S.Context);
7623 }
7624
7625 if (isConstant) {
7626 if (const Expr *Init = VD->getAnyInitializer()) {
7627 // Look through initializers like const char c[] = { "foo" }
7628 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
7629 if (InitList->isStringLiteralInit())
7630 Init = InitList->getInit(Init: 0)->IgnoreParenImpCasts();
7631 }
7632 return checkFormatStringExpr(
7633 S, ReferenceFormatString, E: Init, Args, APK, format_idx,
7634 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7635 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7636 }
7637 }
7638
7639 // When the format argument is an argument of this function, and this
7640 // function also has the format attribute, there are several interactions
7641 // for which there shouldn't be a warning. For instance, when calling
7642 // v*printf from a function that has the printf format attribute, we
7643 // should not emit a warning about using `fmt`, even though it's not
7644 // constant, because the arguments have already been checked for the
7645 // caller of `logmessage`:
7646 //
7647 // __attribute__((format(printf, 1, 2)))
7648 // void logmessage(char const *fmt, ...) {
7649 // va_list ap;
7650 // va_start(ap, fmt);
7651 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7652 // ...
7653 // }
7654 //
7655 // Another interaction that we need to support is using a format string
7656 // specified by the format_matches attribute:
7657 //
7658 // __attribute__((format_matches(printf, 1, "%s %d")))
7659 // void logmessage(char const *fmt, const char *a, int b) {
7660 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7661 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7662 // ...
7663 // }
7664 //
7665 // Yet another interaction that we need to support is calling a variadic
7666 // format function from a format function that has fixed arguments. For
7667 // instance:
7668 //
7669 // __attribute__((format(printf, 1, 2)))
7670 // void logstring(char const *fmt, char const *str) {
7671 // printf(fmt, str); /* do not emit a warning about "fmt" */
7672 // }
7673 //
7674 // Same (and perhaps more relatably) for the variadic template case:
7675 //
7676 // template<typename... Args>
7677 // __attribute__((format(printf, 1, 2)))
7678 // void log(const char *fmt, Args&&... args) {
7679 // printf(fmt, forward<Args>(args)...);
7680 // /* do not emit a warning about "fmt" */
7681 // }
7682 //
7683 // Due to implementation difficulty, we only check the format, not the
7684 // format arguments, in all cases.
7685 //
7686 if (const auto *PV = dyn_cast<ParmVarDecl>(Val: VD)) {
7687 if (CallerFormatParamIdx)
7688 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7689 if (const auto *D = dyn_cast<Decl>(Val: PV->getDeclContext())) {
7690 for (const auto *PVFormatMatches :
7691 D->specific_attrs<FormatMatchesAttr>()) {
7692 Sema::FormatStringInfo CalleeFSI;
7693 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormatMatches->getFormatIdx(),
7694 FirstArg: 0, FSI: &CalleeFSI))
7695 continue;
7696 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7697 // If using the wrong type of format string, emit a diagnostic
7698 // here and stop checking to avoid irrelevant diagnostics.
7699 if (Type != S.GetFormatStringType(Format: PVFormatMatches)) {
7700 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7701 DiagID: diag::warn_format_string_type_incompatible)
7702 << PVFormatMatches->getType()->getName()
7703 << S.GetFormatStringTypeName(FST: Type);
7704 if (!InFunctionCall) {
7705 S.Diag(Loc: PVFormatMatches->getFormatString()->getBeginLoc(),
7706 DiagID: diag::note_format_string_defined);
7707 }
7708 return SLCT_UncheckedLiteral;
7709 }
7710 return checkFormatStringExpr(
7711 S, ReferenceFormatString, E: PVFormatMatches->getFormatString(),
7712 Args, APK, format_idx, firstDataArg, Type, CallType,
7713 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7714 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7715 }
7716 }
7717
7718 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7719 Sema::FormatStringInfo CallerFSI;
7720 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormat->getFormatIdx(),
7721 FirstArg: PVFormat->getFirstArg(), FSI: &CallerFSI))
7722 continue;
7723 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7724 // We also check if the formats are compatible.
7725 // We can't pass a 'scanf' string to a 'printf' function.
7726 if (Type != S.GetFormatStringType(Format: PVFormat)) {
7727 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7728 DiagID: diag::warn_format_string_type_incompatible)
7729 << PVFormat->getType()->getName()
7730 << S.GetFormatStringTypeName(FST: Type);
7731 if (!InFunctionCall) {
7732 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_format_string_defined);
7733 }
7734 return SLCT_UncheckedLiteral;
7735 }
7736 // Lastly, check that argument passing kinds transition in a
7737 // way that makes sense:
7738 // from a caller with FAPK_VAList, allow FAPK_VAList
7739 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7740 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7741 // from a caller with FAPK_Variadic, allow FAPK_VAList
7742 switch (combineFAPK(A: CallerFSI.ArgPassingKind, B: APK)) {
7743 case combineFAPK(A: Sema::FAPK_VAList, B: Sema::FAPK_VAList):
7744 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Fixed):
7745 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Variadic):
7746 case combineFAPK(A: Sema::FAPK_Variadic, B: Sema::FAPK_VAList):
7747 return SLCT_UncheckedLiteral;
7748 }
7749 }
7750 }
7751 }
7752 }
7753 }
7754
7755 return SLCT_NotALiteral;
7756 }
7757
7758 case Stmt::CallExprClass:
7759 case Stmt::CXXMemberCallExprClass: {
7760 const CallExpr *CE = cast<CallExpr>(Val: E);
7761 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Val: CE->getCalleeDecl())) {
7762 bool IsFirst = true;
7763 StringLiteralCheckType CommonResult;
7764 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7765 const Expr *Arg = CE->getArg(Arg: FA->getFormatIdx().getASTIndex());
7766 StringLiteralCheckType Result = checkFormatStringExpr(
7767 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7768 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7769 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7770 if (IsFirst) {
7771 CommonResult = Result;
7772 IsFirst = false;
7773 }
7774 }
7775 if (!IsFirst)
7776 return CommonResult;
7777
7778 if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) {
7779 unsigned BuiltinID = FD->getBuiltinID();
7780 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7781 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7782 const Expr *Arg = CE->getArg(Arg: 0);
7783 return checkFormatStringExpr(
7784 S, ReferenceFormatString, E: Arg, Args, APK, format_idx,
7785 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7786 UncoveredArg, Offset, CallerFormatParamIdx,
7787 IgnoreStringsWithoutSpecifiers);
7788 }
7789 }
7790 }
7791 if (const Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E))
7792 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7793 format_idx, firstDataArg, Type, CallType,
7794 /*InFunctionCall*/ false, CheckedVarArgs,
7795 UncoveredArg, Offset, CallerFormatParamIdx,
7796 IgnoreStringsWithoutSpecifiers);
7797 return SLCT_NotALiteral;
7798 }
7799 case Stmt::ObjCMessageExprClass: {
7800 const auto *ME = cast<ObjCMessageExpr>(Val: E);
7801 if (const auto *MD = ME->getMethodDecl()) {
7802 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7803 // As a special case heuristic, if we're using the method -[NSBundle
7804 // localizedStringForKey:value:table:], ignore any key strings that lack
7805 // format specifiers. The idea is that if the key doesn't have any
7806 // format specifiers then its probably just a key to map to the
7807 // localized strings. If it does have format specifiers though, then its
7808 // likely that the text of the key is the format string in the
7809 // programmer's language, and should be checked.
7810 const ObjCInterfaceDecl *IFace;
7811 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7812 IFace->getIdentifier()->isStr(Str: "NSBundle") &&
7813 MD->getSelector().isKeywordSelector(
7814 Names: {"localizedStringForKey", "value", "table"})) {
7815 IgnoreStringsWithoutSpecifiers = true;
7816 }
7817
7818 const Expr *Arg = ME->getArg(Arg: FA->getFormatIdx().getASTIndex());
7819 return checkFormatStringExpr(
7820 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7821 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7822 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7823 }
7824 }
7825
7826 return SLCT_NotALiteral;
7827 }
7828 case Stmt::ObjCStringLiteralClass:
7829 case Stmt::StringLiteralClass: {
7830 const StringLiteral *StrE = nullptr;
7831
7832 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(Val: E))
7833 StrE = ObjCFExpr->getString();
7834 else
7835 StrE = cast<StringLiteral>(Val: E);
7836
7837 if (StrE) {
7838 if (Offset.isNegative() || Offset > StrE->getLength()) {
7839 // TODO: It would be better to have an explicit warning for out of
7840 // bounds literals.
7841 return SLCT_NotALiteral;
7842 }
7843 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(width: 64).getSExtValue());
7844 CheckFormatString(S, FExpr: &FStr, ReferenceFormatString, OrigFormatExpr: E, Args, APK,
7845 format_idx, firstDataArg, Type, inFunctionCall: InFunctionCall,
7846 CallType, CheckedVarArgs, UncoveredArg,
7847 IgnoreStringsWithoutSpecifiers);
7848 return SLCT_CheckedLiteral;
7849 }
7850
7851 return SLCT_NotALiteral;
7852 }
7853 case Stmt::BinaryOperatorClass: {
7854 const BinaryOperator *BinOp = cast<BinaryOperator>(Val: E);
7855
7856 // A string literal + an int offset is still a string literal.
7857 if (BinOp->isAdditiveOp()) {
7858 Expr::EvalResult LResult, RResult;
7859
7860 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7861 Result&: LResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7862 InConstantContext: S.isConstantEvaluatedContext());
7863 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7864 Result&: RResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7865 InConstantContext: S.isConstantEvaluatedContext());
7866
7867 if (LIsInt != RIsInt) {
7868 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7869
7870 if (LIsInt) {
7871 if (BinOpKind == BO_Add) {
7872 sumOffsets(Offset, Addend: LResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7873 E = BinOp->getRHS();
7874 goto tryAgain;
7875 }
7876 } else {
7877 sumOffsets(Offset, Addend: RResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7878 E = BinOp->getLHS();
7879 goto tryAgain;
7880 }
7881 }
7882 }
7883
7884 return SLCT_NotALiteral;
7885 }
7886 case Stmt::UnaryOperatorClass: {
7887 const UnaryOperator *UnaOp = cast<UnaryOperator>(Val: E);
7888 auto ASE = dyn_cast<ArraySubscriptExpr>(Val: UnaOp->getSubExpr());
7889 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7890 Expr::EvalResult IndexResult;
7891 if (ASE->getRHS()->EvaluateAsInt(Result&: IndexResult, Ctx: S.Context,
7892 AllowSideEffects: Expr::SE_NoSideEffects,
7893 InConstantContext: S.isConstantEvaluatedContext())) {
7894 sumOffsets(Offset, Addend: IndexResult.Val.getInt(), BinOpKind: BO_Add,
7895 /*RHS is int*/ AddendIsRight: true);
7896 E = ASE->getBase();
7897 goto tryAgain;
7898 }
7899 }
7900
7901 return SLCT_NotALiteral;
7902 }
7903
7904 default:
7905 return SLCT_NotALiteral;
7906 }
7907}
7908
7909// If this expression can be evaluated at compile-time,
7910// check if the result is a StringLiteral and return it
7911// otherwise return nullptr
7912static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7913 const Expr *E) {
7914 Expr::EvalResult Result;
7915 if (E->EvaluateAsRValue(Result, Ctx: Context) && Result.Val.isLValue()) {
7916 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7917 if (isa_and_nonnull<StringLiteral>(Val: LVE))
7918 return LVE;
7919 }
7920 return nullptr;
7921}
7922
7923StringRef Sema::GetFormatStringTypeName(FormatStringType FST) {
7924 switch (FST) {
7925 case FormatStringType::Scanf:
7926 return "scanf";
7927 case FormatStringType::Printf:
7928 return "printf";
7929 case FormatStringType::NSString:
7930 return "NSString";
7931 case FormatStringType::Strftime:
7932 return "strftime";
7933 case FormatStringType::Strfmon:
7934 return "strfmon";
7935 case FormatStringType::Kprintf:
7936 return "kprintf";
7937 case FormatStringType::FreeBSDKPrintf:
7938 return "freebsd_kprintf";
7939 case FormatStringType::OSLog:
7940 return "os_log";
7941 default:
7942 return "<unknown>";
7943 }
7944}
7945
7946FormatStringType Sema::GetFormatStringType(StringRef Flavor) {
7947 return llvm::StringSwitch<FormatStringType>(Flavor)
7948 .Cases(CaseStrings: {"gnu_scanf", "scanf"}, Value: FormatStringType::Scanf)
7949 .Cases(CaseStrings: {"gnu_printf", "printf", "printf0", "syslog"},
7950 Value: FormatStringType::Printf)
7951 .Cases(CaseStrings: {"NSString", "CFString"}, Value: FormatStringType::NSString)
7952 .Cases(CaseStrings: {"gnu_strftime", "strftime"}, Value: FormatStringType::Strftime)
7953 .Cases(CaseStrings: {"gnu_strfmon", "strfmon"}, Value: FormatStringType::Strfmon)
7954 .Cases(CaseStrings: {"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7955 Value: FormatStringType::Kprintf)
7956 .Case(S: "freebsd_kprintf", Value: FormatStringType::FreeBSDKPrintf)
7957 .Case(S: "os_trace", Value: FormatStringType::OSLog)
7958 .Case(S: "os_log", Value: FormatStringType::OSLog)
7959 .Default(Value: FormatStringType::Unknown);
7960}
7961
7962FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7963 return GetFormatStringType(Flavor: Format->getType()->getName());
7964}
7965
7966FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7967 return GetFormatStringType(Flavor: Format->getType()->getName());
7968}
7969
7970bool Sema::CheckFormatArguments(const FormatAttr *Format,
7971 ArrayRef<const Expr *> Args, bool IsCXXMember,
7972 VariadicCallType CallType, SourceLocation Loc,
7973 SourceRange Range,
7974 llvm::SmallBitVector &CheckedVarArgs) {
7975 FormatStringInfo FSI;
7976 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: Format->getFirstArg(),
7977 HasImplicitThisParam: IsCXXMember,
7978 IsVariadic: CallType != VariadicCallType::DoesNotApply, FSI: &FSI))
7979 return CheckFormatArguments(
7980 Args, FAPK: FSI.ArgPassingKind, ReferenceFormatString: nullptr, format_idx: FSI.FormatIdx, firstDataArg: FSI.FirstDataArg,
7981 Type: GetFormatStringType(Format), CallType, Loc, range: Range, CheckedVarArgs);
7982 return false;
7983}
7984
7985bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7986 ArrayRef<const Expr *> Args, bool IsCXXMember,
7987 VariadicCallType CallType, SourceLocation Loc,
7988 SourceRange Range,
7989 llvm::SmallBitVector &CheckedVarArgs) {
7990 FormatStringInfo FSI;
7991 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: 0, HasImplicitThisParam: IsCXXMember, IsVariadic: false,
7992 FSI: &FSI)) {
7993 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7994 return CheckFormatArguments(Args, FAPK: FSI.ArgPassingKind,
7995 ReferenceFormatString: Format->getFormatString(), format_idx: FSI.FormatIdx,
7996 firstDataArg: FSI.FirstDataArg, Type: GetFormatStringType(Format),
7997 CallType, Loc, range: Range, CheckedVarArgs);
7998 }
7999 return false;
8000}
8001
8002static bool CheckMissingFormatAttribute(
8003 Sema *S, ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
8004 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
8005 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
8006 SourceLocation Loc) {
8007 if (S->getDiagnostics().isIgnored(DiagID: diag::warn_missing_format_attribute, Loc))
8008 return false;
8009
8010 DeclContext *DC = S->CurContext->getEnclosingNonExpansionStatementContext();
8011 if (!isa<ObjCMethodDecl>(Val: DC) && !isa<FunctionDecl>(Val: DC) && !isa<BlockDecl>(Val: DC))
8012 return false;
8013 Decl *Caller = cast<Decl>(Val: DC)->getCanonicalDecl();
8014
8015 unsigned NumCallerParams = getFunctionOrMethodNumParams(D: Caller);
8016
8017 // Find the offset to convert between attribute and parameter indexes.
8018 unsigned CallerArgumentIndexOffset =
8019 hasImplicitObjectParameter(D: Caller) ? 2 : 1;
8020
8021 unsigned FirstArgumentIndex = -1;
8022 switch (APK) {
8023 case Sema::FormatArgumentPassingKind::FAPK_Fixed:
8024 case Sema::FormatArgumentPassingKind::FAPK_Variadic: {
8025 // As an extension, clang allows the format attribute on non-variadic
8026 // functions.
8027 // Caller must have fixed arguments to pass them to a fixed or variadic
8028 // function. Try to match caller and callee arguments. If successful, then
8029 // emit a diag with the caller idx, otherwise we can't determine the callee
8030 // arguments.
8031 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
8032 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
8033 // There aren't enough arguments in the caller to pass to callee.
8034 return false;
8035 }
8036 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
8037 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
8038 const auto *Arg =
8039 dyn_cast<DeclRefExpr>(Val: Args[CalleeIdx]->IgnoreParenCasts());
8040 if (!Arg)
8041 return false;
8042 const auto *Param = dyn_cast<ParmVarDecl>(Val: Arg->getDecl());
8043 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
8044 return false;
8045 }
8046 FirstArgumentIndex =
8047 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
8048 break;
8049 }
8050 case Sema::FormatArgumentPassingKind::FAPK_VAList:
8051 // Caller arguments are either variadic or a va_list.
8052 FirstArgumentIndex = isFunctionOrMethodVariadic(D: Caller)
8053 ? (NumCallerParams + CallerArgumentIndexOffset)
8054 : 0;
8055 break;
8056 case Sema::FormatArgumentPassingKind::FAPK_Elsewhere:
8057 // The callee has a format_matches attribute. We will emit that instead.
8058 if (!ReferenceFormatString)
8059 return false;
8060 break;
8061 }
8062
8063 // Emit the diagnostic and fixit.
8064 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
8065 StringRef FormatTypeName = S->GetFormatStringTypeName(FST: FormatType);
8066 NamedDecl *ND = dyn_cast<NamedDecl>(Val: Caller);
8067 do {
8068 std::string Attr, Fixit;
8069 llvm::raw_string_ostream AttrOS(Attr);
8070 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
8071 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
8072 << FirstArgumentIndex << ")";
8073 } else {
8074 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
8075 << ", \"";
8076 AttrOS.write_escaped(Str: ReferenceFormatString->getString());
8077 AttrOS << "\")";
8078 }
8079 AttrOS.flush();
8080 auto DB = S->Diag(Loc, DiagID: diag::warn_missing_format_attribute) << Attr;
8081 if (ND)
8082 DB << ND;
8083 else
8084 DB << "block";
8085
8086 // Blocks don't provide a correct end loc, so skip emitting a fixit.
8087 if (isa<BlockDecl>(Val: Caller))
8088 break;
8089
8090 SourceLocation SL;
8091 llvm::raw_string_ostream IS(Fixit);
8092 // The attribute goes at the start of the declaration in C/C++ functions
8093 // and methods, but after the declaration for Objective-C methods.
8094 if (isa<ObjCMethodDecl>(Val: Caller)) {
8095 IS << ' ';
8096 SL = Caller->getEndLoc();
8097 }
8098 const LangOptions &LO = S->getLangOpts();
8099 if (LO.C23 || LO.CPlusPlus11)
8100 IS << "[[gnu::" << Attr << "]]";
8101 else if (LO.ObjC || LO.GNUMode)
8102 IS << "__attribute__((" << Attr << "))";
8103 else
8104 break;
8105 if (!isa<ObjCMethodDecl>(Val: Caller)) {
8106 IS << ' ';
8107 SL = Caller->getBeginLoc();
8108 }
8109 IS.flush();
8110
8111 DB << FixItHint::CreateInsertion(InsertionLoc: SL, Code: Fixit);
8112 } while (false);
8113
8114 // Add implicit format or format_matches attribute.
8115 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
8116 Caller->addAttr(A: FormatAttr::CreateImplicit(
8117 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
8118 FormatIdx: FormatStringIndex, FirstArg: FirstArgumentIndex));
8119 } else {
8120 Caller->addAttr(A: FormatMatchesAttr::CreateImplicit(
8121 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
8122 FormatIdx: FormatStringIndex, ExpectedFormat: ReferenceFormatString));
8123 }
8124
8125 {
8126 auto DB = S->Diag(Loc: Caller->getLocation(), DiagID: diag::note_entity_declared_at);
8127 if (ND)
8128 DB << ND;
8129 else
8130 DB << "block";
8131 }
8132 return true;
8133}
8134
8135bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8136 Sema::FormatArgumentPassingKind APK,
8137 StringLiteral *ReferenceFormatString,
8138 unsigned format_idx, unsigned firstDataArg,
8139 FormatStringType Type,
8140 VariadicCallType CallType, SourceLocation Loc,
8141 SourceRange Range,
8142 llvm::SmallBitVector &CheckedVarArgs) {
8143 // CHECK: printf/scanf-like function is called with no format string.
8144 if (format_idx >= Args.size()) {
8145 Diag(Loc, DiagID: diag::warn_missing_format_string) << Range;
8146 return false;
8147 }
8148
8149 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8150
8151 // CHECK: format string is not a string literal.
8152 //
8153 // Dynamically generated format strings are difficult to
8154 // automatically vet at compile time. Requiring that format strings
8155 // are string literals: (1) permits the checking of format strings by
8156 // the compiler and thereby (2) can practically remove the source of
8157 // many format string exploits.
8158
8159 // Format string can be either ObjC string (e.g. @"%d") or
8160 // C string (e.g. "%d")
8161 // ObjC string uses the same format specifiers as C string, so we can use
8162 // the same format string checking logic for both ObjC and C strings.
8163 UncoveredArgHandler UncoveredArg;
8164 std::optional<unsigned> CallerParamIdx;
8165 StringLiteralCheckType CT = checkFormatStringExpr(
8166 S&: *this, ReferenceFormatString, E: OrigFormatExpr, Args, APK, format_idx,
8167 firstDataArg, Type, CallType,
8168 /*IsFunctionCall*/ InFunctionCall: true, CheckedVarArgs, UncoveredArg,
8169 /*no string offset*/ Offset: llvm::APSInt(64, false) = 0, CallerFormatParamIdx: &CallerParamIdx);
8170
8171 // Generate a diagnostic where an uncovered argument is detected.
8172 if (UncoveredArg.hasUncoveredArg()) {
8173 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8174 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8175 UncoveredArg.Diagnose(S&: *this, /*IsFunctionCall*/true, ArgExpr: Args[ArgIdx]);
8176 }
8177
8178 if (CT != SLCT_NotALiteral)
8179 // Literal format string found, check done!
8180 return CT == SLCT_CheckedLiteral;
8181
8182 // Do not emit diag when the string param is a macro expansion and the
8183 // format is either NSString or CFString. This is a hack to prevent
8184 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8185 // which are usually used in place of NS and CF string literals.
8186 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8187 if (Type == FormatStringType::NSString &&
8188 SourceMgr.isInSystemMacro(loc: FormatLoc))
8189 return false;
8190
8191 if (CallerParamIdx && CheckMissingFormatAttribute(
8192 S: this, Args, APK, ReferenceFormatString, FormatIdx: format_idx,
8193 FirstDataArg: firstDataArg, FormatType: Type, CallerParamIdx: *CallerParamIdx, Loc))
8194 return false;
8195
8196 // Strftime is particular as it always uses a single 'time' argument,
8197 // so it is safe to pass a non-literal string.
8198 if (Type == FormatStringType::Strftime)
8199 return false;
8200
8201 // If there are no arguments specified, warn with -Wformat-security, otherwise
8202 // warn only with -Wformat-nonliteral.
8203 if (Args.size() == firstDataArg) {
8204 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral_noargs)
8205 << OrigFormatExpr->getSourceRange();
8206 switch (Type) {
8207 default:
8208 break;
8209 case FormatStringType::Kprintf:
8210 case FormatStringType::FreeBSDKPrintf:
8211 case FormatStringType::Printf:
8212 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
8213 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "\"%s\", ");
8214 break;
8215 case FormatStringType::NSString:
8216 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
8217 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "@\"%@\", ");
8218 break;
8219 }
8220 } else {
8221 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral)
8222 << OrigFormatExpr->getSourceRange();
8223 }
8224 return false;
8225}
8226
8227namespace {
8228
8229class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8230protected:
8231 Sema &S;
8232 const FormatStringLiteral *FExpr;
8233 const Expr *OrigFormatExpr;
8234 const FormatStringType FSType;
8235 const unsigned FirstDataArg;
8236 const unsigned NumDataArgs;
8237 const char *Beg; // Start of format string.
8238 const Sema::FormatArgumentPassingKind ArgPassingKind;
8239 ArrayRef<const Expr *> Args;
8240 unsigned FormatIdx;
8241 llvm::SmallBitVector CoveredArgs;
8242 bool usesPositionalArgs = false;
8243 bool atFirstArg = true;
8244 bool inFunctionCall;
8245 VariadicCallType CallType;
8246 llvm::SmallBitVector &CheckedVarArgs;
8247 UncoveredArgHandler &UncoveredArg;
8248
8249public:
8250 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8251 const Expr *origFormatExpr, const FormatStringType type,
8252 unsigned firstDataArg, unsigned numDataArgs,
8253 const char *beg, Sema::FormatArgumentPassingKind APK,
8254 ArrayRef<const Expr *> Args, unsigned formatIdx,
8255 bool inFunctionCall, VariadicCallType callType,
8256 llvm::SmallBitVector &CheckedVarArgs,
8257 UncoveredArgHandler &UncoveredArg)
8258 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8259 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8260 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
8261 inFunctionCall(inFunctionCall), CallType(callType),
8262 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8263 CoveredArgs.resize(N: numDataArgs);
8264 CoveredArgs.reset();
8265 }
8266
8267 bool HasFormatArguments() const {
8268 return ArgPassingKind == Sema::FAPK_Fixed ||
8269 ArgPassingKind == Sema::FAPK_Variadic;
8270 }
8271
8272 void DoneProcessing();
8273
8274 void HandleIncompleteSpecifier(const char *startSpecifier,
8275 unsigned specifierLen) override;
8276
8277 void HandleInvalidLengthModifier(
8278 const analyze_format_string::FormatSpecifier &FS,
8279 const analyze_format_string::ConversionSpecifier &CS,
8280 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
8281
8282 void HandleNonStandardLengthModifier(
8283 const analyze_format_string::FormatSpecifier &FS,
8284 const char *startSpecifier, unsigned specifierLen);
8285
8286 void HandleNonStandardConversionSpecifier(
8287 const analyze_format_string::ConversionSpecifier &CS,
8288 const char *startSpecifier, unsigned specifierLen);
8289
8290 void HandlePosition(const char *startPos, unsigned posLen) override;
8291
8292 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
8293 analyze_format_string::PositionContext p) override;
8294
8295 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8296
8297 void HandleNullChar(const char *nullCharacter) override;
8298
8299 template <typename Range>
8300 static void
8301 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8302 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8303 bool IsStringLocation, Range StringRange,
8304 ArrayRef<FixItHint> Fixit = {});
8305
8306protected:
8307 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8308 const char *startSpec,
8309 unsigned specifierLen,
8310 const char *csStart, unsigned csLen);
8311
8312 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8313 const char *startSpec,
8314 unsigned specifierLen);
8315
8316 SourceRange getFormatStringRange();
8317 CharSourceRange getSpecifierRange(const char *startSpecifier,
8318 unsigned specifierLen);
8319 SourceLocation getLocationOfByte(const char *x);
8320
8321 const Expr *getDataArg(unsigned i) const;
8322
8323 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8324 const analyze_format_string::ConversionSpecifier &CS,
8325 const char *startSpecifier, unsigned specifierLen,
8326 unsigned argIndex);
8327
8328 bool CheckUnsupportedType(const analyze_format_string::ArgType &AT,
8329 const Expr *E, const char *startSpecifier,
8330 unsigned specifierLen);
8331
8332 template <typename Range>
8333 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8334 bool IsStringLocation, Range StringRange,
8335 ArrayRef<FixItHint> Fixit = {});
8336};
8337
8338} // namespace
8339
8340SourceRange CheckFormatHandler::getFormatStringRange() {
8341 return OrigFormatExpr->getSourceRange();
8342}
8343
8344CharSourceRange
8345CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
8346 unsigned specifierLen) {
8347 SourceLocation Start = getLocationOfByte(x: startSpecifier);
8348 SourceLocation End = getLocationOfByte(x: startSpecifier + specifierLen - 1);
8349
8350 // Advance the end SourceLocation by one due to half-open ranges.
8351 End = End.getLocWithOffset(Offset: 1);
8352
8353 return CharSourceRange::getCharRange(B: Start, E: End);
8354}
8355
8356SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8357 return FExpr->getLocationOfByte(ByteNo: x - Beg, SM: S.getSourceManager(),
8358 Features: S.getLangOpts(), Target: S.Context.getTargetInfo());
8359}
8360
8361void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8362 unsigned specifierLen) {
8363 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_incomplete_specifier),
8364 Loc: getLocationOfByte(x: startSpecifier),
8365 /*IsStringLocation*/ true,
8366 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8367}
8368
8369bool CheckFormatHandler::CheckUnsupportedType(
8370 const analyze_format_string::ArgType &AT, const Expr *E,
8371 const char *StartSpecifier, unsigned SpecifierLen) {
8372 if (!AT.isUnsupported())
8373 return false;
8374
8375 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_unsupported_type)
8376 << AT.getRepresentativeTypeName(C&: S.Context),
8377 Loc: E->getExprLoc(), /*IsStringLocation=*/false,
8378 StringRange: getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen));
8379 return true;
8380}
8381
8382void CheckFormatHandler::HandleInvalidLengthModifier(
8383 const analyze_format_string::FormatSpecifier &FS,
8384 const analyze_format_string::ConversionSpecifier &CS,
8385 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8386 using namespace analyze_format_string;
8387
8388 const LengthModifier &LM = FS.getLengthModifier();
8389 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
8390
8391 // See if we know how to fix this length modifier.
8392 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8393 if (FixedLM) {
8394 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
8395 Loc: getLocationOfByte(x: LM.getStart()),
8396 /*IsStringLocation*/ true,
8397 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8398
8399 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
8400 << FixedLM->toString()
8401 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
8402
8403 } else {
8404 FixItHint Hint;
8405 if (DiagID == diag::warn_format_nonsensical_length)
8406 Hint = FixItHint::CreateRemoval(RemoveRange: LMRange);
8407
8408 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
8409 Loc: getLocationOfByte(x: LM.getStart()),
8410 /*IsStringLocation*/ true,
8411 StringRange: getSpecifierRange(startSpecifier, specifierLen), FixIt: Hint);
8412 }
8413}
8414
8415void CheckFormatHandler::HandleNonStandardLengthModifier(
8416 const analyze_format_string::FormatSpecifier &FS,
8417 const char *startSpecifier, unsigned specifierLen) {
8418 using namespace analyze_format_string;
8419
8420 const LengthModifier &LM = FS.getLengthModifier();
8421 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
8422
8423 // See if we know how to fix this length modifier.
8424 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8425 if (FixedLM) {
8426 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8427 << LM.toString() << 0,
8428 Loc: getLocationOfByte(x: LM.getStart()),
8429 /*IsStringLocation*/ true,
8430 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8431
8432 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
8433 << FixedLM->toString()
8434 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
8435
8436 } else {
8437 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8438 << LM.toString() << 0,
8439 Loc: getLocationOfByte(x: LM.getStart()),
8440 /*IsStringLocation*/ true,
8441 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8442 }
8443}
8444
8445void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8446 const analyze_format_string::ConversionSpecifier &CS,
8447 const char *startSpecifier, unsigned specifierLen) {
8448 using namespace analyze_format_string;
8449
8450 // See if we know how to fix this conversion specifier.
8451 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8452 if (FixedCS) {
8453 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8454 << CS.toString() << /*conversion specifier*/ 1,
8455 Loc: getLocationOfByte(x: CS.getStart()),
8456 /*IsStringLocation*/ true,
8457 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8458
8459 CharSourceRange CSRange = getSpecifierRange(startSpecifier: CS.getStart(), specifierLen: CS.getLength());
8460 S.Diag(Loc: getLocationOfByte(x: CS.getStart()), DiagID: diag::note_format_fix_specifier)
8461 << FixedCS->toString()
8462 << FixItHint::CreateReplacement(RemoveRange: CSRange, Code: FixedCS->toString());
8463 } else {
8464 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8465 << CS.toString() << /*conversion specifier*/ 1,
8466 Loc: getLocationOfByte(x: CS.getStart()),
8467 /*IsStringLocation*/ true,
8468 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8469 }
8470}
8471
8472void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8473 if (!S.getDiagnostics().isIgnored(
8474 DiagID: diag::warn_format_non_standard_positional_arg, Loc: SourceLocation()))
8475 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard_positional_arg),
8476 Loc: getLocationOfByte(x: startPos),
8477 /*IsStringLocation*/ true,
8478 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
8479}
8480
8481void CheckFormatHandler::HandleInvalidPosition(
8482 const char *startSpecifier, unsigned specifierLen,
8483 analyze_format_string::PositionContext p) {
8484 if (!S.getDiagnostics().isIgnored(
8485 DiagID: diag::warn_format_invalid_positional_specifier, Loc: SourceLocation()))
8486 EmitFormatDiagnostic(
8487 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8488 Loc: getLocationOfByte(x: startSpecifier), /*IsStringLocation*/ true,
8489 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8490}
8491
8492void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8493 unsigned posLen) {
8494 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_format_zero_positional_specifier,
8495 Loc: SourceLocation()))
8496 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_zero_positional_specifier),
8497 Loc: getLocationOfByte(x: startPos),
8498 /*IsStringLocation*/ true,
8499 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
8500}
8501
8502void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8503 if (!isa<ObjCStringLiteral>(Val: OrigFormatExpr)) {
8504 // The presence of a null character is likely an error.
8505 EmitFormatDiagnostic(
8506 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_contains_null_char),
8507 Loc: getLocationOfByte(x: nullCharacter), /*IsStringLocation*/ true,
8508 StringRange: getFormatStringRange());
8509 }
8510}
8511
8512// Note that this may return NULL if there was an error parsing or building
8513// one of the argument expressions.
8514const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8515 return Args[FirstDataArg + i];
8516}
8517
8518void CheckFormatHandler::DoneProcessing() {
8519 // Does the number of data arguments exceed the number of
8520 // format conversions in the format string?
8521 if (HasFormatArguments()) {
8522 // Find any arguments that weren't covered.
8523 CoveredArgs.flip();
8524 signed notCoveredArg = CoveredArgs.find_first();
8525 if (notCoveredArg >= 0) {
8526 assert((unsigned)notCoveredArg < NumDataArgs);
8527 UncoveredArg.Update(NewFirstUncoveredArg: notCoveredArg, StrExpr: OrigFormatExpr);
8528 } else {
8529 UncoveredArg.setAllCovered();
8530 }
8531 }
8532}
8533
8534void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8535 const Expr *ArgExpr) {
8536 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8537
8538 if (!ArgExpr)
8539 return;
8540
8541 SourceLocation Loc = ArgExpr->getBeginLoc();
8542
8543 if (S.getSourceManager().isInSystemMacro(loc: Loc))
8544 return;
8545
8546 PartialDiagnostic PDiag = S.PDiag(DiagID: diag::warn_printf_data_arg_not_used);
8547 for (auto E : DiagnosticExprs)
8548 PDiag << E->getSourceRange();
8549
8550 CheckFormatHandler::EmitFormatDiagnostic(
8551 S, InFunctionCall: IsFunctionCall, ArgumentExpr: DiagnosticExprs[0], PDiag, Loc,
8552 /*IsStringLocation*/ false, StringRange: DiagnosticExprs[0]->getSourceRange());
8553}
8554
8555bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8556 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8557 unsigned specifierLen, const char *csStart, unsigned csLen) {
8558 bool keepGoing = true;
8559 if (argIndex < NumDataArgs) {
8560 // Consider the argument coverered, even though the specifier doesn't
8561 // make sense.
8562 CoveredArgs.set(argIndex);
8563 } else {
8564 // If argIndex exceeds the number of data arguments we
8565 // don't issue a warning because that is just a cascade of warnings (and
8566 // they may have intended '%%' anyway). We don't want to continue processing
8567 // the format string after this point, however, as we will like just get
8568 // gibberish when trying to match arguments.
8569 keepGoing = false;
8570 }
8571
8572 StringRef Specifier(csStart, csLen);
8573
8574 // If the specifier in non-printable, it could be the first byte of a UTF-8
8575 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8576 // hex value.
8577 std::string CodePointStr;
8578 if (!llvm::sys::locale::isPrint(c: *csStart)) {
8579 llvm::UTF32 CodePoint;
8580 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8581 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8582 llvm::ConversionResult Result =
8583 llvm::convertUTF8Sequence(source: B, sourceEnd: E, target: &CodePoint, flags: llvm::strictConversion);
8584
8585 if (Result != llvm::conversionOK) {
8586 unsigned char FirstChar = *csStart;
8587 CodePoint = (llvm::UTF32)FirstChar;
8588 }
8589
8590 llvm::raw_string_ostream OS(CodePointStr);
8591 if (CodePoint < 256)
8592 OS << "\\x" << llvm::format(Fmt: "%02x", Vals: CodePoint);
8593 else if (CodePoint <= 0xFFFF)
8594 OS << "\\u" << llvm::format(Fmt: "%04x", Vals: CodePoint);
8595 else
8596 OS << "\\U" << llvm::format(Fmt: "%08x", Vals: CodePoint);
8597 Specifier = CodePointStr;
8598 }
8599
8600 EmitFormatDiagnostic(
8601 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_conversion) << Specifier, Loc,
8602 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
8603
8604 return keepGoing;
8605}
8606
8607void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8608 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8609 EmitFormatDiagnostic(
8610 PDiag: S.PDiag(DiagID: diag::warn_format_mix_positional_nonpositional_args), Loc,
8611 /*isStringLoc*/ IsStringLocation: true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
8612}
8613
8614bool CheckFormatHandler::CheckNumArgs(
8615 const analyze_format_string::FormatSpecifier &FS,
8616 const analyze_format_string::ConversionSpecifier &CS,
8617 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8618
8619 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8620 PartialDiagnostic PDiag =
8621 FS.usesPositionalArg()
8622 ? (S.PDiag(DiagID: diag::warn_printf_positional_arg_exceeds_data_args)
8623 << (argIndex + 1) << NumDataArgs)
8624 : S.PDiag(DiagID: diag::warn_printf_insufficient_data_args);
8625 EmitFormatDiagnostic(PDiag, Loc: getLocationOfByte(x: CS.getStart()),
8626 /*IsStringLocation*/ true,
8627 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8628
8629 // Since more arguments than conversion tokens are given, by extension
8630 // all arguments are covered, so mark this as so.
8631 UncoveredArg.setAllCovered();
8632 return false;
8633 }
8634 return true;
8635}
8636
8637template <typename Range>
8638void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8639 SourceLocation Loc,
8640 bool IsStringLocation,
8641 Range StringRange,
8642 ArrayRef<FixItHint> FixIt) {
8643 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8644 IsStringLocation, StringRange, FixIt);
8645}
8646
8647/// If the format string is not within the function call, emit a note
8648/// so that the function call and string are in diagnostic messages.
8649///
8650/// \param InFunctionCall if true, the format string is within the function
8651/// call and only one diagnostic message will be produced. Otherwise, an
8652/// extra note will be emitted pointing to location of the format string.
8653///
8654/// \param ArgumentExpr the expression that is passed as the format string
8655/// argument in the function call. Used for getting locations when two
8656/// diagnostics are emitted.
8657///
8658/// \param PDiag the callee should already have provided any strings for the
8659/// diagnostic message. This function only adds locations and fixits
8660/// to diagnostics.
8661///
8662/// \param Loc primary location for diagnostic. If two diagnostics are
8663/// required, one will be at Loc and a new SourceLocation will be created for
8664/// the other one.
8665///
8666/// \param IsStringLocation if true, Loc points to the format string should be
8667/// used for the note. Otherwise, Loc points to the argument list and will
8668/// be used with PDiag.
8669///
8670/// \param StringRange some or all of the string to highlight. This is
8671/// templated so it can accept either a CharSourceRange or a SourceRange.
8672///
8673/// \param FixIt optional fix it hint for the format string.
8674template <typename Range>
8675void CheckFormatHandler::EmitFormatDiagnostic(
8676 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8677 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8678 Range StringRange, ArrayRef<FixItHint> FixIt) {
8679 if (InFunctionCall) {
8680 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PD: PDiag);
8681 D << StringRange;
8682 D << FixIt;
8683 } else {
8684 S.Diag(Loc: IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PD: PDiag)
8685 << ArgumentExpr->getSourceRange();
8686
8687 const Sema::SemaDiagnosticBuilder &Note =
8688 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8689 diag::note_format_string_defined);
8690
8691 Note << StringRange;
8692 Note << FixIt;
8693 }
8694}
8695
8696//===--- CHECK: Printf format string checking -----------------------------===//
8697
8698namespace {
8699
8700class CheckPrintfHandler : public CheckFormatHandler {
8701public:
8702 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8703 const Expr *origFormatExpr, const FormatStringType type,
8704 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8705 const char *beg, Sema::FormatArgumentPassingKind APK,
8706 ArrayRef<const Expr *> Args, unsigned formatIdx,
8707 bool inFunctionCall, VariadicCallType CallType,
8708 llvm::SmallBitVector &CheckedVarArgs,
8709 UncoveredArgHandler &UncoveredArg)
8710 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8711 numDataArgs, beg, APK, Args, formatIdx,
8712 inFunctionCall, CallType, CheckedVarArgs,
8713 UncoveredArg) {}
8714
8715 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8716
8717 /// Returns true if '%@' specifiers are allowed in the format string.
8718 bool allowsObjCArg() const {
8719 return FSType == FormatStringType::NSString ||
8720 FSType == FormatStringType::OSLog ||
8721 FSType == FormatStringType::OSTrace;
8722 }
8723
8724 bool HandleInvalidPrintfConversionSpecifier(
8725 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8726 unsigned specifierLen) override;
8727
8728 void handleInvalidMaskType(StringRef MaskType) override;
8729
8730 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8731 const char *startSpecifier, unsigned specifierLen,
8732 const TargetInfo &Target) override;
8733 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8734 const char *StartSpecifier, unsigned SpecifierLen,
8735 const Expr *E);
8736
8737 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8738 unsigned k, const char *startSpecifier,
8739 unsigned specifierLen);
8740 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8741 const analyze_printf::OptionalAmount &Amt,
8742 unsigned type, const char *startSpecifier,
8743 unsigned specifierLen);
8744 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8745 const analyze_printf::OptionalFlag &flag,
8746 const char *startSpecifier, unsigned specifierLen);
8747 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8748 const analyze_printf::OptionalFlag &ignoredFlag,
8749 const analyze_printf::OptionalFlag &flag,
8750 const char *startSpecifier, unsigned specifierLen);
8751 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8752
8753 void HandleEmptyObjCModifierFlag(const char *startFlag,
8754 unsigned flagLen) override;
8755
8756 void HandleInvalidObjCModifierFlag(const char *startFlag,
8757 unsigned flagLen) override;
8758
8759 void
8760 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8761 const char *flagsEnd,
8762 const char *conversionPosition) override;
8763};
8764
8765/// Keeps around the information needed to verify that two specifiers are
8766/// compatible.
8767class EquatableFormatArgument {
8768public:
8769 enum SpecifierSensitivity : unsigned {
8770 SS_None,
8771 SS_Private,
8772 SS_Public,
8773 SS_Sensitive
8774 };
8775
8776 enum FormatArgumentRole : unsigned {
8777 FAR_Data,
8778 FAR_FieldWidth,
8779 FAR_Precision,
8780 FAR_Auxiliary, // FreeBSD kernel %b and %D
8781 };
8782
8783private:
8784 analyze_format_string::ArgType ArgType;
8785 analyze_format_string::LengthModifier LengthMod;
8786 StringRef SpecifierLetter;
8787 CharSourceRange Range;
8788 SourceLocation ElementLoc;
8789 FormatArgumentRole Role : 2;
8790 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8791 unsigned Position : 14;
8792 unsigned ModifierFor : 14; // not set for FAR_Data
8793
8794 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8795 bool InFunctionCall) const;
8796
8797public:
8798 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8799 analyze_format_string::LengthModifier LengthMod,
8800 StringRef SpecifierLetter,
8801 analyze_format_string::ArgType ArgType,
8802 FormatArgumentRole Role,
8803 SpecifierSensitivity Sensitivity, unsigned Position,
8804 unsigned ModifierFor)
8805 : ArgType(ArgType), LengthMod(LengthMod),
8806 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8807 Role(Role), Sensitivity(Sensitivity), Position(Position),
8808 ModifierFor(ModifierFor) {}
8809
8810 unsigned getPosition() const { return Position; }
8811 SourceLocation getSourceLocation() const { return ElementLoc; }
8812 CharSourceRange getSourceRange() const { return Range; }
8813 analyze_format_string::LengthModifier getLengthModifier() const {
8814 return LengthMod;
8815 }
8816 void setModifierFor(unsigned V) { ModifierFor = V; }
8817
8818 std::string buildFormatSpecifier() const {
8819 std::string result;
8820 llvm::raw_string_ostream(result)
8821 << getLengthModifier().toString() << SpecifierLetter;
8822 return result;
8823 }
8824
8825 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8826 const Expr *FmtExpr, bool InFunctionCall) const;
8827};
8828
8829/// Turns format strings into lists of EquatableSpecifier objects.
8830class DecomposePrintfHandler : public CheckPrintfHandler {
8831 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8832 bool HadError;
8833
8834 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8835 const Expr *origFormatExpr,
8836 const FormatStringType type, unsigned firstDataArg,
8837 unsigned numDataArgs, bool isObjC, const char *beg,
8838 Sema::FormatArgumentPassingKind APK,
8839 ArrayRef<const Expr *> Args, unsigned formatIdx,
8840 bool inFunctionCall, VariadicCallType CallType,
8841 llvm::SmallBitVector &CheckedVarArgs,
8842 UncoveredArgHandler &UncoveredArg,
8843 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8844 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8845 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8846 inFunctionCall, CallType, CheckedVarArgs,
8847 UncoveredArg),
8848 Specs(Specs), HadError(false) {}
8849
8850public:
8851 static bool
8852 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8853 FormatStringType type, bool IsObjC, bool InFunctionCall,
8854 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8855
8856 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8857 const char *startSpecifier,
8858 unsigned specifierLen,
8859 const TargetInfo &Target) override;
8860};
8861
8862} // namespace
8863
8864bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8865 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8866 unsigned specifierLen) {
8867 const analyze_printf::PrintfConversionSpecifier &CS =
8868 FS.getConversionSpecifier();
8869
8870 return HandleInvalidConversionSpecifier(
8871 argIndex: FS.getArgIndex(), Loc: getLocationOfByte(x: CS.getStart()), startSpec: startSpecifier,
8872 specifierLen, csStart: CS.getStart(), csLen: CS.getLength());
8873}
8874
8875void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8876 S.Diag(Loc: getLocationOfByte(x: MaskType.data()), DiagID: diag::err_invalid_mask_type_size);
8877}
8878
8879// Error out if struct or complex type argments are passed to os_log.
8880static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType,
8881 QualType T) {
8882 if (FSType != FormatStringType::OSLog)
8883 return false;
8884 return T->isRecordType() || T->isComplexType();
8885}
8886
8887bool CheckPrintfHandler::HandleAmount(
8888 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8889 const char *startSpecifier, unsigned specifierLen) {
8890 if (Amt.hasDataArgument()) {
8891 if (HasFormatArguments()) {
8892 unsigned argIndex = Amt.getArgIndex();
8893 if (argIndex >= NumDataArgs) {
8894 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_asterisk_missing_arg)
8895 << k,
8896 Loc: getLocationOfByte(x: Amt.getStart()),
8897 /*IsStringLocation*/ true,
8898 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8899 // Don't do any more checking. We will just emit
8900 // spurious errors.
8901 return false;
8902 }
8903
8904 // Type check the data argument. It should be an 'int'.
8905 // Although not in conformance with C99, we also allow the argument to be
8906 // an 'unsigned int' as that is a reasonably safe case. GCC also
8907 // doesn't emit a warning for that case.
8908 CoveredArgs.set(argIndex);
8909 const Expr *Arg = getDataArg(i: argIndex);
8910 if (!Arg)
8911 return false;
8912
8913 QualType T = Arg->getType();
8914
8915 const analyze_printf::ArgType &AT = Amt.getArgType(Ctx&: S.Context);
8916 assert(AT.isValid());
8917
8918 if (!AT.matchesType(C&: S.Context, argTy: T)) {
8919 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8920 ? diag::err_printf_asterisk_wrong_type
8921 : diag::warn_printf_asterisk_wrong_type;
8922 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID)
8923 << k << AT.getRepresentativeTypeName(C&: S.Context)
8924 << T << Arg->getSourceRange(),
8925 Loc: getLocationOfByte(x: Amt.getStart()),
8926 /*IsStringLocation*/ true,
8927 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8928 // Don't do any more checking. We will just emit
8929 // spurious errors.
8930 return false;
8931 }
8932 }
8933 }
8934 return true;
8935}
8936
8937void CheckPrintfHandler::HandleInvalidAmount(
8938 const analyze_printf::PrintfSpecifier &FS,
8939 const analyze_printf::OptionalAmount &Amt, unsigned type,
8940 const char *startSpecifier, unsigned specifierLen) {
8941 const analyze_printf::PrintfConversionSpecifier &CS =
8942 FS.getConversionSpecifier();
8943
8944 FixItHint fixit =
8945 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8946 ? FixItHint::CreateRemoval(
8947 RemoveRange: getSpecifierRange(startSpecifier: Amt.getStart(), specifierLen: Amt.getConstantLength()))
8948 : FixItHint();
8949
8950 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_optional_amount)
8951 << type << CS.toString(),
8952 Loc: getLocationOfByte(x: Amt.getStart()),
8953 /*IsStringLocation*/ true,
8954 StringRange: getSpecifierRange(startSpecifier, specifierLen), FixIt: fixit);
8955}
8956
8957void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8958 const analyze_printf::OptionalFlag &flag,
8959 const char *startSpecifier,
8960 unsigned specifierLen) {
8961 // Warn about pointless flag with a fixit removal.
8962 const analyze_printf::PrintfConversionSpecifier &CS =
8963 FS.getConversionSpecifier();
8964 EmitFormatDiagnostic(
8965 PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_flag)
8966 << flag.toString() << CS.toString(),
8967 Loc: getLocationOfByte(x: flag.getPosition()),
8968 /*IsStringLocation*/ true,
8969 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8970 FixIt: FixItHint::CreateRemoval(RemoveRange: getSpecifierRange(startSpecifier: flag.getPosition(), specifierLen: 1)));
8971}
8972
8973void CheckPrintfHandler::HandleIgnoredFlag(
8974 const analyze_printf::PrintfSpecifier &FS,
8975 const analyze_printf::OptionalFlag &ignoredFlag,
8976 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
8977 unsigned specifierLen) {
8978 // Warn about ignored flag with a fixit removal.
8979 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_ignored_flag)
8980 << ignoredFlag.toString() << flag.toString(),
8981 Loc: getLocationOfByte(x: ignoredFlag.getPosition()),
8982 /*IsStringLocation*/ true,
8983 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8984 FixIt: FixItHint::CreateRemoval(
8985 RemoveRange: getSpecifierRange(startSpecifier: ignoredFlag.getPosition(), specifierLen: 1)));
8986}
8987
8988void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8989 unsigned flagLen) {
8990 // Warn about an empty flag.
8991 EmitFormatDiagnostic(
8992 PDiag: S.PDiag(DiagID: diag::warn_printf_empty_objc_flag), Loc: getLocationOfByte(x: startFlag),
8993 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen));
8994}
8995
8996void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8997 unsigned flagLen) {
8998 // Warn about an invalid flag.
8999 auto Range = getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen);
9000 StringRef flag(startFlag, flagLen);
9001 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_invalid_objc_flag) << flag,
9002 Loc: getLocationOfByte(x: startFlag),
9003 /*IsStringLocation*/ true, StringRange: Range,
9004 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
9005}
9006
9007void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9008 const char *flagsStart, const char *flagsEnd,
9009 const char *conversionPosition) {
9010 // Warn about using '[...]' without a '@' conversion.
9011 auto Range = getSpecifierRange(startSpecifier: flagsStart, specifierLen: flagsEnd - flagsStart + 1);
9012 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9013 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag) << StringRef(conversionPosition, 1),
9014 Loc: getLocationOfByte(x: conversionPosition),
9015 /*IsStringLocation*/ true, StringRange: Range,
9016 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
9017}
9018
9019void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
9020 const Expr *FmtExpr,
9021 bool InFunctionCall) const {
9022 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, ArgumentExpr: FmtExpr, PDiag,
9023 Loc: ElementLoc, IsStringLocation: true, StringRange: Range);
9024}
9025
9026bool EquatableFormatArgument::VerifyCompatible(
9027 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
9028 bool InFunctionCall) const {
9029 using MK = analyze_format_string::ArgType::MatchKind;
9030 if (Role != Other.Role) {
9031 // diagnose and stop
9032 EmitDiagnostic(
9033 S, PDiag: S.PDiag(DiagID: diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
9034 FmtExpr, InFunctionCall);
9035 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
9036 return false;
9037 }
9038
9039 if (Role != FAR_Data) {
9040 if (ModifierFor != Other.ModifierFor) {
9041 // diagnose and stop
9042 EmitDiagnostic(S,
9043 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_modifierfor_mismatch)
9044 << (ModifierFor + 1) << (Other.ModifierFor + 1),
9045 FmtExpr, InFunctionCall);
9046 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
9047 return false;
9048 }
9049 return true;
9050 }
9051
9052 bool HadError = false;
9053 if (Sensitivity != Other.Sensitivity) {
9054 // diagnose and continue
9055 EmitDiagnostic(S,
9056 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_sensitivity_mismatch)
9057 << Sensitivity << Other.Sensitivity,
9058 FmtExpr, InFunctionCall);
9059 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
9060 << 0 << Other.Range;
9061 }
9062
9063 switch (ArgType.matchesArgType(C&: S.Context, other: Other.ArgType)) {
9064 case MK::Match:
9065 break;
9066
9067 case MK::MatchPromotion:
9068 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
9069 // MatchPromotion is treated as a failure by format_matches.
9070 case MK::NoMatch:
9071 case MK::NoMatchTypeConfusion:
9072 case MK::NoMatchPromotionTypeConfusion:
9073 EmitDiagnostic(S,
9074 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch)
9075 << buildFormatSpecifier()
9076 << Other.buildFormatSpecifier(),
9077 FmtExpr, InFunctionCall);
9078 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
9079 << 0 << Other.Range;
9080 break;
9081
9082 case MK::NoMatchPedantic:
9083 EmitDiagnostic(S,
9084 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch_pedantic)
9085 << buildFormatSpecifier()
9086 << Other.buildFormatSpecifier(),
9087 FmtExpr, InFunctionCall);
9088 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
9089 << 0 << Other.Range;
9090 break;
9091
9092 case MK::NoMatchSignedness:
9093 EmitDiagnostic(S,
9094 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_sign_mismatch)
9095 << buildFormatSpecifier()
9096 << Other.buildFormatSpecifier(),
9097 FmtExpr, InFunctionCall);
9098 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
9099 << 0 << Other.Range;
9100 break;
9101 }
9102 return !HadError;
9103}
9104
9105bool DecomposePrintfHandler::GetSpecifiers(
9106 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
9107 FormatStringType Type, bool IsObjC, bool InFunctionCall,
9108 llvm::SmallVectorImpl<EquatableFormatArgument> &Args) {
9109 StringRef Data = FSL->getString();
9110 const char *Str = Data.data();
9111 llvm::SmallBitVector BV;
9112 UncoveredArgHandler UA;
9113 const Expr *PrintfArgs[] = {FSL->getFormatString()};
9114 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
9115 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
9116 InFunctionCall, VariadicCallType::DoesNotApply, BV,
9117 UA, Args);
9118
9119 if (!analyze_format_string::ParsePrintfString(
9120 H, beg: Str, end: Str + Data.size(), LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
9121 isFreeBSDKPrintf: Type == FormatStringType::FreeBSDKPrintf))
9122 H.DoneProcessing();
9123 if (H.HadError)
9124 return false;
9125
9126 llvm::stable_sort(Range&: Args, C: [](const EquatableFormatArgument &A,
9127 const EquatableFormatArgument &B) {
9128 return A.getPosition() < B.getPosition();
9129 });
9130 return true;
9131}
9132
9133bool DecomposePrintfHandler::HandlePrintfSpecifier(
9134 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9135 unsigned specifierLen, const TargetInfo &Target) {
9136 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
9137 specifierLen, Target)) {
9138 HadError = true;
9139 return false;
9140 }
9141
9142 // Do not add any specifiers to the list for %%. This is possibly incorrect
9143 // if using a precision/width with a data argument, but that combination is
9144 // meaningless and we wouldn't know which format to attach the
9145 // precision/width to.
9146 const auto &CS = FS.getConversionSpecifier();
9147 if (CS.getKind() == analyze_format_string::ConversionSpecifier::PercentArg)
9148 return true;
9149
9150 // have to patch these to have the right ModifierFor if they are used
9151 const unsigned Unset = ~0;
9152 unsigned FieldWidthIndex = Unset;
9153 unsigned PrecisionIndex = Unset;
9154
9155 // field width?
9156 const auto &FieldWidth = FS.getFieldWidth();
9157 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
9158 FieldWidthIndex = Specs.size();
9159 Specs.emplace_back(
9160 Args: getSpecifierRange(startSpecifier, specifierLen),
9161 Args: getLocationOfByte(x: FieldWidth.getStart()),
9162 Args: analyze_format_string::LengthModifier(), Args: FieldWidth.getCharacters(),
9163 Args: FieldWidth.getArgType(Ctx&: S.Context),
9164 Args: EquatableFormatArgument::FAR_FieldWidth,
9165 Args: EquatableFormatArgument::SS_None,
9166 Args: FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
9167 : FieldWidthIndex,
9168 Args: 0);
9169 }
9170 // precision?
9171 const auto &Precision = FS.getPrecision();
9172 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
9173 PrecisionIndex = Specs.size();
9174 Specs.emplace_back(
9175 Args: getSpecifierRange(startSpecifier, specifierLen),
9176 Args: getLocationOfByte(x: Precision.getStart()),
9177 Args: analyze_format_string::LengthModifier(), Args: Precision.getCharacters(),
9178 Args: Precision.getArgType(Ctx&: S.Context), Args: EquatableFormatArgument::FAR_Precision,
9179 Args: EquatableFormatArgument::SS_None,
9180 Args: Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
9181 : PrecisionIndex,
9182 Args: 0);
9183 }
9184
9185 // this specifier
9186 unsigned SpecIndex =
9187 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
9188 if (FieldWidthIndex != Unset)
9189 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
9190 if (PrecisionIndex != Unset)
9191 Specs[PrecisionIndex].setModifierFor(SpecIndex);
9192
9193 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
9194 if (FS.isPrivate())
9195 Sensitivity = EquatableFormatArgument::SS_Private;
9196 else if (FS.isPublic())
9197 Sensitivity = EquatableFormatArgument::SS_Public;
9198 else if (FS.isSensitive())
9199 Sensitivity = EquatableFormatArgument::SS_Sensitive;
9200 else
9201 Sensitivity = EquatableFormatArgument::SS_None;
9202
9203 Specs.emplace_back(
9204 Args: getSpecifierRange(startSpecifier, specifierLen),
9205 Args: getLocationOfByte(x: CS.getStart()), Args: FS.getLengthModifier(),
9206 Args: CS.getCharacters(), Args: FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext()),
9207 Args: EquatableFormatArgument::FAR_Data, Args&: Sensitivity, Args&: SpecIndex, Args: 0);
9208
9209 // auxiliary argument?
9210 if (CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDbArg ||
9211 CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDDArg) {
9212 Specs.emplace_back(Args: getSpecifierRange(startSpecifier, specifierLen),
9213 Args: getLocationOfByte(x: CS.getStart()),
9214 Args: analyze_format_string::LengthModifier(),
9215 Args: CS.getCharacters(),
9216 Args: analyze_format_string::ArgType::CStrTy,
9217 Args: EquatableFormatArgument::FAR_Auxiliary, Args&: Sensitivity,
9218 Args: SpecIndex + 1, Args&: SpecIndex);
9219 }
9220 return true;
9221}
9222
9223// Determines if the specified is a C++ class or struct containing
9224// a member with the specified name and kind (e.g. a CXXMethodDecl named
9225// "c_str()").
9226template<typename MemberKind>
9227static llvm::SmallPtrSet<MemberKind*, 1>
9228CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
9229 auto *RD = Ty->getAsCXXRecordDecl();
9230 llvm::SmallPtrSet<MemberKind*, 1> Results;
9231
9232 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
9233 return Results;
9234
9235 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
9236 Sema::LookupMemberName);
9237 R.suppressDiagnostics();
9238
9239 // We just need to include all members of the right kind turned up by the
9240 // filter, at this point.
9241 if (S.LookupQualifiedName(R, LookupCtx: RD))
9242 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9243 NamedDecl *decl = (*I)->getUnderlyingDecl();
9244 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9245 Results.insert(FK);
9246 }
9247 return Results;
9248}
9249
9250/// Check if we could call '.c_str()' on an object.
9251///
9252/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9253/// allow the call, or if it would be ambiguous).
9254bool Sema::hasCStrMethod(const Expr *E) {
9255 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9256
9257 MethodSet Results =
9258 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S&: *this, Ty: E->getType());
9259 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9260 MI != ME; ++MI)
9261 if ((*MI)->getMinRequiredArguments() == 0)
9262 return true;
9263 return false;
9264}
9265
9266// Check if a (w)string was passed when a (w)char* was needed, and offer a
9267// better diagnostic if so. AT is assumed to be valid.
9268// Returns true when a c_str() conversion method is found.
9269bool CheckPrintfHandler::checkForCStrMembers(
9270 const analyze_printf::ArgType &AT, const Expr *E) {
9271 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9272
9273 MethodSet Results =
9274 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S, Ty: E->getType());
9275
9276 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9277 MI != ME; ++MI) {
9278 const CXXMethodDecl *Method = *MI;
9279 if (Method->getMinRequiredArguments() == 0 &&
9280 AT.matchesType(C&: S.Context, argTy: Method->getReturnType())) {
9281 // FIXME: Suggest parens if the expression needs them.
9282 SourceLocation EndLoc = S.getLocForEndOfToken(Loc: E->getEndLoc());
9283 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_printf_c_str)
9284 << "c_str()" << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ".c_str()");
9285 return true;
9286 }
9287 }
9288
9289 return false;
9290}
9291
9292bool CheckPrintfHandler::HandlePrintfSpecifier(
9293 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9294 unsigned specifierLen, const TargetInfo &Target) {
9295 using namespace analyze_format_string;
9296 using namespace analyze_printf;
9297
9298 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9299
9300 if (FS.consumesDataArgument()) {
9301 if (atFirstArg) {
9302 atFirstArg = false;
9303 usesPositionalArgs = FS.usesPositionalArg();
9304 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9305 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
9306 startSpec: startSpecifier, specifierLen);
9307 return false;
9308 }
9309 }
9310
9311 // First check if the field width, precision, and conversion specifier
9312 // have matching data arguments.
9313 if (!HandleAmount(Amt: FS.getFieldWidth(), /* field width */ k: 0, startSpecifier,
9314 specifierLen)) {
9315 return false;
9316 }
9317
9318 if (!HandleAmount(Amt: FS.getPrecision(), /* precision */ k: 1, startSpecifier,
9319 specifierLen)) {
9320 return false;
9321 }
9322
9323 if (!CS.consumesDataArgument()) {
9324 // FIXME: Technically specifying a precision or field width here
9325 // makes no sense. Worth issuing a warning at some point.
9326 return true;
9327 }
9328
9329 // Consume the argument.
9330 unsigned argIndex = FS.getArgIndex();
9331 if (argIndex < NumDataArgs) {
9332 // The check to see if the argIndex is valid will come later.
9333 // We set the bit here because we may exit early from this
9334 // function if we encounter some other error.
9335 CoveredArgs.set(argIndex);
9336 }
9337
9338 // FreeBSD kernel extensions.
9339 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9340 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9341 // We need at least two arguments.
9342 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex: argIndex + 1))
9343 return false;
9344
9345 if (HasFormatArguments()) {
9346 // Claim the second argument.
9347 CoveredArgs.set(argIndex + 1);
9348
9349 // Type check the first argument (int for %b, pointer for %D)
9350 const Expr *Ex = getDataArg(i: argIndex);
9351 const analyze_printf::ArgType &AT =
9352 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
9353 ? ArgType(S.Context.IntTy)
9354 : ArgType::CPointerTy;
9355 if (AT.isValid() && !AT.matchesType(C&: S.Context, argTy: Ex->getType()))
9356 EmitFormatDiagnostic(
9357 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9358 << AT.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
9359 << false << Ex->getSourceRange(),
9360 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
9361 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9362
9363 // Type check the second argument (char * for both %b and %D)
9364 Ex = getDataArg(i: argIndex + 1);
9365 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9366 if (AT2.isValid() && !AT2.matchesType(C&: S.Context, argTy: Ex->getType()))
9367 EmitFormatDiagnostic(
9368 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9369 << AT2.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
9370 << false << Ex->getSourceRange(),
9371 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
9372 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9373 }
9374 return true;
9375 }
9376
9377 // Check for using an Objective-C specific conversion specifier
9378 // in a non-ObjC literal.
9379 if (!allowsObjCArg() && CS.isObjCArg()) {
9380 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9381 specifierLen);
9382 }
9383
9384 // %P can only be used with os_log.
9385 if (FSType != FormatStringType::OSLog &&
9386 CS.getKind() == ConversionSpecifier::PArg) {
9387 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9388 specifierLen);
9389 }
9390
9391 // %n is not allowed with os_log.
9392 if (FSType == FormatStringType::OSLog &&
9393 CS.getKind() == ConversionSpecifier::nArg) {
9394 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_os_log_format_narg),
9395 Loc: getLocationOfByte(x: CS.getStart()),
9396 /*IsStringLocation*/ false,
9397 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9398
9399 return true;
9400 }
9401
9402 // Only scalars are allowed for os_trace.
9403 if (FSType == FormatStringType::OSTrace &&
9404 (CS.getKind() == ConversionSpecifier::PArg ||
9405 CS.getKind() == ConversionSpecifier::sArg ||
9406 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9407 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9408 specifierLen);
9409 }
9410
9411 // Check for use of public/private annotation outside of os_log().
9412 if (FSType != FormatStringType::OSLog) {
9413 if (FS.isPublic().isSet()) {
9414 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
9415 << "public",
9416 Loc: getLocationOfByte(x: FS.isPublic().getPosition()),
9417 /*IsStringLocation*/ false,
9418 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9419 }
9420 if (FS.isPrivate().isSet()) {
9421 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
9422 << "private",
9423 Loc: getLocationOfByte(x: FS.isPrivate().getPosition()),
9424 /*IsStringLocation*/ false,
9425 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9426 }
9427 }
9428
9429 const llvm::Triple &Triple = Target.getTriple();
9430 if (CS.getKind() == ConversionSpecifier::nArg &&
9431 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9432 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_narg_not_supported),
9433 Loc: getLocationOfByte(x: CS.getStart()),
9434 /*IsStringLocation*/ false,
9435 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9436 }
9437
9438 // Check for invalid use of field width
9439 if (!FS.hasValidFieldWidth()) {
9440 HandleInvalidAmount(FS, Amt: FS.getFieldWidth(), /* field width */ type: 0,
9441 startSpecifier, specifierLen);
9442 }
9443
9444 // Check for invalid use of precision
9445 if (!FS.hasValidPrecision()) {
9446 HandleInvalidAmount(FS, Amt: FS.getPrecision(), /* precision */ type: 1,
9447 startSpecifier, specifierLen);
9448 }
9449
9450 // Precision is mandatory for %P specifier.
9451 if (CS.getKind() == ConversionSpecifier::PArg &&
9452 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9453 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_no_precision),
9454 Loc: getLocationOfByte(x: startSpecifier),
9455 /*IsStringLocation*/ false,
9456 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9457 }
9458
9459 // Check each flag does not conflict with any other component.
9460 if (!FS.hasValidThousandsGroupingPrefix())
9461 HandleFlag(FS, flag: FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9462 if (!FS.hasValidLeadingZeros())
9463 HandleFlag(FS, flag: FS.hasLeadingZeros(), startSpecifier, specifierLen);
9464 if (!FS.hasValidPlusPrefix())
9465 HandleFlag(FS, flag: FS.hasPlusPrefix(), startSpecifier, specifierLen);
9466 if (!FS.hasValidSpacePrefix())
9467 HandleFlag(FS, flag: FS.hasSpacePrefix(), startSpecifier, specifierLen);
9468 if (!FS.hasValidAlternativeForm())
9469 HandleFlag(FS, flag: FS.hasAlternativeForm(), startSpecifier, specifierLen);
9470 if (!FS.hasValidLeftJustified())
9471 HandleFlag(FS, flag: FS.isLeftJustified(), startSpecifier, specifierLen);
9472
9473 // Check that flags are not ignored by another flag
9474 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9475 HandleIgnoredFlag(FS, ignoredFlag: FS.hasSpacePrefix(), flag: FS.hasPlusPrefix(),
9476 startSpecifier, specifierLen);
9477 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9478 HandleIgnoredFlag(FS, ignoredFlag: FS.hasLeadingZeros(), flag: FS.isLeftJustified(),
9479 startSpecifier, specifierLen);
9480
9481 // Check the length modifier is valid with the given conversion specifier.
9482 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
9483 LO: S.getLangOpts()))
9484 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9485 DiagID: diag::warn_format_nonsensical_length);
9486 else if (!FS.hasStandardLengthModifier())
9487 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9488 else if (!FS.hasStandardLengthConversionCombination())
9489 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9490 DiagID: diag::warn_format_non_standard_conversion_spec);
9491
9492 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
9493 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9494
9495 // The remaining checks depend on the data arguments.
9496 if (!HasFormatArguments())
9497 return true;
9498
9499 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9500 return false;
9501
9502 const Expr *Arg = getDataArg(i: argIndex);
9503 if (!Arg)
9504 return true;
9505
9506 return checkFormatExpr(FS, StartSpecifier: startSpecifier, SpecifierLen: specifierLen, E: Arg);
9507}
9508
9509static bool requiresParensToAddCast(const Expr *E) {
9510 // FIXME: We should have a general way to reason about operator
9511 // precedence and whether parens are actually needed here.
9512 // Take care of a few common cases where they aren't.
9513 const Expr *Inside = E->IgnoreImpCasts();
9514 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: Inside))
9515 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9516
9517 switch (Inside->getStmtClass()) {
9518 case Stmt::ArraySubscriptExprClass:
9519 case Stmt::CallExprClass:
9520 case Stmt::CharacterLiteralClass:
9521 case Stmt::CXXBoolLiteralExprClass:
9522 case Stmt::DeclRefExprClass:
9523 case Stmt::FloatingLiteralClass:
9524 case Stmt::IntegerLiteralClass:
9525 case Stmt::MemberExprClass:
9526 case Stmt::ObjCArrayLiteralClass:
9527 case Stmt::ObjCBoolLiteralExprClass:
9528 case Stmt::ObjCBoxedExprClass:
9529 case Stmt::ObjCDictionaryLiteralClass:
9530 case Stmt::ObjCEncodeExprClass:
9531 case Stmt::ObjCIvarRefExprClass:
9532 case Stmt::ObjCMessageExprClass:
9533 case Stmt::ObjCPropertyRefExprClass:
9534 case Stmt::ObjCStringLiteralClass:
9535 case Stmt::ObjCSubscriptRefExprClass:
9536 case Stmt::ParenExprClass:
9537 case Stmt::StringLiteralClass:
9538 case Stmt::UnaryOperatorClass:
9539 return false;
9540 default:
9541 return true;
9542 }
9543}
9544
9545static std::pair<QualType, StringRef>
9546shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9547 const Expr *E) {
9548 // Use a 'while' to peel off layers of typedefs.
9549 QualType TyTy = IntendedTy;
9550 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9551 StringRef Name = UserTy->getDecl()->getName();
9552 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9553 .Case(S: "CFIndex", Value: Context.getNSIntegerType())
9554 .Case(S: "NSInteger", Value: Context.getNSIntegerType())
9555 .Case(S: "NSUInteger", Value: Context.getNSUIntegerType())
9556 .Case(S: "SInt32", Value: Context.IntTy)
9557 .Case(S: "UInt32", Value: Context.UnsignedIntTy)
9558 .Default(Value: QualType());
9559
9560 if (!CastTy.isNull())
9561 return std::make_pair(x&: CastTy, y&: Name);
9562
9563 TyTy = UserTy->desugar();
9564 }
9565
9566 // Strip parens if necessary.
9567 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Val: E))
9568 return shouldNotPrintDirectly(Context, IntendedTy: PE->getSubExpr()->getType(),
9569 E: PE->getSubExpr());
9570
9571 // If this is a conditional expression, then its result type is constructed
9572 // via usual arithmetic conversions and thus there might be no necessary
9573 // typedef sugar there. Recurse to operands to check for NSInteger &
9574 // Co. usage condition.
9575 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
9576 QualType TrueTy, FalseTy;
9577 StringRef TrueName, FalseName;
9578
9579 std::tie(args&: TrueTy, args&: TrueName) = shouldNotPrintDirectly(
9580 Context, IntendedTy: CO->getTrueExpr()->getType(), E: CO->getTrueExpr());
9581 std::tie(args&: FalseTy, args&: FalseName) = shouldNotPrintDirectly(
9582 Context, IntendedTy: CO->getFalseExpr()->getType(), E: CO->getFalseExpr());
9583
9584 if (TrueTy == FalseTy)
9585 return std::make_pair(x&: TrueTy, y&: TrueName);
9586 else if (TrueTy.isNull())
9587 return std::make_pair(x&: FalseTy, y&: FalseName);
9588 else if (FalseTy.isNull())
9589 return std::make_pair(x&: TrueTy, y&: TrueName);
9590 }
9591
9592 return std::make_pair(x: QualType(), y: StringRef());
9593}
9594
9595/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9596/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9597/// type do not count.
9598static bool isArithmeticArgumentPromotion(Sema &S,
9599 const ImplicitCastExpr *ICE) {
9600 QualType From = ICE->getSubExpr()->getType();
9601 QualType To = ICE->getType();
9602 // It's an integer promotion if the destination type is the promoted
9603 // source type.
9604 if (ICE->getCastKind() == CK_IntegralCast &&
9605 S.Context.isPromotableIntegerType(T: From) &&
9606 S.Context.getPromotedIntegerType(PromotableType: From) == To)
9607 return true;
9608 // Look through vector types, since we do default argument promotion for
9609 // those in OpenCL.
9610 if (const auto *VecTy = From->getAs<ExtVectorType>())
9611 From = VecTy->getElementType();
9612 if (const auto *VecTy = To->getAs<ExtVectorType>())
9613 To = VecTy->getElementType();
9614 // It's a floating promotion if the source type is a lower rank.
9615 return ICE->getCastKind() == CK_FloatingCast &&
9616 S.Context.getFloatingTypeOrder(LHS: From, RHS: To) < 0;
9617}
9618
9619static analyze_format_string::ArgType::MatchKind
9620handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match,
9621 DiagnosticsEngine &Diags, SourceLocation Loc) {
9622 if (Match == analyze_format_string::ArgType::NoMatchSignedness) {
9623 if (Diags.isIgnored(
9624 DiagID: diag::warn_format_conversion_argument_type_mismatch_signedness,
9625 Loc) ||
9626 Diags.isIgnored(
9627 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9628 DiagID: diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9629 return analyze_format_string::ArgType::Match;
9630 }
9631 }
9632 return Match;
9633}
9634
9635bool CheckPrintfHandler::checkFormatExpr(
9636 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9637 unsigned SpecifierLen, const Expr *E) {
9638 using namespace analyze_format_string;
9639 using namespace analyze_printf;
9640
9641 // Now type check the data expression that matches the
9642 // format specifier.
9643 const analyze_printf::ArgType &AT = FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9644 if (!AT.isValid())
9645 return true;
9646
9647 QualType ExprTy = E->getType();
9648 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(Val&: ExprTy)) {
9649 ExprTy = TET->getUnderlyingExpr()->getType();
9650 }
9651
9652 if (const OverflowBehaviorType *OBT =
9653 dyn_cast<OverflowBehaviorType>(Val: ExprTy.getCanonicalType()))
9654 ExprTy = OBT->getUnderlyingType();
9655
9656 // When using the format attribute in C++, you can receive a function or an
9657 // array that will necessarily decay to a pointer when passed to the final
9658 // format consumer. Apply decay before type comparison.
9659 if (ExprTy->canDecayToPointerType())
9660 ExprTy = S.Context.getDecayedType(T: ExprTy);
9661
9662 // Diagnose attempts to print a boolean value as a character. Unlike other
9663 // -Wformat diagnostics, this is fine from a type perspective, but it still
9664 // doesn't make sense.
9665 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9666 E->isKnownToHaveBooleanValue()) {
9667 const CharSourceRange &CSR =
9668 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9669 SmallString<4> FSString;
9670 llvm::raw_svector_ostream os(FSString);
9671 FS.toString(os);
9672 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_bool_as_character)
9673 << FSString,
9674 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9675 return true;
9676 }
9677
9678 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9679 // dumping raw class data (like is-a pointer), not actual data.
9680 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
9681 ExprTy->isObjCObjectPointerType()) {
9682 const CharSourceRange &CSR =
9683 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9684 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_with_objc_pointer),
9685 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9686 return true;
9687 }
9688
9689 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9690 return true;
9691
9692 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9693 ArgType::MatchKind Match = AT.matchesType(C&: S.Context, argTy: ExprTy);
9694 ArgType::MatchKind OrigMatch = Match;
9695
9696 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9697 if (Match == ArgType::Match)
9698 return true;
9699
9700 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9701 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9702
9703 // Look through argument promotions for our error message's reported type.
9704 // This includes the integral and floating promotions, but excludes array
9705 // and function pointer decay (seeing that an argument intended to be a
9706 // string has type 'char [6]' is probably more confusing than 'char *') and
9707 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9708 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
9709 if (isArithmeticArgumentPromotion(S, ICE)) {
9710 E = ICE->getSubExpr();
9711 ExprTy = E->getType();
9712
9713 // Check if we didn't match because of an implicit cast from a 'char'
9714 // or 'short' to an 'int'. This is done because printf is a varargs
9715 // function.
9716 if (ICE->getType() == S.Context.IntTy ||
9717 ICE->getType() == S.Context.UnsignedIntTy) {
9718 // All further checking is done on the subexpression
9719 ImplicitMatch = AT.matchesType(C&: S.Context, argTy: ExprTy);
9720 if (OrigMatch == ArgType::NoMatchSignedness &&
9721 ImplicitMatch != ArgType::NoMatchSignedness)
9722 // If the original match was a signedness match this match on the
9723 // implicit cast type also need to be signedness match otherwise we
9724 // might introduce new unexpected warnings from -Wformat-signedness.
9725 return true;
9726 ImplicitMatch = handleFormatSignedness(
9727 Match: ImplicitMatch, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9728 if (ImplicitMatch == ArgType::Match)
9729 return true;
9730 }
9731 }
9732 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(Val: E)) {
9733 // Special case for 'a', which has type 'int' in C.
9734 // Note, however, that we do /not/ want to treat multibyte constants like
9735 // 'MooV' as characters! This form is deprecated but still exists. In
9736 // addition, don't treat expressions as of type 'char' if one byte length
9737 // modifier is provided.
9738 if (ExprTy == S.Context.IntTy &&
9739 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9740 if (llvm::isUIntN(N: S.Context.getCharWidth(), x: CL->getValue())) {
9741 ExprTy = S.Context.CharTy;
9742 // To improve check results, we consider a character literal in C
9743 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9744 // more likely a type confusion situation, so we will suggest to
9745 // use '%hhd' instead by discarding the MatchPromotion.
9746 if (Match == ArgType::MatchPromotion)
9747 Match = ArgType::NoMatch;
9748 }
9749 }
9750 if (Match == ArgType::MatchPromotion) {
9751 // WG14 N2562 only clarified promotions in *printf
9752 // For NSLog in ObjC, just preserve -Wformat behavior
9753 if (!S.getLangOpts().ObjC &&
9754 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9755 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9756 return true;
9757 Match = ArgType::NoMatch;
9758 }
9759 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9760 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9761 Match = ImplicitMatch;
9762 assert(Match != ArgType::MatchPromotion);
9763
9764 // Look through unscoped enums to their underlying type.
9765 bool IsEnum = false;
9766 bool IsScopedEnum = false;
9767 QualType IntendedTy = ExprTy;
9768 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9769 IntendedTy = ED->getIntegerType();
9770 if (!ED->isScoped()) {
9771 ExprTy = IntendedTy;
9772 // This controls whether we're talking about the underlying type or not,
9773 // which we only want to do when it's an unscoped enum.
9774 IsEnum = true;
9775 } else {
9776 IsScopedEnum = true;
9777 }
9778 }
9779
9780 // %C in an Objective-C context prints a unichar, not a wchar_t.
9781 // If the argument is an integer of some kind, believe the %C and suggest
9782 // a cast instead of changing the conversion specifier.
9783 if (isObjCContext() &&
9784 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9785 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9786 !ExprTy->isCharType()) {
9787 // 'unichar' is defined as a typedef of unsigned short, but we should
9788 // prefer using the typedef if it is visible.
9789 IntendedTy = S.Context.UnsignedShortTy;
9790
9791 // While we are here, check if the value is an IntegerLiteral that happens
9792 // to be within the valid range.
9793 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: E)) {
9794 const llvm::APInt &V = IL->getValue();
9795 if (V.getActiveBits() <= S.Context.getTypeSize(T: IntendedTy))
9796 return true;
9797 }
9798
9799 LookupResult Result(S, &S.Context.Idents.get(Name: "unichar"), E->getBeginLoc(),
9800 Sema::LookupOrdinaryName);
9801 if (S.LookupName(R&: Result, S: S.getCurScope())) {
9802 NamedDecl *ND = Result.getFoundDecl();
9803 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: ND))
9804 if (TD->getUnderlyingType() == IntendedTy)
9805 IntendedTy =
9806 S.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
9807 /*Qualifier=*/std::nullopt, Decl: TD);
9808 }
9809 }
9810 }
9811
9812 // Special-case some of Darwin's platform-independence types by suggesting
9813 // casts to primitive types that are known to be large enough.
9814 bool ShouldNotPrintDirectly = false;
9815 StringRef CastTyName;
9816 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9817 QualType CastTy;
9818 std::tie(args&: CastTy, args&: CastTyName) =
9819 shouldNotPrintDirectly(Context: S.Context, IntendedTy, E);
9820 if (!CastTy.isNull()) {
9821 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9822 // (long in ASTContext). Only complain to pedants or when they're the
9823 // underlying type of a scoped enum (which always needs a cast).
9824 if (!IsScopedEnum &&
9825 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9826 (AT.isSizeT() || AT.isPtrdiffT()) &&
9827 AT.matchesType(C&: S.Context, argTy: CastTy))
9828 Match = ArgType::NoMatchPedantic;
9829 IntendedTy = CastTy;
9830 ShouldNotPrintDirectly = true;
9831 }
9832 }
9833
9834 // We may be able to offer a FixItHint if it is a supported type.
9835 PrintfSpecifier fixedFS = FS;
9836 bool Success =
9837 fixedFS.fixType(QT: IntendedTy, LangOpt: S.getLangOpts(), Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9838
9839 if (Success) {
9840 // Get the fix string from the fixed format specifier
9841 SmallString<16> buf;
9842 llvm::raw_svector_ostream os(buf);
9843 fixedFS.toString(os);
9844
9845 CharSourceRange SpecRange = getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9846
9847 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9848 unsigned Diag;
9849 switch (Match) {
9850 case ArgType::Match:
9851 case ArgType::MatchPromotion:
9852 case ArgType::NoMatchPromotionTypeConfusion:
9853 llvm_unreachable("expected non-matching");
9854 case ArgType::NoMatchSignedness:
9855 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9856 break;
9857 case ArgType::NoMatchPedantic:
9858 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9859 break;
9860 case ArgType::NoMatchTypeConfusion:
9861 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9862 break;
9863 case ArgType::NoMatch:
9864 Diag = diag::warn_format_conversion_argument_type_mismatch;
9865 break;
9866 }
9867
9868 // In this case, the specifier is wrong and should be changed to match
9869 // the argument.
9870 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
9871 << AT.getRepresentativeTypeName(C&: S.Context)
9872 << IntendedTy << IsEnum << E->getSourceRange(),
9873 Loc: E->getBeginLoc(),
9874 /*IsStringLocation*/ false, StringRange: SpecRange,
9875 FixIt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9876 } else {
9877 // The canonical type for formatting this value is different from the
9878 // actual type of the expression. (This occurs, for example, with Darwin's
9879 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9880 // should be printed as 'long' for 64-bit compatibility.)
9881 // Rather than emitting a normal format/argument mismatch, we want to
9882 // add a cast to the recommended type (and correct the format string
9883 // if necessary). We should also do so for scoped enumerations.
9884 SmallString<16> CastBuf;
9885 llvm::raw_svector_ostream CastFix(CastBuf);
9886 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9887 IntendedTy.print(OS&: CastFix, Policy: S.Context.getPrintingPolicy());
9888 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9889
9890 SmallVector<FixItHint, 4> Hints;
9891 ArgType::MatchKind IntendedMatch = AT.matchesType(C&: S.Context, argTy: IntendedTy);
9892 IntendedMatch = handleFormatSignedness(Match: IntendedMatch, Diags&: S.getDiagnostics(),
9893 Loc: E->getExprLoc());
9894 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9895 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9896
9897 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(Val: E)) {
9898 // If there's already a cast present, just replace it.
9899 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9900 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: CastRange, Code: CastFix.str()));
9901
9902 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9903 // If the expression has high enough precedence,
9904 // just write the C-style cast.
9905 Hints.push_back(
9906 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9907 } else {
9908 // Otherwise, add parens around the expression as well as the cast.
9909 CastFix << "(";
9910 Hints.push_back(
9911 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9912
9913 // We don't use getLocForEndOfToken because it returns invalid source
9914 // locations for macro expansions (by design).
9915 SourceLocation EndLoc = S.SourceMgr.getSpellingLoc(Loc: E->getEndLoc());
9916 SourceLocation After = EndLoc.getLocWithOffset(
9917 Offset: Lexer::MeasureTokenLength(Loc: EndLoc, SM: S.SourceMgr, LangOpts: S.LangOpts));
9918 Hints.push_back(Elt: FixItHint::CreateInsertion(InsertionLoc: After, Code: ")"));
9919 }
9920
9921 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9922 // The expression has a type that should not be printed directly.
9923 // We extract the name from the typedef because we don't want to show
9924 // the underlying type in the diagnostic.
9925 StringRef Name;
9926 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9927 Name = TypedefTy->getDecl()->getName();
9928 else
9929 Name = CastTyName;
9930 unsigned Diag = Match == ArgType::NoMatchPedantic
9931 ? diag::warn_format_argument_needs_cast_pedantic
9932 : diag::warn_format_argument_needs_cast;
9933 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag) << Name << IntendedTy << IsEnum
9934 << E->getSourceRange(),
9935 Loc: E->getBeginLoc(), /*IsStringLocation=*/false,
9936 StringRange: SpecRange, FixIt: Hints);
9937 } else {
9938 // In this case, the expression could be printed using a different
9939 // specifier, but we've decided that the specifier is probably correct
9940 // and we should cast instead. Just use the normal warning message.
9941
9942 unsigned Diag =
9943 IsScopedEnum
9944 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9945 : diag::warn_format_conversion_argument_type_mismatch;
9946
9947 EmitFormatDiagnostic(
9948 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9949 << IsEnum << E->getSourceRange(),
9950 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: SpecRange, FixIt: Hints);
9951 }
9952 }
9953 } else {
9954 const CharSourceRange &CSR =
9955 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9956 // Since the warning for passing non-POD types to variadic functions
9957 // was deferred until now, we emit a warning for non-POD
9958 // arguments here.
9959 bool EmitTypeMismatch = false;
9960 // Record and complex type arguments cannot be code generated for os_log
9961 // and would crash CodeGen, so they are rejected with a hard error emitted
9962 // after the switch below.
9963 bool EmitOSLogError = false;
9964 switch (S.isValidVarArgType(Ty: ExprTy)) {
9965 case VarArgKind::Valid:
9966 case VarArgKind::ValidInCXX11: {
9967 unsigned Diag;
9968 switch (Match) {
9969 case ArgType::Match:
9970 case ArgType::MatchPromotion:
9971 case ArgType::NoMatchPromotionTypeConfusion:
9972 llvm_unreachable("expected non-matching");
9973 case ArgType::NoMatchSignedness:
9974 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9975 break;
9976 case ArgType::NoMatchPedantic:
9977 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9978 break;
9979 case ArgType::NoMatchTypeConfusion:
9980 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9981 break;
9982 case ArgType::NoMatch:
9983 EmitOSLogError = isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy);
9984 Diag = diag::warn_format_conversion_argument_type_mismatch;
9985 break;
9986 }
9987
9988 if (!EmitOSLogError)
9989 EmitFormatDiagnostic(
9990 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9991 << IsEnum << CSR << E->getSourceRange(),
9992 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9993 break;
9994 }
9995 case VarArgKind::Undefined:
9996 case VarArgKind::MSVCUndefined:
9997 if (CallType == VariadicCallType::DoesNotApply) {
9998 EmitTypeMismatch = true;
9999 } else if (isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy)) {
10000 // Emit a hard error rather than the -Wnon-pod-varargs warning, which
10001 // does not stop compilation.
10002 EmitOSLogError = true;
10003 } else {
10004 EmitFormatDiagnostic(
10005 PDiag: S.PDiag(DiagID: diag::warn_non_pod_vararg_with_format_string)
10006 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
10007 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
10008 << E->getSourceRange(),
10009 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
10010 checkForCStrMembers(AT, E);
10011 }
10012 break;
10013
10014 case VarArgKind::Invalid:
10015 if (CallType == VariadicCallType::DoesNotApply)
10016 EmitTypeMismatch = true;
10017 else if (ExprTy->isObjCObjectType())
10018 EmitFormatDiagnostic(
10019 PDiag: S.PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg_format)
10020 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
10021 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
10022 << E->getSourceRange(),
10023 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
10024 else
10025 // FIXME: If this is an initializer list, suggest removing the braces
10026 // or inserting a cast to the target type.
10027 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg_format)
10028 << isa<InitListExpr>(Val: E) << ExprTy << CallType
10029 << AT.getRepresentativeTypeName(C&: S.Context) << E->getSourceRange();
10030 break;
10031 }
10032
10033 if (EmitOSLogError)
10034 EmitFormatDiagnostic(
10035 PDiag: S.PDiag(DiagID: diag::err_format_conversion_argument_type_mismatch)
10036 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << IsEnum
10037 << CSR << E->getSourceRange(),
10038 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
10039
10040 if (EmitTypeMismatch) {
10041 // The function is not variadic, so we do not generate warnings about
10042 // being allowed to pass that object as a variadic argument. Instead,
10043 // since there are inherently no printf specifiers for types which cannot
10044 // be passed as variadic arguments, emit a plain old specifier mismatch
10045 // argument.
10046 EmitFormatDiagnostic(
10047 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
10048 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << false
10049 << E->getSourceRange(),
10050 Loc: E->getBeginLoc(), IsStringLocation: false, StringRange: CSR);
10051 }
10052
10053 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
10054 "format string specifier index out of range");
10055 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
10056 }
10057
10058 return true;
10059}
10060
10061//===--- CHECK: Scanf format string checking ------------------------------===//
10062
10063namespace {
10064
10065class CheckScanfHandler : public CheckFormatHandler {
10066public:
10067 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
10068 const Expr *origFormatExpr, FormatStringType type,
10069 unsigned firstDataArg, unsigned numDataArgs,
10070 const char *beg, Sema::FormatArgumentPassingKind APK,
10071 ArrayRef<const Expr *> Args, unsigned formatIdx,
10072 bool inFunctionCall, VariadicCallType CallType,
10073 llvm::SmallBitVector &CheckedVarArgs,
10074 UncoveredArgHandler &UncoveredArg)
10075 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
10076 numDataArgs, beg, APK, Args, formatIdx,
10077 inFunctionCall, CallType, CheckedVarArgs,
10078 UncoveredArg) {}
10079
10080 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10081 const char *startSpecifier,
10082 unsigned specifierLen) override;
10083
10084 bool
10085 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
10086 const char *startSpecifier,
10087 unsigned specifierLen) override;
10088
10089 void HandleIncompleteScanList(const char *start, const char *end) override;
10090};
10091
10092} // namespace
10093
10094void CheckScanfHandler::HandleIncompleteScanList(const char *start,
10095 const char *end) {
10096 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_scanlist_incomplete),
10097 Loc: getLocationOfByte(x: end), /*IsStringLocation*/ true,
10098 StringRange: getSpecifierRange(startSpecifier: start, specifierLen: end - start));
10099}
10100
10101bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
10102 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
10103 unsigned specifierLen) {
10104 const analyze_scanf::ScanfConversionSpecifier &CS =
10105 FS.getConversionSpecifier();
10106
10107 return HandleInvalidConversionSpecifier(
10108 argIndex: FS.getArgIndex(), Loc: getLocationOfByte(x: CS.getStart()), startSpec: startSpecifier,
10109 specifierLen, csStart: CS.getStart(), csLen: CS.getLength());
10110}
10111
10112bool CheckScanfHandler::HandleScanfSpecifier(
10113 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
10114 unsigned specifierLen) {
10115 using namespace analyze_scanf;
10116 using namespace analyze_format_string;
10117
10118 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
10119
10120 // Handle case where '%' and '*' don't consume an argument. These shouldn't
10121 // be used to decide if we are using positional arguments consistently.
10122 if (FS.consumesDataArgument()) {
10123 if (atFirstArg) {
10124 atFirstArg = false;
10125 usesPositionalArgs = FS.usesPositionalArg();
10126 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
10127 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
10128 startSpec: startSpecifier, specifierLen);
10129 return false;
10130 }
10131 }
10132
10133 // Check if the field with is non-zero.
10134 const OptionalAmount &Amt = FS.getFieldWidth();
10135 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
10136 if (Amt.getConstantAmount() == 0) {
10137 const CharSourceRange &R =
10138 getSpecifierRange(startSpecifier: Amt.getStart(), specifierLen: Amt.getConstantLength());
10139 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_nonzero_width),
10140 Loc: getLocationOfByte(x: Amt.getStart()),
10141 /*IsStringLocation*/ true, StringRange: R,
10142 FixIt: FixItHint::CreateRemoval(RemoveRange: R));
10143 }
10144 }
10145
10146 if (!FS.consumesDataArgument()) {
10147 // FIXME: Technically specifying a precision or field width here
10148 // makes no sense. Worth issuing a warning at some point.
10149 return true;
10150 }
10151
10152 // Consume the argument.
10153 unsigned argIndex = FS.getArgIndex();
10154 if (argIndex < NumDataArgs) {
10155 // The check to see if the argIndex is valid will come later.
10156 // We set the bit here because we may exit early from this
10157 // function if we encounter some other error.
10158 CoveredArgs.set(argIndex);
10159 }
10160
10161 // Check the length modifier is valid with the given conversion specifier.
10162 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
10163 LO: S.getLangOpts()))
10164 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10165 DiagID: diag::warn_format_nonsensical_length);
10166 else if (!FS.hasStandardLengthModifier())
10167 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10168 else if (!FS.hasStandardLengthConversionCombination())
10169 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10170 DiagID: diag::warn_format_non_standard_conversion_spec);
10171
10172 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
10173 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10174
10175 // The remaining checks depend on the data arguments.
10176 if (!HasFormatArguments())
10177 return true;
10178
10179 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10180 return false;
10181
10182 // Check that the argument type matches the format specifier.
10183 const Expr *Ex = getDataArg(i: argIndex);
10184 if (!Ex)
10185 return true;
10186
10187 const analyze_format_string::ArgType &AT = FS.getArgType(Ctx&: S.Context);
10188
10189 if (!AT.isValid()) {
10190 return true;
10191 }
10192
10193 if (CheckUnsupportedType(AT, E: Ex, StartSpecifier: startSpecifier, SpecifierLen: specifierLen))
10194 return true;
10195
10196 analyze_format_string::ArgType::MatchKind Match =
10197 AT.matchesType(C&: S.Context, argTy: Ex->getType());
10198 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: Ex->getExprLoc());
10199 if (Match == analyze_format_string::ArgType::Match)
10200 return true;
10201 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
10202 bool Signedness = Match == analyze_format_string::ArgType::NoMatchSignedness;
10203
10204 ScanfSpecifier fixedFS = FS;
10205 bool Success = fixedFS.fixType(QT: Ex->getType(), RawQT: Ex->IgnoreImpCasts()->getType(),
10206 LangOpt: S.getLangOpts(), Ctx&: S.Context);
10207
10208 unsigned Diag =
10209 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10210 : Signedness
10211 ? diag::warn_format_conversion_argument_type_mismatch_signedness
10212 : diag::warn_format_conversion_argument_type_mismatch;
10213
10214 if (Success) {
10215 // Get the fix string from the fixed format specifier.
10216 SmallString<128> buf;
10217 llvm::raw_svector_ostream os(buf);
10218 fixedFS.toString(os);
10219
10220 EmitFormatDiagnostic(
10221 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context)
10222 << Ex->getType() << false << Ex->getSourceRange(),
10223 Loc: Ex->getBeginLoc(),
10224 /*IsStringLocation*/ false,
10225 StringRange: getSpecifierRange(startSpecifier, specifierLen),
10226 FixIt: FixItHint::CreateReplacement(
10227 RemoveRange: getSpecifierRange(startSpecifier, specifierLen), Code: os.str()));
10228 } else {
10229 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
10230 << AT.getRepresentativeTypeName(C&: S.Context)
10231 << Ex->getType() << false << Ex->getSourceRange(),
10232 Loc: Ex->getBeginLoc(),
10233 /*IsStringLocation*/ false,
10234 StringRange: getSpecifierRange(startSpecifier, specifierLen));
10235 }
10236
10237 return true;
10238}
10239
10240static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
10241 ArrayRef<EquatableFormatArgument> RefArgs,
10242 const StringLiteral *Fmt,
10243 ArrayRef<EquatableFormatArgument> FmtArgs,
10244 const Expr *FmtExpr, bool InFunctionCall) {
10245 bool HadError = false;
10246 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
10247 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
10248 while (FmtIter < FmtEnd && RefIter < RefEnd) {
10249 // In positional-style format strings, the same specifier can appear
10250 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
10251 // are sorted by getPosition(), and we process each range of equal
10252 // getPosition() values as one group.
10253 // RefArgs are taken from a string literal that was given to
10254 // attribute(format_matches), and if we got this far, we have already
10255 // verified that if it has positional specifiers that appear in multiple
10256 // locations, then they are all mutually compatible. What's left for us to
10257 // do is verify that all specifiers with the same position in FmtArgs are
10258 // compatible with the RefArgs specifiers. We check each specifier from
10259 // FmtArgs against the first member of the RefArgs group.
10260 for (; FmtIter < FmtEnd; ++FmtIter) {
10261 // Clang does not diagnose missing format specifiers in positional-style
10262 // strings (TODO: which it probably should do, as it is UB to skip over a
10263 // format argument). Skip specifiers if needed.
10264 if (FmtIter->getPosition() < RefIter->getPosition())
10265 continue;
10266
10267 // Delimits a new getPosition() value.
10268 if (FmtIter->getPosition() > RefIter->getPosition())
10269 break;
10270
10271 HadError |=
10272 !FmtIter->VerifyCompatible(S, Other: *RefIter, FmtExpr, InFunctionCall);
10273 }
10274
10275 // Jump RefIter to the start of the next group.
10276 RefIter = std::find_if(first: RefIter + 1, last: RefEnd, pred: [=](const auto &Arg) {
10277 return Arg.getPosition() != RefIter->getPosition();
10278 });
10279 }
10280
10281 if (FmtIter < FmtEnd) {
10282 CheckFormatHandler::EmitFormatDiagnostic(
10283 S, InFunctionCall, ArgumentExpr: FmtExpr,
10284 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 1,
10285 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: FmtIter->getSourceRange());
10286 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with) << 1;
10287 } else if (RefIter < RefEnd) {
10288 CheckFormatHandler::EmitFormatDiagnostic(
10289 S, InFunctionCall, ArgumentExpr: FmtExpr,
10290 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 0,
10291 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: Fmt->getSourceRange());
10292 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with)
10293 << 1 << RefIter->getSourceRange();
10294 }
10295 return !HadError;
10296}
10297
10298static void CheckFormatString(
10299 Sema &S, const FormatStringLiteral *FExpr,
10300 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
10301 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
10302 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
10303 bool inFunctionCall, VariadicCallType CallType,
10304 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10305 bool IgnoreStringsWithoutSpecifiers) {
10306 // CHECK: is the format string a wide literal?
10307 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10308 CheckFormatHandler::EmitFormatDiagnostic(
10309 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10310 PDiag: S.PDiag(DiagID: diag::warn_format_string_is_wide_literal), Loc: FExpr->getBeginLoc(),
10311 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
10312 return;
10313 }
10314
10315 // Str - The format string. NOTE: this is NOT null-terminated!
10316 StringRef StrRef = FExpr->getString();
10317 const char *Str = StrRef.data();
10318 // Account for cases where the string literal is truncated in a declaration.
10319 const ConstantArrayType *T =
10320 S.Context.getAsConstantArrayType(T: FExpr->getType());
10321 assert(T && "String literal not of constant array type!");
10322 size_t TypeSize = T->getZExtSize();
10323 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
10324 const unsigned numDataArgs = Args.size() - firstDataArg;
10325
10326 if (IgnoreStringsWithoutSpecifiers &&
10327 !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10328 Begin: Str, End: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
10329 return;
10330
10331 // Emit a warning if the string literal is truncated and does not contain an
10332 // embedded null character.
10333 if (TypeSize <= StrRef.size() && !StrRef.substr(Start: 0, N: TypeSize).contains(C: '\0')) {
10334 CheckFormatHandler::EmitFormatDiagnostic(
10335 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10336 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_not_null_terminated),
10337 Loc: FExpr->getBeginLoc(),
10338 /*IsStringLocation=*/true, StringRange: OrigFormatExpr->getSourceRange());
10339 return;
10340 }
10341
10342 // CHECK: empty format string?
10343 if (StrLen == 0 && numDataArgs > 0) {
10344 CheckFormatHandler::EmitFormatDiagnostic(
10345 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10346 PDiag: S.PDiag(DiagID: diag::warn_empty_format_string), Loc: FExpr->getBeginLoc(),
10347 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
10348 return;
10349 }
10350
10351 if (Type == FormatStringType::Printf || Type == FormatStringType::NSString ||
10352 Type == FormatStringType::Kprintf ||
10353 Type == FormatStringType::FreeBSDKPrintf ||
10354 Type == FormatStringType::OSLog || Type == FormatStringType::OSTrace) {
10355 bool IsObjC =
10356 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10357 if (ReferenceFormatString == nullptr) {
10358 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10359 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10360 inFunctionCall, CallType, CheckedVarArgs,
10361 UncoveredArg);
10362
10363 if (!analyze_format_string::ParsePrintfString(
10364 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
10365 isFreeBSDKPrintf: Type == FormatStringType::Kprintf ||
10366 Type == FormatStringType::FreeBSDKPrintf))
10367 H.DoneProcessing();
10368 } else {
10369 S.CheckFormatStringsCompatible(
10370 FST: Type, AuthoritativeFormatString: ReferenceFormatString, TestedFormatString: FExpr->getFormatString(),
10371 FunctionCallArg: inFunctionCall ? nullptr : Args[format_idx]);
10372 }
10373 } else if (Type == FormatStringType::Scanf) {
10374 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10375 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10376 CallType, CheckedVarArgs, UncoveredArg);
10377
10378 if (!analyze_format_string::ParseScanfString(
10379 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
10380 H.DoneProcessing();
10381 } // TODO: handle other formats
10382}
10383
10384bool Sema::CheckFormatStringsCompatible(
10385 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
10386 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
10387 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
10388 Type != FormatStringType::Kprintf &&
10389 Type != FormatStringType::FreeBSDKPrintf &&
10390 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
10391 return true;
10392
10393 bool IsObjC =
10394 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10395 llvm::SmallVector<EquatableFormatArgument, 9> RefArgs, FmtArgs;
10396 FormatStringLiteral RefLit = AuthoritativeFormatString;
10397 FormatStringLiteral TestLit = TestedFormatString;
10398 const Expr *Arg;
10399 bool DiagAtStringLiteral;
10400 if (FunctionCallArg) {
10401 Arg = FunctionCallArg;
10402 DiagAtStringLiteral = false;
10403 } else {
10404 Arg = TestedFormatString;
10405 DiagAtStringLiteral = true;
10406 }
10407 if (DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit,
10408 FmtExpr: AuthoritativeFormatString, Type,
10409 IsObjC, InFunctionCall: true, Args&: RefArgs) &&
10410 DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &TestLit, FmtExpr: Arg, Type, IsObjC,
10411 InFunctionCall: DiagAtStringLiteral, Args&: FmtArgs)) {
10412 return CompareFormatSpecifiers(S&: *this, Ref: AuthoritativeFormatString, RefArgs,
10413 Fmt: TestedFormatString, FmtArgs, FmtExpr: Arg,
10414 InFunctionCall: DiagAtStringLiteral);
10415 }
10416 return false;
10417}
10418
10419bool Sema::ValidateFormatString(FormatStringType Type,
10420 const StringLiteral *Str) {
10421 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
10422 Type != FormatStringType::Kprintf &&
10423 Type != FormatStringType::FreeBSDKPrintf &&
10424 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
10425 return true;
10426
10427 FormatStringLiteral RefLit = Str;
10428 llvm::SmallVector<EquatableFormatArgument, 9> Args;
10429 bool IsObjC =
10430 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10431 if (!DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit, FmtExpr: Str, Type, IsObjC,
10432 InFunctionCall: true, Args))
10433 return false;
10434
10435 // Group arguments by getPosition() value, and check that each member of the
10436 // group is compatible with the first member. This verifies that when
10437 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10438 // are mutually compatible. As an optimization, don't test the first member
10439 // against itself.
10440 bool HadError = false;
10441 auto Iter = Args.begin();
10442 auto End = Args.end();
10443 while (Iter != End) {
10444 const auto &FirstInGroup = *Iter;
10445 for (++Iter;
10446 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10447 ++Iter) {
10448 HadError |= !Iter->VerifyCompatible(S&: *this, Other: FirstInGroup, FmtExpr: Str, InFunctionCall: true);
10449 }
10450 }
10451 return !HadError;
10452}
10453
10454bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10455 // Str - The format string. NOTE: this is NOT null-terminated!
10456 StringRef StrRef = FExpr->getString();
10457 const char *Str = StrRef.data();
10458 // Account for cases where the string literal is truncated in a declaration.
10459 const ConstantArrayType *T = Context.getAsConstantArrayType(T: FExpr->getType());
10460 assert(T && "String literal not of constant array type!");
10461 size_t TypeSize = T->getZExtSize();
10462 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
10463 return analyze_format_string::ParseFormatStringHasSArg(
10464 beg: Str, end: Str + StrLen, LO: getLangOpts(), Target: Context.getTargetInfo());
10465}
10466
10467//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10468
10469// Returns the related absolute value function that is larger, of 0 if one
10470// does not exist.
10471static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10472 switch (AbsFunction) {
10473 default:
10474 return 0;
10475
10476 case Builtin::BI__builtin_abs:
10477 return Builtin::BI__builtin_labs;
10478 case Builtin::BI__builtin_labs:
10479 return Builtin::BI__builtin_llabs;
10480 case Builtin::BI__builtin_llabs:
10481 return 0;
10482
10483 case Builtin::BI__builtin_fabsf:
10484 return Builtin::BI__builtin_fabs;
10485 case Builtin::BI__builtin_fabs:
10486 return Builtin::BI__builtin_fabsl;
10487 case Builtin::BI__builtin_fabsl:
10488 return 0;
10489
10490 case Builtin::BI__builtin_cabsf:
10491 return Builtin::BI__builtin_cabs;
10492 case Builtin::BI__builtin_cabs:
10493 return Builtin::BI__builtin_cabsl;
10494 case Builtin::BI__builtin_cabsl:
10495 return 0;
10496
10497 case Builtin::BIabs:
10498 return Builtin::BIlabs;
10499 case Builtin::BIlabs:
10500 return Builtin::BIllabs;
10501 case Builtin::BIllabs:
10502 return 0;
10503
10504 case Builtin::BIfabsf:
10505 return Builtin::BIfabs;
10506 case Builtin::BIfabs:
10507 return Builtin::BIfabsl;
10508 case Builtin::BIfabsl:
10509 return 0;
10510
10511 case Builtin::BIcabsf:
10512 return Builtin::BIcabs;
10513 case Builtin::BIcabs:
10514 return Builtin::BIcabsl;
10515 case Builtin::BIcabsl:
10516 return 0;
10517 }
10518}
10519
10520// Returns the argument type of the absolute value function.
10521static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10522 unsigned AbsType) {
10523 if (AbsType == 0)
10524 return QualType();
10525
10526 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10527 QualType BuiltinType = Context.GetBuiltinType(ID: AbsType, Error);
10528 if (Error != ASTContext::GE_None)
10529 return QualType();
10530
10531 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10532 if (!FT)
10533 return QualType();
10534
10535 if (FT->getNumParams() != 1)
10536 return QualType();
10537
10538 return FT->getParamType(i: 0);
10539}
10540
10541// Returns the best absolute value function, or zero, based on type and
10542// current absolute value function.
10543static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10544 unsigned AbsFunctionKind) {
10545 unsigned BestKind = 0;
10546 uint64_t ArgSize = Context.getTypeSize(T: ArgType);
10547 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10548 Kind = getLargerAbsoluteValueFunction(AbsFunction: Kind)) {
10549 QualType ParamType = getAbsoluteValueArgumentType(Context, AbsType: Kind);
10550 if (Context.getTypeSize(T: ParamType) >= ArgSize) {
10551 if (BestKind == 0)
10552 BestKind = Kind;
10553 else if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
10554 BestKind = Kind;
10555 break;
10556 }
10557 }
10558 }
10559 return BestKind;
10560}
10561
10562enum AbsoluteValueKind {
10563 AVK_Integer,
10564 AVK_Floating,
10565 AVK_Complex
10566};
10567
10568static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10569 if (T->isIntegralOrEnumerationType())
10570 return AVK_Integer;
10571 if (T->isRealFloatingType())
10572 return AVK_Floating;
10573 if (T->isAnyComplexType())
10574 return AVK_Complex;
10575
10576 llvm_unreachable("Type not integer, floating, or complex");
10577}
10578
10579// Changes the absolute value function to a different type. Preserves whether
10580// the function is a builtin.
10581static unsigned changeAbsFunction(unsigned AbsKind,
10582 AbsoluteValueKind ValueKind) {
10583 switch (ValueKind) {
10584 case AVK_Integer:
10585 switch (AbsKind) {
10586 default:
10587 return 0;
10588 case Builtin::BI__builtin_fabsf:
10589 case Builtin::BI__builtin_fabs:
10590 case Builtin::BI__builtin_fabsl:
10591 case Builtin::BI__builtin_cabsf:
10592 case Builtin::BI__builtin_cabs:
10593 case Builtin::BI__builtin_cabsl:
10594 return Builtin::BI__builtin_abs;
10595 case Builtin::BIfabsf:
10596 case Builtin::BIfabs:
10597 case Builtin::BIfabsl:
10598 case Builtin::BIcabsf:
10599 case Builtin::BIcabs:
10600 case Builtin::BIcabsl:
10601 return Builtin::BIabs;
10602 }
10603 case AVK_Floating:
10604 switch (AbsKind) {
10605 default:
10606 return 0;
10607 case Builtin::BI__builtin_abs:
10608 case Builtin::BI__builtin_labs:
10609 case Builtin::BI__builtin_llabs:
10610 case Builtin::BI__builtin_cabsf:
10611 case Builtin::BI__builtin_cabs:
10612 case Builtin::BI__builtin_cabsl:
10613 return Builtin::BI__builtin_fabsf;
10614 case Builtin::BIabs:
10615 case Builtin::BIlabs:
10616 case Builtin::BIllabs:
10617 case Builtin::BIcabsf:
10618 case Builtin::BIcabs:
10619 case Builtin::BIcabsl:
10620 return Builtin::BIfabsf;
10621 }
10622 case AVK_Complex:
10623 switch (AbsKind) {
10624 default:
10625 return 0;
10626 case Builtin::BI__builtin_abs:
10627 case Builtin::BI__builtin_labs:
10628 case Builtin::BI__builtin_llabs:
10629 case Builtin::BI__builtin_fabsf:
10630 case Builtin::BI__builtin_fabs:
10631 case Builtin::BI__builtin_fabsl:
10632 return Builtin::BI__builtin_cabsf;
10633 case Builtin::BIabs:
10634 case Builtin::BIlabs:
10635 case Builtin::BIllabs:
10636 case Builtin::BIfabsf:
10637 case Builtin::BIfabs:
10638 case Builtin::BIfabsl:
10639 return Builtin::BIcabsf;
10640 }
10641 }
10642 llvm_unreachable("Unable to convert function");
10643}
10644
10645static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10646 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10647 if (!FnInfo)
10648 return 0;
10649
10650 switch (FDecl->getBuiltinID()) {
10651 default:
10652 return 0;
10653 case Builtin::BI__builtin_abs:
10654 case Builtin::BI__builtin_fabs:
10655 case Builtin::BI__builtin_fabsf:
10656 case Builtin::BI__builtin_fabsl:
10657 case Builtin::BI__builtin_labs:
10658 case Builtin::BI__builtin_llabs:
10659 case Builtin::BI__builtin_cabs:
10660 case Builtin::BI__builtin_cabsf:
10661 case Builtin::BI__builtin_cabsl:
10662 case Builtin::BIabs:
10663 case Builtin::BIlabs:
10664 case Builtin::BIllabs:
10665 case Builtin::BIfabs:
10666 case Builtin::BIfabsf:
10667 case Builtin::BIfabsl:
10668 case Builtin::BIcabs:
10669 case Builtin::BIcabsf:
10670 case Builtin::BIcabsl:
10671 return FDecl->getBuiltinID();
10672 }
10673 llvm_unreachable("Unknown Builtin type");
10674}
10675
10676// If the replacement is valid, emit a note with replacement function.
10677// Additionally, suggest including the proper header if not already included.
10678static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10679 unsigned AbsKind, QualType ArgType) {
10680 bool EmitHeaderHint = true;
10681 const char *HeaderName = nullptr;
10682 std::string FunctionName;
10683 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10684 FunctionName = "std::abs";
10685 if (ArgType->isIntegralOrEnumerationType()) {
10686 HeaderName = "cstdlib";
10687 } else if (ArgType->isRealFloatingType()) {
10688 HeaderName = "cmath";
10689 } else {
10690 llvm_unreachable("Invalid Type");
10691 }
10692
10693 // Lookup all std::abs
10694 if (NamespaceDecl *Std = S.getStdNamespace()) {
10695 LookupResult R(S, &S.Context.Idents.get(Name: "abs"), Loc, Sema::LookupAnyName);
10696 R.suppressDiagnostics();
10697 S.LookupQualifiedName(R, LookupCtx: Std);
10698
10699 for (const auto *I : R) {
10700 const FunctionDecl *FDecl = nullptr;
10701 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(Val: I)) {
10702 FDecl = dyn_cast<FunctionDecl>(Val: UsingD->getTargetDecl());
10703 } else {
10704 FDecl = dyn_cast<FunctionDecl>(Val: I);
10705 }
10706 if (!FDecl)
10707 continue;
10708
10709 // Found std::abs(), check that they are the right ones.
10710 if (FDecl->getNumParams() != 1)
10711 continue;
10712
10713 // Check that the parameter type can handle the argument.
10714 QualType ParamType = FDecl->getParamDecl(i: 0)->getType();
10715 if (getAbsoluteValueKind(T: ArgType) == getAbsoluteValueKind(T: ParamType) &&
10716 S.Context.getTypeSize(T: ArgType) <=
10717 S.Context.getTypeSize(T: ParamType)) {
10718 // Found a function, don't need the header hint.
10719 EmitHeaderHint = false;
10720 break;
10721 }
10722 }
10723 }
10724 } else {
10725 FunctionName = S.Context.BuiltinInfo.getName(ID: AbsKind);
10726 HeaderName = S.Context.BuiltinInfo.getHeaderName(ID: AbsKind);
10727
10728 if (HeaderName) {
10729 DeclarationName DN(&S.Context.Idents.get(Name: FunctionName));
10730 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10731 R.suppressDiagnostics();
10732 S.LookupName(R, S: S.getCurScope());
10733
10734 if (R.isSingleResult()) {
10735 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
10736 if (FD && FD->getBuiltinID() == AbsKind) {
10737 EmitHeaderHint = false;
10738 } else {
10739 return;
10740 }
10741 } else if (!R.empty()) {
10742 return;
10743 }
10744 }
10745 }
10746
10747 S.Diag(Loc, DiagID: diag::note_replace_abs_function)
10748 << FunctionName << FixItHint::CreateReplacement(RemoveRange: Range, Code: FunctionName);
10749
10750 if (!HeaderName)
10751 return;
10752
10753 if (!EmitHeaderHint)
10754 return;
10755
10756 S.Diag(Loc, DiagID: diag::note_include_header_or_declare) << HeaderName
10757 << FunctionName;
10758}
10759
10760template <std::size_t StrLen>
10761static bool IsStdFunction(const FunctionDecl *FDecl,
10762 const char (&Str)[StrLen]) {
10763 if (!FDecl)
10764 return false;
10765 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10766 return false;
10767 if (!FDecl->isInStdNamespace())
10768 return false;
10769
10770 return true;
10771}
10772
10773enum class MathCheck { NaN, Inf };
10774static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10775 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10776 return llvm::is_contained(Set: names, Element: calleeName);
10777 };
10778
10779 switch (Check) {
10780 case MathCheck::NaN:
10781 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10782 "__builtin_nanf16", "__builtin_nanf128"});
10783 case MathCheck::Inf:
10784 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10785 "__builtin_inff16", "__builtin_inff128"});
10786 }
10787 llvm_unreachable("unknown MathCheck");
10788}
10789
10790static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10791 if (FDecl->getName() != "infinity")
10792 return false;
10793
10794 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(Val: FDecl)) {
10795 const CXXRecordDecl *RDecl = MDecl->getParent();
10796 if (RDecl->getName() != "numeric_limits")
10797 return false;
10798
10799 if (const NamespaceDecl *NSDecl =
10800 dyn_cast<NamespaceDecl>(Val: RDecl->getDeclContext()))
10801 return NSDecl->isStdNamespace();
10802 }
10803
10804 return false;
10805}
10806
10807void Sema::CheckInfNaNFunction(const CallExpr *Call,
10808 const FunctionDecl *FDecl) {
10809 if (!FDecl->getIdentifier())
10810 return;
10811
10812 FPOptions FPO = Call->getFPFeaturesInEffect(LO: getLangOpts());
10813 if (FPO.getNoHonorNaNs() &&
10814 (IsStdFunction(FDecl, Str: "isnan") || IsStdFunction(FDecl, Str: "isunordered") ||
10815 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::NaN))) {
10816 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10817 << 1 << 0 << Call->getSourceRange();
10818 return;
10819 }
10820
10821 if (FPO.getNoHonorInfs() &&
10822 (IsStdFunction(FDecl, Str: "isinf") || IsStdFunction(FDecl, Str: "isfinite") ||
10823 IsInfinityFunction(FDecl) ||
10824 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::Inf))) {
10825 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10826 << 0 << 0 << Call->getSourceRange();
10827 }
10828}
10829
10830void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10831 const FunctionDecl *FDecl) {
10832 if (Call->getNumArgs() != 1)
10833 return;
10834
10835 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10836 bool IsStdAbs = IsStdFunction(FDecl, Str: "abs");
10837 if (AbsKind == 0 && !IsStdAbs)
10838 return;
10839
10840 QualType ArgType = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
10841 QualType ParamType = Call->getArg(Arg: 0)->getType();
10842
10843 // Unsigned types cannot be negative. Suggest removing the absolute value
10844 // function call.
10845 if (ArgType->isUnsignedIntegerType()) {
10846 std::string FunctionName =
10847 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(ID: AbsKind);
10848 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_unsigned_abs) << ArgType << ParamType;
10849 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_abs)
10850 << FunctionName
10851 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange());
10852 return;
10853 }
10854
10855 // Taking the absolute value of a pointer is very suspicious, they probably
10856 // wanted to index into an array, dereference a pointer, call a function, etc.
10857 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10858 unsigned DiagType = 0;
10859 if (ArgType->isFunctionType())
10860 DiagType = 1;
10861 else if (ArgType->isArrayType())
10862 DiagType = 2;
10863
10864 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_pointer_abs) << DiagType << ArgType;
10865 return;
10866 }
10867
10868 // std::abs has overloads which prevent most of the absolute value problems
10869 // from occurring.
10870 if (IsStdAbs)
10871 return;
10872
10873 // Prevent reaching unreachable code in getAbsoluteValueKind for unsupported
10874 // types.
10875 if (!ArgType->isIntegralOrEnumerationType() &&
10876 !ArgType->isRealFloatingType() && !ArgType->isAnyComplexType())
10877 return;
10878
10879 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(T: ArgType);
10880 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(T: ParamType);
10881
10882 // The argument and parameter are the same kind. Check if they are the right
10883 // size.
10884 if (ArgValueKind == ParamValueKind) {
10885 if (Context.getTypeSize(T: ArgType) <= Context.getTypeSize(T: ParamType))
10886 return;
10887
10888 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: AbsKind);
10889 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_abs_too_small)
10890 << FDecl << ArgType << ParamType;
10891
10892 if (NewAbsKind == 0)
10893 return;
10894
10895 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10896 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10897 return;
10898 }
10899
10900 // ArgValueKind != ParamValueKind
10901 // The wrong type of absolute value function was used. Attempt to find the
10902 // proper one.
10903 unsigned NewAbsKind = changeAbsFunction(AbsKind, ValueKind: ArgValueKind);
10904 NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: NewAbsKind);
10905 if (NewAbsKind == 0)
10906 return;
10907
10908 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_wrong_absolute_value_type)
10909 << FDecl << ParamValueKind << ArgValueKind;
10910
10911 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10912 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10913}
10914
10915//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10916void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10917 const FunctionDecl *FDecl) {
10918 if (!Call || !FDecl) return;
10919
10920 // Ignore template specializations and macros.
10921 if (inTemplateInstantiation()) return;
10922 if (Call->getExprLoc().isMacroID()) return;
10923
10924 // Only care about the one template argument, two function parameter std::max
10925 if (Call->getNumArgs() != 2) return;
10926 if (!IsStdFunction(FDecl, Str: "max")) return;
10927 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10928 if (!ArgList) return;
10929 if (ArgList->size() != 1) return;
10930
10931 // Check that template type argument is unsigned integer.
10932 const auto& TA = ArgList->get(Idx: 0);
10933 if (TA.getKind() != TemplateArgument::Type) return;
10934 QualType ArgType = TA.getAsType();
10935 if (!ArgType->isUnsignedIntegerType()) return;
10936
10937 // See if either argument is a literal zero.
10938 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10939 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E);
10940 if (!MTE) return false;
10941 const auto *Num = dyn_cast<IntegerLiteral>(Val: MTE->getSubExpr());
10942 if (!Num) return false;
10943 if (Num->getValue() != 0) return false;
10944 return true;
10945 };
10946
10947 const Expr *FirstArg = Call->getArg(Arg: 0);
10948 const Expr *SecondArg = Call->getArg(Arg: 1);
10949 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10950 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10951
10952 // Only warn when exactly one argument is zero.
10953 if (IsFirstArgZero == IsSecondArgZero) return;
10954
10955 SourceRange FirstRange = FirstArg->getSourceRange();
10956 SourceRange SecondRange = SecondArg->getSourceRange();
10957
10958 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10959
10960 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_max_unsigned_zero)
10961 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10962
10963 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10964 SourceRange RemovalRange;
10965 if (IsFirstArgZero) {
10966 RemovalRange = SourceRange(FirstRange.getBegin(),
10967 SecondRange.getBegin().getLocWithOffset(Offset: -1));
10968 } else {
10969 RemovalRange = SourceRange(getLocForEndOfToken(Loc: FirstRange.getEnd()),
10970 SecondRange.getEnd());
10971 }
10972
10973 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_max_call)
10974 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange())
10975 << FixItHint::CreateRemoval(RemoveRange: RemovalRange);
10976}
10977
10978//===--- CHECK: Standard memory functions ---------------------------------===//
10979
10980/// Takes the expression passed to the size_t parameter of functions
10981/// such as memcmp, strncat, etc and warns if it's a comparison.
10982///
10983/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10984static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10985 const IdentifierInfo *FnName,
10986 SourceLocation FnLoc,
10987 SourceLocation RParenLoc) {
10988 const auto *Size = dyn_cast<BinaryOperator>(Val: E);
10989 if (!Size)
10990 return false;
10991
10992 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10993 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10994 return false;
10995
10996 SourceRange SizeRange = Size->getSourceRange();
10997 S.Diag(Loc: Size->getOperatorLoc(), DiagID: diag::warn_memsize_comparison)
10998 << SizeRange << FnName;
10999 S.Diag(Loc: FnLoc, DiagID: diag::note_memsize_comparison_paren)
11000 << FnName
11001 << FixItHint::CreateInsertion(
11002 InsertionLoc: S.getLocForEndOfToken(Loc: Size->getLHS()->getEndLoc()), Code: ")")
11003 << FixItHint::CreateRemoval(RemoveRange: RParenLoc);
11004 S.Diag(Loc: SizeRange.getBegin(), DiagID: diag::note_memsize_comparison_cast_silence)
11005 << FixItHint::CreateInsertion(InsertionLoc: SizeRange.getBegin(), Code: "(size_t)(")
11006 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: SizeRange.getEnd()),
11007 Code: ")");
11008
11009 return true;
11010}
11011
11012/// Determine whether the given type is or contains a dynamic class type
11013/// (e.g., whether it has a vtable).
11014static const CXXRecordDecl *getContainedDynamicClass(QualType T,
11015 bool &IsContained) {
11016 // Look through array types while ignoring qualifiers.
11017 const Type *Ty = T->getBaseElementTypeUnsafe();
11018 IsContained = false;
11019
11020 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
11021 RD = RD ? RD->getDefinition() : nullptr;
11022 if (!RD || RD->isInvalidDecl())
11023 return nullptr;
11024
11025 if (RD->isDynamicClass())
11026 return RD;
11027
11028 // Check all the fields. If any bases were dynamic, the class is dynamic.
11029 // It's impossible for a class to transitively contain itself by value, so
11030 // infinite recursion is impossible.
11031 for (auto *FD : RD->fields()) {
11032 bool SubContained;
11033 if (const CXXRecordDecl *ContainedRD =
11034 getContainedDynamicClass(T: FD->getType(), IsContained&: SubContained)) {
11035 IsContained = true;
11036 return ContainedRD;
11037 }
11038 }
11039
11040 return nullptr;
11041}
11042
11043static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
11044 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: E))
11045 if (Unary->getKind() == UETT_SizeOf)
11046 return Unary;
11047 return nullptr;
11048}
11049
11050/// If E is a sizeof expression, returns its argument expression,
11051/// otherwise returns NULL.
11052static const Expr *getSizeOfExprArg(const Expr *E) {
11053 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
11054 if (!SizeOf->isArgumentType())
11055 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
11056 return nullptr;
11057}
11058
11059/// If E is a sizeof expression, returns its argument type.
11060static QualType getSizeOfArgType(const Expr *E) {
11061 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
11062 return SizeOf->getTypeOfArgument();
11063 return QualType();
11064}
11065
11066namespace {
11067
11068struct SearchNonTrivialToInitializeField
11069 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
11070 using Super =
11071 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
11072
11073 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
11074
11075 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
11076 SourceLocation SL) {
11077 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
11078 asDerived().visitArray(PDIK, AT, SL);
11079 return;
11080 }
11081
11082 Super::visitWithKind(PDIK, FT, Args&: SL);
11083 }
11084
11085 void visitARCStrong(QualType FT, SourceLocation SL) {
11086 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
11087 }
11088 void visitARCWeak(QualType FT, SourceLocation SL) {
11089 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
11090 }
11091 void visitStruct(QualType FT, SourceLocation SL) {
11092 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
11093 visit(FT: FD->getType(), Args: FD->getLocation());
11094 }
11095 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
11096 const ArrayType *AT, SourceLocation SL) {
11097 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
11098 }
11099 void visitTrivial(QualType FT, SourceLocation SL) {}
11100
11101 static void diag(QualType RT, const Expr *E, Sema &S) {
11102 SearchNonTrivialToInitializeField(E, S).visitStruct(FT: RT, SL: SourceLocation());
11103 }
11104
11105 ASTContext &getContext() { return S.getASTContext(); }
11106
11107 const Expr *E;
11108 Sema &S;
11109};
11110
11111struct SearchNonTrivialToCopyField
11112 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
11113 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
11114
11115 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
11116
11117 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
11118 SourceLocation SL) {
11119 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
11120 asDerived().visitArray(PCK, AT, SL);
11121 return;
11122 }
11123
11124 Super::visitWithKind(PCK, FT, Args&: SL);
11125 }
11126
11127 void visitARCStrong(QualType FT, SourceLocation SL) {
11128 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
11129 }
11130 void visitARCWeak(QualType FT, SourceLocation SL) {
11131 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
11132 }
11133 void visitPtrAuth(QualType FT, SourceLocation SL) {
11134 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
11135 }
11136 void visitStruct(QualType FT, SourceLocation SL) {
11137 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
11138 visit(FT: FD->getType(), Args: FD->getLocation());
11139 }
11140 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
11141 SourceLocation SL) {
11142 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
11143 }
11144 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
11145 SourceLocation SL) {}
11146 void visitTrivial(QualType FT, SourceLocation SL) {}
11147 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
11148
11149 static void diag(QualType RT, const Expr *E, Sema &S) {
11150 SearchNonTrivialToCopyField(E, S).visitStruct(FT: RT, SL: SourceLocation());
11151 }
11152
11153 ASTContext &getContext() { return S.getASTContext(); }
11154
11155 const Expr *E;
11156 Sema &S;
11157};
11158
11159}
11160
11161/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
11162static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
11163 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
11164
11165 if (const auto *BO = dyn_cast<BinaryOperator>(Val: SizeofExpr)) {
11166 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
11167 return false;
11168
11169 return doesExprLikelyComputeSize(SizeofExpr: BO->getLHS()) ||
11170 doesExprLikelyComputeSize(SizeofExpr: BO->getRHS());
11171 }
11172
11173 return getAsSizeOfExpr(E: SizeofExpr) != nullptr;
11174}
11175
11176/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
11177///
11178/// \code
11179/// #define MACRO 0
11180/// foo(MACRO);
11181/// foo(0);
11182/// \endcode
11183///
11184/// This should return true for the first call to foo, but not for the second
11185/// (regardless of whether foo is a macro or function).
11186static bool isArgumentExpandedFromMacro(SourceManager &SM,
11187 SourceLocation CallLoc,
11188 SourceLocation ArgLoc) {
11189 if (!CallLoc.isMacroID())
11190 return SM.getFileID(SpellingLoc: CallLoc) != SM.getFileID(SpellingLoc: ArgLoc);
11191
11192 return SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: CallLoc)) !=
11193 SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: ArgLoc));
11194}
11195
11196/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
11197/// last two arguments transposed.
11198static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
11199 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
11200 return;
11201
11202 const Expr *SizeArg =
11203 Call->getArg(Arg: BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
11204
11205 auto isLiteralZero = [](const Expr *E) {
11206 return (isa<IntegerLiteral>(Val: E) &&
11207 cast<IntegerLiteral>(Val: E)->getValue() == 0) ||
11208 (isa<CharacterLiteral>(Val: E) &&
11209 cast<CharacterLiteral>(Val: E)->getValue() == 0);
11210 };
11211
11212 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
11213 SourceLocation CallLoc = Call->getRParenLoc();
11214 SourceManager &SM = S.getSourceManager();
11215 if (isLiteralZero(SizeArg) &&
11216 !isArgumentExpandedFromMacro(SM, CallLoc, ArgLoc: SizeArg->getExprLoc())) {
11217
11218 SourceLocation DiagLoc = SizeArg->getExprLoc();
11219
11220 // Some platforms #define bzero to __builtin_memset. See if this is the
11221 // case, and if so, emit a better diagnostic.
11222 if (BId == Builtin::BIbzero ||
11223 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
11224 Loc: CallLoc, SM, LangOpts: S.getLangOpts()) == "bzero")) {
11225 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_bzero_size);
11226 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_bzero_size_silence);
11227 } else if (!isLiteralZero(Call->getArg(Arg: 1)->IgnoreImpCasts())) {
11228 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 0;
11229 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 0;
11230 }
11231 return;
11232 }
11233
11234 // If the second argument to a memset is a sizeof expression and the third
11235 // isn't, this is also likely an error. This should catch
11236 // 'memset(buf, sizeof(buf), 0xff)'.
11237 if (BId == Builtin::BImemset &&
11238 doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 1)) &&
11239 !doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 2))) {
11240 SourceLocation DiagLoc = Call->getArg(Arg: 1)->getExprLoc();
11241 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 1;
11242 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 1;
11243 return;
11244 }
11245}
11246
11247void Sema::CheckMemaccessArguments(const CallExpr *Call,
11248 unsigned BId,
11249 IdentifierInfo *FnName) {
11250 assert(BId != 0);
11251
11252 // It is possible to have a non-standard definition of memset. Validate
11253 // we have enough arguments, and if not, abort further checking.
11254 unsigned ExpectedNumArgs =
11255 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11256 if (Call->getNumArgs() < ExpectedNumArgs)
11257 return;
11258
11259 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11260 BId == Builtin::BIstrndup ? 1 : 2);
11261 unsigned LenArg =
11262 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11263 const Expr *LenExpr = Call->getArg(Arg: LenArg)->IgnoreParenImpCasts();
11264
11265 if (CheckMemorySizeofForComparison(S&: *this, E: LenExpr, FnName,
11266 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
11267 return;
11268
11269 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11270 CheckMemaccessSize(S&: *this, BId, Call);
11271
11272 // We have special checking when the length is a sizeof expression.
11273 QualType SizeOfArgTy = getSizeOfArgType(E: LenExpr);
11274
11275 // Although widely used, 'bzero' is not a standard function. Be more strict
11276 // with the argument types before allowing diagnostics and only allow the
11277 // form bzero(ptr, sizeof(...)).
11278 QualType FirstArgTy = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
11279 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11280 return;
11281
11282 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11283 const Expr *Dest = Call->getArg(Arg: ArgIdx)->IgnoreParenImpCasts();
11284 SourceRange ArgRange = Call->getArg(Arg: ArgIdx)->getSourceRange();
11285
11286 QualType DestTy = Dest->getType();
11287 QualType PointeeTy;
11288 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11289 PointeeTy = DestPtrTy->getPointeeType();
11290
11291 // Never warn about void type pointers. This can be used to suppress
11292 // false positives.
11293 if (PointeeTy->isVoidType())
11294 continue;
11295
11296 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11297 // actually comparing the expressions for equality. Because computing the
11298 // expression IDs can be expensive, we only do this if the diagnostic is
11299 // enabled.
11300 if (CheckSizeofMemaccessArgument(SizeOfArg: LenExpr, Dest, FnName))
11301 break;
11302
11303 // Also check for cases where the sizeof argument is the exact same
11304 // type as the memory argument, and where it points to a user-defined
11305 // record type.
11306 if (SizeOfArgTy != QualType()) {
11307 if (PointeeTy->isRecordType() &&
11308 Context.typesAreCompatible(T1: SizeOfArgTy, T2: DestTy)) {
11309 DiagRuntimeBehavior(Loc: LenExpr->getExprLoc(), Statement: Dest,
11310 PD: PDiag(DiagID: diag::warn_sizeof_pointer_type_memaccess)
11311 << FnName << SizeOfArgTy << ArgIdx
11312 << PointeeTy << Dest->getSourceRange()
11313 << LenExpr->getSourceRange());
11314 break;
11315 }
11316 }
11317 } else if (DestTy->isArrayType()) {
11318 PointeeTy = DestTy;
11319 }
11320
11321 if (PointeeTy == QualType())
11322 continue;
11323
11324 // Always complain about dynamic classes.
11325 bool IsContained;
11326 if (const CXXRecordDecl *ContainedRD =
11327 getContainedDynamicClass(T: PointeeTy, IsContained)) {
11328
11329 unsigned OperationType = 0;
11330 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11331 // "overwritten" if we're warning about the destination for any call
11332 // but memcmp; otherwise a verb appropriate to the call.
11333 if (ArgIdx != 0 || IsCmp) {
11334 if (BId == Builtin::BImemcpy)
11335 OperationType = 1;
11336 else if(BId == Builtin::BImemmove)
11337 OperationType = 2;
11338 else if (IsCmp)
11339 OperationType = 3;
11340 }
11341
11342 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11343 PD: PDiag(DiagID: diag::warn_dyn_class_memaccess)
11344 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11345 << IsContained << ContainedRD << OperationType
11346 << Call->getCallee()->getSourceRange());
11347 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11348 BId != Builtin::BImemset)
11349 DiagRuntimeBehavior(
11350 Loc: Dest->getExprLoc(), Statement: Dest,
11351 PD: PDiag(DiagID: diag::warn_arc_object_memaccess)
11352 << ArgIdx << FnName << PointeeTy
11353 << Call->getCallee()->getSourceRange());
11354 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
11355
11356 // FIXME: Do not consider incomplete types even though they may be
11357 // completed later. GCC does not diagnose such code, but we may want to
11358 // consider diagnosing it in the future, perhaps under a different, but
11359 // related, diagnostic group.
11360 bool NonTriviallyCopyableCXXRecord =
11361 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
11362 !PointeeTy.isTriviallyCopyableType(Context);
11363
11364 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11365 RD->isNonTrivialToPrimitiveDefaultInitialize()) {
11366 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11367 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
11368 << ArgIdx << FnName << PointeeTy << 0);
11369 SearchNonTrivialToInitializeField::diag(RT: PointeeTy, E: Dest, S&: *this);
11370 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11371 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11372 // FIXME: Limiting this warning to dest argument until we decide
11373 // whether it's valid for source argument too.
11374 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11375 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
11376 << FnName << PointeeTy);
11377 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11378 RD->isNonTrivialToPrimitiveCopy()) {
11379 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11380 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
11381 << ArgIdx << FnName << PointeeTy << 1);
11382 SearchNonTrivialToCopyField::diag(RT: PointeeTy, E: Dest, S&: *this);
11383 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11384 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11385 // FIXME: Limiting this warning to dest argument until we decide
11386 // whether it's valid for source argument too.
11387 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11388 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
11389 << FnName << PointeeTy);
11390 } else {
11391 continue;
11392 }
11393 } else
11394 continue;
11395
11396 DiagRuntimeBehavior(
11397 Loc: Dest->getExprLoc(), Statement: Dest,
11398 PD: PDiag(DiagID: diag::note_bad_memaccess_silence)
11399 << FixItHint::CreateInsertion(InsertionLoc: ArgRange.getBegin(), Code: "(void*)"));
11400 break;
11401 }
11402}
11403
11404bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
11405 IdentifierInfo *FnName) {
11406 llvm::FoldingSetNodeID SizeOfArgID;
11407 const Expr *SizeOfArg = getSizeOfExprArg(E: LenExpr);
11408 if (!SizeOfArg)
11409 return false;
11410 // Computing this warning is expensive, so we only do so if the warning is
11411 // enabled.
11412 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess,
11413 Loc: SizeOfArg->getExprLoc()))
11414 return false;
11415 QualType DestTy = Dest->getType();
11416 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
11417 if (!DestPtrTy)
11418 return false;
11419
11420 QualType PointeeTy = DestPtrTy->getPointeeType();
11421
11422 if (SizeOfArgID == llvm::FoldingSetNodeID())
11423 SizeOfArg->Profile(ID&: SizeOfArgID, Context, Canonical: true);
11424
11425 llvm::FoldingSetNodeID DestID;
11426 Dest->Profile(ID&: DestID, Context, Canonical: true);
11427 if (DestID == SizeOfArgID) {
11428 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11429 // over sizeof(src) as well.
11430 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11431 StringRef ReadableName = FnName->getName();
11432
11433 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Val: Dest);
11434 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11435 ActionIdx = 1; // If its an address-of operator, just remove it.
11436 if (!PointeeTy->isIncompleteType() &&
11437 (Context.getTypeSize(T: PointeeTy) == Context.getCharWidth()))
11438 ActionIdx = 2; // If the pointee's size is sizeof(char),
11439 // suggest an explicit length.
11440
11441 // If the function is defined as a builtin macro, do not show macro
11442 // expansion.
11443 SourceLocation SL = SizeOfArg->getExprLoc();
11444 SourceRange DSR = Dest->getSourceRange();
11445 SourceRange SSR = SizeOfArg->getSourceRange();
11446 SourceManager &SM = getSourceManager();
11447
11448 if (SM.isMacroArgExpansion(Loc: SL)) {
11449 ReadableName = Lexer::getImmediateMacroName(Loc: SL, SM, LangOpts);
11450 SL = SM.getSpellingLoc(Loc: SL);
11451 DSR = SourceRange(SM.getSpellingLoc(Loc: DSR.getBegin()),
11452 SM.getSpellingLoc(Loc: DSR.getEnd()));
11453 SSR = SourceRange(SM.getSpellingLoc(Loc: SSR.getBegin()),
11454 SM.getSpellingLoc(Loc: SSR.getEnd()));
11455 }
11456
11457 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
11458 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess)
11459 << ReadableName << PointeeTy << DestTy << DSR
11460 << SSR);
11461 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
11462 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess_note)
11463 << ActionIdx << SSR);
11464 return true;
11465 }
11466 return false;
11467}
11468
11469// A little helper routine: ignore addition and subtraction of integer literals.
11470// This intentionally does not ignore all integer constant expressions because
11471// we don't want to remove sizeof().
11472static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11473 Ex = Ex->IgnoreParenCasts();
11474
11475 while (true) {
11476 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Val: Ex);
11477 if (!BO || !BO->isAdditiveOp())
11478 break;
11479
11480 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11481 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11482
11483 if (isa<IntegerLiteral>(Val: RHS))
11484 Ex = LHS;
11485 else if (isa<IntegerLiteral>(Val: LHS))
11486 Ex = RHS;
11487 else
11488 break;
11489 }
11490
11491 return Ex;
11492}
11493
11494static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11495 ASTContext &Context) {
11496 // Only handle constant-sized or VLAs, but not flexible members.
11497 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T: Ty)) {
11498 // Only issue the FIXIT for arrays of size > 1.
11499 if (CAT->getZExtSize() <= 1)
11500 return false;
11501 } else if (!Ty->isVariableArrayType()) {
11502 return false;
11503 }
11504 return true;
11505}
11506
11507void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11508 IdentifierInfo *FnName) {
11509
11510 // Don't crash if the user has the wrong number of arguments
11511 unsigned NumArgs = Call->getNumArgs();
11512 if ((NumArgs != 3) && (NumArgs != 4))
11513 return;
11514
11515 const Expr *SrcArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 1), Ctx&: Context);
11516 const Expr *SizeArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 2), Ctx&: Context);
11517 const Expr *CompareWithSrc = nullptr;
11518
11519 if (CheckMemorySizeofForComparison(S&: *this, E: SizeArg, FnName,
11520 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
11521 return;
11522
11523 // Look for 'strlcpy(dst, x, sizeof(x))'
11524 if (const Expr *Ex = getSizeOfExprArg(E: SizeArg))
11525 CompareWithSrc = Ex;
11526 else {
11527 // Look for 'strlcpy(dst, x, strlen(x))'
11528 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(Val: SizeArg)) {
11529 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11530 SizeCall->getNumArgs() == 1)
11531 CompareWithSrc = ignoreLiteralAdditions(Ex: SizeCall->getArg(Arg: 0), Ctx&: Context);
11532 }
11533 }
11534
11535 if (!CompareWithSrc)
11536 return;
11537
11538 // Determine if the argument to sizeof/strlen is equal to the source
11539 // argument. In principle there's all kinds of things you could do
11540 // here, for instance creating an == expression and evaluating it with
11541 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11542 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(Val: SrcArg);
11543 if (!SrcArgDRE)
11544 return;
11545
11546 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(Val: CompareWithSrc);
11547 if (!CompareWithSrcDRE ||
11548 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11549 return;
11550
11551 const Expr *OriginalSizeArg = Call->getArg(Arg: 2);
11552 Diag(Loc: CompareWithSrcDRE->getBeginLoc(), DiagID: diag::warn_strlcpycat_wrong_size)
11553 << OriginalSizeArg->getSourceRange() << FnName;
11554
11555 // Output a FIXIT hint if the destination is an array (rather than a
11556 // pointer to an array). This could be enhanced to handle some
11557 // pointers if we know the actual size, like if DstArg is 'array+2'
11558 // we could say 'sizeof(array)-2'.
11559 const Expr *DstArg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
11560 if (!isConstantSizeArrayWithMoreThanOneElement(Ty: DstArg->getType(), Context))
11561 return;
11562
11563 SmallString<128> sizeString;
11564 llvm::raw_svector_ostream OS(sizeString);
11565 OS << "sizeof(";
11566 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11567 OS << ")";
11568
11569 Diag(Loc: OriginalSizeArg->getBeginLoc(), DiagID: diag::note_strlcpycat_wrong_size)
11570 << FixItHint::CreateReplacement(RemoveRange: OriginalSizeArg->getSourceRange(),
11571 Code: OS.str());
11572}
11573
11574/// Check if two expressions refer to the same declaration.
11575static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11576 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(Val: E1))
11577 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(Val: E2))
11578 return D1->getDecl() == D2->getDecl();
11579 return false;
11580}
11581
11582static const Expr *getStrlenExprArg(const Expr *E) {
11583 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
11584 const FunctionDecl *FD = CE->getDirectCallee();
11585 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11586 return nullptr;
11587 return CE->getArg(Arg: 0)->IgnoreParenCasts();
11588 }
11589 return nullptr;
11590}
11591
11592void Sema::CheckStrncatArguments(const CallExpr *CE,
11593 const IdentifierInfo *FnName) {
11594 // Don't crash if the user has the wrong number of arguments.
11595 if (CE->getNumArgs() < 3)
11596 return;
11597 const Expr *DstArg = CE->getArg(Arg: 0)->IgnoreParenCasts();
11598 const Expr *SrcArg = CE->getArg(Arg: 1)->IgnoreParenCasts();
11599 const Expr *LenArg = CE->getArg(Arg: 2)->IgnoreParenCasts();
11600
11601 if (CheckMemorySizeofForComparison(S&: *this, E: LenArg, FnName, FnLoc: CE->getBeginLoc(),
11602 RParenLoc: CE->getRParenLoc()))
11603 return;
11604
11605 // Identify common expressions, which are wrongly used as the size argument
11606 // to strncat and may lead to buffer overflows.
11607 unsigned PatternType = 0;
11608 if (const Expr *SizeOfArg = getSizeOfExprArg(E: LenArg)) {
11609 // - sizeof(dst)
11610 if (referToTheSameDecl(E1: SizeOfArg, E2: DstArg))
11611 PatternType = 1;
11612 // - sizeof(src)
11613 else if (referToTheSameDecl(E1: SizeOfArg, E2: SrcArg))
11614 PatternType = 2;
11615 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Val: LenArg)) {
11616 if (BE->getOpcode() == BO_Sub) {
11617 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11618 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11619 // - sizeof(dst) - strlen(dst)
11620 if (referToTheSameDecl(E1: DstArg, E2: getSizeOfExprArg(E: L)) &&
11621 referToTheSameDecl(E1: DstArg, E2: getStrlenExprArg(E: R)))
11622 PatternType = 1;
11623 // - sizeof(src) - (anything)
11624 else if (referToTheSameDecl(E1: SrcArg, E2: getSizeOfExprArg(E: L)))
11625 PatternType = 2;
11626 }
11627 }
11628
11629 if (PatternType == 0)
11630 return;
11631
11632 // Generate the diagnostic.
11633 SourceLocation SL = LenArg->getBeginLoc();
11634 SourceRange SR = LenArg->getSourceRange();
11635 SourceManager &SM = getSourceManager();
11636
11637 // If the function is defined as a builtin macro, do not show macro expansion.
11638 if (SM.isMacroArgExpansion(Loc: SL)) {
11639 SL = SM.getSpellingLoc(Loc: SL);
11640 SR = SourceRange(SM.getSpellingLoc(Loc: SR.getBegin()),
11641 SM.getSpellingLoc(Loc: SR.getEnd()));
11642 }
11643
11644 // Check if the destination is an array (rather than a pointer to an array).
11645 QualType DstTy = DstArg->getType();
11646 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(Ty: DstTy,
11647 Context);
11648 if (!isKnownSizeArray) {
11649 if (PatternType == 1)
11650 Diag(Loc: SL, DiagID: diag::warn_strncat_wrong_size) << SR;
11651 else
11652 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11653 return;
11654 }
11655
11656 if (PatternType == 1)
11657 Diag(Loc: SL, DiagID: diag::warn_strncat_large_size) << SR;
11658 else
11659 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11660
11661 SmallString<128> sizeString;
11662 llvm::raw_svector_ostream OS(sizeString);
11663 OS << "sizeof(";
11664 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11665 OS << ") - ";
11666 OS << "strlen(";
11667 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11668 OS << ") - 1";
11669
11670 Diag(Loc: SL, DiagID: diag::note_strncat_wrong_size)
11671 << FixItHint::CreateReplacement(RemoveRange: SR, Code: OS.str());
11672}
11673
11674namespace {
11675void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11676 const UnaryOperator *UnaryExpr, const Decl *D) {
11677 if (isa<FieldDecl, FunctionDecl, VarDecl>(Val: D)) {
11678 S.Diag(Loc: UnaryExpr->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11679 << CalleeName << 0 /*object: */ << cast<NamedDecl>(Val: D);
11680 return;
11681 }
11682}
11683
11684void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11685 const UnaryOperator *UnaryExpr) {
11686 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: UnaryExpr->getSubExpr())) {
11687 const Decl *D = Lvalue->getDecl();
11688 if (const auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
11689 if (!DD->getType()->isReferenceType())
11690 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11691 }
11692 }
11693
11694 if (const auto *Lvalue = dyn_cast<MemberExpr>(Val: UnaryExpr->getSubExpr()))
11695 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11696 D: Lvalue->getMemberDecl());
11697}
11698
11699void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11700 const UnaryOperator *UnaryExpr) {
11701 const auto *Lambda = dyn_cast<LambdaExpr>(
11702 Val: UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11703 if (!Lambda)
11704 return;
11705
11706 S.Diag(Loc: Lambda->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11707 << CalleeName << 2 /*object: lambda expression*/;
11708}
11709
11710void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11711 const DeclRefExpr *Lvalue) {
11712 const auto *Var = dyn_cast<VarDecl>(Val: Lvalue->getDecl());
11713 if (Var == nullptr)
11714 return;
11715
11716 S.Diag(Loc: Lvalue->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11717 << CalleeName << 0 /*object: */ << Var;
11718}
11719
11720void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11721 const CastExpr *Cast) {
11722 SmallString<128> SizeString;
11723 llvm::raw_svector_ostream OS(SizeString);
11724
11725 clang::CastKind Kind = Cast->getCastKind();
11726 if (Kind == clang::CK_BitCast &&
11727 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11728 return;
11729 if (Kind == clang::CK_IntegralToPointer &&
11730 !isa<IntegerLiteral>(
11731 Val: Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11732 return;
11733
11734 switch (Cast->getCastKind()) {
11735 case clang::CK_BitCast:
11736 case clang::CK_IntegralToPointer:
11737 case clang::CK_FunctionToPointerDecay:
11738 OS << '\'';
11739 Cast->printPretty(OS, Helper: nullptr, Policy: S.getPrintingPolicy());
11740 OS << '\'';
11741 break;
11742 default:
11743 return;
11744 }
11745
11746 S.Diag(Loc: Cast->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11747 << CalleeName << 0 /*object: */ << OS.str();
11748}
11749} // namespace
11750
11751void Sema::CheckFreeArguments(const CallExpr *E) {
11752 const std::string CalleeName =
11753 cast<FunctionDecl>(Val: E->getCalleeDecl())->getQualifiedNameAsString();
11754
11755 { // Prefer something that doesn't involve a cast to make things simpler.
11756 const Expr *Arg = E->getArg(Arg: 0)->IgnoreParenCasts();
11757 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Val: Arg))
11758 switch (UnaryExpr->getOpcode()) {
11759 case UnaryOperator::Opcode::UO_AddrOf:
11760 return CheckFreeArgumentsAddressof(S&: *this, CalleeName, UnaryExpr);
11761 case UnaryOperator::Opcode::UO_Plus:
11762 return CheckFreeArgumentsPlus(S&: *this, CalleeName, UnaryExpr);
11763 default:
11764 break;
11765 }
11766
11767 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: Arg))
11768 if (Lvalue->getType()->isArrayType())
11769 return CheckFreeArgumentsStackArray(S&: *this, CalleeName, Lvalue);
11770
11771 if (const auto *Label = dyn_cast<AddrLabelExpr>(Val: Arg)) {
11772 Diag(Loc: Label->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11773 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11774 return;
11775 }
11776
11777 if (isa<BlockExpr>(Val: Arg)) {
11778 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11779 << CalleeName << 1 /*object: block*/;
11780 return;
11781 }
11782 }
11783 // Maybe the cast was important, check after the other cases.
11784 if (const auto *Cast = dyn_cast<CastExpr>(Val: E->getArg(Arg: 0)))
11785 return CheckFreeArgumentsCast(S&: *this, CalleeName, Cast);
11786}
11787
11788void
11789Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11790 SourceLocation ReturnLoc,
11791 bool isObjCMethod,
11792 const AttrVec *Attrs,
11793 const FunctionDecl *FD) {
11794 // Check if the return value is null but should not be.
11795 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(container: *Attrs)) ||
11796 (!isObjCMethod && isNonNullType(type: lhsType))) &&
11797 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11798 Diag(Loc: ReturnLoc, DiagID: diag::warn_null_ret)
11799 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11800
11801 // C++11 [basic.stc.dynamic.allocation]p4:
11802 // If an allocation function declared with a non-throwing
11803 // exception-specification fails to allocate storage, it shall return
11804 // a null pointer. Any other allocation function that fails to allocate
11805 // storage shall indicate failure only by throwing an exception [...]
11806 if (FD) {
11807 OverloadedOperatorKind Op = FD->getOverloadedOperator();
11808 if (Op == OO_New || Op == OO_Array_New) {
11809 const FunctionProtoType *Proto
11810 = FD->getType()->castAs<FunctionProtoType>();
11811 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11812 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11813 Diag(Loc: ReturnLoc, DiagID: diag::warn_operator_new_returns_null)
11814 << FD << getLangOpts().CPlusPlus11;
11815 }
11816 }
11817
11818 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11819 Diag(Loc: ReturnLoc, DiagID: diag::err_wasm_table_art) << 1;
11820 }
11821
11822 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11823 // here prevent the user from using a PPC MMA type as trailing return type.
11824 if (Context.getTargetInfo().getTriple().isPPC64())
11825 PPC().CheckPPCMMAType(Type: RetValExp->getType(), TypeLoc: ReturnLoc);
11826}
11827
11828void Sema::CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
11829 const Expr *RHS, BinaryOperatorKind Opcode) {
11830 if (!BinaryOperator::isEqualityOp(Opc: Opcode))
11831 return;
11832
11833 // Match and capture subexpressions such as "(float) X == 0.1".
11834 const FloatingLiteral *FPLiteral;
11835 const CastExpr *FPCast;
11836 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11837 FPLiteral = dyn_cast<FloatingLiteral>(Val: L->IgnoreParens());
11838 FPCast = dyn_cast<CastExpr>(Val: R->IgnoreParens());
11839 return FPLiteral && FPCast;
11840 };
11841
11842 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11843 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11844 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11845 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11846 TargetTy->isFloatingPoint()) {
11847 bool Lossy;
11848 llvm::APFloat TargetC = FPLiteral->getValue();
11849 TargetC.convert(ToSemantics: Context.getFloatTypeSemantics(T: QualType(SourceTy, 0)),
11850 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Lossy);
11851 if (Lossy) {
11852 // If the literal cannot be represented in the source type, then a
11853 // check for == is always false and check for != is always true.
11854 Diag(Loc, DiagID: diag::warn_float_compare_literal)
11855 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11856 << LHS->getSourceRange() << RHS->getSourceRange();
11857 return;
11858 }
11859 }
11860 }
11861
11862 // Match a more general floating-point equality comparison (-Wfloat-equal).
11863 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11864 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11865
11866 // Special case: check for x == x (which is OK).
11867 // Do not emit warnings for such cases.
11868 if (const auto *DRL = dyn_cast<DeclRefExpr>(Val: LeftExprSansParen))
11869 if (const auto *DRR = dyn_cast<DeclRefExpr>(Val: RightExprSansParen))
11870 if (DRL->getDecl() == DRR->getDecl())
11871 return;
11872
11873 // Special case: check for comparisons against literals that can be exactly
11874 // represented by APFloat. In such cases, do not emit a warning. This
11875 // is a heuristic: often comparison against such literals are used to
11876 // detect if a value in a variable has not changed. This clearly can
11877 // lead to false negatives.
11878 if (const auto *FLL = dyn_cast<FloatingLiteral>(Val: LeftExprSansParen)) {
11879 if (FLL->isExact())
11880 return;
11881 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(Val: RightExprSansParen))
11882 if (FLR->isExact())
11883 return;
11884
11885 // Check for comparisons with builtin types.
11886 if (const auto *CL = dyn_cast<CallExpr>(Val: LeftExprSansParen);
11887 CL && CL->getBuiltinCallee())
11888 return;
11889
11890 if (const auto *CR = dyn_cast<CallExpr>(Val: RightExprSansParen);
11891 CR && CR->getBuiltinCallee())
11892 return;
11893
11894 // Emit the diagnostic.
11895 Diag(Loc, DiagID: diag::warn_floatingpoint_eq)
11896 << LHS->getSourceRange() << RHS->getSourceRange();
11897}
11898
11899//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11900//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11901
11902namespace {
11903
11904/// Structure recording the 'active' range of an integer-valued
11905/// expression.
11906struct IntRange {
11907 /// The number of bits active in the int. Note that this includes exactly one
11908 /// sign bit if !NonNegative.
11909 unsigned Width;
11910
11911 /// True if the int is known not to have negative values. If so, all leading
11912 /// bits before Width are known zero, otherwise they are known to be the
11913 /// same as the MSB within Width.
11914 bool NonNegative;
11915
11916 IntRange(unsigned Width, bool NonNegative)
11917 : Width(Width), NonNegative(NonNegative) {}
11918
11919 /// Number of bits excluding the sign bit.
11920 unsigned valueBits() const {
11921 return NonNegative ? Width : Width - 1;
11922 }
11923
11924 /// Returns the range of the bool type.
11925 static IntRange forBoolType() {
11926 return IntRange(1, true);
11927 }
11928
11929 /// Returns the range of an opaque value of the given integral type.
11930 static IntRange forValueOfType(ASTContext &C, QualType T) {
11931 return forValueOfCanonicalType(C,
11932 T: T->getCanonicalTypeInternal().getTypePtr());
11933 }
11934
11935 /// Returns the range of an opaque value of a canonical integral type.
11936 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11937 assert(T->isCanonicalUnqualified());
11938
11939 if (const auto *VT = dyn_cast<VectorType>(Val: T))
11940 T = VT->getElementType().getTypePtr();
11941 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
11942 T = MT->getElementType().getTypePtr();
11943 if (const auto *CT = dyn_cast<ComplexType>(Val: T))
11944 T = CT->getElementType().getTypePtr();
11945 if (const auto *AT = dyn_cast<AtomicType>(Val: T))
11946 T = AT->getValueType().getTypePtr();
11947 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11948 T = OBT->getUnderlyingType().getTypePtr();
11949
11950 if (!C.getLangOpts().CPlusPlus) {
11951 // For enum types in C code, use the underlying datatype.
11952 if (const auto *ED = T->getAsEnumDecl())
11953 T = ED->getIntegerType().getDesugaredType(Context: C).getTypePtr();
11954 } else if (auto *Enum = T->getAsEnumDecl()) {
11955 // For enum types in C++, use the known bit width of the enumerators.
11956 // In C++11, enums can have a fixed underlying type. Use this type to
11957 // compute the range.
11958 if (Enum->isFixed()) {
11959 return IntRange(C.getIntWidth(T: QualType(T, 0)),
11960 !Enum->getIntegerType()->isSignedIntegerType());
11961 }
11962
11963 unsigned NumPositive = Enum->getNumPositiveBits();
11964 unsigned NumNegative = Enum->getNumNegativeBits();
11965
11966 if (NumNegative == 0)
11967 return IntRange(NumPositive, true/*NonNegative*/);
11968 else
11969 return IntRange(std::max(a: NumPositive + 1, b: NumNegative),
11970 false/*NonNegative*/);
11971 }
11972
11973 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11974 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11975
11976 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11977 assert(BT->isInteger());
11978
11979 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11980 }
11981
11982 /// Returns the "target" range of a canonical integral type, i.e.
11983 /// the range of values expressible in the type.
11984 ///
11985 /// This matches forValueOfCanonicalType except that enums have the
11986 /// full range of their type, not the range of their enumerators.
11987 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11988 assert(T->isCanonicalUnqualified());
11989
11990 if (const VectorType *VT = dyn_cast<VectorType>(Val: T))
11991 T = VT->getElementType().getTypePtr();
11992 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
11993 T = MT->getElementType().getTypePtr();
11994 if (const ComplexType *CT = dyn_cast<ComplexType>(Val: T))
11995 T = CT->getElementType().getTypePtr();
11996 if (const AtomicType *AT = dyn_cast<AtomicType>(Val: T))
11997 T = AT->getValueType().getTypePtr();
11998 if (const auto *ED = T->getAsEnumDecl())
11999 T = C.getCanonicalType(T: ED->getIntegerType()).getTypePtr();
12000 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
12001 T = OBT->getUnderlyingType().getTypePtr();
12002
12003 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
12004 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
12005
12006 const BuiltinType *BT = cast<BuiltinType>(Val: T);
12007 assert(BT->isInteger());
12008
12009 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
12010 }
12011
12012 /// Returns the supremum of two ranges: i.e. their conservative merge.
12013 static IntRange join(IntRange L, IntRange R) {
12014 bool Unsigned = L.NonNegative && R.NonNegative;
12015 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
12016 L.NonNegative && R.NonNegative);
12017 }
12018
12019 /// Return the range of a bitwise-AND of the two ranges.
12020 static IntRange bit_and(IntRange L, IntRange R) {
12021 unsigned Bits = std::max(a: L.Width, b: R.Width);
12022 bool NonNegative = false;
12023 if (L.NonNegative) {
12024 Bits = std::min(a: Bits, b: L.Width);
12025 NonNegative = true;
12026 }
12027 if (R.NonNegative) {
12028 Bits = std::min(a: Bits, b: R.Width);
12029 NonNegative = true;
12030 }
12031 return IntRange(Bits, NonNegative);
12032 }
12033
12034 /// Return the range of a sum of the two ranges.
12035 static IntRange sum(IntRange L, IntRange R) {
12036 bool Unsigned = L.NonNegative && R.NonNegative;
12037 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + 1 + !Unsigned,
12038 Unsigned);
12039 }
12040
12041 /// Return the range of a difference of the two ranges.
12042 static IntRange difference(IntRange L, IntRange R) {
12043 // We need a 1-bit-wider range if:
12044 // 1) LHS can be negative: least value can be reduced.
12045 // 2) RHS can be negative: greatest value can be increased.
12046 bool CanWiden = !L.NonNegative || !R.NonNegative;
12047 bool Unsigned = L.NonNegative && R.Width == 0;
12048 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + CanWiden +
12049 !Unsigned,
12050 Unsigned);
12051 }
12052
12053 /// Return the range of a product of the two ranges.
12054 static IntRange product(IntRange L, IntRange R) {
12055 // If both LHS and RHS can be negative, we can form
12056 // -2^L * -2^R = 2^(L + R)
12057 // which requires L + R + 1 value bits to represent.
12058 bool CanWiden = !L.NonNegative && !R.NonNegative;
12059 bool Unsigned = L.NonNegative && R.NonNegative;
12060 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
12061 Unsigned);
12062 }
12063
12064 /// Return the range of a remainder operation between the two ranges.
12065 static IntRange rem(IntRange L, IntRange R) {
12066 // The result of a remainder can't be larger than the result of
12067 // either side. The sign of the result is the sign of the LHS.
12068 bool Unsigned = L.NonNegative;
12069 return IntRange(std::min(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
12070 Unsigned);
12071 }
12072};
12073
12074} // namespace
12075
12076static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
12077 if (value.isSigned() && value.isNegative())
12078 return IntRange(value.getSignificantBits(), false);
12079
12080 if (value.getBitWidth() > MaxWidth)
12081 value = value.trunc(width: MaxWidth);
12082
12083 // isNonNegative() just checks the sign bit without considering
12084 // signedness.
12085 return IntRange(value.getActiveBits(), true);
12086}
12087
12088static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
12089 if (result.isInt())
12090 return GetValueRange(value&: result.getInt(), MaxWidth);
12091
12092 if (result.isVector()) {
12093 IntRange R = GetValueRange(result&: result.getVectorElt(I: 0), Ty, MaxWidth);
12094 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
12095 IntRange El = GetValueRange(result&: result.getVectorElt(I: i), Ty, MaxWidth);
12096 R = IntRange::join(L: R, R: El);
12097 }
12098 return R;
12099 }
12100
12101 if (result.isComplexInt()) {
12102 IntRange R = GetValueRange(value&: result.getComplexIntReal(), MaxWidth);
12103 IntRange I = GetValueRange(value&: result.getComplexIntImag(), MaxWidth);
12104 return IntRange::join(L: R, R: I);
12105 }
12106
12107 // This can happen with lossless casts to intptr_t of "based" lvalues.
12108 // Assume it might use arbitrary bits.
12109 // FIXME: The only reason we need to pass the type in here is to get
12110 // the sign right on this one case. It would be nice if APValue
12111 // preserved this.
12112 assert(result.isLValue() || result.isAddrLabelDiff());
12113 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
12114}
12115
12116static QualType GetExprType(const Expr *E) {
12117 QualType Ty = E->getType();
12118 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
12119 Ty = AtomicRHS->getValueType();
12120 return Ty;
12121}
12122
12123/// Attempts to estimate an approximate range for the given integer expression.
12124/// Returns a range if successful, otherwise it returns \c std::nullopt if a
12125/// reliable estimation cannot be determined.
12126///
12127/// \param MaxWidth The width to which the value will be truncated.
12128/// \param InConstantContext If \c true, interpret the expression within a
12129/// constant context.
12130/// \param Approximate If \c true, provide a likely range of values by assuming
12131/// that arithmetic on narrower types remains within those types.
12132/// If \c false, return a range that includes all possible values
12133/// resulting from the expression.
12134/// \returns A range of values that the expression might take, or
12135/// std::nullopt if a reliable estimation cannot be determined.
12136static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12137 unsigned MaxWidth,
12138 bool InConstantContext,
12139 bool Approximate) {
12140 E = E->IgnoreParens();
12141
12142 // Try a full evaluation first.
12143 Expr::EvalResult result;
12144 if (E->EvaluateAsRValue(Result&: result, Ctx: C, InConstantContext))
12145 return GetValueRange(result&: result.Val, Ty: GetExprType(E), MaxWidth);
12146
12147 // I think we only want to look through implicit casts here; if the
12148 // user has an explicit widening cast, we should treat the value as
12149 // being of the new, wider type.
12150 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Val: E)) {
12151 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
12152 return TryGetExprRange(C, E: CE->getSubExpr(), MaxWidth, InConstantContext,
12153 Approximate);
12154
12155 IntRange OutputTypeRange = IntRange::forValueOfType(C, T: GetExprType(E: CE));
12156
12157 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
12158 CE->getCastKind() == CK_BooleanToSignedIntegral;
12159
12160 // Assume that non-integer casts can span the full range of the type.
12161 if (!isIntegerCast)
12162 return OutputTypeRange;
12163
12164 std::optional<IntRange> SubRange = TryGetExprRange(
12165 C, E: CE->getSubExpr(), MaxWidth: std::min(a: MaxWidth, b: OutputTypeRange.Width),
12166 InConstantContext, Approximate);
12167 if (!SubRange)
12168 return std::nullopt;
12169
12170 // Bail out if the subexpr's range is as wide as the cast type.
12171 if (SubRange->Width >= OutputTypeRange.Width)
12172 return OutputTypeRange;
12173
12174 // Otherwise, we take the smaller width, and we're non-negative if
12175 // either the output type or the subexpr is.
12176 return IntRange(SubRange->Width,
12177 SubRange->NonNegative || OutputTypeRange.NonNegative);
12178 }
12179
12180 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
12181 // If we can fold the condition, just take that operand.
12182 bool CondResult;
12183 if (CO->getCond()->EvaluateAsBooleanCondition(Result&: CondResult, Ctx: C))
12184 return TryGetExprRange(
12185 C, E: CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
12186 InConstantContext, Approximate);
12187
12188 // Otherwise, conservatively merge.
12189 // TryGetExprRange requires an integer expression, but a throw expression
12190 // results in a void type.
12191 Expr *TrueExpr = CO->getTrueExpr();
12192 if (TrueExpr->getType()->isVoidType())
12193 return std::nullopt;
12194
12195 std::optional<IntRange> L =
12196 TryGetExprRange(C, E: TrueExpr, MaxWidth, InConstantContext, Approximate);
12197 if (!L)
12198 return std::nullopt;
12199
12200 Expr *FalseExpr = CO->getFalseExpr();
12201 if (FalseExpr->getType()->isVoidType())
12202 return std::nullopt;
12203
12204 std::optional<IntRange> R =
12205 TryGetExprRange(C, E: FalseExpr, MaxWidth, InConstantContext, Approximate);
12206 if (!R)
12207 return std::nullopt;
12208
12209 return IntRange::join(L: *L, R: *R);
12210 }
12211
12212 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
12213 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
12214
12215 switch (BO->getOpcode()) {
12216 case BO_Cmp:
12217 llvm_unreachable("builtin <=> should have class type");
12218
12219 // Boolean-valued operations are single-bit and positive.
12220 case BO_LAnd:
12221 case BO_LOr:
12222 case BO_LT:
12223 case BO_GT:
12224 case BO_LE:
12225 case BO_GE:
12226 case BO_EQ:
12227 case BO_NE:
12228 return IntRange::forBoolType();
12229
12230 // The type of the assignments is the type of the LHS, so the RHS
12231 // is not necessarily the same type.
12232 case BO_MulAssign:
12233 case BO_DivAssign:
12234 case BO_RemAssign:
12235 case BO_AddAssign:
12236 case BO_SubAssign:
12237 case BO_XorAssign:
12238 case BO_OrAssign:
12239 // TODO: bitfields?
12240 return IntRange::forValueOfType(C, T: GetExprType(E));
12241
12242 // Simple assignments just pass through the RHS, which will have
12243 // been coerced to the LHS type.
12244 case BO_Assign:
12245 // TODO: bitfields?
12246 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
12247 Approximate);
12248
12249 // Operations with opaque sources are black-listed.
12250 case BO_PtrMemD:
12251 case BO_PtrMemI:
12252 return IntRange::forValueOfType(C, T: GetExprType(E));
12253
12254 // Bitwise-and uses the *infinum* of the two source ranges.
12255 case BO_And:
12256 case BO_AndAssign:
12257 Combine = IntRange::bit_and;
12258 break;
12259
12260 // Left shift gets black-listed based on a judgement call.
12261 case BO_Shl:
12262 // ...except that we want to treat '1 << (blah)' as logically
12263 // positive. It's an important idiom.
12264 if (IntegerLiteral *I
12265 = dyn_cast<IntegerLiteral>(Val: BO->getLHS()->IgnoreParenCasts())) {
12266 if (I->getValue() == 1) {
12267 IntRange R = IntRange::forValueOfType(C, T: GetExprType(E));
12268 return IntRange(R.Width, /*NonNegative*/ true);
12269 }
12270 }
12271 [[fallthrough]];
12272
12273 case BO_ShlAssign:
12274 return IntRange::forValueOfType(C, T: GetExprType(E));
12275
12276 // Right shift by a constant can narrow its left argument.
12277 case BO_Shr:
12278 case BO_ShrAssign: {
12279 std::optional<IntRange> L = TryGetExprRange(
12280 C, E: BO->getLHS(), MaxWidth, InConstantContext, Approximate);
12281 if (!L)
12282 return std::nullopt;
12283
12284 // If the shift amount is a positive constant, drop the width by
12285 // that much.
12286 if (std::optional<llvm::APSInt> shift =
12287 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
12288 if (shift->isNonNegative()) {
12289 if (shift->uge(RHS: L->Width))
12290 L->Width = (L->NonNegative ? 0 : 1);
12291 else
12292 L->Width -= shift->getZExtValue();
12293 }
12294 }
12295
12296 return L;
12297 }
12298
12299 // Comma acts as its right operand.
12300 case BO_Comma:
12301 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
12302 Approximate);
12303
12304 case BO_Add:
12305 if (!Approximate)
12306 Combine = IntRange::sum;
12307 break;
12308
12309 case BO_Sub:
12310 if (BO->getLHS()->getType()->isPointerType())
12311 return IntRange::forValueOfType(C, T: GetExprType(E));
12312 if (!Approximate)
12313 Combine = IntRange::difference;
12314 break;
12315
12316 case BO_Mul:
12317 if (!Approximate)
12318 Combine = IntRange::product;
12319 break;
12320
12321 // The width of a division result is mostly determined by the size
12322 // of the LHS.
12323 case BO_Div: {
12324 // Don't 'pre-truncate' the operands.
12325 unsigned opWidth = C.getIntWidth(T: GetExprType(E));
12326 std::optional<IntRange> L = TryGetExprRange(
12327 C, E: BO->getLHS(), MaxWidth: opWidth, InConstantContext, Approximate);
12328 if (!L)
12329 return std::nullopt;
12330
12331 // If the divisor is constant, use that.
12332 if (std::optional<llvm::APSInt> divisor =
12333 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
12334 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12335 if (log2 >= L->Width)
12336 L->Width = (L->NonNegative ? 0 : 1);
12337 else
12338 L->Width = std::min(a: L->Width - log2, b: MaxWidth);
12339 return L;
12340 }
12341
12342 // Otherwise, just use the LHS's width.
12343 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12344 // could be -1.
12345 std::optional<IntRange> R = TryGetExprRange(
12346 C, E: BO->getRHS(), MaxWidth: opWidth, InConstantContext, Approximate);
12347 if (!R)
12348 return std::nullopt;
12349
12350 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12351 }
12352
12353 case BO_Rem:
12354 Combine = IntRange::rem;
12355 break;
12356
12357 // The default behavior is okay for these.
12358 case BO_Xor:
12359 case BO_Or:
12360 break;
12361 }
12362
12363 // Combine the two ranges, but limit the result to the type in which we
12364 // performed the computation.
12365 QualType T = GetExprType(E);
12366 unsigned opWidth = C.getIntWidth(T);
12367 std::optional<IntRange> L = TryGetExprRange(C, E: BO->getLHS(), MaxWidth: opWidth,
12368 InConstantContext, Approximate);
12369 if (!L)
12370 return std::nullopt;
12371
12372 std::optional<IntRange> R = TryGetExprRange(C, E: BO->getRHS(), MaxWidth: opWidth,
12373 InConstantContext, Approximate);
12374 if (!R)
12375 return std::nullopt;
12376
12377 IntRange C = Combine(*L, *R);
12378 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12379 C.Width = std::min(a: C.Width, b: MaxWidth);
12380 return C;
12381 }
12382
12383 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
12384 switch (UO->getOpcode()) {
12385 // Boolean-valued operations are white-listed.
12386 case UO_LNot:
12387 return IntRange::forBoolType();
12388
12389 // Operations with opaque sources are black-listed.
12390 case UO_Deref:
12391 case UO_AddrOf: // should be impossible
12392 return IntRange::forValueOfType(C, T: GetExprType(E));
12393
12394 case UO_Minus: {
12395 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12396 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12397 Approximate);
12398 }
12399
12400 std::optional<IntRange> SubRange = TryGetExprRange(
12401 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12402
12403 if (!SubRange)
12404 return std::nullopt;
12405
12406 // If the range was previously non-negative, we need an extra bit for the
12407 // sign bit. Otherwise, we need an extra bit because the negation of the
12408 // most-negative value is one bit wider than that value.
12409 return IntRange(std::min(a: SubRange->Width + 1, b: MaxWidth), false);
12410 }
12411
12412 case UO_Not: {
12413 if (GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12414 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12415 Approximate);
12416 }
12417
12418 std::optional<IntRange> SubRange = TryGetExprRange(
12419 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12420
12421 if (!SubRange)
12422 return std::nullopt;
12423
12424 // The width increments by 1 if the sub-expression cannot be negative
12425 // since it now can be.
12426 return IntRange(
12427 std::min(a: SubRange->Width + (int)SubRange->NonNegative, b: MaxWidth),
12428 false);
12429 }
12430
12431 default:
12432 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12433 Approximate);
12434 }
12435 }
12436
12437 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
12438 // The source expression is null for the OpaqueValueExpr that stands in for
12439 // a non-type template argument of pointer or reference type; fall back to
12440 // the range of the type in that case.
12441 if (const Expr *SourceExpr = OVE->getSourceExpr())
12442 return TryGetExprRange(C, E: SourceExpr, MaxWidth, InConstantContext,
12443 Approximate);
12444 }
12445
12446 if (const auto *BitField = E->getSourceBitField())
12447 return IntRange(BitField->getBitWidthValue(),
12448 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12449
12450 if (GetExprType(E)->isVoidType())
12451 return std::nullopt;
12452
12453 return IntRange::forValueOfType(C, T: GetExprType(E));
12454}
12455
12456static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12457 bool InConstantContext,
12458 bool Approximate) {
12459 return TryGetExprRange(C, E, MaxWidth: C.getIntWidth(T: GetExprType(E)), InConstantContext,
12460 Approximate);
12461}
12462
12463/// Checks whether the given value, which currently has the given
12464/// source semantics, has the same value when coerced through the
12465/// target semantics.
12466static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12467 const llvm::fltSemantics &Src,
12468 const llvm::fltSemantics &Tgt) {
12469 llvm::APFloat truncated = value;
12470
12471 bool ignored;
12472 truncated.convert(ToSemantics: Src, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
12473 truncated.convert(ToSemantics: Tgt, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
12474
12475 return truncated.bitwiseIsEqual(RHS: value);
12476}
12477
12478/// Checks whether the given value, which currently has the given
12479/// source semantics, has the same value when coerced through the
12480/// target semantics.
12481///
12482/// The value might be a vector of floats (or a complex number).
12483static bool IsSameFloatAfterCast(const APValue &value,
12484 const llvm::fltSemantics &Src,
12485 const llvm::fltSemantics &Tgt) {
12486 if (value.isFloat())
12487 return IsSameFloatAfterCast(value: value.getFloat(), Src, Tgt);
12488
12489 if (value.isVector()) {
12490 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12491 if (!IsSameFloatAfterCast(value: value.getVectorElt(I: i), Src, Tgt))
12492 return false;
12493 return true;
12494 }
12495
12496 if (value.isMatrix()) {
12497 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12498 if (!IsSameFloatAfterCast(value: value.getMatrixElt(Idx: i), Src, Tgt))
12499 return false;
12500 return true;
12501 }
12502
12503 assert(value.isComplexFloat());
12504 return (IsSameFloatAfterCast(value: value.getComplexFloatReal(), Src, Tgt) &&
12505 IsSameFloatAfterCast(value: value.getComplexFloatImag(), Src, Tgt));
12506}
12507
12508static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12509 bool IsListInit = false);
12510
12511static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12512 // Suppress cases where we are comparing against an enum constant.
12513 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()))
12514 if (isa<EnumConstantDecl>(Val: DR->getDecl()))
12515 return true;
12516
12517 // Suppress cases where the value is expanded from a macro, unless that macro
12518 // is how a language represents a boolean literal. This is the case in both C
12519 // and Objective-C.
12520 SourceLocation BeginLoc = E->getBeginLoc();
12521 if (BeginLoc.isMacroID()) {
12522 StringRef MacroName = Lexer::getImmediateMacroName(
12523 Loc: BeginLoc, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
12524 return MacroName != "YES" && MacroName != "NO" &&
12525 MacroName != "true" && MacroName != "false";
12526 }
12527
12528 return false;
12529}
12530
12531static bool isKnownToHaveUnsignedValue(const Expr *E) {
12532 return E->getType()->isIntegerType() &&
12533 (!E->getType()->isSignedIntegerType() ||
12534 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
12535}
12536
12537namespace {
12538/// The promoted range of values of a type. In general this has the
12539/// following structure:
12540///
12541/// |-----------| . . . |-----------|
12542/// ^ ^ ^ ^
12543/// Min HoleMin HoleMax Max
12544///
12545/// ... where there is only a hole if a signed type is promoted to unsigned
12546/// (in which case Min and Max are the smallest and largest representable
12547/// values).
12548struct PromotedRange {
12549 // Min, or HoleMax if there is a hole.
12550 llvm::APSInt PromotedMin;
12551 // Max, or HoleMin if there is a hole.
12552 llvm::APSInt PromotedMax;
12553
12554 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12555 if (R.Width == 0)
12556 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12557 else if (R.Width >= BitWidth && !Unsigned) {
12558 // Promotion made the type *narrower*. This happens when promoting
12559 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12560 // Treat all values of 'signed int' as being in range for now.
12561 PromotedMin = llvm::APSInt::getMinValue(numBits: BitWidth, Unsigned);
12562 PromotedMax = llvm::APSInt::getMaxValue(numBits: BitWidth, Unsigned);
12563 } else {
12564 PromotedMin = llvm::APSInt::getMinValue(numBits: R.Width, Unsigned: R.NonNegative)
12565 .extOrTrunc(width: BitWidth);
12566 PromotedMin.setIsUnsigned(Unsigned);
12567
12568 PromotedMax = llvm::APSInt::getMaxValue(numBits: R.Width, Unsigned: R.NonNegative)
12569 .extOrTrunc(width: BitWidth);
12570 PromotedMax.setIsUnsigned(Unsigned);
12571 }
12572 }
12573
12574 // Determine whether this range is contiguous (has no hole).
12575 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12576
12577 // Where a constant value is within the range.
12578 enum ComparisonResult {
12579 LT = 0x1,
12580 LE = 0x2,
12581 GT = 0x4,
12582 GE = 0x8,
12583 EQ = 0x10,
12584 NE = 0x20,
12585 InRangeFlag = 0x40,
12586
12587 Less = LE | LT | NE,
12588 Min = LE | InRangeFlag,
12589 InRange = InRangeFlag,
12590 Max = GE | InRangeFlag,
12591 Greater = GE | GT | NE,
12592
12593 OnlyValue = LE | GE | EQ | InRangeFlag,
12594 InHole = NE
12595 };
12596
12597 ComparisonResult compare(const llvm::APSInt &Value) const {
12598 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12599 Value.isUnsigned() == PromotedMin.isUnsigned());
12600 if (!isContiguous()) {
12601 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12602 if (Value.isMinValue()) return Min;
12603 if (Value.isMaxValue()) return Max;
12604 if (Value >= PromotedMin) return InRange;
12605 if (Value <= PromotedMax) return InRange;
12606 return InHole;
12607 }
12608
12609 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMin)) {
12610 case -1: return Less;
12611 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12612 case 1:
12613 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMax)) {
12614 case -1: return InRange;
12615 case 0: return Max;
12616 case 1: return Greater;
12617 }
12618 }
12619
12620 llvm_unreachable("impossible compare result");
12621 }
12622
12623 static std::optional<StringRef>
12624 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12625 if (Op == BO_Cmp) {
12626 ComparisonResult LTFlag = LT, GTFlag = GT;
12627 if (ConstantOnRHS) std::swap(a&: LTFlag, b&: GTFlag);
12628
12629 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12630 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12631 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12632 return std::nullopt;
12633 }
12634
12635 ComparisonResult TrueFlag, FalseFlag;
12636 if (Op == BO_EQ) {
12637 TrueFlag = EQ;
12638 FalseFlag = NE;
12639 } else if (Op == BO_NE) {
12640 TrueFlag = NE;
12641 FalseFlag = EQ;
12642 } else {
12643 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12644 TrueFlag = LT;
12645 FalseFlag = GE;
12646 } else {
12647 TrueFlag = GT;
12648 FalseFlag = LE;
12649 }
12650 if (Op == BO_GE || Op == BO_LE)
12651 std::swap(a&: TrueFlag, b&: FalseFlag);
12652 }
12653 if (R & TrueFlag)
12654 return StringRef("true");
12655 if (R & FalseFlag)
12656 return StringRef("false");
12657 return std::nullopt;
12658 }
12659};
12660}
12661
12662static bool HasEnumType(const Expr *E) {
12663 // Strip off implicit integral promotions.
12664 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
12665 if (ICE->getCastKind() != CK_IntegralCast &&
12666 ICE->getCastKind() != CK_NoOp)
12667 break;
12668 E = ICE->getSubExpr();
12669 }
12670
12671 return E->getType()->isEnumeralType();
12672}
12673
12674static int classifyConstantValue(Expr *Constant) {
12675 // The values of this enumeration are used in the diagnostics
12676 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12677 enum ConstantValueKind {
12678 Miscellaneous = 0,
12679 LiteralTrue,
12680 LiteralFalse
12681 };
12682 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Val: Constant))
12683 return BL->getValue() ? ConstantValueKind::LiteralTrue
12684 : ConstantValueKind::LiteralFalse;
12685 return ConstantValueKind::Miscellaneous;
12686}
12687
12688static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12689 Expr *Constant, Expr *Other,
12690 const llvm::APSInt &Value,
12691 bool RhsConstant) {
12692 if (S.inTemplateInstantiation())
12693 return false;
12694
12695 Expr *OriginalOther = Other;
12696
12697 Constant = Constant->IgnoreParenImpCasts();
12698 Other = Other->IgnoreParenImpCasts();
12699
12700 // Suppress warnings on tautological comparisons between values of the same
12701 // enumeration type. There are only two ways we could warn on this:
12702 // - If the constant is outside the range of representable values of
12703 // the enumeration. In such a case, we should warn about the cast
12704 // to enumeration type, not about the comparison.
12705 // - If the constant is the maximum / minimum in-range value. For an
12706 // enumeratin type, such comparisons can be meaningful and useful.
12707 if (Constant->getType()->isEnumeralType() &&
12708 S.Context.hasSameUnqualifiedType(T1: Constant->getType(), T2: Other->getType()))
12709 return false;
12710
12711 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12712 C&: S.Context, E: Other, InConstantContext: S.isConstantEvaluatedContext(), /*Approximate=*/false);
12713 if (!OtherValueRange)
12714 return false;
12715
12716 QualType OtherT = Other->getType();
12717 if (const auto *AT = OtherT->getAs<AtomicType>())
12718 OtherT = AT->getValueType();
12719 IntRange OtherTypeRange = IntRange::forValueOfType(C&: S.Context, T: OtherT);
12720
12721 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12722 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12723 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12724 S.ObjC().NSAPIObj->isObjCBOOLType(T: OtherT) &&
12725 OtherT->isSpecificBuiltinType(K: BuiltinType::SChar);
12726
12727 // Whether we're treating Other as being a bool because of the form of
12728 // expression despite it having another type (typically 'int' in C).
12729 bool OtherIsBooleanDespiteType =
12730 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12731 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12732 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12733
12734 // Check if all values in the range of possible values of this expression
12735 // lead to the same comparison outcome.
12736 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12737 Value.isUnsigned());
12738 auto Cmp = OtherPromotedValueRange.compare(Value);
12739 auto Result = PromotedRange::constantValue(Op: E->getOpcode(), R: Cmp, ConstantOnRHS: RhsConstant);
12740 if (!Result)
12741 return false;
12742
12743 // Also consider the range determined by the type alone. This allows us to
12744 // classify the warning under the proper diagnostic group.
12745 bool TautologicalTypeCompare = false;
12746 {
12747 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12748 Value.isUnsigned());
12749 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12750 if (auto TypeResult = PromotedRange::constantValue(Op: E->getOpcode(), R: TypeCmp,
12751 ConstantOnRHS: RhsConstant)) {
12752 TautologicalTypeCompare = true;
12753 Cmp = TypeCmp;
12754 Result = TypeResult;
12755 }
12756 }
12757
12758 // Don't warn if the non-constant operand actually always evaluates to the
12759 // same value.
12760 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12761 return false;
12762
12763 // Suppress the diagnostic for an in-range comparison if the constant comes
12764 // from a macro or enumerator. We don't want to diagnose
12765 //
12766 // some_long_value <= INT_MAX
12767 //
12768 // when sizeof(int) == sizeof(long).
12769 bool InRange = Cmp & PromotedRange::InRangeFlag;
12770 if (InRange && IsEnumConstOrFromMacro(S, E: Constant))
12771 return false;
12772
12773 // A comparison of an unsigned bit-field against 0 is really a type problem,
12774 // even though at the type level the bit-field might promote to 'signed int'.
12775 if (Other->refersToBitField() && InRange && Value == 0 &&
12776 Other->getType()->isUnsignedIntegerOrEnumerationType())
12777 TautologicalTypeCompare = true;
12778
12779 // If this is a comparison to an enum constant, include that
12780 // constant in the diagnostic.
12781 const EnumConstantDecl *ED = nullptr;
12782 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: Constant))
12783 ED = dyn_cast<EnumConstantDecl>(Val: DR->getDecl());
12784
12785 // Should be enough for uint128 (39 decimal digits)
12786 SmallString<64> PrettySourceValue;
12787 llvm::raw_svector_ostream OS(PrettySourceValue);
12788 if (ED) {
12789 OS << '\'' << *ED << "' (" << Value << ")";
12790 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12791 Val: Constant->IgnoreParenImpCasts())) {
12792 OS << (BL->getValue() ? "YES" : "NO");
12793 } else {
12794 OS << Value;
12795 }
12796
12797 if (!TautologicalTypeCompare) {
12798 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_tautological_compare_value_range)
12799 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12800 << E->getOpcodeStr() << OS.str() << *Result
12801 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12802 return true;
12803 }
12804
12805 if (IsObjCSignedCharBool) {
12806 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12807 PD: S.PDiag(DiagID: diag::warn_tautological_compare_objc_bool)
12808 << OS.str() << *Result);
12809 return true;
12810 }
12811
12812 // FIXME: We use a somewhat different formatting for the in-range cases and
12813 // cases involving boolean values for historical reasons. We should pick a
12814 // consistent way of presenting these diagnostics.
12815 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12816
12817 S.DiagRuntimeBehavior(
12818 Loc: E->getOperatorLoc(), Statement: E,
12819 PD: S.PDiag(DiagID: !InRange ? diag::warn_out_of_range_compare
12820 : diag::warn_tautological_bool_compare)
12821 << OS.str() << classifyConstantValue(Constant) << OtherT
12822 << OtherIsBooleanDespiteType << *Result
12823 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12824 } else {
12825 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12826 unsigned Diag =
12827 (isKnownToHaveUnsignedValue(E: OriginalOther) && Value == 0)
12828 ? (HasEnumType(E: OriginalOther)
12829 ? diag::warn_unsigned_enum_always_true_comparison
12830 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12831 : diag::warn_unsigned_always_true_comparison)
12832 : diag::warn_tautological_constant_compare;
12833
12834 S.Diag(Loc: E->getOperatorLoc(), DiagID: Diag)
12835 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12836 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12837 }
12838
12839 return true;
12840}
12841
12842/// Analyze the operands of the given comparison. Implements the
12843/// fallback case from AnalyzeComparison.
12844static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12845 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12846 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12847}
12848
12849/// Implements -Wsign-compare.
12850///
12851/// \param E the binary operator to check for warnings
12852static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12853 // The type the comparison is being performed in.
12854 QualType T = E->getLHS()->getType();
12855
12856 // Only analyze comparison operators where both sides have been converted to
12857 // the same type.
12858 if (!S.Context.hasSameUnqualifiedType(T1: T, T2: E->getRHS()->getType()))
12859 return AnalyzeImpConvsInComparison(S, E);
12860
12861 // Don't analyze value-dependent comparisons directly.
12862 if (E->isValueDependent())
12863 return AnalyzeImpConvsInComparison(S, E);
12864
12865 Expr *LHS = E->getLHS();
12866 Expr *RHS = E->getRHS();
12867
12868 if (T->isIntegralType(Ctx: S.Context)) {
12869 std::optional<llvm::APSInt> RHSValue =
12870 RHS->getIntegerConstantExpr(Ctx: S.Context);
12871 std::optional<llvm::APSInt> LHSValue =
12872 LHS->getIntegerConstantExpr(Ctx: S.Context);
12873
12874 // We don't care about expressions whose result is a constant.
12875 if (RHSValue && LHSValue)
12876 return AnalyzeImpConvsInComparison(S, E);
12877
12878 // We only care about expressions where just one side is literal
12879 if ((bool)RHSValue ^ (bool)LHSValue) {
12880 // Is the constant on the RHS or LHS?
12881 const bool RhsConstant = (bool)RHSValue;
12882 Expr *Const = RhsConstant ? RHS : LHS;
12883 Expr *Other = RhsConstant ? LHS : RHS;
12884 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12885
12886 // Check whether an integer constant comparison results in a value
12887 // of 'true' or 'false'.
12888 if (CheckTautologicalComparison(S, E, Constant: Const, Other, Value, RhsConstant))
12889 return AnalyzeImpConvsInComparison(S, E);
12890 }
12891 }
12892
12893 if (!T->hasUnsignedIntegerRepresentation()) {
12894 // We don't do anything special if this isn't an unsigned integral
12895 // comparison: we're only interested in integral comparisons, and
12896 // signed comparisons only happen in cases we don't care to warn about.
12897 return AnalyzeImpConvsInComparison(S, E);
12898 }
12899
12900 LHS = LHS->IgnoreParenImpCasts();
12901 RHS = RHS->IgnoreParenImpCasts();
12902
12903 if (!S.getLangOpts().CPlusPlus) {
12904 // Avoid warning about comparison of integers with different signs when
12905 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12906 // the type of `E`.
12907 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: LHS->getType()))
12908 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12909 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: RHS->getType()))
12910 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12911 }
12912
12913 // Check to see if one of the (unmodified) operands is of different
12914 // signedness.
12915 Expr *signedOperand, *unsignedOperand;
12916 if (LHS->getType()->hasSignedIntegerRepresentation()) {
12917 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12918 "unsigned comparison between two signed integer expressions?");
12919 signedOperand = LHS;
12920 unsignedOperand = RHS;
12921 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12922 signedOperand = RHS;
12923 unsignedOperand = LHS;
12924 } else {
12925 return AnalyzeImpConvsInComparison(S, E);
12926 }
12927
12928 // Otherwise, calculate the effective range of the signed operand.
12929 std::optional<IntRange> signedRange =
12930 TryGetExprRange(C&: S.Context, E: signedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12931 /*Approximate=*/true);
12932 if (!signedRange)
12933 return;
12934
12935 // Go ahead and analyze implicit conversions in the operands. Note
12936 // that we skip the implicit conversions on both sides.
12937 AnalyzeImplicitConversions(S, E: LHS, CC: E->getOperatorLoc());
12938 AnalyzeImplicitConversions(S, E: RHS, CC: E->getOperatorLoc());
12939
12940 // If the signed range is non-negative, -Wsign-compare won't fire.
12941 if (signedRange->NonNegative)
12942 return;
12943
12944 // For (in)equality comparisons, if the unsigned operand is a
12945 // constant which cannot collide with a overflowed signed operand,
12946 // then reinterpreting the signed operand as unsigned will not
12947 // change the result of the comparison.
12948 if (E->isEqualityOp()) {
12949 unsigned comparisonWidth = S.Context.getIntWidth(T);
12950 std::optional<IntRange> unsignedRange = TryGetExprRange(
12951 C&: S.Context, E: unsignedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12952 /*Approximate=*/true);
12953 if (!unsignedRange)
12954 return;
12955
12956 // We should never be unable to prove that the unsigned operand is
12957 // non-negative.
12958 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12959
12960 if (unsignedRange->Width < comparisonWidth)
12961 return;
12962 }
12963
12964 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12965 PD: S.PDiag(DiagID: diag::warn_mixed_sign_comparison)
12966 << LHS->getType() << RHS->getType()
12967 << LHS->getSourceRange() << RHS->getSourceRange());
12968}
12969
12970/// Analyzes an attempt to assign the given value to a bitfield.
12971///
12972/// Returns true if there was something fishy about the attempt.
12973static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12974 SourceLocation InitLoc) {
12975 assert(Bitfield->isBitField());
12976 if (Bitfield->isInvalidDecl())
12977 return false;
12978
12979 // White-list bool bitfields.
12980 QualType BitfieldType = Bitfield->getType();
12981 if (BitfieldType->isBooleanType())
12982 return false;
12983
12984 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12985 // If the underlying enum type was not explicitly specified as an unsigned
12986 // type and the enum contain only positive values, MSVC++ will cause an
12987 // inconsistency by storing this as a signed type.
12988 if (S.getLangOpts().CPlusPlus11 &&
12989 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12990 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12991 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12992 S.Diag(Loc: InitLoc, DiagID: diag::warn_no_underlying_type_specified_for_enum_bitfield)
12993 << BitfieldEnumDecl;
12994 }
12995 }
12996
12997 // Ignore value- or type-dependent expressions.
12998 if (Bitfield->getBitWidth()->isValueDependent() ||
12999 Bitfield->getBitWidth()->isTypeDependent() ||
13000 Init->isValueDependent() ||
13001 Init->isTypeDependent())
13002 return false;
13003
13004 Expr *OriginalInit = Init->IgnoreParenImpCasts();
13005 unsigned FieldWidth = Bitfield->getBitWidthValue();
13006
13007 Expr::EvalResult Result;
13008 if (!OriginalInit->EvaluateAsInt(Result, Ctx: S.Context,
13009 AllowSideEffects: Expr::SE_AllowSideEffects)) {
13010 // The RHS is not constant. If the RHS has an enum type, make sure the
13011 // bitfield is wide enough to hold all the values of the enum without
13012 // truncation.
13013 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
13014 const PreferredTypeAttr *PTAttr = nullptr;
13015 if (!ED) {
13016 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
13017 if (PTAttr)
13018 ED = PTAttr->getType()->getAsEnumDecl();
13019 }
13020 if (ED) {
13021 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
13022
13023 // Enum types are implicitly signed on Windows, so check if there are any
13024 // negative enumerators to see if the enum was intended to be signed or
13025 // not.
13026 bool SignedEnum = ED->getNumNegativeBits() > 0;
13027
13028 // Check for surprising sign changes when assigning enum values to a
13029 // bitfield of different signedness. If the bitfield is signed and we
13030 // have exactly the right number of bits to store this unsigned enum,
13031 // suggest changing the enum to an unsigned type. This typically happens
13032 // on Windows where unfixed enums always use an underlying type of 'int'.
13033 unsigned DiagID = 0;
13034 if (SignedEnum && !SignedBitfield) {
13035 DiagID =
13036 PTAttr == nullptr
13037 ? diag::warn_unsigned_bitfield_assigned_signed_enum
13038 : diag::
13039 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
13040 } else if (SignedBitfield && !SignedEnum &&
13041 ED->getNumPositiveBits() == FieldWidth) {
13042 DiagID =
13043 PTAttr == nullptr
13044 ? diag::warn_signed_bitfield_enum_conversion
13045 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
13046 }
13047 if (DiagID) {
13048 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
13049 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
13050 SourceRange TypeRange =
13051 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
13052 S.Diag(Loc: Bitfield->getTypeSpecStartLoc(), DiagID: diag::note_change_bitfield_sign)
13053 << SignedEnum << TypeRange;
13054 if (PTAttr)
13055 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
13056 << ED;
13057 }
13058
13059 // Compute the required bitwidth. If the enum has negative values, we need
13060 // one more bit than the normal number of positive bits to represent the
13061 // sign bit.
13062 unsigned BitsNeeded = SignedEnum ? std::max(a: ED->getNumPositiveBits() + 1,
13063 b: ED->getNumNegativeBits())
13064 : ED->getNumPositiveBits();
13065
13066 // Check the bitwidth.
13067 if (BitsNeeded > FieldWidth) {
13068 Expr *WidthExpr = Bitfield->getBitWidth();
13069 auto DiagID =
13070 PTAttr == nullptr
13071 ? diag::warn_bitfield_too_small_for_enum
13072 : diag::warn_preferred_type_bitfield_too_small_for_enum;
13073 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
13074 S.Diag(Loc: WidthExpr->getExprLoc(), DiagID: diag::note_widen_bitfield)
13075 << BitsNeeded << ED << WidthExpr->getSourceRange();
13076 if (PTAttr)
13077 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
13078 << ED;
13079 }
13080 }
13081
13082 return false;
13083 }
13084
13085 llvm::APSInt Value = Result.Val.getInt();
13086
13087 unsigned OriginalWidth = Value.getBitWidth();
13088
13089 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
13090 // false positives where the user is demonstrating they intend to use the
13091 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
13092 // to a one-bit bit-field to see if the value came from a macro named 'true'.
13093 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
13094 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
13095 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
13096 if (S.SourceMgr.isInSystemMacro(loc: MaybeMacroLoc) &&
13097 S.findMacroSpelling(loc&: MaybeMacroLoc, name: "true"))
13098 return false;
13099 }
13100
13101 if (!Value.isSigned() || Value.isNegative())
13102 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: OriginalInit))
13103 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
13104 OriginalWidth = Value.getSignificantBits();
13105
13106 if (OriginalWidth <= FieldWidth)
13107 return false;
13108
13109 // Compute the value which the bitfield will contain.
13110 llvm::APSInt TruncatedValue = Value.trunc(width: FieldWidth);
13111 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
13112
13113 // Check whether the stored value is equal to the original value.
13114 TruncatedValue = TruncatedValue.extend(width: OriginalWidth);
13115 if (llvm::APSInt::isSameValue(I1: Value, I2: TruncatedValue))
13116 return false;
13117
13118 std::string PrettyValue = toString(I: Value, Radix: 10);
13119 std::string PrettyTrunc = toString(I: TruncatedValue, Radix: 10);
13120
13121 S.Diag(Loc: InitLoc, DiagID: OneAssignedToOneBitBitfield
13122 ? diag::warn_impcast_single_bit_bitield_precision_constant
13123 : diag::warn_impcast_bitfield_precision_constant)
13124 << PrettyValue << PrettyTrunc << OriginalInit->getType()
13125 << Init->getSourceRange();
13126
13127 return true;
13128}
13129
13130/// Analyze the given simple or compound assignment for warning-worthy
13131/// operations.
13132static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
13133 // Just recurse on the LHS.
13134 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
13135
13136 // We want to recurse on the RHS as normal unless we're assigning to
13137 // a bitfield.
13138 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
13139 if (AnalyzeBitFieldAssignment(S, Bitfield, Init: E->getRHS(),
13140 InitLoc: E->getOperatorLoc())) {
13141 // Recurse, ignoring any implicit conversions on the RHS.
13142 return AnalyzeImplicitConversions(S, E: E->getRHS()->IgnoreParenImpCasts(),
13143 CC: E->getOperatorLoc());
13144 }
13145 }
13146
13147 // Set context flag for overflow behavior type assignment analysis, use RAII
13148 // pattern to handle nested assignments.
13149 llvm::SaveAndRestore OBTAssignmentContext(
13150 S.InOverflowBehaviorAssignmentContext, true);
13151
13152 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
13153
13154 // Diagnose implicitly sequentially-consistent atomic assignment.
13155 if (E->getLHS()->getType()->isAtomicType())
13156 S.Diag(Loc: E->getRHS()->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13157}
13158
13159/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13160static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
13161 QualType T, SourceLocation CContext, unsigned diag,
13162 bool PruneControlFlow = false) {
13163 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
13164 // address space annotations isn't really useful. The warnings aren't because
13165 // you're converting a `private int` to `unsigned int`, it is because you're
13166 // conerting `int` to `unsigned int`.
13167 if (SourceType.hasAddressSpace())
13168 SourceType = S.getASTContext().removeAddrSpaceQualType(T: SourceType);
13169 if (T.hasAddressSpace())
13170 T = S.getASTContext().removeAddrSpaceQualType(T);
13171 if (PruneControlFlow) {
13172 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13173 PD: S.PDiag(DiagID: diag)
13174 << SourceType << T << E->getSourceRange()
13175 << SourceRange(CContext));
13176 return;
13177 }
13178 S.Diag(Loc: E->getExprLoc(), DiagID: diag)
13179 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
13180}
13181
13182/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
13183static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
13184 SourceLocation CContext, unsigned diag,
13185 bool PruneControlFlow = false) {
13186 DiagnoseImpCast(S, E, SourceType: E->getType(), T, CContext, diag, PruneControlFlow);
13187}
13188
13189/// Diagnose an implicit cast from a floating point value to an integer value.
13190static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
13191 SourceLocation CContext) {
13192 bool IsBool = T->isSpecificBuiltinType(K: BuiltinType::Bool);
13193 bool PruneWarnings = S.inTemplateInstantiation();
13194
13195 const Expr *InnerE = E->IgnoreParenImpCasts();
13196 // We also want to warn on, e.g., "int i = -1.234"
13197 if (const auto *UOp = dyn_cast<UnaryOperator>(Val: InnerE))
13198 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
13199 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
13200
13201 bool IsLiteral = isa<FloatingLiteral>(Val: E) || isa<FloatingLiteral>(Val: InnerE);
13202
13203 llvm::APFloat Value(0.0);
13204 bool IsConstant =
13205 E->EvaluateAsFloat(Result&: Value, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects);
13206 if (!IsConstant) {
13207 if (S.ObjC().isSignedCharBool(Ty: T)) {
13208 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
13209 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_float_to_objc_signed_char_bool)
13210 << E->getType());
13211 }
13212
13213 return DiagnoseImpCast(S, E, T, CContext,
13214 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13215 }
13216
13217 bool isExact = false;
13218
13219 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
13220 T->hasUnsignedIntegerRepresentation());
13221 llvm::APFloat::opStatus Result = Value.convertToInteger(
13222 Result&: IntegerValue, RM: llvm::APFloat::rmTowardZero, IsExact: &isExact);
13223
13224 // FIXME: Force the precision of the source value down so we don't print
13225 // digits which are usually useless (we don't really care here if we
13226 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
13227 // would automatically print the shortest representation, but it's a bit
13228 // tricky to implement.
13229 SmallString<16> PrettySourceValue;
13230 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
13231 precision = (precision * 59 + 195) / 196;
13232 Value.toString(Str&: PrettySourceValue, FormatPrecision: precision);
13233
13234 if (S.ObjC().isSignedCharBool(Ty: T) && IntegerValue != 0 && IntegerValue != 1) {
13235 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
13236 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
13237 << PrettySourceValue);
13238 }
13239
13240 if (Result == llvm::APFloat::opOK && isExact) {
13241 if (IsLiteral) return;
13242 return DiagnoseImpCast(S, E, T, CContext, diag: diag::warn_impcast_float_integer,
13243 PruneControlFlow: PruneWarnings);
13244 }
13245
13246 // Conversion of a floating-point value to a non-bool integer where the
13247 // integral part cannot be represented by the integer type is undefined.
13248 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
13249 return DiagnoseImpCast(
13250 S, E, T, CContext,
13251 diag: IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13252 : diag::warn_impcast_float_to_integer_out_of_range,
13253 PruneControlFlow: PruneWarnings);
13254
13255 unsigned DiagID = 0;
13256 if (IsLiteral) {
13257 // Warn on floating point literal to integer.
13258 DiagID = diag::warn_impcast_literal_float_to_integer;
13259 } else if (IntegerValue == 0) {
13260 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
13261 return DiagnoseImpCast(S, E, T, CContext,
13262 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13263 }
13264 // Warn on non-zero to zero conversion.
13265 DiagID = diag::warn_impcast_float_to_integer_zero;
13266 } else {
13267 if (IntegerValue.isUnsigned()) {
13268 if (!IntegerValue.isMaxValue()) {
13269 return DiagnoseImpCast(S, E, T, CContext,
13270 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13271 }
13272 } else { // IntegerValue.isSigned()
13273 if (!IntegerValue.isMaxSignedValue() &&
13274 !IntegerValue.isMinSignedValue()) {
13275 return DiagnoseImpCast(S, E, T, CContext,
13276 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13277 }
13278 }
13279 // Warn on evaluatable floating point expression to integer conversion.
13280 DiagID = diag::warn_impcast_float_to_integer;
13281 }
13282
13283 SmallString<16> PrettyTargetValue;
13284 if (IsBool)
13285 PrettyTargetValue = Value.isZero() ? "false" : "true";
13286 else
13287 IntegerValue.toString(Str&: PrettyTargetValue);
13288
13289 if (PruneWarnings) {
13290 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13291 PD: S.PDiag(DiagID)
13292 << E->getType() << T.getUnqualifiedType()
13293 << PrettySourceValue << PrettyTargetValue
13294 << E->getSourceRange() << SourceRange(CContext));
13295 } else {
13296 S.Diag(Loc: E->getExprLoc(), DiagID)
13297 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
13298 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
13299 }
13300}
13301
13302/// Analyze the given compound assignment for the possible losing of
13303/// floating-point precision.
13304static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
13305 assert(isa<CompoundAssignOperator>(E) &&
13306 "Must be compound assignment operation");
13307 // Recurse on the LHS and RHS in here
13308 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
13309 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
13310
13311 if (E->getLHS()->getType()->isAtomicType())
13312 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13313
13314 // Now check the outermost expression
13315 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13316 const auto *RBT = cast<CompoundAssignOperator>(Val: E)
13317 ->getComputationResultType()
13318 ->getAs<BuiltinType>();
13319
13320 // The below checks assume source is floating point.
13321 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13322
13323 // If source is floating point but target is an integer.
13324 if (ResultBT->isInteger())
13325 return DiagnoseImpCast(S, E, SourceType: E->getRHS()->getType(), T: E->getLHS()->getType(),
13326 CContext: E->getExprLoc(), diag: diag::warn_impcast_float_integer);
13327
13328 if (!ResultBT->isFloatingPoint())
13329 return;
13330
13331 // If both source and target are floating points, warn about losing precision.
13332 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13333 LHS: QualType(ResultBT, 0), RHS: QualType(RBT, 0));
13334 if (Order < 0 && !S.SourceMgr.isInSystemMacro(loc: E->getOperatorLoc()))
13335 // warn about dropping FP rank.
13336 DiagnoseImpCast(S, E: E->getRHS(), T: E->getLHS()->getType(), CContext: E->getOperatorLoc(),
13337 diag: diag::warn_impcast_float_result_precision);
13338}
13339
13340static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13341 IntRange Range) {
13342 if (!Range.Width) return "0";
13343
13344 llvm::APSInt ValueInRange = Value;
13345 ValueInRange.setIsSigned(!Range.NonNegative);
13346 ValueInRange = ValueInRange.trunc(width: Range.Width);
13347 return toString(I: ValueInRange, Radix: 10);
13348}
13349
13350static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
13351 bool ToBool) {
13352 if (!isa<ImplicitCastExpr>(Val: Ex))
13353 return false;
13354
13355 const Expr *InnerE = Ex->IgnoreParenImpCasts();
13356 const Type *Target = S.Context.getCanonicalType(T: Ex->getType()).getTypePtr();
13357 const Type *Source =
13358 S.Context.getCanonicalType(T: InnerE->getType()).getTypePtr();
13359 if (Target->isDependentType())
13360 return false;
13361
13362 const auto *FloatCandidateBT =
13363 dyn_cast<BuiltinType>(Val: ToBool ? Source : Target);
13364 const Type *BoolCandidateType = ToBool ? Target : Source;
13365
13366 return (BoolCandidateType->isSpecificBuiltinType(K: BuiltinType::Bool) &&
13367 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13368}
13369
13370static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
13371 SourceLocation CC) {
13372 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
13373 const Expr *CurrA = TheCall->getArg(Arg: I);
13374 if (!IsImplicitBoolFloatConversion(S, Ex: CurrA, ToBool: true))
13375 continue;
13376
13377 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
13378 S, Ex: TheCall->getArg(Arg: I - 1), ToBool: false));
13379 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
13380 S, Ex: TheCall->getArg(Arg: I + 1), ToBool: false));
13381 if (IsSwapped) {
13382 // Warn on this floating-point to bool conversion.
13383 DiagnoseImpCast(S, E: CurrA->IgnoreParenImpCasts(),
13384 T: CurrA->getType(), CContext: CC,
13385 diag: diag::warn_impcast_floating_point_to_bool);
13386 }
13387 }
13388}
13389
13390static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
13391 SourceLocation CC) {
13392 // Don't warn on functions which have return type nullptr_t.
13393 if (isa<CallExpr>(Val: E))
13394 return;
13395
13396 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13397 const Expr *NewE = E->IgnoreParenImpCasts();
13398 bool IsGNUNullExpr = isa<GNUNullExpr>(Val: NewE);
13399 bool HasNullPtrType = NewE->getType()->isNullPtrType();
13400 if (!IsGNUNullExpr && !HasNullPtrType)
13401 return;
13402
13403 // Return if target type is a safe conversion.
13404 if (T->isAnyPointerType() || T->isBlockPointerType() ||
13405 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13406 return;
13407
13408 if (S.Diags.isIgnored(DiagID: diag::warn_impcast_null_pointer_to_integer,
13409 Loc: E->getExprLoc()))
13410 return;
13411
13412 SourceLocation Loc = E->getSourceRange().getBegin();
13413
13414 // Venture through the macro stacks to get to the source of macro arguments.
13415 // The new location is a better location than the complete location that was
13416 // passed in.
13417 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13418 CC = S.SourceMgr.getTopMacroCallerLoc(Loc: CC);
13419
13420 // __null is usually wrapped in a macro. Go up a macro if that is the case.
13421 if (IsGNUNullExpr && Loc.isMacroID()) {
13422 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13423 Loc, SM: S.SourceMgr, LangOpts: S.getLangOpts());
13424 if (MacroName == "NULL")
13425 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
13426 }
13427
13428 // Only warn if the null and context location are in the same macro expansion.
13429 if (S.SourceMgr.getFileID(SpellingLoc: Loc) != S.SourceMgr.getFileID(SpellingLoc: CC))
13430 return;
13431
13432 S.Diag(Loc, DiagID: diag::warn_impcast_null_pointer_to_integer)
13433 << HasNullPtrType << T << SourceRange(CC)
13434 << FixItHint::CreateReplacement(RemoveRange: Loc,
13435 Code: S.getFixItZeroLiteralForType(T, Loc));
13436}
13437
13438// Helper function to filter out cases for constant width constant conversion.
13439// Don't warn on unsigned char array initialization or for non-decimal
13440// values.
13441static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
13442 SourceLocation CC) {
13443 // If initializing from a constant, and the constant starts with '0',
13444 // then it is a binary, octal, or hexadecimal. Allow these constants
13445 // to fill all the bits, even if there is a sign change.
13446 if (auto *IntLit = dyn_cast<IntegerLiteral>(Val: E->IgnoreParenImpCasts())) {
13447 const char FirstLiteralCharacter =
13448 S.getSourceManager().getCharacterData(SL: IntLit->getBeginLoc())[0];
13449 if (FirstLiteralCharacter == '0')
13450 return false;
13451 }
13452
13453 // If the CC location points to a '{' and the type is an unsigned char
13454 // type, assume it is an array initialization.
13455 if (T->isCharType() && !T->isSignedIntegerType() && CC.isValid()) {
13456 const char FirstContextCharacter =
13457 S.getSourceManager().getCharacterData(SL: CC)[0];
13458 if (FirstContextCharacter == '{')
13459 return false;
13460 }
13461
13462 return true;
13463}
13464
13465static const IntegerLiteral *getIntegerLiteral(Expr *E) {
13466 const auto *IL = dyn_cast<IntegerLiteral>(Val: E);
13467 if (!IL) {
13468 if (auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
13469 if (UO->getOpcode() == UO_Minus)
13470 return dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13471 }
13472 }
13473
13474 return IL;
13475}
13476
13477static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
13478 E = E->IgnoreParenImpCasts();
13479 SourceLocation ExprLoc = E->getExprLoc();
13480
13481 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
13482 BinaryOperator::Opcode Opc = BO->getOpcode();
13483 Expr::EvalResult Result;
13484 // Do not diagnose unsigned shifts.
13485 if (Opc == BO_Shl) {
13486 const auto *LHS = getIntegerLiteral(E: BO->getLHS());
13487 const auto *RHS = getIntegerLiteral(E: BO->getRHS());
13488 if (LHS && LHS->getValue() == 0)
13489 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always) << 0;
13490 else if (!E->isValueDependent() && LHS && RHS &&
13491 RHS->getValue().isNonNegative() &&
13492 E->EvaluateAsInt(Result, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects))
13493 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always)
13494 << (Result.Val.getInt() != 0);
13495 else if (E->getType()->isSignedIntegerType())
13496 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_in_bool_context)
13497 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "(")
13498 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: E->getEndLoc()),
13499 Code: ") != 0");
13500 }
13501 }
13502
13503 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
13504 const auto *LHS = getIntegerLiteral(E: CO->getTrueExpr());
13505 const auto *RHS = getIntegerLiteral(E: CO->getFalseExpr());
13506 if (!LHS || !RHS)
13507 return;
13508 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13509 (RHS->getValue() == 0 || RHS->getValue() == 1))
13510 // Do not diagnose common idioms.
13511 return;
13512 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13513 S.Diag(Loc: ExprLoc, DiagID: diag::warn_integer_constants_in_conditional_always_true);
13514 }
13515}
13516
13517static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source,
13518 const Type *Target, Expr *E,
13519 QualType T,
13520 SourceLocation CC) {
13521 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13522 Source != Target);
13523
13524 // Lone surrogates have a distinct representation in UTF-32.
13525 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13526 // so don't warn on such conversion.
13527 if (Source->isChar16Type() && Target->isChar32Type())
13528 return;
13529
13530 Expr::EvalResult Result;
13531 if (E->EvaluateAsInt(Result, Ctx: S.getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects,
13532 InConstantContext: S.isConstantEvaluatedContext())) {
13533 llvm::APSInt Value(32);
13534 Value = Result.Val.getInt();
13535 bool IsASCII = Value <= 0x7F;
13536 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13537 bool ConversionPreservesSemantics =
13538 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13539
13540 if (!ConversionPreservesSemantics) {
13541 auto IsSingleCodeUnitCP = [](const QualType &T,
13542 const llvm::APSInt &Value) {
13543 if (T->isChar8Type())
13544 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13545 if (T->isChar16Type())
13546 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13547 assert(T->isChar32Type());
13548 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13549 };
13550
13551 S.Diag(Loc: CC, DiagID: diag::warn_impcast_unicode_char_type_constant)
13552 << E->getType() << T
13553 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13554 << FormatUTFCodeUnitAsCodepoint(Value: Value.getExtValue(), T: E->getType());
13555 }
13556 } else {
13557 bool LosesPrecision = S.getASTContext().getIntWidth(T: E->getType()) >
13558 S.getASTContext().getIntWidth(T);
13559 DiagnoseImpCast(S, E, T, CContext: CC,
13560 diag: LosesPrecision ? diag::warn_impcast_unicode_precision
13561 : diag::warn_impcast_unicode_char_type);
13562 }
13563}
13564
13565bool Sema::DiscardingCFIUncheckedCallee(QualType From, QualType To) const {
13566 From = Context.getCanonicalType(T: From);
13567 To = Context.getCanonicalType(T: To);
13568 QualType MaybePointee = From->getPointeeType();
13569 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13570 From = MaybePointee;
13571 MaybePointee = To->getPointeeType();
13572 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13573 To = MaybePointee;
13574
13575 if (const auto *FromFn = From->getAs<FunctionType>()) {
13576 if (const auto *ToFn = To->getAs<FunctionType>()) {
13577 if (FromFn->getCFIUncheckedCalleeAttr() &&
13578 !ToFn->getCFIUncheckedCalleeAttr())
13579 return true;
13580 }
13581 }
13582 return false;
13583}
13584
13585void Sema::CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
13586 bool *ICContext, bool IsListInit) {
13587 if (E->isTypeDependent() || E->isValueDependent()) return;
13588
13589 const Type *Source = Context.getCanonicalType(T: E->getType()).getTypePtr();
13590 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13591 if (Source == Target) return;
13592 if (Target->isDependentType()) return;
13593
13594 // If the conversion context location is invalid don't complain. We also
13595 // don't want to emit a warning if the issue occurs from the expansion of
13596 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13597 // delay this check as long as possible. Once we detect we are in that
13598 // scenario, we just return.
13599 if (CC.isInvalid())
13600 return;
13601
13602 if (Source->isAtomicType())
13603 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13604
13605 // Diagnose implicit casts to bool.
13606 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool)) {
13607 if (isa<StringLiteral>(Val: E))
13608 // Warn on string literal to bool. Checks for string literals in logical
13609 // and expressions, for instance, assert(0 && "error here"), are
13610 // prevented by a check in AnalyzeImplicitConversions().
13611 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13612 diag: diag::warn_impcast_string_literal_to_bool);
13613 if (isa<ObjCStringLiteral>(Val: E) || isa<ObjCArrayLiteral>(Val: E) ||
13614 isa<ObjCDictionaryLiteral>(Val: E) || isa<ObjCBoxedExpr>(Val: E)) {
13615 // This covers the literal expressions that evaluate to Objective-C
13616 // objects.
13617 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13618 diag: diag::warn_impcast_objective_c_literal_to_bool);
13619 }
13620 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13621 // Warn on pointer to bool conversion that is always true.
13622 DiagnoseAlwaysNonNullPointer(E, NullType: Expr::NPCK_NotNull, /*IsEqual*/ false,
13623 Range: SourceRange(CC));
13624 }
13625 }
13626
13627 CheckOverflowBehaviorTypeConversion(E, T, CC);
13628
13629 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13630 // is a typedef for signed char (macOS), then that constant value has to be 1
13631 // or 0.
13632 if (ObjC().isSignedCharBool(Ty: T) && Source->isIntegralType(Ctx: Context)) {
13633 Expr::EvalResult Result;
13634 if (E->EvaluateAsInt(Result, Ctx: getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects)) {
13635 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13636 ObjC().adornBoolConversionDiagWithTernaryFixit(
13637 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
13638 << toString(I: Result.Val.getInt(), Radix: 10));
13639 }
13640 return;
13641 }
13642 }
13643
13644 // Check implicit casts from Objective-C collection literals to specialized
13645 // collection types, e.g., NSArray<NSString *> *.
13646 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Val: E))
13647 ObjC().checkArrayLiteral(TargetType: QualType(Target, 0), ArrayLiteral);
13648 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Val: E))
13649 ObjC().checkDictionaryLiteral(TargetType: QualType(Target, 0), DictionaryLiteral);
13650
13651 // Strip complex types.
13652 if (isa<ComplexType>(Val: Source)) {
13653 if (!isa<ComplexType>(Val: Target)) {
13654 if (SourceMgr.isInSystemMacro(loc: CC) || Target->isBooleanType())
13655 return;
13656
13657 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13658 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13659 diag: diag::err_impcast_incompatible_type);
13660 }
13661
13662 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13663 diag: getLangOpts().CPlusPlus
13664 ? diag::err_impcast_complex_scalar
13665 : diag::warn_impcast_complex_scalar);
13666 }
13667
13668 Source = cast<ComplexType>(Val: Source)->getElementType().getTypePtr();
13669 Target = cast<ComplexType>(Val: Target)->getElementType().getTypePtr();
13670 }
13671
13672 // Strip vector types.
13673 if (isa<VectorType>(Val: Source)) {
13674 if (Target->isSveVLSBuiltinType() &&
13675 (ARM().areCompatibleSveTypes(FirstType: QualType(Target, 0),
13676 SecondType: QualType(Source, 0)) ||
13677 ARM().areLaxCompatibleSveTypes(FirstType: QualType(Target, 0),
13678 SecondType: QualType(Source, 0))))
13679 return;
13680
13681 if (Target->isRVVVLSBuiltinType() &&
13682 (Context.areCompatibleRVVTypes(FirstType: QualType(Target, 0),
13683 SecondType: QualType(Source, 0)) ||
13684 Context.areLaxCompatibleRVVTypes(FirstType: QualType(Target, 0),
13685 SecondType: QualType(Source, 0))))
13686 return;
13687
13688 if (!isa<VectorType>(Val: Target)) {
13689 if (SourceMgr.isInSystemMacro(loc: CC))
13690 return;
13691 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_vector_scalar);
13692 }
13693 if (getLangOpts().HLSL &&
13694 Target->castAs<VectorType>()->getNumElements() <
13695 Source->castAs<VectorType>()->getNumElements()) {
13696 // Diagnose vector truncation but don't return. We may also want to
13697 // diagnose an element conversion.
13698 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13699 diag: diag::warn_hlsl_impcast_vector_truncation);
13700 }
13701
13702 // If the vector cast is cast between two vectors of the same size, it is
13703 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13704 if (!getLangOpts().HLSL &&
13705 Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13706 return;
13707
13708 Source = cast<VectorType>(Val: Source)->getElementType().getTypePtr();
13709 Target = cast<VectorType>(Val: Target)->getElementType().getTypePtr();
13710 }
13711 if (const auto *VecTy = dyn_cast<VectorType>(Val: Target))
13712 Target = VecTy->getElementType().getTypePtr();
13713
13714 // Strip matrix types.
13715 if (isa<ConstantMatrixType>(Val: Source)) {
13716 if (Target->isScalarType())
13717 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_matrix_scalar);
13718
13719 if (getLangOpts().HLSL && isa<ConstantMatrixType>(Val: Target) &&
13720 Target->castAs<ConstantMatrixType>()->getNumElementsFlattened() <
13721 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13722 // Diagnose Matrix truncation but don't return. We may also want to
13723 // diagnose an element conversion.
13724 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13725 diag: diag::warn_hlsl_impcast_matrix_truncation);
13726 }
13727
13728 Source = cast<ConstantMatrixType>(Val: Source)->getElementType().getTypePtr();
13729 Target = cast<ConstantMatrixType>(Val: Target)->getElementType().getTypePtr();
13730 }
13731 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Val: Target))
13732 Target = MatTy->getElementType().getTypePtr();
13733
13734 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Val: Source);
13735 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Val: Target);
13736
13737 // Strip SVE vector types
13738 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13739 // Need the original target type for vector type checks
13740 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13741 // Handle conversion from scalable to fixed when msve-vector-bits is
13742 // specified
13743 if (ARM().areCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13744 SecondType: QualType(Source, 0)) ||
13745 ARM().areLaxCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13746 SecondType: QualType(Source, 0)))
13747 return;
13748
13749 // If the vector cast is cast between two vectors of the same size, it is
13750 // a bitcast, not a conversion.
13751 if (Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13752 return;
13753
13754 Source = SourceBT->getSveEltType(Ctx: Context).getTypePtr();
13755 }
13756
13757 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13758 Target = TargetBT->getSveEltType(Ctx: Context).getTypePtr();
13759
13760 // Nothing to diagnose if stripping the wrappers left identical element types
13761 // (e.g. a scalar splatted to a vector of its own type).
13762 if (Source == Target)
13763 return;
13764
13765 // If the source is floating point...
13766 if (SourceBT && SourceBT->isFloatingPoint()) {
13767 // ...and the target is floating point...
13768 if (TargetBT && TargetBT->isFloatingPoint()) {
13769 // ...then warn if we're dropping FP rank.
13770
13771 int Order = getASTContext().getFloatingTypeSemanticOrder(
13772 LHS: QualType(SourceBT, 0), RHS: QualType(TargetBT, 0));
13773 if (Order > 0) {
13774 // Don't warn about float constants that are precisely
13775 // representable in the target type.
13776 Expr::EvalResult result;
13777 if (E->EvaluateAsRValue(Result&: result, Ctx: Context)) {
13778 // Value might be a float, a float vector, or a float complex.
13779 if (IsSameFloatAfterCast(
13780 value: result.Val,
13781 Src: Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)),
13782 Tgt: Context.getFloatTypeSemantics(T: QualType(SourceBT, 0))))
13783 return;
13784 }
13785
13786 if (SourceMgr.isInSystemMacro(loc: CC))
13787 return;
13788
13789 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_float_precision);
13790 }
13791 // ... or possibly if we're increasing rank, too
13792 else if (Order < 0) {
13793 if (SourceMgr.isInSystemMacro(loc: CC))
13794 return;
13795
13796 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_double_promotion);
13797 }
13798 return;
13799 }
13800
13801 // If the target is integral, always warn.
13802 if (TargetBT && TargetBT->isInteger()) {
13803 if (SourceMgr.isInSystemMacro(loc: CC))
13804 return;
13805
13806 DiagnoseFloatingImpCast(S&: *this, E, T, CContext: CC);
13807 }
13808
13809 // Detect the case where a call result is converted from floating-point to
13810 // to bool, and the final argument to the call is converted from bool, to
13811 // discover this typo:
13812 //
13813 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13814 //
13815 // FIXME: This is an incredibly special case; is there some more general
13816 // way to detect this class of misplaced-parentheses bug?
13817 if (Target->isBooleanType() && isa<CallExpr>(Val: E)) {
13818 // Check last argument of function call to see if it is an
13819 // implicit cast from a type matching the type the result
13820 // is being cast to.
13821 CallExpr *CEx = cast<CallExpr>(Val: E);
13822 if (unsigned NumArgs = CEx->getNumArgs()) {
13823 Expr *LastA = CEx->getArg(Arg: NumArgs - 1);
13824 Expr *InnerE = LastA->IgnoreParenImpCasts();
13825 if (isa<ImplicitCastExpr>(Val: LastA) &&
13826 InnerE->getType()->isBooleanType()) {
13827 // Warn on this floating-point to bool conversion
13828 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13829 diag: diag::warn_impcast_floating_point_to_bool);
13830 }
13831 }
13832 }
13833 return;
13834 }
13835
13836 // Valid casts involving fixed point types should be accounted for here.
13837 if (Source->isFixedPointType()) {
13838 if (Target->isUnsaturatedFixedPointType()) {
13839 Expr::EvalResult Result;
13840 if (E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13841 InConstantContext: isConstantEvaluatedContext())) {
13842 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13843 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(Ty: T);
13844 llvm::APFixedPoint MinVal = Context.getFixedPointMin(Ty: T);
13845 if (Value > MaxVal || Value < MinVal) {
13846 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13847 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13848 << Value.toString() << T
13849 << E->getSourceRange()
13850 << clang::SourceRange(CC));
13851 return;
13852 }
13853 }
13854 } else if (Target->isIntegerType()) {
13855 Expr::EvalResult Result;
13856 if (!isConstantEvaluatedContext() &&
13857 E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13858 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13859
13860 bool Overflowed;
13861 llvm::APSInt IntResult = FXResult.convertToInt(
13862 DstWidth: Context.getIntWidth(T), DstSign: Target->isSignedIntegerOrEnumerationType(),
13863 Overflow: &Overflowed);
13864
13865 if (Overflowed) {
13866 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13867 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13868 << FXResult.toString() << T
13869 << E->getSourceRange()
13870 << clang::SourceRange(CC));
13871 return;
13872 }
13873 }
13874 }
13875 } else if (Target->isUnsaturatedFixedPointType()) {
13876 if (Source->isIntegerType()) {
13877 Expr::EvalResult Result;
13878 if (!isConstantEvaluatedContext() &&
13879 E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13880 llvm::APSInt Value = Result.Val.getInt();
13881
13882 bool Overflowed;
13883 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13884 Value, DstFXSema: Context.getFixedPointSemantics(Ty: T), Overflow: &Overflowed);
13885
13886 if (Overflowed) {
13887 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13888 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13889 << toString(I: Value, /*Radix=*/10) << T
13890 << E->getSourceRange()
13891 << clang::SourceRange(CC));
13892 return;
13893 }
13894 }
13895 }
13896 }
13897
13898 // If we are casting an integer type to a floating point type without
13899 // initialization-list syntax, we might lose accuracy if the floating
13900 // point type has a narrower significand than the integer type.
13901 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13902 TargetBT->isFloatingType() && !IsListInit) {
13903 // Determine the number of precision bits in the source integer type.
13904 std::optional<IntRange> SourceRange =
13905 TryGetExprRange(C&: Context, E, InConstantContext: isConstantEvaluatedContext(),
13906 /*Approximate=*/true);
13907 if (!SourceRange)
13908 return;
13909 unsigned int SourcePrecision = SourceRange->Width;
13910
13911 // Determine the number of precision bits in the
13912 // target floating point type.
13913 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13914 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13915
13916 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13917 SourcePrecision > TargetPrecision) {
13918
13919 if (std::optional<llvm::APSInt> SourceInt =
13920 E->getIntegerConstantExpr(Ctx: Context)) {
13921 // If the source integer is a constant, convert it to the target
13922 // floating point type. Issue a warning if the value changes
13923 // during the whole conversion.
13924 llvm::APFloat TargetFloatValue(
13925 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13926 llvm::APFloat::opStatus ConversionStatus =
13927 TargetFloatValue.convertFromAPInt(
13928 Input: *SourceInt, IsSigned: SourceBT->isSignedInteger(),
13929 RM: llvm::APFloat::rmNearestTiesToEven);
13930
13931 if (ConversionStatus != llvm::APFloat::opOK) {
13932 SmallString<32> PrettySourceValue;
13933 SourceInt->toString(Str&: PrettySourceValue, Radix: 10);
13934 SmallString<32> PrettyTargetValue;
13935 TargetFloatValue.toString(Str&: PrettyTargetValue, FormatPrecision: TargetPrecision);
13936
13937 DiagRuntimeBehavior(
13938 Loc: E->getExprLoc(), Statement: E,
13939 PD: PDiag(DiagID: diag::warn_impcast_integer_float_precision_constant)
13940 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13941 << E->getSourceRange() << clang::SourceRange(CC));
13942 }
13943 } else {
13944 // Otherwise, the implicit conversion may lose precision.
13945 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13946 diag: diag::warn_impcast_integer_float_precision);
13947 }
13948 }
13949 }
13950
13951 DiagnoseNullConversion(S&: *this, E, T, CC);
13952
13953 DiscardMisalignedMemberAddress(T: Target, E);
13954
13955 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13956 DiagnoseMixedUnicodeImplicitConversion(S&: *this, Source, Target, E, T, CC);
13957 return;
13958 }
13959
13960 if (Target->isBooleanType())
13961 DiagnoseIntInBoolContext(S&: *this, E);
13962
13963 if (DiscardingCFIUncheckedCallee(From: QualType(Source, 0), To: QualType(Target, 0))) {
13964 Diag(Loc: CC, DiagID: diag::warn_cast_discards_cfi_unchecked_callee)
13965 << QualType(Source, 0) << QualType(Target, 0);
13966 }
13967
13968 if (!Source->isIntegerType() || !Target->isIntegerType())
13969 return;
13970
13971 // TODO: remove this early return once the false positives for constant->bool
13972 // in templates, macros, etc, are reduced or removed.
13973 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool))
13974 return;
13975
13976 if (ObjC().isSignedCharBool(Ty: T) && !Source->isCharType() &&
13977 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13978 return ObjC().adornBoolConversionDiagWithTernaryFixit(
13979 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_int_to_objc_signed_char_bool)
13980 << E->getType());
13981 }
13982 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13983 C&: Context, E, InConstantContext: isConstantEvaluatedContext(), /*Approximate=*/true);
13984 if (!LikelySourceRange)
13985 return;
13986
13987 IntRange SourceTypeRange =
13988 IntRange::forTargetOfCanonicalType(C&: Context, T: Source);
13989 IntRange TargetRange = IntRange::forTargetOfCanonicalType(C&: Context, T: Target);
13990
13991 if (LikelySourceRange->Width > TargetRange.Width) {
13992 // Check if target is a wrapping OBT - if so, don't warn about constant
13993 // conversion as this type may be used intentionally with implicit
13994 // truncation, especially during assignments.
13995 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13996 if (TargetOBT->isWrapKind()) {
13997 return;
13998 }
13999 }
14000
14001 // Check if source expression has an explicit __ob_wrap cast because if so,
14002 // wrapping was explicitly requested and we shouldn't warn
14003 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
14004 if (SourceOBT->isWrapKind()) {
14005 return;
14006 }
14007 }
14008
14009 // If the source is a constant, use a default-on diagnostic.
14010 // TODO: this should happen for bitfield stores, too.
14011 Expr::EvalResult Result;
14012 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
14013 InConstantContext: isConstantEvaluatedContext())) {
14014 llvm::APSInt Value(32);
14015 Value = Result.Val.getInt();
14016
14017 if (SourceMgr.isInSystemMacro(loc: CC))
14018 return;
14019
14020 std::string PrettySourceValue = toString(I: Value, Radix: 10);
14021 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
14022
14023 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
14024 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
14025 << PrettySourceValue << PrettyTargetValue
14026 << E->getType() << T << E->getSourceRange()
14027 << SourceRange(CC));
14028 return;
14029 }
14030
14031 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
14032 if (SourceMgr.isInSystemMacro(loc: CC))
14033 return;
14034
14035 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
14036 if (UO->getOpcode() == UO_Minus)
14037 return DiagnoseImpCast(
14038 S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_precision_on_negation);
14039 }
14040
14041 if (TargetRange.Width == 32 && Context.getIntWidth(T: E->getType()) == 64)
14042 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_64_32,
14043 /* pruneControlFlow */ PruneControlFlow: true);
14044 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
14045 diag: diag::warn_impcast_integer_precision);
14046 }
14047
14048 if (TargetRange.Width > SourceTypeRange.Width) {
14049 if (auto *UO = dyn_cast<UnaryOperator>(Val: E))
14050 if (UO->getOpcode() == UO_Minus)
14051 if (Source->isUnsignedIntegerType()) {
14052 if (Target->isUnsignedIntegerType())
14053 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
14054 diag: diag::warn_impcast_high_order_zero_bits);
14055 if (Target->isSignedIntegerType())
14056 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
14057 diag: diag::warn_impcast_nonnegative_result);
14058 }
14059 }
14060
14061 if (TargetRange.Width == LikelySourceRange->Width &&
14062 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
14063 Source->isSignedIntegerType()) {
14064 // Warn when doing a signed to signed conversion, warn if the positive
14065 // source value is exactly the width of the target type, which will
14066 // cause a negative value to be stored.
14067
14068 Expr::EvalResult Result;
14069 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects) &&
14070 !SourceMgr.isInSystemMacro(loc: CC)) {
14071 llvm::APSInt Value = Result.Val.getInt();
14072 if (isSameWidthConstantConversion(S&: *this, E, T, CC)) {
14073 std::string PrettySourceValue = toString(I: Value, Radix: 10);
14074 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
14075
14076 Diag(Loc: E->getExprLoc(),
14077 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
14078 << PrettySourceValue << PrettyTargetValue << E->getType() << T
14079 << E->getSourceRange() << SourceRange(CC));
14080 return;
14081 }
14082 }
14083
14084 // Fall through for non-constants to give a sign conversion warning.
14085 }
14086
14087 if ((!isa<EnumType>(Val: Target) || !isa<EnumType>(Val: Source)) &&
14088 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
14089 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
14090 LikelySourceRange->Width == TargetRange.Width))) {
14091 if (SourceMgr.isInSystemMacro(loc: CC))
14092 return;
14093
14094 if (SourceBT && SourceBT->isInteger() && TargetBT &&
14095 TargetBT->isInteger() &&
14096 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
14097 return;
14098 }
14099
14100 unsigned DiagID = diag::warn_impcast_integer_sign;
14101
14102 // Traditionally, gcc has warned about this under -Wsign-compare.
14103 // We also want to warn about it in -Wconversion.
14104 // So if -Wconversion is off, use a completely identical diagnostic
14105 // in the sign-compare group.
14106 // The conditional-checking code will
14107 if (ICContext) {
14108 DiagID = diag::warn_impcast_integer_sign_conditional;
14109 *ICContext = true;
14110 }
14111
14112 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagID);
14113 }
14114
14115 // If we're implicitly converting from an integer into an enumeration, that
14116 // is valid in C but invalid in C++.
14117 QualType SourceType = E->getEnumCoercedType(Ctx: Context);
14118 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
14119 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Val: Target))
14120 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_int_to_enum);
14121
14122 // Diagnose conversions between different enumeration types.
14123 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
14124 // type, to give us better diagnostics.
14125 Source = Context.getCanonicalType(T: SourceType).getTypePtr();
14126
14127 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
14128 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
14129 if (SourceEnum->getDecl()->hasNameForLinkage() &&
14130 TargetEnum->getDecl()->hasNameForLinkage() &&
14131 SourceEnum != TargetEnum) {
14132 if (SourceMgr.isInSystemMacro(loc: CC))
14133 return;
14134
14135 return DiagnoseImpCast(S&: *this, E, SourceType, T, CContext: CC,
14136 diag: diag::warn_impcast_different_enum_types);
14137 }
14138}
14139
14140static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
14141 SourceLocation CC, QualType T);
14142
14143static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
14144 SourceLocation CC, bool &ICContext) {
14145 E = E->IgnoreParenImpCasts();
14146 // Diagnose incomplete type for second or third operand in C.
14147 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
14148 S.RequireCompleteExprType(E, DiagID: diag::err_incomplete_type);
14149
14150 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: E))
14151 return CheckConditionalOperator(S, E: CO, CC, T);
14152
14153 AnalyzeImplicitConversions(S, E, CC);
14154 if (E->getType() != T)
14155 return S.CheckImplicitConversion(E, T, CC, ICContext: &ICContext);
14156}
14157
14158static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
14159 SourceLocation CC, QualType T) {
14160 AnalyzeImplicitConversions(S, E: E->getCond(), CC: E->getQuestionLoc());
14161
14162 Expr *TrueExpr = E->getTrueExpr();
14163 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(Val: E))
14164 TrueExpr = BCO->getCommon();
14165
14166 bool Suspicious = false;
14167 CheckConditionalOperand(S, E: TrueExpr, T, CC, ICContext&: Suspicious);
14168 CheckConditionalOperand(S, E: E->getFalseExpr(), T, CC, ICContext&: Suspicious);
14169
14170 if (T->isBooleanType())
14171 DiagnoseIntInBoolContext(S, E);
14172
14173 // If -Wconversion would have warned about either of the candidates
14174 // for a signedness conversion to the context type...
14175 if (!Suspicious) return;
14176
14177 // ...but it's currently ignored...
14178 if (!S.Diags.isIgnored(DiagID: diag::warn_impcast_integer_sign_conditional, Loc: CC))
14179 return;
14180
14181 // ...then check whether it would have warned about either of the
14182 // candidates for a signedness conversion to the condition type.
14183 if (E->getType() == T) return;
14184
14185 Suspicious = false;
14186 S.CheckImplicitConversion(E: TrueExpr->IgnoreParenImpCasts(), T: E->getType(), CC,
14187 ICContext: &Suspicious);
14188 if (!Suspicious)
14189 S.CheckImplicitConversion(E: E->getFalseExpr()->IgnoreParenImpCasts(),
14190 T: E->getType(), CC, ICContext: &Suspicious);
14191}
14192
14193/// Check conversion of given expression to boolean.
14194/// Input argument E is a logical expression.
14195static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
14196 // Run the bool-like conversion checks only for C since there bools are
14197 // still not used as the return type from "boolean" operators or as the input
14198 // type for conditional operators.
14199 if (S.getLangOpts().CPlusPlus)
14200 return;
14201 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
14202 return;
14203 S.CheckImplicitConversion(E: E->IgnoreParenImpCasts(), T: S.Context.BoolTy, CC);
14204}
14205
14206namespace {
14207struct AnalyzeImplicitConversionsWorkItem {
14208 Expr *E;
14209 SourceLocation CC;
14210 bool IsListInit;
14211};
14212}
14213
14214static void CheckCommaOperand(
14215 Sema &S, Expr *E, QualType T, SourceLocation CC,
14216 bool ExtraCheckForImplicitConversion,
14217 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
14218 E = E->IgnoreParenImpCasts();
14219 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: false});
14220
14221 if (ExtraCheckForImplicitConversion && E->getType() != T)
14222 S.CheckImplicitConversion(E, T, CC);
14223}
14224
14225/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
14226/// that should be visited are added to WorkList.
14227static void AnalyzeImplicitConversions(
14228 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
14229 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
14230 Expr *OrigE = Item.E;
14231 SourceLocation CC = Item.CC;
14232
14233 QualType T = OrigE->getType();
14234 Expr *E = OrigE->IgnoreParenImpCasts();
14235
14236 // Propagate whether we are in a C++ list initialization expression.
14237 // If so, we do not issue warnings for implicit int-float conversion
14238 // precision loss, because C++11 narrowing already handles it.
14239 //
14240 // HLSL's initialization lists are special, so they shouldn't observe the C++
14241 // behavior here.
14242 bool IsListInit =
14243 Item.IsListInit || (isa<InitListExpr>(Val: OrigE) &&
14244 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
14245
14246 if (E->isTypeDependent() || E->isValueDependent())
14247 return;
14248
14249 Expr *SourceExpr = E;
14250 // Examine, but don't traverse into the source expression of an
14251 // OpaqueValueExpr, since it may have multiple parents and we don't want to
14252 // emit duplicate diagnostics. Its fine to examine the form or attempt to
14253 // evaluate it in the context of checking the specific conversion to T though.
14254 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
14255 if (auto *Src = OVE->getSourceExpr())
14256 SourceExpr = Src;
14257
14258 if (const auto *UO = dyn_cast<UnaryOperator>(Val: SourceExpr))
14259 if (UO->getOpcode() == UO_Not &&
14260 UO->getSubExpr()->isKnownToHaveBooleanValue())
14261 S.Diag(Loc: UO->getBeginLoc(), DiagID: diag::warn_bitwise_negation_bool)
14262 << OrigE->getSourceRange() << T->isBooleanType()
14263 << FixItHint::CreateReplacement(RemoveRange: UO->getBeginLoc(), Code: "!");
14264
14265 if (auto *BO = dyn_cast<BinaryOperator>(Val: SourceExpr)) {
14266 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14267 BO->getLHS()->isKnownToHaveBooleanValue() &&
14268 BO->getRHS()->isKnownToHaveBooleanValue() &&
14269 BO->getLHS()->HasSideEffects(Ctx: S.Context) &&
14270 BO->getRHS()->HasSideEffects(Ctx: S.Context)) {
14271 SourceManager &SM = S.getSourceManager();
14272 const LangOptions &LO = S.getLangOpts();
14273 SourceLocation BLoc = BO->getOperatorLoc();
14274 SourceLocation ELoc = Lexer::getLocForEndOfToken(Loc: BLoc, Offset: 0, SM, LangOpts: LO);
14275 StringRef SR = clang::Lexer::getSourceText(
14276 Range: clang::CharSourceRange::getTokenRange(B: BLoc, E: ELoc), SM, LangOpts: LO);
14277 // To reduce false positives, only issue the diagnostic if the operator
14278 // is explicitly spelled as a punctuator. This suppresses the diagnostic
14279 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
14280 // in C, along with other macro spellings the user might invent.
14281 if (SR.str() == "&" || SR.str() == "|") {
14282
14283 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_bitwise_instead_of_logical)
14284 << (BO->getOpcode() == BO_And ? "&" : "|")
14285 << OrigE->getSourceRange()
14286 << FixItHint::CreateReplacement(
14287 RemoveRange: BO->getOperatorLoc(),
14288 Code: (BO->getOpcode() == BO_And ? "&&" : "||"));
14289 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::note_cast_operand_to_int);
14290 }
14291 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
14292 /// Analyze the given comma operator. The basic idea behind the analysis
14293 /// is to analyze the left and right operands slightly differently. The
14294 /// left operand needs to check whether the operand itself has an implicit
14295 /// conversion, but not whether the left operand induces an implicit
14296 /// conversion for the entire comma expression itself. This is similar to
14297 /// how CheckConditionalOperand behaves; it's as-if the correct operand
14298 /// were directly used for the implicit conversion check.
14299 CheckCommaOperand(S, E: BO->getLHS(), T, CC: BO->getOperatorLoc(),
14300 /*ExtraCheckForImplicitConversion=*/false, WorkList);
14301 CheckCommaOperand(S, E: BO->getRHS(), T, CC: BO->getOperatorLoc(),
14302 /*ExtraCheckForImplicitConversion=*/true, WorkList);
14303 return;
14304 }
14305 }
14306
14307 // For conditional operators, we analyze the arguments as if they
14308 // were being fed directly into the output.
14309 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: SourceExpr)) {
14310 CheckConditionalOperator(S, E: CO, CC, T);
14311 return;
14312 }
14313
14314 // Check implicit argument conversions for function calls.
14315 if (const auto *Call = dyn_cast<CallExpr>(Val: SourceExpr))
14316 CheckImplicitArgumentConversions(S, TheCall: Call, CC);
14317
14318 // Go ahead and check any implicit conversions we might have skipped.
14319 // The non-canonical typecheck is just an optimization;
14320 // CheckImplicitConversion will filter out dead implicit conversions.
14321 if (SourceExpr->getType() != T)
14322 S.CheckImplicitConversion(E: SourceExpr, T, CC, ICContext: nullptr, IsListInit);
14323
14324 // Now continue drilling into this expression.
14325
14326 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E)) {
14327 // The bound subexpressions in a PseudoObjectExpr are not reachable
14328 // as transitive children.
14329 // FIXME: Use a more uniform representation for this.
14330 for (auto *SE : POE->semantics())
14331 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: SE))
14332 WorkList.push_back(Elt: {.E: OVE->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
14333 }
14334
14335 // Skip past explicit casts.
14336 if (auto *CE = dyn_cast<ExplicitCastExpr>(Val: E)) {
14337 E = CE->getSubExpr();
14338 // In the special case of a C++ function-style cast with braces,
14339 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
14340 // initializer. This InitListExpr basically belongs to the cast itself, so
14341 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
14342 if (isa<CXXFunctionalCastExpr>(Val: CE)) {
14343 if (auto *InitListE = dyn_cast<InitListExpr>(Val: E)) {
14344 if (InitListE->getNumInits() == 1) {
14345 E = InitListE->getInit(Init: 0);
14346 }
14347 }
14348 }
14349 E = E->IgnoreParenImpCasts();
14350 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14351 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
14352 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: IsListInit});
14353 return;
14354 }
14355
14356 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(Val: E)) {
14357 WorkList.push_back(Elt: {.E: OutArgE->getArgLValue(), .CC: CC, .IsListInit: IsListInit});
14358 // The base expression is only used to initialize the parameter for
14359 // arguments to `inout` parameters, so we only traverse down the base
14360 // expression for `inout` cases.
14361 if (OutArgE->isInOut())
14362 WorkList.push_back(
14363 Elt: {.E: OutArgE->getCastedTemporary()->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
14364 WorkList.push_back(Elt: {.E: OutArgE->getWritebackCast(), .CC: CC, .IsListInit: IsListInit});
14365 return;
14366 }
14367
14368 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
14369 // Do a somewhat different check with comparison operators.
14370 if (BO->isComparisonOp())
14371 return AnalyzeComparison(S, E: BO);
14372
14373 // And with simple assignments.
14374 if (BO->getOpcode() == BO_Assign)
14375 return AnalyzeAssignment(S, E: BO);
14376 // And with compound assignments.
14377 if (BO->isAssignmentOp())
14378 return AnalyzeCompoundAssignment(S, E: BO);
14379 }
14380
14381 // These break the otherwise-useful invariant below. Fortunately,
14382 // we don't really need to recurse into them, because any internal
14383 // expressions should have been analyzed already when they were
14384 // built into statements.
14385 if (isa<StmtExpr>(Val: E)) return;
14386
14387 // Don't descend into unevaluated contexts.
14388 if (isa<UnaryExprOrTypeTraitExpr>(Val: E)) return;
14389
14390 // Now just recurse over the expression's children.
14391 CC = E->getExprLoc();
14392 BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E);
14393 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14394 for (Stmt *SubStmt : E->children()) {
14395 Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: SubStmt);
14396 if (!ChildExpr)
14397 continue;
14398
14399 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(Val: E))
14400 if (ChildExpr == CSE->getOperand())
14401 // Do not recurse over a CoroutineSuspendExpr's operand.
14402 // The operand is also a subexpression of getCommonExpr(), and
14403 // recursing into it directly would produce duplicate diagnostics.
14404 continue;
14405
14406 if (IsLogicalAndOperator &&
14407 isa<StringLiteral>(Val: ChildExpr->IgnoreParenImpCasts()))
14408 // Ignore checking string literals that are in logical and operators.
14409 // This is a common pattern for asserts.
14410 continue;
14411 WorkList.push_back(Elt: {.E: ChildExpr, .CC: CC, .IsListInit: IsListInit});
14412 }
14413
14414 if (BO && BO->isLogicalOp()) {
14415 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14416 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
14417 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
14418
14419 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14420 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
14421 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
14422 }
14423
14424 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(Val: E)) {
14425 if (U->getOpcode() == UO_LNot) {
14426 ::CheckBoolLikeConversion(S, E: U->getSubExpr(), CC);
14427 } else if (U->getOpcode() != UO_AddrOf) {
14428 if (U->getSubExpr()->getType()->isAtomicType())
14429 S.Diag(Loc: U->getSubExpr()->getBeginLoc(),
14430 DiagID: diag::warn_atomic_implicit_seq_cst);
14431 }
14432 }
14433}
14434
14435/// AnalyzeImplicitConversions - Find and report any interesting
14436/// implicit conversions in the given expression. There are a couple
14437/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14438static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
14439 bool IsListInit/*= false*/) {
14440 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
14441 WorkList.push_back(Elt: {.E: OrigE, .CC: CC, .IsListInit: IsListInit});
14442 while (!WorkList.empty())
14443 AnalyzeImplicitConversions(S, Item: WorkList.pop_back_val(), WorkList);
14444}
14445
14446// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14447// Returns true when emitting a warning about taking the address of a reference.
14448static bool CheckForReference(Sema &SemaRef, const Expr *E,
14449 const PartialDiagnostic &PD) {
14450 E = E->IgnoreParenImpCasts();
14451
14452 const FunctionDecl *FD = nullptr;
14453
14454 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14455 if (!DRE->getDecl()->getType()->isReferenceType())
14456 return false;
14457 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
14458 if (!M->getMemberDecl()->getType()->isReferenceType())
14459 return false;
14460 } else if (const CallExpr *Call = dyn_cast<CallExpr>(Val: E)) {
14461 if (!Call->getCallReturnType(Ctx: SemaRef.Context)->isReferenceType())
14462 return false;
14463 FD = Call->getDirectCallee();
14464 } else {
14465 return false;
14466 }
14467
14468 SemaRef.Diag(Loc: E->getExprLoc(), PD);
14469
14470 // If possible, point to location of function.
14471 if (FD) {
14472 SemaRef.Diag(Loc: FD->getLocation(), DiagID: diag::note_reference_is_return_value) << FD;
14473 }
14474
14475 return true;
14476}
14477
14478// Returns true if the SourceLocation is expanded from any macro body.
14479// Returns false if the SourceLocation is invalid, is from not in a macro
14480// expansion, or is from expanded from a top-level macro argument.
14481static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
14482 if (Loc.isInvalid())
14483 return false;
14484
14485 while (Loc.isMacroID()) {
14486 if (SM.isMacroBodyExpansion(Loc))
14487 return true;
14488 Loc = SM.getImmediateMacroCallerLoc(Loc);
14489 }
14490
14491 return false;
14492}
14493
14494void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
14495 Expr::NullPointerConstantKind NullKind,
14496 bool IsEqual, SourceRange Range) {
14497 if (!E)
14498 return;
14499
14500 // Don't warn inside macros.
14501 if (E->getExprLoc().isMacroID()) {
14502 const SourceManager &SM = getSourceManager();
14503 if (IsInAnyMacroBody(SM, Loc: E->getExprLoc()) ||
14504 IsInAnyMacroBody(SM, Loc: Range.getBegin()))
14505 return;
14506 }
14507 E = E->IgnoreImpCasts();
14508
14509 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14510
14511 if (isa<CXXThisExpr>(Val: E)) {
14512 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14513 : diag::warn_this_bool_conversion;
14514 Diag(Loc: E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14515 return;
14516 }
14517
14518 bool IsAddressOf = false;
14519
14520 if (auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParens())) {
14521 if (UO->getOpcode() != UO_AddrOf)
14522 return;
14523 IsAddressOf = true;
14524 E = UO->getSubExpr();
14525 }
14526
14527 if (IsAddressOf) {
14528 unsigned DiagID = IsCompare
14529 ? diag::warn_address_of_reference_null_compare
14530 : diag::warn_address_of_reference_bool_conversion;
14531 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14532 << IsEqual;
14533 if (CheckForReference(SemaRef&: *this, E, PD)) {
14534 return;
14535 }
14536 }
14537
14538 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14539 bool IsParam = isa<NonNullAttr>(Val: NonnullAttr);
14540 std::string Str;
14541 llvm::raw_string_ostream S(Str);
14542 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
14543 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14544 : diag::warn_cast_nonnull_to_bool;
14545 Diag(Loc: E->getExprLoc(), DiagID) << IsParam << S.str()
14546 << E->getSourceRange() << Range << IsEqual;
14547 Diag(Loc: NonnullAttr->getLocation(), DiagID: diag::note_declared_nonnull) << IsParam;
14548 };
14549
14550 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14551 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts())) {
14552 if (auto *Callee = Call->getDirectCallee()) {
14553 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14554 ComplainAboutNonnullParamOrCall(A);
14555 return;
14556 }
14557 }
14558 }
14559
14560 // Complain if we are converting a lambda expression to a boolean value
14561 // outside of instantiation.
14562 if (!inTemplateInstantiation()) {
14563 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(Val: E)) {
14564 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14565 MRecordDecl && MRecordDecl->isLambda()) {
14566 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_impcast_pointer_to_bool)
14567 << /*LambdaPointerConversionOperatorType=*/3
14568 << MRecordDecl->getSourceRange() << Range << IsEqual;
14569 return;
14570 }
14571 }
14572 }
14573
14574 // Expect to find a single Decl. Skip anything more complicated.
14575 ValueDecl *D = nullptr;
14576 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(Val: E)) {
14577 D = R->getDecl();
14578 } else if (MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
14579 D = M->getMemberDecl();
14580 }
14581
14582 // Weak Decls can be null.
14583 if (!D || D->isWeak())
14584 return;
14585
14586 // Check for parameter decl with nonnull attribute
14587 if (const auto* PV = dyn_cast<ParmVarDecl>(Val: D)) {
14588 if (getCurFunction() &&
14589 !getCurFunction()->ModifiedNonNullParams.count(Ptr: PV)) {
14590 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14591 ComplainAboutNonnullParamOrCall(A);
14592 return;
14593 }
14594
14595 if (const auto *FD = dyn_cast<FunctionDecl>(Val: PV->getDeclContext())) {
14596 // Skip function template not specialized yet.
14597 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
14598 return;
14599 auto ParamIter = llvm::find(Range: FD->parameters(), Val: PV);
14600 assert(ParamIter != FD->param_end());
14601 unsigned ParamNo = std::distance(first: FD->param_begin(), last: ParamIter);
14602
14603 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14604 if (!NonNull->args_size()) {
14605 ComplainAboutNonnullParamOrCall(NonNull);
14606 return;
14607 }
14608
14609 for (const ParamIdx &ArgNo : NonNull->args()) {
14610 if (ArgNo.getASTIndex() == ParamNo) {
14611 ComplainAboutNonnullParamOrCall(NonNull);
14612 return;
14613 }
14614 }
14615 }
14616 }
14617 }
14618 }
14619
14620 QualType T = D->getType();
14621 // A reference to a function is never null either; look through it.
14622 const bool IsFunctionReference =
14623 T->isReferenceType() && T->getPointeeType()->isFunctionType();
14624 if (IsFunctionReference)
14625 T = T->getPointeeType();
14626 const bool IsArray = T->isArrayType();
14627 const bool IsFunction = T->isFunctionType();
14628
14629 // Address of function is used to silence the function warning.
14630 if (IsAddressOf && IsFunction) {
14631 return;
14632 }
14633
14634 // Found nothing.
14635 if (!IsAddressOf && !IsFunction && !IsArray)
14636 return;
14637
14638 // Pretty print the expression for the diagnostic.
14639 std::string Str;
14640 llvm::raw_string_ostream S(Str);
14641 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
14642
14643 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14644 : diag::warn_impcast_pointer_to_bool;
14645 enum {
14646 AddressOf,
14647 FunctionPointer,
14648 ArrayPointer
14649 } DiagType;
14650 if (IsAddressOf)
14651 DiagType = AddressOf;
14652 else if (IsFunction)
14653 DiagType = FunctionPointer;
14654 else if (IsArray)
14655 DiagType = ArrayPointer;
14656 else
14657 llvm_unreachable("Could not determine diagnostic.");
14658 Diag(Loc: E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14659 << Range << IsEqual;
14660
14661 // The fix-it notes below only apply to a bare function name, not a reference.
14662 if (!IsFunction || IsFunctionReference)
14663 return;
14664
14665 // Suggest '&' to silence the function warning.
14666 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_warning_silence)
14667 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "&");
14668
14669 // Check to see if '()' fixit should be emitted.
14670 QualType ReturnType;
14671 UnresolvedSet<4> NonTemplateOverloads;
14672 tryExprAsCall(E&: *E, ZeroArgCallReturnTy&: ReturnType, NonTemplateOverloads);
14673 if (ReturnType.isNull())
14674 return;
14675
14676 if (IsCompare) {
14677 // There are two cases here. If there is null constant, the only suggest
14678 // for a pointer return type. If the null is 0, then suggest if the return
14679 // type is a pointer or an integer type.
14680 if (!ReturnType->isPointerType()) {
14681 if (NullKind == Expr::NPCK_ZeroExpression ||
14682 NullKind == Expr::NPCK_ZeroLiteral) {
14683 if (!ReturnType->isIntegerType())
14684 return;
14685 } else {
14686 return;
14687 }
14688 }
14689 } else { // !IsCompare
14690 // For function to bool, only suggest if the function pointer has bool
14691 // return type.
14692 if (!ReturnType->isSpecificBuiltinType(K: BuiltinType::Bool))
14693 return;
14694 }
14695 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_to_function_call)
14696 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: E->getEndLoc()), Code: "()");
14697}
14698
14699bool Sema::CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
14700 SourceLocation CC) {
14701 QualType Source = E->getType();
14702 QualType Target = T;
14703
14704 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14705 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14706 // Overflow behavior type is being stripped - issue warning
14707 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14708 Target->isUnsignedIntegerType()) {
14709 // For unsigned wrap to unsigned conversions, use pedantic version
14710 unsigned DiagId =
14711 InOverflowBehaviorAssignmentContext
14712 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14713 : diag::warn_impcast_overflow_behavior_pedantic;
14714 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14715 } else {
14716 unsigned DiagId = InOverflowBehaviorAssignmentContext
14717 ? diag::warn_impcast_overflow_behavior_assignment
14718 : diag::warn_impcast_overflow_behavior;
14719 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14720 }
14721 }
14722 }
14723
14724 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14725 if (TargetOBT->isWrapKind()) {
14726 return true;
14727 }
14728 }
14729
14730 return false;
14731}
14732
14733void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14734 // Don't diagnose in unevaluated contexts.
14735 if (isUnevaluatedContext())
14736 return;
14737
14738 // Don't diagnose for value- or type-dependent expressions.
14739 if (E->isTypeDependent() || E->isValueDependent())
14740 return;
14741
14742 // Check for array bounds violations in cases where the check isn't triggered
14743 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14744 // ArraySubscriptExpr is on the RHS of a variable initialization.
14745 CheckArrayAccess(E);
14746
14747 // This is not the right CC for (e.g.) a variable initialization.
14748 AnalyzeImplicitConversions(S&: *this, OrigE: E, CC);
14749}
14750
14751void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14752 ::CheckBoolLikeConversion(S&: *this, E, CC);
14753}
14754
14755void Sema::CheckForIntOverflow (const Expr *E) {
14756 // Use a work list to deal with nested struct initializers.
14757 SmallVector<const Expr *, 2> Exprs(1, E);
14758
14759 do {
14760 const Expr *OriginalE = Exprs.pop_back_val();
14761 const Expr *E = OriginalE->IgnoreParenCasts();
14762
14763 if (isa<BinaryOperator>(Val: E) ||
14764 (isa<UnaryOperator>(Val: E) && cast<UnaryOperator>(Val: E)->canOverflow())) {
14765 E->EvaluateForOverflow(Ctx: Context);
14766 continue;
14767 }
14768
14769 if (const auto *InitList = dyn_cast<InitListExpr>(Val: OriginalE))
14770 Exprs.append(in_start: InitList->inits().begin(), in_end: InitList->inits().end());
14771 else if (isa<ObjCBoxedExpr>(Val: OriginalE))
14772 E->EvaluateForOverflow(Ctx: Context);
14773 else if (const auto *Call = dyn_cast<CallExpr>(Val: E))
14774 Exprs.append(in_start: Call->arg_begin(), in_end: Call->arg_end());
14775 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(Val: E))
14776 Exprs.append(in_start: Message->arg_begin(), in_end: Message->arg_end());
14777 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(Val: E))
14778 Exprs.append(in_start: Construct->arg_begin(), in_end: Construct->arg_end());
14779 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(Val: E))
14780 Exprs.push_back(Elt: Temporary->getSubExpr());
14781 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(Val: E))
14782 Exprs.push_back(Elt: Array->getIdx());
14783 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(Val: E))
14784 Exprs.push_back(Elt: Compound->getInitializer());
14785 else if (const auto *New = dyn_cast<CXXNewExpr>(Val: E);
14786 New && New->isArray()) {
14787 if (auto ArraySize = New->getArraySize())
14788 Exprs.push_back(Elt: *ArraySize);
14789 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: OriginalE))
14790 Exprs.push_back(Elt: MTE->getSubExpr());
14791 } while (!Exprs.empty());
14792}
14793
14794namespace {
14795
14796/// Visitor for expressions which looks for unsequenced operations on the
14797/// same object.
14798class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14799 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14800
14801 /// A tree of sequenced regions within an expression. Two regions are
14802 /// unsequenced if one is an ancestor or a descendent of the other. When we
14803 /// finish processing an expression with sequencing, such as a comma
14804 /// expression, we fold its tree nodes into its parent, since they are
14805 /// unsequenced with respect to nodes we will visit later.
14806 class SequenceTree {
14807 struct Value {
14808 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14809 unsigned Parent : 31;
14810 LLVM_PREFERRED_TYPE(bool)
14811 unsigned Merged : 1;
14812 };
14813 SmallVector<Value, 8> Values;
14814
14815 public:
14816 /// A region within an expression which may be sequenced with respect
14817 /// to some other region.
14818 class Seq {
14819 friend class SequenceTree;
14820
14821 unsigned Index;
14822
14823 explicit Seq(unsigned N) : Index(N) {}
14824
14825 public:
14826 Seq() : Index(0) {}
14827 };
14828
14829 SequenceTree() { Values.push_back(Elt: Value(0)); }
14830 Seq root() const { return Seq(0); }
14831
14832 /// Create a new sequence of operations, which is an unsequenced
14833 /// subset of \p Parent. This sequence of operations is sequenced with
14834 /// respect to other children of \p Parent.
14835 Seq allocate(Seq Parent) {
14836 Values.push_back(Elt: Value(Parent.Index));
14837 return Seq(Values.size() - 1);
14838 }
14839
14840 /// Merge a sequence of operations into its parent.
14841 void merge(Seq S) {
14842 Values[S.Index].Merged = true;
14843 }
14844
14845 /// Determine whether two operations are unsequenced. This operation
14846 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14847 /// should have been merged into its parent as appropriate.
14848 bool isUnsequenced(Seq Cur, Seq Old) {
14849 unsigned C = representative(K: Cur.Index);
14850 unsigned Target = representative(K: Old.Index);
14851 while (C >= Target) {
14852 if (C == Target)
14853 return true;
14854 C = Values[C].Parent;
14855 }
14856 return false;
14857 }
14858
14859 private:
14860 /// Pick a representative for a sequence.
14861 unsigned representative(unsigned K) {
14862 if (Values[K].Merged)
14863 // Perform path compression as we go.
14864 return Values[K].Parent = representative(K: Values[K].Parent);
14865 return K;
14866 }
14867 };
14868
14869 /// An object for which we can track unsequenced uses.
14870 using Object = const NamedDecl *;
14871
14872 /// Different flavors of object usage which we track. We only track the
14873 /// least-sequenced usage of each kind.
14874 enum UsageKind {
14875 /// A read of an object. Multiple unsequenced reads are OK.
14876 UK_Use,
14877
14878 /// A modification of an object which is sequenced before the value
14879 /// computation of the expression, such as ++n in C++.
14880 UK_ModAsValue,
14881
14882 /// A modification of an object which is not sequenced before the value
14883 /// computation of the expression, such as n++.
14884 UK_ModAsSideEffect,
14885
14886 UK_Count = UK_ModAsSideEffect + 1
14887 };
14888
14889 /// Bundle together a sequencing region and the expression corresponding
14890 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14891 struct Usage {
14892 const Expr *UsageExpr = nullptr;
14893 SequenceTree::Seq Seq;
14894
14895 Usage() = default;
14896 };
14897
14898 struct UsageInfo {
14899 Usage Uses[UK_Count];
14900
14901 /// Have we issued a diagnostic for this object already?
14902 bool Diagnosed = false;
14903
14904 UsageInfo();
14905 };
14906 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14907
14908 Sema &SemaRef;
14909
14910 /// Sequenced regions within the expression.
14911 SequenceTree Tree;
14912
14913 /// Declaration modifications and references which we have seen.
14914 UsageInfoMap UsageMap;
14915
14916 /// The region we are currently within.
14917 SequenceTree::Seq Region;
14918
14919 /// Filled in with declarations which were modified as a side-effect
14920 /// (that is, post-increment operations).
14921 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14922
14923 /// Expressions to check later. We defer checking these to reduce
14924 /// stack usage.
14925 SmallVectorImpl<const Expr *> &WorkList;
14926
14927 /// RAII object wrapping the visitation of a sequenced subexpression of an
14928 /// expression. At the end of this process, the side-effects of the evaluation
14929 /// become sequenced with respect to the value computation of the result, so
14930 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14931 /// UK_ModAsValue.
14932 struct SequencedSubexpression {
14933 SequencedSubexpression(SequenceChecker &Self)
14934 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14935 Self.ModAsSideEffect = &ModAsSideEffect;
14936 }
14937
14938 ~SequencedSubexpression() {
14939 for (const std::pair<Object, Usage> &M : llvm::reverse(C&: ModAsSideEffect)) {
14940 // Add a new usage with usage kind UK_ModAsValue, and then restore
14941 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14942 // the previous one was empty).
14943 UsageInfo &UI = Self.UsageMap[M.first];
14944 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14945 Self.addUsage(O: M.first, UI, UsageExpr: SideEffectUsage.UsageExpr, UK: UK_ModAsValue);
14946 SideEffectUsage = M.second;
14947 }
14948 Self.ModAsSideEffect = OldModAsSideEffect;
14949 }
14950
14951 SequenceChecker &Self;
14952 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14953 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14954 };
14955
14956 /// RAII object wrapping the visitation of a subexpression which we might
14957 /// choose to evaluate as a constant. If any subexpression is evaluated and
14958 /// found to be non-constant, this allows us to suppress the evaluation of
14959 /// the outer expression.
14960 class EvaluationTracker {
14961 public:
14962 EvaluationTracker(SequenceChecker &Self)
14963 : Self(Self), Prev(Self.EvalTracker) {
14964 Self.EvalTracker = this;
14965 }
14966
14967 ~EvaluationTracker() {
14968 Self.EvalTracker = Prev;
14969 if (Prev)
14970 Prev->EvalOK &= EvalOK;
14971 }
14972
14973 bool evaluate(const Expr *E, bool &Result) {
14974 if (!EvalOK || E->isValueDependent())
14975 return false;
14976 EvalOK = E->EvaluateAsBooleanCondition(
14977 Result, Ctx: Self.SemaRef.Context,
14978 InConstantContext: Self.SemaRef.isConstantEvaluatedContext());
14979 return EvalOK;
14980 }
14981
14982 private:
14983 SequenceChecker &Self;
14984 EvaluationTracker *Prev;
14985 bool EvalOK = true;
14986 } *EvalTracker = nullptr;
14987
14988 /// Find the object which is produced by the specified expression,
14989 /// if any.
14990 Object getObject(const Expr *E, bool Mod) const {
14991 E = E->IgnoreParenCasts();
14992 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) {
14993 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14994 return getObject(E: UO->getSubExpr(), Mod);
14995 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
14996 if (BO->getOpcode() == BO_Comma)
14997 return getObject(E: BO->getRHS(), Mod);
14998 if (Mod && BO->isAssignmentOp())
14999 return getObject(E: BO->getLHS(), Mod);
15000 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
15001 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
15002 if (isa<CXXThisExpr>(Val: ME->getBase()->IgnoreParenCasts()))
15003 return ME->getMemberDecl();
15004 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
15005 // FIXME: If this is a reference, map through to its value.
15006 return DRE->getDecl();
15007 return nullptr;
15008 }
15009
15010 /// Note that an object \p O was modified or used by an expression
15011 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
15012 /// the object \p O as obtained via the \p UsageMap.
15013 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
15014 // Get the old usage for the given object and usage kind.
15015 Usage &U = UI.Uses[UK];
15016 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq)) {
15017 // If we have a modification as side effect and are in a sequenced
15018 // subexpression, save the old Usage so that we can restore it later
15019 // in SequencedSubexpression::~SequencedSubexpression.
15020 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
15021 ModAsSideEffect->push_back(Elt: std::make_pair(x&: O, y&: U));
15022 // Then record the new usage with the current sequencing region.
15023 U.UsageExpr = UsageExpr;
15024 U.Seq = Region;
15025 }
15026 }
15027
15028 /// Check whether a modification or use of an object \p O in an expression
15029 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
15030 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
15031 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
15032 /// usage and false we are checking for a mod-use unsequenced usage.
15033 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
15034 UsageKind OtherKind, bool IsModMod) {
15035 if (UI.Diagnosed)
15036 return;
15037
15038 const Usage &U = UI.Uses[OtherKind];
15039 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq))
15040 return;
15041
15042 const Expr *Mod = U.UsageExpr;
15043 const Expr *ModOrUse = UsageExpr;
15044 if (OtherKind == UK_Use)
15045 std::swap(a&: Mod, b&: ModOrUse);
15046
15047 SemaRef.DiagRuntimeBehavior(
15048 Loc: Mod->getExprLoc(), Stmts: {Mod, ModOrUse},
15049 PD: SemaRef.PDiag(DiagID: IsModMod ? diag::warn_unsequenced_mod_mod
15050 : diag::warn_unsequenced_mod_use)
15051 << O << SourceRange(ModOrUse->getExprLoc()));
15052 UI.Diagnosed = true;
15053 }
15054
15055 // A note on note{Pre, Post}{Use, Mod}:
15056 //
15057 // (It helps to follow the algorithm with an expression such as
15058 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
15059 // operations before C++17 and both are well-defined in C++17).
15060 //
15061 // When visiting a node which uses/modify an object we first call notePreUse
15062 // or notePreMod before visiting its sub-expression(s). At this point the
15063 // children of the current node have not yet been visited and so the eventual
15064 // uses/modifications resulting from the children of the current node have not
15065 // been recorded yet.
15066 //
15067 // We then visit the children of the current node. After that notePostUse or
15068 // notePostMod is called. These will 1) detect an unsequenced modification
15069 // as side effect (as in "k++ + k") and 2) add a new usage with the
15070 // appropriate usage kind.
15071 //
15072 // We also have to be careful that some operation sequences modification as
15073 // side effect as well (for example: || or ,). To account for this we wrap
15074 // the visitation of such a sub-expression (for example: the LHS of || or ,)
15075 // with SequencedSubexpression. SequencedSubexpression is an RAII object
15076 // which record usages which are modifications as side effect, and then
15077 // downgrade them (or more accurately restore the previous usage which was a
15078 // modification as side effect) when exiting the scope of the sequenced
15079 // subexpression.
15080
15081 void notePreUse(Object O, const Expr *UseExpr) {
15082 UsageInfo &UI = UsageMap[O];
15083 // Uses conflict with other modifications.
15084 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
15085 }
15086
15087 void notePostUse(Object O, const Expr *UseExpr) {
15088 UsageInfo &UI = UsageMap[O];
15089 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
15090 /*IsModMod=*/false);
15091 addUsage(O, UI, UsageExpr: UseExpr, /*UsageKind=*/UK: UK_Use);
15092 }
15093
15094 void notePreMod(Object O, const Expr *ModExpr) {
15095 UsageInfo &UI = UsageMap[O];
15096 // Modifications conflict with other modifications and with uses.
15097 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
15098 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
15099 }
15100
15101 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
15102 UsageInfo &UI = UsageMap[O];
15103 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
15104 /*IsModMod=*/true);
15105 addUsage(O, UI, UsageExpr: ModExpr, /*UsageKind=*/UK);
15106 }
15107
15108public:
15109 SequenceChecker(Sema &S, const Expr *E,
15110 SmallVectorImpl<const Expr *> &WorkList)
15111 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
15112 Visit(S: E);
15113 // Silence a -Wunused-private-field since WorkList is now unused.
15114 // TODO: Evaluate if it can be used, and if not remove it.
15115 (void)this->WorkList;
15116 }
15117
15118 void VisitStmt(const Stmt *S) {
15119 // Skip all statements which aren't expressions for now.
15120 }
15121
15122 void VisitExpr(const Expr *E) {
15123 // By default, just recurse to evaluated subexpressions.
15124 Base::VisitStmt(S: E);
15125 }
15126
15127 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
15128 for (auto *Sub : CSE->children()) {
15129 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: Sub);
15130 if (!ChildExpr)
15131 continue;
15132
15133 if (ChildExpr == CSE->getOperand())
15134 // Do not recurse over a CoroutineSuspendExpr's operand.
15135 // The operand is also a subexpression of getCommonExpr(), and
15136 // recursing into it directly could confuse object management
15137 // for the sake of sequence tracking.
15138 continue;
15139
15140 Visit(S: Sub);
15141 }
15142 }
15143
15144 void VisitCastExpr(const CastExpr *E) {
15145 Object O = Object();
15146 if (E->getCastKind() == CK_LValueToRValue)
15147 O = getObject(E: E->getSubExpr(), Mod: false);
15148
15149 if (O)
15150 notePreUse(O, UseExpr: E);
15151 VisitExpr(E);
15152 if (O)
15153 notePostUse(O, UseExpr: E);
15154 }
15155
15156 void VisitSequencedExpressions(const Expr *SequencedBefore,
15157 const Expr *SequencedAfter) {
15158 SequenceTree::Seq BeforeRegion = Tree.allocate(Parent: Region);
15159 SequenceTree::Seq AfterRegion = Tree.allocate(Parent: Region);
15160 SequenceTree::Seq OldRegion = Region;
15161
15162 {
15163 SequencedSubexpression SeqBefore(*this);
15164 Region = BeforeRegion;
15165 Visit(S: SequencedBefore);
15166 }
15167
15168 Region = AfterRegion;
15169 Visit(S: SequencedAfter);
15170
15171 Region = OldRegion;
15172
15173 Tree.merge(S: BeforeRegion);
15174 Tree.merge(S: AfterRegion);
15175 }
15176
15177 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
15178 // C++17 [expr.sub]p1:
15179 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
15180 // expression E1 is sequenced before the expression E2.
15181 if (SemaRef.getLangOpts().CPlusPlus17)
15182 VisitSequencedExpressions(SequencedBefore: ASE->getLHS(), SequencedAfter: ASE->getRHS());
15183 else {
15184 Visit(S: ASE->getLHS());
15185 Visit(S: ASE->getRHS());
15186 }
15187 }
15188
15189 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15190 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15191 void VisitBinPtrMem(const BinaryOperator *BO) {
15192 // C++17 [expr.mptr.oper]p4:
15193 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
15194 // the expression E1 is sequenced before the expression E2.
15195 if (SemaRef.getLangOpts().CPlusPlus17)
15196 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
15197 else {
15198 Visit(S: BO->getLHS());
15199 Visit(S: BO->getRHS());
15200 }
15201 }
15202
15203 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15204 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
15205 void VisitBinShlShr(const BinaryOperator *BO) {
15206 // C++17 [expr.shift]p4:
15207 // The expression E1 is sequenced before the expression E2.
15208 if (SemaRef.getLangOpts().CPlusPlus17)
15209 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
15210 else {
15211 Visit(S: BO->getLHS());
15212 Visit(S: BO->getRHS());
15213 }
15214 }
15215
15216 void VisitBinComma(const BinaryOperator *BO) {
15217 // C++11 [expr.comma]p1:
15218 // Every value computation and side effect associated with the left
15219 // expression is sequenced before every value computation and side
15220 // effect associated with the right expression.
15221 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
15222 }
15223
15224 void VisitBinAssign(const BinaryOperator *BO) {
15225 SequenceTree::Seq RHSRegion;
15226 SequenceTree::Seq LHSRegion;
15227 if (SemaRef.getLangOpts().CPlusPlus17) {
15228 RHSRegion = Tree.allocate(Parent: Region);
15229 LHSRegion = Tree.allocate(Parent: Region);
15230 } else {
15231 RHSRegion = Region;
15232 LHSRegion = Region;
15233 }
15234 SequenceTree::Seq OldRegion = Region;
15235
15236 // C++11 [expr.ass]p1:
15237 // [...] the assignment is sequenced after the value computation
15238 // of the right and left operands, [...]
15239 //
15240 // so check it before inspecting the operands and update the
15241 // map afterwards.
15242 Object O = getObject(E: BO->getLHS(), /*Mod=*/true);
15243 if (O)
15244 notePreMod(O, ModExpr: BO);
15245
15246 if (SemaRef.getLangOpts().CPlusPlus17) {
15247 // C++17 [expr.ass]p1:
15248 // [...] The right operand is sequenced before the left operand. [...]
15249 {
15250 SequencedSubexpression SeqBefore(*this);
15251 Region = RHSRegion;
15252 Visit(S: BO->getRHS());
15253 }
15254
15255 Region = LHSRegion;
15256 Visit(S: BO->getLHS());
15257
15258 if (O && isa<CompoundAssignOperator>(Val: BO))
15259 notePostUse(O, UseExpr: BO);
15260
15261 } else {
15262 // C++11 does not specify any sequencing between the LHS and RHS.
15263 Region = LHSRegion;
15264 Visit(S: BO->getLHS());
15265
15266 if (O && isa<CompoundAssignOperator>(Val: BO))
15267 notePostUse(O, UseExpr: BO);
15268
15269 Region = RHSRegion;
15270 Visit(S: BO->getRHS());
15271 }
15272
15273 // C++11 [expr.ass]p1:
15274 // the assignment is sequenced [...] before the value computation of the
15275 // assignment expression.
15276 // C11 6.5.16/3 has no such rule.
15277 Region = OldRegion;
15278 if (O)
15279 notePostMod(O, ModExpr: BO,
15280 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15281 : UK_ModAsSideEffect);
15282 if (SemaRef.getLangOpts().CPlusPlus17) {
15283 Tree.merge(S: RHSRegion);
15284 Tree.merge(S: LHSRegion);
15285 }
15286 }
15287
15288 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
15289 VisitBinAssign(BO: CAO);
15290 }
15291
15292 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15293 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15294 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
15295 Object O = getObject(E: UO->getSubExpr(), Mod: true);
15296 if (!O)
15297 return VisitExpr(E: UO);
15298
15299 notePreMod(O, ModExpr: UO);
15300 Visit(S: UO->getSubExpr());
15301 // C++11 [expr.pre.incr]p1:
15302 // the expression ++x is equivalent to x+=1
15303 notePostMod(O, ModExpr: UO,
15304 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15305 : UK_ModAsSideEffect);
15306 }
15307
15308 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15309 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15310 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
15311 Object O = getObject(E: UO->getSubExpr(), Mod: true);
15312 if (!O)
15313 return VisitExpr(E: UO);
15314
15315 notePreMod(O, ModExpr: UO);
15316 Visit(S: UO->getSubExpr());
15317 notePostMod(O, ModExpr: UO, UK: UK_ModAsSideEffect);
15318 }
15319
15320 void VisitBinLOr(const BinaryOperator *BO) {
15321 // C++11 [expr.log.or]p2:
15322 // If the second expression is evaluated, every value computation and
15323 // side effect associated with the first expression is sequenced before
15324 // every value computation and side effect associated with the
15325 // second expression.
15326 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
15327 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
15328 SequenceTree::Seq OldRegion = Region;
15329
15330 EvaluationTracker Eval(*this);
15331 {
15332 SequencedSubexpression Sequenced(*this);
15333 Region = LHSRegion;
15334 Visit(S: BO->getLHS());
15335 }
15336
15337 // C++11 [expr.log.or]p1:
15338 // [...] the second operand is not evaluated if the first operand
15339 // evaluates to true.
15340 bool EvalResult = false;
15341 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
15342 bool ShouldVisitRHS = !EvalOK || !EvalResult;
15343 if (ShouldVisitRHS) {
15344 Region = RHSRegion;
15345 Visit(S: BO->getRHS());
15346 }
15347
15348 Region = OldRegion;
15349 Tree.merge(S: LHSRegion);
15350 Tree.merge(S: RHSRegion);
15351 }
15352
15353 void VisitBinLAnd(const BinaryOperator *BO) {
15354 // C++11 [expr.log.and]p2:
15355 // If the second expression is evaluated, every value computation and
15356 // side effect associated with the first expression is sequenced before
15357 // every value computation and side effect associated with the
15358 // second expression.
15359 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
15360 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
15361 SequenceTree::Seq OldRegion = Region;
15362
15363 EvaluationTracker Eval(*this);
15364 {
15365 SequencedSubexpression Sequenced(*this);
15366 Region = LHSRegion;
15367 Visit(S: BO->getLHS());
15368 }
15369
15370 // C++11 [expr.log.and]p1:
15371 // [...] the second operand is not evaluated if the first operand is false.
15372 bool EvalResult = false;
15373 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
15374 bool ShouldVisitRHS = !EvalOK || EvalResult;
15375 if (ShouldVisitRHS) {
15376 Region = RHSRegion;
15377 Visit(S: BO->getRHS());
15378 }
15379
15380 Region = OldRegion;
15381 Tree.merge(S: LHSRegion);
15382 Tree.merge(S: RHSRegion);
15383 }
15384
15385 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15386 // C++11 [expr.cond]p1:
15387 // [...] Every value computation and side effect associated with the first
15388 // expression is sequenced before every value computation and side effect
15389 // associated with the second or third expression.
15390 SequenceTree::Seq ConditionRegion = Tree.allocate(Parent: Region);
15391
15392 // No sequencing is specified between the true and false expression.
15393 // However since exactly one of both is going to be evaluated we can
15394 // consider them to be sequenced. This is needed to avoid warning on
15395 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15396 // both the true and false expressions because we can't evaluate x.
15397 // This will still allow us to detect an expression like (pre C++17)
15398 // "(x ? y += 1 : y += 2) = y".
15399 //
15400 // We don't wrap the visitation of the true and false expression with
15401 // SequencedSubexpression because we don't want to downgrade modifications
15402 // as side effect in the true and false expressions after the visition
15403 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15404 // not warn between the two "y++", but we should warn between the "y++"
15405 // and the "y".
15406 SequenceTree::Seq TrueRegion = Tree.allocate(Parent: Region);
15407 SequenceTree::Seq FalseRegion = Tree.allocate(Parent: Region);
15408 SequenceTree::Seq OldRegion = Region;
15409
15410 EvaluationTracker Eval(*this);
15411 {
15412 SequencedSubexpression Sequenced(*this);
15413 Region = ConditionRegion;
15414 Visit(S: CO->getCond());
15415 }
15416
15417 // C++11 [expr.cond]p1:
15418 // [...] The first expression is contextually converted to bool (Clause 4).
15419 // It is evaluated and if it is true, the result of the conditional
15420 // expression is the value of the second expression, otherwise that of the
15421 // third expression. Only one of the second and third expressions is
15422 // evaluated. [...]
15423 bool EvalResult = false;
15424 bool EvalOK = Eval.evaluate(E: CO->getCond(), Result&: EvalResult);
15425 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15426 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15427 if (ShouldVisitTrueExpr) {
15428 Region = TrueRegion;
15429 Visit(S: CO->getTrueExpr());
15430 }
15431 if (ShouldVisitFalseExpr) {
15432 Region = FalseRegion;
15433 Visit(S: CO->getFalseExpr());
15434 }
15435
15436 Region = OldRegion;
15437 Tree.merge(S: ConditionRegion);
15438 Tree.merge(S: TrueRegion);
15439 Tree.merge(S: FalseRegion);
15440 }
15441
15442 void VisitCallExpr(const CallExpr *CE) {
15443 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15444
15445 if (CE->isUnevaluatedBuiltinCall(Ctx: Context))
15446 return;
15447
15448 // C++11 [intro.execution]p15:
15449 // When calling a function [...], every value computation and side effect
15450 // associated with any argument expression, or with the postfix expression
15451 // designating the called function, is sequenced before execution of every
15452 // expression or statement in the body of the function [and thus before
15453 // the value computation of its result].
15454 SequencedSubexpression Sequenced(*this);
15455 SemaRef.runWithSufficientStackSpace(Loc: CE->getExprLoc(), Fn: [&] {
15456 // C++17 [expr.call]p5
15457 // The postfix-expression is sequenced before each expression in the
15458 // expression-list and any default argument. [...]
15459 SequenceTree::Seq CalleeRegion;
15460 SequenceTree::Seq OtherRegion;
15461 if (SemaRef.getLangOpts().CPlusPlus17) {
15462 CalleeRegion = Tree.allocate(Parent: Region);
15463 OtherRegion = Tree.allocate(Parent: Region);
15464 } else {
15465 CalleeRegion = Region;
15466 OtherRegion = Region;
15467 }
15468 SequenceTree::Seq OldRegion = Region;
15469
15470 // Visit the callee expression first.
15471 Region = CalleeRegion;
15472 if (SemaRef.getLangOpts().CPlusPlus17) {
15473 SequencedSubexpression Sequenced(*this);
15474 Visit(S: CE->getCallee());
15475 } else {
15476 Visit(S: CE->getCallee());
15477 }
15478
15479 // Then visit the argument expressions.
15480 Region = OtherRegion;
15481 for (const Expr *Argument : CE->arguments())
15482 Visit(S: Argument);
15483
15484 Region = OldRegion;
15485 if (SemaRef.getLangOpts().CPlusPlus17) {
15486 Tree.merge(S: CalleeRegion);
15487 Tree.merge(S: OtherRegion);
15488 }
15489 });
15490 }
15491
15492 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15493 // C++17 [over.match.oper]p2:
15494 // [...] the operator notation is first transformed to the equivalent
15495 // function-call notation as summarized in Table 12 (where @ denotes one
15496 // of the operators covered in the specified subclause). However, the
15497 // operands are sequenced in the order prescribed for the built-in
15498 // operator (Clause 8).
15499 //
15500 // From the above only overloaded binary operators and overloaded call
15501 // operators have sequencing rules in C++17 that we need to handle
15502 // separately.
15503 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15504 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15505 return VisitCallExpr(CE: CXXOCE);
15506
15507 enum {
15508 NoSequencing,
15509 LHSBeforeRHS,
15510 RHSBeforeLHS,
15511 LHSBeforeRest
15512 } SequencingKind;
15513 switch (CXXOCE->getOperator()) {
15514 case OO_Equal:
15515 case OO_PlusEqual:
15516 case OO_MinusEqual:
15517 case OO_StarEqual:
15518 case OO_SlashEqual:
15519 case OO_PercentEqual:
15520 case OO_CaretEqual:
15521 case OO_AmpEqual:
15522 case OO_PipeEqual:
15523 case OO_LessLessEqual:
15524 case OO_GreaterGreaterEqual:
15525 SequencingKind = RHSBeforeLHS;
15526 break;
15527
15528 case OO_LessLess:
15529 case OO_GreaterGreater:
15530 case OO_AmpAmp:
15531 case OO_PipePipe:
15532 case OO_Comma:
15533 case OO_ArrowStar:
15534 case OO_Subscript:
15535 SequencingKind = LHSBeforeRHS;
15536 break;
15537
15538 case OO_Call:
15539 SequencingKind = LHSBeforeRest;
15540 break;
15541
15542 default:
15543 SequencingKind = NoSequencing;
15544 break;
15545 }
15546
15547 if (SequencingKind == NoSequencing)
15548 return VisitCallExpr(CE: CXXOCE);
15549
15550 // This is a call, so all subexpressions are sequenced before the result.
15551 SequencedSubexpression Sequenced(*this);
15552
15553 SemaRef.runWithSufficientStackSpace(Loc: CXXOCE->getExprLoc(), Fn: [&] {
15554 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15555 "Should only get there with C++17 and above!");
15556 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15557 "Should only get there with an overloaded binary operator"
15558 " or an overloaded call operator!");
15559
15560 if (SequencingKind == LHSBeforeRest) {
15561 assert(CXXOCE->getOperator() == OO_Call &&
15562 "We should only have an overloaded call operator here!");
15563
15564 // This is very similar to VisitCallExpr, except that we only have the
15565 // C++17 case. The postfix-expression is the first argument of the
15566 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15567 // are in the following arguments.
15568 //
15569 // Note that we intentionally do not visit the callee expression since
15570 // it is just a decayed reference to a function.
15571 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Parent: Region);
15572 SequenceTree::Seq ArgsRegion = Tree.allocate(Parent: Region);
15573 SequenceTree::Seq OldRegion = Region;
15574
15575 assert(CXXOCE->getNumArgs() >= 1 &&
15576 "An overloaded call operator must have at least one argument"
15577 " for the postfix-expression!");
15578 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15579 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15580 CXXOCE->getNumArgs() - 1);
15581
15582 // Visit the postfix-expression first.
15583 {
15584 Region = PostfixExprRegion;
15585 SequencedSubexpression Sequenced(*this);
15586 Visit(S: PostfixExpr);
15587 }
15588
15589 // Then visit the argument expressions.
15590 Region = ArgsRegion;
15591 for (const Expr *Arg : Args)
15592 Visit(S: Arg);
15593
15594 Region = OldRegion;
15595 Tree.merge(S: PostfixExprRegion);
15596 Tree.merge(S: ArgsRegion);
15597 } else {
15598 assert(CXXOCE->getNumArgs() == 2 &&
15599 "Should only have two arguments here!");
15600 assert((SequencingKind == LHSBeforeRHS ||
15601 SequencingKind == RHSBeforeLHS) &&
15602 "Unexpected sequencing kind!");
15603
15604 // We do not visit the callee expression since it is just a decayed
15605 // reference to a function.
15606 const Expr *E1 = CXXOCE->getArg(Arg: 0);
15607 const Expr *E2 = CXXOCE->getArg(Arg: 1);
15608 if (SequencingKind == RHSBeforeLHS)
15609 std::swap(a&: E1, b&: E2);
15610
15611 return VisitSequencedExpressions(SequencedBefore: E1, SequencedAfter: E2);
15612 }
15613 });
15614 }
15615
15616 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15617 // This is a call, so all subexpressions are sequenced before the result.
15618 SequencedSubexpression Sequenced(*this);
15619
15620 if (!CCE->isListInitialization())
15621 return VisitExpr(E: CCE);
15622
15623 // In C++11, list initializations are sequenced.
15624 SequenceExpressionsInOrder(
15625 ExpressionList: llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15626 }
15627
15628 void VisitInitListExpr(const InitListExpr *ILE) {
15629 if (!SemaRef.getLangOpts().CPlusPlus11)
15630 return VisitExpr(E: ILE);
15631
15632 // In C++11, list initializations are sequenced.
15633 SequenceExpressionsInOrder(ExpressionList: ILE->inits());
15634 }
15635
15636 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15637 // C++20 parenthesized list initializations are sequenced. See C++20
15638 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15639 SequenceExpressionsInOrder(ExpressionList: PLIE->getInitExprs());
15640 }
15641
15642private:
15643 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15644 SmallVector<SequenceTree::Seq, 32> Elts;
15645 SequenceTree::Seq Parent = Region;
15646 for (const Expr *E : ExpressionList) {
15647 if (!E)
15648 continue;
15649 Region = Tree.allocate(Parent);
15650 Elts.push_back(Elt: Region);
15651 Visit(S: E);
15652 }
15653
15654 // Forget that the initializers are sequenced.
15655 Region = Parent;
15656 for (unsigned I = 0; I < Elts.size(); ++I)
15657 Tree.merge(S: Elts[I]);
15658 }
15659};
15660
15661SequenceChecker::UsageInfo::UsageInfo() = default;
15662
15663} // namespace
15664
15665void Sema::CheckUnsequencedOperations(const Expr *E) {
15666 SmallVector<const Expr *, 8> WorkList;
15667 WorkList.push_back(Elt: E);
15668 while (!WorkList.empty()) {
15669 const Expr *Item = WorkList.pop_back_val();
15670 SequenceChecker(*this, Item, WorkList);
15671 }
15672}
15673
15674void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15675 bool IsConstexpr) {
15676 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15677 IsConstexpr || isa<ConstantExpr>(Val: E));
15678 CheckImplicitConversions(E, CC: CheckLoc);
15679 if (!E->isInstantiationDependent())
15680 CheckUnsequencedOperations(E);
15681 if (!IsConstexpr && !E->isValueDependent())
15682 CheckForIntOverflow(E);
15683}
15684
15685void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15686 FieldDecl *BitField,
15687 Expr *Init) {
15688 (void) AnalyzeBitFieldAssignment(S&: *this, Bitfield: BitField, Init, InitLoc);
15689}
15690
15691static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
15692 SourceLocation Loc) {
15693 if (!PType->isVariablyModifiedType())
15694 return;
15695 if (const auto *PointerTy = dyn_cast<PointerType>(Val&: PType)) {
15696 diagnoseArrayStarInParamType(S, PType: PointerTy->getPointeeType(), Loc);
15697 return;
15698 }
15699 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(Val&: PType)) {
15700 diagnoseArrayStarInParamType(S, PType: ReferenceTy->getPointeeType(), Loc);
15701 return;
15702 }
15703 if (const auto *ParenTy = dyn_cast<ParenType>(Val&: PType)) {
15704 diagnoseArrayStarInParamType(S, PType: ParenTy->getInnerType(), Loc);
15705 return;
15706 }
15707
15708 const ArrayType *AT = S.Context.getAsArrayType(T: PType);
15709 if (!AT)
15710 return;
15711
15712 if (AT->getSizeModifier() != ArraySizeModifier::Star) {
15713 diagnoseArrayStarInParamType(S, PType: AT->getElementType(), Loc);
15714 return;
15715 }
15716
15717 S.Diag(Loc, DiagID: diag::err_array_star_in_function_definition);
15718}
15719
15720bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
15721 bool CheckParameterNames) {
15722 bool HasInvalidParm = false;
15723 for (ParmVarDecl *Param : Parameters) {
15724 assert(Param && "null in a parameter list");
15725 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15726 // function declarator that is part of a function definition of
15727 // that function shall not have incomplete type.
15728 //
15729 // C++23 [dcl.fct.def.general]/p2
15730 // The type of a parameter [...] for a function definition
15731 // shall not be a (possibly cv-qualified) class type that is incomplete
15732 // or abstract within the function body unless the function is deleted.
15733 if (!Param->isInvalidDecl() &&
15734 (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
15735 DiagID: diag::err_typecheck_decl_incomplete_type) ||
15736 RequireNonAbstractType(Loc: Param->getBeginLoc(), T: Param->getOriginalType(),
15737 DiagID: diag::err_abstract_type_in_decl,
15738 Args: AbstractParamType))) {
15739 Param->setInvalidDecl();
15740 HasInvalidParm = true;
15741 }
15742
15743 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15744 // declaration of each parameter shall include an identifier.
15745 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15746 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15747 // Diagnose this as an extension in C17 and earlier.
15748 if (!getLangOpts().C23)
15749 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
15750 }
15751
15752 // C99 6.7.5.3p12:
15753 // If the function declarator is not part of a definition of that
15754 // function, parameters may have incomplete type and may use the [*]
15755 // notation in their sequences of declarator specifiers to specify
15756 // variable length array types.
15757 QualType PType = Param->getOriginalType();
15758 // FIXME: This diagnostic should point the '[*]' if source-location
15759 // information is added for it.
15760 diagnoseArrayStarInParamType(S&: *this, PType, Loc: Param->getLocation());
15761
15762 // If the parameter is a c++ class type and it has to be destructed in the
15763 // callee function, declare the destructor so that it can be called by the
15764 // callee function. Do not perform any direct access check on the dtor here.
15765 if (!Param->isInvalidDecl()) {
15766 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15767 if (!ClassDecl->isInvalidDecl() &&
15768 !ClassDecl->hasIrrelevantDestructor() &&
15769 !ClassDecl->isDependentContext() &&
15770 ClassDecl->isParamDestroyedInCallee()) {
15771 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
15772 MarkFunctionReferenced(Loc: Param->getLocation(), Func: Destructor);
15773 DiagnoseUseOfDecl(D: Destructor, Locs: Param->getLocation());
15774 }
15775 }
15776 }
15777
15778 // Parameters with the pass_object_size attribute only need to be marked
15779 // constant at function definitions. Because we lack information about
15780 // whether we're on a declaration or definition when we're instantiating the
15781 // attribute, we need to check for constness here.
15782 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15783 if (!Param->getType().isConstQualified())
15784 Diag(Loc: Param->getLocation(), DiagID: diag::err_attribute_pointers_only)
15785 << Attr->getSpelling() << 1;
15786
15787 // Check for parameter names shadowing fields from the class.
15788 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15789 // The owning context for the parameter should be the function, but we
15790 // want to see if this function's declaration context is a record.
15791 DeclContext *DC = Param->getDeclContext();
15792 if (DC && DC->isFunctionOrMethod()) {
15793 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC->getParent()))
15794 CheckShadowInheritedFields(Loc: Param->getLocation(), FieldName: Param->getDeclName(),
15795 RD, /*DeclIsField*/ false);
15796 }
15797 }
15798
15799 if (!Param->isInvalidDecl() &&
15800 Param->getOriginalType()->isWebAssemblyTableType()) {
15801 Param->setInvalidDecl();
15802 HasInvalidParm = true;
15803 Diag(Loc: Param->getLocation(), DiagID: diag::err_wasm_table_as_function_parameter);
15804 }
15805 }
15806
15807 return HasInvalidParm;
15808}
15809
15810std::optional<std::pair<
15811 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15812 *E,
15813 ASTContext
15814 &Ctx);
15815
15816/// Compute the alignment and offset of the base class object given the
15817/// derived-to-base cast expression and the alignment and offset of the derived
15818/// class object.
15819static std::pair<CharUnits, CharUnits>
15820getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15821 CharUnits BaseAlignment, CharUnits Offset,
15822 ASTContext &Ctx) {
15823 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15824 ++PathI) {
15825 const CXXBaseSpecifier *Base = *PathI;
15826 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15827 if (Base->isVirtual()) {
15828 // The complete object may have a lower alignment than the non-virtual
15829 // alignment of the base, in which case the base may be misaligned. Choose
15830 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15831 // conservative lower bound of the complete object alignment.
15832 CharUnits NonVirtualAlignment =
15833 Ctx.getASTRecordLayout(D: BaseDecl).getNonVirtualAlignment();
15834 BaseAlignment = std::min(a: BaseAlignment, b: NonVirtualAlignment);
15835 Offset = CharUnits::Zero();
15836 } else {
15837 const ASTRecordLayout &RL =
15838 Ctx.getASTRecordLayout(D: DerivedType->getAsCXXRecordDecl());
15839 Offset += RL.getBaseClassOffset(Base: BaseDecl);
15840 }
15841 DerivedType = Base->getType();
15842 }
15843
15844 return std::make_pair(x&: BaseAlignment, y&: Offset);
15845}
15846
15847/// Compute the alignment and offset of a binary additive operator.
15848static std::optional<std::pair<CharUnits, CharUnits>>
15849getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15850 bool IsSub, ASTContext &Ctx) {
15851 QualType PointeeType = PtrE->getType()->getPointeeType();
15852
15853 if (!PointeeType->isConstantSizeType())
15854 return std::nullopt;
15855
15856 auto P = getBaseAlignmentAndOffsetFromPtr(E: PtrE, Ctx);
15857
15858 if (!P)
15859 return std::nullopt;
15860
15861 CharUnits EltSize = Ctx.getTypeSizeInChars(T: PointeeType);
15862 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15863 CharUnits Offset = EltSize * IdxRes->getExtValue();
15864 if (IsSub)
15865 Offset = -Offset;
15866 return std::make_pair(x&: P->first, y: P->second + Offset);
15867 }
15868
15869 // If the integer expression isn't a constant expression, compute the lower
15870 // bound of the alignment using the alignment and offset of the pointer
15871 // expression and the element size.
15872 return std::make_pair(
15873 x: P->first.alignmentAtOffset(offset: P->second).alignmentAtOffset(offset: EltSize),
15874 y: CharUnits::Zero());
15875}
15876
15877/// This helper function takes an lvalue expression and returns the alignment of
15878/// a VarDecl and a constant offset from the VarDecl.
15879std::optional<std::pair<
15880 CharUnits,
15881 CharUnits>> static getBaseAlignmentAndOffsetFromLValue(const Expr *E,
15882 ASTContext &Ctx) {
15883 E = E->IgnoreParens();
15884 switch (E->getStmtClass()) {
15885 default:
15886 break;
15887 case Stmt::CStyleCastExprClass:
15888 case Stmt::CXXStaticCastExprClass:
15889 case Stmt::ImplicitCastExprClass: {
15890 auto *CE = cast<CastExpr>(Val: E);
15891 const Expr *From = CE->getSubExpr();
15892 switch (CE->getCastKind()) {
15893 default:
15894 break;
15895 case CK_NoOp:
15896 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15897 case CK_UncheckedDerivedToBase:
15898 case CK_DerivedToBase: {
15899 auto P = getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15900 if (!P)
15901 break;
15902 return getDerivedToBaseAlignmentAndOffset(CE, DerivedType: From->getType(), BaseAlignment: P->first,
15903 Offset: P->second, Ctx);
15904 }
15905 }
15906 break;
15907 }
15908 case Stmt::ArraySubscriptExprClass: {
15909 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
15910 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: ASE->getBase(), IntE: ASE->getIdx(),
15911 IsSub: false, Ctx);
15912 }
15913 case Stmt::DeclRefExprClass: {
15914 if (auto *VD = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: E)->getDecl())) {
15915 // FIXME: If VD is captured by copy or is an escaping __block variable,
15916 // use the alignment of VD's type.
15917 if (!VD->getType()->isReferenceType()) {
15918 // Dependent alignment cannot be resolved -> bail out.
15919 if (VD->hasDependentAlignment())
15920 break;
15921 return std::make_pair(x: Ctx.getDeclAlign(D: VD), y: CharUnits::Zero());
15922 }
15923 if (VD->hasInit())
15924 return getBaseAlignmentAndOffsetFromLValue(E: VD->getInit(), Ctx);
15925 }
15926 break;
15927 }
15928 case Stmt::MemberExprClass: {
15929 auto *ME = cast<MemberExpr>(Val: E);
15930 auto *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
15931 if (!FD || FD->getType()->isReferenceType() ||
15932 !ASTContext::hasLayout(D: FD->getParent()))
15933 break;
15934 std::optional<std::pair<CharUnits, CharUnits>> P;
15935 if (ME->isArrow())
15936 P = getBaseAlignmentAndOffsetFromPtr(E: ME->getBase(), Ctx);
15937 else
15938 P = getBaseAlignmentAndOffsetFromLValue(E: ME->getBase(), Ctx);
15939 if (!P)
15940 break;
15941 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(D: FD->getParent());
15942 uint64_t Offset = Layout.getFieldOffset(FieldNo: FD->getFieldIndex());
15943 return std::make_pair(x&: P->first,
15944 y: P->second + CharUnits::fromQuantity(Quantity: Offset));
15945 }
15946 case Stmt::UnaryOperatorClass: {
15947 auto *UO = cast<UnaryOperator>(Val: E);
15948 switch (UO->getOpcode()) {
15949 default:
15950 break;
15951 case UO_Deref:
15952 return getBaseAlignmentAndOffsetFromPtr(E: UO->getSubExpr(), Ctx);
15953 }
15954 break;
15955 }
15956 case Stmt::BinaryOperatorClass: {
15957 auto *BO = cast<BinaryOperator>(Val: E);
15958 auto Opcode = BO->getOpcode();
15959 switch (Opcode) {
15960 default:
15961 break;
15962 case BO_Comma:
15963 return getBaseAlignmentAndOffsetFromLValue(E: BO->getRHS(), Ctx);
15964 }
15965 break;
15966 }
15967 }
15968 return std::nullopt;
15969}
15970
15971/// This helper function takes a pointer expression and returns the alignment of
15972/// a VarDecl and a constant offset from the VarDecl.
15973std::optional<std::pair<
15974 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15975 *E,
15976 ASTContext
15977 &Ctx) {
15978 E = E->IgnoreParens();
15979 switch (E->getStmtClass()) {
15980 default:
15981 break;
15982 case Stmt::CStyleCastExprClass:
15983 case Stmt::CXXStaticCastExprClass:
15984 case Stmt::ImplicitCastExprClass: {
15985 auto *CE = cast<CastExpr>(Val: E);
15986 const Expr *From = CE->getSubExpr();
15987 switch (CE->getCastKind()) {
15988 default:
15989 break;
15990 case CK_NoOp:
15991 return getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15992 case CK_ArrayToPointerDecay:
15993 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15994 case CK_UncheckedDerivedToBase:
15995 case CK_DerivedToBase: {
15996 auto P = getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15997 if (!P)
15998 break;
15999 return getDerivedToBaseAlignmentAndOffset(
16000 CE, DerivedType: From->getType()->getPointeeType(), BaseAlignment: P->first, Offset: P->second, Ctx);
16001 }
16002 }
16003 break;
16004 }
16005 case Stmt::CXXThisExprClass: {
16006 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
16007 CharUnits Alignment = Ctx.getASTRecordLayout(D: RD).getNonVirtualAlignment();
16008 return std::make_pair(x&: Alignment, y: CharUnits::Zero());
16009 }
16010 case Stmt::UnaryOperatorClass: {
16011 auto *UO = cast<UnaryOperator>(Val: E);
16012 if (UO->getOpcode() == UO_AddrOf)
16013 return getBaseAlignmentAndOffsetFromLValue(E: UO->getSubExpr(), Ctx);
16014 break;
16015 }
16016 case Stmt::BinaryOperatorClass: {
16017 auto *BO = cast<BinaryOperator>(Val: E);
16018 auto Opcode = BO->getOpcode();
16019 switch (Opcode) {
16020 default:
16021 break;
16022 case BO_Add:
16023 case BO_Sub: {
16024 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
16025 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
16026 std::swap(a&: LHS, b&: RHS);
16027 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: LHS, IntE: RHS, IsSub: Opcode == BO_Sub,
16028 Ctx);
16029 }
16030 case BO_Comma:
16031 return getBaseAlignmentAndOffsetFromPtr(E: BO->getRHS(), Ctx);
16032 }
16033 break;
16034 }
16035 }
16036 return std::nullopt;
16037}
16038
16039static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
16040 // See if we can compute the alignment of a VarDecl and an offset from it.
16041 std::optional<std::pair<CharUnits, CharUnits>> P =
16042 getBaseAlignmentAndOffsetFromPtr(E, Ctx&: S.Context);
16043
16044 if (P)
16045 return P->first.alignmentAtOffset(offset: P->second);
16046
16047 // If that failed, return the type's alignment.
16048 return S.Context.getTypeAlignInChars(T: E->getType()->getPointeeType());
16049}
16050
16051void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
16052 // This is actually a lot of work to potentially be doing on every
16053 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
16054 if (getDiagnostics().isIgnored(DiagID: diag::warn_cast_align, Loc: TRange.getBegin()))
16055 return;
16056
16057 // Ignore dependent types.
16058 if (T->isDependentType() || Op->getType()->isDependentType())
16059 return;
16060
16061 // Require that the destination be a pointer type.
16062 const PointerType *DestPtr = T->getAs<PointerType>();
16063 if (!DestPtr) return;
16064
16065 // If the destination has alignment 1, we're done.
16066 QualType DestPointee = DestPtr->getPointeeType();
16067 if (DestPointee->isIncompleteType()) return;
16068 CharUnits DestAlign = Context.getTypeAlignInChars(T: DestPointee);
16069 if (DestAlign.isOne()) return;
16070
16071 // Require that the source be a pointer type.
16072 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
16073 if (!SrcPtr) return;
16074 QualType SrcPointee = SrcPtr->getPointeeType();
16075
16076 // Explicitly allow casts from cv void*. We already implicitly
16077 // allowed casts to cv void*, since they have alignment 1.
16078 // Also allow casts involving incomplete types, which implicitly
16079 // includes 'void'.
16080 if (SrcPointee->isIncompleteType()) return;
16081
16082 CharUnits SrcAlign = getPresumedAlignmentOfPointer(E: Op, S&: *this);
16083
16084 if (SrcAlign >= DestAlign) return;
16085
16086 Diag(Loc: TRange.getBegin(), DiagID: diag::warn_cast_align)
16087 << Op->getType() << T
16088 << static_cast<unsigned>(SrcAlign.getQuantity())
16089 << static_cast<unsigned>(DestAlign.getQuantity())
16090 << TRange << Op->getSourceRange();
16091}
16092
16093void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
16094 const ArraySubscriptExpr *ASE,
16095 bool AllowOnePastEnd, bool IndexNegated) {
16096 // Already diagnosed by the constant evaluator.
16097 if (isConstantEvaluatedContext())
16098 return;
16099
16100 IndexExpr = IndexExpr->IgnoreParenImpCasts();
16101 if (IndexExpr->isValueDependent())
16102 return;
16103
16104 const Type *EffectiveType =
16105 BaseExpr->getType()->getPointeeOrArrayElementType();
16106 BaseExpr = BaseExpr->IgnoreParenCasts();
16107 const ConstantArrayType *ArrayTy =
16108 Context.getAsConstantArrayType(T: BaseExpr->getType());
16109
16110 LangOptions::StrictFlexArraysLevelKind
16111 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
16112
16113 const Type *BaseType =
16114 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
16115 bool IsUnboundedArray =
16116 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
16117 Context, StrictFlexArraysLevel,
16118 /*IgnoreTemplateOrMacroSubstitution=*/true);
16119 if (EffectiveType->isDependentType() ||
16120 (!IsUnboundedArray && BaseType->isDependentType()))
16121 return;
16122
16123 Expr::EvalResult Result;
16124 if (!IndexExpr->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects))
16125 return;
16126
16127 llvm::APSInt index = Result.Val.getInt();
16128 if (IndexNegated) {
16129 index.setIsUnsigned(false);
16130 index = -index;
16131 }
16132
16133 if (IsUnboundedArray) {
16134 if (EffectiveType->isFunctionType())
16135 return;
16136 if (index.isUnsigned() || !index.isNegative()) {
16137 const auto &ASTC = getASTContext();
16138 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
16139 AddrSpace: EffectiveType->getCanonicalTypeInternal().getAddressSpace());
16140 if (index.getBitWidth() < AddrBits)
16141 index = index.zext(width: AddrBits);
16142 std::optional<CharUnits> ElemCharUnits =
16143 ASTC.getTypeSizeInCharsIfKnown(Ty: EffectiveType);
16144 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
16145 // pointer) bounds-checking isn't meaningful.
16146 if (!ElemCharUnits || ElemCharUnits->isZero())
16147 return;
16148 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
16149 // If index has more active bits than address space, we already know
16150 // we have a bounds violation to warn about. Otherwise, compute
16151 // address of (index + 1)th element, and warn about bounds violation
16152 // only if that address exceeds address space.
16153 if (index.getActiveBits() <= AddrBits) {
16154 bool Overflow;
16155 llvm::APInt Product(index);
16156 Product += 1;
16157 Product = Product.umul_ov(RHS: ElemBytes, Overflow);
16158 if (!Overflow && Product.getActiveBits() <= AddrBits)
16159 return;
16160 }
16161
16162 // Need to compute max possible elements in address space, since that
16163 // is included in diag message.
16164 llvm::APInt MaxElems = llvm::APInt::getMaxValue(numBits: AddrBits);
16165 MaxElems = MaxElems.zext(width: std::max(a: AddrBits + 1, b: ElemBytes.getBitWidth()));
16166 MaxElems += 1;
16167 ElemBytes = ElemBytes.zextOrTrunc(width: MaxElems.getBitWidth());
16168 MaxElems = MaxElems.udiv(RHS: ElemBytes);
16169
16170 unsigned DiagID =
16171 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
16172 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
16173
16174 // Diag message shows element size in bits and in "bytes" (platform-
16175 // dependent CharUnits)
16176 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16177 PD: PDiag(DiagID) << index << AddrBits
16178 << (unsigned)ASTC.toBits(CharSize: *ElemCharUnits)
16179 << ElemBytes << MaxElems
16180 << MaxElems.getZExtValue()
16181 << IndexExpr->getSourceRange());
16182
16183 const NamedDecl *ND = nullptr;
16184 // Try harder to find a NamedDecl to point at in the note.
16185 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
16186 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16187 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
16188 ND = DRE->getDecl();
16189 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
16190 ND = ME->getMemberDecl();
16191
16192 if (ND)
16193 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
16194 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
16195 }
16196 return;
16197 }
16198
16199 if (index.isUnsigned() || !index.isNegative()) {
16200 // It is possible that the type of the base expression after
16201 // IgnoreParenCasts is incomplete, even though the type of the base
16202 // expression before IgnoreParenCasts is complete (see PR39746 for an
16203 // example). In this case we have no information about whether the array
16204 // access exceeds the array bounds. However we can still diagnose an array
16205 // access which precedes the array bounds.
16206 if (BaseType->isIncompleteType())
16207 return;
16208
16209 llvm::APInt size = ArrayTy->getSize();
16210
16211 if (BaseType != EffectiveType) {
16212 // Make sure we're comparing apples to apples when comparing index to
16213 // size.
16214 uint64_t ptrarith_typesize = Context.getTypeSize(T: EffectiveType);
16215 uint64_t array_typesize = Context.getTypeSize(T: BaseType);
16216
16217 // Handle ptrarith_typesize being zero, such as when casting to void*.
16218 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
16219 if (!ptrarith_typesize)
16220 ptrarith_typesize = Context.getCharWidth();
16221
16222 if (ptrarith_typesize != array_typesize) {
16223 // There's a cast to a different size type involved.
16224 uint64_t ratio = array_typesize / ptrarith_typesize;
16225
16226 // TODO: Be smarter about handling cases where array_typesize is not a
16227 // multiple of ptrarith_typesize.
16228 if (ptrarith_typesize * ratio == array_typesize)
16229 size *= llvm::APInt(size.getBitWidth(), ratio);
16230 }
16231 }
16232
16233 if (size.getBitWidth() > index.getBitWidth())
16234 index = index.zext(width: size.getBitWidth());
16235 else if (size.getBitWidth() < index.getBitWidth())
16236 size = size.zext(width: index.getBitWidth());
16237
16238 // For array subscripting the index must be less than size, but for pointer
16239 // arithmetic also allow the index (offset) to be equal to size since
16240 // computing the next address after the end of the array is legal and
16241 // commonly done e.g. in C++ iterators and range-based for loops.
16242 if (AllowOnePastEnd ? index.ule(RHS: size) : index.ult(RHS: size))
16243 return;
16244
16245 // Suppress the warning if the subscript expression (as identified by the
16246 // ']' location) and the index expression are both from macro expansions
16247 // within a system header.
16248 if (ASE) {
16249 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
16250 Loc: ASE->getRBracketLoc());
16251 if (SourceMgr.isInSystemHeader(Loc: RBracketLoc)) {
16252 SourceLocation IndexLoc =
16253 SourceMgr.getSpellingLoc(Loc: IndexExpr->getBeginLoc());
16254 if (SourceMgr.isWrittenInSameFile(Loc1: RBracketLoc, Loc2: IndexLoc))
16255 return;
16256 }
16257 }
16258
16259 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
16260 : diag::warn_ptr_arith_exceeds_bounds;
16261 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
16262 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
16263
16264 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16265 PD: PDiag(DiagID)
16266 << index << ArrayTy->desugar() << CastMsg
16267 << CastMsgTy << IndexExpr->getSourceRange());
16268 } else {
16269 unsigned DiagID = diag::warn_array_index_precedes_bounds;
16270 if (!ASE) {
16271 DiagID = diag::warn_ptr_arith_precedes_bounds;
16272 if (index.isNegative()) index = -index;
16273 }
16274
16275 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16276 PD: PDiag(DiagID) << index << IndexExpr->getSourceRange());
16277 }
16278
16279 const NamedDecl *ND = nullptr;
16280 // Try harder to find a NamedDecl to point at in the note.
16281 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
16282 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16283 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
16284 ND = DRE->getDecl();
16285 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
16286 ND = ME->getMemberDecl();
16287
16288 if (ND)
16289 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
16290 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
16291}
16292
16293void Sema::CheckArrayAccess(const Expr *expr) {
16294 int AllowOnePastEnd = 0;
16295 while (expr) {
16296 expr = expr->IgnoreParenImpCasts();
16297 switch (expr->getStmtClass()) {
16298 case Stmt::ArraySubscriptExprClass: {
16299 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Val: expr);
16300 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getIdx(), ASE,
16301 AllowOnePastEnd: AllowOnePastEnd > 0);
16302 expr = ASE->getBase();
16303 break;
16304 }
16305 case Stmt::MemberExprClass: {
16306 expr = cast<MemberExpr>(Val: expr)->getBase();
16307 break;
16308 }
16309 case Stmt::CXXMemberCallExprClass: {
16310 expr = cast<CXXMemberCallExpr>(Val: expr)->getImplicitObjectArgument();
16311 break;
16312 }
16313 case Stmt::ArraySectionExprClass: {
16314 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(Val: expr);
16315 // FIXME: We should probably be checking all of the elements to the
16316 // 'length' here as well.
16317 if (ASE->getLowerBound())
16318 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getLowerBound(),
16319 /*ASE=*/nullptr, AllowOnePastEnd: AllowOnePastEnd > 0);
16320 return;
16321 }
16322 case Stmt::UnaryOperatorClass: {
16323 // Only unwrap the * and & unary operators
16324 const UnaryOperator *UO = cast<UnaryOperator>(Val: expr);
16325 expr = UO->getSubExpr();
16326 switch (UO->getOpcode()) {
16327 case UO_AddrOf:
16328 AllowOnePastEnd++;
16329 break;
16330 case UO_Deref:
16331 AllowOnePastEnd--;
16332 break;
16333 default:
16334 return;
16335 }
16336 break;
16337 }
16338 case Stmt::ConditionalOperatorClass: {
16339 const ConditionalOperator *cond = cast<ConditionalOperator>(Val: expr);
16340 if (const Expr *lhs = cond->getLHS())
16341 CheckArrayAccess(expr: lhs);
16342 if (const Expr *rhs = cond->getRHS())
16343 CheckArrayAccess(expr: rhs);
16344 return;
16345 }
16346 case Stmt::CXXOperatorCallExprClass: {
16347 const auto *OCE = cast<CXXOperatorCallExpr>(Val: expr);
16348 for (const auto *Arg : OCE->arguments())
16349 CheckArrayAccess(expr: Arg);
16350 return;
16351 }
16352 default:
16353 return;
16354 }
16355 }
16356}
16357
16358static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16359 Expr *RHS, bool isProperty) {
16360 // Check if RHS is an Objective-C object literal, which also can get
16361 // immediately zapped in a weak reference. Note that we explicitly
16362 // allow ObjCStringLiterals, since those are designed to never really die.
16363 RHS = RHS->IgnoreParenImpCasts();
16364
16365 // This enum needs to match with the 'select' in
16366 // warn_objc_arc_literal_assign (off-by-1).
16367 SemaObjC::ObjCLiteralKind Kind = S.ObjC().CheckLiteralKind(FromE: RHS);
16368 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
16369 return false;
16370
16371 S.Diag(Loc, DiagID: diag::warn_arc_literal_assign)
16372 << (unsigned) Kind
16373 << (isProperty ? 0 : 1)
16374 << RHS->getSourceRange();
16375
16376 return true;
16377}
16378
16379static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16380 Qualifiers::ObjCLifetime LT,
16381 Expr *RHS, bool isProperty) {
16382 // Strip off any implicit cast added to get to the one ARC-specific.
16383 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
16384 if (cast->getCastKind() == CK_ARCConsumeObject) {
16385 S.Diag(Loc, DiagID: diag::warn_arc_retained_assign)
16386 << (LT == Qualifiers::OCL_ExplicitNone)
16387 << (isProperty ? 0 : 1)
16388 << RHS->getSourceRange();
16389 return true;
16390 }
16391 RHS = cast->getSubExpr();
16392 }
16393
16394 if (LT == Qualifiers::OCL_Weak &&
16395 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16396 return true;
16397
16398 return false;
16399}
16400
16401bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16402 QualType LHS, Expr *RHS) {
16403 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16404
16405 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16406 return false;
16407
16408 if (checkUnsafeAssignObject(S&: *this, Loc, LT, RHS, isProperty: false))
16409 return true;
16410
16411 return false;
16412}
16413
16414void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16415 Expr *LHS, Expr *RHS) {
16416 QualType LHSType;
16417 // PropertyRef on LHS type need be directly obtained from
16418 // its declaration as it has a PseudoType.
16419 ObjCPropertyRefExpr *PRE
16420 = dyn_cast<ObjCPropertyRefExpr>(Val: LHS->IgnoreParens());
16421 if (PRE && !PRE->isImplicitProperty()) {
16422 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16423 if (PD)
16424 LHSType = PD->getType();
16425 }
16426
16427 if (LHSType.isNull())
16428 LHSType = LHS->getType();
16429
16430 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16431
16432 if (LT == Qualifiers::OCL_Weak) {
16433 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc))
16434 getCurFunction()->markSafeWeakUse(E: LHS);
16435 }
16436
16437 if (checkUnsafeAssigns(Loc, LHS: LHSType, RHS))
16438 return;
16439
16440 // FIXME. Check for other life times.
16441 if (LT != Qualifiers::OCL_None)
16442 return;
16443
16444 if (PRE) {
16445 if (PRE->isImplicitProperty())
16446 return;
16447 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16448 if (!PD)
16449 return;
16450
16451 unsigned Attributes = PD->getPropertyAttributes();
16452 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16453 // when 'assign' attribute was not explicitly specified
16454 // by user, ignore it and rely on property type itself
16455 // for lifetime info.
16456 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16457 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16458 LHSType->isObjCRetainableType())
16459 return;
16460
16461 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
16462 if (cast->getCastKind() == CK_ARCConsumeObject) {
16463 Diag(Loc, DiagID: diag::warn_arc_retained_property_assign)
16464 << RHS->getSourceRange();
16465 return;
16466 }
16467 RHS = cast->getSubExpr();
16468 }
16469 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16470 if (checkUnsafeAssignObject(S&: *this, Loc, LT: Qualifiers::OCL_Weak, RHS, isProperty: true))
16471 return;
16472 }
16473 }
16474}
16475
16476//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16477
16478static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16479 SourceLocation StmtLoc,
16480 const NullStmt *Body) {
16481 // Do not warn if the body is a macro that expands to nothing, e.g:
16482 //
16483 // #define CALL(x)
16484 // if (condition)
16485 // CALL(0);
16486 if (Body->hasLeadingEmptyMacro())
16487 return false;
16488
16489 // Get line numbers of statement and body.
16490 bool StmtLineInvalid;
16491 unsigned StmtLine = SourceMgr.getPresumedLineNumber(Loc: StmtLoc,
16492 Invalid: &StmtLineInvalid);
16493 if (StmtLineInvalid)
16494 return false;
16495
16496 bool BodyLineInvalid;
16497 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Loc: Body->getSemiLoc(),
16498 Invalid: &BodyLineInvalid);
16499 if (BodyLineInvalid)
16500 return false;
16501
16502 // Warn if null statement and body are on the same line.
16503 if (StmtLine != BodyLine)
16504 return false;
16505
16506 return true;
16507}
16508
16509void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16510 const Stmt *Body,
16511 unsigned DiagID) {
16512 // Since this is a syntactic check, don't emit diagnostic for template
16513 // instantiations, this just adds noise.
16514 if (CurrentInstantiationScope)
16515 return;
16516
16517 // The body should be a null statement.
16518 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
16519 if (!NBody)
16520 return;
16521
16522 // Do the usual checks.
16523 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
16524 return;
16525
16526 Diag(Loc: NBody->getSemiLoc(), DiagID);
16527 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
16528}
16529
16530void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16531 const Stmt *PossibleBody) {
16532 assert(!CurrentInstantiationScope); // Ensured by caller
16533
16534 SourceLocation StmtLoc;
16535 const Stmt *Body;
16536 unsigned DiagID;
16537 if (const ForStmt *FS = dyn_cast<ForStmt>(Val: S)) {
16538 StmtLoc = FS->getRParenLoc();
16539 Body = FS->getBody();
16540 DiagID = diag::warn_empty_for_body;
16541 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Val: S)) {
16542 StmtLoc = WS->getRParenLoc();
16543 Body = WS->getBody();
16544 DiagID = diag::warn_empty_while_body;
16545 } else
16546 return; // Neither `for' nor `while'.
16547
16548 // The body should be a null statement.
16549 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
16550 if (!NBody)
16551 return;
16552
16553 // Skip expensive checks if diagnostic is disabled.
16554 if (Diags.isIgnored(DiagID, Loc: NBody->getSemiLoc()))
16555 return;
16556
16557 // Do the usual checks.
16558 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
16559 return;
16560
16561 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16562 // noise level low, emit diagnostics only if for/while is followed by a
16563 // CompoundStmt, e.g.:
16564 // for (int i = 0; i < n; i++);
16565 // {
16566 // a(i);
16567 // }
16568 // or if for/while is followed by a statement with more indentation
16569 // than for/while itself:
16570 // for (int i = 0; i < n; i++);
16571 // a(i);
16572 bool ProbableTypo = isa<CompoundStmt>(Val: PossibleBody);
16573 if (!ProbableTypo) {
16574 bool BodyColInvalid;
16575 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16576 Loc: PossibleBody->getBeginLoc(), Invalid: &BodyColInvalid);
16577 if (BodyColInvalid)
16578 return;
16579
16580 bool StmtColInvalid;
16581 unsigned StmtCol =
16582 SourceMgr.getPresumedColumnNumber(Loc: S->getBeginLoc(), Invalid: &StmtColInvalid);
16583 if (StmtColInvalid)
16584 return;
16585
16586 if (BodyCol > StmtCol)
16587 ProbableTypo = true;
16588 }
16589
16590 if (ProbableTypo) {
16591 Diag(Loc: NBody->getSemiLoc(), DiagID);
16592 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
16593 }
16594}
16595
16596//===--- CHECK: Warn on self move with std::move. -------------------------===//
16597
16598void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16599 SourceLocation OpLoc) {
16600 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess, Loc: OpLoc))
16601 return;
16602
16603 if (inTemplateInstantiation())
16604 return;
16605
16606 // Strip parens and casts away.
16607 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16608 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16609
16610 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16611 // which we can treat as an inlined std::move
16612 if (const auto *CE = dyn_cast<CallExpr>(Val: RHSExpr);
16613 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16614 RHSExpr = CE->getArg(Arg: 0);
16615 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(Val: RHSExpr);
16616 CXXSCE && CXXSCE->isXValue())
16617 RHSExpr = CXXSCE->getSubExpr();
16618 else
16619 return;
16620
16621 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
16622 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
16623
16624 // Two DeclRefExpr's, check that the decls are the same.
16625 if (LHSDeclRef && RHSDeclRef) {
16626 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16627 return;
16628 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16629 RHSDeclRef->getDecl()->getCanonicalDecl())
16630 return;
16631
16632 auto D = Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16633 << LHSExpr->getType() << LHSExpr->getSourceRange()
16634 << RHSExpr->getSourceRange();
16635 if (const FieldDecl *F =
16636 getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDeclRef->getDecl()))
16637 D << 1 << F
16638 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
16639 else
16640 D << 0;
16641 return;
16642 }
16643
16644 // Member variables require a different approach to check for self moves.
16645 // MemberExpr's are the same if every nested MemberExpr refers to the same
16646 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16647 // the base Expr's are CXXThisExpr's.
16648 const Expr *LHSBase = LHSExpr;
16649 const Expr *RHSBase = RHSExpr;
16650 const MemberExpr *LHSME = dyn_cast<MemberExpr>(Val: LHSExpr);
16651 const MemberExpr *RHSME = dyn_cast<MemberExpr>(Val: RHSExpr);
16652 if (!LHSME || !RHSME)
16653 return;
16654
16655 while (LHSME && RHSME) {
16656 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16657 RHSME->getMemberDecl()->getCanonicalDecl())
16658 return;
16659
16660 LHSBase = LHSME->getBase();
16661 RHSBase = RHSME->getBase();
16662 LHSME = dyn_cast<MemberExpr>(Val: LHSBase);
16663 RHSME = dyn_cast<MemberExpr>(Val: RHSBase);
16664 }
16665
16666 LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSBase);
16667 RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSBase);
16668 if (LHSDeclRef && RHSDeclRef) {
16669 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16670 return;
16671 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16672 RHSDeclRef->getDecl()->getCanonicalDecl())
16673 return;
16674
16675 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16676 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16677 << RHSExpr->getSourceRange();
16678 return;
16679 }
16680
16681 if (isa<CXXThisExpr>(Val: LHSBase) && isa<CXXThisExpr>(Val: RHSBase))
16682 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16683 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16684 << RHSExpr->getSourceRange();
16685}
16686
16687//===--- Layout compatibility ----------------------------------------------//
16688
16689static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16690
16691/// Check if two enumeration types are layout-compatible.
16692static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16693 const EnumDecl *ED2) {
16694 // C++11 [dcl.enum] p8:
16695 // Two enumeration types are layout-compatible if they have the same
16696 // underlying type.
16697 return ED1->isComplete() && ED2->isComplete() &&
16698 C.hasSameType(T1: ED1->getIntegerType(), T2: ED2->getIntegerType());
16699}
16700
16701/// Check if two fields are layout-compatible.
16702/// Can be used on union members, which are exempt from alignment requirement
16703/// of common initial sequence.
16704static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16705 const FieldDecl *Field2,
16706 bool AreUnionMembers = false) {
16707#ifndef NDEBUG
16708 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16709 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16710 assert(((Field1Parent->isStructureOrClassType() &&
16711 Field2Parent->isStructureOrClassType()) ||
16712 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16713 "Can't evaluate layout compatibility between a struct field and a "
16714 "union field.");
16715 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16716 (AreUnionMembers && Field1Parent->isUnionType())) &&
16717 "AreUnionMembers should be 'true' for union fields (only).");
16718#endif
16719
16720 if (!isLayoutCompatible(C, T1: Field1->getType(), T2: Field2->getType()))
16721 return false;
16722
16723 if (Field1->isBitField() != Field2->isBitField())
16724 return false;
16725
16726 if (Field1->isBitField()) {
16727 // Make sure that the bit-fields are the same length.
16728 unsigned Bits1 = Field1->getBitWidthValue();
16729 unsigned Bits2 = Field2->getBitWidthValue();
16730
16731 if (Bits1 != Bits2)
16732 return false;
16733 }
16734
16735 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16736 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16737 return false;
16738
16739 if (!AreUnionMembers &&
16740 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16741 return false;
16742
16743 return true;
16744}
16745
16746/// Check if two standard-layout structs are layout-compatible.
16747/// (C++11 [class.mem] p17)
16748static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16749 const RecordDecl *RD2) {
16750 // Get to the class where the fields are declared
16751 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(Val: RD1))
16752 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16753
16754 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(Val: RD2))
16755 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16756
16757 // Check the fields.
16758 return llvm::equal(LRange: RD1->fields(), RRange: RD2->fields(),
16759 P: [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16760 return isLayoutCompatible(C, Field1: F1, Field2: F2);
16761 });
16762}
16763
16764/// Check if two standard-layout unions are layout-compatible.
16765/// (C++11 [class.mem] p18)
16766static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16767 const RecordDecl *RD2) {
16768 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16769 RD2->fields());
16770
16771 for (auto *Field1 : RD1->fields()) {
16772 auto It = llvm::find_if(Range&: UnmatchedFields, P: [&](const FieldDecl *Field2) {
16773 return isLayoutCompatible(C, Field1, Field2, /*IsUnionMember=*/AreUnionMembers: true);
16774 });
16775 if (It == UnmatchedFields.end())
16776 return false;
16777 [[maybe_unused]] bool Result = UnmatchedFields.erase(Ptr: *It);
16778 assert(Result);
16779 }
16780
16781 return UnmatchedFields.empty();
16782}
16783
16784static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16785 const RecordDecl *RD2) {
16786 if (RD1->isUnion() != RD2->isUnion())
16787 return false;
16788
16789 if (RD1->isUnion())
16790 return isLayoutCompatibleUnion(C, RD1, RD2);
16791 else
16792 return isLayoutCompatibleStruct(C, RD1, RD2);
16793}
16794
16795/// Check if two types are layout-compatible in C++11 sense.
16796static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16797 if (T1.isNull() || T2.isNull())
16798 return false;
16799
16800 // C++20 [basic.types] p11:
16801 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16802 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16803 // or layout-compatible standard-layout class types (11.4).
16804 T1 = T1.getCanonicalType().getUnqualifiedType();
16805 T2 = T2.getCanonicalType().getUnqualifiedType();
16806
16807 if (C.hasSameType(T1, T2))
16808 return true;
16809
16810 const Type::TypeClass TC1 = T1->getTypeClass();
16811 const Type::TypeClass TC2 = T2->getTypeClass();
16812
16813 if (TC1 != TC2)
16814 return false;
16815
16816 if (TC1 == Type::Enum)
16817 return isLayoutCompatible(C, ED1: T1->castAsEnumDecl(), ED2: T2->castAsEnumDecl());
16818 if (TC1 == Type::Record) {
16819 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16820 return false;
16821
16822 return isLayoutCompatible(C, RD1: T1->castAsRecordDecl(),
16823 RD2: T2->castAsRecordDecl());
16824 }
16825
16826 return false;
16827}
16828
16829bool Sema::IsLayoutCompatible(QualType T1, QualType T2) const {
16830 return isLayoutCompatible(C: getASTContext(), T1, T2);
16831}
16832
16833//===-------------- Pointer interconvertibility ----------------------------//
16834
16835bool Sema::IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
16836 const TypeSourceInfo *Derived) {
16837 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16838 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16839
16840 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16841 getASTContext().hasSameType(T1: BaseT, T2: DerivedT))
16842 return true;
16843
16844 if (!IsDerivedFrom(Loc: Derived->getTypeLoc().getBeginLoc(), Derived: DerivedT, Base: BaseT))
16845 return false;
16846
16847 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16848 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16849 return true;
16850
16851 return false;
16852}
16853
16854//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16855
16856/// Given a type tag expression find the type tag itself.
16857///
16858/// \param TypeExpr Type tag expression, as it appears in user's code.
16859///
16860/// \param VD Declaration of an identifier that appears in a type tag.
16861///
16862/// \param MagicValue Type tag magic value.
16863///
16864/// \param isConstantEvaluated whether the evalaution should be performed in
16865
16866/// constant context.
16867static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16868 const ValueDecl **VD, uint64_t *MagicValue,
16869 bool isConstantEvaluated) {
16870 while(true) {
16871 if (!TypeExpr)
16872 return false;
16873
16874 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16875
16876 switch (TypeExpr->getStmtClass()) {
16877 case Stmt::UnaryOperatorClass: {
16878 const UnaryOperator *UO = cast<UnaryOperator>(Val: TypeExpr);
16879 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16880 TypeExpr = UO->getSubExpr();
16881 continue;
16882 }
16883 return false;
16884 }
16885
16886 case Stmt::DeclRefExprClass: {
16887 const DeclRefExpr *DRE = cast<DeclRefExpr>(Val: TypeExpr);
16888 *VD = DRE->getDecl();
16889 return true;
16890 }
16891
16892 case Stmt::IntegerLiteralClass: {
16893 const IntegerLiteral *IL = cast<IntegerLiteral>(Val: TypeExpr);
16894 llvm::APInt MagicValueAPInt = IL->getValue();
16895 if (MagicValueAPInt.getActiveBits() <= 64) {
16896 *MagicValue = MagicValueAPInt.getZExtValue();
16897 return true;
16898 } else
16899 return false;
16900 }
16901
16902 case Stmt::BinaryConditionalOperatorClass:
16903 case Stmt::ConditionalOperatorClass: {
16904 const AbstractConditionalOperator *ACO =
16905 cast<AbstractConditionalOperator>(Val: TypeExpr);
16906 bool Result;
16907 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16908 InConstantContext: isConstantEvaluated)) {
16909 if (Result)
16910 TypeExpr = ACO->getTrueExpr();
16911 else
16912 TypeExpr = ACO->getFalseExpr();
16913 continue;
16914 }
16915 return false;
16916 }
16917
16918 case Stmt::BinaryOperatorClass: {
16919 const BinaryOperator *BO = cast<BinaryOperator>(Val: TypeExpr);
16920 if (BO->getOpcode() == BO_Comma) {
16921 TypeExpr = BO->getRHS();
16922 continue;
16923 }
16924 return false;
16925 }
16926
16927 default:
16928 return false;
16929 }
16930 }
16931}
16932
16933/// Retrieve the C type corresponding to type tag TypeExpr.
16934///
16935/// \param TypeExpr Expression that specifies a type tag.
16936///
16937/// \param MagicValues Registered magic values.
16938///
16939/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16940/// kind.
16941///
16942/// \param TypeInfo Information about the corresponding C type.
16943///
16944/// \param isConstantEvaluated whether the evalaution should be performed in
16945/// constant context.
16946///
16947/// \returns true if the corresponding C type was found.
16948static bool GetMatchingCType(
16949 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16950 const ASTContext &Ctx,
16951 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16952 *MagicValues,
16953 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16954 bool isConstantEvaluated) {
16955 FoundWrongKind = false;
16956
16957 // Variable declaration that has type_tag_for_datatype attribute.
16958 const ValueDecl *VD = nullptr;
16959
16960 uint64_t MagicValue;
16961
16962 if (!FindTypeTagExpr(TypeExpr, Ctx, VD: &VD, MagicValue: &MagicValue, isConstantEvaluated))
16963 return false;
16964
16965 if (VD) {
16966 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16967 if (I->getArgumentKind() != ArgumentKind) {
16968 FoundWrongKind = true;
16969 return false;
16970 }
16971 TypeInfo.Type = I->getMatchingCType();
16972 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16973 TypeInfo.MustBeNull = I->getMustBeNull();
16974 return true;
16975 }
16976 return false;
16977 }
16978
16979 if (!MagicValues)
16980 return false;
16981
16982 llvm::DenseMap<Sema::TypeTagMagicValue,
16983 Sema::TypeTagData>::const_iterator I =
16984 MagicValues->find(Val: std::make_pair(x&: ArgumentKind, y&: MagicValue));
16985 if (I == MagicValues->end())
16986 return false;
16987
16988 TypeInfo = I->second;
16989 return true;
16990}
16991
16992void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16993 uint64_t MagicValue, QualType Type,
16994 bool LayoutCompatible,
16995 bool MustBeNull) {
16996 if (!TypeTagForDatatypeMagicValues)
16997 TypeTagForDatatypeMagicValues.reset(
16998 p: new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16999
17000 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
17001 (*TypeTagForDatatypeMagicValues)[Magic] =
17002 TypeTagData(Type, LayoutCompatible, MustBeNull);
17003}
17004
17005static bool IsSameCharType(QualType T1, QualType T2) {
17006 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
17007 if (!BT1)
17008 return false;
17009
17010 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
17011 if (!BT2)
17012 return false;
17013
17014 BuiltinType::Kind T1Kind = BT1->getKind();
17015 BuiltinType::Kind T2Kind = BT2->getKind();
17016
17017 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
17018 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
17019 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
17020 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
17021}
17022
17023void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
17024 const ArrayRef<const Expr *> ExprArgs,
17025 SourceLocation CallSiteLoc) {
17026 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
17027 bool IsPointerAttr = Attr->getIsPointer();
17028
17029 // Retrieve the argument representing the 'type_tag'.
17030 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
17031 if (TypeTagIdxAST >= ExprArgs.size()) {
17032 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
17033 << 0 << Attr->getTypeTagIdx().getSourceIndex();
17034 return;
17035 }
17036 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
17037 bool FoundWrongKind;
17038 TypeTagData TypeInfo;
17039 if (!GetMatchingCType(ArgumentKind, TypeExpr: TypeTagExpr, Ctx: Context,
17040 MagicValues: TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
17041 TypeInfo, isConstantEvaluated: isConstantEvaluatedContext())) {
17042 if (FoundWrongKind)
17043 Diag(Loc: TypeTagExpr->getExprLoc(),
17044 DiagID: diag::warn_type_tag_for_datatype_wrong_kind)
17045 << TypeTagExpr->getSourceRange();
17046 return;
17047 }
17048
17049 // Retrieve the argument representing the 'arg_idx'.
17050 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
17051 if (ArgumentIdxAST >= ExprArgs.size()) {
17052 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
17053 << 1 << Attr->getArgumentIdx().getSourceIndex();
17054 return;
17055 }
17056 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
17057 if (IsPointerAttr) {
17058 // Skip implicit cast of pointer to `void *' (as a function argument).
17059 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgumentExpr))
17060 if (ICE->getType()->isVoidPointerType() &&
17061 ICE->getCastKind() == CK_BitCast)
17062 ArgumentExpr = ICE->getSubExpr();
17063 }
17064 QualType ArgumentType = ArgumentExpr->getType();
17065
17066 // Passing a `void*' pointer shouldn't trigger a warning.
17067 if (IsPointerAttr && ArgumentType->isVoidPointerType())
17068 return;
17069
17070 if (TypeInfo.MustBeNull) {
17071 // Type tag with matching void type requires a null pointer.
17072 if (!ArgumentExpr->isNullPointerConstant(Ctx&: Context,
17073 NPC: Expr::NPC_ValueDependentIsNotNull)) {
17074 Diag(Loc: ArgumentExpr->getExprLoc(),
17075 DiagID: diag::warn_type_safety_null_pointer_required)
17076 << ArgumentKind->getName()
17077 << ArgumentExpr->getSourceRange()
17078 << TypeTagExpr->getSourceRange();
17079 }
17080 return;
17081 }
17082
17083 QualType RequiredType = TypeInfo.Type;
17084 if (IsPointerAttr)
17085 RequiredType = Context.getPointerType(T: RequiredType);
17086
17087 bool mismatch = false;
17088 if (!TypeInfo.LayoutCompatible) {
17089 mismatch = !Context.hasSameType(T1: ArgumentType, T2: RequiredType);
17090
17091 // C++11 [basic.fundamental] p1:
17092 // Plain char, signed char, and unsigned char are three distinct types.
17093 //
17094 // But we treat plain `char' as equivalent to `signed char' or `unsigned
17095 // char' depending on the current char signedness mode.
17096 if (mismatch)
17097 if ((IsPointerAttr && IsSameCharType(T1: ArgumentType->getPointeeType(),
17098 T2: RequiredType->getPointeeType())) ||
17099 (!IsPointerAttr && IsSameCharType(T1: ArgumentType, T2: RequiredType)))
17100 mismatch = false;
17101 } else
17102 if (IsPointerAttr)
17103 mismatch = !isLayoutCompatible(C: Context,
17104 T1: ArgumentType->getPointeeType(),
17105 T2: RequiredType->getPointeeType());
17106 else
17107 mismatch = !isLayoutCompatible(C: Context, T1: ArgumentType, T2: RequiredType);
17108
17109 if (mismatch)
17110 Diag(Loc: ArgumentExpr->getExprLoc(), DiagID: diag::warn_type_safety_type_mismatch)
17111 << ArgumentType << ArgumentKind
17112 << TypeInfo.LayoutCompatible << RequiredType
17113 << ArgumentExpr->getSourceRange()
17114 << TypeTagExpr->getSourceRange();
17115}
17116
17117void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
17118 CharUnits Alignment) {
17119 currentEvaluationContext().MisalignedMembers.emplace_back(Args&: E, Args&: RD, Args&: MD,
17120 Args&: Alignment);
17121}
17122
17123void Sema::DiagnoseMisalignedMembers() {
17124 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
17125 const NamedDecl *ND = m.RD;
17126 if (ND->getName().empty()) {
17127 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
17128 ND = TD;
17129 }
17130 Diag(Loc: m.E->getBeginLoc(), DiagID: diag::warn_taking_address_of_packed_member)
17131 << m.MD << ND << m.E->getSourceRange();
17132 }
17133 currentEvaluationContext().MisalignedMembers.clear();
17134}
17135
17136void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
17137 E = E->IgnoreParens();
17138 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
17139 return;
17140 if (isa<UnaryOperator>(Val: E) &&
17141 cast<UnaryOperator>(Val: E)->getOpcode() == UO_AddrOf) {
17142 auto *Op = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
17143 if (isa<MemberExpr>(Val: Op)) {
17144 auto &MisalignedMembersForExpr =
17145 currentEvaluationContext().MisalignedMembers;
17146 auto *MA = llvm::find(Range&: MisalignedMembersForExpr, Val: MisalignedMember(Op));
17147 if (MA != MisalignedMembersForExpr.end() &&
17148 (T->isDependentType() || T->isIntegerType() ||
17149 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
17150 Context.getTypeAlignInChars(
17151 T: T->getPointeeType()) <= MA->Alignment))))
17152 MisalignedMembersForExpr.erase(CI: MA);
17153 }
17154 }
17155}
17156
17157void Sema::RefersToMemberWithReducedAlignment(
17158 Expr *E,
17159 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
17160 Action) {
17161 const auto *ME = dyn_cast<MemberExpr>(Val: E);
17162 if (!ME)
17163 return;
17164
17165 // No need to check expressions with an __unaligned-qualified type.
17166 if (E->getType().getQualifiers().hasUnaligned())
17167 return;
17168
17169 // For a chain of MemberExpr like "a.b.c.d" this list
17170 // will keep FieldDecl's like [d, c, b].
17171 SmallVector<FieldDecl *, 4> ReverseMemberChain;
17172 const MemberExpr *TopME = nullptr;
17173 bool AnyIsPacked = false;
17174 do {
17175 QualType BaseType = ME->getBase()->getType();
17176 if (BaseType->isDependentType())
17177 return;
17178 if (ME->isArrow())
17179 BaseType = BaseType->getPointeeType();
17180 auto *RD = BaseType->castAsRecordDecl();
17181 if (RD->isInvalidDecl())
17182 return;
17183
17184 ValueDecl *MD = ME->getMemberDecl();
17185 auto *FD = dyn_cast<FieldDecl>(Val: MD);
17186 // We do not care about non-data members.
17187 if (!FD || FD->isInvalidDecl())
17188 return;
17189
17190 AnyIsPacked =
17191 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
17192 ReverseMemberChain.push_back(Elt: FD);
17193
17194 TopME = ME;
17195 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParens());
17196 } while (ME);
17197 assert(TopME && "We did not compute a topmost MemberExpr!");
17198
17199 // Not the scope of this diagnostic.
17200 if (!AnyIsPacked)
17201 return;
17202
17203 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
17204 const auto *DRE = dyn_cast<DeclRefExpr>(Val: TopBase);
17205 // TODO: The innermost base of the member expression may be too complicated.
17206 // For now, just disregard these cases. This is left for future
17207 // improvement.
17208 if (!DRE && !isa<CXXThisExpr>(Val: TopBase))
17209 return;
17210
17211 // Alignment expected by the whole expression.
17212 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(T: E->getType());
17213
17214 // No need to do anything else with this case.
17215 if (ExpectedAlignment.isOne())
17216 return;
17217
17218 // Synthesize offset of the whole access.
17219 CharUnits Offset;
17220 for (const FieldDecl *FD : llvm::reverse(C&: ReverseMemberChain))
17221 Offset += Context.toCharUnitsFromBits(BitSize: Context.getFieldOffset(FD));
17222
17223 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
17224 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
17225 T: Context.getCanonicalTagType(TD: ReverseMemberChain.back()->getParent()));
17226
17227 // The base expression of the innermost MemberExpr may give
17228 // stronger guarantees than the class containing the member.
17229 if (DRE && !TopME->isArrow()) {
17230 const ValueDecl *VD = DRE->getDecl();
17231 if (!VD->getType()->isReferenceType())
17232 CompleteObjectAlignment =
17233 std::max(a: CompleteObjectAlignment, b: Context.getDeclAlign(D: VD));
17234 }
17235
17236 // Check if the synthesized offset fulfills the alignment.
17237 if (!Offset.isMultipleOf(N: ExpectedAlignment) ||
17238 // It may fulfill the offset it but the effective alignment may still be
17239 // lower than the expected expression alignment.
17240 CompleteObjectAlignment < ExpectedAlignment) {
17241 // If this happens, we want to determine a sensible culprit of this.
17242 // Intuitively, watching the chain of member expressions from right to
17243 // left, we start with the required alignment (as required by the field
17244 // type) but some packed attribute in that chain has reduced the alignment.
17245 // It may happen that another packed structure increases it again. But if
17246 // we are here such increase has not been enough. So pointing the first
17247 // FieldDecl that either is packed or else its RecordDecl is,
17248 // seems reasonable.
17249 FieldDecl *FD = nullptr;
17250 CharUnits Alignment;
17251 for (FieldDecl *FDI : ReverseMemberChain) {
17252 if (FDI->hasAttr<PackedAttr>() ||
17253 FDI->getParent()->hasAttr<PackedAttr>()) {
17254 FD = FDI;
17255 Alignment = std::min(a: Context.getTypeAlignInChars(T: FD->getType()),
17256 b: Context.getTypeAlignInChars(
17257 T: Context.getCanonicalTagType(TD: FD->getParent())));
17258 break;
17259 }
17260 }
17261 assert(FD && "We did not find a packed FieldDecl!");
17262 Action(E, FD->getParent(), FD, Alignment);
17263 }
17264}
17265
17266void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17267 using namespace std::placeholders;
17268
17269 RefersToMemberWithReducedAlignment(
17270 E: rhs, Action: std::bind(f: &Sema::AddPotentialMisalignedMembers, args: std::ref(t&: *this), args: _1,
17271 args: _2, args: _3, args: _4));
17272}
17273
17274bool Sema::PrepareBuiltinElementwiseMathOneArgCall(
17275 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17276 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17277 return true;
17278
17279 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
17280 if (A.isInvalid())
17281 return true;
17282
17283 TheCall->setArg(Arg: 0, ArgExpr: A.get());
17284 QualType TyA = A.get()->getType();
17285
17286 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
17287 ArgTyRestr, ArgOrdinal: 1))
17288 return true;
17289
17290 TheCall->setType(TyA);
17291 return false;
17292}
17293
17294bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
17295 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17296 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
17297 TheCall->setType(*Res);
17298 return false;
17299 }
17300 return true;
17301}
17302
17303bool Sema::BuiltinVectorToScalarMath(CallExpr *TheCall) {
17304 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
17305 if (!Res)
17306 return true;
17307
17308 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
17309 TheCall->setType(VecTy0->getElementType());
17310 else
17311 TheCall->setType(*Res);
17312
17313 return false;
17314}
17315
17316static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS,
17317 SourceLocation Loc) {
17318 QualType L = LHS->getEnumCoercedType(Ctx: S.Context),
17319 R = RHS->getEnumCoercedType(Ctx: S.Context);
17320 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
17321 !S.Context.hasSameUnqualifiedType(T1: L, T2: R)) {
17322 return S.Diag(Loc, DiagID: diag::err_conv_mixed_enum_types)
17323 << LHS->getSourceRange() << RHS->getSourceRange()
17324 << /*Arithmetic Between*/ 0 << L << R;
17325 }
17326 return false;
17327}
17328
17329/// Check if all arguments have the same type. If the types don't match, emit an
17330/// error message and return true. Otherwise return false.
17331///
17332/// For scalars we directly compare their unqualified types. But even if we
17333/// compare unqualified vector types, a difference in qualifiers in the element
17334/// types can make the vector types be considered not equal. For example,
17335/// vector of 4 'const float' values vs vector of 4 'float' values.
17336/// So we compare unqualified types of their elements and number of elements.
17337static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef,
17338 ArrayRef<Expr *> Args) {
17339 assert(!Args.empty() && "Should have at least one argument.");
17340
17341 Expr *Arg0 = Args.front();
17342 QualType Ty0 = Arg0->getType();
17343
17344 auto EmitError = [&](Expr *ArgI) {
17345 SemaRef.Diag(Loc: Arg0->getBeginLoc(),
17346 DiagID: diag::err_typecheck_call_different_arg_types)
17347 << Arg0->getType() << ArgI->getType();
17348 };
17349
17350 // Compare scalar types.
17351 if (!Ty0->isVectorType()) {
17352 for (Expr *ArgI : Args.drop_front())
17353 if (!SemaRef.Context.hasSameUnqualifiedType(T1: Ty0, T2: ArgI->getType())) {
17354 EmitError(ArgI);
17355 return true;
17356 }
17357
17358 return false;
17359 }
17360
17361 // Compare vector types.
17362 const auto *Vec0 = Ty0->castAs<VectorType>();
17363 for (Expr *ArgI : Args.drop_front()) {
17364 const auto *VecI = ArgI->getType()->getAs<VectorType>();
17365 if (!VecI ||
17366 !SemaRef.Context.hasSameUnqualifiedType(T1: Vec0->getElementType(),
17367 T2: VecI->getElementType()) ||
17368 Vec0->getNumElements() != VecI->getNumElements()) {
17369 EmitError(ArgI);
17370 return true;
17371 }
17372 }
17373
17374 return false;
17375}
17376
17377std::optional<QualType>
17378Sema::BuiltinVectorMath(CallExpr *TheCall,
17379 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17380 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
17381 return std::nullopt;
17382
17383 if (checkBuiltinVectorMathMixedEnums(
17384 S&: *this, LHS: TheCall->getArg(Arg: 0), RHS: TheCall->getArg(Arg: 1), Loc: TheCall->getExprLoc()))
17385 return std::nullopt;
17386
17387 Expr *Args[2];
17388 for (int I = 0; I < 2; ++I) {
17389 ExprResult Converted =
17390 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
17391 if (Converted.isInvalid())
17392 return std::nullopt;
17393 Args[I] = Converted.get();
17394 }
17395
17396 SourceLocation LocA = Args[0]->getBeginLoc();
17397 QualType TyA = Args[0]->getType();
17398
17399 if (checkMathBuiltinElementType(S&: *this, Loc: LocA, ArgTy: TyA, ArgTyRestr, ArgOrdinal: 1))
17400 return std::nullopt;
17401
17402 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
17403 return std::nullopt;
17404
17405 TheCall->setArg(Arg: 0, ArgExpr: Args[0]);
17406 TheCall->setArg(Arg: 1, ArgExpr: Args[1]);
17407 return TyA;
17408}
17409
17410bool Sema::BuiltinElementwiseTernaryMath(
17411 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17412 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
17413 return true;
17414
17415 SourceLocation Loc = TheCall->getExprLoc();
17416 if (checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 0),
17417 RHS: TheCall->getArg(Arg: 1), Loc) ||
17418 checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 1),
17419 RHS: TheCall->getArg(Arg: 2), Loc))
17420 return true;
17421
17422 Expr *Args[3];
17423 for (int I = 0; I < 3; ++I) {
17424 ExprResult Converted =
17425 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
17426 if (Converted.isInvalid())
17427 return true;
17428 Args[I] = Converted.get();
17429 }
17430
17431 int ArgOrdinal = 1;
17432 for (Expr *Arg : Args) {
17433 if (checkMathBuiltinElementType(S&: *this, Loc: Arg->getBeginLoc(), ArgTy: Arg->getType(),
17434 ArgTyRestr, ArgOrdinal: ArgOrdinal++))
17435 return true;
17436 }
17437
17438 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
17439 return true;
17440
17441 for (int I = 0; I < 3; ++I)
17442 TheCall->setArg(Arg: I, ArgExpr: Args[I]);
17443
17444 TheCall->setType(Args[0]->getType());
17445 return false;
17446}
17447
17448bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17449 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17450 return true;
17451
17452 ExprResult A = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
17453 if (A.isInvalid())
17454 return true;
17455
17456 TheCall->setArg(Arg: 0, ArgExpr: A.get());
17457 return false;
17458}
17459
17460bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17461 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17462 return true;
17463
17464 ExprResult Arg = TheCall->getArg(Arg: 0);
17465 QualType TyArg = Arg.get()->getType();
17466
17467 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17468 return Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
17469 DiagID: diag::err_builtin_invalid_arg_type)
17470 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17471
17472 TheCall->setType(TyArg);
17473 return false;
17474}
17475
17476ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17477 ExprResult CallResult) {
17478 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17479 return ExprError();
17480
17481 ExprResult MatrixArg = DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
17482 if (MatrixArg.isInvalid())
17483 return MatrixArg;
17484 Expr *Matrix = MatrixArg.get();
17485
17486 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17487 if (!MType) {
17488 Diag(Loc: Matrix->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17489 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17490 << Matrix->getType();
17491 return ExprError();
17492 }
17493
17494 // Create returned matrix type by swapping rows and columns of the argument
17495 // matrix type.
17496 QualType ResultType = Context.getConstantMatrixType(
17497 ElementType: MType->getElementType(), NumRows: MType->getNumColumns(), NumColumns: MType->getNumRows());
17498
17499 // Change the return type to the type of the returned matrix.
17500 TheCall->setType(ResultType);
17501
17502 // Update call argument to use the possibly converted matrix argument.
17503 TheCall->setArg(Arg: 0, ArgExpr: Matrix);
17504 return CallResult;
17505}
17506
17507// Get and verify the matrix dimensions.
17508static std::optional<unsigned>
17509getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17510 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(Ctx: S.Context);
17511 if (!Value) {
17512 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_scalar_unsigned_arg)
17513 << Name;
17514 return {};
17515 }
17516 uint64_t Dim = Value->getZExtValue();
17517 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17518 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_invalid_dimension)
17519 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17520 return {};
17521 }
17522 return Dim;
17523}
17524
17525ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17526 ExprResult CallResult) {
17527 if (!getLangOpts().MatrixTypes) {
17528 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
17529 return ExprError();
17530 }
17531
17532 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17533 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
17534 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
17535 << /*column*/ 1 << /*load*/ 0;
17536 return ExprError();
17537 }
17538
17539 if (checkArgCount(Call: TheCall, DesiredArgCount: 4))
17540 return ExprError();
17541
17542 unsigned PtrArgIdx = 0;
17543 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
17544 Expr *RowsExpr = TheCall->getArg(Arg: 1);
17545 Expr *ColumnsExpr = TheCall->getArg(Arg: 2);
17546 Expr *StrideExpr = TheCall->getArg(Arg: 3);
17547
17548 bool ArgError = false;
17549
17550 // Check pointer argument.
17551 {
17552 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
17553 if (PtrConv.isInvalid())
17554 return PtrConv;
17555 PtrExpr = PtrConv.get();
17556 TheCall->setArg(Arg: 0, ArgExpr: PtrExpr);
17557 if (PtrExpr->isTypeDependent()) {
17558 TheCall->setType(Context.DependentTy);
17559 return TheCall;
17560 }
17561 }
17562
17563 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17564 QualType ElementTy;
17565 if (!PtrTy) {
17566 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17567 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17568 << PtrExpr->getType();
17569 ArgError = true;
17570 } else {
17571 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17572
17573 if (!ConstantMatrixType::isValidElementType(T: ElementTy, LangOpts: getLangOpts())) {
17574 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17575 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17576 << /* no fp */ 0 << PtrExpr->getType();
17577 ArgError = true;
17578 }
17579 }
17580
17581 // Apply default Lvalue conversions and convert the expression to size_t.
17582 auto ApplyArgumentConversions = [this](Expr *E) {
17583 ExprResult Conv = DefaultLvalueConversion(E);
17584 if (Conv.isInvalid())
17585 return Conv;
17586
17587 return tryConvertExprToType(E: Conv.get(), Ty: Context.getSizeType());
17588 };
17589
17590 // Apply conversion to row and column expressions.
17591 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17592 if (!RowsConv.isInvalid()) {
17593 RowsExpr = RowsConv.get();
17594 TheCall->setArg(Arg: 1, ArgExpr: RowsExpr);
17595 } else
17596 RowsExpr = nullptr;
17597
17598 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17599 if (!ColumnsConv.isInvalid()) {
17600 ColumnsExpr = ColumnsConv.get();
17601 TheCall->setArg(Arg: 2, ArgExpr: ColumnsExpr);
17602 } else
17603 ColumnsExpr = nullptr;
17604
17605 // If any part of the result matrix type is still pending, just use
17606 // Context.DependentTy, until all parts are resolved.
17607 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17608 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17609 TheCall->setType(Context.DependentTy);
17610 return CallResult;
17611 }
17612
17613 // Check row and column dimensions.
17614 std::optional<unsigned> MaybeRows;
17615 if (RowsExpr)
17616 MaybeRows = getAndVerifyMatrixDimension(Expr: RowsExpr, Name: "row", S&: *this);
17617
17618 std::optional<unsigned> MaybeColumns;
17619 if (ColumnsExpr)
17620 MaybeColumns = getAndVerifyMatrixDimension(Expr: ColumnsExpr, Name: "column", S&: *this);
17621
17622 // Check stride argument.
17623 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17624 if (StrideConv.isInvalid())
17625 return ExprError();
17626 StrideExpr = StrideConv.get();
17627 TheCall->setArg(Arg: 3, ArgExpr: StrideExpr);
17628
17629 if (MaybeRows) {
17630 if (std::optional<llvm::APSInt> Value =
17631 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
17632 uint64_t Stride = Value->getZExtValue();
17633 if (Stride < *MaybeRows) {
17634 Diag(Loc: StrideExpr->getBeginLoc(),
17635 DiagID: diag::err_builtin_matrix_stride_too_small);
17636 ArgError = true;
17637 }
17638 }
17639 }
17640
17641 if (ArgError || !MaybeRows || !MaybeColumns)
17642 return ExprError();
17643
17644 TheCall->setType(
17645 Context.getConstantMatrixType(ElementType: ElementTy, NumRows: *MaybeRows, NumColumns: *MaybeColumns));
17646 return CallResult;
17647}
17648
17649ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17650 ExprResult CallResult) {
17651 if (!getLangOpts().MatrixTypes) {
17652 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
17653 return ExprError();
17654 }
17655
17656 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17657 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
17658 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
17659 << /*column*/ 1 << /*store*/ 1;
17660 return ExprError();
17661 }
17662
17663 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
17664 return ExprError();
17665
17666 unsigned PtrArgIdx = 1;
17667 Expr *MatrixExpr = TheCall->getArg(Arg: 0);
17668 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
17669 Expr *StrideExpr = TheCall->getArg(Arg: 2);
17670
17671 bool ArgError = false;
17672
17673 {
17674 ExprResult MatrixConv = DefaultLvalueConversion(E: MatrixExpr);
17675 if (MatrixConv.isInvalid())
17676 return MatrixConv;
17677 MatrixExpr = MatrixConv.get();
17678 TheCall->setArg(Arg: 0, ArgExpr: MatrixExpr);
17679 }
17680 if (MatrixExpr->isTypeDependent()) {
17681 TheCall->setType(Context.DependentTy);
17682 return TheCall;
17683 }
17684
17685 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17686 if (!MatrixTy) {
17687 Diag(Loc: MatrixExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17688 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17689 ArgError = true;
17690 }
17691
17692 {
17693 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
17694 if (PtrConv.isInvalid())
17695 return PtrConv;
17696 PtrExpr = PtrConv.get();
17697 TheCall->setArg(Arg: 1, ArgExpr: PtrExpr);
17698 if (PtrExpr->isTypeDependent()) {
17699 TheCall->setType(Context.DependentTy);
17700 return TheCall;
17701 }
17702 }
17703
17704 // Check pointer argument.
17705 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17706 if (!PtrTy) {
17707 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17708 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17709 << PtrExpr->getType();
17710 ArgError = true;
17711 } else {
17712 QualType ElementTy = PtrTy->getPointeeType();
17713 if (ElementTy.isConstQualified()) {
17714 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_matrix_store_to_const);
17715 ArgError = true;
17716 }
17717 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17718 if (MatrixTy &&
17719 !Context.hasSameType(T1: ElementTy, T2: MatrixTy->getElementType())) {
17720 Diag(Loc: PtrExpr->getBeginLoc(),
17721 DiagID: diag::err_builtin_matrix_pointer_arg_mismatch)
17722 << ElementTy << MatrixTy->getElementType();
17723 ArgError = true;
17724 }
17725 }
17726
17727 // Apply default Lvalue conversions and convert the stride expression to
17728 // size_t.
17729 {
17730 ExprResult StrideConv = DefaultLvalueConversion(E: StrideExpr);
17731 if (StrideConv.isInvalid())
17732 return StrideConv;
17733
17734 StrideConv = tryConvertExprToType(E: StrideConv.get(), Ty: Context.getSizeType());
17735 if (StrideConv.isInvalid())
17736 return StrideConv;
17737 StrideExpr = StrideConv.get();
17738 TheCall->setArg(Arg: 2, ArgExpr: StrideExpr);
17739 }
17740
17741 // Check stride argument.
17742 if (MatrixTy) {
17743 if (std::optional<llvm::APSInt> Value =
17744 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
17745 uint64_t Stride = Value->getZExtValue();
17746 if (Stride < MatrixTy->getNumRows()) {
17747 Diag(Loc: StrideExpr->getBeginLoc(),
17748 DiagID: diag::err_builtin_matrix_stride_too_small);
17749 ArgError = true;
17750 }
17751 }
17752 }
17753
17754 if (ArgError)
17755 return ExprError();
17756
17757 return CallResult;
17758}
17759
17760void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
17761 const NamedDecl *Callee) {
17762 // This warning does not make sense in code that has no runtime behavior.
17763 if (isUnevaluatedContext())
17764 return;
17765
17766 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17767
17768 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17769 return;
17770
17771 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17772 // all TCBs the callee is a part of.
17773 llvm::StringSet<> CalleeTCBs;
17774 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17775 CalleeTCBs.insert(key: A->getTCBName());
17776 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17777 CalleeTCBs.insert(key: A->getTCBName());
17778
17779 // Go through the TCBs the caller is a part of and emit warnings if Caller
17780 // is in a TCB that the Callee is not.
17781 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17782 StringRef CallerTCB = A->getTCBName();
17783 if (CalleeTCBs.count(Key: CallerTCB) == 0) {
17784 this->Diag(Loc: CallExprLoc, DiagID: diag::warn_tcb_enforcement_violation)
17785 << Callee << CallerTCB;
17786 }
17787 }
17788}
17789