1//===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements extra semantic analysis beyond what is enforced
10// by the C type system.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CheckExprLifetime.h"
15#include "clang/AST/APValue.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTDiagnostic.h"
18#include "clang/AST/Attr.h"
19#include "clang/AST/AttrIterator.h"
20#include "clang/AST/CharUnits.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclObjC.h"
25#include "clang/AST/DeclarationName.h"
26#include "clang/AST/EvaluatedExprVisitor.h"
27#include "clang/AST/Expr.h"
28#include "clang/AST/ExprCXX.h"
29#include "clang/AST/ExprObjC.h"
30#include "clang/AST/FormatString.h"
31#include "clang/AST/IgnoreExpr.h"
32#include "clang/AST/NSAPI.h"
33#include "clang/AST/NonTrivialTypeVisitor.h"
34#include "clang/AST/OperationKinds.h"
35#include "clang/AST/RecordLayout.h"
36#include "clang/AST/Stmt.h"
37#include "clang/AST/TemplateBase.h"
38#include "clang/AST/TemplateName.h"
39#include "clang/AST/Type.h"
40#include "clang/AST/TypeBase.h"
41#include "clang/AST/TypeLoc.h"
42#include "clang/AST/UnresolvedSet.h"
43#include "clang/Basic/AddressSpaces.h"
44#include "clang/Basic/Diagnostic.h"
45#include "clang/Basic/DiagnosticSema.h"
46#include "clang/Basic/IdentifierTable.h"
47#include "clang/Basic/LLVM.h"
48#include "clang/Basic/LangOptions.h"
49#include "clang/Basic/OpenCLOptions.h"
50#include "clang/Basic/OperatorKinds.h"
51#include "clang/Basic/PartialDiagnostic.h"
52#include "clang/Basic/SourceLocation.h"
53#include "clang/Basic/SourceManager.h"
54#include "clang/Basic/Specifiers.h"
55#include "clang/Basic/SyncScope.h"
56#include "clang/Basic/TargetInfo.h"
57#include "clang/Basic/TypeTraits.h"
58#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
59#include "clang/Sema/Initialization.h"
60#include "clang/Sema/Lookup.h"
61#include "clang/Sema/Ownership.h"
62#include "clang/Sema/Scope.h"
63#include "clang/Sema/ScopeInfo.h"
64#include "clang/Sema/Sema.h"
65#include "clang/Sema/SemaAMDGPU.h"
66#include "clang/Sema/SemaARM.h"
67#include "clang/Sema/SemaBPF.h"
68#include "clang/Sema/SemaDirectX.h"
69#include "clang/Sema/SemaHLSL.h"
70#include "clang/Sema/SemaHexagon.h"
71#include "clang/Sema/SemaLoongArch.h"
72#include "clang/Sema/SemaMIPS.h"
73#include "clang/Sema/SemaNVPTX.h"
74#include "clang/Sema/SemaObjC.h"
75#include "clang/Sema/SemaOpenCL.h"
76#include "clang/Sema/SemaPPC.h"
77#include "clang/Sema/SemaRISCV.h"
78#include "clang/Sema/SemaSPIRV.h"
79#include "clang/Sema/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
204static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty) {
205 if (Value->isTypeDependent())
206 return false;
207
208 InitializedEntity Entity =
209 InitializedEntity::InitializeParameter(Context&: S.Context, Type: Ty, Consumed: false);
210 ExprResult Result =
211 S.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 errors, even if we managed to build the
545 // call. We don't want to produce more than one error.
546 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred();
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 if (!DABAttr)
1167 return Index;
1168 unsigned DABIndices = DABAttr->argIndices_size();
1169 unsigned NewIndex = Index < DABIndices
1170 ? DABAttr->argIndices_begin()[Index]
1171 : Index - DABIndices + FD->getNumParams();
1172 if (NewIndex >= TheCall->getNumArgs())
1173 return std::nullopt;
1174 return NewIndex;
1175 }
1176
1177 std::optional<llvm::APSInt>
1178 ComputeExplicitObjectSizeArgument(unsigned Index) {
1179 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1180 if (!IndexOptional)
1181 return std::nullopt;
1182 unsigned NewIndex = *IndexOptional;
1183 Expr::EvalResult Result;
1184 Expr *SizeArg = TheCall->getArg(Arg: NewIndex);
1185 if (!SizeArg->EvaluateAsInt(Result, Ctx: S.getASTContext()))
1186 return std::nullopt;
1187 llvm::APSInt Integer = Result.Val.getInt();
1188 assert(Integer.isUnsigned() &&
1189 "size arg should be unsigned after implicit conversion to size_t");
1190 return Integer;
1191 }
1192
1193 std::optional<llvm::APSInt> ComputeSizeArgument(unsigned Index) {
1194 // If the parameter has a pass_object_size attribute, then we should use its
1195 // (potentially) more strict checking mode. Otherwise, conservatively assume
1196 // type 0.
1197 int BOSType = 0;
1198 // This check can fail for variadic functions.
1199 if (Index < FD->getNumParams()) {
1200 if (const auto *POS =
1201 FD->getParamDecl(i: Index)->getAttr<PassObjectSizeAttr>())
1202 BOSType = POS->getType();
1203 }
1204
1205 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1206 if (!IndexOptional)
1207 return std::nullopt;
1208 unsigned NewIndex = *IndexOptional;
1209
1210 if (NewIndex >= TheCall->getNumArgs())
1211 return std::nullopt;
1212
1213 const Expr *ObjArg = TheCall->getArg(Arg: NewIndex);
1214 if (std::optional<uint64_t> ObjSize =
1215 ObjArg->tryEvaluateObjectSize(Ctx: S.getASTContext(), Type: BOSType)) {
1216 // Get the object size in the target's size_t width.
1217 return llvm::APSInt::getUnsigned(X: *ObjSize).extOrTrunc(width: SizeTypeWidth);
1218 }
1219 return std::nullopt;
1220 }
1221
1222 std::optional<llvm::APSInt> ComputeStrLenArgument(unsigned Index) {
1223 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1224 if (!IndexOptional)
1225 return std::nullopt;
1226 unsigned NewIndex = *IndexOptional;
1227
1228 const Expr *ObjArg = TheCall->getArg(Arg: NewIndex);
1229
1230 if (std::optional<uint64_t> Result =
1231 ObjArg->tryEvaluateStrLen(Ctx: S.getASTContext())) {
1232 // Add 1 for null byte.
1233 return llvm::APSInt::getUnsigned(X: *Result + 1).extOrTrunc(width: SizeTypeWidth);
1234 }
1235 return std::nullopt;
1236 }
1237
1238 unsigned getSizeTypeWidth() const { return SizeTypeWidth; }
1239
1240 unsigned getBuiltinID() const {
1241 const FunctionDecl *UseDecl = FD;
1242 if (DABAttr) {
1243 UseDecl = DABAttr->getFunction();
1244 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1245 }
1246 return UseDecl->getBuiltinID(/*ConsiderWrappers=*/ConsiderWrapperFunctions: true);
1247 }
1248
1249 /// Return function name after stripping __builtin_ and _chk affixes.
1250 std::string getFunctionName() const {
1251 unsigned ID = getBuiltinID();
1252 if (!ID) {
1253 // Use callee name directly if not a builtin.
1254 const FunctionDecl *Callee = TheCall->getDirectCallee();
1255 assert(Callee && "expected callee");
1256 return Callee->getName().str();
1257 }
1258 std::string Name = S.getASTContext().BuiltinInfo.getName(ID);
1259 StringRef Ref = Name;
1260 // Strip __builtin___*_chk or __builtin_ prefix.
1261 if (!(Ref.consume_front(Prefix: "__builtin___") && Ref.consume_back(Suffix: "_chk")))
1262 Ref.consume_front(Prefix: "__builtin_");
1263 assert(!Ref.empty() && "expected non-empty function name");
1264 return Ref.str();
1265 }
1266
1267 /// Check for source buffer overread in memory functions.
1268 void checkSourceOverread(unsigned SrcArgIdx, unsigned SizeArgIdx) {
1269 if (S.isConstantEvaluatedContext())
1270 return;
1271
1272 const Expr *SrcArg = TheCall->getArg(Arg: SrcArgIdx);
1273 const Expr *SizeArg = TheCall->getArg(Arg: SizeArgIdx);
1274 if (SrcArg->isInstantiationDependent() ||
1275 SizeArg->isInstantiationDependent())
1276 return;
1277
1278 std::optional<llvm::APSInt> CopyLen =
1279 ComputeExplicitObjectSizeArgument(Index: SizeArgIdx);
1280 std::optional<llvm::APSInt> SrcBufSize = ComputeSizeArgument(Index: SrcArgIdx);
1281
1282 if (!CopyLen || !SrcBufSize)
1283 return;
1284
1285 // Warn only if copy length exceeds source buffer size.
1286 if (llvm::APSInt::compareValues(I1: *CopyLen, I2: *SrcBufSize) <= 0)
1287 return;
1288
1289 S.DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1290 PD: S.PDiag(DiagID: diag::warn_stringop_overread)
1291 << getFunctionName() << CopyLen->getZExtValue()
1292 << SrcBufSize->getZExtValue());
1293 }
1294
1295private:
1296 Sema &S;
1297 CallExpr *TheCall;
1298 FunctionDecl *FD;
1299 const DiagnoseAsBuiltinAttr *DABAttr;
1300 unsigned SizeTypeWidth;
1301};
1302} // anonymous namespace
1303
1304void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
1305 CallExpr *TheCall) {
1306 if (TheCall->isInstantiationDependent() || isConstantEvaluatedContext())
1307 return;
1308
1309 FortifiedBufferChecker Checker(*this, FD, TheCall);
1310
1311 unsigned BuiltinID = Checker.getBuiltinID();
1312 if (!BuiltinID)
1313 return;
1314
1315 unsigned SizeTypeWidth = Checker.getSizeTypeWidth();
1316
1317 std::optional<llvm::APSInt> SourceSize;
1318 std::optional<llvm::APSInt> DestinationSize;
1319 unsigned DiagID = 0;
1320
1321 switch (BuiltinID) {
1322 default:
1323 return;
1324 case Builtin::BI__builtin_strcat:
1325 case Builtin::BIstrcat:
1326 case Builtin::BI__builtin_stpcpy:
1327 case Builtin::BIstpcpy:
1328 case Builtin::BI__builtin_strcpy:
1329 case Builtin::BIstrcpy: {
1330 DiagID = diag::warn_fortify_strlen_overflow;
1331 SourceSize = Checker.ComputeStrLenArgument(Index: 1);
1332 DestinationSize = Checker.ComputeSizeArgument(Index: 0);
1333 break;
1334 }
1335
1336 case Builtin::BI__builtin___strcat_chk:
1337 case Builtin::BI__builtin___stpcpy_chk:
1338 case Builtin::BI__builtin___strcpy_chk: {
1339 DiagID = diag::warn_fortify_strlen_overflow;
1340 SourceSize = Checker.ComputeStrLenArgument(Index: 1);
1341 DestinationSize = Checker.ComputeExplicitObjectSizeArgument(Index: 2);
1342 break;
1343 }
1344
1345 case Builtin::BIscanf:
1346 case Builtin::BIfscanf:
1347 case Builtin::BIsscanf: {
1348 unsigned FormatIndex = 1;
1349 unsigned DataIndex = 2;
1350 if (BuiltinID == Builtin::BIscanf) {
1351 FormatIndex = 0;
1352 DataIndex = 1;
1353 }
1354
1355 const auto *FormatExpr =
1356 TheCall->getArg(Arg: FormatIndex)->IgnoreParenImpCasts();
1357
1358 StringRef FormatStrRef;
1359 size_t StrLen;
1360 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context))
1361 return;
1362
1363 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize,
1364 unsigned SourceSize) {
1365 DiagID = diag::warn_fortify_scanf_overflow;
1366 unsigned Index = ArgIndex + DataIndex;
1367 std::string FunctionName = Checker.getFunctionName();
1368 DiagRuntimeBehavior(Loc: TheCall->getArg(Arg: Index)->getBeginLoc(), Statement: TheCall,
1369 PD: PDiag(DiagID) << FunctionName << (Index + 1)
1370 << DestSize << SourceSize);
1371 };
1372
1373 auto ShiftedComputeSizeArgument = [&](unsigned Index) {
1374 return Checker.ComputeSizeArgument(Index: Index + DataIndex);
1375 };
1376 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose);
1377 const char *FormatBytes = FormatStrRef.data();
1378 analyze_format_string::ParseScanfString(H, beg: FormatBytes,
1379 end: FormatBytes + StrLen, LO: getLangOpts(),
1380 Target: Context.getTargetInfo());
1381
1382 // Unlike the other cases, in this one we have already issued the diagnostic
1383 // here, so no need to continue (because unlike the other cases, here the
1384 // diagnostic refers to the argument number).
1385 return;
1386 }
1387
1388 case Builtin::BIsprintf:
1389 case Builtin::BI__builtin___sprintf_chk: {
1390 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
1391 auto *FormatExpr = TheCall->getArg(Arg: FormatIndex)->IgnoreParenImpCasts();
1392
1393 StringRef FormatStrRef;
1394 size_t StrLen;
1395 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1396 EstimateSizeFormatHandler H(FormatStrRef);
1397 const char *FormatBytes = FormatStrRef.data();
1398 if (!analyze_format_string::ParsePrintfString(
1399 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1400 Target: Context.getTargetInfo(), isFreeBSDKPrintf: false)) {
1401 DiagID = H.isKernelCompatible()
1402 ? diag::warn_format_overflow
1403 : diag::warn_format_overflow_non_kprintf;
1404 SourceSize = llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1405 .extOrTrunc(width: SizeTypeWidth);
1406 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
1407 DestinationSize = Checker.ComputeExplicitObjectSizeArgument(Index: 2);
1408 } else {
1409 DestinationSize = Checker.ComputeSizeArgument(Index: 0);
1410 }
1411 break;
1412 }
1413 }
1414 return;
1415 }
1416 case Builtin::BI__builtin___memcpy_chk:
1417 case Builtin::BI__builtin___memmove_chk:
1418 case Builtin::BI__builtin___memset_chk:
1419 case Builtin::BI__builtin___strlcat_chk:
1420 case Builtin::BI__builtin___strlcpy_chk:
1421 case Builtin::BI__builtin___strncat_chk:
1422 case Builtin::BI__builtin___strncpy_chk:
1423 case Builtin::BI__builtin___stpncpy_chk:
1424 case Builtin::BI__builtin___memccpy_chk:
1425 case Builtin::BI__builtin___mempcpy_chk: {
1426 DiagID = diag::warn_builtin_chk_overflow;
1427 SourceSize =
1428 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 2);
1429 DestinationSize =
1430 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1431
1432 if (BuiltinID == Builtin::BI__builtin___memcpy_chk ||
1433 BuiltinID == Builtin::BI__builtin___memmove_chk ||
1434 BuiltinID == Builtin::BI__builtin___mempcpy_chk) {
1435 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1436 }
1437 break;
1438 }
1439
1440 case Builtin::BI__builtin___snprintf_chk:
1441 case Builtin::BI__builtin___vsnprintf_chk: {
1442 DiagID = diag::warn_builtin_chk_overflow;
1443 SourceSize = Checker.ComputeExplicitObjectSizeArgument(Index: 1);
1444 DestinationSize = Checker.ComputeExplicitObjectSizeArgument(Index: 3);
1445 break;
1446 }
1447
1448 case Builtin::BIstrncat:
1449 case Builtin::BI__builtin_strncat:
1450 case Builtin::BIstrncpy:
1451 case Builtin::BI__builtin_strncpy:
1452 case Builtin::BIstpncpy:
1453 case Builtin::BI__builtin_stpncpy: {
1454 // Whether these functions overflow depends on the runtime strlen of the
1455 // string, not just the buffer size, so emitting the "always overflow"
1456 // diagnostic isn't quite right. We should still diagnose passing a buffer
1457 // size larger than the destination buffer though; this is a runtime abort
1458 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
1459 DiagID = diag::warn_fortify_source_size_mismatch;
1460 SourceSize =
1461 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1462 DestinationSize = Checker.ComputeSizeArgument(Index: 0);
1463 break;
1464 }
1465
1466 case Builtin::BIbzero:
1467 case Builtin::BI__builtin_bzero:
1468 case Builtin::BImemcpy:
1469 case Builtin::BI__builtin_memcpy:
1470 case Builtin::BImemmove:
1471 case Builtin::BI__builtin_memmove:
1472 case Builtin::BImemset:
1473 case Builtin::BI__builtin_memset:
1474 case Builtin::BImempcpy:
1475 case Builtin::BI__builtin_mempcpy: {
1476 DiagID = diag::warn_fortify_source_overflow;
1477 SourceSize =
1478 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1479 DestinationSize = Checker.ComputeSizeArgument(Index: 0);
1480
1481 // Buffer overread doesn't make sense for memset/bzero.
1482 if (BuiltinID != Builtin::BImemset &&
1483 BuiltinID != Builtin::BI__builtin_memset &&
1484 BuiltinID != Builtin::BIbzero &&
1485 BuiltinID != Builtin::BI__builtin_bzero) {
1486 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1487 }
1488 break;
1489 }
1490 case Builtin::BIbcopy:
1491 case Builtin::BI__builtin_bcopy: {
1492 DiagID = diag::warn_fortify_source_overflow;
1493 SourceSize =
1494 Checker.ComputeExplicitObjectSizeArgument(Index: TheCall->getNumArgs() - 1);
1495 DestinationSize = Checker.ComputeSizeArgument(Index: 1);
1496 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1497 break;
1498 }
1499
1500 // memchr(buf, val, size)
1501 case Builtin::BImemchr:
1502 case Builtin::BI__builtin_memchr: {
1503 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1504 return;
1505 }
1506
1507 // memcmp/bcmp(buf0, buf1, size)
1508 // Two checks since each buffer is read
1509 case Builtin::BImemcmp:
1510 case Builtin::BI__builtin_memcmp:
1511 case Builtin::BIbcmp:
1512 case Builtin::BI__builtin_bcmp: {
1513 Checker.checkSourceOverread(/*SrcArgIdx=*/0, /*SizeArgIdx=*/2);
1514 Checker.checkSourceOverread(/*SrcArgIdx=*/1, /*SizeArgIdx=*/2);
1515 return;
1516 }
1517 case Builtin::BIsnprintf:
1518 case Builtin::BI__builtin_snprintf:
1519 case Builtin::BIvsnprintf:
1520 case Builtin::BI__builtin_vsnprintf: {
1521 DiagID = diag::warn_fortify_source_size_mismatch;
1522 SourceSize = Checker.ComputeExplicitObjectSizeArgument(Index: 1);
1523 const auto *FormatExpr = TheCall->getArg(Arg: 2)->IgnoreParenImpCasts();
1524 StringRef FormatStrRef;
1525 size_t StrLen;
1526 if (SourceSize &&
1527 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) {
1528 EstimateSizeFormatHandler H(FormatStrRef);
1529 const char *FormatBytes = FormatStrRef.data();
1530 if (!analyze_format_string::ParsePrintfString(
1531 H, beg: FormatBytes, end: FormatBytes + StrLen, LO: getLangOpts(),
1532 Target: Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) {
1533 llvm::APSInt FormatSize =
1534 llvm::APSInt::getUnsigned(X: H.getSizeLowerBound())
1535 .extOrTrunc(width: SizeTypeWidth);
1536 if (FormatSize > *SourceSize && *SourceSize != 0) {
1537 unsigned TruncationDiagID =
1538 H.isKernelCompatible() ? diag::warn_format_truncation
1539 : diag::warn_format_truncation_non_kprintf;
1540 SmallString<16> SpecifiedSizeStr;
1541 SmallString<16> FormatSizeStr;
1542 SourceSize->toString(Str&: SpecifiedSizeStr, /*Radix=*/10);
1543 FormatSize.toString(Str&: FormatSizeStr, /*Radix=*/10);
1544 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1545 PD: PDiag(DiagID: TruncationDiagID)
1546 << Checker.getFunctionName()
1547 << SpecifiedSizeStr << FormatSizeStr);
1548 }
1549 }
1550 }
1551 DestinationSize = Checker.ComputeSizeArgument(Index: 0);
1552 const Expr *LenArg = TheCall->getArg(Arg: 1)->IgnoreCasts();
1553 const Expr *Dest = TheCall->getArg(Arg: 0)->IgnoreCasts();
1554 IdentifierInfo *FnInfo = FD->getIdentifier();
1555 CheckSizeofMemaccessArgument(SizeOfArg: LenArg, Dest, FnName: FnInfo);
1556 }
1557 }
1558
1559 if (!SourceSize || !DestinationSize ||
1560 llvm::APSInt::compareValues(I1: *SourceSize, I2: *DestinationSize) <= 0)
1561 return;
1562
1563 std::string FunctionName = Checker.getFunctionName();
1564
1565 SmallString<16> DestinationStr;
1566 SmallString<16> SourceStr;
1567 DestinationSize->toString(Str&: DestinationStr, /*Radix=*/10);
1568 SourceSize->toString(Str&: SourceStr, /*Radix=*/10);
1569 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
1570 PD: PDiag(DiagID)
1571 << FunctionName << DestinationStr << SourceStr);
1572}
1573
1574static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
1575 Scope::ScopeFlags NeededScopeFlags,
1576 unsigned DiagID) {
1577 // Scopes aren't available during instantiation. Fortunately, builtin
1578 // functions cannot be template args so they cannot be formed through template
1579 // instantiation. Therefore checking once during the parse is sufficient.
1580 if (SemaRef.inTemplateInstantiation())
1581 return false;
1582
1583 Scope *S = SemaRef.getCurScope();
1584 while (S && !S->isSEHExceptScope())
1585 S = S->getParent();
1586 if (!S || !(S->getFlags() & NeededScopeFlags)) {
1587 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
1588 SemaRef.Diag(Loc: TheCall->getExprLoc(), DiagID)
1589 << DRE->getDecl()->getIdentifier();
1590 return true;
1591 }
1592
1593 return false;
1594}
1595
1596// In OpenCL, __builtin_alloca_* should return a pointer to address space
1597// that corresponds to the stack address space i.e private address space.
1598static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) {
1599 QualType RT = TheCall->getType();
1600 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) &&
1601 "__builtin_alloca has invalid address space");
1602
1603 RT = RT->getPointeeType();
1604 RT = S.Context.getAddrSpaceQualType(T: RT, AddressSpace: LangAS::opencl_private);
1605 TheCall->setType(S.Context.getPointerType(T: RT));
1606}
1607
1608static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall) {
1609 if (S.checkArgCountAtLeast(Call: TheCall, MinArgCount: 1))
1610 return true;
1611
1612 for (Expr *Arg : TheCall->arguments()) {
1613 // If argument is dependent on a template parameter, we can't resolve now.
1614 if (Arg->isTypeDependent() || Arg->isValueDependent())
1615 continue;
1616 // Reject void types.
1617 QualType ArgTy = Arg->IgnoreParenImpCasts()->getType();
1618 if (ArgTy->isVoidType())
1619 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_param_with_void_type);
1620 }
1621
1622 TheCall->setType(S.Context.getSizeType());
1623 return false;
1624}
1625
1626namespace {
1627enum PointerAuthOpKind {
1628 PAO_Strip,
1629 PAO_Sign,
1630 PAO_Auth,
1631 PAO_SignGeneric,
1632 PAO_Discriminator,
1633 PAO_BlendPointer,
1634 PAO_BlendInteger
1635};
1636}
1637
1638bool Sema::checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range) {
1639 if (getLangOpts().PointerAuthIntrinsics)
1640 return false;
1641
1642 Diag(Loc, DiagID: diag::err_ptrauth_disabled) << Range;
1643 return true;
1644}
1645
1646static bool checkPointerAuthEnabled(Sema &S, Expr *E) {
1647 return S.checkPointerAuthEnabled(Loc: E->getExprLoc(), Range: E->getSourceRange());
1648}
1649
1650static bool checkPointerAuthKey(Sema &S, Expr *&Arg) {
1651 // Convert it to type 'int'.
1652 if (convertArgumentToType(S, Value&: Arg, Ty: S.Context.IntTy))
1653 return true;
1654
1655 // Value-dependent expressions are okay; wait for template instantiation.
1656 if (Arg->isValueDependent())
1657 return false;
1658
1659 unsigned KeyValue;
1660 return S.checkConstantPointerAuthKey(keyExpr: Arg, key&: KeyValue);
1661}
1662
1663bool Sema::checkConstantPointerAuthKey(Expr *Arg, unsigned &Result) {
1664 // Attempt to constant-evaluate the expression.
1665 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Ctx: Context);
1666 if (!KeyValue) {
1667 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_expr_not_ice)
1668 << 0 << Arg->getSourceRange();
1669 return true;
1670 }
1671
1672 // Ask the target to validate the key parameter.
1673 if (!Context.getTargetInfo().validatePointerAuthKey(value: *KeyValue)) {
1674 llvm::SmallString<32> Value;
1675 {
1676 llvm::raw_svector_ostream Str(Value);
1677 Str << *KeyValue;
1678 }
1679
1680 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_invalid_key)
1681 << Value << Arg->getSourceRange();
1682 return true;
1683 }
1684
1685 Result = KeyValue->getZExtValue();
1686 return false;
1687}
1688
1689bool Sema::checkPointerAuthDiscriminatorArg(Expr *Arg,
1690 PointerAuthDiscArgKind Kind,
1691 unsigned &IntVal) {
1692 if (!Arg) {
1693 IntVal = 0;
1694 return true;
1695 }
1696
1697 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
1698 if (!Result) {
1699 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_arg_not_ice);
1700 return false;
1701 }
1702
1703 unsigned Max;
1704 bool IsAddrDiscArg = false;
1705
1706 switch (Kind) {
1707 case PointerAuthDiscArgKind::Addr:
1708 Max = 1;
1709 IsAddrDiscArg = true;
1710 break;
1711 case PointerAuthDiscArgKind::Extra:
1712 Max = PointerAuthQualifier::MaxDiscriminator;
1713 break;
1714 };
1715
1716 if (*Result < 0 || *Result > Max) {
1717 if (IsAddrDiscArg)
1718 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_address_discrimination_invalid)
1719 << Result->getExtValue();
1720 else
1721 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_extra_discriminator_invalid)
1722 << Result->getExtValue() << Max;
1723
1724 return false;
1725 };
1726
1727 IntVal = Result->getZExtValue();
1728 return true;
1729}
1730
1731static std::pair<const ValueDecl *, CharUnits>
1732findConstantBaseAndOffset(Sema &S, Expr *E) {
1733 // Must evaluate as a pointer.
1734 Expr::EvalResult Result;
1735 if (!E->EvaluateAsRValue(Result, Ctx: S.Context) || !Result.Val.isLValue())
1736 return {nullptr, CharUnits()};
1737
1738 const auto *BaseDecl =
1739 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>();
1740 if (!BaseDecl)
1741 return {nullptr, CharUnits()};
1742
1743 return {BaseDecl, Result.Val.getLValueOffset()};
1744}
1745
1746static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind,
1747 bool RequireConstant = false) {
1748 if (Arg->hasPlaceholderType()) {
1749 ExprResult R = S.CheckPlaceholderExpr(E: Arg);
1750 if (R.isInvalid())
1751 return true;
1752 Arg = R.get();
1753 }
1754
1755 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1756 return OpKind != PAO_BlendInteger;
1757 };
1758 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1759 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1760 OpKind == PAO_SignGeneric;
1761 };
1762
1763 // Require the value to have the right range of type.
1764 QualType ExpectedTy;
1765 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) {
1766 ExpectedTy = Arg->getType().getUnqualifiedType();
1767 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) {
1768 ExpectedTy = S.Context.VoidPtrTy;
1769 } else if (AllowsInteger(OpKind) &&
1770 Arg->getType()->isIntegralOrUnscopedEnumerationType()) {
1771 ExpectedTy = S.Context.getUIntPtrType();
1772
1773 } else {
1774 // Diagnose the failures.
1775 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_value_bad_type)
1776 << unsigned(OpKind == PAO_Discriminator ? 1
1777 : OpKind == PAO_BlendPointer ? 2
1778 : OpKind == PAO_BlendInteger ? 3
1779 : 0)
1780 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1781 << Arg->getType() << Arg->getSourceRange();
1782 return true;
1783 }
1784
1785 // Convert to that type. This should just be an lvalue-to-rvalue
1786 // conversion.
1787 if (convertArgumentToType(S, Value&: Arg, Ty: ExpectedTy))
1788 return true;
1789
1790 if (!RequireConstant) {
1791 // Warn about null pointers for non-generic sign and auth operations.
1792 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1793 Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNull)) {
1794 S.Diag(Loc: Arg->getExprLoc(), DiagID: OpKind == PAO_Sign
1795 ? diag::warn_ptrauth_sign_null_pointer
1796 : diag::warn_ptrauth_auth_null_pointer)
1797 << Arg->getSourceRange();
1798 }
1799
1800 return false;
1801 }
1802
1803 // Perform special checking on the arguments to ptrauth_sign_constant.
1804
1805 // The main argument.
1806 if (OpKind == PAO_Sign) {
1807 // Require the value we're signing to have a special form.
1808 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Arg);
1809 bool Invalid;
1810
1811 // Must be rooted in a declaration reference.
1812 if (!BaseDecl)
1813 Invalid = true;
1814
1815 // If it's a function declaration, we can't have an offset.
1816 else if (isa<FunctionDecl>(Val: BaseDecl))
1817 Invalid = !Offset.isZero();
1818
1819 // Otherwise we're fine.
1820 else
1821 Invalid = false;
1822
1823 if (Invalid)
1824 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_pointer);
1825 return Invalid;
1826 }
1827
1828 // The discriminator argument.
1829 assert(OpKind == PAO_Discriminator);
1830
1831 // Must be a pointer or integer or blend thereof.
1832 Expr *Pointer = nullptr;
1833 Expr *Integer = nullptr;
1834 if (auto *Call = dyn_cast<CallExpr>(Val: Arg->IgnoreParens())) {
1835 if (Call->getBuiltinCallee() ==
1836 Builtin::BI__builtin_ptrauth_blend_discriminator) {
1837 Pointer = Call->getArg(Arg: 0);
1838 Integer = Call->getArg(Arg: 1);
1839 }
1840 }
1841 if (!Pointer && !Integer) {
1842 if (Arg->getType()->isPointerType())
1843 Pointer = Arg;
1844 else
1845 Integer = Arg;
1846 }
1847
1848 // Check the pointer.
1849 bool Invalid = false;
1850 if (Pointer) {
1851 assert(Pointer->getType()->isPointerType());
1852
1853 // TODO: if we're initializing a global, check that the address is
1854 // somehow related to what we're initializing. This probably will
1855 // never really be feasible and we'll have to catch it at link-time.
1856 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, E: Pointer);
1857 if (!BaseDecl || !isa<VarDecl>(Val: BaseDecl))
1858 Invalid = true;
1859 }
1860
1861 // Check the integer.
1862 if (Integer) {
1863 assert(Integer->getType()->isIntegerType());
1864 if (!Integer->isEvaluatable(Ctx: S.Context))
1865 Invalid = true;
1866 }
1867
1868 if (Invalid)
1869 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_bad_constant_discriminator);
1870 return Invalid;
1871}
1872
1873static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call) {
1874 if (S.checkArgCount(Call, DesiredArgCount: 2))
1875 return ExprError();
1876 if (checkPointerAuthEnabled(S, E: Call))
1877 return ExprError();
1878 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Strip) ||
1879 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]))
1880 return ExprError();
1881
1882 Call->setType(Call->getArgs()[0]->getType());
1883 return Call;
1884}
1885
1886static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call) {
1887 if (S.checkArgCount(Call, DesiredArgCount: 2))
1888 return ExprError();
1889 if (checkPointerAuthEnabled(S, E: Call))
1890 return ExprError();
1891 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_BlendPointer) ||
1892 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_BlendInteger))
1893 return ExprError();
1894
1895 Call->setType(S.Context.getUIntPtrType());
1896 return Call;
1897}
1898
1899static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call) {
1900 if (S.checkArgCount(Call, DesiredArgCount: 2))
1901 return ExprError();
1902 if (checkPointerAuthEnabled(S, E: Call))
1903 return ExprError();
1904 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_SignGeneric) ||
1905 checkPointerAuthValue(S, Arg&: Call->getArgs()[1], OpKind: PAO_Discriminator))
1906 return ExprError();
1907
1908 Call->setType(S.Context.getUIntPtrType());
1909 return Call;
1910}
1911
1912static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call,
1913 PointerAuthOpKind OpKind,
1914 bool RequireConstant) {
1915 if (S.checkArgCount(Call, DesiredArgCount: 3))
1916 return ExprError();
1917 if (checkPointerAuthEnabled(S, E: Call))
1918 return ExprError();
1919 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind, RequireConstant) ||
1920 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1921 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator,
1922 RequireConstant))
1923 return ExprError();
1924
1925 Call->setType(Call->getArgs()[0]->getType());
1926 return Call;
1927}
1928
1929static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call) {
1930 if (S.checkArgCount(Call, DesiredArgCount: 5))
1931 return ExprError();
1932 if (checkPointerAuthEnabled(S, E: Call))
1933 return ExprError();
1934 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
1935 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1936 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
1937 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
1938 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator))
1939 return ExprError();
1940
1941 Call->setType(Call->getArgs()[0]->getType());
1942 return Call;
1943}
1944
1945static ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call) {
1946 if (S.checkArgCount(Call, DesiredArgCount: 6))
1947 return ExprError();
1948 if (checkPointerAuthEnabled(S, E: Call))
1949 return ExprError();
1950 const Expr *AddendExpr = Call->getArg(Arg: 5);
1951 bool AddendIsConstInt = AddendExpr->isIntegerConstantExpr(Ctx: S.Context);
1952 if (!AddendIsConstInt) {
1953 const Expr *Arg = Call->getArg(Arg: 5)->IgnoreParenImpCasts();
1954 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreParenCasts());
1955 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
1956 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_constant_integer_last_arg_type)
1957 << FDecl->getDeclName() << Arg->getSourceRange();
1958 }
1959 if (checkPointerAuthValue(S, Arg&: Call->getArgs()[0], OpKind: PAO_Auth) ||
1960 checkPointerAuthKey(S, Arg&: Call->getArgs()[1]) ||
1961 checkPointerAuthValue(S, Arg&: Call->getArgs()[2], OpKind: PAO_Discriminator) ||
1962 checkPointerAuthKey(S, Arg&: Call->getArgs()[3]) ||
1963 checkPointerAuthValue(S, Arg&: Call->getArgs()[4], OpKind: PAO_Discriminator) ||
1964 !AddendIsConstInt)
1965 return ExprError();
1966
1967 Call->setType(Call->getArgs()[0]->getType());
1968 return Call;
1969}
1970
1971static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call) {
1972 if (checkPointerAuthEnabled(S, E: Call))
1973 return ExprError();
1974
1975 // We've already performed normal call type-checking.
1976 const Expr *Arg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
1977
1978 // Operand must be an ordinary or UTF-8 string literal.
1979 const auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
1980 if (!Literal || Literal->getCharByteWidth() != 1) {
1981 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_ptrauth_string_not_literal)
1982 << (Literal ? 1 : 0) << Arg->getSourceRange();
1983 return ExprError();
1984 }
1985
1986 return Call;
1987}
1988
1989static ExprResult GetVTablePointer(Sema &S, CallExpr *Call) {
1990 if (S.checkArgCount(Call, DesiredArgCount: 1))
1991 return ExprError();
1992 Expr *FirstArg = Call->getArg(Arg: 0);
1993 ExprResult FirstValue = S.DefaultFunctionArrayLvalueConversion(E: FirstArg);
1994 if (FirstValue.isInvalid())
1995 return ExprError();
1996 Call->setArg(Arg: 0, ArgExpr: FirstValue.get());
1997 QualType FirstArgType = FirstArg->getType();
1998 if (FirstArgType->canDecayToPointerType() && FirstArgType->isArrayType())
1999 FirstArgType = S.Context.getDecayedType(T: FirstArgType);
2000
2001 const CXXRecordDecl *FirstArgRecord = FirstArgType->getPointeeCXXRecordDecl();
2002 if (!FirstArgRecord) {
2003 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
2004 << /*isPolymorphic=*/0 << FirstArgType;
2005 return ExprError();
2006 }
2007 if (S.RequireCompleteType(
2008 Loc: FirstArg->getBeginLoc(), T: FirstArgType->getPointeeType(),
2009 DiagID: diag::err_get_vtable_pointer_requires_complete_type)) {
2010 return ExprError();
2011 }
2012
2013 if (!FirstArgRecord->isPolymorphic()) {
2014 S.Diag(Loc: FirstArg->getBeginLoc(), DiagID: diag::err_get_vtable_pointer_incorrect_type)
2015 << /*isPolymorphic=*/1 << FirstArgRecord;
2016 return ExprError();
2017 }
2018 QualType ReturnType = S.Context.getPointerType(T: S.Context.VoidTy.withConst());
2019 Call->setType(ReturnType);
2020 return Call;
2021}
2022
2023static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) {
2024 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2025 return ExprError();
2026
2027 // Compute __builtin_launder's parameter type from the argument.
2028 // The parameter type is:
2029 // * The type of the argument if it's not an array or function type,
2030 // Otherwise,
2031 // * The decayed argument type.
2032 QualType ParamTy = [&]() {
2033 QualType ArgTy = TheCall->getArg(Arg: 0)->getType();
2034 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
2035 return S.Context.getPointerType(T: Ty->getElementType());
2036 if (ArgTy->isFunctionType()) {
2037 return S.Context.getPointerType(T: ArgTy);
2038 }
2039 return ArgTy;
2040 }();
2041
2042 TheCall->setType(ParamTy);
2043
2044 auto DiagSelect = [&]() -> std::optional<unsigned> {
2045 if (!ParamTy->isPointerType())
2046 return 0;
2047 if (ParamTy->isFunctionPointerType())
2048 return 1;
2049 if (ParamTy->isVoidPointerType())
2050 return 2;
2051 return std::optional<unsigned>{};
2052 }();
2053 if (DiagSelect) {
2054 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_launder_invalid_arg)
2055 << *DiagSelect << TheCall->getSourceRange();
2056 return ExprError();
2057 }
2058
2059 // We either have an incomplete class type, or we have a class template
2060 // whose instantiation has not been forced. Example:
2061 //
2062 // template <class T> struct Foo { T value; };
2063 // Foo<int> *p = nullptr;
2064 // auto *d = __builtin_launder(p);
2065 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T: ParamTy->getPointeeType(),
2066 DiagID: diag::err_incomplete_type))
2067 return ExprError();
2068
2069 assert(ParamTy->getPointeeType()->isObjectType() &&
2070 "Unhandled non-object pointer case");
2071
2072 InitializedEntity Entity =
2073 InitializedEntity::InitializeParameter(Context&: S.Context, Type: ParamTy, Consumed: false);
2074 ExprResult Arg =
2075 S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: TheCall->getArg(Arg: 0));
2076 if (Arg.isInvalid())
2077 return ExprError();
2078 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
2079
2080 return TheCall;
2081}
2082
2083static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall) {
2084 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2085 return ExprError();
2086
2087 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
2088 if (Arg.isInvalid())
2089 return ExprError();
2090 QualType ParamTy = Arg.get()->getType();
2091 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
2092 TheCall->setType(S.Context.BoolTy);
2093
2094 // Only accept pointers to objects as arguments, which should have object
2095 // pointer or void pointer types.
2096 if (const auto *PT = ParamTy->getAs<PointerType>()) {
2097 // LWG4138: Function pointer types not allowed
2098 if (PT->getPointeeType()->isFunctionType()) {
2099 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2100 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2101 << 1;
2102 return ExprError();
2103 }
2104 // Disallow VLAs too since those shouldn't be able to
2105 // be a template parameter for `std::is_within_lifetime`
2106 if (PT->getPointeeType()->isVariableArrayType()) {
2107 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(), DiagID: diag::err_vla_unsupported)
2108 << 1 << "__builtin_is_within_lifetime";
2109 return ExprError();
2110 }
2111 } else {
2112 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2113 DiagID: diag::err_builtin_is_within_lifetime_invalid_arg)
2114 << 0;
2115 return ExprError();
2116 }
2117 return TheCall;
2118}
2119
2120static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall) {
2121 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2122 return ExprError();
2123
2124 QualType Dest = TheCall->getArg(Arg: 0)->getType();
2125 if (!Dest->isPointerType() || Dest.getCVRQualifiers() != 0) {
2126 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2127 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2128 << /*a pointer*/ 0;
2129 return ExprError();
2130 }
2131
2132 QualType T = Dest->getPointeeType();
2133 if (S.RequireCompleteType(Loc: TheCall->getBeginLoc(), T,
2134 DiagID: diag::err_incomplete_type))
2135 return ExprError();
2136
2137 if (T.isConstQualified() || !S.IsCXXTriviallyRelocatableType(T) ||
2138 T->isIncompleteArrayType()) {
2139 S.Diag(Loc: TheCall->getArg(Arg: 0)->getExprLoc(),
2140 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2141 << (T.isConstQualified() ? /*non-const*/ 1 : /*relocatable*/ 2);
2142 return ExprError();
2143 }
2144
2145 TheCall->setType(Dest);
2146
2147 QualType Src = TheCall->getArg(Arg: 1)->getType();
2148 if (Src.getCanonicalType() != Dest.getCanonicalType()) {
2149 S.Diag(Loc: TheCall->getArg(Arg: 1)->getExprLoc(),
2150 DiagID: diag::err_builtin_trivially_relocate_invalid_arg_type)
2151 << /*the same*/ 3;
2152 return ExprError();
2153 }
2154
2155 Expr *SizeExpr = TheCall->getArg(Arg: 2);
2156 ExprResult Size = S.DefaultLvalueConversion(E: SizeExpr);
2157 if (Size.isInvalid())
2158 return ExprError();
2159
2160 Size = S.tryConvertExprToType(E: Size.get(), Ty: S.getASTContext().getSizeType());
2161 if (Size.isInvalid())
2162 return ExprError();
2163 SizeExpr = Size.get();
2164 TheCall->setArg(Arg: 2, ArgExpr: SizeExpr);
2165
2166 return TheCall;
2167}
2168
2169// Emit an error and return true if the current object format type is in the
2170// list of unsupported types.
2171static bool CheckBuiltinTargetNotInUnsupported(
2172 Sema &S, unsigned BuiltinID, CallExpr *TheCall,
2173 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) {
2174 llvm::Triple::ObjectFormatType CurObjFormat =
2175 S.getASTContext().getTargetInfo().getTriple().getObjectFormat();
2176 if (llvm::is_contained(Range&: UnsupportedObjectFormatTypes, Element: CurObjFormat)) {
2177 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2178 << TheCall->getSourceRange();
2179 return true;
2180 }
2181 return false;
2182}
2183
2184// Emit an error and return true if the current architecture is not in the list
2185// of supported architectures.
2186static bool
2187CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall,
2188 ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
2189 llvm::Triple::ArchType CurArch =
2190 S.getASTContext().getTargetInfo().getTriple().getArch();
2191 if (llvm::is_contained(Range&: SupportedArchs, Element: CurArch))
2192 return false;
2193 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
2194 << TheCall->getSourceRange();
2195 return true;
2196}
2197
2198static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
2199 SourceLocation CallSiteLoc);
2200
2201bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2202 CallExpr *TheCall) {
2203 switch (TI.getTriple().getArch()) {
2204 default:
2205 // Some builtins don't require additional checking, so just consider these
2206 // acceptable.
2207 return false;
2208 case llvm::Triple::arm:
2209 case llvm::Triple::armeb:
2210 case llvm::Triple::thumb:
2211 case llvm::Triple::thumbeb:
2212 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
2213 case llvm::Triple::aarch64:
2214 case llvm::Triple::aarch64_32:
2215 case llvm::Triple::aarch64_be:
2216 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
2217 case llvm::Triple::bpfeb:
2218 case llvm::Triple::bpfel:
2219 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
2220 case llvm::Triple::dxil:
2221 return DirectX().CheckDirectXBuiltinFunctionCall(BuiltinID, TheCall);
2222 case llvm::Triple::hexagon:
2223 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
2224 case llvm::Triple::mips:
2225 case llvm::Triple::mipsel:
2226 case llvm::Triple::mips64:
2227 case llvm::Triple::mips64el:
2228 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
2229 case llvm::Triple::spirv:
2230 case llvm::Triple::spirv32:
2231 case llvm::Triple::spirv64:
2232 if (TI.getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2233 return SPIRV().CheckSPIRVBuiltinFunctionCall(TI, BuiltinID, TheCall);
2234 return false;
2235 case llvm::Triple::systemz:
2236 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
2237 case llvm::Triple::x86:
2238 case llvm::Triple::x86_64:
2239 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2240 case llvm::Triple::ppc:
2241 case llvm::Triple::ppcle:
2242 case llvm::Triple::ppc64:
2243 case llvm::Triple::ppc64le:
2244 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
2245 case llvm::Triple::amdgcn:
2246 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
2247 case llvm::Triple::riscv32:
2248 case llvm::Triple::riscv64:
2249 case llvm::Triple::riscv32be:
2250 case llvm::Triple::riscv64be:
2251 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall);
2252 case llvm::Triple::loongarch32:
2253 case llvm::Triple::loongarch64:
2254 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID,
2255 TheCall);
2256 case llvm::Triple::wasm32:
2257 case llvm::Triple::wasm64:
2258 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall);
2259 case llvm::Triple::nvptx:
2260 case llvm::Triple::nvptx64:
2261 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall);
2262 }
2263}
2264
2265static bool isValidMathElementType(QualType T) {
2266 return T->isDependentType() ||
2267 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
2268}
2269
2270// Check if \p Ty is a valid type for the elementwise math builtins. If it is
2271// not a valid type, emit an error message and return true. Otherwise return
2272// false.
2273static bool
2274checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy,
2275 Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr,
2276 int ArgOrdinal) {
2277 clang::QualType EltTy =
2278 ArgTy->isVectorType() ? ArgTy->getAs<VectorType>()->getElementType()
2279 : ArgTy->isMatrixType() ? ArgTy->getAs<MatrixType>()->getElementType()
2280 : ArgTy;
2281
2282 switch (ArgTyRestr) {
2283 case Sema::EltwiseBuiltinArgTyRestriction::None:
2284 if (!ArgTy->getAs<VectorType>() && !isValidMathElementType(T: ArgTy)) {
2285 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2286 << ArgOrdinal << /* vector */ 2 << /* integer */ 1 << /* fp */ 1
2287 << ArgTy;
2288 }
2289 break;
2290 case Sema::EltwiseBuiltinArgTyRestriction::FloatTy:
2291 if (!EltTy->isRealFloatingType()) {
2292 // FIXME: make diagnostic's wording correct for matrices
2293 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2294 << ArgOrdinal << /* scalar or vector */ 5 << /* no int */ 0
2295 << /* floating-point */ 1 << ArgTy;
2296 }
2297 break;
2298 case Sema::EltwiseBuiltinArgTyRestriction::IntegerTy:
2299 if (!EltTy->isIntegerType()) {
2300 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2301 << ArgOrdinal << /* scalar or vector */ 5 << /* integer */ 1
2302 << /* no fp */ 0 << ArgTy;
2303 }
2304 break;
2305 case Sema::EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy:
2306 if (!EltTy->isSignedIntegerType() && !EltTy->isRealFloatingType()) {
2307 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2308 << 1 << /* scalar or vector */ 5 << /* signed int */ 2
2309 << /* or fp */ 1 << ArgTy;
2310 }
2311 break;
2312 }
2313
2314 return false;
2315}
2316
2317/// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
2318/// This checks that the target supports the builtin and that the string
2319/// argument is constant and valid.
2320static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall,
2321 const TargetInfo *AuxTI, unsigned BuiltinID) {
2322 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2323 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2324 "Expecting __builtin_cpu_...");
2325
2326 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2327 const TargetInfo *TheTI = &TI;
2328 auto SupportsBI = [=](const TargetInfo *TInfo) {
2329 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2330 (!IsCPUSupports && TInfo->supportsCpuIs()));
2331 };
2332 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2333 TheTI = AuxTI;
2334
2335 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) ||
2336 (IsCPUSupports && !TheTI->supportsCpuSupports()))
2337 return S.Diag(Loc: TheCall->getBeginLoc(),
2338 DiagID: TI.getTriple().isOSAIX()
2339 ? diag::err_builtin_aix_os_unsupported
2340 : diag::err_builtin_target_unsupported)
2341 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
2342
2343 Expr *Arg = TheCall->getArg(Arg: 0)->IgnoreParenImpCasts();
2344 // Check if the argument is a string literal.
2345 if (!isa<StringLiteral>(Val: Arg))
2346 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
2347 << Arg->getSourceRange();
2348
2349 // Check the contents of the string.
2350 StringRef Feature = cast<StringLiteral>(Val: Arg)->getString();
2351 if (IsCPUSupports && !TheTI->validateCpuSupports(Name: Feature)) {
2352 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_invalid_cpu_supports)
2353 << Arg->getSourceRange();
2354 return false;
2355 }
2356 if (!IsCPUSupports && !TheTI->validateCpuIs(Name: Feature))
2357 return S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_cpu_is)
2358 << Arg->getSourceRange();
2359 return false;
2360}
2361
2362/// Checks that __builtin_bswapg was called with a single argument, which is an
2363/// unsigned integer, and overrides the return value type to the integer type.
2364static bool BuiltinBswapg(Sema &S, CallExpr *TheCall) {
2365 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2366 return true;
2367 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2368 if (ArgRes.isInvalid())
2369 return true;
2370
2371 Expr *Arg = ArgRes.get();
2372 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2373 if (Arg->isTypeDependent())
2374 return false;
2375
2376 QualType ArgTy = Arg->getType();
2377
2378 if (!ArgTy->isIntegerType()) {
2379 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2380 << 1 << /*scalar=*/1 << /*unsigned integer=*/1 << /*floating point=*/0
2381 << ArgTy;
2382 return true;
2383 }
2384 if (const auto *BT = dyn_cast<BitIntType>(Val&: ArgTy)) {
2385 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2386 BT->getNumBits() != 1) {
2387 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_bswapg_invalid_bit_width)
2388 << ArgTy << BT->getNumBits();
2389 return true;
2390 }
2391 }
2392 TheCall->setType(ArgTy);
2393 return false;
2394}
2395
2396/// Checks that __builtin_bitreverseg was called with a single argument, which
2397/// is an integer
2398static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall) {
2399 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2400 return true;
2401 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2402 if (ArgRes.isInvalid())
2403 return true;
2404
2405 Expr *Arg = ArgRes.get();
2406 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2407 if (Arg->isTypeDependent())
2408 return false;
2409
2410 QualType ArgTy = Arg->getType();
2411
2412 if (!ArgTy->isIntegerType()) {
2413 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2414 << 1 << /*scalar=*/1 << /*unsigned integer*/ 1 << /*float point*/ 0
2415 << ArgTy;
2416 return true;
2417 }
2418 TheCall->setType(ArgTy);
2419 return false;
2420}
2421
2422/// Checks that __builtin_popcountg was called with a single argument, which is
2423/// an unsigned integer.
2424static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) {
2425 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2426 return true;
2427
2428 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2429 if (ArgRes.isInvalid())
2430 return true;
2431
2432 Expr *Arg = ArgRes.get();
2433 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2434
2435 QualType ArgTy = Arg->getType();
2436
2437 if (!ArgTy->isUnsignedIntegerType() && !ArgTy->isExtVectorBoolType()) {
2438 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2439 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2440 << ArgTy;
2441 return true;
2442 }
2443 return false;
2444}
2445
2446/// Checks the __builtin_stdc_* builtins that take a single unsigned integer
2447/// argument and return either int, bool, or the argument type.
2448static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall,
2449 QualType ReturnType) {
2450 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 1))
2451 return true;
2452
2453 ExprResult ArgRes = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2454 if (ArgRes.isInvalid())
2455 return true;
2456
2457 Expr *Arg = ArgRes.get();
2458 TheCall->setArg(Arg: 0, ArgExpr: Arg);
2459
2460 QualType ArgTy = Arg->getType();
2461 // C23 stdbit.h functions do not permit bool or enumeration types.
2462 if (ArgTy->isBooleanType() || ArgTy->isEnumeralType())
2463 return S.Diag(Loc: Arg->getBeginLoc(),
2464 DiagID: diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2465 << 1 /*1st argument*/ << ArgTy;
2466 if (!ArgTy->isUnsignedIntegerType())
2467 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_stdc_invalid_arg_type)
2468 << 1 /*1st argument*/ << ArgTy;
2469
2470 // For builtins returning unsigned int, verify the argument's bit width fits.
2471 // On targets where unsigned int is 16 bits, a large _BitInt argument could
2472 // produce a count that overflows the return type.
2473 if (!ReturnType.isNull() && ReturnType == S.Context.UnsignedIntTy) {
2474 uint64_t ArgWidth = S.Context.getIntWidth(T: ArgTy);
2475 uint64_t ReturnTypeWidth = S.Context.getIntWidth(T: S.Context.UnsignedIntTy);
2476 if (!llvm::isUIntN(N: ReturnTypeWidth, x: ArgWidth))
2477 return S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_stdc_result_overflow)
2478 << ArgTy;
2479 }
2480
2481 TheCall->setType(ReturnType.isNull() ? ArgTy : ReturnType);
2482 return false;
2483}
2484
2485/// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is
2486/// an unsigned integer, and an optional second argument, which is promoted to
2487/// an 'int'.
2488static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) {
2489 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
2490 return true;
2491
2492 ExprResult Arg0Res = S.DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
2493 if (Arg0Res.isInvalid())
2494 return true;
2495
2496 Expr *Arg0 = Arg0Res.get();
2497 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2498
2499 QualType Arg0Ty = Arg0->getType();
2500
2501 if (!Arg0Ty->isUnsignedIntegerType() && !Arg0Ty->isExtVectorBoolType()) {
2502 S.Diag(Loc: Arg0->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2503 << 1 << /* scalar */ 1 << /* unsigned integer ty */ 3 << /* no fp */ 0
2504 << Arg0Ty;
2505 return true;
2506 }
2507
2508 if (TheCall->getNumArgs() > 1) {
2509 ExprResult Arg1Res = S.UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
2510 if (Arg1Res.isInvalid())
2511 return true;
2512
2513 Expr *Arg1 = Arg1Res.get();
2514 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2515
2516 QualType Arg1Ty = Arg1->getType();
2517
2518 if (!Arg1Ty->isSpecificBuiltinType(K: BuiltinType::Int)) {
2519 S.Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2520 << 2 << /* scalar */ 1 << /* 'int' ty */ 4 << /* no fp */ 0 << Arg1Ty;
2521 return true;
2522 }
2523 }
2524
2525 return false;
2526}
2527
2528class RotateIntegerConverter : public Sema::ContextualImplicitConverter {
2529 unsigned ArgIndex;
2530 bool OnlyUnsigned;
2531
2532 Sema::SemaDiagnosticBuilder emitError(Sema &S, SourceLocation Loc,
2533 QualType T) {
2534 return S.Diag(Loc, DiagID: diag::err_builtin_invalid_arg_type)
2535 << ArgIndex << /*scalar*/ 1
2536 << (OnlyUnsigned ? /*unsigned integer*/ 3 : /*integer*/ 1)
2537 << /*no fp*/ 0 << T;
2538 }
2539
2540public:
2541 RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
2542 : ContextualImplicitConverter(/*Suppress=*/false,
2543 /*SuppressConversion=*/true),
2544 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2545
2546 bool match(QualType T) override {
2547 return OnlyUnsigned ? T->isUnsignedIntegerType() : T->isIntegerType();
2548 }
2549
2550 Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2551 QualType T) override {
2552 return emitError(S, Loc, T);
2553 }
2554
2555 Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2556 QualType T) override {
2557 return emitError(S, Loc, T);
2558 }
2559
2560 Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2561 QualType T,
2562 QualType ConvTy) override {
2563 return emitError(S, Loc, T);
2564 }
2565
2566 Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2567 QualType ConvTy) override {
2568 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2569 }
2570
2571 Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2572 QualType T) override {
2573 return emitError(S, Loc, T);
2574 }
2575
2576 Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2577 QualType ConvTy) override {
2578 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_conv_function_declared_at);
2579 }
2580
2581 Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2582 QualType T,
2583 QualType ConvTy) override {
2584 llvm_unreachable("conversion functions are permitted");
2585 }
2586};
2587
2588/// Checks that __builtin_stdc_rotate_{left,right} was called with two
2589/// arguments, that the first argument is an unsigned integer type, and that
2590/// the second argument is an integer type.
2591static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall) {
2592 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
2593 return true;
2594
2595 // First argument (value to rotate) must be unsigned integer type.
2596 RotateIntegerConverter Arg0Converter(1, /*OnlyUnsigned=*/true);
2597 ExprResult Arg0Res = S.PerformContextualImplicitConversion(
2598 Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), FromE: TheCall->getArg(Arg: 0), Converter&: Arg0Converter);
2599 if (Arg0Res.isInvalid())
2600 return true;
2601
2602 Expr *Arg0 = Arg0Res.get();
2603 TheCall->setArg(Arg: 0, ArgExpr: Arg0);
2604
2605 QualType Arg0Ty = Arg0->getType();
2606 if (!Arg0Ty->isUnsignedIntegerType())
2607 return true;
2608
2609 // Second argument (rotation count) must be integer type.
2610 RotateIntegerConverter Arg1Converter(2, /*OnlyUnsigned=*/false);
2611 ExprResult Arg1Res = S.PerformContextualImplicitConversion(
2612 Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), FromE: TheCall->getArg(Arg: 1), Converter&: Arg1Converter);
2613 if (Arg1Res.isInvalid())
2614 return true;
2615
2616 Expr *Arg1 = Arg1Res.get();
2617 TheCall->setArg(Arg: 1, ArgExpr: Arg1);
2618
2619 QualType Arg1Ty = Arg1->getType();
2620 if (!Arg1Ty->isIntegerType())
2621 return true;
2622
2623 TheCall->setType(Arg0Ty);
2624 return false;
2625}
2626
2627static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg,
2628 unsigned Pos, bool AllowConst,
2629 bool AllowAS) {
2630 QualType MaskTy = MaskArg->getType();
2631 if (!MaskTy->isExtVectorBoolType())
2632 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2633 << 1 << /* vector of */ 4 << /* booleans */ 6 << /* no fp */ 0
2634 << MaskTy;
2635
2636 QualType PtrTy = PtrArg->getType();
2637 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2638 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2639 << Pos << "scalar pointer";
2640
2641 QualType PointeeTy = PtrTy->getPointeeType();
2642 if (PointeeTy.isVolatileQualified() || PointeeTy->isAtomicType() ||
2643 (!AllowConst && PointeeTy.isConstQualified()) ||
2644 (!AllowAS && PointeeTy.hasAddressSpace())) {
2645 QualType Target =
2646 S.Context.getPointerType(T: PointeeTy.getAtomicUnqualifiedType());
2647 return S.Diag(Loc: PtrArg->getExprLoc(),
2648 DiagID: diag::err_typecheck_convert_incompatible)
2649 << PtrTy << Target << /*different qualifiers=*/5
2650 << /*qualifier difference=*/0 << /*parameter mismatch=*/3 << 2
2651 << PtrTy << Target;
2652 }
2653 return false;
2654}
2655
2656static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall) {
2657 bool TypeDependent = false;
2658 for (unsigned Arg = 0, E = TheCall->getNumArgs(); Arg != E; ++Arg) {
2659 ExprResult Converted =
2660 S.DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg));
2661 if (Converted.isInvalid())
2662 return true;
2663 TheCall->setArg(Arg, ArgExpr: Converted.get());
2664 TypeDependent |= Converted.get()->isTypeDependent();
2665 }
2666
2667 if (TypeDependent)
2668 TheCall->setType(S.Context.DependentTy);
2669 return false;
2670}
2671
2672static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall) {
2673 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
2674 return ExprError();
2675
2676 if (ConvertMaskedBuiltinArgs(S, TheCall))
2677 return ExprError();
2678
2679 Expr *MaskArg = TheCall->getArg(Arg: 0);
2680 Expr *PtrArg = TheCall->getArg(Arg: 1);
2681 if (TheCall->isTypeDependent())
2682 return TheCall;
2683
2684 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 2, /*AllowConst=*/true,
2685 AllowAS: TheCall->getBuiltinCallee() ==
2686 Builtin::BI__builtin_masked_load))
2687 return ExprError();
2688
2689 QualType MaskTy = MaskArg->getType();
2690 QualType PtrTy = PtrArg->getType();
2691 QualType PointeeTy = PtrTy->getPointeeType();
2692 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2693
2694 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2695 NumElts: MaskVecTy->getNumElements());
2696 if (TheCall->getNumArgs() == 3) {
2697 Expr *PassThruArg = TheCall->getArg(Arg: 2);
2698 QualType PassThruTy = PassThruArg->getType();
2699 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2700 return S.Diag(Loc: PtrArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2701 << /* third argument */ 3 << RetTy;
2702 }
2703
2704 TheCall->setType(RetTy);
2705 return TheCall;
2706}
2707
2708static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall) {
2709 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 3))
2710 return ExprError();
2711
2712 if (ConvertMaskedBuiltinArgs(S, TheCall))
2713 return ExprError();
2714
2715 Expr *MaskArg = TheCall->getArg(Arg: 0);
2716 Expr *ValArg = TheCall->getArg(Arg: 1);
2717 Expr *PtrArg = TheCall->getArg(Arg: 2);
2718 if (TheCall->isTypeDependent())
2719 return TheCall;
2720
2721 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/false,
2722 AllowAS: TheCall->getBuiltinCallee() ==
2723 Builtin::BI__builtin_masked_store))
2724 return ExprError();
2725
2726 QualType MaskTy = MaskArg->getType();
2727 QualType PtrTy = PtrArg->getType();
2728 QualType ValTy = ValArg->getType();
2729 if (!ValTy->isVectorType())
2730 return ExprError(
2731 S.Diag(Loc: ValArg->getExprLoc(), DiagID: diag::err_vec_masked_load_store_ptr)
2732 << 2 << "vector");
2733
2734 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2735 const VectorType *ValVecTy = ValTy->getAs<VectorType>();
2736
2737 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements()) {
2738 return ExprError(
2739 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2740 << S.getASTContext().BuiltinInfo.getQuotedName(
2741 ID: TheCall->getBuiltinCallee())
2742 << MaskTy << ValTy);
2743 }
2744
2745 if (!S.Context.hasSameType(T1: ValVecTy->getElementType().getUnqualifiedType(),
2746 T2: PtrTy->getPointeeType().getUnqualifiedType()))
2747 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
2748 DiagID: diag::err_vec_builtin_incompatible_vector)
2749 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ 2
2750 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
2751 TheCall->getArg(Arg: 1)->getEndLoc()));
2752
2753 TheCall->setType(S.Context.VoidTy);
2754 return TheCall;
2755}
2756
2757static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall) {
2758 if (S.checkArgCountRange(Call: TheCall, MinArgCount: 3, MaxArgCount: 4))
2759 return ExprError();
2760
2761 if (ConvertMaskedBuiltinArgs(S, TheCall))
2762 return ExprError();
2763
2764 Expr *MaskArg = TheCall->getArg(Arg: 0);
2765 Expr *IdxArg = TheCall->getArg(Arg: 1);
2766 Expr *PtrArg = TheCall->getArg(Arg: 2);
2767 if (TheCall->isTypeDependent())
2768 return TheCall;
2769
2770 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 3, /*AllowConst=*/true,
2771 /*AllowAS=*/true))
2772 return ExprError();
2773
2774 QualType IdxTy = IdxArg->getType();
2775 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2776 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2777 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2778 << 1 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2779 << IdxTy;
2780
2781 QualType MaskTy = MaskArg->getType();
2782 QualType PtrTy = PtrArg->getType();
2783 QualType PointeeTy = PtrTy->getPointeeType();
2784 const VectorType *MaskVecTy = MaskTy->getAs<VectorType>();
2785 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2786 return ExprError(
2787 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2788 << S.getASTContext().BuiltinInfo.getQuotedName(
2789 ID: TheCall->getBuiltinCallee())
2790 << MaskTy << IdxTy);
2791
2792 QualType RetTy = S.Context.getExtVectorType(VectorType: PointeeTy.getUnqualifiedType(),
2793 NumElts: MaskVecTy->getNumElements());
2794 if (TheCall->getNumArgs() == 4) {
2795 Expr *PassThruArg = TheCall->getArg(Arg: 3);
2796 QualType PassThruTy = PassThruArg->getType();
2797 if (!S.Context.hasSameType(T1: PassThruTy, T2: RetTy))
2798 return S.Diag(Loc: PassThruArg->getExprLoc(),
2799 DiagID: diag::err_vec_masked_load_store_ptr)
2800 << /* fourth argument */ 4 << RetTy;
2801 }
2802
2803 TheCall->setType(RetTy);
2804 return TheCall;
2805}
2806
2807static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall) {
2808 if (S.checkArgCount(Call: TheCall, DesiredArgCount: 4))
2809 return ExprError();
2810
2811 if (ConvertMaskedBuiltinArgs(S, TheCall))
2812 return ExprError();
2813
2814 Expr *MaskArg = TheCall->getArg(Arg: 0);
2815 Expr *IdxArg = TheCall->getArg(Arg: 1);
2816 Expr *ValArg = TheCall->getArg(Arg: 2);
2817 Expr *PtrArg = TheCall->getArg(Arg: 3);
2818 if (TheCall->isTypeDependent())
2819 return TheCall;
2820
2821 if (CheckMaskedBuiltinArgs(S, MaskArg, PtrArg, Pos: 4, /*AllowConst=*/false,
2822 /*AllowAS=*/true))
2823 return ExprError();
2824
2825 QualType IdxTy = IdxArg->getType();
2826 const VectorType *IdxVecTy = IdxTy->getAs<VectorType>();
2827 if (!IdxTy->isVectorType() || !IdxVecTy->getElementType()->isIntegerType())
2828 return S.Diag(Loc: MaskArg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
2829 << 2 << /* vector of */ 4 << /* integer */ 1 << /* no fp */ 0
2830 << IdxTy;
2831
2832 QualType ValTy = ValArg->getType();
2833 QualType MaskTy = MaskArg->getType();
2834 QualType PtrTy = PtrArg->getType();
2835
2836 const VectorType *MaskVecTy = MaskTy->castAs<VectorType>();
2837 const VectorType *ValVecTy = ValTy->castAs<VectorType>();
2838 if (MaskVecTy->getNumElements() != IdxVecTy->getNumElements())
2839 return ExprError(
2840 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2841 << S.getASTContext().BuiltinInfo.getQuotedName(
2842 ID: TheCall->getBuiltinCallee())
2843 << MaskTy << IdxTy);
2844 if (MaskVecTy->getNumElements() != ValVecTy->getNumElements())
2845 return ExprError(
2846 S.Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_masked_load_store_size)
2847 << S.getASTContext().BuiltinInfo.getQuotedName(
2848 ID: TheCall->getBuiltinCallee())
2849 << MaskTy << ValTy);
2850
2851 if (!S.Context.hasSameType(T1: ValVecTy->getElementType().getUnqualifiedType(),
2852 T2: PtrTy->getPointeeType().getUnqualifiedType()))
2853 return ExprError(S.Diag(Loc: TheCall->getBeginLoc(),
2854 DiagID: diag::err_vec_builtin_incompatible_vector)
2855 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ 2
2856 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
2857 TheCall->getArg(Arg: 1)->getEndLoc()));
2858
2859 TheCall->setType(S.Context.VoidTy);
2860 return TheCall;
2861}
2862
2863static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall) {
2864 SourceLocation Loc = TheCall->getBeginLoc();
2865 MutableArrayRef Args(TheCall->getArgs(), TheCall->getNumArgs());
2866 assert(llvm::none_of(Args, [](Expr *Arg) { return Arg->isTypeDependent(); }));
2867
2868 if (Args.size() == 0) {
2869 S.Diag(Loc: TheCall->getBeginLoc(),
2870 DiagID: diag::err_typecheck_call_too_few_args_at_least)
2871 << /*callee_type=*/0 << /*min_arg_count=*/1 << /*actual_arg_count=*/0
2872 << /*is_non_object=*/0 << TheCall->getSourceRange();
2873 return ExprError();
2874 }
2875
2876 QualType FuncT = Args[0]->getType();
2877
2878 if (const auto *MPT = FuncT->getAs<MemberPointerType>()) {
2879 if (Args.size() < 2) {
2880 S.Diag(Loc: TheCall->getBeginLoc(),
2881 DiagID: diag::err_typecheck_call_too_few_args_at_least)
2882 << /*callee_type=*/0 << /*min_arg_count=*/2 << /*actual_arg_count=*/1
2883 << /*is_non_object=*/0 << TheCall->getSourceRange();
2884 return ExprError();
2885 }
2886
2887 const Type *MemPtrClass = MPT->getQualifier().getAsType();
2888 QualType ObjectT = Args[1]->getType();
2889
2890 if (MPT->isMemberDataPointer() && S.checkArgCount(Call: TheCall, DesiredArgCount: 2))
2891 return ExprError();
2892
2893 ExprResult ObjectArg = [&]() -> ExprResult {
2894 // (1.1): (t1.*f)(t2, ..., tN) when f is a pointer to a member function of
2895 // a class T and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2896 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2897 // (1.4): t1.*f when N=1 and f is a pointer to data member of a class T
2898 // and is_same_v<T, remove_cvref_t<decltype(t1)>> ||
2899 // is_base_of_v<T, remove_cvref_t<decltype(t1)>> is true;
2900 if (S.Context.hasSameType(T1: QualType(MemPtrClass, 0),
2901 T2: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc)) ||
2902 S.BuiltinIsBaseOf(RhsTLoc: Args[1]->getBeginLoc(), LhsT: QualType(MemPtrClass, 0),
2903 RhsT: S.BuiltinRemoveCVRef(BaseType: ObjectT, Loc))) {
2904 return Args[1];
2905 }
2906
2907 // (t1.get().*f)(t2, ..., tN) when f is a pointer to a member function of
2908 // a class T and remove_cvref_t<decltype(t1)> is a specialization of
2909 // reference_wrapper;
2910 if (const auto *RD = ObjectT->getAsCXXRecordDecl()) {
2911 if (RD->isInStdNamespace() &&
2912 RD->getDeclName().getAsString() == "reference_wrapper") {
2913 CXXScopeSpec SS;
2914 IdentifierInfo *GetName = &S.Context.Idents.get(Name: "get");
2915 UnqualifiedId GetID;
2916 GetID.setIdentifier(Id: GetName, IdLoc: Loc);
2917
2918 ExprResult MemExpr = S.ActOnMemberAccessExpr(
2919 S: S.getCurScope(), Base: Args[1], OpLoc: Loc, OpKind: tok::period, SS,
2920 /*TemplateKWLoc=*/SourceLocation(), Member&: GetID, ObjCImpDecl: nullptr);
2921
2922 if (MemExpr.isInvalid())
2923 return ExprError();
2924
2925 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemExpr.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
2926 }
2927 }
2928
2929 // ((*t1).*f)(t2, ..., tN) when f is a pointer to a member function of a
2930 // class T and t1 does not satisfy the previous two items;
2931
2932 return S.ActOnUnaryOp(S: S.getCurScope(), OpLoc: Loc, Op: tok::star, Input: Args[1]);
2933 }();
2934
2935 if (ObjectArg.isInvalid())
2936 return ExprError();
2937
2938 ExprResult BinOp = S.ActOnBinOp(S: S.getCurScope(), TokLoc: TheCall->getBeginLoc(),
2939 Kind: tok::periodstar, LHSExpr: ObjectArg.get(), RHSExpr: Args[0]);
2940 if (BinOp.isInvalid())
2941 return ExprError();
2942
2943 if (MPT->isMemberDataPointer())
2944 return BinOp;
2945
2946 auto *MemCall = new (S.Context)
2947 ParenExpr(SourceLocation(), SourceLocation(), BinOp.get());
2948
2949 return S.ActOnCallExpr(S: S.getCurScope(), Fn: MemCall, LParenLoc: TheCall->getBeginLoc(),
2950 ArgExprs: Args.drop_front(N: 2), RParenLoc: TheCall->getRParenLoc());
2951 }
2952 return S.ActOnCallExpr(S: S.getCurScope(), Fn: Args.front(), LParenLoc: TheCall->getBeginLoc(),
2953 ArgExprs: Args.drop_front(), RParenLoc: TheCall->getRParenLoc());
2954}
2955
2956// Performs a similar job to Sema::UsualUnaryConversions, but without any
2957// implicit promotion of integral/enumeration types.
2958static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E) {
2959 // First, convert to an r-value.
2960 ExprResult Res = S.DefaultFunctionArrayLvalueConversion(E);
2961 if (Res.isInvalid())
2962 return ExprError();
2963
2964 // Promote floating-point types.
2965 return S.UsualUnaryFPConversions(E: Res.get());
2966}
2967
2968static QualType getVectorElementType(ASTContext &Context, QualType VecTy) {
2969 if (const auto *TyA = VecTy->getAs<VectorType>())
2970 return TyA->getElementType();
2971 if (VecTy->isSizelessVectorType())
2972 return VecTy->getSizelessVectorEltType(Ctx: Context);
2973 return QualType();
2974}
2975
2976ExprResult
2977Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
2978 CallExpr *TheCall) {
2979 ExprResult TheCallResult(TheCall);
2980
2981 // Find out if any arguments are required to be integer constant expressions.
2982 unsigned ICEArguments = 0;
2983 ASTContext::GetBuiltinTypeError Error;
2984 Context.GetBuiltinType(ID: BuiltinID, Error, IntegerConstantArgs: &ICEArguments);
2985 if (Error != ASTContext::GE_None)
2986 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
2987
2988 // If any arguments are required to be ICE's, check and diagnose.
2989 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
2990 // Skip arguments not required to be ICE's.
2991 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
2992
2993 llvm::APSInt Result;
2994 // If we don't have enough arguments, continue so we can issue better
2995 // diagnostic in checkArgCount(...)
2996 if (ArgNo < TheCall->getNumArgs() &&
2997 BuiltinConstantArg(TheCall, ArgNum: ArgNo, Result))
2998 return true;
2999 ICEArguments &= ~(1 << ArgNo);
3000 }
3001
3002 FPOptions FPO;
3003 switch (BuiltinID) {
3004 case Builtin::BI__builtin___get_unsafe_stack_start:
3005 case Builtin::BI__builtin___get_unsafe_stack_bottom:
3006 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3007 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3008 << "__safestack_get_unsafe_stack_bottom";
3009 break;
3010 case Builtin::BI__builtin___get_unsafe_stack_top:
3011 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3012 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3013 << "__safestack_get_unsafe_stack_top";
3014 break;
3015 case Builtin::BI__builtin___get_unsafe_stack_ptr:
3016 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin)
3017 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID)
3018 << "__safestack_get_unsafe_stack_ptr";
3019 break;
3020 case Builtin::BI__builtin_cpu_supports:
3021 case Builtin::BI__builtin_cpu_is:
3022 if (BuiltinCpu(S&: *this, TI: Context.getTargetInfo(), TheCall,
3023 AuxTI: Context.getAuxTargetInfo(), BuiltinID))
3024 return ExprError();
3025 break;
3026 case Builtin::BI__builtin_cpu_init:
3027 if (!Context.getTargetInfo().supportsCpuInit()) {
3028 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
3029 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
3030 return ExprError();
3031 }
3032 break;
3033 case Builtin::BI__builtin___CFStringMakeConstantString:
3034 // CFStringMakeConstantString is currently not implemented for GOFF (i.e.,
3035 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported
3036 if (CheckBuiltinTargetNotInUnsupported(
3037 S&: *this, BuiltinID, TheCall,
3038 UnsupportedObjectFormatTypes: {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
3039 return ExprError();
3040 assert(TheCall->getNumArgs() == 1 &&
3041 "Wrong # arguments to builtin CFStringMakeConstantString");
3042 if (ObjC().CheckObjCString(Arg: TheCall->getArg(Arg: 0)))
3043 return ExprError();
3044 break;
3045 case Builtin::BI__builtin_ms_va_start:
3046 case Builtin::BI__builtin_stdarg_start:
3047 case Builtin::BI__builtin_va_start:
3048 case Builtin::BI__builtin_c23_va_start:
3049 if (BuiltinVAStart(BuiltinID, TheCall))
3050 return ExprError();
3051 break;
3052 case Builtin::BI__va_start: {
3053 switch (Context.getTargetInfo().getTriple().getArch()) {
3054 case llvm::Triple::aarch64:
3055 case llvm::Triple::arm:
3056 case llvm::Triple::thumb:
3057 if (BuiltinVAStartARMMicrosoft(Call: TheCall))
3058 return ExprError();
3059 break;
3060 default:
3061 if (BuiltinVAStart(BuiltinID, TheCall))
3062 return ExprError();
3063 break;
3064 }
3065 break;
3066 }
3067
3068 // The acquire, release, and no fence variants are ARM and AArch64 only.
3069 case Builtin::BI_interlockedbittestandset_acq:
3070 case Builtin::BI_interlockedbittestandset_rel:
3071 case Builtin::BI_interlockedbittestandset_nf:
3072 case Builtin::BI_interlockedbittestandreset_acq:
3073 case Builtin::BI_interlockedbittestandreset_rel:
3074 case Builtin::BI_interlockedbittestandreset_nf:
3075 if (CheckBuiltinTargetInSupported(
3076 S&: *this, TheCall,
3077 SupportedArchs: {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
3078 return ExprError();
3079 break;
3080
3081 // The 64-bit bittest variants are x64, ARM, and AArch64 only.
3082 case Builtin::BI_bittest64:
3083 case Builtin::BI_bittestandcomplement64:
3084 case Builtin::BI_bittestandreset64:
3085 case Builtin::BI_bittestandset64:
3086 case Builtin::BI_interlockedbittestandreset64:
3087 case Builtin::BI_interlockedbittestandset64:
3088 if (CheckBuiltinTargetInSupported(
3089 S&: *this, TheCall,
3090 SupportedArchs: {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3091 llvm::Triple::aarch64, llvm::Triple::amdgcn}))
3092 return ExprError();
3093 break;
3094
3095 // The 64-bit acquire, release, and no fence variants are AArch64 only.
3096 case Builtin::BI_interlockedbittestandreset64_acq:
3097 case Builtin::BI_interlockedbittestandreset64_rel:
3098 case Builtin::BI_interlockedbittestandreset64_nf:
3099 case Builtin::BI_interlockedbittestandset64_acq:
3100 case Builtin::BI_interlockedbittestandset64_rel:
3101 case Builtin::BI_interlockedbittestandset64_nf:
3102 if (CheckBuiltinTargetInSupported(S&: *this, TheCall, SupportedArchs: {llvm::Triple::aarch64}))
3103 return ExprError();
3104 break;
3105
3106 case Builtin::BI__builtin_set_flt_rounds:
3107 if (CheckBuiltinTargetInSupported(
3108 S&: *this, TheCall,
3109 SupportedArchs: {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3110 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn,
3111 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3112 llvm::Triple::ppc64le}))
3113 return ExprError();
3114 break;
3115
3116 case Builtin::BI__builtin_isgreater:
3117 case Builtin::BI__builtin_isgreaterequal:
3118 case Builtin::BI__builtin_isless:
3119 case Builtin::BI__builtin_islessequal:
3120 case Builtin::BI__builtin_islessgreater:
3121 case Builtin::BI__builtin_isunordered:
3122 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3123 return ExprError();
3124 break;
3125 case Builtin::BI__builtin_fpclassify:
3126 if (BuiltinFPClassification(TheCall, NumArgs: 6, BuiltinID))
3127 return ExprError();
3128 break;
3129 case Builtin::BI__builtin_isfpclass:
3130 if (BuiltinFPClassification(TheCall, NumArgs: 2, BuiltinID))
3131 return ExprError();
3132 break;
3133 case Builtin::BI__builtin_isfinite:
3134 case Builtin::BI__builtin_isinf:
3135 case Builtin::BI__builtin_isinf_sign:
3136 case Builtin::BI__builtin_isnan:
3137 case Builtin::BI__builtin_issignaling:
3138 case Builtin::BI__builtin_isnormal:
3139 case Builtin::BI__builtin_issubnormal:
3140 case Builtin::BI__builtin_iszero:
3141 case Builtin::BI__builtin_signbit:
3142 case Builtin::BI__builtin_signbitf:
3143 case Builtin::BI__builtin_signbitl:
3144 if (BuiltinFPClassification(TheCall, NumArgs: 1, BuiltinID))
3145 return ExprError();
3146 break;
3147 case Builtin::BI__builtin_shufflevector:
3148 return BuiltinShuffleVector(TheCall);
3149 // TheCall will be freed by the smart pointer here, but that's fine, since
3150 // BuiltinShuffleVector guts it, but then doesn't release it.
3151 case Builtin::BI__builtin_masked_load:
3152 case Builtin::BI__builtin_masked_expand_load:
3153 return BuiltinMaskedLoad(S&: *this, TheCall);
3154 case Builtin::BI__builtin_masked_store:
3155 case Builtin::BI__builtin_masked_compress_store:
3156 return BuiltinMaskedStore(S&: *this, TheCall);
3157 case Builtin::BI__builtin_masked_gather:
3158 return BuiltinMaskedGather(S&: *this, TheCall);
3159 case Builtin::BI__builtin_masked_scatter:
3160 return BuiltinMaskedScatter(S&: *this, TheCall);
3161 case Builtin::BI__builtin_invoke:
3162 return BuiltinInvoke(S&: *this, TheCall);
3163 case Builtin::BI__builtin_prefetch:
3164 if (BuiltinPrefetch(TheCall))
3165 return ExprError();
3166 break;
3167 case Builtin::BI__builtin_alloca_with_align:
3168 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3169 if (BuiltinAllocaWithAlign(TheCall))
3170 return ExprError();
3171 [[fallthrough]];
3172 case Builtin::BI__builtin_alloca:
3173 case Builtin::BI__builtin_alloca_uninitialized:
3174 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca)
3175 << TheCall->getDirectCallee();
3176 if (getLangOpts().OpenCL) {
3177 builtinAllocaAddrSpace(S&: *this, TheCall);
3178 }
3179 break;
3180 case Builtin::BI__builtin_infer_alloc_token:
3181 if (checkBuiltinInferAllocToken(S&: *this, TheCall))
3182 return ExprError();
3183 break;
3184 case Builtin::BI__arithmetic_fence:
3185 if (BuiltinArithmeticFence(TheCall))
3186 return ExprError();
3187 break;
3188 case Builtin::BI__assume:
3189 case Builtin::BI__builtin_assume:
3190 if (BuiltinAssume(TheCall))
3191 return ExprError();
3192 break;
3193 case Builtin::BI__builtin_assume_aligned:
3194 if (BuiltinAssumeAligned(TheCall))
3195 return ExprError();
3196 break;
3197 case Builtin::BI__builtin_dynamic_object_size:
3198 case Builtin::BI__builtin_object_size:
3199 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: 3))
3200 return ExprError();
3201 break;
3202 case Builtin::BI__builtin_longjmp:
3203 if (BuiltinLongjmp(TheCall))
3204 return ExprError();
3205 break;
3206 case Builtin::BI__builtin_setjmp:
3207 if (BuiltinSetjmp(TheCall))
3208 return ExprError();
3209 break;
3210 case Builtin::BI__builtin_complex:
3211 if (BuiltinComplex(TheCall))
3212 return ExprError();
3213 break;
3214 case Builtin::BI__builtin_classify_type:
3215 case Builtin::BI__builtin_constant_p: {
3216 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3217 return true;
3218 ExprResult Arg = DefaultFunctionArrayLvalueConversion(E: TheCall->getArg(Arg: 0));
3219 if (Arg.isInvalid()) return true;
3220 TheCall->setArg(Arg: 0, ArgExpr: Arg.get());
3221 TheCall->setType(Context.IntTy);
3222 break;
3223 }
3224 case Builtin::BI__builtin_launder:
3225 return BuiltinLaunder(S&: *this, TheCall);
3226 case Builtin::BI__builtin_is_within_lifetime:
3227 return BuiltinIsWithinLifetime(S&: *this, TheCall);
3228 case Builtin::BI__builtin_trivially_relocate:
3229 return BuiltinTriviallyRelocate(S&: *this, TheCall);
3230 case Builtin::BI__builtin_clear_padding: {
3231 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3232 return ExprError();
3233
3234 const Expr *PtrArg = TheCall->getArg(Arg: 0);
3235 const QualType PtrArgType = PtrArg->getType();
3236 if (!PtrArgType->isPointerType()) {
3237 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
3238 << PtrArgType << "pointer" << 1 << 0 << 3 << 1 << PtrArgType
3239 << "pointer";
3240 return ExprError();
3241 }
3242 QualType PointeeType = PtrArgType->getPointeeType();
3243 if (PointeeType.isConstQualified()) {
3244 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_typecheck_assign_const)
3245 << TheCall->getSourceRange() << 4 /*ConstUnknown*/;
3246 return ExprError();
3247 }
3248 if (RequireCompleteType(Loc: PtrArg->getBeginLoc(), T: PointeeType,
3249 DiagID: diag::err_typecheck_decl_incomplete_type))
3250 return ExprError();
3251
3252 // For non trivially copyable types, we try to match gcc's behaviour.
3253 // i.e. __builtin_clear_padding(&var) is OK as long as var is a complete
3254 // object, either a local variable or a function parameter passed by value
3255 auto IsAddrOfDeclExpr = [&]() {
3256 const Expr *Inner = PtrArg->IgnoreParenNoopCasts(Ctx: Context);
3257 const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: Inner);
3258 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3259 return false;
3260
3261 const Expr *Operand =
3262 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(Ctx: Context);
3263 const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: Operand);
3264 if (!DeclRef)
3265 return false;
3266
3267 const auto *VarDecl = dyn_cast<::clang::VarDecl>(Val: DeclRef->getDecl());
3268 if (!VarDecl || VarDecl->getType()->isReferenceType())
3269 return false;
3270
3271 // matching GCC behaviour
3272 // __builtin_clear_padding((X*)&var) is fine as long X is the type of var
3273 QualType VarQType = VarDecl->getType();
3274 return PointeeType.getTypePtr() == VarQType.getTypePtr() ||
3275 Context.hasSameUnqualifiedType(T1: PointeeType, T2: VarQType);
3276 };
3277
3278 if (!PointeeType.isTriviallyCopyableType(Context) &&
3279 !PointeeType->isAtomicType() // _Atomic is not copyable
3280 && !IsAddrOfDeclExpr()) {
3281 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_clear_padding_needs_trivial_copy)
3282 << PtrArg->getType() << PtrArg->getSourceRange();
3283 return ExprError();
3284 }
3285
3286 if (auto *Record = PointeeType->getAsRecordDecl();
3287 Record && Record->hasFlexibleArrayMember()) {
3288 Diag(Loc: PtrArg->getBeginLoc(), DiagID: diag::err_clear_padding_no_flexible_array)
3289 << PointeeType << PtrArg->getSourceRange();
3290 return ExprError();
3291 }
3292
3293 break;
3294 }
3295 case Builtin::BI__sync_fetch_and_add:
3296 case Builtin::BI__sync_fetch_and_add_1:
3297 case Builtin::BI__sync_fetch_and_add_2:
3298 case Builtin::BI__sync_fetch_and_add_4:
3299 case Builtin::BI__sync_fetch_and_add_8:
3300 case Builtin::BI__sync_fetch_and_add_16:
3301 case Builtin::BI__sync_fetch_and_sub:
3302 case Builtin::BI__sync_fetch_and_sub_1:
3303 case Builtin::BI__sync_fetch_and_sub_2:
3304 case Builtin::BI__sync_fetch_and_sub_4:
3305 case Builtin::BI__sync_fetch_and_sub_8:
3306 case Builtin::BI__sync_fetch_and_sub_16:
3307 case Builtin::BI__sync_fetch_and_or:
3308 case Builtin::BI__sync_fetch_and_or_1:
3309 case Builtin::BI__sync_fetch_and_or_2:
3310 case Builtin::BI__sync_fetch_and_or_4:
3311 case Builtin::BI__sync_fetch_and_or_8:
3312 case Builtin::BI__sync_fetch_and_or_16:
3313 case Builtin::BI__sync_fetch_and_and:
3314 case Builtin::BI__sync_fetch_and_and_1:
3315 case Builtin::BI__sync_fetch_and_and_2:
3316 case Builtin::BI__sync_fetch_and_and_4:
3317 case Builtin::BI__sync_fetch_and_and_8:
3318 case Builtin::BI__sync_fetch_and_and_16:
3319 case Builtin::BI__sync_fetch_and_xor:
3320 case Builtin::BI__sync_fetch_and_xor_1:
3321 case Builtin::BI__sync_fetch_and_xor_2:
3322 case Builtin::BI__sync_fetch_and_xor_4:
3323 case Builtin::BI__sync_fetch_and_xor_8:
3324 case Builtin::BI__sync_fetch_and_xor_16:
3325 case Builtin::BI__sync_fetch_and_nand:
3326 case Builtin::BI__sync_fetch_and_nand_1:
3327 case Builtin::BI__sync_fetch_and_nand_2:
3328 case Builtin::BI__sync_fetch_and_nand_4:
3329 case Builtin::BI__sync_fetch_and_nand_8:
3330 case Builtin::BI__sync_fetch_and_nand_16:
3331 case Builtin::BI__sync_add_and_fetch:
3332 case Builtin::BI__sync_add_and_fetch_1:
3333 case Builtin::BI__sync_add_and_fetch_2:
3334 case Builtin::BI__sync_add_and_fetch_4:
3335 case Builtin::BI__sync_add_and_fetch_8:
3336 case Builtin::BI__sync_add_and_fetch_16:
3337 case Builtin::BI__sync_sub_and_fetch:
3338 case Builtin::BI__sync_sub_and_fetch_1:
3339 case Builtin::BI__sync_sub_and_fetch_2:
3340 case Builtin::BI__sync_sub_and_fetch_4:
3341 case Builtin::BI__sync_sub_and_fetch_8:
3342 case Builtin::BI__sync_sub_and_fetch_16:
3343 case Builtin::BI__sync_and_and_fetch:
3344 case Builtin::BI__sync_and_and_fetch_1:
3345 case Builtin::BI__sync_and_and_fetch_2:
3346 case Builtin::BI__sync_and_and_fetch_4:
3347 case Builtin::BI__sync_and_and_fetch_8:
3348 case Builtin::BI__sync_and_and_fetch_16:
3349 case Builtin::BI__sync_or_and_fetch:
3350 case Builtin::BI__sync_or_and_fetch_1:
3351 case Builtin::BI__sync_or_and_fetch_2:
3352 case Builtin::BI__sync_or_and_fetch_4:
3353 case Builtin::BI__sync_or_and_fetch_8:
3354 case Builtin::BI__sync_or_and_fetch_16:
3355 case Builtin::BI__sync_xor_and_fetch:
3356 case Builtin::BI__sync_xor_and_fetch_1:
3357 case Builtin::BI__sync_xor_and_fetch_2:
3358 case Builtin::BI__sync_xor_and_fetch_4:
3359 case Builtin::BI__sync_xor_and_fetch_8:
3360 case Builtin::BI__sync_xor_and_fetch_16:
3361 case Builtin::BI__sync_nand_and_fetch:
3362 case Builtin::BI__sync_nand_and_fetch_1:
3363 case Builtin::BI__sync_nand_and_fetch_2:
3364 case Builtin::BI__sync_nand_and_fetch_4:
3365 case Builtin::BI__sync_nand_and_fetch_8:
3366 case Builtin::BI__sync_nand_and_fetch_16:
3367 case Builtin::BI__sync_val_compare_and_swap:
3368 case Builtin::BI__sync_val_compare_and_swap_1:
3369 case Builtin::BI__sync_val_compare_and_swap_2:
3370 case Builtin::BI__sync_val_compare_and_swap_4:
3371 case Builtin::BI__sync_val_compare_and_swap_8:
3372 case Builtin::BI__sync_val_compare_and_swap_16:
3373 case Builtin::BI__sync_bool_compare_and_swap:
3374 case Builtin::BI__sync_bool_compare_and_swap_1:
3375 case Builtin::BI__sync_bool_compare_and_swap_2:
3376 case Builtin::BI__sync_bool_compare_and_swap_4:
3377 case Builtin::BI__sync_bool_compare_and_swap_8:
3378 case Builtin::BI__sync_bool_compare_and_swap_16:
3379 case Builtin::BI__sync_lock_test_and_set:
3380 case Builtin::BI__sync_lock_test_and_set_1:
3381 case Builtin::BI__sync_lock_test_and_set_2:
3382 case Builtin::BI__sync_lock_test_and_set_4:
3383 case Builtin::BI__sync_lock_test_and_set_8:
3384 case Builtin::BI__sync_lock_test_and_set_16:
3385 case Builtin::BI__sync_lock_release:
3386 case Builtin::BI__sync_lock_release_1:
3387 case Builtin::BI__sync_lock_release_2:
3388 case Builtin::BI__sync_lock_release_4:
3389 case Builtin::BI__sync_lock_release_8:
3390 case Builtin::BI__sync_lock_release_16:
3391 case Builtin::BI__sync_swap:
3392 case Builtin::BI__sync_swap_1:
3393 case Builtin::BI__sync_swap_2:
3394 case Builtin::BI__sync_swap_4:
3395 case Builtin::BI__sync_swap_8:
3396 case Builtin::BI__sync_swap_16:
3397 return BuiltinAtomicOverloaded(TheCallResult);
3398 case Builtin::BI__sync_synchronize:
3399 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
3400 << TheCall->getCallee()->getSourceRange();
3401 break;
3402 case Builtin::BI__builtin_nontemporal_load:
3403 case Builtin::BI__builtin_nontemporal_store:
3404 return BuiltinNontemporalOverloaded(TheCallResult);
3405 case Builtin::BI__builtin_memcpy_inline: {
3406 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3407 // We warn about copying to or from `nullptr` pointers when `size` is
3408 // greater than 0. When `size` is value dependent we cannot evaluate its
3409 // value so we bail out.
3410 if (SizeOp->isValueDependent())
3411 break;
3412 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero()) {
3413 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3414 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 1), CallSiteLoc: TheCall->getExprLoc());
3415 }
3416 break;
3417 }
3418 case Builtin::BI__builtin_memset_inline: {
3419 clang::Expr *SizeOp = TheCall->getArg(Arg: 2);
3420 // We warn about filling to `nullptr` pointers when `size` is greater than
3421 // 0. When `size` is value dependent we cannot evaluate its value so we bail
3422 // out.
3423 if (SizeOp->isValueDependent())
3424 break;
3425 if (!SizeOp->EvaluateKnownConstInt(Ctx: Context).isZero())
3426 CheckNonNullArgument(S&: *this, ArgExpr: TheCall->getArg(Arg: 0), CallSiteLoc: TheCall->getExprLoc());
3427 break;
3428 }
3429#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3430 case Builtin::BI##ID: \
3431 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3432#include "clang/Basic/Builtins.inc"
3433 case Builtin::BI__annotation: {
3434 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3435 if (!TT.isOSWindows() && !TT.isUEFI()) {
3436 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
3437 << TheCall->getSourceRange();
3438 return ExprError();
3439 }
3440 if (BuiltinMSVCAnnotation(S&: *this, TheCall))
3441 return ExprError();
3442 break;
3443 }
3444 case Builtin::BI__builtin_annotation:
3445 if (BuiltinAnnotation(S&: *this, TheCall))
3446 return ExprError();
3447 break;
3448 case Builtin::BI__builtin_addressof:
3449 if (BuiltinAddressof(S&: *this, TheCall))
3450 return ExprError();
3451 break;
3452 case Builtin::BI__builtin_function_start:
3453 if (BuiltinFunctionStart(S&: *this, TheCall))
3454 return ExprError();
3455 break;
3456 case Builtin::BI__builtin_is_aligned:
3457 case Builtin::BI__builtin_align_up:
3458 case Builtin::BI__builtin_align_down:
3459 if (BuiltinAlignment(S&: *this, TheCall, ID: BuiltinID))
3460 return ExprError();
3461 break;
3462 case Builtin::BI__builtin_add_overflow:
3463 case Builtin::BI__builtin_sub_overflow:
3464 case Builtin::BI__builtin_mul_overflow:
3465 if (BuiltinOverflow(S&: *this, TheCall, BuiltinID))
3466 return ExprError();
3467 break;
3468 case Builtin::BI__builtin_operator_new:
3469 case Builtin::BI__builtin_operator_delete: {
3470 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3471 ExprResult Res =
3472 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3473 return Res;
3474 }
3475 case Builtin::BI__builtin_dump_struct:
3476 return BuiltinDumpStruct(S&: *this, TheCall);
3477 case Builtin::BI__builtin_expect_with_probability: {
3478 // We first want to ensure we are called with 3 arguments
3479 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
3480 return ExprError();
3481 // then check probability is constant float in range [0.0, 1.0]
3482 const Expr *ProbArg = TheCall->getArg(Arg: 2);
3483 SmallVector<PartialDiagnosticAt, 8> Notes;
3484 Expr::EvalResult Eval;
3485 Eval.Diag = &Notes;
3486 if ((!ProbArg->EvaluateAsConstantExpr(Result&: Eval, Ctx: Context)) ||
3487 !Eval.Val.isFloat()) {
3488 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_not_constant_float)
3489 << ProbArg->getSourceRange();
3490 for (const PartialDiagnosticAt &PDiag : Notes)
3491 Diag(Loc: PDiag.first, PD: PDiag.second);
3492 return ExprError();
3493 }
3494 llvm::APFloat Probability = Eval.Val.getFloat();
3495 bool LoseInfo = false;
3496 Probability.convert(ToSemantics: llvm::APFloat::IEEEdouble(),
3497 RM: llvm::RoundingMode::Dynamic, losesInfo: &LoseInfo);
3498 if (!(Probability >= llvm::APFloat(0.0) &&
3499 Probability <= llvm::APFloat(1.0))) {
3500 Diag(Loc: ProbArg->getBeginLoc(), DiagID: diag::err_probability_out_of_range)
3501 << ProbArg->getSourceRange();
3502 return ExprError();
3503 }
3504 break;
3505 }
3506 case Builtin::BI__builtin_preserve_access_index:
3507 if (BuiltinPreserveAI(S&: *this, TheCall))
3508 return ExprError();
3509 break;
3510 case Builtin::BI__builtin_call_with_static_chain:
3511 if (BuiltinCallWithStaticChain(S&: *this, BuiltinCall: TheCall))
3512 return ExprError();
3513 break;
3514 case Builtin::BI__exception_code:
3515 case Builtin::BI_exception_code:
3516 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHExceptScope,
3517 DiagID: diag::err_seh___except_block))
3518 return ExprError();
3519 break;
3520 case Builtin::BI__exception_info:
3521 case Builtin::BI_exception_info:
3522 if (BuiltinSEHScopeCheck(SemaRef&: *this, TheCall, NeededScopeFlags: Scope::SEHFilterScope,
3523 DiagID: diag::err_seh___except_filter))
3524 return ExprError();
3525 break;
3526 case Builtin::BI__GetExceptionInfo:
3527 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3528 return ExprError();
3529
3530 if (CheckCXXThrowOperand(
3531 ThrowLoc: TheCall->getBeginLoc(),
3532 ThrowTy: Context.getExceptionObjectType(T: FDecl->getParamDecl(i: 0)->getType()),
3533 E: TheCall))
3534 return ExprError();
3535
3536 TheCall->setType(Context.VoidPtrTy);
3537 break;
3538 case Builtin::BIaddressof:
3539 case Builtin::BI__addressof:
3540 case Builtin::BIforward:
3541 case Builtin::BIforward_like:
3542 case Builtin::BImove:
3543 case Builtin::BImove_if_noexcept:
3544 case Builtin::BIas_const: {
3545 // These are all expected to be of the form
3546 // T &/&&/* f(U &/&&)
3547 // where T and U only differ in qualification.
3548 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
3549 return ExprError();
3550 QualType Param = FDecl->getParamDecl(i: 0)->getType();
3551 QualType Result = FDecl->getReturnType();
3552 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3553 BuiltinID == Builtin::BI__addressof;
3554 if (!(Param->isReferenceType() &&
3555 (ReturnsPointer ? Result->isAnyPointerType()
3556 : Result->isReferenceType()) &&
3557 Context.hasSameUnqualifiedType(T1: Param->getPointeeType(),
3558 T2: Result->getPointeeType()))) {
3559 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_move_forward_unsupported)
3560 << FDecl;
3561 return ExprError();
3562 }
3563 break;
3564 }
3565 case Builtin::BI__builtin_ptrauth_strip:
3566 return PointerAuthStrip(S&: *this, Call: TheCall);
3567 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3568 return PointerAuthBlendDiscriminator(S&: *this, Call: TheCall);
3569 case Builtin::BI__builtin_ptrauth_sign_constant:
3570 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3571 /*RequireConstant=*/true);
3572 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3573 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Sign,
3574 /*RequireConstant=*/false);
3575 case Builtin::BI__builtin_ptrauth_auth:
3576 return PointerAuthSignOrAuth(S&: *this, Call: TheCall, OpKind: PAO_Auth,
3577 /*RequireConstant=*/false);
3578 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3579 return PointerAuthSignGenericData(S&: *this, Call: TheCall);
3580 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3581 return PointerAuthAuthAndResign(S&: *this, Call: TheCall);
3582 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3583 return PointerAuthAuthLoadRelativeAndSign(S&: *this, Call: TheCall);
3584 case Builtin::BI__builtin_ptrauth_string_discriminator:
3585 return PointerAuthStringDiscriminator(S&: *this, Call: TheCall);
3586
3587 case Builtin::BI__builtin_get_vtable_pointer:
3588 return GetVTablePointer(S&: *this, Call: TheCall);
3589
3590 // OpenCL v2.0, s6.13.16 - Pipe functions
3591 case Builtin::BIread_pipe:
3592 case Builtin::BIwrite_pipe:
3593 // Since those two functions are declared with var args, we need a semantic
3594 // check for the argument.
3595 if (OpenCL().checkBuiltinRWPipe(Call: TheCall))
3596 return ExprError();
3597 break;
3598 case Builtin::BIreserve_read_pipe:
3599 case Builtin::BIreserve_write_pipe:
3600 case Builtin::BIwork_group_reserve_read_pipe:
3601 case Builtin::BIwork_group_reserve_write_pipe:
3602 if (OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3603 return ExprError();
3604 break;
3605 case Builtin::BIsub_group_reserve_read_pipe:
3606 case Builtin::BIsub_group_reserve_write_pipe:
3607 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3608 OpenCL().checkBuiltinReserveRWPipe(Call: TheCall))
3609 return ExprError();
3610 break;
3611 case Builtin::BIcommit_read_pipe:
3612 case Builtin::BIcommit_write_pipe:
3613 case Builtin::BIwork_group_commit_read_pipe:
3614 case Builtin::BIwork_group_commit_write_pipe:
3615 if (OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3616 return ExprError();
3617 break;
3618 case Builtin::BIsub_group_commit_read_pipe:
3619 case Builtin::BIsub_group_commit_write_pipe:
3620 if (OpenCL().checkSubgroupExt(Call: TheCall) ||
3621 OpenCL().checkBuiltinCommitRWPipe(Call: TheCall))
3622 return ExprError();
3623 break;
3624 case Builtin::BIget_pipe_num_packets:
3625 case Builtin::BIget_pipe_max_packets:
3626 if (OpenCL().checkBuiltinPipePackets(Call: TheCall))
3627 return ExprError();
3628 break;
3629 case Builtin::BIto_global:
3630 case Builtin::BIto_local:
3631 case Builtin::BIto_private:
3632 if (OpenCL().checkBuiltinToAddr(BuiltinID, Call: TheCall))
3633 return ExprError();
3634 break;
3635 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
3636 case Builtin::BIenqueue_kernel:
3637 if (OpenCL().checkBuiltinEnqueueKernel(TheCall))
3638 return ExprError();
3639 break;
3640 case Builtin::BIget_kernel_work_group_size:
3641 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3642 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3643 return ExprError();
3644 break;
3645 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3646 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3647 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3648 return ExprError();
3649 break;
3650 case Builtin::BI__builtin_os_log_format:
3651 Cleanup.setExprNeedsCleanups(true);
3652 [[fallthrough]];
3653 case Builtin::BI__builtin_os_log_format_buffer_size:
3654 if (BuiltinOSLogFormat(TheCall))
3655 return ExprError();
3656 break;
3657 case Builtin::BI__builtin_frame_address:
3658 case Builtin::BI__builtin_return_address: {
3659 if (BuiltinConstantArgRange(TheCall, ArgNum: 0, Low: 0, High: 0xFFFF))
3660 return ExprError();
3661
3662 // -Wframe-address warning if non-zero passed to builtin
3663 // return/frame address.
3664 Expr::EvalResult Result;
3665 if (!TheCall->getArg(Arg: 0)->isValueDependent() &&
3666 TheCall->getArg(Arg: 0)->EvaluateAsInt(Result, Ctx: getASTContext()) &&
3667 Result.Val.getInt() != 0)
3668 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_frame_address)
3669 << ((BuiltinID == Builtin::BI__builtin_return_address)
3670 ? "__builtin_return_address"
3671 : "__builtin_frame_address")
3672 << TheCall->getSourceRange();
3673 break;
3674 }
3675
3676 case Builtin::BI__builtin_nondeterministic_value: {
3677 if (BuiltinNonDeterministicValue(TheCall))
3678 return ExprError();
3679 break;
3680 }
3681
3682 // __builtin_elementwise_abs restricts the element type to signed integers or
3683 // floating point types only.
3684 case Builtin::BI__builtin_elementwise_abs:
3685 if (PrepareBuiltinElementwiseMathOneArgCall(
3686 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::SignedIntOrFloatTy))
3687 return ExprError();
3688 break;
3689
3690 // These builtins restrict the element type to floating point
3691 // types only.
3692 case Builtin::BI__builtin_elementwise_acos:
3693 case Builtin::BI__builtin_elementwise_asin:
3694 case Builtin::BI__builtin_elementwise_atan:
3695 case Builtin::BI__builtin_elementwise_ceil:
3696 case Builtin::BI__builtin_elementwise_cos:
3697 case Builtin::BI__builtin_elementwise_cosh:
3698 case Builtin::BI__builtin_elementwise_exp:
3699 case Builtin::BI__builtin_elementwise_exp2:
3700 case Builtin::BI__builtin_elementwise_exp10:
3701 case Builtin::BI__builtin_elementwise_floor:
3702 case Builtin::BI__builtin_elementwise_log:
3703 case Builtin::BI__builtin_elementwise_log2:
3704 case Builtin::BI__builtin_elementwise_log10:
3705 case Builtin::BI__builtin_elementwise_roundeven:
3706 case Builtin::BI__builtin_elementwise_round:
3707 case Builtin::BI__builtin_elementwise_rint:
3708 case Builtin::BI__builtin_elementwise_nearbyint:
3709 case Builtin::BI__builtin_elementwise_sin:
3710 case Builtin::BI__builtin_elementwise_sinh:
3711 case Builtin::BI__builtin_elementwise_sqrt:
3712 case Builtin::BI__builtin_elementwise_tan:
3713 case Builtin::BI__builtin_elementwise_tanh:
3714 case Builtin::BI__builtin_elementwise_trunc:
3715 case Builtin::BI__builtin_elementwise_canonicalize:
3716 if (PrepareBuiltinElementwiseMathOneArgCall(
3717 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3718 return ExprError();
3719 break;
3720 case Builtin::BI__builtin_elementwise_fma:
3721 if (BuiltinElementwiseTernaryMath(TheCall))
3722 return ExprError();
3723 break;
3724
3725 case Builtin::BI__builtin_elementwise_ldexp: {
3726 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3727 return ExprError();
3728
3729 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
3730 if (A.isInvalid())
3731 return ExprError();
3732 QualType TyA = A.get()->getType();
3733 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
3734 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1))
3735 return ExprError();
3736
3737 ExprResult Exp = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3738 if (Exp.isInvalid())
3739 return ExprError();
3740 QualType TyExp = Exp.get()->getType();
3741 if (checkMathBuiltinElementType(S&: *this, Loc: Exp.get()->getBeginLoc(), ArgTy: TyExp,
3742 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy,
3743 ArgOrdinal: 2))
3744 return ExprError();
3745
3746 // Check the two arguments are either scalars or vectors of equal length.
3747 const auto *Vec0 = TyA->getAs<VectorType>();
3748 const auto *Vec1 = TyExp->getAs<VectorType>();
3749 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
3750 unsigned Arg1Length = Vec1 ? Vec1->getNumElements() : 0;
3751 if (Arg0Length != Arg1Length) {
3752 Diag(Loc: Exp.get()->getBeginLoc(),
3753 DiagID: diag::err_typecheck_vector_lengths_not_equal)
3754 << TyA << TyExp << A.get()->getSourceRange()
3755 << Exp.get()->getSourceRange();
3756 return ExprError();
3757 }
3758
3759 TheCall->setArg(Arg: 0, ArgExpr: A.get());
3760 TheCall->setArg(Arg: 1, ArgExpr: Exp.get());
3761 TheCall->setType(TyA);
3762 break;
3763 }
3764
3765 // These builtins restrict the element type to floating point
3766 // types only, and take in two arguments.
3767 case Builtin::BI__builtin_elementwise_minnum:
3768 case Builtin::BI__builtin_elementwise_maxnum:
3769 case Builtin::BI__builtin_elementwise_minimum:
3770 case Builtin::BI__builtin_elementwise_maximum:
3771 case Builtin::BI__builtin_elementwise_minimumnum:
3772 case Builtin::BI__builtin_elementwise_maximumnum:
3773 case Builtin::BI__builtin_elementwise_atan2:
3774 case Builtin::BI__builtin_elementwise_fmod:
3775 case Builtin::BI__builtin_elementwise_pow:
3776 if (BuiltinElementwiseMath(TheCall,
3777 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy))
3778 return ExprError();
3779 break;
3780 // These builtins restrict the element type to integer
3781 // types only.
3782 case Builtin::BI__builtin_elementwise_add_sat:
3783 case Builtin::BI__builtin_elementwise_sub_sat:
3784 case Builtin::BI__builtin_elementwise_clmul:
3785 case Builtin::BI__builtin_elementwise_pext:
3786 case Builtin::BI__builtin_elementwise_pdep:
3787 if (BuiltinElementwiseMath(TheCall,
3788 ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3789 return ExprError();
3790 break;
3791 case Builtin::BI__builtin_elementwise_fshl:
3792 case Builtin::BI__builtin_elementwise_fshr:
3793 if (BuiltinElementwiseTernaryMath(
3794 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3795 return ExprError();
3796 break;
3797 case Builtin::BI__builtin_elementwise_min:
3798 case Builtin::BI__builtin_elementwise_max: {
3799 if (BuiltinElementwiseMath(TheCall))
3800 return ExprError();
3801 Expr *Arg0 = TheCall->getArg(Arg: 0);
3802 Expr *Arg1 = TheCall->getArg(Arg: 1);
3803 QualType Ty0 = Arg0->getType();
3804 QualType Ty1 = Arg1->getType();
3805 const VectorType *VecTy0 = Ty0->getAs<VectorType>();
3806 const VectorType *VecTy1 = Ty1->getAs<VectorType>();
3807 if (Ty0->isFloatingType() || Ty1->isFloatingType() ||
3808 (VecTy0 && VecTy0->getElementType()->isFloatingType()) ||
3809 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
3810 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_deprecated_builtin_no_suggestion)
3811 << Context.BuiltinInfo.getQuotedName(ID: BuiltinID);
3812 break;
3813 }
3814 case Builtin::BI__builtin_elementwise_popcount:
3815 case Builtin::BI__builtin_elementwise_bitreverse:
3816 if (PrepareBuiltinElementwiseMathOneArgCall(
3817 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3818 return ExprError();
3819 break;
3820 case Builtin::BI__builtin_elementwise_copysign: {
3821 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
3822 return ExprError();
3823
3824 ExprResult Magnitude = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
3825 ExprResult Sign = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3826 if (Magnitude.isInvalid() || Sign.isInvalid())
3827 return ExprError();
3828
3829 QualType MagnitudeTy = Magnitude.get()->getType();
3830 QualType SignTy = Sign.get()->getType();
3831 if (checkMathBuiltinElementType(
3832 S&: *this, Loc: TheCall->getArg(Arg: 0)->getBeginLoc(), ArgTy: MagnitudeTy,
3833 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 1) ||
3834 checkMathBuiltinElementType(
3835 S&: *this, Loc: TheCall->getArg(Arg: 1)->getBeginLoc(), ArgTy: SignTy,
3836 ArgTyRestr: EltwiseBuiltinArgTyRestriction::FloatTy, ArgOrdinal: 2)) {
3837 return ExprError();
3838 }
3839
3840 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) {
3841 return Diag(Loc: Sign.get()->getBeginLoc(),
3842 DiagID: diag::err_typecheck_call_different_arg_types)
3843 << MagnitudeTy << SignTy;
3844 }
3845
3846 TheCall->setArg(Arg: 0, ArgExpr: Magnitude.get());
3847 TheCall->setArg(Arg: 1, ArgExpr: Sign.get());
3848 TheCall->setType(Magnitude.get()->getType());
3849 break;
3850 }
3851 case Builtin::BI__builtin_elementwise_clzg:
3852 case Builtin::BI__builtin_elementwise_ctzg:
3853 // These builtins can be unary or binary. Note for empty calls we call the
3854 // unary checker in order to not emit an error that says the function
3855 // expects 2 arguments, which would be misleading.
3856 if (TheCall->getNumArgs() <= 1) {
3857 if (PrepareBuiltinElementwiseMathOneArgCall(
3858 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3859 return ExprError();
3860 } else if (BuiltinElementwiseMath(
3861 TheCall, ArgTyRestr: EltwiseBuiltinArgTyRestriction::IntegerTy))
3862 return ExprError();
3863 break;
3864 case Builtin::BI__builtin_reduce_max:
3865 case Builtin::BI__builtin_reduce_min: {
3866 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3867 return ExprError();
3868
3869 const Expr *Arg = TheCall->getArg(Arg: 0);
3870 const auto *TyA = Arg->getType()->getAs<VectorType>();
3871
3872 QualType ElTy;
3873 if (TyA)
3874 ElTy = TyA->getElementType();
3875 else if (Arg->getType()->isSizelessVectorType())
3876 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
3877
3878 if (ElTy.isNull()) {
3879 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3880 << 1 << /* vector ty */ 2 << /* no int */ 0 << /* no fp */ 0
3881 << Arg->getType();
3882 return ExprError();
3883 }
3884
3885 TheCall->setType(ElTy);
3886 break;
3887 }
3888 case Builtin::BI__builtin_reduce_maximum:
3889 case Builtin::BI__builtin_reduce_minimum: {
3890 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3891 return ExprError();
3892
3893 const Expr *Arg = TheCall->getArg(Arg: 0);
3894 const auto *TyA = Arg->getType()->getAs<VectorType>();
3895
3896 QualType ElTy;
3897 if (TyA)
3898 ElTy = TyA->getElementType();
3899 else if (Arg->getType()->isSizelessVectorType())
3900 ElTy = Arg->getType()->getSizelessVectorEltType(Ctx: Context);
3901
3902 if (ElTy.isNull() || !ElTy->isFloatingType()) {
3903 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3904 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3905 << Arg->getType();
3906 return ExprError();
3907 }
3908
3909 TheCall->setType(ElTy);
3910 break;
3911 }
3912
3913 // These builtins support vectors of integers only.
3914 // TODO: ADD/MUL should support floating-point types.
3915 case Builtin::BI__builtin_reduce_add:
3916 case Builtin::BI__builtin_reduce_mul:
3917 case Builtin::BI__builtin_reduce_xor:
3918 case Builtin::BI__builtin_reduce_or:
3919 case Builtin::BI__builtin_reduce_and: {
3920 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
3921 return ExprError();
3922
3923 const Expr *Arg = TheCall->getArg(Arg: 0);
3924
3925 QualType ElTy = getVectorElementType(Context, VecTy: Arg->getType());
3926 if (ElTy.isNull() || !ElTy->isIntegerType()) {
3927 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3928 << 1 << /* vector of */ 4 << /* int */ 1 << /* no fp */ 0
3929 << Arg->getType();
3930 return ExprError();
3931 }
3932
3933 TheCall->setType(ElTy);
3934 break;
3935 }
3936
3937 case Builtin::BI__builtin_reduce_assoc_fadd:
3938 case Builtin::BI__builtin_reduce_in_order_fadd: {
3939 // For in-order reductions require the user to specify the start value.
3940 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
3941 if (InOrder ? checkArgCount(Call: TheCall, DesiredArgCount: 2) : checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
3942 return ExprError();
3943
3944 ExprResult Vec = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
3945 if (Vec.isInvalid())
3946 return ExprError();
3947
3948 TheCall->setArg(Arg: 0, ArgExpr: Vec.get());
3949
3950 QualType ElTy = getVectorElementType(Context, VecTy: Vec.get()->getType());
3951 if (ElTy.isNull() || !ElTy->isRealFloatingType()) {
3952 Diag(Loc: Vec.get()->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
3953 << 1 << /* vector of */ 4 << /* no int */ 0 << /* fp */ 1
3954 << Vec.get()->getType();
3955 return ExprError();
3956 }
3957
3958 if (TheCall->getNumArgs() == 2) {
3959 ExprResult StartValue = UsualUnaryConversions(E: TheCall->getArg(Arg: 1));
3960 if (StartValue.isInvalid())
3961 return ExprError();
3962
3963 if (!StartValue.get()->getType()->isRealFloatingType()) {
3964 Diag(Loc: StartValue.get()->getBeginLoc(),
3965 DiagID: diag::err_builtin_invalid_arg_type)
3966 << 2 << /* scalar */ 1 << /* no int */ 0 << /* fp */ 1
3967 << StartValue.get()->getType();
3968 return ExprError();
3969 }
3970 TheCall->setArg(Arg: 1, ArgExpr: StartValue.get());
3971 }
3972
3973 TheCall->setType(ElTy);
3974 break;
3975 }
3976
3977 case Builtin::BI__builtin_matrix_transpose:
3978 return BuiltinMatrixTranspose(TheCall, CallResult: TheCallResult);
3979
3980 case Builtin::BI__builtin_matrix_column_major_load:
3981 return BuiltinMatrixColumnMajorLoad(TheCall, CallResult: TheCallResult);
3982
3983 case Builtin::BI__builtin_matrix_column_major_store:
3984 return BuiltinMatrixColumnMajorStore(TheCall, CallResult: TheCallResult);
3985
3986 case Builtin::BI__builtin_verbose_trap:
3987 if (!checkBuiltinVerboseTrap(Call: TheCall, S&: *this))
3988 return ExprError();
3989 break;
3990
3991 case Builtin::BI__builtin_get_device_side_mangled_name: {
3992 auto Check = [](CallExpr *TheCall) {
3993 if (TheCall->getNumArgs() != 1)
3994 return false;
3995 auto *DRE = dyn_cast<DeclRefExpr>(Val: TheCall->getArg(Arg: 0)->IgnoreImpCasts());
3996 if (!DRE)
3997 return false;
3998 auto *D = DRE->getDecl();
3999 if (!isa<FunctionDecl>(Val: D) && !isa<VarDecl>(Val: D))
4000 return false;
4001 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4002 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
4003 };
4004 if (!Check(TheCall)) {
4005 Diag(Loc: TheCall->getBeginLoc(),
4006 DiagID: diag::err_hip_invalid_args_builtin_mangled_name);
4007 return ExprError();
4008 }
4009 break;
4010 }
4011 case Builtin::BI__builtin_bswapg:
4012 if (BuiltinBswapg(S&: *this, TheCall))
4013 return ExprError();
4014 break;
4015 case Builtin::BI__builtin_bitreverseg:
4016 if (BuiltinBitreverseg(S&: *this, TheCall))
4017 return ExprError();
4018 break;
4019 case Builtin::BI__builtin_popcountg:
4020 if (BuiltinPopcountg(S&: *this, TheCall))
4021 return ExprError();
4022 break;
4023 case Builtin::BI__builtin_clzg:
4024 case Builtin::BI__builtin_ctzg:
4025 if (BuiltinCountZeroBitsGeneric(S&: *this, TheCall))
4026 return ExprError();
4027 break;
4028
4029 case Builtin::BI__builtin_stdc_rotate_left:
4030 case Builtin::BI__builtin_stdc_rotate_right:
4031 if (BuiltinRotateGeneric(S&: *this, TheCall))
4032 return ExprError();
4033 break;
4034
4035 case Builtin::BI__builtin_stdc_memreverse8:
4036 case Builtin::BIstdc_memreverse8:
4037 case Builtin::BIstdc_memreverse8u8:
4038 case Builtin::BIstdc_memreverse8u16:
4039 case Builtin::BIstdc_memreverse8u32:
4040 case Builtin::BIstdc_memreverse8u64:
4041 if (Context.getTargetInfo().getCharWidth() != 8) {
4042 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_requires_char_bit_8)
4043 << TheCall->getDirectCallee()->getName();
4044 return ExprError();
4045 }
4046 break;
4047
4048 case Builtin::BI__builtin_stdc_bit_floor:
4049 case Builtin::BI__builtin_stdc_bit_ceil:
4050 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: QualType()))
4051 return ExprError();
4052 break;
4053 case Builtin::BI__builtin_stdc_has_single_bit:
4054 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: Context.BoolTy))
4055 return ExprError();
4056 break;
4057 case Builtin::BI__builtin_stdc_leading_zeros:
4058 case Builtin::BI__builtin_stdc_leading_ones:
4059 case Builtin::BI__builtin_stdc_trailing_zeros:
4060 case Builtin::BI__builtin_stdc_trailing_ones:
4061 case Builtin::BI__builtin_stdc_first_leading_zero:
4062 case Builtin::BI__builtin_stdc_first_leading_one:
4063 case Builtin::BI__builtin_stdc_first_trailing_zero:
4064 case Builtin::BI__builtin_stdc_first_trailing_one:
4065 case Builtin::BI__builtin_stdc_count_zeros:
4066 case Builtin::BI__builtin_stdc_count_ones:
4067 case Builtin::BI__builtin_stdc_bit_width:
4068 if (BuiltinStdCBuiltin(S&: *this, TheCall, ReturnType: Context.UnsignedIntTy))
4069 return ExprError();
4070 break;
4071
4072 case Builtin::BI__builtin_allow_runtime_check: {
4073 Expr *Arg = TheCall->getArg(Arg: 0);
4074 // Check if the argument is a string literal.
4075 if (!isa<StringLiteral>(Val: Arg->IgnoreParenImpCasts())) {
4076 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
4077 << Arg->getSourceRange();
4078 return ExprError();
4079 }
4080 break;
4081 }
4082
4083 case Builtin::BI__builtin_allow_sanitize_check: {
4084 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
4085 return ExprError();
4086
4087 Expr *Arg = TheCall->getArg(Arg: 0);
4088 // Check if the argument is a string literal.
4089 const StringLiteral *SanitizerName =
4090 dyn_cast<StringLiteral>(Val: Arg->IgnoreParenImpCasts());
4091 if (!SanitizerName) {
4092 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_expr_not_string_literal)
4093 << Arg->getSourceRange();
4094 return ExprError();
4095 }
4096 // Validate the sanitizer name.
4097 if (!llvm::StringSwitch<bool>(SanitizerName->getString())
4098 .Cases(CaseStrings: {"address", "thread", "memory", "hwaddress",
4099 "kernel-address", "kernel-memory", "kernel-hwaddress"},
4100 Value: true)
4101 .Default(Value: false)) {
4102 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_invalid_builtin_argument)
4103 << SanitizerName->getString() << "__builtin_allow_sanitize_check"
4104 << Arg->getSourceRange();
4105 return ExprError();
4106 }
4107 break;
4108 }
4109 case Builtin::BI__builtin_counted_by_ref:
4110 if (BuiltinCountedByRef(TheCall))
4111 return ExprError();
4112 break;
4113 }
4114
4115 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall))
4116 return ExprError();
4117
4118 // Since the target specific builtins for each arch overlap, only check those
4119 // of the arch we are compiling for.
4120 if (Context.BuiltinInfo.isTSBuiltin(ID: BuiltinID)) {
4121 if (Context.BuiltinInfo.isAuxBuiltinID(ID: BuiltinID)) {
4122 assert(Context.getAuxTargetInfo() &&
4123 "Aux Target Builtin, but not an aux target?");
4124
4125 if (CheckTSBuiltinFunctionCall(
4126 TI: *Context.getAuxTargetInfo(),
4127 BuiltinID: Context.BuiltinInfo.getAuxBuiltinID(ID: BuiltinID), TheCall))
4128 return ExprError();
4129 } else {
4130 if (CheckTSBuiltinFunctionCall(TI: Context.getTargetInfo(), BuiltinID,
4131 TheCall))
4132 return ExprError();
4133 }
4134 }
4135
4136 return TheCallResult;
4137}
4138
4139bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
4140 llvm::APSInt Result;
4141 // We can't check the value of a dependent argument.
4142 Expr *Arg = TheCall->getArg(Arg: ArgNum);
4143 if (Arg->isTypeDependent() || Arg->isValueDependent())
4144 return false;
4145
4146 // Check constant-ness first.
4147 if (BuiltinConstantArg(TheCall, ArgNum, Result))
4148 return true;
4149
4150 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
4151 if (Result.isShiftedMask() || (~Result).isShiftedMask())
4152 return false;
4153
4154 return Diag(Loc: TheCall->getBeginLoc(),
4155 DiagID: diag::err_argument_not_contiguous_bit_field)
4156 << ArgNum << Arg->getSourceRange();
4157}
4158
4159bool Sema::getFormatStringInfo(const Decl *D, unsigned FormatIdx,
4160 unsigned FirstArg, FormatStringInfo *FSI) {
4161 bool HasImplicitThisParam = hasImplicitObjectParameter(D);
4162 bool IsVariadic = false;
4163 if (const FunctionType *FnTy = D->getFunctionType())
4164 IsVariadic = cast<FunctionProtoType>(Val: FnTy)->isVariadic();
4165 else if (const auto *BD = dyn_cast<BlockDecl>(Val: D))
4166 IsVariadic = BD->isVariadic();
4167 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(Val: D))
4168 IsVariadic = OMD->isVariadic();
4169
4170 return getFormatStringInfo(FormatIdx, FirstArg, HasImplicitThisParam,
4171 IsVariadic, FSI);
4172}
4173
4174bool Sema::getFormatStringInfo(unsigned FormatIdx, unsigned FirstArg,
4175 bool HasImplicitThisParam, bool IsVariadic,
4176 FormatStringInfo *FSI) {
4177 if (FirstArg == 0)
4178 FSI->ArgPassingKind = FAPK_VAList;
4179 else if (IsVariadic)
4180 FSI->ArgPassingKind = FAPK_Variadic;
4181 else
4182 FSI->ArgPassingKind = FAPK_Fixed;
4183 FSI->FormatIdx = FormatIdx - 1;
4184 FSI->FirstDataArg = FSI->ArgPassingKind == FAPK_VAList ? 0 : FirstArg - 1;
4185
4186 // The way the format attribute works in GCC, the implicit this argument
4187 // of member functions is counted. However, it doesn't appear in our own
4188 // lists, so decrement format_idx in that case.
4189 if (HasImplicitThisParam) {
4190 if(FSI->FormatIdx == 0)
4191 return false;
4192 --FSI->FormatIdx;
4193 if (FSI->FirstDataArg != 0)
4194 --FSI->FirstDataArg;
4195 }
4196 return true;
4197}
4198
4199/// Checks if a the given expression evaluates to null.
4200///
4201/// Returns true if the value evaluates to null.
4202static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4203 // Treat (smart) pointers constructed from nullptr as null, whether we can
4204 // const-evaluate them or not.
4205 // This must happen first: the smart pointer expr might have _Nonnull type!
4206 if (isa<CXXNullPtrLiteralExpr>(
4207 Val: IgnoreExprNodes(E: Expr, Fns&: IgnoreImplicitAsWrittenSingleStep,
4208 Fns&: IgnoreElidableImplicitConstructorSingleStep)))
4209 return true;
4210
4211 // If the expression has non-null type, it doesn't evaluate to null.
4212 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) {
4213 if (*nullability == NullabilityKind::NonNull)
4214 return false;
4215 }
4216
4217 // As a special case, transparent unions initialized with zero are
4218 // considered null for the purposes of the nonnull attribute.
4219 if (const RecordType *UT = Expr->getType()->getAsUnionType();
4220 UT &&
4221 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4222 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Val: Expr))
4223 if (const auto *ILE = dyn_cast<InitListExpr>(Val: CLE->getInitializer()))
4224 Expr = ILE->getInit(Init: 0);
4225 }
4226
4227 bool Result;
4228 return (!Expr->isValueDependent() &&
4229 Expr->EvaluateAsBooleanCondition(Result, Ctx: S.Context) &&
4230 !Result);
4231}
4232
4233static void CheckNonNullArgument(Sema &S,
4234 const Expr *ArgExpr,
4235 SourceLocation CallSiteLoc) {
4236 if (CheckNonNullExpr(S, Expr: ArgExpr))
4237 S.DiagRuntimeBehavior(Loc: CallSiteLoc, Statement: ArgExpr,
4238 PD: S.PDiag(DiagID: diag::warn_null_arg)
4239 << ArgExpr->getSourceRange());
4240}
4241
4242/// Determine whether the given type has a non-null nullability annotation.
4243static bool isNonNullType(QualType type) {
4244 if (auto nullability = type->getNullability())
4245 return *nullability == NullabilityKind::NonNull;
4246
4247 return false;
4248}
4249
4250static void CheckNonNullArguments(Sema &S,
4251 const NamedDecl *FDecl,
4252 const FunctionProtoType *Proto,
4253 ArrayRef<const Expr *> Args,
4254 SourceLocation CallSiteLoc) {
4255 assert((FDecl || Proto) && "Need a function declaration or prototype");
4256
4257 // Already checked by constant evaluator.
4258 if (S.isConstantEvaluatedContext())
4259 return;
4260 // Check the attributes attached to the method/function itself.
4261 llvm::SmallBitVector NonNullArgs;
4262 if (FDecl) {
4263 // Handle the nonnull attribute on the function/method declaration itself.
4264 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4265 if (!NonNull->args_size()) {
4266 // Easy case: all pointer arguments are nonnull.
4267 for (const auto *Arg : Args)
4268 if (S.isValidPointerAttrType(T: Arg->getType()))
4269 CheckNonNullArgument(S, ArgExpr: Arg, CallSiteLoc);
4270 return;
4271 }
4272
4273 for (const ParamIdx &Idx : NonNull->args()) {
4274 unsigned IdxAST = Idx.getASTIndex();
4275 if (IdxAST >= Args.size())
4276 continue;
4277 if (NonNullArgs.empty())
4278 NonNullArgs.resize(N: Args.size());
4279 NonNullArgs.set(IdxAST);
4280 }
4281 }
4282 }
4283
4284 if (FDecl && (isa<FunctionDecl>(Val: FDecl) || isa<ObjCMethodDecl>(Val: FDecl))) {
4285 // Handle the nonnull attribute on the parameters of the
4286 // function/method.
4287 ArrayRef<ParmVarDecl*> parms;
4288 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: FDecl))
4289 parms = FD->parameters();
4290 else
4291 parms = cast<ObjCMethodDecl>(Val: FDecl)->parameters();
4292
4293 unsigned ParamIndex = 0;
4294 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4295 I != E; ++I, ++ParamIndex) {
4296 const ParmVarDecl *PVD = *I;
4297 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(type: PVD->getType())) {
4298 if (NonNullArgs.empty())
4299 NonNullArgs.resize(N: Args.size());
4300
4301 NonNullArgs.set(ParamIndex);
4302 }
4303 }
4304 } else {
4305 // If we have a non-function, non-method declaration but no
4306 // function prototype, try to dig out the function prototype.
4307 if (!Proto) {
4308 if (const ValueDecl *VD = dyn_cast<ValueDecl>(Val: FDecl)) {
4309 QualType type = VD->getType().getNonReferenceType();
4310 if (auto pointerType = type->getAs<PointerType>())
4311 type = pointerType->getPointeeType();
4312 else if (auto blockType = type->getAs<BlockPointerType>())
4313 type = blockType->getPointeeType();
4314 // FIXME: data member pointers?
4315
4316 // Dig out the function prototype, if there is one.
4317 Proto = type->getAs<FunctionProtoType>();
4318 }
4319 }
4320
4321 // Fill in non-null argument information from the nullability
4322 // information on the parameter types (if we have them).
4323 if (Proto) {
4324 unsigned Index = 0;
4325 for (auto paramType : Proto->getParamTypes()) {
4326 if (isNonNullType(type: paramType)) {
4327 if (NonNullArgs.empty())
4328 NonNullArgs.resize(N: Args.size());
4329
4330 NonNullArgs.set(Index);
4331 }
4332
4333 ++Index;
4334 }
4335 }
4336 }
4337
4338 // Check for non-null arguments.
4339 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4340 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4341 if (NonNullArgs[ArgIndex])
4342 CheckNonNullArgument(S, ArgExpr: Args[ArgIndex], CallSiteLoc: Args[ArgIndex]->getExprLoc());
4343 }
4344}
4345
4346void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4347 StringRef ParamName, QualType ArgTy,
4348 QualType ParamTy) {
4349
4350 // If a function accepts a pointer or reference type
4351 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4352 return;
4353
4354 // If the parameter is a pointer type, get the pointee type for the
4355 // argument too. If the parameter is a reference type, don't try to get
4356 // the pointee type for the argument.
4357 if (ParamTy->isPointerType())
4358 ArgTy = ArgTy->getPointeeType();
4359
4360 // Remove reference or pointer
4361 ParamTy = ParamTy->getPointeeType();
4362
4363 // Find expected alignment, and the actual alignment of the passed object.
4364 // getTypeAlignInChars requires complete types
4365 if (ArgTy.isNull() || ParamTy->isDependentType() ||
4366 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() ||
4367 ParamTy->isUndeducedType() || ArgTy->isUndeducedType())
4368 return;
4369
4370 CharUnits ParamAlign = Context.getTypeAlignInChars(T: ParamTy);
4371 CharUnits ArgAlign = Context.getTypeAlignInChars(T: ArgTy);
4372
4373 // If the argument is less aligned than the parameter, there is a
4374 // potential alignment issue.
4375 if (ArgAlign < ParamAlign)
4376 Diag(Loc, DiagID: diag::warn_param_mismatched_alignment)
4377 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4378 << ParamName << (FDecl != nullptr) << FDecl;
4379}
4380
4381void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
4382 const Expr *ThisArg,
4383 ArrayRef<const Expr *> Args) {
4384 if (!FD || Args.empty())
4385 return;
4386 auto GetArgAt = [&](int Idx) -> const Expr * {
4387 if (Idx == LifetimeCaptureByAttr::Global ||
4388 Idx == LifetimeCaptureByAttr::Unknown)
4389 return nullptr;
4390 if (IsMemberFunction && Idx == 0)
4391 return ThisArg;
4392 return Args[Idx - IsMemberFunction];
4393 };
4394 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr,
4395 unsigned ArgIdx) {
4396 if (!Attr)
4397 return;
4398
4399 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx));
4400 for (int CapturingParamIdx : Attr->params()) {
4401 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4402 continue;
4403 // lifetime_capture_by(this) case is handled in the lifetimebound expr
4404 // initialization codepath.
4405 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4406 isa<CXXConstructorDecl>(Val: FD))
4407 continue;
4408 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx));
4409 CapturingEntity CE{.Entity: Capturing};
4410 // Ensure that 'Captured' outlives the 'Capturing' entity.
4411 checkCaptureByLifetime(SemaRef&: *this, Entity: CE, Init: Captured);
4412 }
4413 };
4414 for (unsigned I = 0; I < FD->getNumParams(); ++I)
4415 HandleCaptureByAttr(FD->getParamDecl(i: I)->getAttr<LifetimeCaptureByAttr>(),
4416 I + IsMemberFunction);
4417 // Check when the implicit object param is captured.
4418 if (IsMemberFunction) {
4419 TypeSourceInfo *TSI = FD->getTypeSourceInfo();
4420 if (!TSI)
4421 return;
4422 AttributedTypeLoc ATL;
4423 for (TypeLoc TL = TSI->getTypeLoc();
4424 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
4425 TL = ATL.getModifiedLoc())
4426 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0);
4427 }
4428}
4429
4430void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4431 const Expr *ThisArg, ArrayRef<const Expr *> Args,
4432 bool IsMemberFunction, SourceLocation Loc,
4433 SourceRange Range, VariadicCallType CallType) {
4434
4435 if ((ThisArg && ThisArg->isInstantiationDependent()) ||
4436 llvm::any_of(Range&: Args, P: [](const Expr *E) {
4437 return E && E->isInstantiationDependent();
4438 }))
4439 return;
4440
4441 // Printf and scanf checking.
4442 llvm::SmallBitVector CheckedVarArgs;
4443 if (FDecl) {
4444 for (const auto *I : FDecl->specific_attrs<FormatMatchesAttr>()) {
4445 // Only create vector if there are format attributes.
4446 CheckedVarArgs.resize(N: Args.size());
4447 CheckFormatString(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4448 CheckedVarArgs);
4449 }
4450
4451 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4452 CheckedVarArgs.resize(N: Args.size());
4453 CheckFormatArguments(Format: I, Args, IsCXXMember: IsMemberFunction, CallType, Loc, Range,
4454 CheckedVarArgs);
4455 }
4456 }
4457
4458 // Refuse POD arguments that weren't caught by the format string
4459 // checks above.
4460 auto *FD = dyn_cast_or_null<FunctionDecl>(Val: FDecl);
4461 if (CallType != VariadicCallType::DoesNotApply &&
4462 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4463 unsigned NumParams = Proto ? Proto->getNumParams()
4464 : isa_and_nonnull<FunctionDecl>(Val: FDecl)
4465 ? cast<FunctionDecl>(Val: FDecl)->getNumParams()
4466 : isa_and_nonnull<ObjCMethodDecl>(Val: FDecl)
4467 ? cast<ObjCMethodDecl>(Val: FDecl)->param_size()
4468 : 0;
4469
4470 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4471 // Args[ArgIdx] can be null in malformed code.
4472 if (const Expr *Arg = Args[ArgIdx]) {
4473 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4474 checkVariadicArgument(E: Arg, CT: CallType);
4475 }
4476 }
4477 }
4478 if (FD)
4479 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args);
4480 if (FDecl || Proto) {
4481 CheckNonNullArguments(S&: *this, FDecl, Proto, Args, CallSiteLoc: Loc);
4482
4483 // Type safety checking.
4484 if (FDecl) {
4485 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4486 CheckArgumentWithTypeTag(Attr: I, ExprArgs: Args, CallSiteLoc: Loc);
4487 }
4488 }
4489
4490 // Check that passed arguments match the alignment of original arguments.
4491 // Try to get the missing prototype from the declaration.
4492 if (!Proto && FDecl) {
4493 const auto *FT = FDecl->getFunctionType();
4494 if (isa_and_nonnull<FunctionProtoType>(Val: FT))
4495 Proto = cast<FunctionProtoType>(Val: FDecl->getFunctionType());
4496 }
4497 if (Proto) {
4498 // For variadic functions, we may have more args than parameters.
4499 // For some K&R functions, we may have less args than parameters.
4500 const auto N = std::min<unsigned>(a: Proto->getNumParams(), b: Args.size());
4501 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType();
4502 bool IsScalableArg = false;
4503 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4504 // Args[ArgIdx] can be null in malformed code.
4505 if (const Expr *Arg = Args[ArgIdx]) {
4506 if (Arg->containsErrors())
4507 continue;
4508
4509 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4510 FDecl->hasLinkage() &&
4511 FDecl->getFormalLinkage() != Linkage::Internal &&
4512 CallType == VariadicCallType::DoesNotApply)
4513 PPC().checkAIXMemberAlignment(Loc: (Arg->getExprLoc()), Arg);
4514
4515 QualType ParamTy = Proto->getParamType(i: ArgIdx);
4516 if (ParamTy->isSizelessVectorType())
4517 IsScalableArg = true;
4518 QualType ArgTy = Arg->getType();
4519 CheckArgAlignment(Loc: Arg->getExprLoc(), FDecl, ParamName: std::to_string(val: ArgIdx + 1),
4520 ArgTy, ParamTy);
4521 }
4522 }
4523
4524 // If the callee has an AArch64 SME attribute to indicate that it is an
4525 // __arm_streaming function, then the caller requires SME to be available.
4526 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
4527 if (ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask) {
4528 if (auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext)) {
4529 llvm::StringMap<bool> CallerFeatureMap;
4530 Context.getFunctionFeatureMap(FeatureMap&: CallerFeatureMap, CallerFD);
4531 if (!CallerFeatureMap.contains(Key: "sme"))
4532 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4533 } else if (!Context.getTargetInfo().hasFeature(Feature: "sme")) {
4534 Diag(Loc, DiagID: diag::err_sme_call_in_non_sme_target);
4535 }
4536 }
4537
4538 // If the call requires a streaming-mode change and has scalable vector
4539 // arguments or return values, then warn the user that the streaming and
4540 // non-streaming vector lengths may be different.
4541 // When both streaming and non-streaming vector lengths are defined and
4542 // mismatched, produce an error.
4543 const auto *CallerFD = dyn_cast<FunctionDecl>(Val: CurContext);
4544 if (CallerFD && (!FD || !FD->getBuiltinID()) &&
4545 (IsScalableArg || IsScalableRet)) {
4546 bool IsCalleeStreaming =
4547 ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask;
4548 bool IsCalleeStreamingCompatible =
4549 ExtInfo.AArch64SMEAttributes &
4550 FunctionType::SME_PStateSMCompatibleMask;
4551 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(FD: CallerFD);
4552 if (!IsCalleeStreamingCompatible &&
4553 (CallerFnType == SemaARM::ArmStreamingCompatible ||
4554 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) {
4555 const LangOptions &LO = getLangOpts();
4556 unsigned VL = LO.VScaleMin * 128;
4557 unsigned SVL = LO.VScaleStreamingMin * 128;
4558 bool IsVLMismatch = VL && SVL && VL != SVL;
4559
4560 auto EmitDiag = [&](bool IsArg) {
4561 if (IsVLMismatch) {
4562 if (CallerFnType == SemaARM::ArmStreamingCompatible)
4563 // Emit warning for streaming-compatible callers
4564 Diag(Loc, DiagID: diag::warn_sme_streaming_compatible_vl_mismatch)
4565 << IsArg << IsCalleeStreaming << SVL << VL;
4566 else
4567 // Emit error otherwise
4568 Diag(Loc, DiagID: diag::err_sme_streaming_transition_vl_mismatch)
4569 << IsArg << SVL << VL;
4570 } else
4571 Diag(Loc, DiagID: diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4572 << IsArg;
4573 };
4574
4575 if (IsScalableArg)
4576 EmitDiag(true);
4577 if (IsScalableRet)
4578 EmitDiag(false);
4579 }
4580 }
4581
4582 FunctionType::ArmStateValue CalleeArmZAState =
4583 FunctionType::getArmZAState(AttrBits: ExtInfo.AArch64SMEAttributes);
4584 FunctionType::ArmStateValue CalleeArmZT0State =
4585 FunctionType::getArmZT0State(AttrBits: ExtInfo.AArch64SMEAttributes);
4586 if (CalleeArmZAState != FunctionType::ARM_None ||
4587 CalleeArmZT0State != FunctionType::ARM_None) {
4588 bool CallerHasZAState = false;
4589 bool CallerHasZT0State = false;
4590 if (CallerFD) {
4591 auto *Attr = CallerFD->getAttr<ArmNewAttr>();
4592 if (Attr && Attr->isNewZA())
4593 CallerHasZAState = true;
4594 if (Attr && Attr->isNewZT0())
4595 CallerHasZT0State = true;
4596 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) {
4597 CallerHasZAState |=
4598 FunctionType::getArmZAState(
4599 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4600 FunctionType::ARM_None;
4601 CallerHasZT0State |=
4602 FunctionType::getArmZT0State(
4603 AttrBits: FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4604 FunctionType::ARM_None;
4605 }
4606 }
4607
4608 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState)
4609 Diag(Loc, DiagID: diag::err_sme_za_call_no_za_state);
4610
4611 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State)
4612 Diag(Loc, DiagID: diag::err_sme_zt0_call_no_zt0_state);
4613
4614 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None &&
4615 CalleeArmZT0State != FunctionType::ARM_None) {
4616 Diag(Loc, DiagID: diag::err_sme_unimplemented_za_save_restore);
4617 Diag(Loc, DiagID: diag::note_sme_use_preserves_za);
4618 }
4619 }
4620 }
4621
4622 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4623 auto *AA = FDecl->getAttr<AllocAlignAttr>();
4624 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4625 if (!Arg->isValueDependent()) {
4626 Expr::EvalResult Align;
4627 if (Arg->EvaluateAsInt(Result&: Align, Ctx: Context)) {
4628 const llvm::APSInt &I = Align.Val.getInt();
4629 if (!I.isPowerOf2())
4630 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_alignment_not_power_of_two)
4631 << Arg->getSourceRange();
4632
4633 if (I > Sema::MaximumAlignment)
4634 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_assume_aligned_too_great)
4635 << Arg->getSourceRange() << Sema::MaximumAlignment;
4636 }
4637 }
4638 }
4639
4640 if (FD && FD->isVariadic() && getLangOpts().SYCLIsDevice &&
4641 !isUnevaluatedContext())
4642 SYCL().DiagIfDeviceCode(Loc, DiagID: diag::err_variadic_device_fn)
4643 << diag::OffloadLang::SYCL;
4644
4645 if (FD)
4646 diagnoseArgDependentDiagnoseIfAttrs(Function: FD, ThisArg, Args, Loc);
4647}
4648
4649void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) {
4650 if (TemplateDecl *Decl = AutoT->getTypeConstraintConcept()) {
4651 DiagnoseUseOfDecl(D: Decl, Locs: Loc);
4652 }
4653}
4654
4655void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4656 ArrayRef<const Expr *> Args,
4657 const FunctionProtoType *Proto,
4658 SourceLocation Loc) {
4659 VariadicCallType CallType = Proto->isVariadic()
4660 ? VariadicCallType::Constructor
4661 : VariadicCallType::DoesNotApply;
4662
4663 auto *Ctor = cast<CXXConstructorDecl>(Val: FDecl);
4664 CheckArgAlignment(
4665 Loc, FDecl, ParamName: "'this'", ArgTy: Context.getPointerType(T: ThisType),
4666 ParamTy: Context.getPointerType(T: Ctor->getFunctionObjectParameterType()));
4667
4668 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4669 Loc, Range: SourceRange(), CallType);
4670}
4671
4672bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4673 const FunctionProtoType *Proto) {
4674 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(Val: TheCall) &&
4675 isa<CXXMethodDecl>(Val: FDecl);
4676 bool IsMemberFunction = isa<CXXMemberCallExpr>(Val: TheCall) ||
4677 IsMemberOperatorCall;
4678 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4679 Fn: TheCall->getCallee());
4680 Expr** Args = TheCall->getArgs();
4681 unsigned NumArgs = TheCall->getNumArgs();
4682
4683 Expr *ImplicitThis = nullptr;
4684 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) {
4685 // If this is a call to a member operator, hide the first
4686 // argument from checkCall.
4687 // FIXME: Our choice of AST representation here is less than ideal.
4688 ImplicitThis = Args[0];
4689 ++Args;
4690 --NumArgs;
4691 } else if (IsMemberFunction && !FDecl->isStatic() &&
4692 !FDecl->hasCXXExplicitFunctionObjectParameter())
4693 ImplicitThis =
4694 cast<CXXMemberCallExpr>(Val: TheCall)->getImplicitObjectArgument();
4695
4696 if (ImplicitThis) {
4697 // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4698 // used.
4699 QualType ThisType = ImplicitThis->getType();
4700 if (!ThisType->isPointerType()) {
4701 assert(!ThisType->isReferenceType());
4702 ThisType = Context.getPointerType(T: ThisType);
4703 }
4704
4705 QualType ThisTypeFromDecl = Context.getPointerType(
4706 T: cast<CXXMethodDecl>(Val: FDecl)->getFunctionObjectParameterType());
4707
4708 CheckArgAlignment(Loc: TheCall->getRParenLoc(), FDecl, ParamName: "'this'", ArgTy: ThisType,
4709 ParamTy: ThisTypeFromDecl);
4710 }
4711
4712 checkCall(FDecl, Proto, ThisArg: ImplicitThis, Args: llvm::ArrayRef(Args, NumArgs),
4713 IsMemberFunction, Loc: TheCall->getRParenLoc(),
4714 Range: TheCall->getCallee()->getSourceRange(), CallType);
4715
4716 IdentifierInfo *FnInfo = FDecl->getIdentifier();
4717 // None of the checks below are needed for functions that don't have
4718 // simple names (e.g., C++ conversion functions).
4719 if (!FnInfo)
4720 return false;
4721
4722 // Enforce TCB except for builtin calls, which are always allowed.
4723 if (FDecl->getBuiltinID() == 0)
4724 CheckTCBEnforcement(CallExprLoc: TheCall->getExprLoc(), Callee: FDecl);
4725
4726 CheckAbsoluteValueFunction(Call: TheCall, FDecl);
4727 CheckMaxUnsignedZero(Call: TheCall, FDecl);
4728 CheckInfNaNFunction(Call: TheCall, FDecl);
4729
4730 if (getLangOpts().ObjC)
4731 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs);
4732
4733 unsigned CMId = FDecl->getMemoryFunctionKind();
4734
4735 // Handle memory setting and copying functions.
4736 switch (CMId) {
4737 case 0:
4738 return false;
4739 case Builtin::BIstrlcpy: // fallthrough
4740 case Builtin::BIstrlcat:
4741 CheckStrlcpycatArguments(Call: TheCall, FnName: FnInfo);
4742 break;
4743 case Builtin::BIstrncat:
4744 CheckStrncatArguments(Call: TheCall, FnName: FnInfo);
4745 break;
4746 case Builtin::BIfree:
4747 CheckFreeArguments(E: TheCall);
4748 break;
4749 default:
4750 CheckMemaccessArguments(Call: TheCall, BId: CMId, FnName: FnInfo);
4751 }
4752
4753 return false;
4754}
4755
4756bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4757 const FunctionProtoType *Proto) {
4758 QualType Ty;
4759 if (const auto *V = dyn_cast<VarDecl>(Val: NDecl))
4760 Ty = V->getType().getNonReferenceType();
4761 else if (const auto *F = dyn_cast<FieldDecl>(Val: NDecl))
4762 Ty = F->getType().getNonReferenceType();
4763 else
4764 return false;
4765
4766 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4767 !Ty->isFunctionProtoType())
4768 return false;
4769
4770 VariadicCallType CallType;
4771 if (!Proto || !Proto->isVariadic()) {
4772 CallType = VariadicCallType::DoesNotApply;
4773 } else if (Ty->isBlockPointerType()) {
4774 CallType = VariadicCallType::Block;
4775 } else { // Ty->isFunctionPointerType()
4776 CallType = VariadicCallType::Function;
4777 }
4778
4779 checkCall(FDecl: NDecl, Proto, /*ThisArg=*/nullptr,
4780 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4781 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4782 Range: TheCall->getCallee()->getSourceRange(), CallType);
4783
4784 return false;
4785}
4786
4787bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4788 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4789 Fn: TheCall->getCallee());
4790 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4791 Args: llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4792 /*IsMemberFunction=*/false, Loc: TheCall->getRParenLoc(),
4793 Range: TheCall->getCallee()->getSourceRange(), CallType);
4794
4795 return false;
4796}
4797
4798static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4799 if (!llvm::isValidAtomicOrderingCABI(I: Ordering))
4800 return false;
4801
4802 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4803 switch (Op) {
4804 case AtomicExpr::AO__c11_atomic_init:
4805 case AtomicExpr::AO__opencl_atomic_init:
4806 llvm_unreachable("There is no ordering argument for an init");
4807
4808 case AtomicExpr::AO__c11_atomic_load:
4809 case AtomicExpr::AO__opencl_atomic_load:
4810 case AtomicExpr::AO__hip_atomic_load:
4811 case AtomicExpr::AO__atomic_load_n:
4812 case AtomicExpr::AO__atomic_load:
4813 case AtomicExpr::AO__scoped_atomic_load_n:
4814 case AtomicExpr::AO__scoped_atomic_load:
4815 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4816 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4817
4818 case AtomicExpr::AO__c11_atomic_store:
4819 case AtomicExpr::AO__opencl_atomic_store:
4820 case AtomicExpr::AO__hip_atomic_store:
4821 case AtomicExpr::AO__atomic_store:
4822 case AtomicExpr::AO__atomic_store_n:
4823 case AtomicExpr::AO__scoped_atomic_store:
4824 case AtomicExpr::AO__scoped_atomic_store_n:
4825 case AtomicExpr::AO__atomic_clear:
4826 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4827 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4828 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4829
4830 default:
4831 return true;
4832 }
4833}
4834
4835ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult,
4836 AtomicExpr::AtomicOp Op) {
4837 CallExpr *TheCall = cast<CallExpr>(Val: TheCallResult.get());
4838 DeclRefExpr *DRE =cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
4839 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4840 return BuildAtomicExpr(CallRange: {TheCall->getBeginLoc(), TheCall->getEndLoc()},
4841 ExprRange: DRE->getSourceRange(), RParenLoc: TheCall->getRParenLoc(), Args,
4842 Op);
4843}
4844
4845/// Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_*
4846/// equivalents. Provide a fixit when the scope is a compile-time constant and
4847/// there is a direct mapping from the HIP builtin to a Clang builtin. The
4848/// compare_exchange builtins differ in how they accept the desired value, so
4849/// only a warning (without a fixit) is emitted for those.
4850static void DiagnoseDeprecatedHIPAtomic(Sema &S, SourceRange ExprRange,
4851 MultiExprArg Args,
4852 AtomicExpr::AtomicOp Op) {
4853 StringRef OldName;
4854 StringRef NewName;
4855 bool CanFixIt;
4856
4857 switch (Op) {
4858#define HIP_ATOMIC_FIXABLE(hip, scoped) \
4859 case AtomicExpr::AO__hip_atomic_##hip: \
4860 OldName = "__hip_atomic_" #hip; \
4861 NewName = "__scoped_atomic_" #scoped; \
4862 CanFixIt = true; \
4863 break;
4864 HIP_ATOMIC_FIXABLE(load, load_n)
4865 HIP_ATOMIC_FIXABLE(store, store_n)
4866 HIP_ATOMIC_FIXABLE(exchange, exchange_n)
4867 HIP_ATOMIC_FIXABLE(fetch_add, fetch_add)
4868 HIP_ATOMIC_FIXABLE(fetch_sub, fetch_sub)
4869 HIP_ATOMIC_FIXABLE(fetch_and, fetch_and)
4870 HIP_ATOMIC_FIXABLE(fetch_or, fetch_or)
4871 HIP_ATOMIC_FIXABLE(fetch_xor, fetch_xor)
4872 HIP_ATOMIC_FIXABLE(fetch_min, fetch_min)
4873 HIP_ATOMIC_FIXABLE(fetch_max, fetch_max)
4874#undef HIP_ATOMIC_FIXABLE
4875 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
4876 OldName = "__hip_atomic_compare_exchange_weak";
4877 NewName = "__scoped_atomic_compare_exchange";
4878 CanFixIt = false;
4879 break;
4880 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
4881 OldName = "__hip_atomic_compare_exchange_strong";
4882 NewName = "__scoped_atomic_compare_exchange";
4883 CanFixIt = false;
4884 break;
4885 default:
4886 llvm_unreachable("unhandled HIP atomic op");
4887 }
4888
4889 auto DB = S.Diag(Loc: ExprRange.getBegin(), DiagID: diag::warn_hip_deprecated_builtin)
4890 << OldName << NewName;
4891 if (!CanFixIt)
4892 return;
4893
4894 DB << FixItHint::CreateReplacement(RemoveRange: ExprRange, Code: NewName);
4895
4896 Expr *Scope = Args[Args.size() - 1];
4897 std::optional<llvm::APSInt> ScopeVal =
4898 Scope->getIntegerConstantExpr(Ctx: S.Context);
4899 if (!ScopeVal)
4900 return;
4901
4902 StringRef ScopeName;
4903 switch (ScopeVal->getZExtValue()) {
4904 case AtomicScopeHIPModel::SingleThread:
4905 ScopeName = "__MEMORY_SCOPE_SINGLE";
4906 break;
4907 case AtomicScopeHIPModel::Wavefront:
4908 ScopeName = "__MEMORY_SCOPE_WVFRNT";
4909 break;
4910 case AtomicScopeHIPModel::Workgroup:
4911 ScopeName = "__MEMORY_SCOPE_WRKGRP";
4912 break;
4913 case AtomicScopeHIPModel::Agent:
4914 ScopeName = "__MEMORY_SCOPE_DEVICE";
4915 break;
4916 case AtomicScopeHIPModel::System:
4917 ScopeName = "__MEMORY_SCOPE_SYSTEM";
4918 break;
4919 case AtomicScopeHIPModel::Cluster:
4920 ScopeName = "__MEMORY_SCOPE_CLUSTR";
4921 break;
4922 default:
4923 return;
4924 }
4925
4926 DB << FixItHint::CreateReplacement(
4927 RemoveRange: CharSourceRange::getTokenRange(R: Scope->getSourceRange()), Code: ScopeName);
4928}
4929
4930ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4931 SourceLocation RParenLoc, MultiExprArg Args,
4932 AtomicExpr::AtomicOp Op,
4933 AtomicArgumentOrder ArgOrder) {
4934 // All the non-OpenCL operations take one of the following forms.
4935 // The OpenCL operations take the __c11 forms with one extra argument for
4936 // synchronization scope.
4937 enum {
4938 // C __c11_atomic_init(A *, C)
4939 Init,
4940
4941 // C __c11_atomic_load(A *, int)
4942 Load,
4943
4944 // void __atomic_load(A *, CP, int)
4945 LoadCopy,
4946
4947 // void __atomic_store(A *, CP, int)
4948 Copy,
4949
4950 // C __c11_atomic_add(A *, M, int)
4951 Arithmetic,
4952
4953 // C __atomic_exchange_n(A *, CP, int)
4954 Xchg,
4955
4956 // void __atomic_exchange(A *, C *, CP, int)
4957 GNUXchg,
4958
4959 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4960 C11CmpXchg,
4961
4962 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4963 GNUCmpXchg,
4964
4965 // bool __atomic_test_and_set(A *, int)
4966 TestAndSetByte,
4967
4968 // void __atomic_clear(A *, int)
4969 ClearByte,
4970 } Form = Init;
4971
4972 const unsigned NumForm = ClearByte + 1;
4973 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
4974 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
4975 // where:
4976 // C is an appropriate type,
4977 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4978 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4979 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4980 // the int parameters are for orderings.
4981
4982 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4983 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4984 "need to update code for modified forms");
4985 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
4986 AtomicExpr::AO__atomic_xor_fetch + 1 ==
4987 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
4988 "need to update code for modified C11 atomics");
4989 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
4990 Op <= AtomicExpr::AO__opencl_atomic_store;
4991 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
4992 Op <= AtomicExpr::AO__hip_atomic_store;
4993 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
4994 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
4995 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
4996 Op <= AtomicExpr::AO__c11_atomic_store) ||
4997 IsOpenCL;
4998 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4999 Op == AtomicExpr::AO__atomic_store_n ||
5000 Op == AtomicExpr::AO__atomic_exchange_n ||
5001 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
5002 Op == AtomicExpr::AO__scoped_atomic_load_n ||
5003 Op == AtomicExpr::AO__scoped_atomic_store_n ||
5004 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
5005 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
5006 // Bit mask for extra allowed value types other than integers for atomic
5007 // arithmetic operations. Add/sub allow pointer and floating point. Min/max
5008 // allow floating point.
5009 enum ArithOpExtraValueType {
5010 AOEVT_None = 0,
5011 AOEVT_Pointer = 1,
5012 AOEVT_FP = 2,
5013 AOEVT_Int = 4,
5014 };
5015 unsigned ArithAllows = AOEVT_None;
5016
5017 switch (Op) {
5018 case AtomicExpr::AO__c11_atomic_init:
5019 case AtomicExpr::AO__opencl_atomic_init:
5020 Form = Init;
5021 break;
5022
5023 case AtomicExpr::AO__c11_atomic_load:
5024 case AtomicExpr::AO__opencl_atomic_load:
5025 case AtomicExpr::AO__hip_atomic_load:
5026 case AtomicExpr::AO__atomic_load_n:
5027 case AtomicExpr::AO__scoped_atomic_load_n:
5028 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5029 Form = Load;
5030 break;
5031
5032 case AtomicExpr::AO__atomic_load:
5033 case AtomicExpr::AO__scoped_atomic_load:
5034 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5035 Form = LoadCopy;
5036 break;
5037
5038 case AtomicExpr::AO__c11_atomic_store:
5039 case AtomicExpr::AO__opencl_atomic_store:
5040 case AtomicExpr::AO__hip_atomic_store:
5041 case AtomicExpr::AO__atomic_store:
5042 case AtomicExpr::AO__atomic_store_n:
5043 case AtomicExpr::AO__scoped_atomic_store:
5044 case AtomicExpr::AO__scoped_atomic_store_n:
5045 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5046 Form = Copy;
5047 break;
5048 case AtomicExpr::AO__atomic_fetch_add:
5049 case AtomicExpr::AO__atomic_fetch_sub:
5050 case AtomicExpr::AO__atomic_add_fetch:
5051 case AtomicExpr::AO__atomic_sub_fetch:
5052 case AtomicExpr::AO__scoped_atomic_fetch_add:
5053 case AtomicExpr::AO__scoped_atomic_fetch_sub:
5054 case AtomicExpr::AO__scoped_atomic_add_fetch:
5055 case AtomicExpr::AO__scoped_atomic_sub_fetch:
5056 case AtomicExpr::AO__c11_atomic_fetch_add:
5057 case AtomicExpr::AO__c11_atomic_fetch_sub:
5058 case AtomicExpr::AO__opencl_atomic_fetch_add:
5059 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5060 case AtomicExpr::AO__hip_atomic_fetch_add:
5061 case AtomicExpr::AO__hip_atomic_fetch_sub:
5062 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5063 Form = Arithmetic;
5064 break;
5065 case AtomicExpr::AO__atomic_fetch_fminimum:
5066 case AtomicExpr::AO__atomic_fetch_fmaximum:
5067 case AtomicExpr::AO__atomic_fetch_fminimum_num:
5068 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
5069 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
5070 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
5071 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
5072 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
5073 ArithAllows = AOEVT_FP;
5074 Form = Arithmetic;
5075 break;
5076 case AtomicExpr::AO__atomic_fetch_max:
5077 case AtomicExpr::AO__atomic_fetch_min:
5078 case AtomicExpr::AO__atomic_max_fetch:
5079 case AtomicExpr::AO__atomic_min_fetch:
5080 case AtomicExpr::AO__scoped_atomic_fetch_max:
5081 case AtomicExpr::AO__scoped_atomic_fetch_min:
5082 case AtomicExpr::AO__scoped_atomic_max_fetch:
5083 case AtomicExpr::AO__scoped_atomic_min_fetch:
5084 case AtomicExpr::AO__c11_atomic_fetch_max:
5085 case AtomicExpr::AO__c11_atomic_fetch_min:
5086 case AtomicExpr::AO__opencl_atomic_fetch_max:
5087 case AtomicExpr::AO__opencl_atomic_fetch_min:
5088 case AtomicExpr::AO__hip_atomic_fetch_max:
5089 case AtomicExpr::AO__hip_atomic_fetch_min:
5090 ArithAllows = AOEVT_Int | AOEVT_FP;
5091 Form = Arithmetic;
5092 break;
5093 case AtomicExpr::AO__c11_atomic_fetch_and:
5094 case AtomicExpr::AO__c11_atomic_fetch_or:
5095 case AtomicExpr::AO__c11_atomic_fetch_xor:
5096 case AtomicExpr::AO__hip_atomic_fetch_and:
5097 case AtomicExpr::AO__hip_atomic_fetch_or:
5098 case AtomicExpr::AO__hip_atomic_fetch_xor:
5099 case AtomicExpr::AO__c11_atomic_fetch_nand:
5100 case AtomicExpr::AO__opencl_atomic_fetch_and:
5101 case AtomicExpr::AO__opencl_atomic_fetch_or:
5102 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5103 case AtomicExpr::AO__atomic_fetch_and:
5104 case AtomicExpr::AO__atomic_fetch_or:
5105 case AtomicExpr::AO__atomic_fetch_xor:
5106 case AtomicExpr::AO__atomic_fetch_nand:
5107 case AtomicExpr::AO__atomic_and_fetch:
5108 case AtomicExpr::AO__atomic_or_fetch:
5109 case AtomicExpr::AO__atomic_xor_fetch:
5110 case AtomicExpr::AO__atomic_nand_fetch:
5111 case AtomicExpr::AO__atomic_fetch_uinc:
5112 case AtomicExpr::AO__atomic_fetch_udec:
5113 case AtomicExpr::AO__scoped_atomic_fetch_and:
5114 case AtomicExpr::AO__scoped_atomic_fetch_or:
5115 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5116 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5117 case AtomicExpr::AO__scoped_atomic_and_fetch:
5118 case AtomicExpr::AO__scoped_atomic_or_fetch:
5119 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5120 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5121 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5122 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5123 Form = Arithmetic;
5124 break;
5125
5126 case AtomicExpr::AO__c11_atomic_exchange:
5127 case AtomicExpr::AO__hip_atomic_exchange:
5128 case AtomicExpr::AO__opencl_atomic_exchange:
5129 case AtomicExpr::AO__atomic_exchange_n:
5130 case AtomicExpr::AO__scoped_atomic_exchange_n:
5131 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5132 Form = Xchg;
5133 break;
5134
5135 case AtomicExpr::AO__atomic_exchange:
5136 case AtomicExpr::AO__scoped_atomic_exchange:
5137 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5138 Form = GNUXchg;
5139 break;
5140
5141 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5142 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5143 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5144 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5145 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5146 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5147 Form = C11CmpXchg;
5148 break;
5149
5150 case AtomicExpr::AO__atomic_compare_exchange:
5151 case AtomicExpr::AO__atomic_compare_exchange_n:
5152 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5153 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5154 ArithAllows = AOEVT_Pointer;
5155 Form = GNUCmpXchg;
5156 break;
5157
5158 case AtomicExpr::AO__atomic_test_and_set:
5159 Form = TestAndSetByte;
5160 break;
5161
5162 case AtomicExpr::AO__atomic_clear:
5163 Form = ClearByte;
5164 break;
5165 }
5166
5167 unsigned AdjustedNumArgs = NumArgs[Form];
5168 if ((IsOpenCL || IsHIP || IsScoped) &&
5169 Op != AtomicExpr::AO__opencl_atomic_init)
5170 ++AdjustedNumArgs;
5171 // Check we have the right number of arguments.
5172 if (Args.size() < AdjustedNumArgs) {
5173 Diag(Loc: CallRange.getEnd(), DiagID: diag::err_typecheck_call_too_few_args)
5174 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5175 << /*is non object*/ 0 << ExprRange;
5176 return ExprError();
5177 } else if (Args.size() > AdjustedNumArgs) {
5178 Diag(Loc: Args[AdjustedNumArgs]->getBeginLoc(),
5179 DiagID: diag::err_typecheck_call_too_many_args)
5180 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5181 << /*is non object*/ 0 << ExprRange;
5182 return ExprError();
5183 }
5184
5185 // Inspect the first argument of the atomic operation.
5186 Expr *Ptr = Args[0];
5187 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(E: Ptr);
5188 if (ConvertedPtr.isInvalid())
5189 return ExprError();
5190
5191 Ptr = ConvertedPtr.get();
5192 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5193 if (!pointerType) {
5194 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5195 << Ptr->getType() << 0 << Ptr->getSourceRange();
5196 return ExprError();
5197 }
5198
5199 // For a __c11 builtin, this should be a pointer to an _Atomic type.
5200 QualType AtomTy = pointerType->getPointeeType(); // 'A'
5201 QualType ValType = AtomTy; // 'C'
5202 if (IsC11) {
5203 if (!AtomTy->isAtomicType()) {
5204 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_atomic)
5205 << Ptr->getType() << Ptr->getSourceRange();
5206 return ExprError();
5207 }
5208 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5209 AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5210 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_atomic)
5211 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5212 << Ptr->getSourceRange();
5213 return ExprError();
5214 }
5215 ValType = AtomTy->castAs<AtomicType>()->getValueType();
5216 } else if (Form != Load && Form != LoadCopy) {
5217 if (ValType.isConstQualified()) {
5218 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_non_const_pointer)
5219 << Ptr->getType() << Ptr->getSourceRange();
5220 return ExprError();
5221 }
5222 }
5223
5224 if (Form != TestAndSetByte && Form != ClearByte) {
5225 // Pointer to object of size zero is not allowed.
5226 if (RequireCompleteType(Loc: Ptr->getBeginLoc(), T: AtomTy,
5227 DiagID: diag::err_incomplete_type))
5228 return ExprError();
5229
5230 if (Context.getTypeInfoInChars(T: AtomTy).Width.isZero()) {
5231 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5232 << Ptr->getType() << 1 << Ptr->getSourceRange();
5233 return ExprError();
5234 }
5235 } else {
5236 // The __atomic_clear and __atomic_test_and_set intrinsics accept any
5237 // non-const pointer type, including void* and pointers to incomplete
5238 // structs, but only access the first byte.
5239 AtomTy = Context.CharTy;
5240 AtomTy = AtomTy.withCVRQualifiers(
5241 CVR: pointerType->getPointeeType().getCVRQualifiers());
5242 QualType PointerQT = Context.getPointerType(T: AtomTy);
5243 pointerType = PointerQT->getAs<PointerType>();
5244 Ptr = ImpCastExprToType(E: Ptr, Type: PointerQT, CK: CK_BitCast).get();
5245 ValType = AtomTy;
5246 }
5247
5248 PointerAuthQualifier PointerAuth = AtomTy.getPointerAuth();
5249 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5250 Diag(Loc: ExprRange.getBegin(),
5251 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5252 << 0 << Ptr->getType() << Ptr->getSourceRange();
5253 return ExprError();
5254 }
5255
5256 // For an arithmetic operation, the implied arithmetic must be well-formed.
5257 // For _n operations, the value type must also be a valid atomic type.
5258 if (Form == Arithmetic || IsN) {
5259 // GCC does not enforce these rules for GNU atomics, but we do to help catch
5260 // trivial type errors.
5261 auto IsAllowedValueType = [&](QualType ValType,
5262 unsigned AllowedType) -> bool {
5263 bool IsX87LongDouble =
5264 ValType->isSpecificBuiltinType(K: BuiltinType::LongDouble) &&
5265 &Context.getTargetInfo().getLongDoubleFormat() ==
5266 &llvm::APFloat::x87DoubleExtended();
5267 if (ValType->isIntegerType())
5268 // Special case: f-prefixed operations (AOEVT_FP exactly) reject
5269 // integers. Explicit AOEVT_Int or other combinations allow integers.
5270 return (AllowedType & AOEVT_Int) || AllowedType != AOEVT_FP;
5271 if (ValType->isPointerType())
5272 return AllowedType & AOEVT_Pointer;
5273 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP)))
5274 return false;
5275 // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5276 if (IsX87LongDouble)
5277 return false;
5278 return true;
5279 };
5280 if (!IsAllowedValueType(ValType, ArithAllows)) {
5281 auto DID =
5282 ArithAllows == AOEVT_FP
5283 ? diag::err_atomic_op_needs_atomic_fp
5284 : (ArithAllows & AOEVT_FP
5285 ? (ArithAllows & AOEVT_Pointer
5286 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5287 : diag::err_atomic_op_needs_atomic_int_or_fp)
5288 : (ArithAllows & AOEVT_Pointer
5289 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5290 : diag::err_atomic_op_needs_atomic_int));
5291 Diag(Loc: ExprRange.getBegin(), DiagID: DID)
5292 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5293 return ExprError();
5294 }
5295 if (IsC11 && ValType->isPointerType() &&
5296 RequireCompleteType(Loc: Ptr->getBeginLoc(), T: ValType->getPointeeType(),
5297 DiagID: diag::err_incomplete_type)) {
5298 return ExprError();
5299 }
5300 }
5301
5302 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5303 !AtomTy->isScalarType()) {
5304 // For GNU atomics, require a trivially-copyable type. This is not part of
5305 // the GNU atomics specification but we enforce it for consistency with
5306 // other atomics which generally all require a trivially-copyable type. This
5307 // is because atomics just copy bits.
5308 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_atomic_op_needs_trivial_copy)
5309 << Ptr->getType() << Ptr->getSourceRange();
5310 return ExprError();
5311 }
5312
5313 switch (ValType.getObjCLifetime()) {
5314 case Qualifiers::OCL_None:
5315 case Qualifiers::OCL_ExplicitNone:
5316 // okay
5317 break;
5318
5319 case Qualifiers::OCL_Weak:
5320 case Qualifiers::OCL_Strong:
5321 case Qualifiers::OCL_Autoreleasing:
5322 // FIXME: Can this happen? By this point, ValType should be known
5323 // to be trivially copyable.
5324 Diag(Loc: ExprRange.getBegin(), DiagID: diag::err_arc_atomic_ownership)
5325 << ValType << Ptr->getSourceRange();
5326 return ExprError();
5327 }
5328
5329 // All atomic operations have an overload which takes a pointer to a volatile
5330 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself
5331 // into the result or the other operands. Similarly atomic_load takes a
5332 // pointer to a const 'A'.
5333 ValType.removeLocalVolatile();
5334 ValType.removeLocalConst();
5335 QualType ResultType = ValType;
5336 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init ||
5337 Form == ClearByte)
5338 ResultType = Context.VoidTy;
5339 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5340 ResultType = Context.BoolTy;
5341
5342 // The type of a parameter passed 'by value'. In the GNU atomics, such
5343 // arguments are actually passed as pointers.
5344 QualType ByValType = ValType; // 'CP'
5345 bool IsPassedByAddress = false;
5346 if (!IsC11 && !IsHIP && !IsN) {
5347 ByValType = Ptr->getType();
5348 IsPassedByAddress = true;
5349 }
5350
5351 SmallVector<Expr *, 5> APIOrderedArgs;
5352 if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5353 APIOrderedArgs.push_back(Elt: Args[0]);
5354 switch (Form) {
5355 case Init:
5356 case Load:
5357 APIOrderedArgs.push_back(Elt: Args[1]); // Val1/Order
5358 break;
5359 case LoadCopy:
5360 case Copy:
5361 case Arithmetic:
5362 case Xchg:
5363 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5364 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5365 break;
5366 case GNUXchg:
5367 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5368 APIOrderedArgs.push_back(Elt: Args[3]); // Val2
5369 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5370 break;
5371 case C11CmpXchg:
5372 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5373 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
5374 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5375 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
5376 break;
5377 case GNUCmpXchg:
5378 APIOrderedArgs.push_back(Elt: Args[2]); // Val1
5379 APIOrderedArgs.push_back(Elt: Args[4]); // Val2
5380 APIOrderedArgs.push_back(Elt: Args[5]); // Weak
5381 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5382 APIOrderedArgs.push_back(Elt: Args[3]); // OrderFail
5383 break;
5384 case TestAndSetByte:
5385 case ClearByte:
5386 APIOrderedArgs.push_back(Elt: Args[1]); // Order
5387 break;
5388 }
5389 } else
5390 APIOrderedArgs.append(in_start: Args.begin(), in_end: Args.end());
5391
5392 // The first argument's non-CV pointer type is used to deduce the type of
5393 // subsequent arguments, except for:
5394 // - weak flag (always converted to bool)
5395 // - memory order (always converted to int)
5396 // - scope (always converted to int)
5397 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5398 QualType Ty;
5399 if (i < NumVals[Form] + 1) {
5400 switch (i) {
5401 case 0:
5402 // The first argument is always a pointer. It has a fixed type.
5403 // It is always dereferenced, a nullptr is undefined.
5404 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5405 // Nothing else to do: we already know all we want about this pointer.
5406 continue;
5407 case 1:
5408 // The second argument is the non-atomic operand. For arithmetic, this
5409 // is always passed by value, and for a compare_exchange it is always
5410 // passed by address. For the rest, GNU uses by-address and C11 uses
5411 // by-value.
5412 assert(Form != Load);
5413 if (Form == Arithmetic && ValType->isPointerType())
5414 Ty = Context.getPointerDiffType();
5415 else if (Form == Init || Form == Arithmetic)
5416 Ty = ValType;
5417 else if (Form == Copy || Form == Xchg) {
5418 if (IsPassedByAddress) {
5419 // The value pointer is always dereferenced, a nullptr is undefined.
5420 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i],
5421 CallSiteLoc: ExprRange.getBegin());
5422 }
5423 Ty = ByValType;
5424 } else {
5425 Expr *ValArg = APIOrderedArgs[i];
5426 // The value pointer is always dereferenced, a nullptr is undefined.
5427 CheckNonNullArgument(S&: *this, ArgExpr: ValArg, CallSiteLoc: ExprRange.getBegin());
5428 LangAS AS = LangAS::Default;
5429 // Keep address space of non-atomic pointer type.
5430 if (const PointerType *PtrTy =
5431 ValArg->getType()->getAs<PointerType>()) {
5432 AS = PtrTy->getPointeeType().getAddressSpace();
5433 }
5434 Ty = Context.getPointerType(
5435 T: Context.getAddrSpaceQualType(T: ValType.getUnqualifiedType(), AddressSpace: AS));
5436 }
5437 break;
5438 case 2:
5439 // The third argument to compare_exchange / GNU exchange is the desired
5440 // value, either by-value (for the C11 and *_n variant) or as a pointer.
5441 if (IsPassedByAddress)
5442 CheckNonNullArgument(S&: *this, ArgExpr: APIOrderedArgs[i], CallSiteLoc: ExprRange.getBegin());
5443 Ty = ByValType;
5444 break;
5445 case 3:
5446 // The fourth argument to GNU compare_exchange is a 'weak' flag.
5447 Ty = Context.BoolTy;
5448 break;
5449 }
5450 } else {
5451 // The order(s) and scope are always converted to int.
5452 Ty = Context.IntTy;
5453 }
5454
5455 InitializedEntity Entity =
5456 InitializedEntity::InitializeParameter(Context, Type: Ty, Consumed: false);
5457 ExprResult Arg = APIOrderedArgs[i];
5458 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5459 if (Arg.isInvalid())
5460 return true;
5461 APIOrderedArgs[i] = Arg.get();
5462 }
5463
5464 // Permute the arguments into a 'consistent' order.
5465 SmallVector<Expr*, 5> SubExprs;
5466 SubExprs.push_back(Elt: Ptr);
5467 switch (Form) {
5468 case Init:
5469 // Note, AtomicExpr::getVal1() has a special case for this atomic.
5470 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5471 break;
5472 case Load:
5473 case TestAndSetByte:
5474 case ClearByte:
5475 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Order
5476 break;
5477 case LoadCopy:
5478 case Copy:
5479 case Arithmetic:
5480 case Xchg:
5481 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Order
5482 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5483 break;
5484 case GNUXchg:
5485 // Note, AtomicExpr::getVal2() has a special case for this atomic.
5486 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5487 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5488 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5489 break;
5490 case C11CmpXchg:
5491 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Order
5492 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5493 SubExprs.push_back(Elt: APIOrderedArgs[4]); // OrderFail
5494 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5495 break;
5496 case GNUCmpXchg:
5497 SubExprs.push_back(Elt: APIOrderedArgs[4]); // Order
5498 SubExprs.push_back(Elt: APIOrderedArgs[1]); // Val1
5499 SubExprs.push_back(Elt: APIOrderedArgs[5]); // OrderFail
5500 SubExprs.push_back(Elt: APIOrderedArgs[2]); // Val2
5501 SubExprs.push_back(Elt: APIOrderedArgs[3]); // Weak
5502 break;
5503 }
5504
5505 // If the memory orders are constants, check they are valid.
5506 if (SubExprs.size() >= 2 && Form != Init) {
5507 std::optional<llvm::APSInt> Success =
5508 SubExprs[1]->getIntegerConstantExpr(Ctx: Context);
5509 if (Success && !isValidOrderingForOp(Ordering: Success->getSExtValue(), Op)) {
5510 Diag(Loc: SubExprs[1]->getBeginLoc(),
5511 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5512 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg)
5513 << SubExprs[1]->getSourceRange();
5514 }
5515 if (SubExprs.size() >= 5) {
5516 if (std::optional<llvm::APSInt> Failure =
5517 SubExprs[3]->getIntegerConstantExpr(Ctx: Context)) {
5518 if (!llvm::is_contained(
5519 Set: {llvm::AtomicOrderingCABI::relaxed,
5520 llvm::AtomicOrderingCABI::consume,
5521 llvm::AtomicOrderingCABI::acquire,
5522 llvm::AtomicOrderingCABI::seq_cst},
5523 Element: (llvm::AtomicOrderingCABI)Failure->getSExtValue())) {
5524 Diag(Loc: SubExprs[3]->getBeginLoc(),
5525 DiagID: diag::warn_atomic_op_has_invalid_memory_order)
5526 << /*failure=*/2 << SubExprs[3]->getSourceRange();
5527 }
5528 }
5529 }
5530 }
5531
5532 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5533 auto *Scope = Args[Args.size() - 1];
5534 if (std::optional<llvm::APSInt> Result =
5535 Scope->getIntegerConstantExpr(Ctx: Context)) {
5536 if (!ScopeModel->isValid(S: Result->getZExtValue()))
5537 Diag(Loc: Scope->getBeginLoc(), DiagID: diag::err_atomic_op_has_invalid_sync_scope)
5538 << Scope->getSourceRange();
5539 }
5540 SubExprs.push_back(Elt: Scope);
5541 }
5542
5543 if (IsHIP)
5544 DiagnoseDeprecatedHIPAtomic(S&: *this, ExprRange, Args, Op);
5545
5546 AtomicExpr *AE = new (Context)
5547 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5548
5549 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5550 Op == AtomicExpr::AO__c11_atomic_store ||
5551 Op == AtomicExpr::AO__opencl_atomic_load ||
5552 Op == AtomicExpr::AO__hip_atomic_load ||
5553 Op == AtomicExpr::AO__opencl_atomic_store ||
5554 Op == AtomicExpr::AO__hip_atomic_store) &&
5555 Context.AtomicUsesUnsupportedLibcall(E: AE))
5556 Diag(Loc: AE->getBeginLoc(), DiagID: diag::err_atomic_load_store_uses_lib)
5557 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5558 Op == AtomicExpr::AO__opencl_atomic_load ||
5559 Op == AtomicExpr::AO__hip_atomic_load)
5560 ? 0
5561 : 1);
5562
5563 if (ValType->isBitIntType()) {
5564 Diag(Loc: Ptr->getExprLoc(), DiagID: diag::err_atomic_builtin_bit_int_prohibit);
5565 return ExprError();
5566 }
5567
5568 return AE;
5569}
5570
5571/// checkBuiltinArgument - Given a call to a builtin function, perform
5572/// normal type-checking on the given argument, updating the call in
5573/// place. This is useful when a builtin function requires custom
5574/// type-checking for some of its arguments but not necessarily all of
5575/// them.
5576///
5577/// Returns true on error.
5578static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5579 FunctionDecl *Fn = E->getDirectCallee();
5580 assert(Fn && "builtin call without direct callee!");
5581
5582 ParmVarDecl *Param = Fn->getParamDecl(i: ArgIndex);
5583 InitializedEntity Entity =
5584 InitializedEntity::InitializeParameter(Context&: S.Context, Parm: Param);
5585
5586 ExprResult Arg = E->getArg(Arg: ArgIndex);
5587 Arg = S.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5588 if (Arg.isInvalid())
5589 return true;
5590
5591 E->setArg(Arg: ArgIndex, ArgExpr: Arg.get());
5592 return false;
5593}
5594
5595ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) {
5596 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5597 Expr *Callee = TheCall->getCallee();
5598 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: Callee->IgnoreParenCasts());
5599 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
5600
5601 // Ensure that we have at least one argument to do type inference from.
5602 if (TheCall->getNumArgs() < 1) {
5603 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5604 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0
5605 << Callee->getSourceRange();
5606 return ExprError();
5607 }
5608
5609 // Inspect the first argument of the atomic builtin. This should always be
5610 // a pointer type, whose element is an integral scalar or pointer type.
5611 // Because it is a pointer type, we don't have to worry about any implicit
5612 // casts here.
5613 // FIXME: We don't allow floating point scalars as input.
5614 Expr *FirstArg = TheCall->getArg(Arg: 0);
5615 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(E: FirstArg);
5616 if (FirstArgResult.isInvalid())
5617 return ExprError();
5618 FirstArg = FirstArgResult.get();
5619 TheCall->setArg(Arg: 0, ArgExpr: FirstArg);
5620
5621 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5622 if (!pointerType) {
5623 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer)
5624 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5625 return ExprError();
5626 }
5627
5628 QualType ValType = pointerType->getPointeeType();
5629 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5630 !ValType->isBlockPointerType()) {
5631 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_must_be_pointer_intptr)
5632 << FirstArg->getType() << 0 << FirstArg->getSourceRange();
5633 return ExprError();
5634 }
5635 PointerAuthQualifier PointerAuth = ValType.getPointerAuth();
5636 if (PointerAuth && PointerAuth.isAddressDiscriminated()) {
5637 Diag(Loc: FirstArg->getBeginLoc(),
5638 DiagID: diag::err_atomic_op_needs_non_address_discriminated_pointer)
5639 << 1 << ValType << FirstArg->getSourceRange();
5640 return ExprError();
5641 }
5642
5643 if (ValType.isConstQualified()) {
5644 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_cannot_be_const)
5645 << FirstArg->getType() << FirstArg->getSourceRange();
5646 return ExprError();
5647 }
5648
5649 switch (ValType.getObjCLifetime()) {
5650 case Qualifiers::OCL_None:
5651 case Qualifiers::OCL_ExplicitNone:
5652 // okay
5653 break;
5654
5655 case Qualifiers::OCL_Weak:
5656 case Qualifiers::OCL_Strong:
5657 case Qualifiers::OCL_Autoreleasing:
5658 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_arc_atomic_ownership)
5659 << ValType << FirstArg->getSourceRange();
5660 return ExprError();
5661 }
5662
5663 // Strip any qualifiers off ValType.
5664 ValType = ValType.getUnqualifiedType();
5665
5666 // The majority of builtins return a value, but a few have special return
5667 // types, so allow them to override appropriately below.
5668 QualType ResultType = ValType;
5669
5670 // We need to figure out which concrete builtin this maps onto. For example,
5671 // __sync_fetch_and_add with a 2 byte object turns into
5672 // __sync_fetch_and_add_2.
5673#define BUILTIN_ROW(x) \
5674 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5675 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5676
5677 static const unsigned BuiltinIndices[][5] = {
5678 BUILTIN_ROW(__sync_fetch_and_add),
5679 BUILTIN_ROW(__sync_fetch_and_sub),
5680 BUILTIN_ROW(__sync_fetch_and_or),
5681 BUILTIN_ROW(__sync_fetch_and_and),
5682 BUILTIN_ROW(__sync_fetch_and_xor),
5683 BUILTIN_ROW(__sync_fetch_and_nand),
5684
5685 BUILTIN_ROW(__sync_add_and_fetch),
5686 BUILTIN_ROW(__sync_sub_and_fetch),
5687 BUILTIN_ROW(__sync_and_and_fetch),
5688 BUILTIN_ROW(__sync_or_and_fetch),
5689 BUILTIN_ROW(__sync_xor_and_fetch),
5690 BUILTIN_ROW(__sync_nand_and_fetch),
5691
5692 BUILTIN_ROW(__sync_val_compare_and_swap),
5693 BUILTIN_ROW(__sync_bool_compare_and_swap),
5694 BUILTIN_ROW(__sync_lock_test_and_set),
5695 BUILTIN_ROW(__sync_lock_release),
5696 BUILTIN_ROW(__sync_swap)
5697 };
5698#undef BUILTIN_ROW
5699
5700 // Determine the index of the size.
5701 unsigned SizeIndex;
5702 switch (Context.getTypeSizeInChars(T: ValType).getQuantity()) {
5703 case 1: SizeIndex = 0; break;
5704 case 2: SizeIndex = 1; break;
5705 case 4: SizeIndex = 2; break;
5706 case 8: SizeIndex = 3; break;
5707 case 16: SizeIndex = 4; break;
5708 default:
5709 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_atomic_builtin_pointer_size)
5710 << FirstArg->getType() << FirstArg->getSourceRange();
5711 return ExprError();
5712 }
5713
5714 // Each of these builtins has one pointer argument, followed by some number of
5715 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5716 // that we ignore. Find out which row of BuiltinIndices to read from as well
5717 // as the number of fixed args.
5718 unsigned BuiltinID = FDecl->getBuiltinID();
5719 unsigned BuiltinIndex, NumFixed = 1;
5720 bool WarnAboutSemanticsChange = false;
5721 switch (BuiltinID) {
5722 default: llvm_unreachable("Unknown overloaded atomic builtin!");
5723 case Builtin::BI__sync_fetch_and_add:
5724 case Builtin::BI__sync_fetch_and_add_1:
5725 case Builtin::BI__sync_fetch_and_add_2:
5726 case Builtin::BI__sync_fetch_and_add_4:
5727 case Builtin::BI__sync_fetch_and_add_8:
5728 case Builtin::BI__sync_fetch_and_add_16:
5729 BuiltinIndex = 0;
5730 break;
5731
5732 case Builtin::BI__sync_fetch_and_sub:
5733 case Builtin::BI__sync_fetch_and_sub_1:
5734 case Builtin::BI__sync_fetch_and_sub_2:
5735 case Builtin::BI__sync_fetch_and_sub_4:
5736 case Builtin::BI__sync_fetch_and_sub_8:
5737 case Builtin::BI__sync_fetch_and_sub_16:
5738 BuiltinIndex = 1;
5739 break;
5740
5741 case Builtin::BI__sync_fetch_and_or:
5742 case Builtin::BI__sync_fetch_and_or_1:
5743 case Builtin::BI__sync_fetch_and_or_2:
5744 case Builtin::BI__sync_fetch_and_or_4:
5745 case Builtin::BI__sync_fetch_and_or_8:
5746 case Builtin::BI__sync_fetch_and_or_16:
5747 BuiltinIndex = 2;
5748 break;
5749
5750 case Builtin::BI__sync_fetch_and_and:
5751 case Builtin::BI__sync_fetch_and_and_1:
5752 case Builtin::BI__sync_fetch_and_and_2:
5753 case Builtin::BI__sync_fetch_and_and_4:
5754 case Builtin::BI__sync_fetch_and_and_8:
5755 case Builtin::BI__sync_fetch_and_and_16:
5756 BuiltinIndex = 3;
5757 break;
5758
5759 case Builtin::BI__sync_fetch_and_xor:
5760 case Builtin::BI__sync_fetch_and_xor_1:
5761 case Builtin::BI__sync_fetch_and_xor_2:
5762 case Builtin::BI__sync_fetch_and_xor_4:
5763 case Builtin::BI__sync_fetch_and_xor_8:
5764 case Builtin::BI__sync_fetch_and_xor_16:
5765 BuiltinIndex = 4;
5766 break;
5767
5768 case Builtin::BI__sync_fetch_and_nand:
5769 case Builtin::BI__sync_fetch_and_nand_1:
5770 case Builtin::BI__sync_fetch_and_nand_2:
5771 case Builtin::BI__sync_fetch_and_nand_4:
5772 case Builtin::BI__sync_fetch_and_nand_8:
5773 case Builtin::BI__sync_fetch_and_nand_16:
5774 BuiltinIndex = 5;
5775 WarnAboutSemanticsChange = true;
5776 break;
5777
5778 case Builtin::BI__sync_add_and_fetch:
5779 case Builtin::BI__sync_add_and_fetch_1:
5780 case Builtin::BI__sync_add_and_fetch_2:
5781 case Builtin::BI__sync_add_and_fetch_4:
5782 case Builtin::BI__sync_add_and_fetch_8:
5783 case Builtin::BI__sync_add_and_fetch_16:
5784 BuiltinIndex = 6;
5785 break;
5786
5787 case Builtin::BI__sync_sub_and_fetch:
5788 case Builtin::BI__sync_sub_and_fetch_1:
5789 case Builtin::BI__sync_sub_and_fetch_2:
5790 case Builtin::BI__sync_sub_and_fetch_4:
5791 case Builtin::BI__sync_sub_and_fetch_8:
5792 case Builtin::BI__sync_sub_and_fetch_16:
5793 BuiltinIndex = 7;
5794 break;
5795
5796 case Builtin::BI__sync_and_and_fetch:
5797 case Builtin::BI__sync_and_and_fetch_1:
5798 case Builtin::BI__sync_and_and_fetch_2:
5799 case Builtin::BI__sync_and_and_fetch_4:
5800 case Builtin::BI__sync_and_and_fetch_8:
5801 case Builtin::BI__sync_and_and_fetch_16:
5802 BuiltinIndex = 8;
5803 break;
5804
5805 case Builtin::BI__sync_or_and_fetch:
5806 case Builtin::BI__sync_or_and_fetch_1:
5807 case Builtin::BI__sync_or_and_fetch_2:
5808 case Builtin::BI__sync_or_and_fetch_4:
5809 case Builtin::BI__sync_or_and_fetch_8:
5810 case Builtin::BI__sync_or_and_fetch_16:
5811 BuiltinIndex = 9;
5812 break;
5813
5814 case Builtin::BI__sync_xor_and_fetch:
5815 case Builtin::BI__sync_xor_and_fetch_1:
5816 case Builtin::BI__sync_xor_and_fetch_2:
5817 case Builtin::BI__sync_xor_and_fetch_4:
5818 case Builtin::BI__sync_xor_and_fetch_8:
5819 case Builtin::BI__sync_xor_and_fetch_16:
5820 BuiltinIndex = 10;
5821 break;
5822
5823 case Builtin::BI__sync_nand_and_fetch:
5824 case Builtin::BI__sync_nand_and_fetch_1:
5825 case Builtin::BI__sync_nand_and_fetch_2:
5826 case Builtin::BI__sync_nand_and_fetch_4:
5827 case Builtin::BI__sync_nand_and_fetch_8:
5828 case Builtin::BI__sync_nand_and_fetch_16:
5829 BuiltinIndex = 11;
5830 WarnAboutSemanticsChange = true;
5831 break;
5832
5833 case Builtin::BI__sync_val_compare_and_swap:
5834 case Builtin::BI__sync_val_compare_and_swap_1:
5835 case Builtin::BI__sync_val_compare_and_swap_2:
5836 case Builtin::BI__sync_val_compare_and_swap_4:
5837 case Builtin::BI__sync_val_compare_and_swap_8:
5838 case Builtin::BI__sync_val_compare_and_swap_16:
5839 BuiltinIndex = 12;
5840 NumFixed = 2;
5841 break;
5842
5843 case Builtin::BI__sync_bool_compare_and_swap:
5844 case Builtin::BI__sync_bool_compare_and_swap_1:
5845 case Builtin::BI__sync_bool_compare_and_swap_2:
5846 case Builtin::BI__sync_bool_compare_and_swap_4:
5847 case Builtin::BI__sync_bool_compare_and_swap_8:
5848 case Builtin::BI__sync_bool_compare_and_swap_16:
5849 BuiltinIndex = 13;
5850 NumFixed = 2;
5851 ResultType = Context.BoolTy;
5852 break;
5853
5854 case Builtin::BI__sync_lock_test_and_set:
5855 case Builtin::BI__sync_lock_test_and_set_1:
5856 case Builtin::BI__sync_lock_test_and_set_2:
5857 case Builtin::BI__sync_lock_test_and_set_4:
5858 case Builtin::BI__sync_lock_test_and_set_8:
5859 case Builtin::BI__sync_lock_test_and_set_16:
5860 BuiltinIndex = 14;
5861 break;
5862
5863 case Builtin::BI__sync_lock_release:
5864 case Builtin::BI__sync_lock_release_1:
5865 case Builtin::BI__sync_lock_release_2:
5866 case Builtin::BI__sync_lock_release_4:
5867 case Builtin::BI__sync_lock_release_8:
5868 case Builtin::BI__sync_lock_release_16:
5869 BuiltinIndex = 15;
5870 NumFixed = 0;
5871 ResultType = Context.VoidTy;
5872 break;
5873
5874 case Builtin::BI__sync_swap:
5875 case Builtin::BI__sync_swap_1:
5876 case Builtin::BI__sync_swap_2:
5877 case Builtin::BI__sync_swap_4:
5878 case Builtin::BI__sync_swap_8:
5879 case Builtin::BI__sync_swap_16:
5880 BuiltinIndex = 16;
5881 break;
5882 }
5883
5884 // Now that we know how many fixed arguments we expect, first check that we
5885 // have at least that many.
5886 if (TheCall->getNumArgs() < 1+NumFixed) {
5887 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args_at_least)
5888 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0
5889 << Callee->getSourceRange();
5890 return ExprError();
5891 }
5892
5893 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_atomic_implicit_seq_cst)
5894 << Callee->getSourceRange();
5895
5896 if (WarnAboutSemanticsChange) {
5897 Diag(Loc: TheCall->getEndLoc(), DiagID: diag::warn_sync_fetch_and_nand_semantics_change)
5898 << Callee->getSourceRange();
5899 }
5900
5901 // Get the decl for the concrete builtin from this, we can tell what the
5902 // concrete integer type we should convert to is.
5903 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5904 std::string NewBuiltinName = Context.BuiltinInfo.getName(ID: NewBuiltinID);
5905 FunctionDecl *NewBuiltinDecl;
5906 if (NewBuiltinID == BuiltinID)
5907 NewBuiltinDecl = FDecl;
5908 else {
5909 // Perform builtin lookup to avoid redeclaring it.
5910 DeclarationName DN(&Context.Idents.get(Name: NewBuiltinName));
5911 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5912 LookupName(R&: Res, S: TUScope, /*AllowBuiltinCreation=*/true);
5913 assert(Res.getFoundDecl());
5914 NewBuiltinDecl = dyn_cast<FunctionDecl>(Val: Res.getFoundDecl());
5915 if (!NewBuiltinDecl)
5916 return ExprError();
5917 }
5918
5919 // The first argument --- the pointer --- has a fixed type; we
5920 // deduce the types of the rest of the arguments accordingly. Walk
5921 // the remaining arguments, converting them to the deduced value type.
5922 for (unsigned i = 0; i != NumFixed; ++i) {
5923 ExprResult Arg = TheCall->getArg(Arg: i+1);
5924
5925 // GCC does an implicit conversion to the pointer or integer ValType. This
5926 // can fail in some cases (1i -> int**), check for this error case now.
5927 // Initialize the argument.
5928 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5929 Type: ValType, /*consume*/ Consumed: false);
5930 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
5931 if (Arg.isInvalid())
5932 return ExprError();
5933
5934 // Okay, we have something that *can* be converted to the right type. Check
5935 // to see if there is a potentially weird extension going on here. This can
5936 // happen when you do an atomic operation on something like an char* and
5937 // pass in 42. The 42 gets converted to char. This is even more strange
5938 // for things like 45.123 -> char, etc.
5939 // FIXME: Do this check.
5940 TheCall->setArg(Arg: i+1, ArgExpr: Arg.get());
5941 }
5942
5943 // Create a new DeclRefExpr to refer to the new decl.
5944 DeclRefExpr *NewDRE = DeclRefExpr::Create(
5945 Context, QualifierLoc: DRE->getQualifierLoc(), TemplateKWLoc: SourceLocation(), D: NewBuiltinDecl,
5946 /*enclosing*/ RefersToEnclosingVariableOrCapture: false, NameLoc: DRE->getLocation(), T: Context.BuiltinFnTy,
5947 VK: DRE->getValueKind(), FoundD: nullptr, TemplateArgs: nullptr, NOUR: DRE->isNonOdrUse());
5948
5949 // Set the callee in the CallExpr.
5950 // FIXME: This loses syntactic information.
5951 QualType CalleePtrTy = Context.getPointerType(T: NewBuiltinDecl->getType());
5952 ExprResult PromotedCall = ImpCastExprToType(E: NewDRE, Type: CalleePtrTy,
5953 CK: CK_BuiltinFnToFnPtr);
5954 TheCall->setCallee(PromotedCall.get());
5955
5956 // Change the result type of the call to match the original value type. This
5957 // is arbitrary, but the codegen for these builtins ins design to handle it
5958 // gracefully.
5959 TheCall->setType(ResultType);
5960
5961 // Prohibit problematic uses of bit-precise integer types with atomic
5962 // builtins. The arguments would have already been converted to the first
5963 // argument's type, so only need to check the first argument.
5964 const auto *BitIntValType = ValType->getAs<BitIntType>();
5965 if (BitIntValType && !llvm::isPowerOf2_64(Value: BitIntValType->getNumBits())) {
5966 Diag(Loc: FirstArg->getExprLoc(), DiagID: diag::err_atomic_builtin_ext_int_size);
5967 return ExprError();
5968 }
5969
5970 return TheCallResult;
5971}
5972
5973ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5974 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5975 DeclRefExpr *DRE =
5976 cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
5977 FunctionDecl *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
5978 unsigned BuiltinID = FDecl->getBuiltinID();
5979 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5980 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5981 "Unexpected nontemporal load/store builtin!");
5982 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5983 unsigned numArgs = isStore ? 2 : 1;
5984
5985 // Ensure that we have the proper number of arguments.
5986 if (checkArgCount(Call: TheCall, DesiredArgCount: numArgs))
5987 return ExprError();
5988
5989 // Inspect the last argument of the nontemporal builtin. This should always
5990 // be a pointer type, from which we imply the type of the memory access.
5991 // Because it is a pointer type, we don't have to worry about any implicit
5992 // casts here.
5993 Expr *PointerArg = TheCall->getArg(Arg: numArgs - 1);
5994 ExprResult PointerArgResult =
5995 DefaultFunctionArrayLvalueConversion(E: PointerArg);
5996
5997 if (PointerArgResult.isInvalid())
5998 return ExprError();
5999 PointerArg = PointerArgResult.get();
6000 TheCall->setArg(Arg: numArgs - 1, ArgExpr: PointerArg);
6001
6002 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6003 if (!pointerType) {
6004 Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_nontemporal_builtin_must_be_pointer)
6005 << PointerArg->getType() << PointerArg->getSourceRange();
6006 return ExprError();
6007 }
6008
6009 QualType ValType = pointerType->getPointeeType();
6010
6011 // Strip any qualifiers off ValType.
6012 ValType = ValType.getUnqualifiedType();
6013 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6014 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6015 !ValType->isVectorType()) {
6016 Diag(Loc: DRE->getBeginLoc(),
6017 DiagID: diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6018 << PointerArg->getType() << PointerArg->getSourceRange();
6019 return ExprError();
6020 }
6021
6022 if (!isStore) {
6023 TheCall->setType(ValType);
6024 return TheCallResult;
6025 }
6026
6027 ExprResult ValArg = TheCall->getArg(Arg: 0);
6028 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6029 Context, Type: ValType, /*consume*/ Consumed: false);
6030 ValArg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: ValArg);
6031 if (ValArg.isInvalid())
6032 return ExprError();
6033
6034 TheCall->setArg(Arg: 0, ArgExpr: ValArg.get());
6035 TheCall->setType(Context.VoidTy);
6036 return TheCallResult;
6037}
6038
6039/// CheckObjCString - Checks that the format string argument to the os_log()
6040/// and os_trace() functions is correct, and converts it to const char *.
6041ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6042 Arg = Arg->IgnoreParenCasts();
6043 auto *Literal = dyn_cast<StringLiteral>(Val: Arg);
6044 if (!Literal) {
6045 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Val: Arg)) {
6046 Literal = ObjcLiteral->getString();
6047 }
6048 }
6049
6050 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) {
6051 return ExprError(
6052 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_os_log_format_not_string_constant)
6053 << Arg->getSourceRange());
6054 }
6055
6056 ExprResult Result(Literal);
6057 QualType ResultTy = Context.getPointerType(T: Context.CharTy.withConst());
6058 InitializedEntity Entity =
6059 InitializedEntity::InitializeParameter(Context, Type: ResultTy, Consumed: false);
6060 Result = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Result);
6061 return Result;
6062}
6063
6064/// Check that the user is calling the appropriate va_start builtin for the
6065/// target and calling convention.
6066static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6067 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6068 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6069 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6070 TT.getArch() == llvm::Triple::aarch64_32);
6071 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
6072 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6073 if (IsX64 || IsAArch64) {
6074 CallingConv CC = CC_C;
6075 if (const FunctionDecl *FD = S.getCurFunctionDecl())
6076 CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6077 if (IsMSVAStart) {
6078 // Don't allow this in System V ABI functions.
6079 if (CC == CC_X86_64SysV || (!IsWindowsOrUEFI && CC != CC_Win64))
6080 return S.Diag(Loc: Fn->getBeginLoc(),
6081 DiagID: diag::err_ms_va_start_used_in_sysv_function);
6082 } else {
6083 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6084 // On x64 Windows, don't allow this in System V ABI functions.
6085 // (Yes, that means there's no corresponding way to support variadic
6086 // System V ABI functions on Windows.)
6087 if ((IsWindowsOrUEFI && CC == CC_X86_64SysV) ||
6088 (!IsWindowsOrUEFI && CC == CC_Win64))
6089 return S.Diag(Loc: Fn->getBeginLoc(),
6090 DiagID: diag::err_va_start_used_in_wrong_abi_function)
6091 << !IsWindowsOrUEFI;
6092 }
6093 return false;
6094 }
6095
6096 if (IsMSVAStart)
6097 return S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_builtin_x64_aarch64_only);
6098 return false;
6099}
6100
6101static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6102 ParmVarDecl **LastParam = nullptr) {
6103 // Determine whether the current function, block, or obj-c method is variadic
6104 // and get its parameter list.
6105 bool IsVariadic = false;
6106 ArrayRef<ParmVarDecl *> Params;
6107 DeclContext *Caller = S.CurContext;
6108 if (auto *Block = dyn_cast<BlockDecl>(Val: Caller)) {
6109 IsVariadic = Block->isVariadic();
6110 Params = Block->parameters();
6111 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: Caller)) {
6112 IsVariadic = FD->isVariadic();
6113 Params = FD->parameters();
6114 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Val: Caller)) {
6115 IsVariadic = MD->isVariadic();
6116 // FIXME: This isn't correct for methods (results in bogus warning).
6117 Params = MD->parameters();
6118 } else if (isa<CapturedDecl>(Val: Caller)) {
6119 // We don't support va_start in a CapturedDecl.
6120 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_captured_stmt);
6121 return true;
6122 } else {
6123 // This must be some other declcontext that parses exprs.
6124 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_outside_function);
6125 return true;
6126 }
6127
6128 if (!IsVariadic) {
6129 S.Diag(Loc: Fn->getBeginLoc(), DiagID: diag::err_va_start_fixed_function);
6130 return true;
6131 }
6132
6133 if (LastParam)
6134 *LastParam = Params.empty() ? nullptr : Params.back();
6135
6136 return false;
6137}
6138
6139bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6140 Expr *Fn = TheCall->getCallee();
6141 if (checkVAStartABI(S&: *this, BuiltinID, Fn))
6142 return true;
6143
6144 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6145 // This builtin requires one argument (the va_list), allows two arguments,
6146 // but diagnoses more than two arguments. e.g.,
6147 // __builtin_c23_va_start(); // error
6148 // __builtin_c23_va_start(list); // ok
6149 // __builtin_c23_va_start(list, param); // ok
6150 // __builtin_c23_va_start(list, anything, anything); // error
6151 // This differs from the GCC behavior in that they accept the last case
6152 // with a warning, but it doesn't seem like a useful behavior to allow.
6153 if (checkArgCountRange(Call: TheCall, MinArgCount: 1, MaxArgCount: 2))
6154 return true;
6155 } else {
6156 // In C23 mode, va_start only needs one argument. However, the builtin still
6157 // requires two arguments (which matches the behavior of the GCC builtin),
6158 // <stdarg.h> passes `0` as the second argument in C23 mode.
6159 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6160 return true;
6161 }
6162
6163 // Type-check the first argument normally.
6164 if (checkBuiltinArgument(S&: *this, E: TheCall, ArgIndex: 0))
6165 return true;
6166
6167 // Check that the current function is variadic, and get its last parameter.
6168 ParmVarDecl *LastParam;
6169 if (checkVAStartIsInVariadicFunction(S&: *this, Fn, LastParam: &LastParam))
6170 return true;
6171
6172 // Verify that the second argument to the builtin is the last non-variadic
6173 // argument of the current function or method. In C23 mode, if the call is
6174 // not to __builtin_c23_va_start, and the second argument is an integer
6175 // constant expression with value 0, then we don't bother with this check.
6176 // For __builtin_c23_va_start, we only perform the check for the second
6177 // argument being the last argument to the current function if there is a
6178 // second argument present.
6179 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6180 TheCall->getNumArgs() < 2) {
6181 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
6182 return false;
6183 }
6184
6185 const Expr *Arg = TheCall->getArg(Arg: 1)->IgnoreParenCasts();
6186 if (std::optional<llvm::APSInt> Val =
6187 TheCall->getArg(Arg: 1)->getIntegerConstantExpr(Ctx: Context);
6188 Val && LangOpts.C23 && *Val == 0 &&
6189 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6190 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::warn_c17_compat_va_start_one_arg);
6191 return false;
6192 }
6193
6194 // These are valid if SecondArgIsLastNonVariadicArgument is false after the
6195 // next block.
6196 QualType Type;
6197 SourceLocation ParamLoc;
6198 bool IsCRegister = false;
6199 bool SecondArgIsLastNonVariadicArgument = false;
6200 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Val: Arg)) {
6201 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: DR->getDecl())) {
6202 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6203
6204 Type = PV->getType();
6205 ParamLoc = PV->getLocation();
6206 IsCRegister =
6207 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6208 }
6209 }
6210
6211 if (!SecondArgIsLastNonVariadicArgument)
6212 Diag(Loc: TheCall->getArg(Arg: 1)->getBeginLoc(),
6213 DiagID: diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6214 else if (IsCRegister || Type->isReferenceType() ||
6215 Type->isSpecificBuiltinType(K: BuiltinType::Float) || [=] {
6216 // Promotable integers are UB, but enumerations need a bit of
6217 // extra checking to see what their promotable type actually is.
6218 if (!Context.isPromotableIntegerType(T: Type))
6219 return false;
6220 const auto *ED = Type->getAsEnumDecl();
6221 if (!ED)
6222 return true;
6223 return !Context.typesAreCompatible(T1: ED->getPromotionType(), T2: Type);
6224 }()) {
6225 unsigned Reason = 0;
6226 if (Type->isReferenceType()) Reason = 1;
6227 else if (IsCRegister) Reason = 2;
6228 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_va_start_type_is_undefined) << Reason;
6229 Diag(Loc: ParamLoc, DiagID: diag::note_parameter_type) << Type;
6230 }
6231
6232 return false;
6233}
6234
6235bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) {
6236 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6237 const LangOptions &LO = getLangOpts();
6238
6239 if (LO.CPlusPlus)
6240 return Arg->getType()
6241 .getCanonicalType()
6242 .getTypePtr()
6243 ->getPointeeType()
6244 .withoutLocalFastQualifiers() == Context.CharTy;
6245
6246 // In C, allow aliasing through `char *`, this is required for AArch64 at
6247 // least.
6248 return true;
6249 };
6250
6251 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6252 // const char *named_addr);
6253
6254 Expr *Func = Call->getCallee();
6255
6256 if (Call->getNumArgs() < 3)
6257 return Diag(Loc: Call->getEndLoc(),
6258 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6259 << 0 /*function call*/ << 3 << Call->getNumArgs()
6260 << /*is non object*/ 0;
6261
6262 // Type-check the first argument normally.
6263 if (checkBuiltinArgument(S&: *this, E: Call, ArgIndex: 0))
6264 return true;
6265
6266 // Check that the current function is variadic.
6267 if (checkVAStartIsInVariadicFunction(S&: *this, Fn: Func))
6268 return true;
6269
6270 // __va_start on Windows does not validate the parameter qualifiers
6271
6272 const Expr *Arg1 = Call->getArg(Arg: 1)->IgnoreParens();
6273 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6274
6275 const Expr *Arg2 = Call->getArg(Arg: 2)->IgnoreParens();
6276 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6277
6278 const QualType &ConstCharPtrTy =
6279 Context.getPointerType(T: Context.CharTy.withConst());
6280 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6281 Diag(Loc: Arg1->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
6282 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6283 << 0 /* qualifier difference */
6284 << 3 /* parameter mismatch */
6285 << 2 << Arg1->getType() << ConstCharPtrTy;
6286
6287 const QualType SizeTy = Context.getSizeType();
6288 if (!Context.hasSameType(
6289 T1: Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers(),
6290 T2: SizeTy))
6291 Diag(Loc: Arg2->getBeginLoc(), DiagID: diag::err_typecheck_convert_incompatible)
6292 << Arg2->getType() << SizeTy << 1 /* different class */
6293 << 0 /* qualifier difference */
6294 << 3 /* parameter mismatch */
6295 << 3 << Arg2->getType() << SizeTy;
6296
6297 return false;
6298}
6299
6300bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) {
6301 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6302 return true;
6303
6304 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6305 TheCall->getFPFeaturesInEffect(LO: getLangOpts()).getNoHonorNaNs())
6306 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6307 << 1 << 0 << TheCall->getSourceRange();
6308
6309 ExprResult OrigArg0 = TheCall->getArg(Arg: 0);
6310 ExprResult OrigArg1 = TheCall->getArg(Arg: 1);
6311
6312 // Do standard promotions between the two arguments, returning their common
6313 // type.
6314 QualType Res = UsualArithmeticConversions(
6315 LHS&: OrigArg0, RHS&: OrigArg1, Loc: TheCall->getExprLoc(), ACK: ArithConvKind::Comparison);
6316 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6317 return true;
6318
6319 // Make sure any conversions are pushed back into the call; this is
6320 // type safe since unordered compare builtins are declared as "_Bool
6321 // foo(...)".
6322 TheCall->setArg(Arg: 0, ArgExpr: OrigArg0.get());
6323 TheCall->setArg(Arg: 1, ArgExpr: OrigArg1.get());
6324
6325 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6326 return false;
6327
6328 // If the common type isn't a real floating type, then the arguments were
6329 // invalid for this operation.
6330 if (Res.isNull() || !Res->isRealFloatingType())
6331 return Diag(Loc: OrigArg0.get()->getBeginLoc(),
6332 DiagID: diag::err_typecheck_call_invalid_ordered_compare)
6333 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6334 << SourceRange(OrigArg0.get()->getBeginLoc(),
6335 OrigArg1.get()->getEndLoc());
6336
6337 return false;
6338}
6339
6340bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs,
6341 unsigned BuiltinID) {
6342 if (checkArgCount(Call: TheCall, DesiredArgCount: NumArgs))
6343 return true;
6344
6345 FPOptions FPO = TheCall->getFPFeaturesInEffect(LO: getLangOpts());
6346 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6347 BuiltinID == Builtin::BI__builtin_isinf ||
6348 BuiltinID == Builtin::BI__builtin_isinf_sign))
6349 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6350 << 0 << 0 << TheCall->getSourceRange();
6351
6352 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6353 BuiltinID == Builtin::BI__builtin_isunordered))
6354 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
6355 << 1 << 0 << TheCall->getSourceRange();
6356
6357 bool IsFPClass = NumArgs == 2;
6358
6359 // Find out position of floating-point argument.
6360 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6361
6362 // We can count on all parameters preceding the floating-point just being int.
6363 // Try all of those.
6364 for (unsigned i = 0; i < FPArgNo; ++i) {
6365 Expr *Arg = TheCall->getArg(Arg: i);
6366
6367 if (Arg->isTypeDependent())
6368 return false;
6369
6370 ExprResult Res = PerformImplicitConversion(From: Arg, ToType: Context.IntTy,
6371 Action: AssignmentAction::Passing);
6372
6373 if (Res.isInvalid())
6374 return true;
6375 TheCall->setArg(Arg: i, ArgExpr: Res.get());
6376 }
6377
6378 Expr *OrigArg = TheCall->getArg(Arg: FPArgNo);
6379
6380 if (OrigArg->isTypeDependent())
6381 return false;
6382
6383 // Usual Unary Conversions will convert half to float, which we want for
6384 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6385 // type how it is, but do normal L->Rvalue conversions.
6386 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) {
6387 ExprResult Res = UsualUnaryConversions(E: OrigArg);
6388
6389 if (!Res.isUsable())
6390 return true;
6391 OrigArg = Res.get();
6392 } else {
6393 ExprResult Res = DefaultFunctionArrayLvalueConversion(E: OrigArg);
6394
6395 if (!Res.isUsable())
6396 return true;
6397 OrigArg = Res.get();
6398 }
6399 TheCall->setArg(Arg: FPArgNo, ArgExpr: OrigArg);
6400
6401 QualType VectorResultTy;
6402 QualType ElementTy = OrigArg->getType();
6403 // TODO: When all classification function are implemented with is_fpclass,
6404 // vector argument can be supported in all of them.
6405 if (ElementTy->isVectorType() && IsFPClass) {
6406 VectorResultTy = GetSignedVectorType(V: ElementTy);
6407 ElementTy = ElementTy->castAs<VectorType>()->getElementType();
6408 }
6409
6410 // This operation requires a non-_Complex floating-point number.
6411 if (!ElementTy->isRealFloatingType())
6412 return Diag(Loc: OrigArg->getBeginLoc(),
6413 DiagID: diag::err_typecheck_call_invalid_unary_fp)
6414 << OrigArg->getType() << OrigArg->getSourceRange();
6415
6416 // __builtin_isfpclass has integer parameter that specify test mask. It is
6417 // passed in (...), so it should be analyzed completely here.
6418 if (IsFPClass)
6419 if (BuiltinConstantArgRange(TheCall, ArgNum: 1, Low: 0, High: llvm::fcAllFlags))
6420 return true;
6421
6422 // TODO: enable this code to all classification functions.
6423 if (IsFPClass) {
6424 QualType ResultTy;
6425 if (!VectorResultTy.isNull())
6426 ResultTy = VectorResultTy;
6427 else
6428 ResultTy = Context.IntTy;
6429 TheCall->setType(ResultTy);
6430 }
6431
6432 return false;
6433}
6434
6435bool Sema::BuiltinComplex(CallExpr *TheCall) {
6436 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
6437 return true;
6438
6439 bool Dependent = false;
6440 for (unsigned I = 0; I != 2; ++I) {
6441 Expr *Arg = TheCall->getArg(Arg: I);
6442 QualType T = Arg->getType();
6443 if (T->isDependentType()) {
6444 Dependent = true;
6445 continue;
6446 }
6447
6448 // Despite supporting _Complex int, GCC requires a real floating point type
6449 // for the operands of __builtin_complex.
6450 if (!T->isRealFloatingType()) {
6451 return Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_typecheck_call_requires_real_fp)
6452 << Arg->getType() << Arg->getSourceRange();
6453 }
6454
6455 ExprResult Converted = DefaultLvalueConversion(E: Arg);
6456 if (Converted.isInvalid())
6457 return true;
6458 TheCall->setArg(Arg: I, ArgExpr: Converted.get());
6459 }
6460
6461 if (Dependent) {
6462 TheCall->setType(Context.DependentTy);
6463 return false;
6464 }
6465
6466 Expr *Real = TheCall->getArg(Arg: 0);
6467 Expr *Imag = TheCall->getArg(Arg: 1);
6468 if (!Context.hasSameType(T1: Real->getType(), T2: Imag->getType())) {
6469 return Diag(Loc: Real->getBeginLoc(),
6470 DiagID: diag::err_typecheck_call_different_arg_types)
6471 << Real->getType() << Imag->getType()
6472 << Real->getSourceRange() << Imag->getSourceRange();
6473 }
6474
6475 TheCall->setType(Context.getComplexType(T: Real->getType()));
6476 return false;
6477}
6478
6479/// BuiltinShuffleVector - Handle __builtin_shufflevector.
6480// This is declared to take (...), so we have to check everything.
6481ExprResult Sema::BuiltinShuffleVector(CallExpr *TheCall) {
6482 unsigned NumArgs = TheCall->getNumArgs();
6483 if (NumArgs < 2)
6484 return ExprError(Diag(Loc: TheCall->getEndLoc(),
6485 DiagID: diag::err_typecheck_call_too_few_args_at_least)
6486 << 0 /*function call*/ << 2 << NumArgs
6487 << /*is non object*/ 0 << TheCall->getSourceRange());
6488
6489 // Determine which of the following types of shufflevector we're checking:
6490 // 1) unary, vector mask: (lhs, mask)
6491 // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6492 QualType ResType = TheCall->getArg(Arg: 0)->getType();
6493 unsigned NumElements = 0;
6494
6495 if (!TheCall->getArg(Arg: 0)->isTypeDependent() &&
6496 !TheCall->getArg(Arg: 1)->isTypeDependent()) {
6497 QualType LHSType = TheCall->getArg(Arg: 0)->getType();
6498 QualType RHSType = TheCall->getArg(Arg: 1)->getType();
6499
6500 if (!LHSType->isVectorType() || !RHSType->isVectorType())
6501 return ExprError(
6502 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_vec_builtin_non_vector)
6503 << TheCall->getDirectCallee() << /*isMoreThanTwoArgs*/ false
6504 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6505 TheCall->getArg(Arg: 1)->getEndLoc()));
6506
6507 NumElements = LHSType->castAs<VectorType>()->getNumElements();
6508 unsigned NumResElements = NumArgs - 2;
6509
6510 // Check to see if we have a call with 2 vector arguments, the unary shuffle
6511 // with mask. If so, verify that RHS is an integer vector type with the
6512 // same number of elts as lhs.
6513 if (NumArgs == 2) {
6514 if (!RHSType->hasIntegerRepresentation() ||
6515 RHSType->castAs<VectorType>()->getNumElements() != NumElements)
6516 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6517 DiagID: diag::err_vec_builtin_incompatible_vector)
6518 << TheCall->getDirectCallee()
6519 << /*isMoreThanTwoArgs*/ false
6520 << SourceRange(TheCall->getArg(Arg: 1)->getBeginLoc(),
6521 TheCall->getArg(Arg: 1)->getEndLoc()));
6522 } else if (!Context.hasSameUnqualifiedType(T1: LHSType, T2: RHSType)) {
6523 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6524 DiagID: diag::err_vec_builtin_incompatible_vector)
6525 << TheCall->getDirectCallee()
6526 << /*isMoreThanTwoArgs*/ false
6527 << SourceRange(TheCall->getArg(Arg: 0)->getBeginLoc(),
6528 TheCall->getArg(Arg: 1)->getEndLoc()));
6529 } else if (NumElements != NumResElements) {
6530 QualType EltType = LHSType->castAs<VectorType>()->getElementType();
6531 ResType = ResType->isExtVectorType()
6532 ? Context.getExtVectorType(VectorType: EltType, NumElts: NumResElements)
6533 : Context.getVectorType(VectorType: EltType, NumElts: NumResElements,
6534 VecKind: VectorKind::Generic);
6535 }
6536 }
6537
6538 for (unsigned I = 2; I != NumArgs; ++I) {
6539 Expr *Arg = TheCall->getArg(Arg: I);
6540 if (Arg->isTypeDependent() || Arg->isValueDependent())
6541 continue;
6542
6543 std::optional<llvm::APSInt> Result = Arg->getIntegerConstantExpr(Ctx: Context);
6544 if (!Result)
6545 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6546 DiagID: diag::err_shufflevector_nonconstant_argument)
6547 << Arg->getSourceRange());
6548
6549 // Allow -1 which will be translated to undef in the IR.
6550 if (Result->isSigned() && Result->isAllOnes())
6551 ;
6552 else if (Result->getActiveBits() > 64 ||
6553 Result->getZExtValue() >= NumElements * 2)
6554 return ExprError(Diag(Loc: TheCall->getBeginLoc(),
6555 DiagID: diag::err_shufflevector_argument_too_large)
6556 << Arg->getSourceRange());
6557
6558 TheCall->setArg(Arg: I, ArgExpr: ConstantExpr::Create(Context, E: Arg, Result: APValue(*Result)));
6559 }
6560
6561 auto *Result = new (Context) ShuffleVectorExpr(
6562 Context, ArrayRef(TheCall->getArgs(), NumArgs), ResType,
6563 TheCall->getCallee()->getBeginLoc(), TheCall->getRParenLoc());
6564
6565 // All moved to Result.
6566 TheCall->shrinkNumArgs(NewNumArgs: 0);
6567 return Result;
6568}
6569
6570ExprResult Sema::ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6571 SourceLocation BuiltinLoc,
6572 SourceLocation RParenLoc) {
6573 ExprValueKind VK = VK_PRValue;
6574 ExprObjectKind OK = OK_Ordinary;
6575 QualType DstTy = TInfo->getType();
6576 QualType SrcTy = E->getType();
6577
6578 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6579 return ExprError(Diag(Loc: BuiltinLoc,
6580 DiagID: diag::err_convertvector_non_vector)
6581 << E->getSourceRange());
6582 if (!DstTy->isVectorType() && !DstTy->isDependentType())
6583 return ExprError(Diag(Loc: BuiltinLoc, DiagID: diag::err_builtin_non_vector_type)
6584 << "second"
6585 << "__builtin_convertvector");
6586
6587 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6588 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6589 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6590 if (SrcElts != DstElts)
6591 return ExprError(Diag(Loc: BuiltinLoc,
6592 DiagID: diag::err_convertvector_incompatible_vector)
6593 << E->getSourceRange());
6594 }
6595
6596 return ConvertVectorExpr::Create(C: Context, SrcExpr: E, TI: TInfo, DstType: DstTy, VK, OK, BuiltinLoc,
6597 RParenLoc, FPFeatures: CurFPFeatureOverrides());
6598}
6599
6600bool Sema::BuiltinPrefetch(CallExpr *TheCall) {
6601 unsigned NumArgs = TheCall->getNumArgs();
6602
6603 if (NumArgs > 3)
6604 return Diag(Loc: TheCall->getEndLoc(),
6605 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6606 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0
6607 << TheCall->getSourceRange();
6608
6609 // Argument 0 is checked for us and the remaining arguments must be
6610 // constant integers.
6611 for (unsigned i = 1; i != NumArgs; ++i)
6612 if (BuiltinConstantArgRange(TheCall, ArgNum: i, Low: 0, High: i == 1 ? 1 : 3))
6613 return true;
6614
6615 return false;
6616}
6617
6618bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) {
6619 if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6620 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_target_unsupported)
6621 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6622 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
6623 return true;
6624 Expr *Arg = TheCall->getArg(Arg: 0);
6625 if (Arg->isInstantiationDependent())
6626 return false;
6627
6628 QualType ArgTy = Arg->getType();
6629 if (!ArgTy->hasFloatingRepresentation())
6630 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_expect_flt_or_vector)
6631 << ArgTy;
6632 if (Arg->isLValue()) {
6633 ExprResult FirstArg = DefaultLvalueConversion(E: Arg);
6634 TheCall->setArg(Arg: 0, ArgExpr: FirstArg.get());
6635 }
6636 TheCall->setType(TheCall->getArg(Arg: 0)->getType());
6637 return false;
6638}
6639
6640bool Sema::BuiltinAssume(CallExpr *TheCall) {
6641 Expr *Arg = TheCall->getArg(Arg: 0);
6642 if (Arg->isInstantiationDependent()) return false;
6643
6644 if (Arg->HasSideEffects(Ctx: Context))
6645 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_assume_side_effects)
6646 << Arg->getSourceRange()
6647 << cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getIdentifier();
6648
6649 return false;
6650}
6651
6652bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) {
6653 // The alignment must be a constant integer.
6654 Expr *Arg = TheCall->getArg(Arg: 1);
6655
6656 // We can't check the value of a dependent argument.
6657 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6658 if (const auto *UE =
6659 dyn_cast<UnaryExprOrTypeTraitExpr>(Val: Arg->IgnoreParenImpCasts()))
6660 if (UE->getKind() == UETT_AlignOf ||
6661 UE->getKind() == UETT_PreferredAlignOf)
6662 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_alloca_align_alignof)
6663 << Arg->getSourceRange();
6664
6665 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Ctx: Context);
6666
6667 if (!Result.isPowerOf2())
6668 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6669 << Arg->getSourceRange();
6670
6671 if (Result < Context.getCharWidth())
6672 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_small)
6673 << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6674
6675 if (Result > std::numeric_limits<int32_t>::max())
6676 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_too_big)
6677 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6678 }
6679
6680 return false;
6681}
6682
6683bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) {
6684 if (checkArgCountRange(Call: TheCall, MinArgCount: 2, MaxArgCount: 3))
6685 return true;
6686
6687 unsigned NumArgs = TheCall->getNumArgs();
6688 Expr *FirstArg = TheCall->getArg(Arg: 0);
6689
6690 {
6691 ExprResult FirstArgResult =
6692 DefaultFunctionArrayLvalueConversion(E: FirstArg);
6693 if (!FirstArgResult.get()->getType()->isPointerType()) {
6694 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_assume_aligned_invalid_arg)
6695 << TheCall->getSourceRange();
6696 return true;
6697 }
6698 TheCall->setArg(Arg: 0, ArgExpr: FirstArgResult.get());
6699 }
6700
6701 // The alignment must be a constant integer.
6702 Expr *SecondArg = TheCall->getArg(Arg: 1);
6703
6704 // We can't check the value of a dependent argument.
6705 if (!SecondArg->isValueDependent()) {
6706 llvm::APSInt Result;
6707 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
6708 return true;
6709
6710 if (!Result.isPowerOf2())
6711 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_alignment_not_power_of_two)
6712 << SecondArg->getSourceRange();
6713
6714 if (Result > Sema::MaximumAlignment)
6715 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::warn_assume_aligned_too_great)
6716 << SecondArg->getSourceRange() << Sema::MaximumAlignment;
6717
6718 TheCall->setArg(Arg: 1,
6719 ArgExpr: ConstantExpr::Create(Context, E: SecondArg, Result: APValue(Result)));
6720 }
6721
6722 if (NumArgs > 2) {
6723 Expr *ThirdArg = TheCall->getArg(Arg: 2);
6724 if (convertArgumentToType(S&: *this, Value&: ThirdArg, Ty: Context.getSizeType()))
6725 return true;
6726 TheCall->setArg(Arg: 2, ArgExpr: ThirdArg);
6727 }
6728
6729 return false;
6730}
6731
6732bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) {
6733 unsigned BuiltinID =
6734 cast<FunctionDecl>(Val: TheCall->getCalleeDecl())->getBuiltinID();
6735 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6736
6737 unsigned NumArgs = TheCall->getNumArgs();
6738 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6739 if (NumArgs < NumRequiredArgs) {
6740 return Diag(Loc: TheCall->getEndLoc(), DiagID: diag::err_typecheck_call_too_few_args)
6741 << 0 /* function call */ << NumRequiredArgs << NumArgs
6742 << /*is non object*/ 0 << TheCall->getSourceRange();
6743 }
6744 if (NumArgs >= NumRequiredArgs + 0x100) {
6745 return Diag(Loc: TheCall->getEndLoc(),
6746 DiagID: diag::err_typecheck_call_too_many_args_at_most)
6747 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6748 << /*is non object*/ 0 << TheCall->getSourceRange();
6749 }
6750 unsigned i = 0;
6751
6752 // For formatting call, check buffer arg.
6753 if (!IsSizeCall) {
6754 ExprResult Arg(TheCall->getArg(Arg: i));
6755 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6756 Context, Type: Context.VoidPtrTy, Consumed: false);
6757 Arg = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
6758 if (Arg.isInvalid())
6759 return true;
6760 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6761 i++;
6762 }
6763
6764 // Check string literal arg.
6765 unsigned FormatIdx = i;
6766 {
6767 ExprResult Arg = CheckOSLogFormatStringArg(Arg: TheCall->getArg(Arg: i));
6768 if (Arg.isInvalid())
6769 return true;
6770 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6771 i++;
6772 }
6773
6774 // Make sure variadic args are scalar.
6775 unsigned FirstDataArg = i;
6776 while (i < NumArgs) {
6777 ExprResult Arg = DefaultVariadicArgumentPromotion(
6778 E: TheCall->getArg(Arg: i), CT: VariadicCallType::Function, FDecl: nullptr);
6779 if (Arg.isInvalid())
6780 return true;
6781 CharUnits ArgSize = Context.getTypeSizeInChars(T: Arg.get()->getType());
6782 if (ArgSize.getQuantity() >= 0x100) {
6783 return Diag(Loc: Arg.get()->getEndLoc(), DiagID: diag::err_os_log_argument_too_big)
6784 << i << (int)ArgSize.getQuantity() << 0xff
6785 << TheCall->getSourceRange();
6786 }
6787 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
6788 i++;
6789 }
6790
6791 // Check formatting specifiers. NOTE: We're only doing this for the non-size
6792 // call to avoid duplicate diagnostics.
6793 if (!IsSizeCall) {
6794 llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6795 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6796 bool Success = CheckFormatArguments(
6797 Args, FAPK: FAPK_Variadic, ReferenceFormatString: nullptr, format_idx: FormatIdx, firstDataArg: FirstDataArg,
6798 Type: FormatStringType::OSLog, CallType: VariadicCallType::Function,
6799 Loc: TheCall->getBeginLoc(), range: SourceRange(), CheckedVarArgs);
6800 if (!Success)
6801 return true;
6802 }
6803
6804 if (IsSizeCall) {
6805 TheCall->setType(Context.getSizeType());
6806 } else {
6807 TheCall->setType(Context.VoidPtrTy);
6808 }
6809 return false;
6810}
6811
6812bool Sema::BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum,
6813 llvm::APSInt &Result) {
6814 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6815
6816 if (Arg->isTypeDependent() || Arg->isValueDependent())
6817 return false;
6818
6819 std::optional<llvm::APSInt> R = Arg->getIntegerConstantExpr(Ctx: Context);
6820 if (!R) {
6821 auto *DRE = cast<DeclRefExpr>(Val: TheCall->getCallee()->IgnoreParenCasts());
6822 auto *FDecl = cast<FunctionDecl>(Val: DRE->getDecl());
6823 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_constant_integer_arg_type)
6824 << FDecl->getDeclName() << Arg->getSourceRange();
6825 }
6826 Result = *R;
6827
6828 return false;
6829}
6830
6831bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low,
6832 int High, bool RangeIsError) {
6833 if (isConstantEvaluatedContext())
6834 return false;
6835 llvm::APSInt Result;
6836
6837 // We can't check the value of a dependent argument.
6838 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6839 if (Arg->isTypeDependent() || Arg->isValueDependent())
6840 return false;
6841
6842 // Check constant-ness first.
6843 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6844 return true;
6845
6846 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6847 if (RangeIsError)
6848 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_invalid_range)
6849 << toString(I: Result, Radix: 10) << Low << High << Arg->getSourceRange();
6850 else
6851 // Defer the warning until we know if the code will be emitted so that
6852 // dead code can ignore this.
6853 DiagRuntimeBehavior(Loc: TheCall->getBeginLoc(), Statement: TheCall,
6854 PD: PDiag(DiagID: diag::warn_argument_invalid_range)
6855 << toString(I: Result, Radix: 10) << Low << High
6856 << Arg->getSourceRange());
6857 }
6858
6859 return false;
6860}
6861
6862bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum,
6863 unsigned Num) {
6864 llvm::APSInt Result;
6865
6866 // We can't check the value of a dependent argument.
6867 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6868 if (Arg->isTypeDependent() || Arg->isValueDependent())
6869 return false;
6870
6871 // Check constant-ness first.
6872 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6873 return true;
6874
6875 if (Result.getSExtValue() % Num != 0)
6876 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_multiple)
6877 << Num << Arg->getSourceRange();
6878
6879 return false;
6880}
6881
6882bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum) {
6883 llvm::APSInt Result;
6884
6885 // We can't check the value of a dependent argument.
6886 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6887 if (Arg->isTypeDependent() || Arg->isValueDependent())
6888 return false;
6889
6890 // Check constant-ness first.
6891 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6892 return true;
6893
6894 if (Result.isPowerOf2())
6895 return false;
6896
6897 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_power_of_2)
6898 << Arg->getSourceRange();
6899}
6900
6901static bool IsShiftedByte(llvm::APSInt Value) {
6902 if (Value.isNegative())
6903 return false;
6904
6905 // Check if it's a shifted byte, by shifting it down
6906 while (true) {
6907 // If the value fits in the bottom byte, the check passes.
6908 if (Value < 0x100)
6909 return true;
6910
6911 // Otherwise, if the value has _any_ bits in the bottom byte, the check
6912 // fails.
6913 if ((Value & 0xFF) != 0)
6914 return false;
6915
6916 // If the bottom 8 bits are all 0, but something above that is nonzero,
6917 // then shifting the value right by 8 bits won't affect whether it's a
6918 // shifted byte or not. So do that, and go round again.
6919 Value >>= 8;
6920 }
6921}
6922
6923bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum,
6924 unsigned ArgBits) {
6925 llvm::APSInt Result;
6926
6927 // We can't check the value of a dependent argument.
6928 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6929 if (Arg->isTypeDependent() || Arg->isValueDependent())
6930 return false;
6931
6932 // Check constant-ness first.
6933 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6934 return true;
6935
6936 // Truncate to the given size.
6937 Result = Result.getLoBits(numBits: ArgBits);
6938 Result.setIsUnsigned(true);
6939
6940 if (IsShiftedByte(Value: Result))
6941 return false;
6942
6943 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_argument_not_shifted_byte)
6944 << Arg->getSourceRange();
6945}
6946
6947bool Sema::BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6948 unsigned ArgNum,
6949 unsigned ArgBits) {
6950 llvm::APSInt Result;
6951
6952 // We can't check the value of a dependent argument.
6953 Expr *Arg = TheCall->getArg(Arg: ArgNum);
6954 if (Arg->isTypeDependent() || Arg->isValueDependent())
6955 return false;
6956
6957 // Check constant-ness first.
6958 if (BuiltinConstantArg(TheCall, ArgNum, Result))
6959 return true;
6960
6961 // Truncate to the given size.
6962 Result = Result.getLoBits(numBits: ArgBits);
6963 Result.setIsUnsigned(true);
6964
6965 // Check to see if it's in either of the required forms.
6966 if (IsShiftedByte(Value: Result) ||
6967 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6968 return false;
6969
6970 return Diag(Loc: TheCall->getBeginLoc(),
6971 DiagID: diag::err_argument_not_shifted_byte_or_xxff)
6972 << Arg->getSourceRange();
6973}
6974
6975bool Sema::BuiltinLongjmp(CallExpr *TheCall) {
6976 if (!Context.getTargetInfo().hasSjLjLowering())
6977 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_unsupported)
6978 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6979
6980 Expr *Arg = TheCall->getArg(Arg: 1);
6981 llvm::APSInt Result;
6982
6983 // TODO: This is less than ideal. Overload this to take a value.
6984 if (BuiltinConstantArg(TheCall, ArgNum: 1, Result))
6985 return true;
6986
6987 if (Result != 1)
6988 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_longjmp_invalid_val)
6989 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6990
6991 return false;
6992}
6993
6994bool Sema::BuiltinSetjmp(CallExpr *TheCall) {
6995 if (!Context.getTargetInfo().hasSjLjLowering())
6996 return Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_setjmp_unsupported)
6997 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6998 return false;
6999}
7000
7001bool Sema::BuiltinCountedByRef(CallExpr *TheCall) {
7002 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
7003 return true;
7004
7005 ExprResult ArgRes = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
7006 if (ArgRes.isInvalid())
7007 return true;
7008
7009 // For simplicity, we support only limited expressions for the argument.
7010 // Specifically a flexible array member or a pointer with counted_by:
7011 // 'ptr->array' or 'ptr->pointer'. This allows us to reject arguments with
7012 // complex casting, which really shouldn't be a huge problem.
7013 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts();
7014 if (!Arg->getType()->isPointerType() && !Arg->getType()->isArrayType())
7015 return Diag(Loc: Arg->getBeginLoc(),
7016 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7017 << Arg->getSourceRange();
7018
7019 if (Arg->HasSideEffects(Ctx: Context))
7020 return Diag(Loc: Arg->getBeginLoc(),
7021 DiagID: diag::err_builtin_counted_by_ref_has_side_effects)
7022 << Arg->getSourceRange();
7023
7024 if (const auto *ME = dyn_cast<MemberExpr>(Val: Arg)) {
7025 const auto *CATy =
7026 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
7027
7028 if (CATy && CATy->getKind() == CountAttributedType::CountedBy) {
7029 // Member has counted_by attribute - return pointer to count field
7030 const auto *MemberDecl = cast<FieldDecl>(Val: ME->getMemberDecl());
7031 if (const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
7032 TheCall->setType(Context.getPointerType(T: CountFD->getType()));
7033 return false;
7034 }
7035 }
7036
7037 // FAMs and pointers without counted_by return void*
7038 QualType MemberTy = ME->getMemberDecl()->getType();
7039 if (!MemberTy->isArrayType() && !MemberTy->isPointerType())
7040 return Diag(Loc: Arg->getBeginLoc(),
7041 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7042 << Arg->getSourceRange();
7043 } else {
7044 return Diag(Loc: Arg->getBeginLoc(),
7045 DiagID: diag::err_builtin_counted_by_ref_invalid_arg)
7046 << Arg->getSourceRange();
7047 }
7048
7049 TheCall->setType(Context.getPointerType(T: Context.VoidTy));
7050 return false;
7051}
7052
7053/// The result of __builtin_counted_by_ref cannot be assigned to a variable.
7054/// It allows leaking and modification of bounds safety information.
7055bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E,
7056 BuiltinCountedByRefKind K) {
7057 const CallExpr *CE =
7058 E ? dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts()) : nullptr;
7059 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref)
7060 return false;
7061
7062 switch (K) {
7063 case BuiltinCountedByRefKind::Assignment:
7064 case BuiltinCountedByRefKind::Initializer:
7065 Diag(Loc: E->getExprLoc(),
7066 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7067 << 0 << E->getSourceRange();
7068 break;
7069 case BuiltinCountedByRefKind::FunctionArg:
7070 Diag(Loc: E->getExprLoc(),
7071 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7072 << 1 << E->getSourceRange();
7073 break;
7074 case BuiltinCountedByRefKind::ReturnArg:
7075 Diag(Loc: E->getExprLoc(),
7076 DiagID: diag::err_builtin_counted_by_ref_cannot_leak_reference)
7077 << 2 << E->getSourceRange();
7078 break;
7079 case BuiltinCountedByRefKind::ArraySubscript:
7080 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
7081 << 0 << E->getSourceRange();
7082 break;
7083 case BuiltinCountedByRefKind::BinaryExpr:
7084 Diag(Loc: E->getExprLoc(), DiagID: diag::err_builtin_counted_by_ref_invalid_use)
7085 << 1 << E->getSourceRange();
7086 break;
7087 }
7088
7089 return true;
7090}
7091
7092namespace {
7093
7094class UncoveredArgHandler {
7095 enum { Unknown = -1, AllCovered = -2 };
7096
7097 signed FirstUncoveredArg = Unknown;
7098 SmallVector<const Expr *, 4> DiagnosticExprs;
7099
7100public:
7101 UncoveredArgHandler() = default;
7102
7103 bool hasUncoveredArg() const {
7104 return (FirstUncoveredArg >= 0);
7105 }
7106
7107 unsigned getUncoveredArg() const {
7108 assert(hasUncoveredArg() && "no uncovered argument");
7109 return FirstUncoveredArg;
7110 }
7111
7112 void setAllCovered() {
7113 // A string has been found with all arguments covered, so clear out
7114 // the diagnostics.
7115 DiagnosticExprs.clear();
7116 FirstUncoveredArg = AllCovered;
7117 }
7118
7119 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7120 assert(NewFirstUncoveredArg >= 0 && "Outside range");
7121
7122 // Don't update if a previous string covers all arguments.
7123 if (FirstUncoveredArg == AllCovered)
7124 return;
7125
7126 // UncoveredArgHandler tracks the highest uncovered argument index
7127 // and with it all the strings that match this index.
7128 if (NewFirstUncoveredArg == FirstUncoveredArg)
7129 DiagnosticExprs.push_back(Elt: StrExpr);
7130 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7131 DiagnosticExprs.clear();
7132 DiagnosticExprs.push_back(Elt: StrExpr);
7133 FirstUncoveredArg = NewFirstUncoveredArg;
7134 }
7135 }
7136
7137 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7138};
7139
7140enum StringLiteralCheckType {
7141 SLCT_NotALiteral,
7142 SLCT_UncheckedLiteral,
7143 SLCT_CheckedLiteral
7144};
7145
7146} // namespace
7147
7148static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7149 BinaryOperatorKind BinOpKind,
7150 bool AddendIsRight) {
7151 unsigned BitWidth = Offset.getBitWidth();
7152 unsigned AddendBitWidth = Addend.getBitWidth();
7153 // There might be negative interim results.
7154 if (Addend.isUnsigned()) {
7155 Addend = Addend.zext(width: ++AddendBitWidth);
7156 Addend.setIsSigned(true);
7157 }
7158 // Adjust the bit width of the APSInts.
7159 if (AddendBitWidth > BitWidth) {
7160 Offset = Offset.sext(width: AddendBitWidth);
7161 BitWidth = AddendBitWidth;
7162 } else if (BitWidth > AddendBitWidth) {
7163 Addend = Addend.sext(width: BitWidth);
7164 }
7165
7166 bool Ov = false;
7167 llvm::APSInt ResOffset = Offset;
7168 if (BinOpKind == BO_Add)
7169 ResOffset = Offset.sadd_ov(RHS: Addend, Overflow&: Ov);
7170 else {
7171 assert(AddendIsRight && BinOpKind == BO_Sub &&
7172 "operator must be add or sub with addend on the right");
7173 ResOffset = Offset.ssub_ov(RHS: Addend, Overflow&: Ov);
7174 }
7175
7176 // We add an offset to a pointer here so we should support an offset as big as
7177 // possible.
7178 if (Ov) {
7179 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7180 "index (intermediate) result too big");
7181 Offset = Offset.sext(width: 2 * BitWidth);
7182 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7183 return;
7184 }
7185
7186 Offset = std::move(ResOffset);
7187}
7188
7189namespace {
7190
7191// This is a wrapper class around StringLiteral to support offsetted string
7192// literals as format strings. It takes the offset into account when returning
7193// the string and its length or the source locations to display notes correctly.
7194class FormatStringLiteral {
7195 const StringLiteral *FExpr;
7196 int64_t Offset;
7197
7198public:
7199 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7200 : FExpr(fexpr), Offset(Offset) {}
7201
7202 const StringLiteral *getFormatString() const { return FExpr; }
7203
7204 StringRef getString() const { return FExpr->getString().drop_front(N: Offset); }
7205
7206 unsigned getByteLength() const {
7207 return FExpr->getByteLength() - getCharByteWidth() * Offset;
7208 }
7209
7210 unsigned getLength() const { return FExpr->getLength() - Offset; }
7211 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7212
7213 StringLiteralKind getKind() const { return FExpr->getKind(); }
7214
7215 QualType getType() const { return FExpr->getType(); }
7216
7217 bool isAscii() const { return FExpr->isOrdinary(); }
7218 bool isWide() const { return FExpr->isWide(); }
7219 bool isUTF8() const { return FExpr->isUTF8(); }
7220 bool isUTF16() const { return FExpr->isUTF16(); }
7221 bool isUTF32() const { return FExpr->isUTF32(); }
7222 bool isPascal() const { return FExpr->isPascal(); }
7223
7224 SourceLocation getLocationOfByte(
7225 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7226 const TargetInfo &Target, unsigned *StartToken = nullptr,
7227 unsigned *StartTokenByteOffset = nullptr) const {
7228 return FExpr->getLocationOfByte(ByteNo: ByteNo + Offset, SM, Features, Target,
7229 StartToken, StartTokenByteOffset);
7230 }
7231
7232 SourceLocation getBeginLoc() const LLVM_READONLY {
7233 return FExpr->getBeginLoc().getLocWithOffset(Offset);
7234 }
7235
7236 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7237};
7238
7239} // namespace
7240
7241static void CheckFormatString(
7242 Sema &S, const FormatStringLiteral *FExpr,
7243 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
7244 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
7245 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
7246 bool inFunctionCall, VariadicCallType CallType,
7247 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7248 bool IgnoreStringsWithoutSpecifiers);
7249
7250static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7251 const Expr *E);
7252
7253// Determine if an expression is a string literal or constant string.
7254// If this function returns false on the arguments to a function expecting a
7255// format string, we will usually need to emit a warning.
7256// True string literals are then checked by CheckFormatString.
7257static StringLiteralCheckType
7258checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString,
7259 const Expr *E, ArrayRef<const Expr *> Args,
7260 Sema::FormatArgumentPassingKind APK, unsigned format_idx,
7261 unsigned firstDataArg, FormatStringType Type,
7262 VariadicCallType CallType, bool InFunctionCall,
7263 llvm::SmallBitVector &CheckedVarArgs,
7264 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7265 std::optional<unsigned> *CallerFormatParamIdx = nullptr,
7266 bool IgnoreStringsWithoutSpecifiers = false) {
7267 if (S.isConstantEvaluatedContext())
7268 return SLCT_NotALiteral;
7269tryAgain:
7270 assert(Offset.isSigned() && "invalid offset");
7271
7272 if (E->isTypeDependent() || E->isValueDependent())
7273 return SLCT_NotALiteral;
7274
7275 E = E->IgnoreParenCasts();
7276
7277 if (E->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull))
7278 // Technically -Wformat-nonliteral does not warn about this case.
7279 // The behavior of printf and friends in this case is implementation
7280 // dependent. Ideally if the format string cannot be null then
7281 // it should have a 'nonnull' attribute in the function prototype.
7282 return SLCT_UncheckedLiteral;
7283
7284 switch (E->getStmtClass()) {
7285 case Stmt::InitListExprClass:
7286 // Handle expressions like {"foobar"}.
7287 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E)) {
7288 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7289 format_idx, firstDataArg, Type, CallType,
7290 /*InFunctionCall*/ false, CheckedVarArgs,
7291 UncoveredArg, Offset, CallerFormatParamIdx,
7292 IgnoreStringsWithoutSpecifiers);
7293 }
7294 return SLCT_NotALiteral;
7295 case Stmt::BinaryConditionalOperatorClass:
7296 case Stmt::ConditionalOperatorClass: {
7297 // The expression is a literal if both sub-expressions were, and it was
7298 // completely checked only if both sub-expressions were checked.
7299 const AbstractConditionalOperator *C =
7300 cast<AbstractConditionalOperator>(Val: E);
7301
7302 // Determine whether it is necessary to check both sub-expressions, for
7303 // example, because the condition expression is a constant that can be
7304 // evaluated at compile time.
7305 bool CheckLeft = true, CheckRight = true;
7306
7307 bool Cond;
7308 if (C->getCond()->EvaluateAsBooleanCondition(
7309 Result&: Cond, Ctx: S.getASTContext(), InConstantContext: S.isConstantEvaluatedContext())) {
7310 if (Cond)
7311 CheckRight = false;
7312 else
7313 CheckLeft = false;
7314 }
7315
7316 // We need to maintain the offsets for the right and the left hand side
7317 // separately to check if every possible indexed expression is a valid
7318 // string literal. They might have different offsets for different string
7319 // literals in the end.
7320 StringLiteralCheckType Left;
7321 if (!CheckLeft)
7322 Left = SLCT_UncheckedLiteral;
7323 else {
7324 Left = checkFormatStringExpr(S, ReferenceFormatString, E: C->getTrueExpr(),
7325 Args, APK, format_idx, firstDataArg, Type,
7326 CallType, InFunctionCall, CheckedVarArgs,
7327 UncoveredArg, Offset, CallerFormatParamIdx,
7328 IgnoreStringsWithoutSpecifiers);
7329 if (Left == SLCT_NotALiteral || !CheckRight) {
7330 return Left;
7331 }
7332 }
7333
7334 StringLiteralCheckType Right = checkFormatStringExpr(
7335 S, ReferenceFormatString, E: C->getFalseExpr(), Args, APK, format_idx,
7336 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7337 UncoveredArg, Offset, CallerFormatParamIdx,
7338 IgnoreStringsWithoutSpecifiers);
7339
7340 return (CheckLeft && Left < Right) ? Left : Right;
7341 }
7342
7343 case Stmt::ImplicitCastExprClass:
7344 E = cast<ImplicitCastExpr>(Val: E)->getSubExpr();
7345 goto tryAgain;
7346
7347 case Stmt::OpaqueValueExprClass:
7348 if (const Expr *src = cast<OpaqueValueExpr>(Val: E)->getSourceExpr()) {
7349 E = src;
7350 goto tryAgain;
7351 }
7352 return SLCT_NotALiteral;
7353
7354 case Stmt::PredefinedExprClass:
7355 // While __func__, etc., are technically not string literals, they
7356 // cannot contain format specifiers and thus are not a security
7357 // liability.
7358 return SLCT_UncheckedLiteral;
7359
7360 case Stmt::DeclRefExprClass: {
7361 const DeclRefExpr *DR = cast<DeclRefExpr>(Val: E);
7362
7363 // As an exception, do not flag errors for variables binding to
7364 // const string literals.
7365 if (const VarDecl *VD = dyn_cast<VarDecl>(Val: DR->getDecl())) {
7366 bool isConstant = false;
7367 QualType T = DR->getType();
7368
7369 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7370 isConstant = AT->getElementType().isConstant(Ctx: S.Context);
7371 } else if (const PointerType *PT = T->getAs<PointerType>()) {
7372 isConstant = T.isConstant(Ctx: S.Context) &&
7373 PT->getPointeeType().isConstant(Ctx: S.Context);
7374 } else if (T->isObjCObjectPointerType()) {
7375 // In ObjC, there is usually no "const ObjectPointer" type,
7376 // so don't check if the pointee type is constant.
7377 isConstant = T.isConstant(Ctx: S.Context);
7378 }
7379
7380 if (isConstant) {
7381 if (const Expr *Init = VD->getAnyInitializer()) {
7382 // Look through initializers like const char c[] = { "foo" }
7383 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
7384 if (InitList->isStringLiteralInit())
7385 Init = InitList->getInit(Init: 0)->IgnoreParenImpCasts();
7386 }
7387 return checkFormatStringExpr(
7388 S, ReferenceFormatString, E: Init, Args, APK, format_idx,
7389 firstDataArg, Type, CallType, /*InFunctionCall=*/false,
7390 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7391 }
7392 }
7393
7394 // When the format argument is an argument of this function, and this
7395 // function also has the format attribute, there are several interactions
7396 // for which there shouldn't be a warning. For instance, when calling
7397 // v*printf from a function that has the printf format attribute, we
7398 // should not emit a warning about using `fmt`, even though it's not
7399 // constant, because the arguments have already been checked for the
7400 // caller of `logmessage`:
7401 //
7402 // __attribute__((format(printf, 1, 2)))
7403 // void logmessage(char const *fmt, ...) {
7404 // va_list ap;
7405 // va_start(ap, fmt);
7406 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */
7407 // ...
7408 // }
7409 //
7410 // Another interaction that we need to support is using a format string
7411 // specified by the format_matches attribute:
7412 //
7413 // __attribute__((format_matches(printf, 1, "%s %d")))
7414 // void logmessage(char const *fmt, const char *a, int b) {
7415 // printf(fmt, a, b); /* do not emit a warning about "fmt" */
7416 // printf(fmt, 123.4); /* emit warnings that "%s %d" is incompatible */
7417 // ...
7418 // }
7419 //
7420 // Yet another interaction that we need to support is calling a variadic
7421 // format function from a format function that has fixed arguments. For
7422 // instance:
7423 //
7424 // __attribute__((format(printf, 1, 2)))
7425 // void logstring(char const *fmt, char const *str) {
7426 // printf(fmt, str); /* do not emit a warning about "fmt" */
7427 // }
7428 //
7429 // Same (and perhaps more relatably) for the variadic template case:
7430 //
7431 // template<typename... Args>
7432 // __attribute__((format(printf, 1, 2)))
7433 // void log(const char *fmt, Args&&... args) {
7434 // printf(fmt, forward<Args>(args)...);
7435 // /* do not emit a warning about "fmt" */
7436 // }
7437 //
7438 // Due to implementation difficulty, we only check the format, not the
7439 // format arguments, in all cases.
7440 //
7441 if (const auto *PV = dyn_cast<ParmVarDecl>(Val: VD)) {
7442 if (CallerFormatParamIdx)
7443 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7444 if (const auto *D = dyn_cast<Decl>(Val: PV->getDeclContext())) {
7445 for (const auto *PVFormatMatches :
7446 D->specific_attrs<FormatMatchesAttr>()) {
7447 Sema::FormatStringInfo CalleeFSI;
7448 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormatMatches->getFormatIdx(),
7449 FirstArg: 0, FSI: &CalleeFSI))
7450 continue;
7451 if (PV->getFunctionScopeIndex() == CalleeFSI.FormatIdx) {
7452 // If using the wrong type of format string, emit a diagnostic
7453 // here and stop checking to avoid irrelevant diagnostics.
7454 if (Type != S.GetFormatStringType(Format: PVFormatMatches)) {
7455 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7456 DiagID: diag::warn_format_string_type_incompatible)
7457 << PVFormatMatches->getType()->getName()
7458 << S.GetFormatStringTypeName(FST: Type);
7459 if (!InFunctionCall) {
7460 S.Diag(Loc: PVFormatMatches->getFormatString()->getBeginLoc(),
7461 DiagID: diag::note_format_string_defined);
7462 }
7463 return SLCT_UncheckedLiteral;
7464 }
7465 return checkFormatStringExpr(
7466 S, ReferenceFormatString, E: PVFormatMatches->getFormatString(),
7467 Args, APK, format_idx, firstDataArg, Type, CallType,
7468 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg,
7469 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7470 }
7471 }
7472
7473 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7474 Sema::FormatStringInfo CallerFSI;
7475 if (!Sema::getFormatStringInfo(D, FormatIdx: PVFormat->getFormatIdx(),
7476 FirstArg: PVFormat->getFirstArg(), FSI: &CallerFSI))
7477 continue;
7478 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx) {
7479 // We also check if the formats are compatible.
7480 // We can't pass a 'scanf' string to a 'printf' function.
7481 if (Type != S.GetFormatStringType(Format: PVFormat)) {
7482 S.Diag(Loc: Args[format_idx]->getBeginLoc(),
7483 DiagID: diag::warn_format_string_type_incompatible)
7484 << PVFormat->getType()->getName()
7485 << S.GetFormatStringTypeName(FST: Type);
7486 if (!InFunctionCall) {
7487 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_format_string_defined);
7488 }
7489 return SLCT_UncheckedLiteral;
7490 }
7491 // Lastly, check that argument passing kinds transition in a
7492 // way that makes sense:
7493 // from a caller with FAPK_VAList, allow FAPK_VAList
7494 // from a caller with FAPK_Fixed, allow FAPK_Fixed
7495 // from a caller with FAPK_Fixed, allow FAPK_Variadic
7496 // from a caller with FAPK_Variadic, allow FAPK_VAList
7497 switch (combineFAPK(A: CallerFSI.ArgPassingKind, B: APK)) {
7498 case combineFAPK(A: Sema::FAPK_VAList, B: Sema::FAPK_VAList):
7499 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Fixed):
7500 case combineFAPK(A: Sema::FAPK_Fixed, B: Sema::FAPK_Variadic):
7501 case combineFAPK(A: Sema::FAPK_Variadic, B: Sema::FAPK_VAList):
7502 return SLCT_UncheckedLiteral;
7503 }
7504 }
7505 }
7506 }
7507 }
7508 }
7509
7510 return SLCT_NotALiteral;
7511 }
7512
7513 case Stmt::CallExprClass:
7514 case Stmt::CXXMemberCallExprClass: {
7515 const CallExpr *CE = cast<CallExpr>(Val: E);
7516 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Val: CE->getCalleeDecl())) {
7517 bool IsFirst = true;
7518 StringLiteralCheckType CommonResult;
7519 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7520 const Expr *Arg = CE->getArg(Arg: FA->getFormatIdx().getASTIndex());
7521 StringLiteralCheckType Result = checkFormatStringExpr(
7522 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7523 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7524 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7525 if (IsFirst) {
7526 CommonResult = Result;
7527 IsFirst = false;
7528 }
7529 }
7530 if (!IsFirst)
7531 return CommonResult;
7532
7533 if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) {
7534 unsigned BuiltinID = FD->getBuiltinID();
7535 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7536 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7537 const Expr *Arg = CE->getArg(Arg: 0);
7538 return checkFormatStringExpr(
7539 S, ReferenceFormatString, E: Arg, Args, APK, format_idx,
7540 firstDataArg, Type, CallType, InFunctionCall, CheckedVarArgs,
7541 UncoveredArg, Offset, CallerFormatParamIdx,
7542 IgnoreStringsWithoutSpecifiers);
7543 }
7544 }
7545 }
7546 if (const Expr *SLE = maybeConstEvalStringLiteral(Context&: S.Context, E))
7547 return checkFormatStringExpr(S, ReferenceFormatString, E: SLE, Args, APK,
7548 format_idx, firstDataArg, Type, CallType,
7549 /*InFunctionCall*/ false, CheckedVarArgs,
7550 UncoveredArg, Offset, CallerFormatParamIdx,
7551 IgnoreStringsWithoutSpecifiers);
7552 return SLCT_NotALiteral;
7553 }
7554 case Stmt::ObjCMessageExprClass: {
7555 const auto *ME = cast<ObjCMessageExpr>(Val: E);
7556 if (const auto *MD = ME->getMethodDecl()) {
7557 if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7558 // As a special case heuristic, if we're using the method -[NSBundle
7559 // localizedStringForKey:value:table:], ignore any key strings that lack
7560 // format specifiers. The idea is that if the key doesn't have any
7561 // format specifiers then its probably just a key to map to the
7562 // localized strings. If it does have format specifiers though, then its
7563 // likely that the text of the key is the format string in the
7564 // programmer's language, and should be checked.
7565 const ObjCInterfaceDecl *IFace;
7566 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7567 IFace->getIdentifier()->isStr(Str: "NSBundle") &&
7568 MD->getSelector().isKeywordSelector(
7569 Names: {"localizedStringForKey", "value", "table"})) {
7570 IgnoreStringsWithoutSpecifiers = true;
7571 }
7572
7573 const Expr *Arg = ME->getArg(Arg: FA->getFormatIdx().getASTIndex());
7574 return checkFormatStringExpr(
7575 S, ReferenceFormatString, E: Arg, Args, APK, format_idx, firstDataArg,
7576 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7577 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7578 }
7579 }
7580
7581 return SLCT_NotALiteral;
7582 }
7583 case Stmt::ObjCStringLiteralClass:
7584 case Stmt::StringLiteralClass: {
7585 const StringLiteral *StrE = nullptr;
7586
7587 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(Val: E))
7588 StrE = ObjCFExpr->getString();
7589 else
7590 StrE = cast<StringLiteral>(Val: E);
7591
7592 if (StrE) {
7593 if (Offset.isNegative() || Offset > StrE->getLength()) {
7594 // TODO: It would be better to have an explicit warning for out of
7595 // bounds literals.
7596 return SLCT_NotALiteral;
7597 }
7598 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(width: 64).getSExtValue());
7599 CheckFormatString(S, FExpr: &FStr, ReferenceFormatString, OrigFormatExpr: E, Args, APK,
7600 format_idx, firstDataArg, Type, inFunctionCall: InFunctionCall,
7601 CallType, CheckedVarArgs, UncoveredArg,
7602 IgnoreStringsWithoutSpecifiers);
7603 return SLCT_CheckedLiteral;
7604 }
7605
7606 return SLCT_NotALiteral;
7607 }
7608 case Stmt::BinaryOperatorClass: {
7609 const BinaryOperator *BinOp = cast<BinaryOperator>(Val: E);
7610
7611 // A string literal + an int offset is still a string literal.
7612 if (BinOp->isAdditiveOp()) {
7613 Expr::EvalResult LResult, RResult;
7614
7615 bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7616 Result&: LResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7617 InConstantContext: S.isConstantEvaluatedContext());
7618 bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7619 Result&: RResult, Ctx: S.Context, AllowSideEffects: Expr::SE_NoSideEffects,
7620 InConstantContext: S.isConstantEvaluatedContext());
7621
7622 if (LIsInt != RIsInt) {
7623 BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7624
7625 if (LIsInt) {
7626 if (BinOpKind == BO_Add) {
7627 sumOffsets(Offset, Addend: LResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7628 E = BinOp->getRHS();
7629 goto tryAgain;
7630 }
7631 } else {
7632 sumOffsets(Offset, Addend: RResult.Val.getInt(), BinOpKind, AddendIsRight: RIsInt);
7633 E = BinOp->getLHS();
7634 goto tryAgain;
7635 }
7636 }
7637 }
7638
7639 return SLCT_NotALiteral;
7640 }
7641 case Stmt::UnaryOperatorClass: {
7642 const UnaryOperator *UnaOp = cast<UnaryOperator>(Val: E);
7643 auto ASE = dyn_cast<ArraySubscriptExpr>(Val: UnaOp->getSubExpr());
7644 if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7645 Expr::EvalResult IndexResult;
7646 if (ASE->getRHS()->EvaluateAsInt(Result&: IndexResult, Ctx: S.Context,
7647 AllowSideEffects: Expr::SE_NoSideEffects,
7648 InConstantContext: S.isConstantEvaluatedContext())) {
7649 sumOffsets(Offset, Addend: IndexResult.Val.getInt(), BinOpKind: BO_Add,
7650 /*RHS is int*/ AddendIsRight: true);
7651 E = ASE->getBase();
7652 goto tryAgain;
7653 }
7654 }
7655
7656 return SLCT_NotALiteral;
7657 }
7658
7659 default:
7660 return SLCT_NotALiteral;
7661 }
7662}
7663
7664// If this expression can be evaluated at compile-time,
7665// check if the result is a StringLiteral and return it
7666// otherwise return nullptr
7667static const Expr *maybeConstEvalStringLiteral(ASTContext &Context,
7668 const Expr *E) {
7669 Expr::EvalResult Result;
7670 if (E->EvaluateAsRValue(Result, Ctx: Context) && Result.Val.isLValue()) {
7671 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>();
7672 if (isa_and_nonnull<StringLiteral>(Val: LVE))
7673 return LVE;
7674 }
7675 return nullptr;
7676}
7677
7678StringRef Sema::GetFormatStringTypeName(FormatStringType FST) {
7679 switch (FST) {
7680 case FormatStringType::Scanf:
7681 return "scanf";
7682 case FormatStringType::Printf:
7683 return "printf";
7684 case FormatStringType::NSString:
7685 return "NSString";
7686 case FormatStringType::Strftime:
7687 return "strftime";
7688 case FormatStringType::Strfmon:
7689 return "strfmon";
7690 case FormatStringType::Kprintf:
7691 return "kprintf";
7692 case FormatStringType::FreeBSDKPrintf:
7693 return "freebsd_kprintf";
7694 case FormatStringType::OSLog:
7695 return "os_log";
7696 default:
7697 return "<unknown>";
7698 }
7699}
7700
7701FormatStringType Sema::GetFormatStringType(StringRef Flavor) {
7702 return llvm::StringSwitch<FormatStringType>(Flavor)
7703 .Cases(CaseStrings: {"gnu_scanf", "scanf"}, Value: FormatStringType::Scanf)
7704 .Cases(CaseStrings: {"gnu_printf", "printf", "printf0", "syslog"},
7705 Value: FormatStringType::Printf)
7706 .Cases(CaseStrings: {"NSString", "CFString"}, Value: FormatStringType::NSString)
7707 .Cases(CaseStrings: {"gnu_strftime", "strftime"}, Value: FormatStringType::Strftime)
7708 .Cases(CaseStrings: {"gnu_strfmon", "strfmon"}, Value: FormatStringType::Strfmon)
7709 .Cases(CaseStrings: {"kprintf", "cmn_err", "vcmn_err", "zcmn_err"},
7710 Value: FormatStringType::Kprintf)
7711 .Case(S: "freebsd_kprintf", Value: FormatStringType::FreeBSDKPrintf)
7712 .Case(S: "os_trace", Value: FormatStringType::OSLog)
7713 .Case(S: "os_log", Value: FormatStringType::OSLog)
7714 .Default(Value: FormatStringType::Unknown);
7715}
7716
7717FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7718 return GetFormatStringType(Flavor: Format->getType()->getName());
7719}
7720
7721FormatStringType Sema::GetFormatStringType(const FormatMatchesAttr *Format) {
7722 return GetFormatStringType(Flavor: Format->getType()->getName());
7723}
7724
7725bool Sema::CheckFormatArguments(const FormatAttr *Format,
7726 ArrayRef<const Expr *> Args, bool IsCXXMember,
7727 VariadicCallType CallType, SourceLocation Loc,
7728 SourceRange Range,
7729 llvm::SmallBitVector &CheckedVarArgs) {
7730 FormatStringInfo FSI;
7731 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: Format->getFirstArg(),
7732 HasImplicitThisParam: IsCXXMember,
7733 IsVariadic: CallType != VariadicCallType::DoesNotApply, FSI: &FSI))
7734 return CheckFormatArguments(
7735 Args, FAPK: FSI.ArgPassingKind, ReferenceFormatString: nullptr, format_idx: FSI.FormatIdx, firstDataArg: FSI.FirstDataArg,
7736 Type: GetFormatStringType(Format), CallType, Loc, range: Range, CheckedVarArgs);
7737 return false;
7738}
7739
7740bool Sema::CheckFormatString(const FormatMatchesAttr *Format,
7741 ArrayRef<const Expr *> Args, bool IsCXXMember,
7742 VariadicCallType CallType, SourceLocation Loc,
7743 SourceRange Range,
7744 llvm::SmallBitVector &CheckedVarArgs) {
7745 FormatStringInfo FSI;
7746 if (getFormatStringInfo(FormatIdx: Format->getFormatIdx(), FirstArg: 0, HasImplicitThisParam: IsCXXMember, IsVariadic: false,
7747 FSI: &FSI)) {
7748 FSI.ArgPassingKind = Sema::FAPK_Elsewhere;
7749 return CheckFormatArguments(Args, FAPK: FSI.ArgPassingKind,
7750 ReferenceFormatString: Format->getFormatString(), format_idx: FSI.FormatIdx,
7751 firstDataArg: FSI.FirstDataArg, Type: GetFormatStringType(Format),
7752 CallType, Loc, range: Range, CheckedVarArgs);
7753 }
7754 return false;
7755}
7756
7757static bool CheckMissingFormatAttribute(
7758 Sema *S, ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
7759 StringLiteral *ReferenceFormatString, unsigned FormatIdx,
7760 unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx,
7761 SourceLocation Loc) {
7762 if (S->getDiagnostics().isIgnored(DiagID: diag::warn_missing_format_attribute, Loc))
7763 return false;
7764
7765 DeclContext *DC = S->CurContext;
7766 if (!isa<ObjCMethodDecl>(Val: DC) && !isa<FunctionDecl>(Val: DC) && !isa<BlockDecl>(Val: DC))
7767 return false;
7768 Decl *Caller = cast<Decl>(Val: DC)->getCanonicalDecl();
7769
7770 unsigned NumCallerParams = getFunctionOrMethodNumParams(D: Caller);
7771
7772 // Find the offset to convert between attribute and parameter indexes.
7773 unsigned CallerArgumentIndexOffset =
7774 hasImplicitObjectParameter(D: Caller) ? 2 : 1;
7775
7776 unsigned FirstArgumentIndex = -1;
7777 switch (APK) {
7778 case Sema::FormatArgumentPassingKind::FAPK_Fixed:
7779 case Sema::FormatArgumentPassingKind::FAPK_Variadic: {
7780 // As an extension, clang allows the format attribute on non-variadic
7781 // functions.
7782 // Caller must have fixed arguments to pass them to a fixed or variadic
7783 // function. Try to match caller and callee arguments. If successful, then
7784 // emit a diag with the caller idx, otherwise we can't determine the callee
7785 // arguments.
7786 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
7787 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
7788 // There aren't enough arguments in the caller to pass to callee.
7789 return false;
7790 }
7791 for (unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
7792 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
7793 const auto *Arg =
7794 dyn_cast<DeclRefExpr>(Val: Args[CalleeIdx]->IgnoreParenCasts());
7795 if (!Arg)
7796 return false;
7797 const auto *Param = dyn_cast<ParmVarDecl>(Val: Arg->getDecl());
7798 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
7799 return false;
7800 }
7801 FirstArgumentIndex =
7802 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
7803 break;
7804 }
7805 case Sema::FormatArgumentPassingKind::FAPK_VAList:
7806 // Caller arguments are either variadic or a va_list.
7807 FirstArgumentIndex = isFunctionOrMethodVariadic(D: Caller)
7808 ? (NumCallerParams + CallerArgumentIndexOffset)
7809 : 0;
7810 break;
7811 case Sema::FormatArgumentPassingKind::FAPK_Elsewhere:
7812 // The callee has a format_matches attribute. We will emit that instead.
7813 if (!ReferenceFormatString)
7814 return false;
7815 break;
7816 }
7817
7818 // Emit the diagnostic and fixit.
7819 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
7820 StringRef FormatTypeName = S->GetFormatStringTypeName(FST: FormatType);
7821 NamedDecl *ND = dyn_cast<NamedDecl>(Val: Caller);
7822 do {
7823 std::string Attr, Fixit;
7824 llvm::raw_string_ostream AttrOS(Attr);
7825 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
7826 AttrOS << "format(" << FormatTypeName << ", " << FormatStringIndex << ", "
7827 << FirstArgumentIndex << ")";
7828 } else {
7829 AttrOS << "format_matches(" << FormatTypeName << ", " << FormatStringIndex
7830 << ", \"";
7831 AttrOS.write_escaped(Str: ReferenceFormatString->getString());
7832 AttrOS << "\")";
7833 }
7834 AttrOS.flush();
7835 auto DB = S->Diag(Loc, DiagID: diag::warn_missing_format_attribute) << Attr;
7836 if (ND)
7837 DB << ND;
7838 else
7839 DB << "block";
7840
7841 // Blocks don't provide a correct end loc, so skip emitting a fixit.
7842 if (isa<BlockDecl>(Val: Caller))
7843 break;
7844
7845 SourceLocation SL;
7846 llvm::raw_string_ostream IS(Fixit);
7847 // The attribute goes at the start of the declaration in C/C++ functions
7848 // and methods, but after the declaration for Objective-C methods.
7849 if (isa<ObjCMethodDecl>(Val: Caller)) {
7850 IS << ' ';
7851 SL = Caller->getEndLoc();
7852 }
7853 const LangOptions &LO = S->getLangOpts();
7854 if (LO.C23 || LO.CPlusPlus11)
7855 IS << "[[gnu::" << Attr << "]]";
7856 else if (LO.ObjC || LO.GNUMode)
7857 IS << "__attribute__((" << Attr << "))";
7858 else
7859 break;
7860 if (!isa<ObjCMethodDecl>(Val: Caller)) {
7861 IS << ' ';
7862 SL = Caller->getBeginLoc();
7863 }
7864 IS.flush();
7865
7866 DB << FixItHint::CreateInsertion(InsertionLoc: SL, Code: Fixit);
7867 } while (false);
7868
7869 // Add implicit format or format_matches attribute.
7870 if (APK != Sema::FormatArgumentPassingKind::FAPK_Elsewhere) {
7871 Caller->addAttr(A: FormatAttr::CreateImplicit(
7872 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
7873 FormatIdx: FormatStringIndex, FirstArg: FirstArgumentIndex));
7874 } else {
7875 Caller->addAttr(A: FormatMatchesAttr::CreateImplicit(
7876 Ctx&: S->getASTContext(), Type: &S->getASTContext().Idents.get(Name: FormatTypeName),
7877 FormatIdx: FormatStringIndex, ExpectedFormat: ReferenceFormatString));
7878 }
7879
7880 {
7881 auto DB = S->Diag(Loc: Caller->getLocation(), DiagID: diag::note_entity_declared_at);
7882 if (ND)
7883 DB << ND;
7884 else
7885 DB << "block";
7886 }
7887 return true;
7888}
7889
7890bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7891 Sema::FormatArgumentPassingKind APK,
7892 StringLiteral *ReferenceFormatString,
7893 unsigned format_idx, unsigned firstDataArg,
7894 FormatStringType Type,
7895 VariadicCallType CallType, SourceLocation Loc,
7896 SourceRange Range,
7897 llvm::SmallBitVector &CheckedVarArgs) {
7898 // CHECK: printf/scanf-like function is called with no format string.
7899 if (format_idx >= Args.size()) {
7900 Diag(Loc, DiagID: diag::warn_missing_format_string) << Range;
7901 return false;
7902 }
7903
7904 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7905
7906 // CHECK: format string is not a string literal.
7907 //
7908 // Dynamically generated format strings are difficult to
7909 // automatically vet at compile time. Requiring that format strings
7910 // are string literals: (1) permits the checking of format strings by
7911 // the compiler and thereby (2) can practically remove the source of
7912 // many format string exploits.
7913
7914 // Format string can be either ObjC string (e.g. @"%d") or
7915 // C string (e.g. "%d")
7916 // ObjC string uses the same format specifiers as C string, so we can use
7917 // the same format string checking logic for both ObjC and C strings.
7918 UncoveredArgHandler UncoveredArg;
7919 std::optional<unsigned> CallerParamIdx;
7920 StringLiteralCheckType CT = checkFormatStringExpr(
7921 S&: *this, ReferenceFormatString, E: OrigFormatExpr, Args, APK, format_idx,
7922 firstDataArg, Type, CallType,
7923 /*IsFunctionCall*/ InFunctionCall: true, CheckedVarArgs, UncoveredArg,
7924 /*no string offset*/ Offset: llvm::APSInt(64, false) = 0, CallerFormatParamIdx: &CallerParamIdx);
7925
7926 // Generate a diagnostic where an uncovered argument is detected.
7927 if (UncoveredArg.hasUncoveredArg()) {
7928 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7929 assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7930 UncoveredArg.Diagnose(S&: *this, /*IsFunctionCall*/true, ArgExpr: Args[ArgIdx]);
7931 }
7932
7933 if (CT != SLCT_NotALiteral)
7934 // Literal format string found, check done!
7935 return CT == SLCT_CheckedLiteral;
7936
7937 // Do not emit diag when the string param is a macro expansion and the
7938 // format is either NSString or CFString. This is a hack to prevent
7939 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7940 // which are usually used in place of NS and CF string literals.
7941 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7942 if (Type == FormatStringType::NSString &&
7943 SourceMgr.isInSystemMacro(loc: FormatLoc))
7944 return false;
7945
7946 if (CallerParamIdx && CheckMissingFormatAttribute(
7947 S: this, Args, APK, ReferenceFormatString, FormatIdx: format_idx,
7948 FirstDataArg: firstDataArg, FormatType: Type, CallerParamIdx: *CallerParamIdx, Loc))
7949 return false;
7950
7951 // Strftime is particular as it always uses a single 'time' argument,
7952 // so it is safe to pass a non-literal string.
7953 if (Type == FormatStringType::Strftime)
7954 return false;
7955
7956 // If there are no arguments specified, warn with -Wformat-security, otherwise
7957 // warn only with -Wformat-nonliteral.
7958 if (Args.size() == firstDataArg) {
7959 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral_noargs)
7960 << OrigFormatExpr->getSourceRange();
7961 switch (Type) {
7962 default:
7963 break;
7964 case FormatStringType::Kprintf:
7965 case FormatStringType::FreeBSDKPrintf:
7966 case FormatStringType::Printf:
7967 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
7968 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "\"%s\", ");
7969 break;
7970 case FormatStringType::NSString:
7971 Diag(Loc: FormatLoc, DiagID: diag::note_format_security_fixit)
7972 << FixItHint::CreateInsertion(InsertionLoc: FormatLoc, Code: "@\"%@\", ");
7973 break;
7974 }
7975 } else {
7976 Diag(Loc: FormatLoc, DiagID: diag::warn_format_nonliteral)
7977 << OrigFormatExpr->getSourceRange();
7978 }
7979 return false;
7980}
7981
7982namespace {
7983
7984class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7985protected:
7986 Sema &S;
7987 const FormatStringLiteral *FExpr;
7988 const Expr *OrigFormatExpr;
7989 const FormatStringType FSType;
7990 const unsigned FirstDataArg;
7991 const unsigned NumDataArgs;
7992 const char *Beg; // Start of format string.
7993 const Sema::FormatArgumentPassingKind ArgPassingKind;
7994 ArrayRef<const Expr *> Args;
7995 unsigned FormatIdx;
7996 llvm::SmallBitVector CoveredArgs;
7997 bool usesPositionalArgs = false;
7998 bool atFirstArg = true;
7999 bool inFunctionCall;
8000 VariadicCallType CallType;
8001 llvm::SmallBitVector &CheckedVarArgs;
8002 UncoveredArgHandler &UncoveredArg;
8003
8004public:
8005 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8006 const Expr *origFormatExpr, const FormatStringType type,
8007 unsigned firstDataArg, unsigned numDataArgs,
8008 const char *beg, Sema::FormatArgumentPassingKind APK,
8009 ArrayRef<const Expr *> Args, unsigned formatIdx,
8010 bool inFunctionCall, VariadicCallType callType,
8011 llvm::SmallBitVector &CheckedVarArgs,
8012 UncoveredArgHandler &UncoveredArg)
8013 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8014 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8015 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
8016 inFunctionCall(inFunctionCall), CallType(callType),
8017 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8018 CoveredArgs.resize(N: numDataArgs);
8019 CoveredArgs.reset();
8020 }
8021
8022 bool HasFormatArguments() const {
8023 return ArgPassingKind == Sema::FAPK_Fixed ||
8024 ArgPassingKind == Sema::FAPK_Variadic;
8025 }
8026
8027 void DoneProcessing();
8028
8029 void HandleIncompleteSpecifier(const char *startSpecifier,
8030 unsigned specifierLen) override;
8031
8032 void HandleInvalidLengthModifier(
8033 const analyze_format_string::FormatSpecifier &FS,
8034 const analyze_format_string::ConversionSpecifier &CS,
8035 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
8036
8037 void HandleNonStandardLengthModifier(
8038 const analyze_format_string::FormatSpecifier &FS,
8039 const char *startSpecifier, unsigned specifierLen);
8040
8041 void HandleNonStandardConversionSpecifier(
8042 const analyze_format_string::ConversionSpecifier &CS,
8043 const char *startSpecifier, unsigned specifierLen);
8044
8045 void HandlePosition(const char *startPos, unsigned posLen) override;
8046
8047 void HandleInvalidPosition(const char *startSpecifier, unsigned specifierLen,
8048 analyze_format_string::PositionContext p) override;
8049
8050 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8051
8052 void HandleNullChar(const char *nullCharacter) override;
8053
8054 template <typename Range>
8055 static void
8056 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8057 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8058 bool IsStringLocation, Range StringRange,
8059 ArrayRef<FixItHint> Fixit = {});
8060
8061protected:
8062 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8063 const char *startSpec,
8064 unsigned specifierLen,
8065 const char *csStart, unsigned csLen);
8066
8067 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8068 const char *startSpec,
8069 unsigned specifierLen);
8070
8071 SourceRange getFormatStringRange();
8072 CharSourceRange getSpecifierRange(const char *startSpecifier,
8073 unsigned specifierLen);
8074 SourceLocation getLocationOfByte(const char *x);
8075
8076 const Expr *getDataArg(unsigned i) const;
8077
8078 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8079 const analyze_format_string::ConversionSpecifier &CS,
8080 const char *startSpecifier, unsigned specifierLen,
8081 unsigned argIndex);
8082
8083 bool CheckUnsupportedType(const analyze_format_string::ArgType &AT,
8084 const Expr *E, const char *startSpecifier,
8085 unsigned specifierLen);
8086
8087 template <typename Range>
8088 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8089 bool IsStringLocation, Range StringRange,
8090 ArrayRef<FixItHint> Fixit = {});
8091};
8092
8093} // namespace
8094
8095SourceRange CheckFormatHandler::getFormatStringRange() {
8096 return OrigFormatExpr->getSourceRange();
8097}
8098
8099CharSourceRange
8100CheckFormatHandler::getSpecifierRange(const char *startSpecifier,
8101 unsigned specifierLen) {
8102 SourceLocation Start = getLocationOfByte(x: startSpecifier);
8103 SourceLocation End = getLocationOfByte(x: startSpecifier + specifierLen - 1);
8104
8105 // Advance the end SourceLocation by one due to half-open ranges.
8106 End = End.getLocWithOffset(Offset: 1);
8107
8108 return CharSourceRange::getCharRange(B: Start, E: End);
8109}
8110
8111SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8112 return FExpr->getLocationOfByte(ByteNo: x - Beg, SM: S.getSourceManager(),
8113 Features: S.getLangOpts(), Target: S.Context.getTargetInfo());
8114}
8115
8116void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8117 unsigned specifierLen) {
8118 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_incomplete_specifier),
8119 Loc: getLocationOfByte(x: startSpecifier),
8120 /*IsStringLocation*/ true,
8121 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8122}
8123
8124bool CheckFormatHandler::CheckUnsupportedType(
8125 const analyze_format_string::ArgType &AT, const Expr *E,
8126 const char *StartSpecifier, unsigned SpecifierLen) {
8127 if (!AT.isUnsupported())
8128 return false;
8129
8130 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_unsupported_type)
8131 << AT.getRepresentativeTypeName(C&: S.Context),
8132 Loc: E->getExprLoc(), /*IsStringLocation=*/false,
8133 StringRange: getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen));
8134 return true;
8135}
8136
8137void CheckFormatHandler::HandleInvalidLengthModifier(
8138 const analyze_format_string::FormatSpecifier &FS,
8139 const analyze_format_string::ConversionSpecifier &CS,
8140 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8141 using namespace analyze_format_string;
8142
8143 const LengthModifier &LM = FS.getLengthModifier();
8144 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
8145
8146 // See if we know how to fix this length modifier.
8147 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8148 if (FixedLM) {
8149 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
8150 Loc: getLocationOfByte(x: LM.getStart()),
8151 /*IsStringLocation*/ true,
8152 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8153
8154 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
8155 << FixedLM->toString()
8156 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
8157
8158 } else {
8159 FixItHint Hint;
8160 if (DiagID == diag::warn_format_nonsensical_length)
8161 Hint = FixItHint::CreateRemoval(RemoveRange: LMRange);
8162
8163 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID) << LM.toString() << CS.toString(),
8164 Loc: getLocationOfByte(x: LM.getStart()),
8165 /*IsStringLocation*/ true,
8166 StringRange: getSpecifierRange(startSpecifier, specifierLen), FixIt: Hint);
8167 }
8168}
8169
8170void CheckFormatHandler::HandleNonStandardLengthModifier(
8171 const analyze_format_string::FormatSpecifier &FS,
8172 const char *startSpecifier, unsigned specifierLen) {
8173 using namespace analyze_format_string;
8174
8175 const LengthModifier &LM = FS.getLengthModifier();
8176 CharSourceRange LMRange = getSpecifierRange(startSpecifier: LM.getStart(), specifierLen: LM.getLength());
8177
8178 // See if we know how to fix this length modifier.
8179 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8180 if (FixedLM) {
8181 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8182 << LM.toString() << 0,
8183 Loc: getLocationOfByte(x: LM.getStart()),
8184 /*IsStringLocation*/ true,
8185 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8186
8187 S.Diag(Loc: getLocationOfByte(x: LM.getStart()), DiagID: diag::note_format_fix_specifier)
8188 << FixedLM->toString()
8189 << FixItHint::CreateReplacement(RemoveRange: LMRange, Code: FixedLM->toString());
8190
8191 } else {
8192 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8193 << LM.toString() << 0,
8194 Loc: getLocationOfByte(x: LM.getStart()),
8195 /*IsStringLocation*/ true,
8196 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8197 }
8198}
8199
8200void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8201 const analyze_format_string::ConversionSpecifier &CS,
8202 const char *startSpecifier, unsigned specifierLen) {
8203 using namespace analyze_format_string;
8204
8205 // See if we know how to fix this conversion specifier.
8206 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8207 if (FixedCS) {
8208 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8209 << CS.toString() << /*conversion specifier*/ 1,
8210 Loc: getLocationOfByte(x: CS.getStart()),
8211 /*IsStringLocation*/ true,
8212 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8213
8214 CharSourceRange CSRange = getSpecifierRange(startSpecifier: CS.getStart(), specifierLen: CS.getLength());
8215 S.Diag(Loc: getLocationOfByte(x: CS.getStart()), DiagID: diag::note_format_fix_specifier)
8216 << FixedCS->toString()
8217 << FixItHint::CreateReplacement(RemoveRange: CSRange, Code: FixedCS->toString());
8218 } else {
8219 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard)
8220 << CS.toString() << /*conversion specifier*/ 1,
8221 Loc: getLocationOfByte(x: CS.getStart()),
8222 /*IsStringLocation*/ true,
8223 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8224 }
8225}
8226
8227void CheckFormatHandler::HandlePosition(const char *startPos, unsigned posLen) {
8228 if (!S.getDiagnostics().isIgnored(
8229 DiagID: diag::warn_format_non_standard_positional_arg, Loc: SourceLocation()))
8230 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_non_standard_positional_arg),
8231 Loc: getLocationOfByte(x: startPos),
8232 /*IsStringLocation*/ true,
8233 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
8234}
8235
8236void CheckFormatHandler::HandleInvalidPosition(
8237 const char *startSpecifier, unsigned specifierLen,
8238 analyze_format_string::PositionContext p) {
8239 if (!S.getDiagnostics().isIgnored(
8240 DiagID: diag::warn_format_invalid_positional_specifier, Loc: SourceLocation()))
8241 EmitFormatDiagnostic(
8242 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_positional_specifier) << (unsigned)p,
8243 Loc: getLocationOfByte(x: startSpecifier), /*IsStringLocation*/ true,
8244 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8245}
8246
8247void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8248 unsigned posLen) {
8249 if (!S.getDiagnostics().isIgnored(DiagID: diag::warn_format_zero_positional_specifier,
8250 Loc: SourceLocation()))
8251 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_zero_positional_specifier),
8252 Loc: getLocationOfByte(x: startPos),
8253 /*IsStringLocation*/ true,
8254 StringRange: getSpecifierRange(startSpecifier: startPos, specifierLen: posLen));
8255}
8256
8257void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8258 if (!isa<ObjCStringLiteral>(Val: OrigFormatExpr)) {
8259 // The presence of a null character is likely an error.
8260 EmitFormatDiagnostic(
8261 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_contains_null_char),
8262 Loc: getLocationOfByte(x: nullCharacter), /*IsStringLocation*/ true,
8263 StringRange: getFormatStringRange());
8264 }
8265}
8266
8267// Note that this may return NULL if there was an error parsing or building
8268// one of the argument expressions.
8269const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8270 return Args[FirstDataArg + i];
8271}
8272
8273void CheckFormatHandler::DoneProcessing() {
8274 // Does the number of data arguments exceed the number of
8275 // format conversions in the format string?
8276 if (HasFormatArguments()) {
8277 // Find any arguments that weren't covered.
8278 CoveredArgs.flip();
8279 signed notCoveredArg = CoveredArgs.find_first();
8280 if (notCoveredArg >= 0) {
8281 assert((unsigned)notCoveredArg < NumDataArgs);
8282 UncoveredArg.Update(NewFirstUncoveredArg: notCoveredArg, StrExpr: OrigFormatExpr);
8283 } else {
8284 UncoveredArg.setAllCovered();
8285 }
8286 }
8287}
8288
8289void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8290 const Expr *ArgExpr) {
8291 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && "Invalid state");
8292
8293 if (!ArgExpr)
8294 return;
8295
8296 SourceLocation Loc = ArgExpr->getBeginLoc();
8297
8298 if (S.getSourceManager().isInSystemMacro(loc: Loc))
8299 return;
8300
8301 PartialDiagnostic PDiag = S.PDiag(DiagID: diag::warn_printf_data_arg_not_used);
8302 for (auto E : DiagnosticExprs)
8303 PDiag << E->getSourceRange();
8304
8305 CheckFormatHandler::EmitFormatDiagnostic(
8306 S, InFunctionCall: IsFunctionCall, ArgumentExpr: DiagnosticExprs[0], PDiag, Loc,
8307 /*IsStringLocation*/ false, StringRange: DiagnosticExprs[0]->getSourceRange());
8308}
8309
8310bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8311 unsigned argIndex, SourceLocation Loc, const char *startSpec,
8312 unsigned specifierLen, const char *csStart, unsigned csLen) {
8313 bool keepGoing = true;
8314 if (argIndex < NumDataArgs) {
8315 // Consider the argument coverered, even though the specifier doesn't
8316 // make sense.
8317 CoveredArgs.set(argIndex);
8318 } else {
8319 // If argIndex exceeds the number of data arguments we
8320 // don't issue a warning because that is just a cascade of warnings (and
8321 // they may have intended '%%' anyway). We don't want to continue processing
8322 // the format string after this point, however, as we will like just get
8323 // gibberish when trying to match arguments.
8324 keepGoing = false;
8325 }
8326
8327 StringRef Specifier(csStart, csLen);
8328
8329 // If the specifier in non-printable, it could be the first byte of a UTF-8
8330 // sequence. In that case, print the UTF-8 code point. If not, print the byte
8331 // hex value.
8332 std::string CodePointStr;
8333 if (!llvm::sys::locale::isPrint(c: *csStart)) {
8334 llvm::UTF32 CodePoint;
8335 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8336 const llvm::UTF8 *E = reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8337 llvm::ConversionResult Result =
8338 llvm::convertUTF8Sequence(source: B, sourceEnd: E, target: &CodePoint, flags: llvm::strictConversion);
8339
8340 if (Result != llvm::conversionOK) {
8341 unsigned char FirstChar = *csStart;
8342 CodePoint = (llvm::UTF32)FirstChar;
8343 }
8344
8345 llvm::raw_string_ostream OS(CodePointStr);
8346 if (CodePoint < 256)
8347 OS << "\\x" << llvm::format(Fmt: "%02x", Vals: CodePoint);
8348 else if (CodePoint <= 0xFFFF)
8349 OS << "\\u" << llvm::format(Fmt: "%04x", Vals: CodePoint);
8350 else
8351 OS << "\\U" << llvm::format(Fmt: "%08x", Vals: CodePoint);
8352 Specifier = CodePointStr;
8353 }
8354
8355 EmitFormatDiagnostic(
8356 PDiag: S.PDiag(DiagID: diag::warn_format_invalid_conversion) << Specifier, Loc,
8357 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
8358
8359 return keepGoing;
8360}
8361
8362void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8363 SourceLocation Loc, const char *startSpec, unsigned specifierLen) {
8364 EmitFormatDiagnostic(
8365 PDiag: S.PDiag(DiagID: diag::warn_format_mix_positional_nonpositional_args), Loc,
8366 /*isStringLoc*/ IsStringLocation: true, StringRange: getSpecifierRange(startSpecifier: startSpec, specifierLen));
8367}
8368
8369bool CheckFormatHandler::CheckNumArgs(
8370 const analyze_format_string::FormatSpecifier &FS,
8371 const analyze_format_string::ConversionSpecifier &CS,
8372 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8373
8374 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8375 PartialDiagnostic PDiag =
8376 FS.usesPositionalArg()
8377 ? (S.PDiag(DiagID: diag::warn_printf_positional_arg_exceeds_data_args)
8378 << (argIndex + 1) << NumDataArgs)
8379 : S.PDiag(DiagID: diag::warn_printf_insufficient_data_args);
8380 EmitFormatDiagnostic(PDiag, Loc: getLocationOfByte(x: CS.getStart()),
8381 /*IsStringLocation*/ true,
8382 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8383
8384 // Since more arguments than conversion tokens are given, by extension
8385 // all arguments are covered, so mark this as so.
8386 UncoveredArg.setAllCovered();
8387 return false;
8388 }
8389 return true;
8390}
8391
8392template <typename Range>
8393void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8394 SourceLocation Loc,
8395 bool IsStringLocation,
8396 Range StringRange,
8397 ArrayRef<FixItHint> FixIt) {
8398 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8399 IsStringLocation, StringRange, FixIt);
8400}
8401
8402/// If the format string is not within the function call, emit a note
8403/// so that the function call and string are in diagnostic messages.
8404///
8405/// \param InFunctionCall if true, the format string is within the function
8406/// call and only one diagnostic message will be produced. Otherwise, an
8407/// extra note will be emitted pointing to location of the format string.
8408///
8409/// \param ArgumentExpr the expression that is passed as the format string
8410/// argument in the function call. Used for getting locations when two
8411/// diagnostics are emitted.
8412///
8413/// \param PDiag the callee should already have provided any strings for the
8414/// diagnostic message. This function only adds locations and fixits
8415/// to diagnostics.
8416///
8417/// \param Loc primary location for diagnostic. If two diagnostics are
8418/// required, one will be at Loc and a new SourceLocation will be created for
8419/// the other one.
8420///
8421/// \param IsStringLocation if true, Loc points to the format string should be
8422/// used for the note. Otherwise, Loc points to the argument list and will
8423/// be used with PDiag.
8424///
8425/// \param StringRange some or all of the string to highlight. This is
8426/// templated so it can accept either a CharSourceRange or a SourceRange.
8427///
8428/// \param FixIt optional fix it hint for the format string.
8429template <typename Range>
8430void CheckFormatHandler::EmitFormatDiagnostic(
8431 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8432 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8433 Range StringRange, ArrayRef<FixItHint> FixIt) {
8434 if (InFunctionCall) {
8435 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PD: PDiag);
8436 D << StringRange;
8437 D << FixIt;
8438 } else {
8439 S.Diag(Loc: IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PD: PDiag)
8440 << ArgumentExpr->getSourceRange();
8441
8442 const Sema::SemaDiagnosticBuilder &Note =
8443 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8444 diag::note_format_string_defined);
8445
8446 Note << StringRange;
8447 Note << FixIt;
8448 }
8449}
8450
8451//===--- CHECK: Printf format string checking -----------------------------===//
8452
8453namespace {
8454
8455class CheckPrintfHandler : public CheckFormatHandler {
8456public:
8457 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8458 const Expr *origFormatExpr, const FormatStringType type,
8459 unsigned firstDataArg, unsigned numDataArgs, bool isObjC,
8460 const char *beg, Sema::FormatArgumentPassingKind APK,
8461 ArrayRef<const Expr *> Args, unsigned formatIdx,
8462 bool inFunctionCall, VariadicCallType CallType,
8463 llvm::SmallBitVector &CheckedVarArgs,
8464 UncoveredArgHandler &UncoveredArg)
8465 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8466 numDataArgs, beg, APK, Args, formatIdx,
8467 inFunctionCall, CallType, CheckedVarArgs,
8468 UncoveredArg) {}
8469
8470 bool isObjCContext() const { return FSType == FormatStringType::NSString; }
8471
8472 /// Returns true if '%@' specifiers are allowed in the format string.
8473 bool allowsObjCArg() const {
8474 return FSType == FormatStringType::NSString ||
8475 FSType == FormatStringType::OSLog ||
8476 FSType == FormatStringType::OSTrace;
8477 }
8478
8479 bool HandleInvalidPrintfConversionSpecifier(
8480 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8481 unsigned specifierLen) override;
8482
8483 void handleInvalidMaskType(StringRef MaskType) override;
8484
8485 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8486 const char *startSpecifier, unsigned specifierLen,
8487 const TargetInfo &Target) override;
8488 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8489 const char *StartSpecifier, unsigned SpecifierLen,
8490 const Expr *E);
8491
8492 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt,
8493 unsigned k, const char *startSpecifier,
8494 unsigned specifierLen);
8495 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8496 const analyze_printf::OptionalAmount &Amt,
8497 unsigned type, const char *startSpecifier,
8498 unsigned specifierLen);
8499 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8500 const analyze_printf::OptionalFlag &flag,
8501 const char *startSpecifier, unsigned specifierLen);
8502 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8503 const analyze_printf::OptionalFlag &ignoredFlag,
8504 const analyze_printf::OptionalFlag &flag,
8505 const char *startSpecifier, unsigned specifierLen);
8506 bool checkForCStrMembers(const analyze_printf::ArgType &AT, const Expr *E);
8507
8508 void HandleEmptyObjCModifierFlag(const char *startFlag,
8509 unsigned flagLen) override;
8510
8511 void HandleInvalidObjCModifierFlag(const char *startFlag,
8512 unsigned flagLen) override;
8513
8514 void
8515 HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8516 const char *flagsEnd,
8517 const char *conversionPosition) override;
8518};
8519
8520/// Keeps around the information needed to verify that two specifiers are
8521/// compatible.
8522class EquatableFormatArgument {
8523public:
8524 enum SpecifierSensitivity : unsigned {
8525 SS_None,
8526 SS_Private,
8527 SS_Public,
8528 SS_Sensitive
8529 };
8530
8531 enum FormatArgumentRole : unsigned {
8532 FAR_Data,
8533 FAR_FieldWidth,
8534 FAR_Precision,
8535 FAR_Auxiliary, // FreeBSD kernel %b and %D
8536 };
8537
8538private:
8539 analyze_format_string::ArgType ArgType;
8540 analyze_format_string::LengthModifier LengthMod;
8541 StringRef SpecifierLetter;
8542 CharSourceRange Range;
8543 SourceLocation ElementLoc;
8544 FormatArgumentRole Role : 2;
8545 SpecifierSensitivity Sensitivity : 2; // only set for FAR_Data
8546 unsigned Position : 14;
8547 unsigned ModifierFor : 14; // not set for FAR_Data
8548
8549 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag, const Expr *FmtExpr,
8550 bool InFunctionCall) const;
8551
8552public:
8553 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8554 analyze_format_string::LengthModifier LengthMod,
8555 StringRef SpecifierLetter,
8556 analyze_format_string::ArgType ArgType,
8557 FormatArgumentRole Role,
8558 SpecifierSensitivity Sensitivity, unsigned Position,
8559 unsigned ModifierFor)
8560 : ArgType(ArgType), LengthMod(LengthMod),
8561 SpecifierLetter(SpecifierLetter), Range(Range), ElementLoc(ElementLoc),
8562 Role(Role), Sensitivity(Sensitivity), Position(Position),
8563 ModifierFor(ModifierFor) {}
8564
8565 unsigned getPosition() const { return Position; }
8566 SourceLocation getSourceLocation() const { return ElementLoc; }
8567 CharSourceRange getSourceRange() const { return Range; }
8568 analyze_format_string::LengthModifier getLengthModifier() const {
8569 return LengthMod;
8570 }
8571 void setModifierFor(unsigned V) { ModifierFor = V; }
8572
8573 std::string buildFormatSpecifier() const {
8574 std::string result;
8575 llvm::raw_string_ostream(result)
8576 << getLengthModifier().toString() << SpecifierLetter;
8577 return result;
8578 }
8579
8580 bool VerifyCompatible(Sema &S, const EquatableFormatArgument &Other,
8581 const Expr *FmtExpr, bool InFunctionCall) const;
8582};
8583
8584/// Turns format strings into lists of EquatableSpecifier objects.
8585class DecomposePrintfHandler : public CheckPrintfHandler {
8586 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8587 bool HadError;
8588
8589 DecomposePrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8590 const Expr *origFormatExpr,
8591 const FormatStringType type, unsigned firstDataArg,
8592 unsigned numDataArgs, bool isObjC, const char *beg,
8593 Sema::FormatArgumentPassingKind APK,
8594 ArrayRef<const Expr *> Args, unsigned formatIdx,
8595 bool inFunctionCall, VariadicCallType CallType,
8596 llvm::SmallBitVector &CheckedVarArgs,
8597 UncoveredArgHandler &UncoveredArg,
8598 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8599 : CheckPrintfHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8600 numDataArgs, isObjC, beg, APK, Args, formatIdx,
8601 inFunctionCall, CallType, CheckedVarArgs,
8602 UncoveredArg),
8603 Specs(Specs), HadError(false) {}
8604
8605public:
8606 static bool
8607 GetSpecifiers(Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8608 FormatStringType type, bool IsObjC, bool InFunctionCall,
8609 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8610
8611 virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8612 const char *startSpecifier,
8613 unsigned specifierLen,
8614 const TargetInfo &Target) override;
8615};
8616
8617} // namespace
8618
8619bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8620 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8621 unsigned specifierLen) {
8622 const analyze_printf::PrintfConversionSpecifier &CS =
8623 FS.getConversionSpecifier();
8624
8625 return HandleInvalidConversionSpecifier(
8626 argIndex: FS.getArgIndex(), Loc: getLocationOfByte(x: CS.getStart()), startSpec: startSpecifier,
8627 specifierLen, csStart: CS.getStart(), csLen: CS.getLength());
8628}
8629
8630void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8631 S.Diag(Loc: getLocationOfByte(x: MaskType.data()), DiagID: diag::err_invalid_mask_type_size);
8632}
8633
8634// Error out if struct or complex type argments are passed to os_log.
8635static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType,
8636 QualType T) {
8637 if (FSType != FormatStringType::OSLog)
8638 return false;
8639 return T->isRecordType() || T->isComplexType();
8640}
8641
8642bool CheckPrintfHandler::HandleAmount(
8643 const analyze_format_string::OptionalAmount &Amt, unsigned k,
8644 const char *startSpecifier, unsigned specifierLen) {
8645 if (Amt.hasDataArgument()) {
8646 if (HasFormatArguments()) {
8647 unsigned argIndex = Amt.getArgIndex();
8648 if (argIndex >= NumDataArgs) {
8649 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_asterisk_missing_arg)
8650 << k,
8651 Loc: getLocationOfByte(x: Amt.getStart()),
8652 /*IsStringLocation*/ true,
8653 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8654 // Don't do any more checking. We will just emit
8655 // spurious errors.
8656 return false;
8657 }
8658
8659 // Type check the data argument. It should be an 'int'.
8660 // Although not in conformance with C99, we also allow the argument to be
8661 // an 'unsigned int' as that is a reasonably safe case. GCC also
8662 // doesn't emit a warning for that case.
8663 CoveredArgs.set(argIndex);
8664 const Expr *Arg = getDataArg(i: argIndex);
8665 if (!Arg)
8666 return false;
8667
8668 QualType T = Arg->getType();
8669
8670 const analyze_printf::ArgType &AT = Amt.getArgType(Ctx&: S.Context);
8671 assert(AT.isValid());
8672
8673 if (!AT.matchesType(C&: S.Context, argTy: T)) {
8674 unsigned DiagID = isInvalidOSLogArgTypeForCodeGen(FSType, T)
8675 ? diag::err_printf_asterisk_wrong_type
8676 : diag::warn_printf_asterisk_wrong_type;
8677 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID)
8678 << k << AT.getRepresentativeTypeName(C&: S.Context)
8679 << T << Arg->getSourceRange(),
8680 Loc: getLocationOfByte(x: Amt.getStart()),
8681 /*IsStringLocation*/ true,
8682 StringRange: getSpecifierRange(startSpecifier, specifierLen));
8683 // Don't do any more checking. We will just emit
8684 // spurious errors.
8685 return false;
8686 }
8687 }
8688 }
8689 return true;
8690}
8691
8692void CheckPrintfHandler::HandleInvalidAmount(
8693 const analyze_printf::PrintfSpecifier &FS,
8694 const analyze_printf::OptionalAmount &Amt, unsigned type,
8695 const char *startSpecifier, unsigned specifierLen) {
8696 const analyze_printf::PrintfConversionSpecifier &CS =
8697 FS.getConversionSpecifier();
8698
8699 FixItHint fixit =
8700 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8701 ? FixItHint::CreateRemoval(
8702 RemoveRange: getSpecifierRange(startSpecifier: Amt.getStart(), specifierLen: Amt.getConstantLength()))
8703 : FixItHint();
8704
8705 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_optional_amount)
8706 << type << CS.toString(),
8707 Loc: getLocationOfByte(x: Amt.getStart()),
8708 /*IsStringLocation*/ true,
8709 StringRange: getSpecifierRange(startSpecifier, specifierLen), FixIt: fixit);
8710}
8711
8712void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8713 const analyze_printf::OptionalFlag &flag,
8714 const char *startSpecifier,
8715 unsigned specifierLen) {
8716 // Warn about pointless flag with a fixit removal.
8717 const analyze_printf::PrintfConversionSpecifier &CS =
8718 FS.getConversionSpecifier();
8719 EmitFormatDiagnostic(
8720 PDiag: S.PDiag(DiagID: diag::warn_printf_nonsensical_flag)
8721 << flag.toString() << CS.toString(),
8722 Loc: getLocationOfByte(x: flag.getPosition()),
8723 /*IsStringLocation*/ true,
8724 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8725 FixIt: FixItHint::CreateRemoval(RemoveRange: getSpecifierRange(startSpecifier: flag.getPosition(), specifierLen: 1)));
8726}
8727
8728void CheckPrintfHandler::HandleIgnoredFlag(
8729 const analyze_printf::PrintfSpecifier &FS,
8730 const analyze_printf::OptionalFlag &ignoredFlag,
8731 const analyze_printf::OptionalFlag &flag, const char *startSpecifier,
8732 unsigned specifierLen) {
8733 // Warn about ignored flag with a fixit removal.
8734 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_ignored_flag)
8735 << ignoredFlag.toString() << flag.toString(),
8736 Loc: getLocationOfByte(x: ignoredFlag.getPosition()),
8737 /*IsStringLocation*/ true,
8738 StringRange: getSpecifierRange(startSpecifier, specifierLen),
8739 FixIt: FixItHint::CreateRemoval(
8740 RemoveRange: getSpecifierRange(startSpecifier: ignoredFlag.getPosition(), specifierLen: 1)));
8741}
8742
8743void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8744 unsigned flagLen) {
8745 // Warn about an empty flag.
8746 EmitFormatDiagnostic(
8747 PDiag: S.PDiag(DiagID: diag::warn_printf_empty_objc_flag), Loc: getLocationOfByte(x: startFlag),
8748 /*IsStringLocation*/ true, StringRange: getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen));
8749}
8750
8751void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8752 unsigned flagLen) {
8753 // Warn about an invalid flag.
8754 auto Range = getSpecifierRange(startSpecifier: startFlag, specifierLen: flagLen);
8755 StringRef flag(startFlag, flagLen);
8756 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_invalid_objc_flag) << flag,
8757 Loc: getLocationOfByte(x: startFlag),
8758 /*IsStringLocation*/ true, StringRange: Range,
8759 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8760}
8761
8762void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8763 const char *flagsStart, const char *flagsEnd,
8764 const char *conversionPosition) {
8765 // Warn about using '[...]' without a '@' conversion.
8766 auto Range = getSpecifierRange(startSpecifier: flagsStart, specifierLen: flagsEnd - flagsStart + 1);
8767 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8768 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag) << StringRef(conversionPosition, 1),
8769 Loc: getLocationOfByte(x: conversionPosition),
8770 /*IsStringLocation*/ true, StringRange: Range,
8771 FixIt: FixItHint::CreateRemoval(RemoveRange: Range));
8772}
8773
8774void EquatableFormatArgument::EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
8775 const Expr *FmtExpr,
8776 bool InFunctionCall) const {
8777 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, ArgumentExpr: FmtExpr, PDiag,
8778 Loc: ElementLoc, IsStringLocation: true, StringRange: Range);
8779}
8780
8781bool EquatableFormatArgument::VerifyCompatible(
8782 Sema &S, const EquatableFormatArgument &Other, const Expr *FmtExpr,
8783 bool InFunctionCall) const {
8784 using MK = analyze_format_string::ArgType::MatchKind;
8785 if (Role != Other.Role) {
8786 // diagnose and stop
8787 EmitDiagnostic(
8788 S, PDiag: S.PDiag(DiagID: diag::warn_format_cmp_role_mismatch) << Role << Other.Role,
8789 FmtExpr, InFunctionCall);
8790 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8791 return false;
8792 }
8793
8794 if (Role != FAR_Data) {
8795 if (ModifierFor != Other.ModifierFor) {
8796 // diagnose and stop
8797 EmitDiagnostic(S,
8798 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_modifierfor_mismatch)
8799 << (ModifierFor + 1) << (Other.ModifierFor + 1),
8800 FmtExpr, InFunctionCall);
8801 S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with) << 0 << Other.Range;
8802 return false;
8803 }
8804 return true;
8805 }
8806
8807 bool HadError = false;
8808 if (Sensitivity != Other.Sensitivity) {
8809 // diagnose and continue
8810 EmitDiagnostic(S,
8811 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_sensitivity_mismatch)
8812 << Sensitivity << Other.Sensitivity,
8813 FmtExpr, InFunctionCall);
8814 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8815 << 0 << Other.Range;
8816 }
8817
8818 switch (ArgType.matchesArgType(C&: S.Context, other: Other.ArgType)) {
8819 case MK::Match:
8820 break;
8821
8822 case MK::MatchPromotion:
8823 // Per consensus reached at https://discourse.llvm.org/t/-/83076/12,
8824 // MatchPromotion is treated as a failure by format_matches.
8825 case MK::NoMatch:
8826 case MK::NoMatchTypeConfusion:
8827 case MK::NoMatchPromotionTypeConfusion:
8828 EmitDiagnostic(S,
8829 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch)
8830 << buildFormatSpecifier()
8831 << Other.buildFormatSpecifier(),
8832 FmtExpr, InFunctionCall);
8833 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8834 << 0 << Other.Range;
8835 break;
8836
8837 case MK::NoMatchPedantic:
8838 EmitDiagnostic(S,
8839 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_mismatch_pedantic)
8840 << buildFormatSpecifier()
8841 << Other.buildFormatSpecifier(),
8842 FmtExpr, InFunctionCall);
8843 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8844 << 0 << Other.Range;
8845 break;
8846
8847 case MK::NoMatchSignedness:
8848 EmitDiagnostic(S,
8849 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_sign_mismatch)
8850 << buildFormatSpecifier()
8851 << Other.buildFormatSpecifier(),
8852 FmtExpr, InFunctionCall);
8853 HadError = S.Diag(Loc: Other.ElementLoc, DiagID: diag::note_format_cmp_with)
8854 << 0 << Other.Range;
8855 break;
8856 }
8857 return !HadError;
8858}
8859
8860bool DecomposePrintfHandler::GetSpecifiers(
8861 Sema &S, const FormatStringLiteral *FSL, const Expr *FmtExpr,
8862 FormatStringType Type, bool IsObjC, bool InFunctionCall,
8863 llvm::SmallVectorImpl<EquatableFormatArgument> &Args) {
8864 StringRef Data = FSL->getString();
8865 const char *Str = Data.data();
8866 llvm::SmallBitVector BV;
8867 UncoveredArgHandler UA;
8868 const Expr *PrintfArgs[] = {FSL->getFormatString()};
8869 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(), Type, 0, 0, IsObjC,
8870 Str, Sema::FAPK_Elsewhere, PrintfArgs, 0,
8871 InFunctionCall, VariadicCallType::DoesNotApply, BV,
8872 UA, Args);
8873
8874 if (!analyze_format_string::ParsePrintfString(
8875 H, beg: Str, end: Str + Data.size(), LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
8876 isFreeBSDKPrintf: Type == FormatStringType::FreeBSDKPrintf))
8877 H.DoneProcessing();
8878 if (H.HadError)
8879 return false;
8880
8881 llvm::stable_sort(Range&: Args, C: [](const EquatableFormatArgument &A,
8882 const EquatableFormatArgument &B) {
8883 return A.getPosition() < B.getPosition();
8884 });
8885 return true;
8886}
8887
8888bool DecomposePrintfHandler::HandlePrintfSpecifier(
8889 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
8890 unsigned specifierLen, const TargetInfo &Target) {
8891 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
8892 specifierLen, Target)) {
8893 HadError = true;
8894 return false;
8895 }
8896
8897 // Do not add any specifiers to the list for %%. This is possibly incorrect
8898 // if using a precision/width with a data argument, but that combination is
8899 // meaningless and we wouldn't know which format to attach the
8900 // precision/width to.
8901 const auto &CS = FS.getConversionSpecifier();
8902 if (CS.getKind() == analyze_format_string::ConversionSpecifier::PercentArg)
8903 return true;
8904
8905 // have to patch these to have the right ModifierFor if they are used
8906 const unsigned Unset = ~0;
8907 unsigned FieldWidthIndex = Unset;
8908 unsigned PrecisionIndex = Unset;
8909
8910 // field width?
8911 const auto &FieldWidth = FS.getFieldWidth();
8912 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
8913 FieldWidthIndex = Specs.size();
8914 Specs.emplace_back(
8915 Args: getSpecifierRange(startSpecifier, specifierLen),
8916 Args: getLocationOfByte(x: FieldWidth.getStart()),
8917 Args: analyze_format_string::LengthModifier(), Args: FieldWidth.getCharacters(),
8918 Args: FieldWidth.getArgType(Ctx&: S.Context),
8919 Args: EquatableFormatArgument::FAR_FieldWidth,
8920 Args: EquatableFormatArgument::SS_None,
8921 Args: FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
8922 : FieldWidthIndex,
8923 Args: 0);
8924 }
8925 // precision?
8926 const auto &Precision = FS.getPrecision();
8927 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
8928 PrecisionIndex = Specs.size();
8929 Specs.emplace_back(
8930 Args: getSpecifierRange(startSpecifier, specifierLen),
8931 Args: getLocationOfByte(x: Precision.getStart()),
8932 Args: analyze_format_string::LengthModifier(), Args: Precision.getCharacters(),
8933 Args: Precision.getArgType(Ctx&: S.Context), Args: EquatableFormatArgument::FAR_Precision,
8934 Args: EquatableFormatArgument::SS_None,
8935 Args: Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
8936 : PrecisionIndex,
8937 Args: 0);
8938 }
8939
8940 // this specifier
8941 unsigned SpecIndex =
8942 FS.usesPositionalArg() ? FS.getPositionalArgIndex() - 1 : Specs.size();
8943 if (FieldWidthIndex != Unset)
8944 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
8945 if (PrecisionIndex != Unset)
8946 Specs[PrecisionIndex].setModifierFor(SpecIndex);
8947
8948 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
8949 if (FS.isPrivate())
8950 Sensitivity = EquatableFormatArgument::SS_Private;
8951 else if (FS.isPublic())
8952 Sensitivity = EquatableFormatArgument::SS_Public;
8953 else if (FS.isSensitive())
8954 Sensitivity = EquatableFormatArgument::SS_Sensitive;
8955 else
8956 Sensitivity = EquatableFormatArgument::SS_None;
8957
8958 Specs.emplace_back(
8959 Args: getSpecifierRange(startSpecifier, specifierLen),
8960 Args: getLocationOfByte(x: CS.getStart()), Args: FS.getLengthModifier(),
8961 Args: CS.getCharacters(), Args: FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext()),
8962 Args: EquatableFormatArgument::FAR_Data, Args&: Sensitivity, Args&: SpecIndex, Args: 0);
8963
8964 // auxiliary argument?
8965 if (CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDbArg ||
8966 CS.getKind() == analyze_format_string::ConversionSpecifier::FreeBSDDArg) {
8967 Specs.emplace_back(Args: getSpecifierRange(startSpecifier, specifierLen),
8968 Args: getLocationOfByte(x: CS.getStart()),
8969 Args: analyze_format_string::LengthModifier(),
8970 Args: CS.getCharacters(),
8971 Args: analyze_format_string::ArgType::CStrTy,
8972 Args: EquatableFormatArgument::FAR_Auxiliary, Args&: Sensitivity,
8973 Args: SpecIndex + 1, Args&: SpecIndex);
8974 }
8975 return true;
8976}
8977
8978// Determines if the specified is a C++ class or struct containing
8979// a member with the specified name and kind (e.g. a CXXMethodDecl named
8980// "c_str()").
8981template<typename MemberKind>
8982static llvm::SmallPtrSet<MemberKind*, 1>
8983CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8984 auto *RD = Ty->getAsCXXRecordDecl();
8985 llvm::SmallPtrSet<MemberKind*, 1> Results;
8986
8987 if (!RD || !(RD->isBeingDefined() || RD->isCompleteDefinition()))
8988 return Results;
8989
8990 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8991 Sema::LookupMemberName);
8992 R.suppressDiagnostics();
8993
8994 // We just need to include all members of the right kind turned up by the
8995 // filter, at this point.
8996 if (S.LookupQualifiedName(R, LookupCtx: RD))
8997 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8998 NamedDecl *decl = (*I)->getUnderlyingDecl();
8999 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
9000 Results.insert(FK);
9001 }
9002 return Results;
9003}
9004
9005/// Check if we could call '.c_str()' on an object.
9006///
9007/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
9008/// allow the call, or if it would be ambiguous).
9009bool Sema::hasCStrMethod(const Expr *E) {
9010 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9011
9012 MethodSet Results =
9013 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S&: *this, Ty: E->getType());
9014 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9015 MI != ME; ++MI)
9016 if ((*MI)->getMinRequiredArguments() == 0)
9017 return true;
9018 return false;
9019}
9020
9021// Check if a (w)string was passed when a (w)char* was needed, and offer a
9022// better diagnostic if so. AT is assumed to be valid.
9023// Returns true when a c_str() conversion method is found.
9024bool CheckPrintfHandler::checkForCStrMembers(
9025 const analyze_printf::ArgType &AT, const Expr *E) {
9026 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
9027
9028 MethodSet Results =
9029 CXXRecordMembersNamed<CXXMethodDecl>(Name: "c_str", S, Ty: E->getType());
9030
9031 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9032 MI != ME; ++MI) {
9033 const CXXMethodDecl *Method = *MI;
9034 if (Method->getMinRequiredArguments() == 0 &&
9035 AT.matchesType(C&: S.Context, argTy: Method->getReturnType())) {
9036 // FIXME: Suggest parens if the expression needs them.
9037 SourceLocation EndLoc = S.getLocForEndOfToken(Loc: E->getEndLoc());
9038 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::note_printf_c_str)
9039 << "c_str()" << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ".c_str()");
9040 return true;
9041 }
9042 }
9043
9044 return false;
9045}
9046
9047bool CheckPrintfHandler::HandlePrintfSpecifier(
9048 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier,
9049 unsigned specifierLen, const TargetInfo &Target) {
9050 using namespace analyze_format_string;
9051 using namespace analyze_printf;
9052
9053 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
9054
9055 if (FS.consumesDataArgument()) {
9056 if (atFirstArg) {
9057 atFirstArg = false;
9058 usesPositionalArgs = FS.usesPositionalArg();
9059 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9060 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
9061 startSpec: startSpecifier, specifierLen);
9062 return false;
9063 }
9064 }
9065
9066 // First check if the field width, precision, and conversion specifier
9067 // have matching data arguments.
9068 if (!HandleAmount(Amt: FS.getFieldWidth(), /* field width */ k: 0, startSpecifier,
9069 specifierLen)) {
9070 return false;
9071 }
9072
9073 if (!HandleAmount(Amt: FS.getPrecision(), /* precision */ k: 1, startSpecifier,
9074 specifierLen)) {
9075 return false;
9076 }
9077
9078 if (!CS.consumesDataArgument()) {
9079 // FIXME: Technically specifying a precision or field width here
9080 // makes no sense. Worth issuing a warning at some point.
9081 return true;
9082 }
9083
9084 // Consume the argument.
9085 unsigned argIndex = FS.getArgIndex();
9086 if (argIndex < NumDataArgs) {
9087 // The check to see if the argIndex is valid will come later.
9088 // We set the bit here because we may exit early from this
9089 // function if we encounter some other error.
9090 CoveredArgs.set(argIndex);
9091 }
9092
9093 // FreeBSD kernel extensions.
9094 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9095 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9096 // We need at least two arguments.
9097 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex: argIndex + 1))
9098 return false;
9099
9100 if (HasFormatArguments()) {
9101 // Claim the second argument.
9102 CoveredArgs.set(argIndex + 1);
9103
9104 // Type check the first argument (int for %b, pointer for %D)
9105 const Expr *Ex = getDataArg(i: argIndex);
9106 const analyze_printf::ArgType &AT =
9107 (CS.getKind() == ConversionSpecifier::FreeBSDbArg)
9108 ? ArgType(S.Context.IntTy)
9109 : ArgType::CPointerTy;
9110 if (AT.isValid() && !AT.matchesType(C&: S.Context, argTy: Ex->getType()))
9111 EmitFormatDiagnostic(
9112 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9113 << AT.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
9114 << false << Ex->getSourceRange(),
9115 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
9116 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9117
9118 // Type check the second argument (char * for both %b and %D)
9119 Ex = getDataArg(i: argIndex + 1);
9120 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9121 if (AT2.isValid() && !AT2.matchesType(C&: S.Context, argTy: Ex->getType()))
9122 EmitFormatDiagnostic(
9123 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9124 << AT2.getRepresentativeTypeName(C&: S.Context) << Ex->getType()
9125 << false << Ex->getSourceRange(),
9126 Loc: Ex->getBeginLoc(), /*IsStringLocation*/ false,
9127 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9128 }
9129 return true;
9130 }
9131
9132 // Check for using an Objective-C specific conversion specifier
9133 // in a non-ObjC literal.
9134 if (!allowsObjCArg() && CS.isObjCArg()) {
9135 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9136 specifierLen);
9137 }
9138
9139 // %P can only be used with os_log.
9140 if (FSType != FormatStringType::OSLog &&
9141 CS.getKind() == ConversionSpecifier::PArg) {
9142 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9143 specifierLen);
9144 }
9145
9146 // %n is not allowed with os_log.
9147 if (FSType == FormatStringType::OSLog &&
9148 CS.getKind() == ConversionSpecifier::nArg) {
9149 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_os_log_format_narg),
9150 Loc: getLocationOfByte(x: CS.getStart()),
9151 /*IsStringLocation*/ false,
9152 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9153
9154 return true;
9155 }
9156
9157 // Only scalars are allowed for os_trace.
9158 if (FSType == FormatStringType::OSTrace &&
9159 (CS.getKind() == ConversionSpecifier::PArg ||
9160 CS.getKind() == ConversionSpecifier::sArg ||
9161 CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9162 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9163 specifierLen);
9164 }
9165
9166 // Check for use of public/private annotation outside of os_log().
9167 if (FSType != FormatStringType::OSLog) {
9168 if (FS.isPublic().isSet()) {
9169 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
9170 << "public",
9171 Loc: getLocationOfByte(x: FS.isPublic().getPosition()),
9172 /*IsStringLocation*/ false,
9173 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9174 }
9175 if (FS.isPrivate().isSet()) {
9176 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_invalid_annotation)
9177 << "private",
9178 Loc: getLocationOfByte(x: FS.isPrivate().getPosition()),
9179 /*IsStringLocation*/ false,
9180 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9181 }
9182 }
9183
9184 const llvm::Triple &Triple = Target.getTriple();
9185 if (CS.getKind() == ConversionSpecifier::nArg &&
9186 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9187 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_printf_narg_not_supported),
9188 Loc: getLocationOfByte(x: CS.getStart()),
9189 /*IsStringLocation*/ false,
9190 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9191 }
9192
9193 // Check for invalid use of field width
9194 if (!FS.hasValidFieldWidth()) {
9195 HandleInvalidAmount(FS, Amt: FS.getFieldWidth(), /* field width */ type: 0,
9196 startSpecifier, specifierLen);
9197 }
9198
9199 // Check for invalid use of precision
9200 if (!FS.hasValidPrecision()) {
9201 HandleInvalidAmount(FS, Amt: FS.getPrecision(), /* precision */ type: 1,
9202 startSpecifier, specifierLen);
9203 }
9204
9205 // Precision is mandatory for %P specifier.
9206 if (CS.getKind() == ConversionSpecifier::PArg &&
9207 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9208 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_no_precision),
9209 Loc: getLocationOfByte(x: startSpecifier),
9210 /*IsStringLocation*/ false,
9211 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9212 }
9213
9214 // Check each flag does not conflict with any other component.
9215 if (!FS.hasValidThousandsGroupingPrefix())
9216 HandleFlag(FS, flag: FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9217 if (!FS.hasValidLeadingZeros())
9218 HandleFlag(FS, flag: FS.hasLeadingZeros(), startSpecifier, specifierLen);
9219 if (!FS.hasValidPlusPrefix())
9220 HandleFlag(FS, flag: FS.hasPlusPrefix(), startSpecifier, specifierLen);
9221 if (!FS.hasValidSpacePrefix())
9222 HandleFlag(FS, flag: FS.hasSpacePrefix(), startSpecifier, specifierLen);
9223 if (!FS.hasValidAlternativeForm())
9224 HandleFlag(FS, flag: FS.hasAlternativeForm(), startSpecifier, specifierLen);
9225 if (!FS.hasValidLeftJustified())
9226 HandleFlag(FS, flag: FS.isLeftJustified(), startSpecifier, specifierLen);
9227
9228 // Check that flags are not ignored by another flag
9229 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9230 HandleIgnoredFlag(FS, ignoredFlag: FS.hasSpacePrefix(), flag: FS.hasPlusPrefix(),
9231 startSpecifier, specifierLen);
9232 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9233 HandleIgnoredFlag(FS, ignoredFlag: FS.hasLeadingZeros(), flag: FS.isLeftJustified(),
9234 startSpecifier, specifierLen);
9235
9236 // Check the length modifier is valid with the given conversion specifier.
9237 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
9238 LO: S.getLangOpts()))
9239 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9240 DiagID: diag::warn_format_nonsensical_length);
9241 else if (!FS.hasStandardLengthModifier())
9242 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9243 else if (!FS.hasStandardLengthConversionCombination())
9244 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9245 DiagID: diag::warn_format_non_standard_conversion_spec);
9246
9247 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
9248 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9249
9250 // The remaining checks depend on the data arguments.
9251 if (!HasFormatArguments())
9252 return true;
9253
9254 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9255 return false;
9256
9257 const Expr *Arg = getDataArg(i: argIndex);
9258 if (!Arg)
9259 return true;
9260
9261 return checkFormatExpr(FS, StartSpecifier: startSpecifier, SpecifierLen: specifierLen, E: Arg);
9262}
9263
9264static bool requiresParensToAddCast(const Expr *E) {
9265 // FIXME: We should have a general way to reason about operator
9266 // precedence and whether parens are actually needed here.
9267 // Take care of a few common cases where they aren't.
9268 const Expr *Inside = E->IgnoreImpCasts();
9269 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: Inside))
9270 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9271
9272 switch (Inside->getStmtClass()) {
9273 case Stmt::ArraySubscriptExprClass:
9274 case Stmt::CallExprClass:
9275 case Stmt::CharacterLiteralClass:
9276 case Stmt::CXXBoolLiteralExprClass:
9277 case Stmt::DeclRefExprClass:
9278 case Stmt::FloatingLiteralClass:
9279 case Stmt::IntegerLiteralClass:
9280 case Stmt::MemberExprClass:
9281 case Stmt::ObjCArrayLiteralClass:
9282 case Stmt::ObjCBoolLiteralExprClass:
9283 case Stmt::ObjCBoxedExprClass:
9284 case Stmt::ObjCDictionaryLiteralClass:
9285 case Stmt::ObjCEncodeExprClass:
9286 case Stmt::ObjCIvarRefExprClass:
9287 case Stmt::ObjCMessageExprClass:
9288 case Stmt::ObjCPropertyRefExprClass:
9289 case Stmt::ObjCStringLiteralClass:
9290 case Stmt::ObjCSubscriptRefExprClass:
9291 case Stmt::ParenExprClass:
9292 case Stmt::StringLiteralClass:
9293 case Stmt::UnaryOperatorClass:
9294 return false;
9295 default:
9296 return true;
9297 }
9298}
9299
9300static std::pair<QualType, StringRef>
9301shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy,
9302 const Expr *E) {
9303 // Use a 'while' to peel off layers of typedefs.
9304 QualType TyTy = IntendedTy;
9305 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9306 StringRef Name = UserTy->getDecl()->getName();
9307 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9308 .Case(S: "CFIndex", Value: Context.getNSIntegerType())
9309 .Case(S: "NSInteger", Value: Context.getNSIntegerType())
9310 .Case(S: "NSUInteger", Value: Context.getNSUIntegerType())
9311 .Case(S: "SInt32", Value: Context.IntTy)
9312 .Case(S: "UInt32", Value: Context.UnsignedIntTy)
9313 .Default(Value: QualType());
9314
9315 if (!CastTy.isNull())
9316 return std::make_pair(x&: CastTy, y&: Name);
9317
9318 TyTy = UserTy->desugar();
9319 }
9320
9321 // Strip parens if necessary.
9322 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Val: E))
9323 return shouldNotPrintDirectly(Context, IntendedTy: PE->getSubExpr()->getType(),
9324 E: PE->getSubExpr());
9325
9326 // If this is a conditional expression, then its result type is constructed
9327 // via usual arithmetic conversions and thus there might be no necessary
9328 // typedef sugar there. Recurse to operands to check for NSInteger &
9329 // Co. usage condition.
9330 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
9331 QualType TrueTy, FalseTy;
9332 StringRef TrueName, FalseName;
9333
9334 std::tie(args&: TrueTy, args&: TrueName) = shouldNotPrintDirectly(
9335 Context, IntendedTy: CO->getTrueExpr()->getType(), E: CO->getTrueExpr());
9336 std::tie(args&: FalseTy, args&: FalseName) = shouldNotPrintDirectly(
9337 Context, IntendedTy: CO->getFalseExpr()->getType(), E: CO->getFalseExpr());
9338
9339 if (TrueTy == FalseTy)
9340 return std::make_pair(x&: TrueTy, y&: TrueName);
9341 else if (TrueTy.isNull())
9342 return std::make_pair(x&: FalseTy, y&: FalseName);
9343 else if (FalseTy.isNull())
9344 return std::make_pair(x&: TrueTy, y&: TrueName);
9345 }
9346
9347 return std::make_pair(x: QualType(), y: StringRef());
9348}
9349
9350/// Return true if \p ICE is an implicit argument promotion of an arithmetic
9351/// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9352/// type do not count.
9353static bool isArithmeticArgumentPromotion(Sema &S,
9354 const ImplicitCastExpr *ICE) {
9355 QualType From = ICE->getSubExpr()->getType();
9356 QualType To = ICE->getType();
9357 // It's an integer promotion if the destination type is the promoted
9358 // source type.
9359 if (ICE->getCastKind() == CK_IntegralCast &&
9360 S.Context.isPromotableIntegerType(T: From) &&
9361 S.Context.getPromotedIntegerType(PromotableType: From) == To)
9362 return true;
9363 // Look through vector types, since we do default argument promotion for
9364 // those in OpenCL.
9365 if (const auto *VecTy = From->getAs<ExtVectorType>())
9366 From = VecTy->getElementType();
9367 if (const auto *VecTy = To->getAs<ExtVectorType>())
9368 To = VecTy->getElementType();
9369 // It's a floating promotion if the source type is a lower rank.
9370 return ICE->getCastKind() == CK_FloatingCast &&
9371 S.Context.getFloatingTypeOrder(LHS: From, RHS: To) < 0;
9372}
9373
9374static analyze_format_string::ArgType::MatchKind
9375handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match,
9376 DiagnosticsEngine &Diags, SourceLocation Loc) {
9377 if (Match == analyze_format_string::ArgType::NoMatchSignedness) {
9378 if (Diags.isIgnored(
9379 DiagID: diag::warn_format_conversion_argument_type_mismatch_signedness,
9380 Loc) ||
9381 Diags.isIgnored(
9382 // Arbitrary -Wformat diagnostic to detect -Wno-format:
9383 DiagID: diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9384 return analyze_format_string::ArgType::Match;
9385 }
9386 }
9387 return Match;
9388}
9389
9390bool CheckPrintfHandler::checkFormatExpr(
9391 const analyze_printf::PrintfSpecifier &FS, const char *StartSpecifier,
9392 unsigned SpecifierLen, const Expr *E) {
9393 using namespace analyze_format_string;
9394 using namespace analyze_printf;
9395
9396 // Now type check the data expression that matches the
9397 // format specifier.
9398 const analyze_printf::ArgType &AT = FS.getArgType(Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9399 if (!AT.isValid())
9400 return true;
9401
9402 QualType ExprTy = E->getType();
9403 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(Val&: ExprTy)) {
9404 ExprTy = TET->getUnderlyingExpr()->getType();
9405 }
9406
9407 if (const OverflowBehaviorType *OBT =
9408 dyn_cast<OverflowBehaviorType>(Val: ExprTy.getCanonicalType()))
9409 ExprTy = OBT->getUnderlyingType();
9410
9411 // When using the format attribute in C++, you can receive a function or an
9412 // array that will necessarily decay to a pointer when passed to the final
9413 // format consumer. Apply decay before type comparison.
9414 if (ExprTy->canDecayToPointerType())
9415 ExprTy = S.Context.getDecayedType(T: ExprTy);
9416
9417 // Diagnose attempts to print a boolean value as a character. Unlike other
9418 // -Wformat diagnostics, this is fine from a type perspective, but it still
9419 // doesn't make sense.
9420 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9421 E->isKnownToHaveBooleanValue()) {
9422 const CharSourceRange &CSR =
9423 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9424 SmallString<4> FSString;
9425 llvm::raw_svector_ostream os(FSString);
9426 FS.toString(os);
9427 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_bool_as_character)
9428 << FSString,
9429 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9430 return true;
9431 }
9432
9433 // Diagnose attempts to use '%P' with ObjC object types, which will result in
9434 // dumping raw class data (like is-a pointer), not actual data.
9435 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg &&
9436 ExprTy->isObjCObjectPointerType()) {
9437 const CharSourceRange &CSR =
9438 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9439 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_format_P_with_objc_pointer),
9440 Loc: E->getExprLoc(), IsStringLocation: false, StringRange: CSR);
9441 return true;
9442 }
9443
9444 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9445 return true;
9446
9447 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch;
9448 ArgType::MatchKind Match = AT.matchesType(C&: S.Context, argTy: ExprTy);
9449 ArgType::MatchKind OrigMatch = Match;
9450
9451 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9452 if (Match == ArgType::Match)
9453 return true;
9454
9455 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr
9456 assert(Match != ArgType::NoMatchPromotionTypeConfusion);
9457
9458 // Look through argument promotions for our error message's reported type.
9459 // This includes the integral and floating promotions, but excludes array
9460 // and function pointer decay (seeing that an argument intended to be a
9461 // string has type 'char [6]' is probably more confusing than 'char *') and
9462 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9463 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
9464 if (isArithmeticArgumentPromotion(S, ICE)) {
9465 E = ICE->getSubExpr();
9466 ExprTy = E->getType();
9467
9468 // Check if we didn't match because of an implicit cast from a 'char'
9469 // or 'short' to an 'int'. This is done because printf is a varargs
9470 // function.
9471 if (ICE->getType() == S.Context.IntTy ||
9472 ICE->getType() == S.Context.UnsignedIntTy) {
9473 // All further checking is done on the subexpression
9474 ImplicitMatch = AT.matchesType(C&: S.Context, argTy: ExprTy);
9475 if (OrigMatch == ArgType::NoMatchSignedness &&
9476 ImplicitMatch != ArgType::NoMatchSignedness)
9477 // If the original match was a signedness match this match on the
9478 // implicit cast type also need to be signedness match otherwise we
9479 // might introduce new unexpected warnings from -Wformat-signedness.
9480 return true;
9481 ImplicitMatch = handleFormatSignedness(
9482 Match: ImplicitMatch, Diags&: S.getDiagnostics(), Loc: E->getExprLoc());
9483 if (ImplicitMatch == ArgType::Match)
9484 return true;
9485 }
9486 }
9487 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(Val: E)) {
9488 // Special case for 'a', which has type 'int' in C.
9489 // Note, however, that we do /not/ want to treat multibyte constants like
9490 // 'MooV' as characters! This form is deprecated but still exists. In
9491 // addition, don't treat expressions as of type 'char' if one byte length
9492 // modifier is provided.
9493 if (ExprTy == S.Context.IntTy &&
9494 FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9495 if (llvm::isUIntN(N: S.Context.getCharWidth(), x: CL->getValue())) {
9496 ExprTy = S.Context.CharTy;
9497 // To improve check results, we consider a character literal in C
9498 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is
9499 // more likely a type confusion situation, so we will suggest to
9500 // use '%hhd' instead by discarding the MatchPromotion.
9501 if (Match == ArgType::MatchPromotion)
9502 Match = ArgType::NoMatch;
9503 }
9504 }
9505 if (Match == ArgType::MatchPromotion) {
9506 // WG14 N2562 only clarified promotions in *printf
9507 // For NSLog in ObjC, just preserve -Wformat behavior
9508 if (!S.getLangOpts().ObjC &&
9509 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9510 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9511 return true;
9512 Match = ArgType::NoMatch;
9513 }
9514 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9515 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9516 Match = ImplicitMatch;
9517 assert(Match != ArgType::MatchPromotion);
9518
9519 // Look through unscoped enums to their underlying type.
9520 bool IsEnum = false;
9521 bool IsScopedEnum = false;
9522 QualType IntendedTy = ExprTy;
9523 if (const auto *ED = ExprTy->getAsEnumDecl()) {
9524 IntendedTy = ED->getIntegerType();
9525 if (!ED->isScoped()) {
9526 ExprTy = IntendedTy;
9527 // This controls whether we're talking about the underlying type or not,
9528 // which we only want to do when it's an unscoped enum.
9529 IsEnum = true;
9530 } else {
9531 IsScopedEnum = true;
9532 }
9533 }
9534
9535 // %C in an Objective-C context prints a unichar, not a wchar_t.
9536 // If the argument is an integer of some kind, believe the %C and suggest
9537 // a cast instead of changing the conversion specifier.
9538 if (isObjCContext() &&
9539 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9540 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9541 !ExprTy->isCharType()) {
9542 // 'unichar' is defined as a typedef of unsigned short, but we should
9543 // prefer using the typedef if it is visible.
9544 IntendedTy = S.Context.UnsignedShortTy;
9545
9546 // While we are here, check if the value is an IntegerLiteral that happens
9547 // to be within the valid range.
9548 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(Val: E)) {
9549 const llvm::APInt &V = IL->getValue();
9550 if (V.getActiveBits() <= S.Context.getTypeSize(T: IntendedTy))
9551 return true;
9552 }
9553
9554 LookupResult Result(S, &S.Context.Idents.get(Name: "unichar"), E->getBeginLoc(),
9555 Sema::LookupOrdinaryName);
9556 if (S.LookupName(R&: Result, S: S.getCurScope())) {
9557 NamedDecl *ND = Result.getFoundDecl();
9558 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: ND))
9559 if (TD->getUnderlyingType() == IntendedTy)
9560 IntendedTy =
9561 S.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
9562 /*Qualifier=*/std::nullopt, Decl: TD);
9563 }
9564 }
9565 }
9566
9567 // Special-case some of Darwin's platform-independence types by suggesting
9568 // casts to primitive types that are known to be large enough.
9569 bool ShouldNotPrintDirectly = false;
9570 StringRef CastTyName;
9571 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9572 QualType CastTy;
9573 std::tie(args&: CastTy, args&: CastTyName) =
9574 shouldNotPrintDirectly(Context: S.Context, IntendedTy, E);
9575 if (!CastTy.isNull()) {
9576 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9577 // (long in ASTContext). Only complain to pedants or when they're the
9578 // underlying type of a scoped enum (which always needs a cast).
9579 if (!IsScopedEnum &&
9580 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9581 (AT.isSizeT() || AT.isPtrdiffT()) &&
9582 AT.matchesType(C&: S.Context, argTy: CastTy))
9583 Match = ArgType::NoMatchPedantic;
9584 IntendedTy = CastTy;
9585 ShouldNotPrintDirectly = true;
9586 }
9587 }
9588
9589 // We may be able to offer a FixItHint if it is a supported type.
9590 PrintfSpecifier fixedFS = FS;
9591 bool Success =
9592 fixedFS.fixType(QT: IntendedTy, LangOpt: S.getLangOpts(), Ctx&: S.Context, IsObjCLiteral: isObjCContext());
9593
9594 if (Success) {
9595 // Get the fix string from the fixed format specifier
9596 SmallString<16> buf;
9597 llvm::raw_svector_ostream os(buf);
9598 fixedFS.toString(os);
9599
9600 CharSourceRange SpecRange = getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9601
9602 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9603 unsigned Diag;
9604 switch (Match) {
9605 case ArgType::Match:
9606 case ArgType::MatchPromotion:
9607 case ArgType::NoMatchPromotionTypeConfusion:
9608 llvm_unreachable("expected non-matching");
9609 case ArgType::NoMatchSignedness:
9610 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9611 break;
9612 case ArgType::NoMatchPedantic:
9613 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9614 break;
9615 case ArgType::NoMatchTypeConfusion:
9616 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9617 break;
9618 case ArgType::NoMatch:
9619 Diag = diag::warn_format_conversion_argument_type_mismatch;
9620 break;
9621 }
9622
9623 // In this case, the specifier is wrong and should be changed to match
9624 // the argument.
9625 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
9626 << AT.getRepresentativeTypeName(C&: S.Context)
9627 << IntendedTy << IsEnum << E->getSourceRange(),
9628 Loc: E->getBeginLoc(),
9629 /*IsStringLocation*/ false, StringRange: SpecRange,
9630 FixIt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9631 } else {
9632 // The canonical type for formatting this value is different from the
9633 // actual type of the expression. (This occurs, for example, with Darwin's
9634 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9635 // should be printed as 'long' for 64-bit compatibility.)
9636 // Rather than emitting a normal format/argument mismatch, we want to
9637 // add a cast to the recommended type (and correct the format string
9638 // if necessary). We should also do so for scoped enumerations.
9639 SmallString<16> CastBuf;
9640 llvm::raw_svector_ostream CastFix(CastBuf);
9641 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
9642 IntendedTy.print(OS&: CastFix, Policy: S.Context.getPrintingPolicy());
9643 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
9644
9645 SmallVector<FixItHint, 4> Hints;
9646 ArgType::MatchKind IntendedMatch = AT.matchesType(C&: S.Context, argTy: IntendedTy);
9647 IntendedMatch = handleFormatSignedness(Match: IntendedMatch, Diags&: S.getDiagnostics(),
9648 Loc: E->getExprLoc());
9649 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9650 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: SpecRange, Code: os.str()));
9651
9652 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(Val: E)) {
9653 // If there's already a cast present, just replace it.
9654 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9655 Hints.push_back(Elt: FixItHint::CreateReplacement(RemoveRange: CastRange, Code: CastFix.str()));
9656
9657 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
9658 // If the expression has high enough precedence,
9659 // just write the C-style cast.
9660 Hints.push_back(
9661 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9662 } else {
9663 // Otherwise, add parens around the expression as well as the cast.
9664 CastFix << "(";
9665 Hints.push_back(
9666 Elt: FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: CastFix.str()));
9667
9668 // We don't use getLocForEndOfToken because it returns invalid source
9669 // locations for macro expansions (by design).
9670 SourceLocation EndLoc = S.SourceMgr.getSpellingLoc(Loc: E->getEndLoc());
9671 SourceLocation After = EndLoc.getLocWithOffset(
9672 Offset: Lexer::MeasureTokenLength(Loc: EndLoc, SM: S.SourceMgr, LangOpts: S.LangOpts));
9673 Hints.push_back(Elt: FixItHint::CreateInsertion(InsertionLoc: After, Code: ")"));
9674 }
9675
9676 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9677 // The expression has a type that should not be printed directly.
9678 // We extract the name from the typedef because we don't want to show
9679 // the underlying type in the diagnostic.
9680 StringRef Name;
9681 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>())
9682 Name = TypedefTy->getDecl()->getName();
9683 else
9684 Name = CastTyName;
9685 unsigned Diag = Match == ArgType::NoMatchPedantic
9686 ? diag::warn_format_argument_needs_cast_pedantic
9687 : diag::warn_format_argument_needs_cast;
9688 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag) << Name << IntendedTy << IsEnum
9689 << E->getSourceRange(),
9690 Loc: E->getBeginLoc(), /*IsStringLocation=*/false,
9691 StringRange: SpecRange, FixIt: Hints);
9692 } else {
9693 // In this case, the expression could be printed using a different
9694 // specifier, but we've decided that the specifier is probably correct
9695 // and we should cast instead. Just use the normal warning message.
9696
9697 unsigned Diag =
9698 IsScopedEnum
9699 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9700 : diag::warn_format_conversion_argument_type_mismatch;
9701
9702 EmitFormatDiagnostic(
9703 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9704 << IsEnum << E->getSourceRange(),
9705 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: SpecRange, FixIt: Hints);
9706 }
9707 }
9708 } else {
9709 const CharSourceRange &CSR =
9710 getSpecifierRange(startSpecifier: StartSpecifier, specifierLen: SpecifierLen);
9711 // Since the warning for passing non-POD types to variadic functions
9712 // was deferred until now, we emit a warning for non-POD
9713 // arguments here.
9714 bool EmitTypeMismatch = false;
9715 // Record and complex type arguments cannot be code generated for os_log
9716 // and would crash CodeGen, so they are rejected with a hard error emitted
9717 // after the switch below.
9718 bool EmitOSLogError = false;
9719 switch (S.isValidVarArgType(Ty: ExprTy)) {
9720 case VarArgKind::Valid:
9721 case VarArgKind::ValidInCXX11: {
9722 unsigned Diag;
9723 switch (Match) {
9724 case ArgType::Match:
9725 case ArgType::MatchPromotion:
9726 case ArgType::NoMatchPromotionTypeConfusion:
9727 llvm_unreachable("expected non-matching");
9728 case ArgType::NoMatchSignedness:
9729 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9730 break;
9731 case ArgType::NoMatchPedantic:
9732 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9733 break;
9734 case ArgType::NoMatchTypeConfusion:
9735 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9736 break;
9737 case ArgType::NoMatch:
9738 EmitOSLogError = isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy);
9739 Diag = diag::warn_format_conversion_argument_type_mismatch;
9740 break;
9741 }
9742
9743 if (!EmitOSLogError)
9744 EmitFormatDiagnostic(
9745 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy
9746 << IsEnum << CSR << E->getSourceRange(),
9747 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9748 break;
9749 }
9750 case VarArgKind::Undefined:
9751 case VarArgKind::MSVCUndefined:
9752 if (CallType == VariadicCallType::DoesNotApply) {
9753 EmitTypeMismatch = true;
9754 } else if (isInvalidOSLogArgTypeForCodeGen(FSType, T: ExprTy)) {
9755 // Emit a hard error rather than the -Wnon-pod-varargs warning, which
9756 // does not stop compilation.
9757 EmitOSLogError = true;
9758 } else {
9759 EmitFormatDiagnostic(
9760 PDiag: S.PDiag(DiagID: diag::warn_non_pod_vararg_with_format_string)
9761 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9762 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9763 << E->getSourceRange(),
9764 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9765 checkForCStrMembers(AT, E);
9766 }
9767 break;
9768
9769 case VarArgKind::Invalid:
9770 if (CallType == VariadicCallType::DoesNotApply)
9771 EmitTypeMismatch = true;
9772 else if (ExprTy->isObjCObjectType())
9773 EmitFormatDiagnostic(
9774 PDiag: S.PDiag(DiagID: diag::err_cannot_pass_objc_interface_to_vararg_format)
9775 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9776 << AT.getRepresentativeTypeName(C&: S.Context) << CSR
9777 << E->getSourceRange(),
9778 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9779 else
9780 // FIXME: If this is an initializer list, suggest removing the braces
9781 // or inserting a cast to the target type.
9782 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_cannot_pass_to_vararg_format)
9783 << isa<InitListExpr>(Val: E) << ExprTy << CallType
9784 << AT.getRepresentativeTypeName(C&: S.Context) << E->getSourceRange();
9785 break;
9786 }
9787
9788 if (EmitOSLogError)
9789 EmitFormatDiagnostic(
9790 PDiag: S.PDiag(DiagID: diag::err_format_conversion_argument_type_mismatch)
9791 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << IsEnum
9792 << CSR << E->getSourceRange(),
9793 Loc: E->getBeginLoc(), /*IsStringLocation*/ false, StringRange: CSR);
9794
9795 if (EmitTypeMismatch) {
9796 // The function is not variadic, so we do not generate warnings about
9797 // being allowed to pass that object as a variadic argument. Instead,
9798 // since there are inherently no printf specifiers for types which cannot
9799 // be passed as variadic arguments, emit a plain old specifier mismatch
9800 // argument.
9801 EmitFormatDiagnostic(
9802 PDiag: S.PDiag(DiagID: diag::warn_format_conversion_argument_type_mismatch)
9803 << AT.getRepresentativeTypeName(C&: S.Context) << ExprTy << false
9804 << E->getSourceRange(),
9805 Loc: E->getBeginLoc(), IsStringLocation: false, StringRange: CSR);
9806 }
9807
9808 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9809 "format string specifier index out of range");
9810 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9811 }
9812
9813 return true;
9814}
9815
9816//===--- CHECK: Scanf format string checking ------------------------------===//
9817
9818namespace {
9819
9820class CheckScanfHandler : public CheckFormatHandler {
9821public:
9822 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9823 const Expr *origFormatExpr, FormatStringType type,
9824 unsigned firstDataArg, unsigned numDataArgs,
9825 const char *beg, Sema::FormatArgumentPassingKind APK,
9826 ArrayRef<const Expr *> Args, unsigned formatIdx,
9827 bool inFunctionCall, VariadicCallType CallType,
9828 llvm::SmallBitVector &CheckedVarArgs,
9829 UncoveredArgHandler &UncoveredArg)
9830 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9831 numDataArgs, beg, APK, Args, formatIdx,
9832 inFunctionCall, CallType, CheckedVarArgs,
9833 UncoveredArg) {}
9834
9835 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9836 const char *startSpecifier,
9837 unsigned specifierLen) override;
9838
9839 bool
9840 HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9841 const char *startSpecifier,
9842 unsigned specifierLen) override;
9843
9844 void HandleIncompleteScanList(const char *start, const char *end) override;
9845};
9846
9847} // namespace
9848
9849void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9850 const char *end) {
9851 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_scanlist_incomplete),
9852 Loc: getLocationOfByte(x: end), /*IsStringLocation*/ true,
9853 StringRange: getSpecifierRange(startSpecifier: start, specifierLen: end - start));
9854}
9855
9856bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9857 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9858 unsigned specifierLen) {
9859 const analyze_scanf::ScanfConversionSpecifier &CS =
9860 FS.getConversionSpecifier();
9861
9862 return HandleInvalidConversionSpecifier(
9863 argIndex: FS.getArgIndex(), Loc: getLocationOfByte(x: CS.getStart()), startSpec: startSpecifier,
9864 specifierLen, csStart: CS.getStart(), csLen: CS.getLength());
9865}
9866
9867bool CheckScanfHandler::HandleScanfSpecifier(
9868 const analyze_scanf::ScanfSpecifier &FS, const char *startSpecifier,
9869 unsigned specifierLen) {
9870 using namespace analyze_scanf;
9871 using namespace analyze_format_string;
9872
9873 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9874
9875 // Handle case where '%' and '*' don't consume an argument. These shouldn't
9876 // be used to decide if we are using positional arguments consistently.
9877 if (FS.consumesDataArgument()) {
9878 if (atFirstArg) {
9879 atFirstArg = false;
9880 usesPositionalArgs = FS.usesPositionalArg();
9881 } else if (usesPositionalArgs != FS.usesPositionalArg()) {
9882 HandlePositionalNonpositionalArgs(Loc: getLocationOfByte(x: CS.getStart()),
9883 startSpec: startSpecifier, specifierLen);
9884 return false;
9885 }
9886 }
9887
9888 // Check if the field with is non-zero.
9889 const OptionalAmount &Amt = FS.getFieldWidth();
9890 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9891 if (Amt.getConstantAmount() == 0) {
9892 const CharSourceRange &R =
9893 getSpecifierRange(startSpecifier: Amt.getStart(), specifierLen: Amt.getConstantLength());
9894 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: diag::warn_scanf_nonzero_width),
9895 Loc: getLocationOfByte(x: Amt.getStart()),
9896 /*IsStringLocation*/ true, StringRange: R,
9897 FixIt: FixItHint::CreateRemoval(RemoveRange: R));
9898 }
9899 }
9900
9901 if (!FS.consumesDataArgument()) {
9902 // FIXME: Technically specifying a precision or field width here
9903 // makes no sense. Worth issuing a warning at some point.
9904 return true;
9905 }
9906
9907 // Consume the argument.
9908 unsigned argIndex = FS.getArgIndex();
9909 if (argIndex < NumDataArgs) {
9910 // The check to see if the argIndex is valid will come later.
9911 // We set the bit here because we may exit early from this
9912 // function if we encounter some other error.
9913 CoveredArgs.set(argIndex);
9914 }
9915
9916 // Check the length modifier is valid with the given conversion specifier.
9917 if (!FS.hasValidLengthModifier(Target: S.getASTContext().getTargetInfo(),
9918 LO: S.getLangOpts()))
9919 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9920 DiagID: diag::warn_format_nonsensical_length);
9921 else if (!FS.hasStandardLengthModifier())
9922 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9923 else if (!FS.hasStandardLengthConversionCombination())
9924 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9925 DiagID: diag::warn_format_non_standard_conversion_spec);
9926
9927 if (!FS.hasStandardConversionSpecifier(LangOpt: S.getLangOpts()))
9928 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9929
9930 // The remaining checks depend on the data arguments.
9931 if (!HasFormatArguments())
9932 return true;
9933
9934 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9935 return false;
9936
9937 // Check that the argument type matches the format specifier.
9938 const Expr *Ex = getDataArg(i: argIndex);
9939 if (!Ex)
9940 return true;
9941
9942 const analyze_format_string::ArgType &AT = FS.getArgType(Ctx&: S.Context);
9943
9944 if (!AT.isValid()) {
9945 return true;
9946 }
9947
9948 if (CheckUnsupportedType(AT, E: Ex, StartSpecifier: startSpecifier, SpecifierLen: specifierLen))
9949 return true;
9950
9951 analyze_format_string::ArgType::MatchKind Match =
9952 AT.matchesType(C&: S.Context, argTy: Ex->getType());
9953 Match = handleFormatSignedness(Match, Diags&: S.getDiagnostics(), Loc: Ex->getExprLoc());
9954 if (Match == analyze_format_string::ArgType::Match)
9955 return true;
9956 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9957 bool Signedness = Match == analyze_format_string::ArgType::NoMatchSignedness;
9958
9959 ScanfSpecifier fixedFS = FS;
9960 bool Success = fixedFS.fixType(QT: Ex->getType(), RawQT: Ex->IgnoreImpCasts()->getType(),
9961 LangOpt: S.getLangOpts(), Ctx&: S.Context);
9962
9963 unsigned Diag =
9964 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9965 : Signedness
9966 ? diag::warn_format_conversion_argument_type_mismatch_signedness
9967 : diag::warn_format_conversion_argument_type_mismatch;
9968
9969 if (Success) {
9970 // Get the fix string from the fixed format specifier.
9971 SmallString<128> buf;
9972 llvm::raw_svector_ostream os(buf);
9973 fixedFS.toString(os);
9974
9975 EmitFormatDiagnostic(
9976 PDiag: S.PDiag(DiagID: Diag) << AT.getRepresentativeTypeName(C&: S.Context)
9977 << Ex->getType() << false << Ex->getSourceRange(),
9978 Loc: Ex->getBeginLoc(),
9979 /*IsStringLocation*/ false,
9980 StringRange: getSpecifierRange(startSpecifier, specifierLen),
9981 FixIt: FixItHint::CreateReplacement(
9982 RemoveRange: getSpecifierRange(startSpecifier, specifierLen), Code: os.str()));
9983 } else {
9984 EmitFormatDiagnostic(PDiag: S.PDiag(DiagID: Diag)
9985 << AT.getRepresentativeTypeName(C&: S.Context)
9986 << Ex->getType() << false << Ex->getSourceRange(),
9987 Loc: Ex->getBeginLoc(),
9988 /*IsStringLocation*/ false,
9989 StringRange: getSpecifierRange(startSpecifier, specifierLen));
9990 }
9991
9992 return true;
9993}
9994
9995static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref,
9996 ArrayRef<EquatableFormatArgument> RefArgs,
9997 const StringLiteral *Fmt,
9998 ArrayRef<EquatableFormatArgument> FmtArgs,
9999 const Expr *FmtExpr, bool InFunctionCall) {
10000 bool HadError = false;
10001 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
10002 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
10003 while (FmtIter < FmtEnd && RefIter < RefEnd) {
10004 // In positional-style format strings, the same specifier can appear
10005 // multiple times (like %2$i %2$d). Specifiers in both RefArgs and FmtArgs
10006 // are sorted by getPosition(), and we process each range of equal
10007 // getPosition() values as one group.
10008 // RefArgs are taken from a string literal that was given to
10009 // attribute(format_matches), and if we got this far, we have already
10010 // verified that if it has positional specifiers that appear in multiple
10011 // locations, then they are all mutually compatible. What's left for us to
10012 // do is verify that all specifiers with the same position in FmtArgs are
10013 // compatible with the RefArgs specifiers. We check each specifier from
10014 // FmtArgs against the first member of the RefArgs group.
10015 for (; FmtIter < FmtEnd; ++FmtIter) {
10016 // Clang does not diagnose missing format specifiers in positional-style
10017 // strings (TODO: which it probably should do, as it is UB to skip over a
10018 // format argument). Skip specifiers if needed.
10019 if (FmtIter->getPosition() < RefIter->getPosition())
10020 continue;
10021
10022 // Delimits a new getPosition() value.
10023 if (FmtIter->getPosition() > RefIter->getPosition())
10024 break;
10025
10026 HadError |=
10027 !FmtIter->VerifyCompatible(S, Other: *RefIter, FmtExpr, InFunctionCall);
10028 }
10029
10030 // Jump RefIter to the start of the next group.
10031 RefIter = std::find_if(first: RefIter + 1, last: RefEnd, pred: [=](const auto &Arg) {
10032 return Arg.getPosition() != RefIter->getPosition();
10033 });
10034 }
10035
10036 if (FmtIter < FmtEnd) {
10037 CheckFormatHandler::EmitFormatDiagnostic(
10038 S, InFunctionCall, ArgumentExpr: FmtExpr,
10039 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 1,
10040 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: FmtIter->getSourceRange());
10041 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with) << 1;
10042 } else if (RefIter < RefEnd) {
10043 CheckFormatHandler::EmitFormatDiagnostic(
10044 S, InFunctionCall, ArgumentExpr: FmtExpr,
10045 PDiag: S.PDiag(DiagID: diag::warn_format_cmp_specifier_arity) << 0,
10046 Loc: FmtExpr->getBeginLoc(), IsStringLocation: false, StringRange: Fmt->getSourceRange());
10047 HadError = S.Diag(Loc: Ref->getBeginLoc(), DiagID: diag::note_format_cmp_with)
10048 << 1 << RefIter->getSourceRange();
10049 }
10050 return !HadError;
10051}
10052
10053static void CheckFormatString(
10054 Sema &S, const FormatStringLiteral *FExpr,
10055 const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr,
10056 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK,
10057 unsigned format_idx, unsigned firstDataArg, FormatStringType Type,
10058 bool inFunctionCall, VariadicCallType CallType,
10059 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10060 bool IgnoreStringsWithoutSpecifiers) {
10061 // CHECK: is the format string a wide literal?
10062 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10063 CheckFormatHandler::EmitFormatDiagnostic(
10064 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10065 PDiag: S.PDiag(DiagID: diag::warn_format_string_is_wide_literal), Loc: FExpr->getBeginLoc(),
10066 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
10067 return;
10068 }
10069
10070 // Str - The format string. NOTE: this is NOT null-terminated!
10071 StringRef StrRef = FExpr->getString();
10072 const char *Str = StrRef.data();
10073 // Account for cases where the string literal is truncated in a declaration.
10074 const ConstantArrayType *T =
10075 S.Context.getAsConstantArrayType(T: FExpr->getType());
10076 assert(T && "String literal not of constant array type!");
10077 size_t TypeSize = T->getZExtSize();
10078 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
10079 const unsigned numDataArgs = Args.size() - firstDataArg;
10080
10081 if (IgnoreStringsWithoutSpecifiers &&
10082 !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
10083 Begin: Str, End: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
10084 return;
10085
10086 // Emit a warning if the string literal is truncated and does not contain an
10087 // embedded null character.
10088 if (TypeSize <= StrRef.size() && !StrRef.substr(Start: 0, N: TypeSize).contains(C: '\0')) {
10089 CheckFormatHandler::EmitFormatDiagnostic(
10090 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10091 PDiag: S.PDiag(DiagID: diag::warn_printf_format_string_not_null_terminated),
10092 Loc: FExpr->getBeginLoc(),
10093 /*IsStringLocation=*/true, StringRange: OrigFormatExpr->getSourceRange());
10094 return;
10095 }
10096
10097 // CHECK: empty format string?
10098 if (StrLen == 0 && numDataArgs > 0) {
10099 CheckFormatHandler::EmitFormatDiagnostic(
10100 S, InFunctionCall: inFunctionCall, ArgumentExpr: Args[format_idx],
10101 PDiag: S.PDiag(DiagID: diag::warn_empty_format_string), Loc: FExpr->getBeginLoc(),
10102 /*IsStringLocation*/ true, StringRange: OrigFormatExpr->getSourceRange());
10103 return;
10104 }
10105
10106 if (Type == FormatStringType::Printf || Type == FormatStringType::NSString ||
10107 Type == FormatStringType::Kprintf ||
10108 Type == FormatStringType::FreeBSDKPrintf ||
10109 Type == FormatStringType::OSLog || Type == FormatStringType::OSTrace) {
10110 bool IsObjC =
10111 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10112 if (ReferenceFormatString == nullptr) {
10113 CheckPrintfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10114 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10115 inFunctionCall, CallType, CheckedVarArgs,
10116 UncoveredArg);
10117
10118 if (!analyze_format_string::ParsePrintfString(
10119 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo(),
10120 isFreeBSDKPrintf: Type == FormatStringType::Kprintf ||
10121 Type == FormatStringType::FreeBSDKPrintf))
10122 H.DoneProcessing();
10123 } else {
10124 S.CheckFormatStringsCompatible(
10125 FST: Type, AuthoritativeFormatString: ReferenceFormatString, TestedFormatString: FExpr->getFormatString(),
10126 FunctionCallArg: inFunctionCall ? nullptr : Args[format_idx]);
10127 }
10128 } else if (Type == FormatStringType::Scanf) {
10129 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
10130 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10131 CallType, CheckedVarArgs, UncoveredArg);
10132
10133 if (!analyze_format_string::ParseScanfString(
10134 H, beg: Str, end: Str + StrLen, LO: S.getLangOpts(), Target: S.Context.getTargetInfo()))
10135 H.DoneProcessing();
10136 } // TODO: handle other formats
10137}
10138
10139bool Sema::CheckFormatStringsCompatible(
10140 FormatStringType Type, const StringLiteral *AuthoritativeFormatString,
10141 const StringLiteral *TestedFormatString, const Expr *FunctionCallArg) {
10142 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
10143 Type != FormatStringType::Kprintf &&
10144 Type != FormatStringType::FreeBSDKPrintf &&
10145 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
10146 return true;
10147
10148 bool IsObjC =
10149 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10150 llvm::SmallVector<EquatableFormatArgument, 9> RefArgs, FmtArgs;
10151 FormatStringLiteral RefLit = AuthoritativeFormatString;
10152 FormatStringLiteral TestLit = TestedFormatString;
10153 const Expr *Arg;
10154 bool DiagAtStringLiteral;
10155 if (FunctionCallArg) {
10156 Arg = FunctionCallArg;
10157 DiagAtStringLiteral = false;
10158 } else {
10159 Arg = TestedFormatString;
10160 DiagAtStringLiteral = true;
10161 }
10162 if (DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit,
10163 FmtExpr: AuthoritativeFormatString, Type,
10164 IsObjC, InFunctionCall: true, Args&: RefArgs) &&
10165 DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &TestLit, FmtExpr: Arg, Type, IsObjC,
10166 InFunctionCall: DiagAtStringLiteral, Args&: FmtArgs)) {
10167 return CompareFormatSpecifiers(S&: *this, Ref: AuthoritativeFormatString, RefArgs,
10168 Fmt: TestedFormatString, FmtArgs, FmtExpr: Arg,
10169 InFunctionCall: DiagAtStringLiteral);
10170 }
10171 return false;
10172}
10173
10174bool Sema::ValidateFormatString(FormatStringType Type,
10175 const StringLiteral *Str) {
10176 if (Type != FormatStringType::Printf && Type != FormatStringType::NSString &&
10177 Type != FormatStringType::Kprintf &&
10178 Type != FormatStringType::FreeBSDKPrintf &&
10179 Type != FormatStringType::OSLog && Type != FormatStringType::OSTrace)
10180 return true;
10181
10182 FormatStringLiteral RefLit = Str;
10183 llvm::SmallVector<EquatableFormatArgument, 9> Args;
10184 bool IsObjC =
10185 Type == FormatStringType::NSString || Type == FormatStringType::OSTrace;
10186 if (!DecomposePrintfHandler::GetSpecifiers(S&: *this, FSL: &RefLit, FmtExpr: Str, Type, IsObjC,
10187 InFunctionCall: true, Args))
10188 return false;
10189
10190 // Group arguments by getPosition() value, and check that each member of the
10191 // group is compatible with the first member. This verifies that when
10192 // positional arguments are used multiple times (such as %2$i %2$d), all uses
10193 // are mutually compatible. As an optimization, don't test the first member
10194 // against itself.
10195 bool HadError = false;
10196 auto Iter = Args.begin();
10197 auto End = Args.end();
10198 while (Iter != End) {
10199 const auto &FirstInGroup = *Iter;
10200 for (++Iter;
10201 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10202 ++Iter) {
10203 HadError |= !Iter->VerifyCompatible(S&: *this, Other: FirstInGroup, FmtExpr: Str, InFunctionCall: true);
10204 }
10205 }
10206 return !HadError;
10207}
10208
10209bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
10210 // Str - The format string. NOTE: this is NOT null-terminated!
10211 StringRef StrRef = FExpr->getString();
10212 const char *Str = StrRef.data();
10213 // Account for cases where the string literal is truncated in a declaration.
10214 const ConstantArrayType *T = Context.getAsConstantArrayType(T: FExpr->getType());
10215 assert(T && "String literal not of constant array type!");
10216 size_t TypeSize = T->getZExtSize();
10217 size_t StrLen = std::min(a: std::max(a: TypeSize, b: size_t(1)) - 1, b: StrRef.size());
10218 return analyze_format_string::ParseFormatStringHasSArg(
10219 beg: Str, end: Str + StrLen, LO: getLangOpts(), Target: Context.getTargetInfo());
10220}
10221
10222//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
10223
10224// Returns the related absolute value function that is larger, of 0 if one
10225// does not exist.
10226static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
10227 switch (AbsFunction) {
10228 default:
10229 return 0;
10230
10231 case Builtin::BI__builtin_abs:
10232 return Builtin::BI__builtin_labs;
10233 case Builtin::BI__builtin_labs:
10234 return Builtin::BI__builtin_llabs;
10235 case Builtin::BI__builtin_llabs:
10236 return 0;
10237
10238 case Builtin::BI__builtin_fabsf:
10239 return Builtin::BI__builtin_fabs;
10240 case Builtin::BI__builtin_fabs:
10241 return Builtin::BI__builtin_fabsl;
10242 case Builtin::BI__builtin_fabsl:
10243 return 0;
10244
10245 case Builtin::BI__builtin_cabsf:
10246 return Builtin::BI__builtin_cabs;
10247 case Builtin::BI__builtin_cabs:
10248 return Builtin::BI__builtin_cabsl;
10249 case Builtin::BI__builtin_cabsl:
10250 return 0;
10251
10252 case Builtin::BIabs:
10253 return Builtin::BIlabs;
10254 case Builtin::BIlabs:
10255 return Builtin::BIllabs;
10256 case Builtin::BIllabs:
10257 return 0;
10258
10259 case Builtin::BIfabsf:
10260 return Builtin::BIfabs;
10261 case Builtin::BIfabs:
10262 return Builtin::BIfabsl;
10263 case Builtin::BIfabsl:
10264 return 0;
10265
10266 case Builtin::BIcabsf:
10267 return Builtin::BIcabs;
10268 case Builtin::BIcabs:
10269 return Builtin::BIcabsl;
10270 case Builtin::BIcabsl:
10271 return 0;
10272 }
10273}
10274
10275// Returns the argument type of the absolute value function.
10276static QualType getAbsoluteValueArgumentType(ASTContext &Context,
10277 unsigned AbsType) {
10278 if (AbsType == 0)
10279 return QualType();
10280
10281 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
10282 QualType BuiltinType = Context.GetBuiltinType(ID: AbsType, Error);
10283 if (Error != ASTContext::GE_None)
10284 return QualType();
10285
10286 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
10287 if (!FT)
10288 return QualType();
10289
10290 if (FT->getNumParams() != 1)
10291 return QualType();
10292
10293 return FT->getParamType(i: 0);
10294}
10295
10296// Returns the best absolute value function, or zero, based on type and
10297// current absolute value function.
10298static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
10299 unsigned AbsFunctionKind) {
10300 unsigned BestKind = 0;
10301 uint64_t ArgSize = Context.getTypeSize(T: ArgType);
10302 for (unsigned Kind = AbsFunctionKind; Kind != 0;
10303 Kind = getLargerAbsoluteValueFunction(AbsFunction: Kind)) {
10304 QualType ParamType = getAbsoluteValueArgumentType(Context, AbsType: Kind);
10305 if (Context.getTypeSize(T: ParamType) >= ArgSize) {
10306 if (BestKind == 0)
10307 BestKind = Kind;
10308 else if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
10309 BestKind = Kind;
10310 break;
10311 }
10312 }
10313 }
10314 return BestKind;
10315}
10316
10317enum AbsoluteValueKind {
10318 AVK_Integer,
10319 AVK_Floating,
10320 AVK_Complex
10321};
10322
10323static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
10324 if (T->isIntegralOrEnumerationType())
10325 return AVK_Integer;
10326 if (T->isRealFloatingType())
10327 return AVK_Floating;
10328 if (T->isAnyComplexType())
10329 return AVK_Complex;
10330
10331 llvm_unreachable("Type not integer, floating, or complex");
10332}
10333
10334// Changes the absolute value function to a different type. Preserves whether
10335// the function is a builtin.
10336static unsigned changeAbsFunction(unsigned AbsKind,
10337 AbsoluteValueKind ValueKind) {
10338 switch (ValueKind) {
10339 case AVK_Integer:
10340 switch (AbsKind) {
10341 default:
10342 return 0;
10343 case Builtin::BI__builtin_fabsf:
10344 case Builtin::BI__builtin_fabs:
10345 case Builtin::BI__builtin_fabsl:
10346 case Builtin::BI__builtin_cabsf:
10347 case Builtin::BI__builtin_cabs:
10348 case Builtin::BI__builtin_cabsl:
10349 return Builtin::BI__builtin_abs;
10350 case Builtin::BIfabsf:
10351 case Builtin::BIfabs:
10352 case Builtin::BIfabsl:
10353 case Builtin::BIcabsf:
10354 case Builtin::BIcabs:
10355 case Builtin::BIcabsl:
10356 return Builtin::BIabs;
10357 }
10358 case AVK_Floating:
10359 switch (AbsKind) {
10360 default:
10361 return 0;
10362 case Builtin::BI__builtin_abs:
10363 case Builtin::BI__builtin_labs:
10364 case Builtin::BI__builtin_llabs:
10365 case Builtin::BI__builtin_cabsf:
10366 case Builtin::BI__builtin_cabs:
10367 case Builtin::BI__builtin_cabsl:
10368 return Builtin::BI__builtin_fabsf;
10369 case Builtin::BIabs:
10370 case Builtin::BIlabs:
10371 case Builtin::BIllabs:
10372 case Builtin::BIcabsf:
10373 case Builtin::BIcabs:
10374 case Builtin::BIcabsl:
10375 return Builtin::BIfabsf;
10376 }
10377 case AVK_Complex:
10378 switch (AbsKind) {
10379 default:
10380 return 0;
10381 case Builtin::BI__builtin_abs:
10382 case Builtin::BI__builtin_labs:
10383 case Builtin::BI__builtin_llabs:
10384 case Builtin::BI__builtin_fabsf:
10385 case Builtin::BI__builtin_fabs:
10386 case Builtin::BI__builtin_fabsl:
10387 return Builtin::BI__builtin_cabsf;
10388 case Builtin::BIabs:
10389 case Builtin::BIlabs:
10390 case Builtin::BIllabs:
10391 case Builtin::BIfabsf:
10392 case Builtin::BIfabs:
10393 case Builtin::BIfabsl:
10394 return Builtin::BIcabsf;
10395 }
10396 }
10397 llvm_unreachable("Unable to convert function");
10398}
10399
10400static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10401 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10402 if (!FnInfo)
10403 return 0;
10404
10405 switch (FDecl->getBuiltinID()) {
10406 default:
10407 return 0;
10408 case Builtin::BI__builtin_abs:
10409 case Builtin::BI__builtin_fabs:
10410 case Builtin::BI__builtin_fabsf:
10411 case Builtin::BI__builtin_fabsl:
10412 case Builtin::BI__builtin_labs:
10413 case Builtin::BI__builtin_llabs:
10414 case Builtin::BI__builtin_cabs:
10415 case Builtin::BI__builtin_cabsf:
10416 case Builtin::BI__builtin_cabsl:
10417 case Builtin::BIabs:
10418 case Builtin::BIlabs:
10419 case Builtin::BIllabs:
10420 case Builtin::BIfabs:
10421 case Builtin::BIfabsf:
10422 case Builtin::BIfabsl:
10423 case Builtin::BIcabs:
10424 case Builtin::BIcabsf:
10425 case Builtin::BIcabsl:
10426 return FDecl->getBuiltinID();
10427 }
10428 llvm_unreachable("Unknown Builtin type");
10429}
10430
10431// If the replacement is valid, emit a note with replacement function.
10432// Additionally, suggest including the proper header if not already included.
10433static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10434 unsigned AbsKind, QualType ArgType) {
10435 bool EmitHeaderHint = true;
10436 const char *HeaderName = nullptr;
10437 std::string FunctionName;
10438 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10439 FunctionName = "std::abs";
10440 if (ArgType->isIntegralOrEnumerationType()) {
10441 HeaderName = "cstdlib";
10442 } else if (ArgType->isRealFloatingType()) {
10443 HeaderName = "cmath";
10444 } else {
10445 llvm_unreachable("Invalid Type");
10446 }
10447
10448 // Lookup all std::abs
10449 if (NamespaceDecl *Std = S.getStdNamespace()) {
10450 LookupResult R(S, &S.Context.Idents.get(Name: "abs"), Loc, Sema::LookupAnyName);
10451 R.suppressDiagnostics();
10452 S.LookupQualifiedName(R, LookupCtx: Std);
10453
10454 for (const auto *I : R) {
10455 const FunctionDecl *FDecl = nullptr;
10456 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(Val: I)) {
10457 FDecl = dyn_cast<FunctionDecl>(Val: UsingD->getTargetDecl());
10458 } else {
10459 FDecl = dyn_cast<FunctionDecl>(Val: I);
10460 }
10461 if (!FDecl)
10462 continue;
10463
10464 // Found std::abs(), check that they are the right ones.
10465 if (FDecl->getNumParams() != 1)
10466 continue;
10467
10468 // Check that the parameter type can handle the argument.
10469 QualType ParamType = FDecl->getParamDecl(i: 0)->getType();
10470 if (getAbsoluteValueKind(T: ArgType) == getAbsoluteValueKind(T: ParamType) &&
10471 S.Context.getTypeSize(T: ArgType) <=
10472 S.Context.getTypeSize(T: ParamType)) {
10473 // Found a function, don't need the header hint.
10474 EmitHeaderHint = false;
10475 break;
10476 }
10477 }
10478 }
10479 } else {
10480 FunctionName = S.Context.BuiltinInfo.getName(ID: AbsKind);
10481 HeaderName = S.Context.BuiltinInfo.getHeaderName(ID: AbsKind);
10482
10483 if (HeaderName) {
10484 DeclarationName DN(&S.Context.Idents.get(Name: FunctionName));
10485 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10486 R.suppressDiagnostics();
10487 S.LookupName(R, S: S.getCurScope());
10488
10489 if (R.isSingleResult()) {
10490 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
10491 if (FD && FD->getBuiltinID() == AbsKind) {
10492 EmitHeaderHint = false;
10493 } else {
10494 return;
10495 }
10496 } else if (!R.empty()) {
10497 return;
10498 }
10499 }
10500 }
10501
10502 S.Diag(Loc, DiagID: diag::note_replace_abs_function)
10503 << FunctionName << FixItHint::CreateReplacement(RemoveRange: Range, Code: FunctionName);
10504
10505 if (!HeaderName)
10506 return;
10507
10508 if (!EmitHeaderHint)
10509 return;
10510
10511 S.Diag(Loc, DiagID: diag::note_include_header_or_declare) << HeaderName
10512 << FunctionName;
10513}
10514
10515template <std::size_t StrLen>
10516static bool IsStdFunction(const FunctionDecl *FDecl,
10517 const char (&Str)[StrLen]) {
10518 if (!FDecl)
10519 return false;
10520 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10521 return false;
10522 if (!FDecl->isInStdNamespace())
10523 return false;
10524
10525 return true;
10526}
10527
10528enum class MathCheck { NaN, Inf };
10529static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) {
10530 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10531 return llvm::is_contained(Set: names, Element: calleeName);
10532 };
10533
10534 switch (Check) {
10535 case MathCheck::NaN:
10536 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl",
10537 "__builtin_nanf16", "__builtin_nanf128"});
10538 case MathCheck::Inf:
10539 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl",
10540 "__builtin_inff16", "__builtin_inff128"});
10541 }
10542 llvm_unreachable("unknown MathCheck");
10543}
10544
10545static bool IsInfinityFunction(const FunctionDecl *FDecl) {
10546 if (FDecl->getName() != "infinity")
10547 return false;
10548
10549 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(Val: FDecl)) {
10550 const CXXRecordDecl *RDecl = MDecl->getParent();
10551 if (RDecl->getName() != "numeric_limits")
10552 return false;
10553
10554 if (const NamespaceDecl *NSDecl =
10555 dyn_cast<NamespaceDecl>(Val: RDecl->getDeclContext()))
10556 return NSDecl->isStdNamespace();
10557 }
10558
10559 return false;
10560}
10561
10562void Sema::CheckInfNaNFunction(const CallExpr *Call,
10563 const FunctionDecl *FDecl) {
10564 if (!FDecl->getIdentifier())
10565 return;
10566
10567 FPOptions FPO = Call->getFPFeaturesInEffect(LO: getLangOpts());
10568 if (FPO.getNoHonorNaNs() &&
10569 (IsStdFunction(FDecl, Str: "isnan") || IsStdFunction(FDecl, Str: "isunordered") ||
10570 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::NaN))) {
10571 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10572 << 1 << 0 << Call->getSourceRange();
10573 return;
10574 }
10575
10576 if (FPO.getNoHonorInfs() &&
10577 (IsStdFunction(FDecl, Str: "isinf") || IsStdFunction(FDecl, Str: "isfinite") ||
10578 IsInfinityFunction(FDecl) ||
10579 IsInfOrNanFunction(calleeName: FDecl->getName(), Check: MathCheck::Inf))) {
10580 Diag(Loc: Call->getBeginLoc(), DiagID: diag::warn_fp_nan_inf_when_disabled)
10581 << 0 << 0 << Call->getSourceRange();
10582 }
10583}
10584
10585void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10586 const FunctionDecl *FDecl) {
10587 if (Call->getNumArgs() != 1)
10588 return;
10589
10590 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10591 bool IsStdAbs = IsStdFunction(FDecl, Str: "abs");
10592 if (AbsKind == 0 && !IsStdAbs)
10593 return;
10594
10595 QualType ArgType = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
10596 QualType ParamType = Call->getArg(Arg: 0)->getType();
10597
10598 // Unsigned types cannot be negative. Suggest removing the absolute value
10599 // function call.
10600 if (ArgType->isUnsignedIntegerType()) {
10601 std::string FunctionName =
10602 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(ID: AbsKind);
10603 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_unsigned_abs) << ArgType << ParamType;
10604 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_abs)
10605 << FunctionName
10606 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange());
10607 return;
10608 }
10609
10610 // Taking the absolute value of a pointer is very suspicious, they probably
10611 // wanted to index into an array, dereference a pointer, call a function, etc.
10612 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10613 unsigned DiagType = 0;
10614 if (ArgType->isFunctionType())
10615 DiagType = 1;
10616 else if (ArgType->isArrayType())
10617 DiagType = 2;
10618
10619 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_pointer_abs) << DiagType << ArgType;
10620 return;
10621 }
10622
10623 // std::abs has overloads which prevent most of the absolute value problems
10624 // from occurring.
10625 if (IsStdAbs)
10626 return;
10627
10628 // Prevent reaching unreachable code in getAbsoluteValueKind for unsupported
10629 // types.
10630 if (!ArgType->isIntegralOrEnumerationType() &&
10631 !ArgType->isRealFloatingType() && !ArgType->isAnyComplexType())
10632 return;
10633
10634 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(T: ArgType);
10635 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(T: ParamType);
10636
10637 // The argument and parameter are the same kind. Check if they are the right
10638 // size.
10639 if (ArgValueKind == ParamValueKind) {
10640 if (Context.getTypeSize(T: ArgType) <= Context.getTypeSize(T: ParamType))
10641 return;
10642
10643 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: AbsKind);
10644 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_abs_too_small)
10645 << FDecl << ArgType << ParamType;
10646
10647 if (NewAbsKind == 0)
10648 return;
10649
10650 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10651 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10652 return;
10653 }
10654
10655 // ArgValueKind != ParamValueKind
10656 // The wrong type of absolute value function was used. Attempt to find the
10657 // proper one.
10658 unsigned NewAbsKind = changeAbsFunction(AbsKind, ValueKind: ArgValueKind);
10659 NewAbsKind = getBestAbsFunction(Context, ArgType, AbsFunctionKind: NewAbsKind);
10660 if (NewAbsKind == 0)
10661 return;
10662
10663 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_wrong_absolute_value_type)
10664 << FDecl << ParamValueKind << ArgValueKind;
10665
10666 emitReplacement(S&: *this, Loc: Call->getExprLoc(),
10667 Range: Call->getCallee()->getSourceRange(), AbsKind: NewAbsKind, ArgType);
10668}
10669
10670//===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10671void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10672 const FunctionDecl *FDecl) {
10673 if (!Call || !FDecl) return;
10674
10675 // Ignore template specializations and macros.
10676 if (inTemplateInstantiation()) return;
10677 if (Call->getExprLoc().isMacroID()) return;
10678
10679 // Only care about the one template argument, two function parameter std::max
10680 if (Call->getNumArgs() != 2) return;
10681 if (!IsStdFunction(FDecl, Str: "max")) return;
10682 const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10683 if (!ArgList) return;
10684 if (ArgList->size() != 1) return;
10685
10686 // Check that template type argument is unsigned integer.
10687 const auto& TA = ArgList->get(Idx: 0);
10688 if (TA.getKind() != TemplateArgument::Type) return;
10689 QualType ArgType = TA.getAsType();
10690 if (!ArgType->isUnsignedIntegerType()) return;
10691
10692 // See if either argument is a literal zero.
10693 auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10694 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E);
10695 if (!MTE) return false;
10696 const auto *Num = dyn_cast<IntegerLiteral>(Val: MTE->getSubExpr());
10697 if (!Num) return false;
10698 if (Num->getValue() != 0) return false;
10699 return true;
10700 };
10701
10702 const Expr *FirstArg = Call->getArg(Arg: 0);
10703 const Expr *SecondArg = Call->getArg(Arg: 1);
10704 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10705 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10706
10707 // Only warn when exactly one argument is zero.
10708 if (IsFirstArgZero == IsSecondArgZero) return;
10709
10710 SourceRange FirstRange = FirstArg->getSourceRange();
10711 SourceRange SecondRange = SecondArg->getSourceRange();
10712
10713 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10714
10715 Diag(Loc: Call->getExprLoc(), DiagID: diag::warn_max_unsigned_zero)
10716 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10717
10718 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10719 SourceRange RemovalRange;
10720 if (IsFirstArgZero) {
10721 RemovalRange = SourceRange(FirstRange.getBegin(),
10722 SecondRange.getBegin().getLocWithOffset(Offset: -1));
10723 } else {
10724 RemovalRange = SourceRange(getLocForEndOfToken(Loc: FirstRange.getEnd()),
10725 SecondRange.getEnd());
10726 }
10727
10728 Diag(Loc: Call->getExprLoc(), DiagID: diag::note_remove_max_call)
10729 << FixItHint::CreateRemoval(RemoveRange: Call->getCallee()->getSourceRange())
10730 << FixItHint::CreateRemoval(RemoveRange: RemovalRange);
10731}
10732
10733//===--- CHECK: Standard memory functions ---------------------------------===//
10734
10735/// Takes the expression passed to the size_t parameter of functions
10736/// such as memcmp, strncat, etc and warns if it's a comparison.
10737///
10738/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10739static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10740 const IdentifierInfo *FnName,
10741 SourceLocation FnLoc,
10742 SourceLocation RParenLoc) {
10743 const auto *Size = dyn_cast<BinaryOperator>(Val: E);
10744 if (!Size)
10745 return false;
10746
10747 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10748 if (!Size->isComparisonOp() && !Size->isLogicalOp())
10749 return false;
10750
10751 SourceRange SizeRange = Size->getSourceRange();
10752 S.Diag(Loc: Size->getOperatorLoc(), DiagID: diag::warn_memsize_comparison)
10753 << SizeRange << FnName;
10754 S.Diag(Loc: FnLoc, DiagID: diag::note_memsize_comparison_paren)
10755 << FnName
10756 << FixItHint::CreateInsertion(
10757 InsertionLoc: S.getLocForEndOfToken(Loc: Size->getLHS()->getEndLoc()), Code: ")")
10758 << FixItHint::CreateRemoval(RemoveRange: RParenLoc);
10759 S.Diag(Loc: SizeRange.getBegin(), DiagID: diag::note_memsize_comparison_cast_silence)
10760 << FixItHint::CreateInsertion(InsertionLoc: SizeRange.getBegin(), Code: "(size_t)(")
10761 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: SizeRange.getEnd()),
10762 Code: ")");
10763
10764 return true;
10765}
10766
10767/// Determine whether the given type is or contains a dynamic class type
10768/// (e.g., whether it has a vtable).
10769static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10770 bool &IsContained) {
10771 // Look through array types while ignoring qualifiers.
10772 const Type *Ty = T->getBaseElementTypeUnsafe();
10773 IsContained = false;
10774
10775 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10776 RD = RD ? RD->getDefinition() : nullptr;
10777 if (!RD || RD->isInvalidDecl())
10778 return nullptr;
10779
10780 if (RD->isDynamicClass())
10781 return RD;
10782
10783 // Check all the fields. If any bases were dynamic, the class is dynamic.
10784 // It's impossible for a class to transitively contain itself by value, so
10785 // infinite recursion is impossible.
10786 for (auto *FD : RD->fields()) {
10787 bool SubContained;
10788 if (const CXXRecordDecl *ContainedRD =
10789 getContainedDynamicClass(T: FD->getType(), IsContained&: SubContained)) {
10790 IsContained = true;
10791 return ContainedRD;
10792 }
10793 }
10794
10795 return nullptr;
10796}
10797
10798static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10799 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: E))
10800 if (Unary->getKind() == UETT_SizeOf)
10801 return Unary;
10802 return nullptr;
10803}
10804
10805/// If E is a sizeof expression, returns its argument expression,
10806/// otherwise returns NULL.
10807static const Expr *getSizeOfExprArg(const Expr *E) {
10808 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10809 if (!SizeOf->isArgumentType())
10810 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10811 return nullptr;
10812}
10813
10814/// If E is a sizeof expression, returns its argument type.
10815static QualType getSizeOfArgType(const Expr *E) {
10816 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10817 return SizeOf->getTypeOfArgument();
10818 return QualType();
10819}
10820
10821namespace {
10822
10823struct SearchNonTrivialToInitializeField
10824 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10825 using Super =
10826 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10827
10828 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10829
10830 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10831 SourceLocation SL) {
10832 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
10833 asDerived().visitArray(PDIK, AT, SL);
10834 return;
10835 }
10836
10837 Super::visitWithKind(PDIK, FT, Args&: SL);
10838 }
10839
10840 void visitARCStrong(QualType FT, SourceLocation SL) {
10841 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
10842 }
10843 void visitARCWeak(QualType FT, SourceLocation SL) {
10844 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 1);
10845 }
10846 void visitStruct(QualType FT, SourceLocation SL) {
10847 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10848 visit(FT: FD->getType(), Args: FD->getLocation());
10849 }
10850 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10851 const ArrayType *AT, SourceLocation SL) {
10852 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
10853 }
10854 void visitTrivial(QualType FT, SourceLocation SL) {}
10855
10856 static void diag(QualType RT, const Expr *E, Sema &S) {
10857 SearchNonTrivialToInitializeField(E, S).visitStruct(FT: RT, SL: SourceLocation());
10858 }
10859
10860 ASTContext &getContext() { return S.getASTContext(); }
10861
10862 const Expr *E;
10863 Sema &S;
10864};
10865
10866struct SearchNonTrivialToCopyField
10867 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10868 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10869
10870 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10871
10872 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10873 SourceLocation SL) {
10874 if (const auto *AT = asDerived().getContext().getAsArrayType(T: FT)) {
10875 asDerived().visitArray(PCK, AT, SL);
10876 return;
10877 }
10878
10879 Super::visitWithKind(PCK, FT, Args&: SL);
10880 }
10881
10882 void visitARCStrong(QualType FT, SourceLocation SL) {
10883 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10884 }
10885 void visitARCWeak(QualType FT, SourceLocation SL) {
10886 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10887 }
10888 void visitPtrAuth(QualType FT, SourceLocation SL) {
10889 S.DiagRuntimeBehavior(Loc: SL, Statement: E, PD: S.PDiag(DiagID: diag::note_nontrivial_field) << 0);
10890 }
10891 void visitStruct(QualType FT, SourceLocation SL) {
10892 for (const FieldDecl *FD : FT->castAsRecordDecl()->fields())
10893 visit(FT: FD->getType(), Args: FD->getLocation());
10894 }
10895 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10896 SourceLocation SL) {
10897 visit(FT: getContext().getBaseElementType(VAT: AT), Args&: SL);
10898 }
10899 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10900 SourceLocation SL) {}
10901 void visitTrivial(QualType FT, SourceLocation SL) {}
10902 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10903
10904 static void diag(QualType RT, const Expr *E, Sema &S) {
10905 SearchNonTrivialToCopyField(E, S).visitStruct(FT: RT, SL: SourceLocation());
10906 }
10907
10908 ASTContext &getContext() { return S.getASTContext(); }
10909
10910 const Expr *E;
10911 Sema &S;
10912};
10913
10914}
10915
10916/// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10917static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10918 SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10919
10920 if (const auto *BO = dyn_cast<BinaryOperator>(Val: SizeofExpr)) {
10921 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10922 return false;
10923
10924 return doesExprLikelyComputeSize(SizeofExpr: BO->getLHS()) ||
10925 doesExprLikelyComputeSize(SizeofExpr: BO->getRHS());
10926 }
10927
10928 return getAsSizeOfExpr(E: SizeofExpr) != nullptr;
10929}
10930
10931/// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10932///
10933/// \code
10934/// #define MACRO 0
10935/// foo(MACRO);
10936/// foo(0);
10937/// \endcode
10938///
10939/// This should return true for the first call to foo, but not for the second
10940/// (regardless of whether foo is a macro or function).
10941static bool isArgumentExpandedFromMacro(SourceManager &SM,
10942 SourceLocation CallLoc,
10943 SourceLocation ArgLoc) {
10944 if (!CallLoc.isMacroID())
10945 return SM.getFileID(SpellingLoc: CallLoc) != SM.getFileID(SpellingLoc: ArgLoc);
10946
10947 return SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: CallLoc)) !=
10948 SM.getFileID(SpellingLoc: SM.getImmediateMacroCallerLoc(Loc: ArgLoc));
10949}
10950
10951/// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10952/// last two arguments transposed.
10953static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10954 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10955 return;
10956
10957 const Expr *SizeArg =
10958 Call->getArg(Arg: BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10959
10960 auto isLiteralZero = [](const Expr *E) {
10961 return (isa<IntegerLiteral>(Val: E) &&
10962 cast<IntegerLiteral>(Val: E)->getValue() == 0) ||
10963 (isa<CharacterLiteral>(Val: E) &&
10964 cast<CharacterLiteral>(Val: E)->getValue() == 0);
10965 };
10966
10967 // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10968 SourceLocation CallLoc = Call->getRParenLoc();
10969 SourceManager &SM = S.getSourceManager();
10970 if (isLiteralZero(SizeArg) &&
10971 !isArgumentExpandedFromMacro(SM, CallLoc, ArgLoc: SizeArg->getExprLoc())) {
10972
10973 SourceLocation DiagLoc = SizeArg->getExprLoc();
10974
10975 // Some platforms #define bzero to __builtin_memset. See if this is the
10976 // case, and if so, emit a better diagnostic.
10977 if (BId == Builtin::BIbzero ||
10978 (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10979 Loc: CallLoc, SM, LangOpts: S.getLangOpts()) == "bzero")) {
10980 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_bzero_size);
10981 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_bzero_size_silence);
10982 } else if (!isLiteralZero(Call->getArg(Arg: 1)->IgnoreImpCasts())) {
10983 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 0;
10984 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 0;
10985 }
10986 return;
10987 }
10988
10989 // If the second argument to a memset is a sizeof expression and the third
10990 // isn't, this is also likely an error. This should catch
10991 // 'memset(buf, sizeof(buf), 0xff)'.
10992 if (BId == Builtin::BImemset &&
10993 doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 1)) &&
10994 !doesExprLikelyComputeSize(SizeofExpr: Call->getArg(Arg: 2))) {
10995 SourceLocation DiagLoc = Call->getArg(Arg: 1)->getExprLoc();
10996 S.Diag(Loc: DiagLoc, DiagID: diag::warn_suspicious_sizeof_memset) << 1;
10997 S.Diag(Loc: DiagLoc, DiagID: diag::note_suspicious_sizeof_memset_silence) << 1;
10998 return;
10999 }
11000}
11001
11002void Sema::CheckMemaccessArguments(const CallExpr *Call,
11003 unsigned BId,
11004 IdentifierInfo *FnName) {
11005 assert(BId != 0);
11006
11007 // It is possible to have a non-standard definition of memset. Validate
11008 // we have enough arguments, and if not, abort further checking.
11009 unsigned ExpectedNumArgs =
11010 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11011 if (Call->getNumArgs() < ExpectedNumArgs)
11012 return;
11013
11014 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11015 BId == Builtin::BIstrndup ? 1 : 2);
11016 unsigned LenArg =
11017 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11018 const Expr *LenExpr = Call->getArg(Arg: LenArg)->IgnoreParenImpCasts();
11019
11020 if (CheckMemorySizeofForComparison(S&: *this, E: LenExpr, FnName,
11021 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
11022 return;
11023
11024 // Catch cases like 'memset(buf, sizeof(buf), 0)'.
11025 CheckMemaccessSize(S&: *this, BId, Call);
11026
11027 // We have special checking when the length is a sizeof expression.
11028 QualType SizeOfArgTy = getSizeOfArgType(E: LenExpr);
11029
11030 // Although widely used, 'bzero' is not a standard function. Be more strict
11031 // with the argument types before allowing diagnostics and only allow the
11032 // form bzero(ptr, sizeof(...)).
11033 QualType FirstArgTy = Call->getArg(Arg: 0)->IgnoreParenImpCasts()->getType();
11034 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
11035 return;
11036
11037 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11038 const Expr *Dest = Call->getArg(Arg: ArgIdx)->IgnoreParenImpCasts();
11039 SourceRange ArgRange = Call->getArg(Arg: ArgIdx)->getSourceRange();
11040
11041 QualType DestTy = Dest->getType();
11042 QualType PointeeTy;
11043 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
11044 PointeeTy = DestPtrTy->getPointeeType();
11045
11046 // Never warn about void type pointers. This can be used to suppress
11047 // false positives.
11048 if (PointeeTy->isVoidType())
11049 continue;
11050
11051 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
11052 // actually comparing the expressions for equality. Because computing the
11053 // expression IDs can be expensive, we only do this if the diagnostic is
11054 // enabled.
11055 if (CheckSizeofMemaccessArgument(SizeOfArg: LenExpr, Dest, FnName))
11056 break;
11057
11058 // Also check for cases where the sizeof argument is the exact same
11059 // type as the memory argument, and where it points to a user-defined
11060 // record type.
11061 if (SizeOfArgTy != QualType()) {
11062 if (PointeeTy->isRecordType() &&
11063 Context.typesAreCompatible(T1: SizeOfArgTy, T2: DestTy)) {
11064 DiagRuntimeBehavior(Loc: LenExpr->getExprLoc(), Statement: Dest,
11065 PD: PDiag(DiagID: diag::warn_sizeof_pointer_type_memaccess)
11066 << FnName << SizeOfArgTy << ArgIdx
11067 << PointeeTy << Dest->getSourceRange()
11068 << LenExpr->getSourceRange());
11069 break;
11070 }
11071 }
11072 } else if (DestTy->isArrayType()) {
11073 PointeeTy = DestTy;
11074 }
11075
11076 if (PointeeTy == QualType())
11077 continue;
11078
11079 // Always complain about dynamic classes.
11080 bool IsContained;
11081 if (const CXXRecordDecl *ContainedRD =
11082 getContainedDynamicClass(T: PointeeTy, IsContained)) {
11083
11084 unsigned OperationType = 0;
11085 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11086 // "overwritten" if we're warning about the destination for any call
11087 // but memcmp; otherwise a verb appropriate to the call.
11088 if (ArgIdx != 0 || IsCmp) {
11089 if (BId == Builtin::BImemcpy)
11090 OperationType = 1;
11091 else if(BId == Builtin::BImemmove)
11092 OperationType = 2;
11093 else if (IsCmp)
11094 OperationType = 3;
11095 }
11096
11097 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11098 PD: PDiag(DiagID: diag::warn_dyn_class_memaccess)
11099 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11100 << IsContained << ContainedRD << OperationType
11101 << Call->getCallee()->getSourceRange());
11102 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
11103 BId != Builtin::BImemset)
11104 DiagRuntimeBehavior(
11105 Loc: Dest->getExprLoc(), Statement: Dest,
11106 PD: PDiag(DiagID: diag::warn_arc_object_memaccess)
11107 << ArgIdx << FnName << PointeeTy
11108 << Call->getCallee()->getSourceRange());
11109 else if (const auto *RD = PointeeTy->getAsRecordDecl()) {
11110
11111 // FIXME: Do not consider incomplete types even though they may be
11112 // completed later. GCC does not diagnose such code, but we may want to
11113 // consider diagnosing it in the future, perhaps under a different, but
11114 // related, diagnostic group.
11115 bool NonTriviallyCopyableCXXRecord =
11116 getLangOpts().CPlusPlus && RD->isCompleteDefinition() &&
11117 !PointeeTy.isTriviallyCopyableType(Context);
11118
11119 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11120 RD->isNonTrivialToPrimitiveDefaultInitialize()) {
11121 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11122 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
11123 << ArgIdx << FnName << PointeeTy << 0);
11124 SearchNonTrivialToInitializeField::diag(RT: PointeeTy, E: Dest, S&: *this);
11125 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11126 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11127 // FIXME: Limiting this warning to dest argument until we decide
11128 // whether it's valid for source argument too.
11129 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11130 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
11131 << FnName << PointeeTy);
11132 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11133 RD->isNonTrivialToPrimitiveCopy()) {
11134 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11135 PD: PDiag(DiagID: diag::warn_cstruct_memaccess)
11136 << ArgIdx << FnName << PointeeTy << 1);
11137 SearchNonTrivialToCopyField::diag(RT: PointeeTy, E: Dest, S&: *this);
11138 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11139 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11140 // FIXME: Limiting this warning to dest argument until we decide
11141 // whether it's valid for source argument too.
11142 DiagRuntimeBehavior(Loc: Dest->getExprLoc(), Statement: Dest,
11143 PD: PDiag(DiagID: diag::warn_cxxstruct_memaccess)
11144 << FnName << PointeeTy);
11145 } else {
11146 continue;
11147 }
11148 } else
11149 continue;
11150
11151 DiagRuntimeBehavior(
11152 Loc: Dest->getExprLoc(), Statement: Dest,
11153 PD: PDiag(DiagID: diag::note_bad_memaccess_silence)
11154 << FixItHint::CreateInsertion(InsertionLoc: ArgRange.getBegin(), Code: "(void*)"));
11155 break;
11156 }
11157}
11158
11159bool Sema::CheckSizeofMemaccessArgument(const Expr *LenExpr, const Expr *Dest,
11160 IdentifierInfo *FnName) {
11161 llvm::FoldingSetNodeID SizeOfArgID;
11162 const Expr *SizeOfArg = getSizeOfExprArg(E: LenExpr);
11163 if (!SizeOfArg)
11164 return false;
11165 // Computing this warning is expensive, so we only do so if the warning is
11166 // enabled.
11167 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess,
11168 Loc: SizeOfArg->getExprLoc()))
11169 return false;
11170 QualType DestTy = Dest->getType();
11171 const PointerType *DestPtrTy = DestTy->getAs<PointerType>();
11172 if (!DestPtrTy)
11173 return false;
11174
11175 QualType PointeeTy = DestPtrTy->getPointeeType();
11176
11177 if (SizeOfArgID == llvm::FoldingSetNodeID())
11178 SizeOfArg->Profile(ID&: SizeOfArgID, Context, Canonical: true);
11179
11180 llvm::FoldingSetNodeID DestID;
11181 Dest->Profile(ID&: DestID, Context, Canonical: true);
11182 if (DestID == SizeOfArgID) {
11183 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
11184 // over sizeof(src) as well.
11185 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
11186 StringRef ReadableName = FnName->getName();
11187
11188 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Val: Dest);
11189 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11190 ActionIdx = 1; // If its an address-of operator, just remove it.
11191 if (!PointeeTy->isIncompleteType() &&
11192 (Context.getTypeSize(T: PointeeTy) == Context.getCharWidth()))
11193 ActionIdx = 2; // If the pointee's size is sizeof(char),
11194 // suggest an explicit length.
11195
11196 // If the function is defined as a builtin macro, do not show macro
11197 // expansion.
11198 SourceLocation SL = SizeOfArg->getExprLoc();
11199 SourceRange DSR = Dest->getSourceRange();
11200 SourceRange SSR = SizeOfArg->getSourceRange();
11201 SourceManager &SM = getSourceManager();
11202
11203 if (SM.isMacroArgExpansion(Loc: SL)) {
11204 ReadableName = Lexer::getImmediateMacroName(Loc: SL, SM, LangOpts);
11205 SL = SM.getSpellingLoc(Loc: SL);
11206 DSR = SourceRange(SM.getSpellingLoc(Loc: DSR.getBegin()),
11207 SM.getSpellingLoc(Loc: DSR.getEnd()));
11208 SSR = SourceRange(SM.getSpellingLoc(Loc: SSR.getBegin()),
11209 SM.getSpellingLoc(Loc: SSR.getEnd()));
11210 }
11211
11212 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
11213 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess)
11214 << ReadableName << PointeeTy << DestTy << DSR
11215 << SSR);
11216 DiagRuntimeBehavior(Loc: SL, Statement: SizeOfArg,
11217 PD: PDiag(DiagID: diag::warn_sizeof_pointer_expr_memaccess_note)
11218 << ActionIdx << SSR);
11219 return true;
11220 }
11221 return false;
11222}
11223
11224// A little helper routine: ignore addition and subtraction of integer literals.
11225// This intentionally does not ignore all integer constant expressions because
11226// we don't want to remove sizeof().
11227static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
11228 Ex = Ex->IgnoreParenCasts();
11229
11230 while (true) {
11231 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Val: Ex);
11232 if (!BO || !BO->isAdditiveOp())
11233 break;
11234
11235 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
11236 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
11237
11238 if (isa<IntegerLiteral>(Val: RHS))
11239 Ex = LHS;
11240 else if (isa<IntegerLiteral>(Val: LHS))
11241 Ex = RHS;
11242 else
11243 break;
11244 }
11245
11246 return Ex;
11247}
11248
11249static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
11250 ASTContext &Context) {
11251 // Only handle constant-sized or VLAs, but not flexible members.
11252 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T: Ty)) {
11253 // Only issue the FIXIT for arrays of size > 1.
11254 if (CAT->getZExtSize() <= 1)
11255 return false;
11256 } else if (!Ty->isVariableArrayType()) {
11257 return false;
11258 }
11259 return true;
11260}
11261
11262void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
11263 IdentifierInfo *FnName) {
11264
11265 // Don't crash if the user has the wrong number of arguments
11266 unsigned NumArgs = Call->getNumArgs();
11267 if ((NumArgs != 3) && (NumArgs != 4))
11268 return;
11269
11270 const Expr *SrcArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 1), Ctx&: Context);
11271 const Expr *SizeArg = ignoreLiteralAdditions(Ex: Call->getArg(Arg: 2), Ctx&: Context);
11272 const Expr *CompareWithSrc = nullptr;
11273
11274 if (CheckMemorySizeofForComparison(S&: *this, E: SizeArg, FnName,
11275 FnLoc: Call->getBeginLoc(), RParenLoc: Call->getRParenLoc()))
11276 return;
11277
11278 // Look for 'strlcpy(dst, x, sizeof(x))'
11279 if (const Expr *Ex = getSizeOfExprArg(E: SizeArg))
11280 CompareWithSrc = Ex;
11281 else {
11282 // Look for 'strlcpy(dst, x, strlen(x))'
11283 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(Val: SizeArg)) {
11284 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11285 SizeCall->getNumArgs() == 1)
11286 CompareWithSrc = ignoreLiteralAdditions(Ex: SizeCall->getArg(Arg: 0), Ctx&: Context);
11287 }
11288 }
11289
11290 if (!CompareWithSrc)
11291 return;
11292
11293 // Determine if the argument to sizeof/strlen is equal to the source
11294 // argument. In principle there's all kinds of things you could do
11295 // here, for instance creating an == expression and evaluating it with
11296 // EvaluateAsBooleanCondition, but this uses a more direct technique:
11297 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(Val: SrcArg);
11298 if (!SrcArgDRE)
11299 return;
11300
11301 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(Val: CompareWithSrc);
11302 if (!CompareWithSrcDRE ||
11303 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
11304 return;
11305
11306 const Expr *OriginalSizeArg = Call->getArg(Arg: 2);
11307 Diag(Loc: CompareWithSrcDRE->getBeginLoc(), DiagID: diag::warn_strlcpycat_wrong_size)
11308 << OriginalSizeArg->getSourceRange() << FnName;
11309
11310 // Output a FIXIT hint if the destination is an array (rather than a
11311 // pointer to an array). This could be enhanced to handle some
11312 // pointers if we know the actual size, like if DstArg is 'array+2'
11313 // we could say 'sizeof(array)-2'.
11314 const Expr *DstArg = Call->getArg(Arg: 0)->IgnoreParenImpCasts();
11315 if (!isConstantSizeArrayWithMoreThanOneElement(Ty: DstArg->getType(), Context))
11316 return;
11317
11318 SmallString<128> sizeString;
11319 llvm::raw_svector_ostream OS(sizeString);
11320 OS << "sizeof(";
11321 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11322 OS << ")";
11323
11324 Diag(Loc: OriginalSizeArg->getBeginLoc(), DiagID: diag::note_strlcpycat_wrong_size)
11325 << FixItHint::CreateReplacement(RemoveRange: OriginalSizeArg->getSourceRange(),
11326 Code: OS.str());
11327}
11328
11329/// Check if two expressions refer to the same declaration.
11330static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
11331 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(Val: E1))
11332 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(Val: E2))
11333 return D1->getDecl() == D2->getDecl();
11334 return false;
11335}
11336
11337static const Expr *getStrlenExprArg(const Expr *E) {
11338 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
11339 const FunctionDecl *FD = CE->getDirectCallee();
11340 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
11341 return nullptr;
11342 return CE->getArg(Arg: 0)->IgnoreParenCasts();
11343 }
11344 return nullptr;
11345}
11346
11347void Sema::CheckStrncatArguments(const CallExpr *CE,
11348 const IdentifierInfo *FnName) {
11349 // Don't crash if the user has the wrong number of arguments.
11350 if (CE->getNumArgs() < 3)
11351 return;
11352 const Expr *DstArg = CE->getArg(Arg: 0)->IgnoreParenCasts();
11353 const Expr *SrcArg = CE->getArg(Arg: 1)->IgnoreParenCasts();
11354 const Expr *LenArg = CE->getArg(Arg: 2)->IgnoreParenCasts();
11355
11356 if (CheckMemorySizeofForComparison(S&: *this, E: LenArg, FnName, FnLoc: CE->getBeginLoc(),
11357 RParenLoc: CE->getRParenLoc()))
11358 return;
11359
11360 // Identify common expressions, which are wrongly used as the size argument
11361 // to strncat and may lead to buffer overflows.
11362 unsigned PatternType = 0;
11363 if (const Expr *SizeOfArg = getSizeOfExprArg(E: LenArg)) {
11364 // - sizeof(dst)
11365 if (referToTheSameDecl(E1: SizeOfArg, E2: DstArg))
11366 PatternType = 1;
11367 // - sizeof(src)
11368 else if (referToTheSameDecl(E1: SizeOfArg, E2: SrcArg))
11369 PatternType = 2;
11370 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Val: LenArg)) {
11371 if (BE->getOpcode() == BO_Sub) {
11372 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11373 const Expr *R = BE->getRHS()->IgnoreParenCasts();
11374 // - sizeof(dst) - strlen(dst)
11375 if (referToTheSameDecl(E1: DstArg, E2: getSizeOfExprArg(E: L)) &&
11376 referToTheSameDecl(E1: DstArg, E2: getStrlenExprArg(E: R)))
11377 PatternType = 1;
11378 // - sizeof(src) - (anything)
11379 else if (referToTheSameDecl(E1: SrcArg, E2: getSizeOfExprArg(E: L)))
11380 PatternType = 2;
11381 }
11382 }
11383
11384 if (PatternType == 0)
11385 return;
11386
11387 // Generate the diagnostic.
11388 SourceLocation SL = LenArg->getBeginLoc();
11389 SourceRange SR = LenArg->getSourceRange();
11390 SourceManager &SM = getSourceManager();
11391
11392 // If the function is defined as a builtin macro, do not show macro expansion.
11393 if (SM.isMacroArgExpansion(Loc: SL)) {
11394 SL = SM.getSpellingLoc(Loc: SL);
11395 SR = SourceRange(SM.getSpellingLoc(Loc: SR.getBegin()),
11396 SM.getSpellingLoc(Loc: SR.getEnd()));
11397 }
11398
11399 // Check if the destination is an array (rather than a pointer to an array).
11400 QualType DstTy = DstArg->getType();
11401 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(Ty: DstTy,
11402 Context);
11403 if (!isKnownSizeArray) {
11404 if (PatternType == 1)
11405 Diag(Loc: SL, DiagID: diag::warn_strncat_wrong_size) << SR;
11406 else
11407 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11408 return;
11409 }
11410
11411 if (PatternType == 1)
11412 Diag(Loc: SL, DiagID: diag::warn_strncat_large_size) << SR;
11413 else
11414 Diag(Loc: SL, DiagID: diag::warn_strncat_src_size) << SR;
11415
11416 SmallString<128> sizeString;
11417 llvm::raw_svector_ostream OS(sizeString);
11418 OS << "sizeof(";
11419 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11420 OS << ") - ";
11421 OS << "strlen(";
11422 DstArg->printPretty(OS, Helper: nullptr, Policy: getPrintingPolicy());
11423 OS << ") - 1";
11424
11425 Diag(Loc: SL, DiagID: diag::note_strncat_wrong_size)
11426 << FixItHint::CreateReplacement(RemoveRange: SR, Code: OS.str());
11427}
11428
11429namespace {
11430void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
11431 const UnaryOperator *UnaryExpr, const Decl *D) {
11432 if (isa<FieldDecl, FunctionDecl, VarDecl>(Val: D)) {
11433 S.Diag(Loc: UnaryExpr->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11434 << CalleeName << 0 /*object: */ << cast<NamedDecl>(Val: D);
11435 return;
11436 }
11437}
11438
11439void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
11440 const UnaryOperator *UnaryExpr) {
11441 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: UnaryExpr->getSubExpr())) {
11442 const Decl *D = Lvalue->getDecl();
11443 if (const auto *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
11444 if (!DD->getType()->isReferenceType())
11445 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11446 }
11447 }
11448
11449 if (const auto *Lvalue = dyn_cast<MemberExpr>(Val: UnaryExpr->getSubExpr()))
11450 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11451 D: Lvalue->getMemberDecl());
11452}
11453
11454void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
11455 const UnaryOperator *UnaryExpr) {
11456 const auto *Lambda = dyn_cast<LambdaExpr>(
11457 Val: UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
11458 if (!Lambda)
11459 return;
11460
11461 S.Diag(Loc: Lambda->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11462 << CalleeName << 2 /*object: lambda expression*/;
11463}
11464
11465void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11466 const DeclRefExpr *Lvalue) {
11467 const auto *Var = dyn_cast<VarDecl>(Val: Lvalue->getDecl());
11468 if (Var == nullptr)
11469 return;
11470
11471 S.Diag(Loc: Lvalue->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11472 << CalleeName << 0 /*object: */ << Var;
11473}
11474
11475void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11476 const CastExpr *Cast) {
11477 SmallString<128> SizeString;
11478 llvm::raw_svector_ostream OS(SizeString);
11479
11480 clang::CastKind Kind = Cast->getCastKind();
11481 if (Kind == clang::CK_BitCast &&
11482 !Cast->getSubExpr()->getType()->isFunctionPointerType())
11483 return;
11484 if (Kind == clang::CK_IntegralToPointer &&
11485 !isa<IntegerLiteral>(
11486 Val: Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11487 return;
11488
11489 switch (Cast->getCastKind()) {
11490 case clang::CK_BitCast:
11491 case clang::CK_IntegralToPointer:
11492 case clang::CK_FunctionToPointerDecay:
11493 OS << '\'';
11494 Cast->printPretty(OS, Helper: nullptr, Policy: S.getPrintingPolicy());
11495 OS << '\'';
11496 break;
11497 default:
11498 return;
11499 }
11500
11501 S.Diag(Loc: Cast->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11502 << CalleeName << 0 /*object: */ << OS.str();
11503}
11504} // namespace
11505
11506void Sema::CheckFreeArguments(const CallExpr *E) {
11507 const std::string CalleeName =
11508 cast<FunctionDecl>(Val: E->getCalleeDecl())->getQualifiedNameAsString();
11509
11510 { // Prefer something that doesn't involve a cast to make things simpler.
11511 const Expr *Arg = E->getArg(Arg: 0)->IgnoreParenCasts();
11512 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Val: Arg))
11513 switch (UnaryExpr->getOpcode()) {
11514 case UnaryOperator::Opcode::UO_AddrOf:
11515 return CheckFreeArgumentsAddressof(S&: *this, CalleeName, UnaryExpr);
11516 case UnaryOperator::Opcode::UO_Plus:
11517 return CheckFreeArgumentsPlus(S&: *this, CalleeName, UnaryExpr);
11518 default:
11519 break;
11520 }
11521
11522 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Val: Arg))
11523 if (Lvalue->getType()->isArrayType())
11524 return CheckFreeArgumentsStackArray(S&: *this, CalleeName, Lvalue);
11525
11526 if (const auto *Label = dyn_cast<AddrLabelExpr>(Val: Arg)) {
11527 Diag(Loc: Label->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11528 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11529 return;
11530 }
11531
11532 if (isa<BlockExpr>(Val: Arg)) {
11533 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_free_nonheap_object)
11534 << CalleeName << 1 /*object: block*/;
11535 return;
11536 }
11537 }
11538 // Maybe the cast was important, check after the other cases.
11539 if (const auto *Cast = dyn_cast<CastExpr>(Val: E->getArg(Arg: 0)))
11540 return CheckFreeArgumentsCast(S&: *this, CalleeName, Cast);
11541}
11542
11543void
11544Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11545 SourceLocation ReturnLoc,
11546 bool isObjCMethod,
11547 const AttrVec *Attrs,
11548 const FunctionDecl *FD) {
11549 // Check if the return value is null but should not be.
11550 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(container: *Attrs)) ||
11551 (!isObjCMethod && isNonNullType(type: lhsType))) &&
11552 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11553 Diag(Loc: ReturnLoc, DiagID: diag::warn_null_ret)
11554 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11555
11556 // C++11 [basic.stc.dynamic.allocation]p4:
11557 // If an allocation function declared with a non-throwing
11558 // exception-specification fails to allocate storage, it shall return
11559 // a null pointer. Any other allocation function that fails to allocate
11560 // storage shall indicate failure only by throwing an exception [...]
11561 if (FD) {
11562 OverloadedOperatorKind Op = FD->getOverloadedOperator();
11563 if (Op == OO_New || Op == OO_Array_New) {
11564 const FunctionProtoType *Proto
11565 = FD->getType()->castAs<FunctionProtoType>();
11566 if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11567 CheckNonNullExpr(S&: *this, Expr: RetValExp))
11568 Diag(Loc: ReturnLoc, DiagID: diag::warn_operator_new_returns_null)
11569 << FD << getLangOpts().CPlusPlus11;
11570 }
11571 }
11572
11573 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) {
11574 Diag(Loc: ReturnLoc, DiagID: diag::err_wasm_table_art) << 1;
11575 }
11576
11577 // PPC MMA non-pointer types are not allowed as return type. Checking the type
11578 // here prevent the user from using a PPC MMA type as trailing return type.
11579 if (Context.getTargetInfo().getTriple().isPPC64())
11580 PPC().CheckPPCMMAType(Type: RetValExp->getType(), TypeLoc: ReturnLoc);
11581}
11582
11583void Sema::CheckFloatComparison(SourceLocation Loc, const Expr *LHS,
11584 const Expr *RHS, BinaryOperatorKind Opcode) {
11585 if (!BinaryOperator::isEqualityOp(Opc: Opcode))
11586 return;
11587
11588 // Match and capture subexpressions such as "(float) X == 0.1".
11589 const FloatingLiteral *FPLiteral;
11590 const CastExpr *FPCast;
11591 auto getCastAndLiteral = [&FPLiteral, &FPCast](const Expr *L, const Expr *R) {
11592 FPLiteral = dyn_cast<FloatingLiteral>(Val: L->IgnoreParens());
11593 FPCast = dyn_cast<CastExpr>(Val: R->IgnoreParens());
11594 return FPLiteral && FPCast;
11595 };
11596
11597 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11598 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>();
11599 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>();
11600 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() &&
11601 TargetTy->isFloatingPoint()) {
11602 bool Lossy;
11603 llvm::APFloat TargetC = FPLiteral->getValue();
11604 TargetC.convert(ToSemantics: Context.getFloatTypeSemantics(T: QualType(SourceTy, 0)),
11605 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Lossy);
11606 if (Lossy) {
11607 // If the literal cannot be represented in the source type, then a
11608 // check for == is always false and check for != is always true.
11609 Diag(Loc, DiagID: diag::warn_float_compare_literal)
11610 << (Opcode == BO_EQ) << QualType(SourceTy, 0)
11611 << LHS->getSourceRange() << RHS->getSourceRange();
11612 return;
11613 }
11614 }
11615 }
11616
11617 // Match a more general floating-point equality comparison (-Wfloat-equal).
11618 const Expr *LeftExprSansParen = LHS->IgnoreParenImpCasts();
11619 const Expr *RightExprSansParen = RHS->IgnoreParenImpCasts();
11620
11621 // Special case: check for x == x (which is OK).
11622 // Do not emit warnings for such cases.
11623 if (const auto *DRL = dyn_cast<DeclRefExpr>(Val: LeftExprSansParen))
11624 if (const auto *DRR = dyn_cast<DeclRefExpr>(Val: RightExprSansParen))
11625 if (DRL->getDecl() == DRR->getDecl())
11626 return;
11627
11628 // Special case: check for comparisons against literals that can be exactly
11629 // represented by APFloat. In such cases, do not emit a warning. This
11630 // is a heuristic: often comparison against such literals are used to
11631 // detect if a value in a variable has not changed. This clearly can
11632 // lead to false negatives.
11633 if (const auto *FLL = dyn_cast<FloatingLiteral>(Val: LeftExprSansParen)) {
11634 if (FLL->isExact())
11635 return;
11636 } else if (const auto *FLR = dyn_cast<FloatingLiteral>(Val: RightExprSansParen))
11637 if (FLR->isExact())
11638 return;
11639
11640 // Check for comparisons with builtin types.
11641 if (const auto *CL = dyn_cast<CallExpr>(Val: LeftExprSansParen);
11642 CL && CL->getBuiltinCallee())
11643 return;
11644
11645 if (const auto *CR = dyn_cast<CallExpr>(Val: RightExprSansParen);
11646 CR && CR->getBuiltinCallee())
11647 return;
11648
11649 // Emit the diagnostic.
11650 Diag(Loc, DiagID: diag::warn_floatingpoint_eq)
11651 << LHS->getSourceRange() << RHS->getSourceRange();
11652}
11653
11654//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11655//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11656
11657namespace {
11658
11659/// Structure recording the 'active' range of an integer-valued
11660/// expression.
11661struct IntRange {
11662 /// The number of bits active in the int. Note that this includes exactly one
11663 /// sign bit if !NonNegative.
11664 unsigned Width;
11665
11666 /// True if the int is known not to have negative values. If so, all leading
11667 /// bits before Width are known zero, otherwise they are known to be the
11668 /// same as the MSB within Width.
11669 bool NonNegative;
11670
11671 IntRange(unsigned Width, bool NonNegative)
11672 : Width(Width), NonNegative(NonNegative) {}
11673
11674 /// Number of bits excluding the sign bit.
11675 unsigned valueBits() const {
11676 return NonNegative ? Width : Width - 1;
11677 }
11678
11679 /// Returns the range of the bool type.
11680 static IntRange forBoolType() {
11681 return IntRange(1, true);
11682 }
11683
11684 /// Returns the range of an opaque value of the given integral type.
11685 static IntRange forValueOfType(ASTContext &C, QualType T) {
11686 return forValueOfCanonicalType(C,
11687 T: T->getCanonicalTypeInternal().getTypePtr());
11688 }
11689
11690 /// Returns the range of an opaque value of a canonical integral type.
11691 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11692 assert(T->isCanonicalUnqualified());
11693
11694 if (const auto *VT = dyn_cast<VectorType>(Val: T))
11695 T = VT->getElementType().getTypePtr();
11696 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
11697 T = MT->getElementType().getTypePtr();
11698 if (const auto *CT = dyn_cast<ComplexType>(Val: T))
11699 T = CT->getElementType().getTypePtr();
11700 if (const auto *AT = dyn_cast<AtomicType>(Val: T))
11701 T = AT->getValueType().getTypePtr();
11702 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11703 T = OBT->getUnderlyingType().getTypePtr();
11704
11705 if (!C.getLangOpts().CPlusPlus) {
11706 // For enum types in C code, use the underlying datatype.
11707 if (const auto *ED = T->getAsEnumDecl())
11708 T = ED->getIntegerType().getDesugaredType(Context: C).getTypePtr();
11709 } else if (auto *Enum = T->getAsEnumDecl()) {
11710 // For enum types in C++, use the known bit width of the enumerators.
11711 // In C++11, enums can have a fixed underlying type. Use this type to
11712 // compute the range.
11713 if (Enum->isFixed()) {
11714 return IntRange(C.getIntWidth(T: QualType(T, 0)),
11715 !Enum->getIntegerType()->isSignedIntegerType());
11716 }
11717
11718 unsigned NumPositive = Enum->getNumPositiveBits();
11719 unsigned NumNegative = Enum->getNumNegativeBits();
11720
11721 if (NumNegative == 0)
11722 return IntRange(NumPositive, true/*NonNegative*/);
11723 else
11724 return IntRange(std::max(a: NumPositive + 1, b: NumNegative),
11725 false/*NonNegative*/);
11726 }
11727
11728 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11729 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11730
11731 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11732 assert(BT->isInteger());
11733
11734 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11735 }
11736
11737 /// Returns the "target" range of a canonical integral type, i.e.
11738 /// the range of values expressible in the type.
11739 ///
11740 /// This matches forValueOfCanonicalType except that enums have the
11741 /// full range of their type, not the range of their enumerators.
11742 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11743 assert(T->isCanonicalUnqualified());
11744
11745 if (const VectorType *VT = dyn_cast<VectorType>(Val: T))
11746 T = VT->getElementType().getTypePtr();
11747 if (const auto *MT = dyn_cast<ConstantMatrixType>(Val: T))
11748 T = MT->getElementType().getTypePtr();
11749 if (const ComplexType *CT = dyn_cast<ComplexType>(Val: T))
11750 T = CT->getElementType().getTypePtr();
11751 if (const AtomicType *AT = dyn_cast<AtomicType>(Val: T))
11752 T = AT->getValueType().getTypePtr();
11753 if (const auto *ED = T->getAsEnumDecl())
11754 T = C.getCanonicalType(T: ED->getIntegerType()).getTypePtr();
11755 if (const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(Val: T))
11756 T = OBT->getUnderlyingType().getTypePtr();
11757
11758 if (const auto *EIT = dyn_cast<BitIntType>(Val: T))
11759 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11760
11761 const BuiltinType *BT = cast<BuiltinType>(Val: T);
11762 assert(BT->isInteger());
11763
11764 return IntRange(C.getIntWidth(T: QualType(T, 0)), BT->isUnsignedInteger());
11765 }
11766
11767 /// Returns the supremum of two ranges: i.e. their conservative merge.
11768 static IntRange join(IntRange L, IntRange R) {
11769 bool Unsigned = L.NonNegative && R.NonNegative;
11770 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
11771 L.NonNegative && R.NonNegative);
11772 }
11773
11774 /// Return the range of a bitwise-AND of the two ranges.
11775 static IntRange bit_and(IntRange L, IntRange R) {
11776 unsigned Bits = std::max(a: L.Width, b: R.Width);
11777 bool NonNegative = false;
11778 if (L.NonNegative) {
11779 Bits = std::min(a: Bits, b: L.Width);
11780 NonNegative = true;
11781 }
11782 if (R.NonNegative) {
11783 Bits = std::min(a: Bits, b: R.Width);
11784 NonNegative = true;
11785 }
11786 return IntRange(Bits, NonNegative);
11787 }
11788
11789 /// Return the range of a sum of the two ranges.
11790 static IntRange sum(IntRange L, IntRange R) {
11791 bool Unsigned = L.NonNegative && R.NonNegative;
11792 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + 1 + !Unsigned,
11793 Unsigned);
11794 }
11795
11796 /// Return the range of a difference of the two ranges.
11797 static IntRange difference(IntRange L, IntRange R) {
11798 // We need a 1-bit-wider range if:
11799 // 1) LHS can be negative: least value can be reduced.
11800 // 2) RHS can be negative: greatest value can be increased.
11801 bool CanWiden = !L.NonNegative || !R.NonNegative;
11802 bool Unsigned = L.NonNegative && R.Width == 0;
11803 return IntRange(std::max(a: L.valueBits(), b: R.valueBits()) + CanWiden +
11804 !Unsigned,
11805 Unsigned);
11806 }
11807
11808 /// Return the range of a product of the two ranges.
11809 static IntRange product(IntRange L, IntRange R) {
11810 // If both LHS and RHS can be negative, we can form
11811 // -2^L * -2^R = 2^(L + R)
11812 // which requires L + R + 1 value bits to represent.
11813 bool CanWiden = !L.NonNegative && !R.NonNegative;
11814 bool Unsigned = L.NonNegative && R.NonNegative;
11815 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11816 Unsigned);
11817 }
11818
11819 /// Return the range of a remainder operation between the two ranges.
11820 static IntRange rem(IntRange L, IntRange R) {
11821 // The result of a remainder can't be larger than the result of
11822 // either side. The sign of the result is the sign of the LHS.
11823 bool Unsigned = L.NonNegative;
11824 return IntRange(std::min(a: L.valueBits(), b: R.valueBits()) + !Unsigned,
11825 Unsigned);
11826 }
11827};
11828
11829} // namespace
11830
11831static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth) {
11832 if (value.isSigned() && value.isNegative())
11833 return IntRange(value.getSignificantBits(), false);
11834
11835 if (value.getBitWidth() > MaxWidth)
11836 value = value.trunc(width: MaxWidth);
11837
11838 // isNonNegative() just checks the sign bit without considering
11839 // signedness.
11840 return IntRange(value.getActiveBits(), true);
11841}
11842
11843static IntRange GetValueRange(APValue &result, QualType Ty, unsigned MaxWidth) {
11844 if (result.isInt())
11845 return GetValueRange(value&: result.getInt(), MaxWidth);
11846
11847 if (result.isVector()) {
11848 IntRange R = GetValueRange(result&: result.getVectorElt(I: 0), Ty, MaxWidth);
11849 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11850 IntRange El = GetValueRange(result&: result.getVectorElt(I: i), Ty, MaxWidth);
11851 R = IntRange::join(L: R, R: El);
11852 }
11853 return R;
11854 }
11855
11856 if (result.isComplexInt()) {
11857 IntRange R = GetValueRange(value&: result.getComplexIntReal(), MaxWidth);
11858 IntRange I = GetValueRange(value&: result.getComplexIntImag(), MaxWidth);
11859 return IntRange::join(L: R, R: I);
11860 }
11861
11862 // This can happen with lossless casts to intptr_t of "based" lvalues.
11863 // Assume it might use arbitrary bits.
11864 // FIXME: The only reason we need to pass the type in here is to get
11865 // the sign right on this one case. It would be nice if APValue
11866 // preserved this.
11867 assert(result.isLValue() || result.isAddrLabelDiff());
11868 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11869}
11870
11871static QualType GetExprType(const Expr *E) {
11872 QualType Ty = E->getType();
11873 if (const auto *AtomicRHS = Ty->getAs<AtomicType>())
11874 Ty = AtomicRHS->getValueType();
11875 return Ty;
11876}
11877
11878/// Attempts to estimate an approximate range for the given integer expression.
11879/// Returns a range if successful, otherwise it returns \c std::nullopt if a
11880/// reliable estimation cannot be determined.
11881///
11882/// \param MaxWidth The width to which the value will be truncated.
11883/// \param InConstantContext If \c true, interpret the expression within a
11884/// constant context.
11885/// \param Approximate If \c true, provide a likely range of values by assuming
11886/// that arithmetic on narrower types remains within those types.
11887/// If \c false, return a range that includes all possible values
11888/// resulting from the expression.
11889/// \returns A range of values that the expression might take, or
11890/// std::nullopt if a reliable estimation cannot be determined.
11891static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
11892 unsigned MaxWidth,
11893 bool InConstantContext,
11894 bool Approximate) {
11895 E = E->IgnoreParens();
11896
11897 // Try a full evaluation first.
11898 Expr::EvalResult result;
11899 if (E->EvaluateAsRValue(Result&: result, Ctx: C, InConstantContext))
11900 return GetValueRange(result&: result.Val, Ty: GetExprType(E), MaxWidth);
11901
11902 // I think we only want to look through implicit casts here; if the
11903 // user has an explicit widening cast, we should treat the value as
11904 // being of the new, wider type.
11905 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Val: E)) {
11906 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11907 return TryGetExprRange(C, E: CE->getSubExpr(), MaxWidth, InConstantContext,
11908 Approximate);
11909
11910 IntRange OutputTypeRange = IntRange::forValueOfType(C, T: GetExprType(E: CE));
11911
11912 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11913 CE->getCastKind() == CK_BooleanToSignedIntegral;
11914
11915 // Assume that non-integer casts can span the full range of the type.
11916 if (!isIntegerCast)
11917 return OutputTypeRange;
11918
11919 std::optional<IntRange> SubRange = TryGetExprRange(
11920 C, E: CE->getSubExpr(), MaxWidth: std::min(a: MaxWidth, b: OutputTypeRange.Width),
11921 InConstantContext, Approximate);
11922 if (!SubRange)
11923 return std::nullopt;
11924
11925 // Bail out if the subexpr's range is as wide as the cast type.
11926 if (SubRange->Width >= OutputTypeRange.Width)
11927 return OutputTypeRange;
11928
11929 // Otherwise, we take the smaller width, and we're non-negative if
11930 // either the output type or the subexpr is.
11931 return IntRange(SubRange->Width,
11932 SubRange->NonNegative || OutputTypeRange.NonNegative);
11933 }
11934
11935 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
11936 // If we can fold the condition, just take that operand.
11937 bool CondResult;
11938 if (CO->getCond()->EvaluateAsBooleanCondition(Result&: CondResult, Ctx: C))
11939 return TryGetExprRange(
11940 C, E: CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
11941 InConstantContext, Approximate);
11942
11943 // Otherwise, conservatively merge.
11944 // TryGetExprRange requires an integer expression, but a throw expression
11945 // results in a void type.
11946 Expr *TrueExpr = CO->getTrueExpr();
11947 if (TrueExpr->getType()->isVoidType())
11948 return std::nullopt;
11949
11950 std::optional<IntRange> L =
11951 TryGetExprRange(C, E: TrueExpr, MaxWidth, InConstantContext, Approximate);
11952 if (!L)
11953 return std::nullopt;
11954
11955 Expr *FalseExpr = CO->getFalseExpr();
11956 if (FalseExpr->getType()->isVoidType())
11957 return std::nullopt;
11958
11959 std::optional<IntRange> R =
11960 TryGetExprRange(C, E: FalseExpr, MaxWidth, InConstantContext, Approximate);
11961 if (!R)
11962 return std::nullopt;
11963
11964 return IntRange::join(L: *L, R: *R);
11965 }
11966
11967 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
11968 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11969
11970 switch (BO->getOpcode()) {
11971 case BO_Cmp:
11972 llvm_unreachable("builtin <=> should have class type");
11973
11974 // Boolean-valued operations are single-bit and positive.
11975 case BO_LAnd:
11976 case BO_LOr:
11977 case BO_LT:
11978 case BO_GT:
11979 case BO_LE:
11980 case BO_GE:
11981 case BO_EQ:
11982 case BO_NE:
11983 return IntRange::forBoolType();
11984
11985 // The type of the assignments is the type of the LHS, so the RHS
11986 // is not necessarily the same type.
11987 case BO_MulAssign:
11988 case BO_DivAssign:
11989 case BO_RemAssign:
11990 case BO_AddAssign:
11991 case BO_SubAssign:
11992 case BO_XorAssign:
11993 case BO_OrAssign:
11994 // TODO: bitfields?
11995 return IntRange::forValueOfType(C, T: GetExprType(E));
11996
11997 // Simple assignments just pass through the RHS, which will have
11998 // been coerced to the LHS type.
11999 case BO_Assign:
12000 // TODO: bitfields?
12001 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
12002 Approximate);
12003
12004 // Operations with opaque sources are black-listed.
12005 case BO_PtrMemD:
12006 case BO_PtrMemI:
12007 return IntRange::forValueOfType(C, T: GetExprType(E));
12008
12009 // Bitwise-and uses the *infinum* of the two source ranges.
12010 case BO_And:
12011 case BO_AndAssign:
12012 Combine = IntRange::bit_and;
12013 break;
12014
12015 // Left shift gets black-listed based on a judgement call.
12016 case BO_Shl:
12017 // ...except that we want to treat '1 << (blah)' as logically
12018 // positive. It's an important idiom.
12019 if (IntegerLiteral *I
12020 = dyn_cast<IntegerLiteral>(Val: BO->getLHS()->IgnoreParenCasts())) {
12021 if (I->getValue() == 1) {
12022 IntRange R = IntRange::forValueOfType(C, T: GetExprType(E));
12023 return IntRange(R.Width, /*NonNegative*/ true);
12024 }
12025 }
12026 [[fallthrough]];
12027
12028 case BO_ShlAssign:
12029 return IntRange::forValueOfType(C, T: GetExprType(E));
12030
12031 // Right shift by a constant can narrow its left argument.
12032 case BO_Shr:
12033 case BO_ShrAssign: {
12034 std::optional<IntRange> L = TryGetExprRange(
12035 C, E: BO->getLHS(), MaxWidth, InConstantContext, Approximate);
12036 if (!L)
12037 return std::nullopt;
12038
12039 // If the shift amount is a positive constant, drop the width by
12040 // that much.
12041 if (std::optional<llvm::APSInt> shift =
12042 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
12043 if (shift->isNonNegative()) {
12044 if (shift->uge(RHS: L->Width))
12045 L->Width = (L->NonNegative ? 0 : 1);
12046 else
12047 L->Width -= shift->getZExtValue();
12048 }
12049 }
12050
12051 return L;
12052 }
12053
12054 // Comma acts as its right operand.
12055 case BO_Comma:
12056 return TryGetExprRange(C, E: BO->getRHS(), MaxWidth, InConstantContext,
12057 Approximate);
12058
12059 case BO_Add:
12060 if (!Approximate)
12061 Combine = IntRange::sum;
12062 break;
12063
12064 case BO_Sub:
12065 if (BO->getLHS()->getType()->isPointerType())
12066 return IntRange::forValueOfType(C, T: GetExprType(E));
12067 if (!Approximate)
12068 Combine = IntRange::difference;
12069 break;
12070
12071 case BO_Mul:
12072 if (!Approximate)
12073 Combine = IntRange::product;
12074 break;
12075
12076 // The width of a division result is mostly determined by the size
12077 // of the LHS.
12078 case BO_Div: {
12079 // Don't 'pre-truncate' the operands.
12080 unsigned opWidth = C.getIntWidth(T: GetExprType(E));
12081 std::optional<IntRange> L = TryGetExprRange(
12082 C, E: BO->getLHS(), MaxWidth: opWidth, InConstantContext, Approximate);
12083 if (!L)
12084 return std::nullopt;
12085
12086 // If the divisor is constant, use that.
12087 if (std::optional<llvm::APSInt> divisor =
12088 BO->getRHS()->getIntegerConstantExpr(Ctx: C)) {
12089 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
12090 if (log2 >= L->Width)
12091 L->Width = (L->NonNegative ? 0 : 1);
12092 else
12093 L->Width = std::min(a: L->Width - log2, b: MaxWidth);
12094 return L;
12095 }
12096
12097 // Otherwise, just use the LHS's width.
12098 // FIXME: This is wrong if the LHS could be its minimal value and the RHS
12099 // could be -1.
12100 std::optional<IntRange> R = TryGetExprRange(
12101 C, E: BO->getRHS(), MaxWidth: opWidth, InConstantContext, Approximate);
12102 if (!R)
12103 return std::nullopt;
12104
12105 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12106 }
12107
12108 case BO_Rem:
12109 Combine = IntRange::rem;
12110 break;
12111
12112 // The default behavior is okay for these.
12113 case BO_Xor:
12114 case BO_Or:
12115 break;
12116 }
12117
12118 // Combine the two ranges, but limit the result to the type in which we
12119 // performed the computation.
12120 QualType T = GetExprType(E);
12121 unsigned opWidth = C.getIntWidth(T);
12122 std::optional<IntRange> L = TryGetExprRange(C, E: BO->getLHS(), MaxWidth: opWidth,
12123 InConstantContext, Approximate);
12124 if (!L)
12125 return std::nullopt;
12126
12127 std::optional<IntRange> R = TryGetExprRange(C, E: BO->getRHS(), MaxWidth: opWidth,
12128 InConstantContext, Approximate);
12129 if (!R)
12130 return std::nullopt;
12131
12132 IntRange C = Combine(*L, *R);
12133 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
12134 C.Width = std::min(a: C.Width, b: MaxWidth);
12135 return C;
12136 }
12137
12138 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
12139 switch (UO->getOpcode()) {
12140 // Boolean-valued operations are white-listed.
12141 case UO_LNot:
12142 return IntRange::forBoolType();
12143
12144 // Operations with opaque sources are black-listed.
12145 case UO_Deref:
12146 case UO_AddrOf: // should be impossible
12147 return IntRange::forValueOfType(C, T: GetExprType(E));
12148
12149 case UO_Minus: {
12150 if (E->getType()->isUnsignedIntegerType()) {
12151 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12152 Approximate);
12153 }
12154
12155 std::optional<IntRange> SubRange = TryGetExprRange(
12156 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12157
12158 if (!SubRange)
12159 return std::nullopt;
12160
12161 // If the range was previously non-negative, we need an extra bit for the
12162 // sign bit. Otherwise, we need an extra bit because the negation of the
12163 // most-negative value is one bit wider than that value.
12164 return IntRange(std::min(a: SubRange->Width + 1, b: MaxWidth), false);
12165 }
12166
12167 case UO_Not: {
12168 if (E->getType()->isUnsignedIntegerType()) {
12169 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12170 Approximate);
12171 }
12172
12173 std::optional<IntRange> SubRange = TryGetExprRange(
12174 C, E: UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12175
12176 if (!SubRange)
12177 return std::nullopt;
12178
12179 // The width increments by 1 if the sub-expression cannot be negative
12180 // since it now can be.
12181 return IntRange(
12182 std::min(a: SubRange->Width + (int)SubRange->NonNegative, b: MaxWidth),
12183 false);
12184 }
12185
12186 default:
12187 return TryGetExprRange(C, E: UO->getSubExpr(), MaxWidth, InConstantContext,
12188 Approximate);
12189 }
12190 }
12191
12192 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
12193 return TryGetExprRange(C, E: OVE->getSourceExpr(), MaxWidth, InConstantContext,
12194 Approximate);
12195
12196 if (const auto *BitField = E->getSourceBitField())
12197 return IntRange(BitField->getBitWidthValue(),
12198 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12199
12200 if (GetExprType(E)->isVoidType())
12201 return std::nullopt;
12202
12203 return IntRange::forValueOfType(C, T: GetExprType(E));
12204}
12205
12206static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
12207 bool InConstantContext,
12208 bool Approximate) {
12209 return TryGetExprRange(C, E, MaxWidth: C.getIntWidth(T: GetExprType(E)), InConstantContext,
12210 Approximate);
12211}
12212
12213/// Checks whether the given value, which currently has the given
12214/// source semantics, has the same value when coerced through the
12215/// target semantics.
12216static bool IsSameFloatAfterCast(const llvm::APFloat &value,
12217 const llvm::fltSemantics &Src,
12218 const llvm::fltSemantics &Tgt) {
12219 llvm::APFloat truncated = value;
12220
12221 bool ignored;
12222 truncated.convert(ToSemantics: Src, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
12223 truncated.convert(ToSemantics: Tgt, RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &ignored);
12224
12225 return truncated.bitwiseIsEqual(RHS: value);
12226}
12227
12228/// Checks whether the given value, which currently has the given
12229/// source semantics, has the same value when coerced through the
12230/// target semantics.
12231///
12232/// The value might be a vector of floats (or a complex number).
12233static bool IsSameFloatAfterCast(const APValue &value,
12234 const llvm::fltSemantics &Src,
12235 const llvm::fltSemantics &Tgt) {
12236 if (value.isFloat())
12237 return IsSameFloatAfterCast(value: value.getFloat(), Src, Tgt);
12238
12239 if (value.isVector()) {
12240 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
12241 if (!IsSameFloatAfterCast(value: value.getVectorElt(I: i), Src, Tgt))
12242 return false;
12243 return true;
12244 }
12245
12246 if (value.isMatrix()) {
12247 for (unsigned i = 0, e = value.getMatrixNumElements(); i != e; ++i)
12248 if (!IsSameFloatAfterCast(value: value.getMatrixElt(Idx: i), Src, Tgt))
12249 return false;
12250 return true;
12251 }
12252
12253 assert(value.isComplexFloat());
12254 return (IsSameFloatAfterCast(value: value.getComplexFloatReal(), Src, Tgt) &&
12255 IsSameFloatAfterCast(value: value.getComplexFloatImag(), Src, Tgt));
12256}
12257
12258static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
12259 bool IsListInit = false);
12260
12261static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E) {
12262 // Suppress cases where we are comparing against an enum constant.
12263 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts()))
12264 if (isa<EnumConstantDecl>(Val: DR->getDecl()))
12265 return true;
12266
12267 // Suppress cases where the value is expanded from a macro, unless that macro
12268 // is how a language represents a boolean literal. This is the case in both C
12269 // and Objective-C.
12270 SourceLocation BeginLoc = E->getBeginLoc();
12271 if (BeginLoc.isMacroID()) {
12272 StringRef MacroName = Lexer::getImmediateMacroName(
12273 Loc: BeginLoc, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
12274 return MacroName != "YES" && MacroName != "NO" &&
12275 MacroName != "true" && MacroName != "false";
12276 }
12277
12278 return false;
12279}
12280
12281static bool isKnownToHaveUnsignedValue(const Expr *E) {
12282 return E->getType()->isIntegerType() &&
12283 (!E->getType()->isSignedIntegerType() ||
12284 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
12285}
12286
12287namespace {
12288/// The promoted range of values of a type. In general this has the
12289/// following structure:
12290///
12291/// |-----------| . . . |-----------|
12292/// ^ ^ ^ ^
12293/// Min HoleMin HoleMax Max
12294///
12295/// ... where there is only a hole if a signed type is promoted to unsigned
12296/// (in which case Min and Max are the smallest and largest representable
12297/// values).
12298struct PromotedRange {
12299 // Min, or HoleMax if there is a hole.
12300 llvm::APSInt PromotedMin;
12301 // Max, or HoleMin if there is a hole.
12302 llvm::APSInt PromotedMax;
12303
12304 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
12305 if (R.Width == 0)
12306 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
12307 else if (R.Width >= BitWidth && !Unsigned) {
12308 // Promotion made the type *narrower*. This happens when promoting
12309 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
12310 // Treat all values of 'signed int' as being in range for now.
12311 PromotedMin = llvm::APSInt::getMinValue(numBits: BitWidth, Unsigned);
12312 PromotedMax = llvm::APSInt::getMaxValue(numBits: BitWidth, Unsigned);
12313 } else {
12314 PromotedMin = llvm::APSInt::getMinValue(numBits: R.Width, Unsigned: R.NonNegative)
12315 .extOrTrunc(width: BitWidth);
12316 PromotedMin.setIsUnsigned(Unsigned);
12317
12318 PromotedMax = llvm::APSInt::getMaxValue(numBits: R.Width, Unsigned: R.NonNegative)
12319 .extOrTrunc(width: BitWidth);
12320 PromotedMax.setIsUnsigned(Unsigned);
12321 }
12322 }
12323
12324 // Determine whether this range is contiguous (has no hole).
12325 bool isContiguous() const { return PromotedMin <= PromotedMax; }
12326
12327 // Where a constant value is within the range.
12328 enum ComparisonResult {
12329 LT = 0x1,
12330 LE = 0x2,
12331 GT = 0x4,
12332 GE = 0x8,
12333 EQ = 0x10,
12334 NE = 0x20,
12335 InRangeFlag = 0x40,
12336
12337 Less = LE | LT | NE,
12338 Min = LE | InRangeFlag,
12339 InRange = InRangeFlag,
12340 Max = GE | InRangeFlag,
12341 Greater = GE | GT | NE,
12342
12343 OnlyValue = LE | GE | EQ | InRangeFlag,
12344 InHole = NE
12345 };
12346
12347 ComparisonResult compare(const llvm::APSInt &Value) const {
12348 assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
12349 Value.isUnsigned() == PromotedMin.isUnsigned());
12350 if (!isContiguous()) {
12351 assert(Value.isUnsigned() && "discontiguous range for signed compare");
12352 if (Value.isMinValue()) return Min;
12353 if (Value.isMaxValue()) return Max;
12354 if (Value >= PromotedMin) return InRange;
12355 if (Value <= PromotedMax) return InRange;
12356 return InHole;
12357 }
12358
12359 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMin)) {
12360 case -1: return Less;
12361 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
12362 case 1:
12363 switch (llvm::APSInt::compareValues(I1: Value, I2: PromotedMax)) {
12364 case -1: return InRange;
12365 case 0: return Max;
12366 case 1: return Greater;
12367 }
12368 }
12369
12370 llvm_unreachable("impossible compare result");
12371 }
12372
12373 static std::optional<StringRef>
12374 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
12375 if (Op == BO_Cmp) {
12376 ComparisonResult LTFlag = LT, GTFlag = GT;
12377 if (ConstantOnRHS) std::swap(a&: LTFlag, b&: GTFlag);
12378
12379 if (R & EQ) return StringRef("'std::strong_ordering::equal'");
12380 if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
12381 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
12382 return std::nullopt;
12383 }
12384
12385 ComparisonResult TrueFlag, FalseFlag;
12386 if (Op == BO_EQ) {
12387 TrueFlag = EQ;
12388 FalseFlag = NE;
12389 } else if (Op == BO_NE) {
12390 TrueFlag = NE;
12391 FalseFlag = EQ;
12392 } else {
12393 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12394 TrueFlag = LT;
12395 FalseFlag = GE;
12396 } else {
12397 TrueFlag = GT;
12398 FalseFlag = LE;
12399 }
12400 if (Op == BO_GE || Op == BO_LE)
12401 std::swap(a&: TrueFlag, b&: FalseFlag);
12402 }
12403 if (R & TrueFlag)
12404 return StringRef("true");
12405 if (R & FalseFlag)
12406 return StringRef("false");
12407 return std::nullopt;
12408 }
12409};
12410}
12411
12412static bool HasEnumType(const Expr *E) {
12413 // Strip off implicit integral promotions.
12414 while (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
12415 if (ICE->getCastKind() != CK_IntegralCast &&
12416 ICE->getCastKind() != CK_NoOp)
12417 break;
12418 E = ICE->getSubExpr();
12419 }
12420
12421 return E->getType()->isEnumeralType();
12422}
12423
12424static int classifyConstantValue(Expr *Constant) {
12425 // The values of this enumeration are used in the diagnostics
12426 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
12427 enum ConstantValueKind {
12428 Miscellaneous = 0,
12429 LiteralTrue,
12430 LiteralFalse
12431 };
12432 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Val: Constant))
12433 return BL->getValue() ? ConstantValueKind::LiteralTrue
12434 : ConstantValueKind::LiteralFalse;
12435 return ConstantValueKind::Miscellaneous;
12436}
12437
12438static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
12439 Expr *Constant, Expr *Other,
12440 const llvm::APSInt &Value,
12441 bool RhsConstant) {
12442 if (S.inTemplateInstantiation())
12443 return false;
12444
12445 Expr *OriginalOther = Other;
12446
12447 Constant = Constant->IgnoreParenImpCasts();
12448 Other = Other->IgnoreParenImpCasts();
12449
12450 // Suppress warnings on tautological comparisons between values of the same
12451 // enumeration type. There are only two ways we could warn on this:
12452 // - If the constant is outside the range of representable values of
12453 // the enumeration. In such a case, we should warn about the cast
12454 // to enumeration type, not about the comparison.
12455 // - If the constant is the maximum / minimum in-range value. For an
12456 // enumeratin type, such comparisons can be meaningful and useful.
12457 if (Constant->getType()->isEnumeralType() &&
12458 S.Context.hasSameUnqualifiedType(T1: Constant->getType(), T2: Other->getType()))
12459 return false;
12460
12461 std::optional<IntRange> OtherValueRange = TryGetExprRange(
12462 C&: S.Context, E: Other, InConstantContext: S.isConstantEvaluatedContext(), /*Approximate=*/false);
12463 if (!OtherValueRange)
12464 return false;
12465
12466 QualType OtherT = Other->getType();
12467 if (const auto *AT = OtherT->getAs<AtomicType>())
12468 OtherT = AT->getValueType();
12469 IntRange OtherTypeRange = IntRange::forValueOfType(C&: S.Context, T: OtherT);
12470
12471 // Special case for ObjC BOOL on targets where its a typedef for a signed char
12472 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
12473 bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
12474 S.ObjC().NSAPIObj->isObjCBOOLType(T: OtherT) &&
12475 OtherT->isSpecificBuiltinType(K: BuiltinType::SChar);
12476
12477 // Whether we're treating Other as being a bool because of the form of
12478 // expression despite it having another type (typically 'int' in C).
12479 bool OtherIsBooleanDespiteType =
12480 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
12481 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12482 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12483
12484 // Check if all values in the range of possible values of this expression
12485 // lead to the same comparison outcome.
12486 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(),
12487 Value.isUnsigned());
12488 auto Cmp = OtherPromotedValueRange.compare(Value);
12489 auto Result = PromotedRange::constantValue(Op: E->getOpcode(), R: Cmp, ConstantOnRHS: RhsConstant);
12490 if (!Result)
12491 return false;
12492
12493 // Also consider the range determined by the type alone. This allows us to
12494 // classify the warning under the proper diagnostic group.
12495 bool TautologicalTypeCompare = false;
12496 {
12497 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
12498 Value.isUnsigned());
12499 auto TypeCmp = OtherPromotedTypeRange.compare(Value);
12500 if (auto TypeResult = PromotedRange::constantValue(Op: E->getOpcode(), R: TypeCmp,
12501 ConstantOnRHS: RhsConstant)) {
12502 TautologicalTypeCompare = true;
12503 Cmp = TypeCmp;
12504 Result = TypeResult;
12505 }
12506 }
12507
12508 // Don't warn if the non-constant operand actually always evaluates to the
12509 // same value.
12510 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12511 return false;
12512
12513 // Suppress the diagnostic for an in-range comparison if the constant comes
12514 // from a macro or enumerator. We don't want to diagnose
12515 //
12516 // some_long_value <= INT_MAX
12517 //
12518 // when sizeof(int) == sizeof(long).
12519 bool InRange = Cmp & PromotedRange::InRangeFlag;
12520 if (InRange && IsEnumConstOrFromMacro(S, E: Constant))
12521 return false;
12522
12523 // A comparison of an unsigned bit-field against 0 is really a type problem,
12524 // even though at the type level the bit-field might promote to 'signed int'.
12525 if (Other->refersToBitField() && InRange && Value == 0 &&
12526 Other->getType()->isUnsignedIntegerOrEnumerationType())
12527 TautologicalTypeCompare = true;
12528
12529 // If this is a comparison to an enum constant, include that
12530 // constant in the diagnostic.
12531 const EnumConstantDecl *ED = nullptr;
12532 if (const auto *DR = dyn_cast<DeclRefExpr>(Val: Constant))
12533 ED = dyn_cast<EnumConstantDecl>(Val: DR->getDecl());
12534
12535 // Should be enough for uint128 (39 decimal digits)
12536 SmallString<64> PrettySourceValue;
12537 llvm::raw_svector_ostream OS(PrettySourceValue);
12538 if (ED) {
12539 OS << '\'' << *ED << "' (" << Value << ")";
12540 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12541 Val: Constant->IgnoreParenImpCasts())) {
12542 OS << (BL->getValue() ? "YES" : "NO");
12543 } else {
12544 OS << Value;
12545 }
12546
12547 if (!TautologicalTypeCompare) {
12548 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_tautological_compare_value_range)
12549 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12550 << E->getOpcodeStr() << OS.str() << *Result
12551 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12552 return true;
12553 }
12554
12555 if (IsObjCSignedCharBool) {
12556 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12557 PD: S.PDiag(DiagID: diag::warn_tautological_compare_objc_bool)
12558 << OS.str() << *Result);
12559 return true;
12560 }
12561
12562 // FIXME: We use a somewhat different formatting for the in-range cases and
12563 // cases involving boolean values for historical reasons. We should pick a
12564 // consistent way of presenting these diagnostics.
12565 if (!InRange || Other->isKnownToHaveBooleanValue()) {
12566
12567 S.DiagRuntimeBehavior(
12568 Loc: E->getOperatorLoc(), Statement: E,
12569 PD: S.PDiag(DiagID: !InRange ? diag::warn_out_of_range_compare
12570 : diag::warn_tautological_bool_compare)
12571 << OS.str() << classifyConstantValue(Constant) << OtherT
12572 << OtherIsBooleanDespiteType << *Result
12573 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
12574 } else {
12575 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12576 unsigned Diag =
12577 (isKnownToHaveUnsignedValue(E: OriginalOther) && Value == 0)
12578 ? (HasEnumType(E: OriginalOther)
12579 ? diag::warn_unsigned_enum_always_true_comparison
12580 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12581 : diag::warn_unsigned_always_true_comparison)
12582 : diag::warn_tautological_constant_compare;
12583
12584 S.Diag(Loc: E->getOperatorLoc(), DiagID: Diag)
12585 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12586 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12587 }
12588
12589 return true;
12590}
12591
12592/// Analyze the operands of the given comparison. Implements the
12593/// fallback case from AnalyzeComparison.
12594static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12595 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12596 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12597}
12598
12599/// Implements -Wsign-compare.
12600///
12601/// \param E the binary operator to check for warnings
12602static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12603 // The type the comparison is being performed in.
12604 QualType T = E->getLHS()->getType();
12605
12606 // Only analyze comparison operators where both sides have been converted to
12607 // the same type.
12608 if (!S.Context.hasSameUnqualifiedType(T1: T, T2: E->getRHS()->getType()))
12609 return AnalyzeImpConvsInComparison(S, E);
12610
12611 // Don't analyze value-dependent comparisons directly.
12612 if (E->isValueDependent())
12613 return AnalyzeImpConvsInComparison(S, E);
12614
12615 Expr *LHS = E->getLHS();
12616 Expr *RHS = E->getRHS();
12617
12618 if (T->isIntegralType(Ctx: S.Context)) {
12619 std::optional<llvm::APSInt> RHSValue =
12620 RHS->getIntegerConstantExpr(Ctx: S.Context);
12621 std::optional<llvm::APSInt> LHSValue =
12622 LHS->getIntegerConstantExpr(Ctx: S.Context);
12623
12624 // We don't care about expressions whose result is a constant.
12625 if (RHSValue && LHSValue)
12626 return AnalyzeImpConvsInComparison(S, E);
12627
12628 // We only care about expressions where just one side is literal
12629 if ((bool)RHSValue ^ (bool)LHSValue) {
12630 // Is the constant on the RHS or LHS?
12631 const bool RhsConstant = (bool)RHSValue;
12632 Expr *Const = RhsConstant ? RHS : LHS;
12633 Expr *Other = RhsConstant ? LHS : RHS;
12634 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12635
12636 // Check whether an integer constant comparison results in a value
12637 // of 'true' or 'false'.
12638 if (CheckTautologicalComparison(S, E, Constant: Const, Other, Value, RhsConstant))
12639 return AnalyzeImpConvsInComparison(S, E);
12640 }
12641 }
12642
12643 if (!T->hasUnsignedIntegerRepresentation()) {
12644 // We don't do anything special if this isn't an unsigned integral
12645 // comparison: we're only interested in integral comparisons, and
12646 // signed comparisons only happen in cases we don't care to warn about.
12647 return AnalyzeImpConvsInComparison(S, E);
12648 }
12649
12650 LHS = LHS->IgnoreParenImpCasts();
12651 RHS = RHS->IgnoreParenImpCasts();
12652
12653 if (!S.getLangOpts().CPlusPlus) {
12654 // Avoid warning about comparison of integers with different signs when
12655 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12656 // the type of `E`.
12657 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: LHS->getType()))
12658 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12659 if (const auto *TET = dyn_cast<TypeOfExprType>(Val: RHS->getType()))
12660 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12661 }
12662
12663 // Check to see if one of the (unmodified) operands is of different
12664 // signedness.
12665 Expr *signedOperand, *unsignedOperand;
12666 if (LHS->getType()->hasSignedIntegerRepresentation()) {
12667 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12668 "unsigned comparison between two signed integer expressions?");
12669 signedOperand = LHS;
12670 unsignedOperand = RHS;
12671 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12672 signedOperand = RHS;
12673 unsignedOperand = LHS;
12674 } else {
12675 return AnalyzeImpConvsInComparison(S, E);
12676 }
12677
12678 // Otherwise, calculate the effective range of the signed operand.
12679 std::optional<IntRange> signedRange =
12680 TryGetExprRange(C&: S.Context, E: signedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12681 /*Approximate=*/true);
12682 if (!signedRange)
12683 return;
12684
12685 // Go ahead and analyze implicit conversions in the operands. Note
12686 // that we skip the implicit conversions on both sides.
12687 AnalyzeImplicitConversions(S, E: LHS, CC: E->getOperatorLoc());
12688 AnalyzeImplicitConversions(S, E: RHS, CC: E->getOperatorLoc());
12689
12690 // If the signed range is non-negative, -Wsign-compare won't fire.
12691 if (signedRange->NonNegative)
12692 return;
12693
12694 // For (in)equality comparisons, if the unsigned operand is a
12695 // constant which cannot collide with a overflowed signed operand,
12696 // then reinterpreting the signed operand as unsigned will not
12697 // change the result of the comparison.
12698 if (E->isEqualityOp()) {
12699 unsigned comparisonWidth = S.Context.getIntWidth(T);
12700 std::optional<IntRange> unsignedRange = TryGetExprRange(
12701 C&: S.Context, E: unsignedOperand, InConstantContext: S.isConstantEvaluatedContext(),
12702 /*Approximate=*/true);
12703 if (!unsignedRange)
12704 return;
12705
12706 // We should never be unable to prove that the unsigned operand is
12707 // non-negative.
12708 assert(unsignedRange->NonNegative && "unsigned range includes negative?");
12709
12710 if (unsignedRange->Width < comparisonWidth)
12711 return;
12712 }
12713
12714 S.DiagRuntimeBehavior(Loc: E->getOperatorLoc(), Statement: E,
12715 PD: S.PDiag(DiagID: diag::warn_mixed_sign_comparison)
12716 << LHS->getType() << RHS->getType()
12717 << LHS->getSourceRange() << RHS->getSourceRange());
12718}
12719
12720/// Analyzes an attempt to assign the given value to a bitfield.
12721///
12722/// Returns true if there was something fishy about the attempt.
12723static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12724 SourceLocation InitLoc) {
12725 assert(Bitfield->isBitField());
12726 if (Bitfield->isInvalidDecl())
12727 return false;
12728
12729 // White-list bool bitfields.
12730 QualType BitfieldType = Bitfield->getType();
12731 if (BitfieldType->isBooleanType())
12732 return false;
12733
12734 if (auto *BitfieldEnumDecl = BitfieldType->getAsEnumDecl()) {
12735 // If the underlying enum type was not explicitly specified as an unsigned
12736 // type and the enum contain only positive values, MSVC++ will cause an
12737 // inconsistency by storing this as a signed type.
12738 if (S.getLangOpts().CPlusPlus11 &&
12739 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12740 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12741 BitfieldEnumDecl->getNumNegativeBits() == 0) {
12742 S.Diag(Loc: InitLoc, DiagID: diag::warn_no_underlying_type_specified_for_enum_bitfield)
12743 << BitfieldEnumDecl;
12744 }
12745 }
12746
12747 // Ignore value- or type-dependent expressions.
12748 if (Bitfield->getBitWidth()->isValueDependent() ||
12749 Bitfield->getBitWidth()->isTypeDependent() ||
12750 Init->isValueDependent() ||
12751 Init->isTypeDependent())
12752 return false;
12753
12754 Expr *OriginalInit = Init->IgnoreParenImpCasts();
12755 unsigned FieldWidth = Bitfield->getBitWidthValue();
12756
12757 Expr::EvalResult Result;
12758 if (!OriginalInit->EvaluateAsInt(Result, Ctx: S.Context,
12759 AllowSideEffects: Expr::SE_AllowSideEffects)) {
12760 // The RHS is not constant. If the RHS has an enum type, make sure the
12761 // bitfield is wide enough to hold all the values of the enum without
12762 // truncation.
12763 const auto *ED = OriginalInit->getType()->getAsEnumDecl();
12764 const PreferredTypeAttr *PTAttr = nullptr;
12765 if (!ED) {
12766 PTAttr = Bitfield->getAttr<PreferredTypeAttr>();
12767 if (PTAttr)
12768 ED = PTAttr->getType()->getAsEnumDecl();
12769 }
12770 if (ED) {
12771 bool SignedBitfield = BitfieldType->isSignedIntegerOrEnumerationType();
12772
12773 // Enum types are implicitly signed on Windows, so check if there are any
12774 // negative enumerators to see if the enum was intended to be signed or
12775 // not.
12776 bool SignedEnum = ED->getNumNegativeBits() > 0;
12777
12778 // Check for surprising sign changes when assigning enum values to a
12779 // bitfield of different signedness. If the bitfield is signed and we
12780 // have exactly the right number of bits to store this unsigned enum,
12781 // suggest changing the enum to an unsigned type. This typically happens
12782 // on Windows where unfixed enums always use an underlying type of 'int'.
12783 unsigned DiagID = 0;
12784 if (SignedEnum && !SignedBitfield) {
12785 DiagID =
12786 PTAttr == nullptr
12787 ? diag::warn_unsigned_bitfield_assigned_signed_enum
12788 : diag::
12789 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
12790 } else if (SignedBitfield && !SignedEnum &&
12791 ED->getNumPositiveBits() == FieldWidth) {
12792 DiagID =
12793 PTAttr == nullptr
12794 ? diag::warn_signed_bitfield_enum_conversion
12795 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
12796 }
12797 if (DiagID) {
12798 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
12799 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12800 SourceRange TypeRange =
12801 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12802 S.Diag(Loc: Bitfield->getTypeSpecStartLoc(), DiagID: diag::note_change_bitfield_sign)
12803 << SignedEnum << TypeRange;
12804 if (PTAttr)
12805 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
12806 << ED;
12807 }
12808
12809 // Compute the required bitwidth. If the enum has negative values, we need
12810 // one more bit than the normal number of positive bits to represent the
12811 // sign bit.
12812 unsigned BitsNeeded = SignedEnum ? std::max(a: ED->getNumPositiveBits() + 1,
12813 b: ED->getNumNegativeBits())
12814 : ED->getNumPositiveBits();
12815
12816 // Check the bitwidth.
12817 if (BitsNeeded > FieldWidth) {
12818 Expr *WidthExpr = Bitfield->getBitWidth();
12819 auto DiagID =
12820 PTAttr == nullptr
12821 ? diag::warn_bitfield_too_small_for_enum
12822 : diag::warn_preferred_type_bitfield_too_small_for_enum;
12823 S.Diag(Loc: InitLoc, DiagID) << Bitfield << ED;
12824 S.Diag(Loc: WidthExpr->getExprLoc(), DiagID: diag::note_widen_bitfield)
12825 << BitsNeeded << ED << WidthExpr->getSourceRange();
12826 if (PTAttr)
12827 S.Diag(Loc: PTAttr->getLocation(), DiagID: diag::note_bitfield_preferred_type)
12828 << ED;
12829 }
12830 }
12831
12832 return false;
12833 }
12834
12835 llvm::APSInt Value = Result.Val.getInt();
12836
12837 unsigned OriginalWidth = Value.getBitWidth();
12838
12839 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce
12840 // false positives where the user is demonstrating they intend to use the
12841 // bit-field as a Boolean, check to see if the value is 1 and we're assigning
12842 // to a one-bit bit-field to see if the value came from a macro named 'true'.
12843 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1;
12844 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) {
12845 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc();
12846 if (S.SourceMgr.isInSystemMacro(loc: MaybeMacroLoc) &&
12847 S.findMacroSpelling(loc&: MaybeMacroLoc, name: "true"))
12848 return false;
12849 }
12850
12851 if (!Value.isSigned() || Value.isNegative())
12852 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: OriginalInit))
12853 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12854 OriginalWidth = Value.getSignificantBits();
12855
12856 if (OriginalWidth <= FieldWidth)
12857 return false;
12858
12859 // Compute the value which the bitfield will contain.
12860 llvm::APSInt TruncatedValue = Value.trunc(width: FieldWidth);
12861 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12862
12863 // Check whether the stored value is equal to the original value.
12864 TruncatedValue = TruncatedValue.extend(width: OriginalWidth);
12865 if (llvm::APSInt::isSameValue(I1: Value, I2: TruncatedValue))
12866 return false;
12867
12868 std::string PrettyValue = toString(I: Value, Radix: 10);
12869 std::string PrettyTrunc = toString(I: TruncatedValue, Radix: 10);
12870
12871 S.Diag(Loc: InitLoc, DiagID: OneAssignedToOneBitBitfield
12872 ? diag::warn_impcast_single_bit_bitield_precision_constant
12873 : diag::warn_impcast_bitfield_precision_constant)
12874 << PrettyValue << PrettyTrunc << OriginalInit->getType()
12875 << Init->getSourceRange();
12876
12877 return true;
12878}
12879
12880/// Analyze the given simple or compound assignment for warning-worthy
12881/// operations.
12882static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12883 // Just recurse on the LHS.
12884 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
12885
12886 // We want to recurse on the RHS as normal unless we're assigning to
12887 // a bitfield.
12888 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12889 if (AnalyzeBitFieldAssignment(S, Bitfield, Init: E->getRHS(),
12890 InitLoc: E->getOperatorLoc())) {
12891 // Recurse, ignoring any implicit conversions on the RHS.
12892 return AnalyzeImplicitConversions(S, E: E->getRHS()->IgnoreParenImpCasts(),
12893 CC: E->getOperatorLoc());
12894 }
12895 }
12896
12897 // Set context flag for overflow behavior type assignment analysis, use RAII
12898 // pattern to handle nested assignments.
12899 llvm::SaveAndRestore OBTAssignmentContext(
12900 S.InOverflowBehaviorAssignmentContext, true);
12901
12902 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
12903
12904 // Diagnose implicitly sequentially-consistent atomic assignment.
12905 if (E->getLHS()->getType()->isAtomicType())
12906 S.Diag(Loc: E->getRHS()->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
12907}
12908
12909/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12910static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType,
12911 QualType T, SourceLocation CContext, unsigned diag,
12912 bool PruneControlFlow = false) {
12913 // For languages like HLSL and OpenCL, implicit conversion diagnostics listing
12914 // address space annotations isn't really useful. The warnings aren't because
12915 // you're converting a `private int` to `unsigned int`, it is because you're
12916 // conerting `int` to `unsigned int`.
12917 if (SourceType.hasAddressSpace())
12918 SourceType = S.getASTContext().removeAddrSpaceQualType(T: SourceType);
12919 if (T.hasAddressSpace())
12920 T = S.getASTContext().removeAddrSpaceQualType(T);
12921 if (PruneControlFlow) {
12922 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
12923 PD: S.PDiag(DiagID: diag)
12924 << SourceType << T << E->getSourceRange()
12925 << SourceRange(CContext));
12926 return;
12927 }
12928 S.Diag(Loc: E->getExprLoc(), DiagID: diag)
12929 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12930}
12931
12932/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
12933static void DiagnoseImpCast(Sema &S, const Expr *E, QualType T,
12934 SourceLocation CContext, unsigned diag,
12935 bool PruneControlFlow = false) {
12936 DiagnoseImpCast(S, E, SourceType: E->getType(), T, CContext, diag, PruneControlFlow);
12937}
12938
12939/// Diagnose an implicit cast from a floating point value to an integer value.
12940static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T,
12941 SourceLocation CContext) {
12942 bool IsBool = T->isSpecificBuiltinType(K: BuiltinType::Bool);
12943 bool PruneWarnings = S.inTemplateInstantiation();
12944
12945 const Expr *InnerE = E->IgnoreParenImpCasts();
12946 // We also want to warn on, e.g., "int i = -1.234"
12947 if (const auto *UOp = dyn_cast<UnaryOperator>(Val: InnerE))
12948 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12949 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12950
12951 bool IsLiteral = isa<FloatingLiteral>(Val: E) || isa<FloatingLiteral>(Val: InnerE);
12952
12953 llvm::APFloat Value(0.0);
12954 bool IsConstant =
12955 E->EvaluateAsFloat(Result&: Value, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects);
12956 if (!IsConstant) {
12957 if (S.ObjC().isSignedCharBool(Ty: T)) {
12958 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
12959 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_float_to_objc_signed_char_bool)
12960 << E->getType());
12961 }
12962
12963 return DiagnoseImpCast(S, E, T, CContext,
12964 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
12965 }
12966
12967 bool isExact = false;
12968
12969 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12970 T->hasUnsignedIntegerRepresentation());
12971 llvm::APFloat::opStatus Result = Value.convertToInteger(
12972 Result&: IntegerValue, RM: llvm::APFloat::rmTowardZero, IsExact: &isExact);
12973
12974 // FIXME: Force the precision of the source value down so we don't print
12975 // digits which are usually useless (we don't really care here if we
12976 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
12977 // would automatically print the shortest representation, but it's a bit
12978 // tricky to implement.
12979 SmallString<16> PrettySourceValue;
12980 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12981 precision = (precision * 59 + 195) / 196;
12982 Value.toString(Str&: PrettySourceValue, FormatPrecision: precision);
12983
12984 if (S.ObjC().isSignedCharBool(Ty: T) && IntegerValue != 0 && IntegerValue != 1) {
12985 return S.ObjC().adornBoolConversionDiagWithTernaryFixit(
12986 SourceExpr: E, Builder: S.Diag(Loc: CContext, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
12987 << PrettySourceValue);
12988 }
12989
12990 if (Result == llvm::APFloat::opOK && isExact) {
12991 if (IsLiteral) return;
12992 return DiagnoseImpCast(S, E, T, CContext, diag: diag::warn_impcast_float_integer,
12993 PruneControlFlow: PruneWarnings);
12994 }
12995
12996 // Conversion of a floating-point value to a non-bool integer where the
12997 // integral part cannot be represented by the integer type is undefined.
12998 if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12999 return DiagnoseImpCast(
13000 S, E, T, CContext,
13001 diag: IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13002 : diag::warn_impcast_float_to_integer_out_of_range,
13003 PruneControlFlow: PruneWarnings);
13004
13005 unsigned DiagID = 0;
13006 if (IsLiteral) {
13007 // Warn on floating point literal to integer.
13008 DiagID = diag::warn_impcast_literal_float_to_integer;
13009 } else if (IntegerValue == 0) {
13010 if (Value.isZero()) { // Skip -0.0 to 0 conversion.
13011 return DiagnoseImpCast(S, E, T, CContext,
13012 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13013 }
13014 // Warn on non-zero to zero conversion.
13015 DiagID = diag::warn_impcast_float_to_integer_zero;
13016 } else {
13017 if (IntegerValue.isUnsigned()) {
13018 if (!IntegerValue.isMaxValue()) {
13019 return DiagnoseImpCast(S, E, T, CContext,
13020 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13021 }
13022 } else { // IntegerValue.isSigned()
13023 if (!IntegerValue.isMaxSignedValue() &&
13024 !IntegerValue.isMinSignedValue()) {
13025 return DiagnoseImpCast(S, E, T, CContext,
13026 diag: diag::warn_impcast_float_integer, PruneControlFlow: PruneWarnings);
13027 }
13028 }
13029 // Warn on evaluatable floating point expression to integer conversion.
13030 DiagID = diag::warn_impcast_float_to_integer;
13031 }
13032
13033 SmallString<16> PrettyTargetValue;
13034 if (IsBool)
13035 PrettyTargetValue = Value.isZero() ? "false" : "true";
13036 else
13037 IntegerValue.toString(Str&: PrettyTargetValue);
13038
13039 if (PruneWarnings) {
13040 S.DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13041 PD: S.PDiag(DiagID)
13042 << E->getType() << T.getUnqualifiedType()
13043 << PrettySourceValue << PrettyTargetValue
13044 << E->getSourceRange() << SourceRange(CContext));
13045 } else {
13046 S.Diag(Loc: E->getExprLoc(), DiagID)
13047 << E->getType() << T.getUnqualifiedType() << PrettySourceValue
13048 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
13049 }
13050}
13051
13052/// Analyze the given compound assignment for the possible losing of
13053/// floating-point precision.
13054static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
13055 assert(isa<CompoundAssignOperator>(E) &&
13056 "Must be compound assignment operation");
13057 // Recurse on the LHS and RHS in here
13058 AnalyzeImplicitConversions(S, E: E->getLHS(), CC: E->getOperatorLoc());
13059 AnalyzeImplicitConversions(S, E: E->getRHS(), CC: E->getOperatorLoc());
13060
13061 if (E->getLHS()->getType()->isAtomicType())
13062 S.Diag(Loc: E->getOperatorLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13063
13064 // Now check the outermost expression
13065 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
13066 const auto *RBT = cast<CompoundAssignOperator>(Val: E)
13067 ->getComputationResultType()
13068 ->getAs<BuiltinType>();
13069
13070 // The below checks assume source is floating point.
13071 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
13072
13073 // If source is floating point but target is an integer.
13074 if (ResultBT->isInteger())
13075 return DiagnoseImpCast(S, E, SourceType: E->getRHS()->getType(), T: E->getLHS()->getType(),
13076 CContext: E->getExprLoc(), diag: diag::warn_impcast_float_integer);
13077
13078 if (!ResultBT->isFloatingPoint())
13079 return;
13080
13081 // If both source and target are floating points, warn about losing precision.
13082 int Order = S.getASTContext().getFloatingTypeSemanticOrder(
13083 LHS: QualType(ResultBT, 0), RHS: QualType(RBT, 0));
13084 if (Order < 0 && !S.SourceMgr.isInSystemMacro(loc: E->getOperatorLoc()))
13085 // warn about dropping FP rank.
13086 DiagnoseImpCast(S, E: E->getRHS(), T: E->getLHS()->getType(), CContext: E->getOperatorLoc(),
13087 diag: diag::warn_impcast_float_result_precision);
13088}
13089
13090static std::string PrettyPrintInRange(const llvm::APSInt &Value,
13091 IntRange Range) {
13092 if (!Range.Width) return "0";
13093
13094 llvm::APSInt ValueInRange = Value;
13095 ValueInRange.setIsSigned(!Range.NonNegative);
13096 ValueInRange = ValueInRange.trunc(width: Range.Width);
13097 return toString(I: ValueInRange, Radix: 10);
13098}
13099
13100static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex,
13101 bool ToBool) {
13102 if (!isa<ImplicitCastExpr>(Val: Ex))
13103 return false;
13104
13105 const Expr *InnerE = Ex->IgnoreParenImpCasts();
13106 const Type *Target = S.Context.getCanonicalType(T: Ex->getType()).getTypePtr();
13107 const Type *Source =
13108 S.Context.getCanonicalType(T: InnerE->getType()).getTypePtr();
13109 if (Target->isDependentType())
13110 return false;
13111
13112 const auto *FloatCandidateBT =
13113 dyn_cast<BuiltinType>(Val: ToBool ? Source : Target);
13114 const Type *BoolCandidateType = ToBool ? Target : Source;
13115
13116 return (BoolCandidateType->isSpecificBuiltinType(K: BuiltinType::Bool) &&
13117 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13118}
13119
13120static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall,
13121 SourceLocation CC) {
13122 for (unsigned I = 0, N = TheCall->getNumArgs(); I < N; ++I) {
13123 const Expr *CurrA = TheCall->getArg(Arg: I);
13124 if (!IsImplicitBoolFloatConversion(S, Ex: CurrA, ToBool: true))
13125 continue;
13126
13127 bool IsSwapped = ((I > 0) && IsImplicitBoolFloatConversion(
13128 S, Ex: TheCall->getArg(Arg: I - 1), ToBool: false));
13129 IsSwapped |= ((I < (N - 1)) && IsImplicitBoolFloatConversion(
13130 S, Ex: TheCall->getArg(Arg: I + 1), ToBool: false));
13131 if (IsSwapped) {
13132 // Warn on this floating-point to bool conversion.
13133 DiagnoseImpCast(S, E: CurrA->IgnoreParenImpCasts(),
13134 T: CurrA->getType(), CContext: CC,
13135 diag: diag::warn_impcast_floating_point_to_bool);
13136 }
13137 }
13138}
13139
13140static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
13141 SourceLocation CC) {
13142 // Don't warn on functions which have return type nullptr_t.
13143 if (isa<CallExpr>(Val: E))
13144 return;
13145
13146 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
13147 const Expr *NewE = E->IgnoreParenImpCasts();
13148 bool IsGNUNullExpr = isa<GNUNullExpr>(Val: NewE);
13149 bool HasNullPtrType = NewE->getType()->isNullPtrType();
13150 if (!IsGNUNullExpr && !HasNullPtrType)
13151 return;
13152
13153 // Return if target type is a safe conversion.
13154 if (T->isAnyPointerType() || T->isBlockPointerType() ||
13155 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
13156 return;
13157
13158 if (S.Diags.isIgnored(DiagID: diag::warn_impcast_null_pointer_to_integer,
13159 Loc: E->getExprLoc()))
13160 return;
13161
13162 SourceLocation Loc = E->getSourceRange().getBegin();
13163
13164 // Venture through the macro stacks to get to the source of macro arguments.
13165 // The new location is a better location than the complete location that was
13166 // passed in.
13167 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
13168 CC = S.SourceMgr.getTopMacroCallerLoc(Loc: CC);
13169
13170 // __null is usually wrapped in a macro. Go up a macro if that is the case.
13171 if (IsGNUNullExpr && Loc.isMacroID()) {
13172 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
13173 Loc, SM: S.SourceMgr, LangOpts: S.getLangOpts());
13174 if (MacroName == "NULL")
13175 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
13176 }
13177
13178 // Only warn if the null and context location are in the same macro expansion.
13179 if (S.SourceMgr.getFileID(SpellingLoc: Loc) != S.SourceMgr.getFileID(SpellingLoc: CC))
13180 return;
13181
13182 S.Diag(Loc, DiagID: diag::warn_impcast_null_pointer_to_integer)
13183 << HasNullPtrType << T << SourceRange(CC)
13184 << FixItHint::CreateReplacement(RemoveRange: Loc,
13185 Code: S.getFixItZeroLiteralForType(T, Loc));
13186}
13187
13188// Helper function to filter out cases for constant width constant conversion.
13189// Don't warn on char array initialization or for non-decimal values.
13190static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
13191 SourceLocation CC) {
13192 // If initializing from a constant, and the constant starts with '0',
13193 // then it is a binary, octal, or hexadecimal. Allow these constants
13194 // to fill all the bits, even if there is a sign change.
13195 if (auto *IntLit = dyn_cast<IntegerLiteral>(Val: E->IgnoreParenImpCasts())) {
13196 const char FirstLiteralCharacter =
13197 S.getSourceManager().getCharacterData(SL: IntLit->getBeginLoc())[0];
13198 if (FirstLiteralCharacter == '0')
13199 return false;
13200 }
13201
13202 // If the CC location points to a '{', and the type is char, then assume
13203 // assume it is an array initialization.
13204 if (CC.isValid() && T->isCharType()) {
13205 const char FirstContextCharacter =
13206 S.getSourceManager().getCharacterData(SL: CC)[0];
13207 if (FirstContextCharacter == '{')
13208 return false;
13209 }
13210
13211 return true;
13212}
13213
13214static const IntegerLiteral *getIntegerLiteral(Expr *E) {
13215 const auto *IL = dyn_cast<IntegerLiteral>(Val: E);
13216 if (!IL) {
13217 if (auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
13218 if (UO->getOpcode() == UO_Minus)
13219 return dyn_cast<IntegerLiteral>(Val: UO->getSubExpr());
13220 }
13221 }
13222
13223 return IL;
13224}
13225
13226static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
13227 E = E->IgnoreParenImpCasts();
13228 SourceLocation ExprLoc = E->getExprLoc();
13229
13230 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E)) {
13231 BinaryOperator::Opcode Opc = BO->getOpcode();
13232 Expr::EvalResult Result;
13233 // Do not diagnose unsigned shifts.
13234 if (Opc == BO_Shl) {
13235 const auto *LHS = getIntegerLiteral(E: BO->getLHS());
13236 const auto *RHS = getIntegerLiteral(E: BO->getRHS());
13237 if (LHS && LHS->getValue() == 0)
13238 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always) << 0;
13239 else if (!E->isValueDependent() && LHS && RHS &&
13240 RHS->getValue().isNonNegative() &&
13241 E->EvaluateAsInt(Result, Ctx: S.Context, AllowSideEffects: Expr::SE_AllowSideEffects))
13242 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_always)
13243 << (Result.Val.getInt() != 0);
13244 else if (E->getType()->isSignedIntegerType())
13245 S.Diag(Loc: ExprLoc, DiagID: diag::warn_left_shift_in_bool_context)
13246 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "(")
13247 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: E->getEndLoc()),
13248 Code: ") != 0");
13249 }
13250 }
13251
13252 if (const auto *CO = dyn_cast<ConditionalOperator>(Val: E)) {
13253 const auto *LHS = getIntegerLiteral(E: CO->getTrueExpr());
13254 const auto *RHS = getIntegerLiteral(E: CO->getFalseExpr());
13255 if (!LHS || !RHS)
13256 return;
13257 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13258 (RHS->getValue() == 0 || RHS->getValue() == 1))
13259 // Do not diagnose common idioms.
13260 return;
13261 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13262 S.Diag(Loc: ExprLoc, DiagID: diag::warn_integer_constants_in_conditional_always_true);
13263 }
13264}
13265
13266static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source,
13267 const Type *Target, Expr *E,
13268 QualType T,
13269 SourceLocation CC) {
13270 assert(Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType() &&
13271 Source != Target);
13272
13273 // Lone surrogates have a distinct representation in UTF-32.
13274 // Converting between UTF-16 and UTF-32 codepoints seems very widespread,
13275 // so don't warn on such conversion.
13276 if (Source->isChar16Type() && Target->isChar32Type())
13277 return;
13278
13279 Expr::EvalResult Result;
13280 if (E->EvaluateAsInt(Result, Ctx: S.getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects,
13281 InConstantContext: S.isConstantEvaluatedContext())) {
13282 llvm::APSInt Value(32);
13283 Value = Result.Val.getInt();
13284 bool IsASCII = Value <= 0x7F;
13285 bool IsBMP = Value <= 0xDFFF || (Value >= 0xE000 && Value <= 0xFFFF);
13286 bool ConversionPreservesSemantics =
13287 IsASCII || (!Source->isChar8Type() && !Target->isChar8Type() && IsBMP);
13288
13289 if (!ConversionPreservesSemantics) {
13290 auto IsSingleCodeUnitCP = [](const QualType &T,
13291 const llvm::APSInt &Value) {
13292 if (T->isChar8Type())
13293 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
13294 if (T->isChar16Type())
13295 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
13296 assert(T->isChar32Type());
13297 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
13298 };
13299
13300 S.Diag(Loc: CC, DiagID: diag::warn_impcast_unicode_char_type_constant)
13301 << E->getType() << T
13302 << IsSingleCodeUnitCP(E->getType().getUnqualifiedType(), Value)
13303 << FormatUTFCodeUnitAsCodepoint(Value: Value.getExtValue(), T: E->getType());
13304 }
13305 } else {
13306 bool LosesPrecision = S.getASTContext().getIntWidth(T: E->getType()) >
13307 S.getASTContext().getIntWidth(T);
13308 DiagnoseImpCast(S, E, T, CContext: CC,
13309 diag: LosesPrecision ? diag::warn_impcast_unicode_precision
13310 : diag::warn_impcast_unicode_char_type);
13311 }
13312}
13313
13314bool Sema::DiscardingCFIUncheckedCallee(QualType From, QualType To) const {
13315 From = Context.getCanonicalType(T: From);
13316 To = Context.getCanonicalType(T: To);
13317 QualType MaybePointee = From->getPointeeType();
13318 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13319 From = MaybePointee;
13320 MaybePointee = To->getPointeeType();
13321 if (!MaybePointee.isNull() && MaybePointee->getAs<FunctionType>())
13322 To = MaybePointee;
13323
13324 if (const auto *FromFn = From->getAs<FunctionType>()) {
13325 if (const auto *ToFn = To->getAs<FunctionType>()) {
13326 if (FromFn->getCFIUncheckedCalleeAttr() &&
13327 !ToFn->getCFIUncheckedCalleeAttr())
13328 return true;
13329 }
13330 }
13331 return false;
13332}
13333
13334void Sema::CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC,
13335 bool *ICContext, bool IsListInit) {
13336 if (E->isTypeDependent() || E->isValueDependent()) return;
13337
13338 const Type *Source = Context.getCanonicalType(T: E->getType()).getTypePtr();
13339 const Type *Target = Context.getCanonicalType(T).getTypePtr();
13340 if (Source == Target) return;
13341 if (Target->isDependentType()) return;
13342
13343 // If the conversion context location is invalid don't complain. We also
13344 // don't want to emit a warning if the issue occurs from the expansion of
13345 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
13346 // delay this check as long as possible. Once we detect we are in that
13347 // scenario, we just return.
13348 if (CC.isInvalid())
13349 return;
13350
13351 if (Source->isAtomicType())
13352 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
13353
13354 // Diagnose implicit casts to bool.
13355 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool)) {
13356 if (isa<StringLiteral>(Val: E))
13357 // Warn on string literal to bool. Checks for string literals in logical
13358 // and expressions, for instance, assert(0 && "error here"), are
13359 // prevented by a check in AnalyzeImplicitConversions().
13360 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13361 diag: diag::warn_impcast_string_literal_to_bool);
13362 if (isa<ObjCStringLiteral>(Val: E) || isa<ObjCArrayLiteral>(Val: E) ||
13363 isa<ObjCDictionaryLiteral>(Val: E) || isa<ObjCBoxedExpr>(Val: E)) {
13364 // This covers the literal expressions that evaluate to Objective-C
13365 // objects.
13366 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13367 diag: diag::warn_impcast_objective_c_literal_to_bool);
13368 }
13369 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13370 // Warn on pointer to bool conversion that is always true.
13371 DiagnoseAlwaysNonNullPointer(E, NullType: Expr::NPCK_NotNull, /*IsEqual*/ false,
13372 Range: SourceRange(CC));
13373 }
13374 }
13375
13376 CheckOverflowBehaviorTypeConversion(E, T, CC);
13377
13378 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
13379 // is a typedef for signed char (macOS), then that constant value has to be 1
13380 // or 0.
13381 if (ObjC().isSignedCharBool(Ty: T) && Source->isIntegralType(Ctx: Context)) {
13382 Expr::EvalResult Result;
13383 if (E->EvaluateAsInt(Result, Ctx: getASTContext(), AllowSideEffects: Expr::SE_AllowSideEffects)) {
13384 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
13385 ObjC().adornBoolConversionDiagWithTernaryFixit(
13386 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_constant_value_to_objc_bool)
13387 << toString(I: Result.Val.getInt(), Radix: 10));
13388 }
13389 return;
13390 }
13391 }
13392
13393 // Check implicit casts from Objective-C collection literals to specialized
13394 // collection types, e.g., NSArray<NSString *> *.
13395 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Val: E))
13396 ObjC().checkArrayLiteral(TargetType: QualType(Target, 0), ArrayLiteral);
13397 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Val: E))
13398 ObjC().checkDictionaryLiteral(TargetType: QualType(Target, 0), DictionaryLiteral);
13399
13400 // Strip complex types.
13401 if (isa<ComplexType>(Val: Source)) {
13402 if (!isa<ComplexType>(Val: Target)) {
13403 if (SourceMgr.isInSystemMacro(loc: CC) || Target->isBooleanType())
13404 return;
13405
13406 if (!getLangOpts().CPlusPlus && Target->isVectorType()) {
13407 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13408 diag: diag::err_impcast_incompatible_type);
13409 }
13410
13411 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13412 diag: getLangOpts().CPlusPlus
13413 ? diag::err_impcast_complex_scalar
13414 : diag::warn_impcast_complex_scalar);
13415 }
13416
13417 Source = cast<ComplexType>(Val: Source)->getElementType().getTypePtr();
13418 Target = cast<ComplexType>(Val: Target)->getElementType().getTypePtr();
13419 }
13420
13421 // Strip vector types.
13422 if (isa<VectorType>(Val: Source)) {
13423 if (Target->isSveVLSBuiltinType() &&
13424 (ARM().areCompatibleSveTypes(FirstType: QualType(Target, 0),
13425 SecondType: QualType(Source, 0)) ||
13426 ARM().areLaxCompatibleSveTypes(FirstType: QualType(Target, 0),
13427 SecondType: QualType(Source, 0))))
13428 return;
13429
13430 if (Target->isRVVVLSBuiltinType() &&
13431 (Context.areCompatibleRVVTypes(FirstType: QualType(Target, 0),
13432 SecondType: QualType(Source, 0)) ||
13433 Context.areLaxCompatibleRVVTypes(FirstType: QualType(Target, 0),
13434 SecondType: QualType(Source, 0))))
13435 return;
13436
13437 if (!isa<VectorType>(Val: Target)) {
13438 if (SourceMgr.isInSystemMacro(loc: CC))
13439 return;
13440 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_vector_scalar);
13441 }
13442 if (getLangOpts().HLSL &&
13443 Target->castAs<VectorType>()->getNumElements() <
13444 Source->castAs<VectorType>()->getNumElements()) {
13445 // Diagnose vector truncation but don't return. We may also want to
13446 // diagnose an element conversion.
13447 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13448 diag: diag::warn_hlsl_impcast_vector_truncation);
13449 }
13450
13451 // If the vector cast is cast between two vectors of the same size, it is
13452 // a bitcast, not a conversion, except under HLSL where it is a conversion.
13453 if (!getLangOpts().HLSL &&
13454 Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13455 return;
13456
13457 Source = cast<VectorType>(Val: Source)->getElementType().getTypePtr();
13458 Target = cast<VectorType>(Val: Target)->getElementType().getTypePtr();
13459 }
13460 if (const auto *VecTy = dyn_cast<VectorType>(Val: Target))
13461 Target = VecTy->getElementType().getTypePtr();
13462
13463 // Strip matrix types.
13464 if (isa<ConstantMatrixType>(Val: Source)) {
13465 if (Target->isScalarType())
13466 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_matrix_scalar);
13467
13468 if (getLangOpts().HLSL && isa<ConstantMatrixType>(Val: Target) &&
13469 Target->castAs<ConstantMatrixType>()->getNumElementsFlattened() <
13470 Source->castAs<ConstantMatrixType>()->getNumElementsFlattened()) {
13471 // Diagnose Matrix truncation but don't return. We may also want to
13472 // diagnose an element conversion.
13473 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13474 diag: diag::warn_hlsl_impcast_matrix_truncation);
13475 }
13476
13477 Source = cast<ConstantMatrixType>(Val: Source)->getElementType().getTypePtr();
13478 Target = cast<ConstantMatrixType>(Val: Target)->getElementType().getTypePtr();
13479 }
13480 if (const auto *MatTy = dyn_cast<ConstantMatrixType>(Val: Target))
13481 Target = MatTy->getElementType().getTypePtr();
13482
13483 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Val: Source);
13484 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Val: Target);
13485
13486 // Strip SVE vector types
13487 if (SourceBT && SourceBT->isSveVLSBuiltinType()) {
13488 // Need the original target type for vector type checks
13489 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr();
13490 // Handle conversion from scalable to fixed when msve-vector-bits is
13491 // specified
13492 if (ARM().areCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13493 SecondType: QualType(Source, 0)) ||
13494 ARM().areLaxCompatibleSveTypes(FirstType: QualType(OriginalTarget, 0),
13495 SecondType: QualType(Source, 0)))
13496 return;
13497
13498 // If the vector cast is cast between two vectors of the same size, it is
13499 // a bitcast, not a conversion.
13500 if (Context.getTypeSize(T: Source) == Context.getTypeSize(T: Target))
13501 return;
13502
13503 Source = SourceBT->getSveEltType(Ctx: Context).getTypePtr();
13504 }
13505
13506 if (TargetBT && TargetBT->isSveVLSBuiltinType())
13507 Target = TargetBT->getSveEltType(Ctx: Context).getTypePtr();
13508
13509 // If the source is floating point...
13510 if (SourceBT && SourceBT->isFloatingPoint()) {
13511 // ...and the target is floating point...
13512 if (TargetBT && TargetBT->isFloatingPoint()) {
13513 // ...then warn if we're dropping FP rank.
13514
13515 int Order = getASTContext().getFloatingTypeSemanticOrder(
13516 LHS: QualType(SourceBT, 0), RHS: QualType(TargetBT, 0));
13517 if (Order > 0) {
13518 // Don't warn about float constants that are precisely
13519 // representable in the target type.
13520 Expr::EvalResult result;
13521 if (E->EvaluateAsRValue(Result&: result, Ctx: Context)) {
13522 // Value might be a float, a float vector, or a float complex.
13523 if (IsSameFloatAfterCast(
13524 value: result.Val,
13525 Src: Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)),
13526 Tgt: Context.getFloatTypeSemantics(T: QualType(SourceBT, 0))))
13527 return;
13528 }
13529
13530 if (SourceMgr.isInSystemMacro(loc: CC))
13531 return;
13532
13533 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_float_precision);
13534 }
13535 // ... or possibly if we're increasing rank, too
13536 else if (Order < 0) {
13537 if (SourceMgr.isInSystemMacro(loc: CC))
13538 return;
13539
13540 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_double_promotion);
13541 }
13542 return;
13543 }
13544
13545 // If the target is integral, always warn.
13546 if (TargetBT && TargetBT->isInteger()) {
13547 if (SourceMgr.isInSystemMacro(loc: CC))
13548 return;
13549
13550 DiagnoseFloatingImpCast(S&: *this, E, T, CContext: CC);
13551 }
13552
13553 // Detect the case where a call result is converted from floating-point to
13554 // to bool, and the final argument to the call is converted from bool, to
13555 // discover this typo:
13556 //
13557 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;"
13558 //
13559 // FIXME: This is an incredibly special case; is there some more general
13560 // way to detect this class of misplaced-parentheses bug?
13561 if (Target->isBooleanType() && isa<CallExpr>(Val: E)) {
13562 // Check last argument of function call to see if it is an
13563 // implicit cast from a type matching the type the result
13564 // is being cast to.
13565 CallExpr *CEx = cast<CallExpr>(Val: E);
13566 if (unsigned NumArgs = CEx->getNumArgs()) {
13567 Expr *LastA = CEx->getArg(Arg: NumArgs - 1);
13568 Expr *InnerE = LastA->IgnoreParenImpCasts();
13569 if (isa<ImplicitCastExpr>(Val: LastA) &&
13570 InnerE->getType()->isBooleanType()) {
13571 // Warn on this floating-point to bool conversion
13572 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13573 diag: diag::warn_impcast_floating_point_to_bool);
13574 }
13575 }
13576 }
13577 return;
13578 }
13579
13580 // Valid casts involving fixed point types should be accounted for here.
13581 if (Source->isFixedPointType()) {
13582 if (Target->isUnsaturatedFixedPointType()) {
13583 Expr::EvalResult Result;
13584 if (E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13585 InConstantContext: isConstantEvaluatedContext())) {
13586 llvm::APFixedPoint Value = Result.Val.getFixedPoint();
13587 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(Ty: T);
13588 llvm::APFixedPoint MinVal = Context.getFixedPointMin(Ty: T);
13589 if (Value > MaxVal || Value < MinVal) {
13590 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13591 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13592 << Value.toString() << T
13593 << E->getSourceRange()
13594 << clang::SourceRange(CC));
13595 return;
13596 }
13597 }
13598 } else if (Target->isIntegerType()) {
13599 Expr::EvalResult Result;
13600 if (!isConstantEvaluatedContext() &&
13601 E->EvaluateAsFixedPoint(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13602 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
13603
13604 bool Overflowed;
13605 llvm::APSInt IntResult = FXResult.convertToInt(
13606 DstWidth: Context.getIntWidth(T), DstSign: Target->isSignedIntegerOrEnumerationType(),
13607 Overflow: &Overflowed);
13608
13609 if (Overflowed) {
13610 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13611 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13612 << FXResult.toString() << T
13613 << E->getSourceRange()
13614 << clang::SourceRange(CC));
13615 return;
13616 }
13617 }
13618 }
13619 } else if (Target->isUnsaturatedFixedPointType()) {
13620 if (Source->isIntegerType()) {
13621 Expr::EvalResult Result;
13622 if (!isConstantEvaluatedContext() &&
13623 E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects)) {
13624 llvm::APSInt Value = Result.Val.getInt();
13625
13626 bool Overflowed;
13627 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13628 Value, DstFXSema: Context.getFixedPointSemantics(Ty: T), Overflow: &Overflowed);
13629
13630 if (Overflowed) {
13631 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13632 PD: PDiag(DiagID: diag::warn_impcast_fixed_point_range)
13633 << toString(I: Value, /*Radix=*/10) << T
13634 << E->getSourceRange()
13635 << clang::SourceRange(CC));
13636 return;
13637 }
13638 }
13639 }
13640 }
13641
13642 // If we are casting an integer type to a floating point type without
13643 // initialization-list syntax, we might lose accuracy if the floating
13644 // point type has a narrower significand than the integer type.
13645 if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13646 TargetBT->isFloatingType() && !IsListInit) {
13647 // Determine the number of precision bits in the source integer type.
13648 std::optional<IntRange> SourceRange =
13649 TryGetExprRange(C&: Context, E, InConstantContext: isConstantEvaluatedContext(),
13650 /*Approximate=*/true);
13651 if (!SourceRange)
13652 return;
13653 unsigned int SourcePrecision = SourceRange->Width;
13654
13655 // Determine the number of precision bits in the
13656 // target floating point type.
13657 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13658 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13659
13660 if (SourcePrecision > 0 && TargetPrecision > 0 &&
13661 SourcePrecision > TargetPrecision) {
13662
13663 if (std::optional<llvm::APSInt> SourceInt =
13664 E->getIntegerConstantExpr(Ctx: Context)) {
13665 // If the source integer is a constant, convert it to the target
13666 // floating point type. Issue a warning if the value changes
13667 // during the whole conversion.
13668 llvm::APFloat TargetFloatValue(
13669 Context.getFloatTypeSemantics(T: QualType(TargetBT, 0)));
13670 llvm::APFloat::opStatus ConversionStatus =
13671 TargetFloatValue.convertFromAPInt(
13672 Input: *SourceInt, IsSigned: SourceBT->isSignedInteger(),
13673 RM: llvm::APFloat::rmNearestTiesToEven);
13674
13675 if (ConversionStatus != llvm::APFloat::opOK) {
13676 SmallString<32> PrettySourceValue;
13677 SourceInt->toString(Str&: PrettySourceValue, Radix: 10);
13678 SmallString<32> PrettyTargetValue;
13679 TargetFloatValue.toString(Str&: PrettyTargetValue, FormatPrecision: TargetPrecision);
13680
13681 DiagRuntimeBehavior(
13682 Loc: E->getExprLoc(), Statement: E,
13683 PD: PDiag(DiagID: diag::warn_impcast_integer_float_precision_constant)
13684 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13685 << E->getSourceRange() << clang::SourceRange(CC));
13686 }
13687 } else {
13688 // Otherwise, the implicit conversion may lose precision.
13689 DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13690 diag: diag::warn_impcast_integer_float_precision);
13691 }
13692 }
13693 }
13694
13695 DiagnoseNullConversion(S&: *this, E, T, CC);
13696
13697 DiscardMisalignedMemberAddress(T: Target, E);
13698
13699 if (Source->isUnicodeCharacterType() && Target->isUnicodeCharacterType()) {
13700 DiagnoseMixedUnicodeImplicitConversion(S&: *this, Source, Target, E, T, CC);
13701 return;
13702 }
13703
13704 if (Target->isBooleanType())
13705 DiagnoseIntInBoolContext(S&: *this, E);
13706
13707 if (DiscardingCFIUncheckedCallee(From: QualType(Source, 0), To: QualType(Target, 0))) {
13708 Diag(Loc: CC, DiagID: diag::warn_cast_discards_cfi_unchecked_callee)
13709 << QualType(Source, 0) << QualType(Target, 0);
13710 }
13711
13712 if (!Source->isIntegerType() || !Target->isIntegerType())
13713 return;
13714
13715 // TODO: remove this early return once the false positives for constant->bool
13716 // in templates, macros, etc, are reduced or removed.
13717 if (Target->isSpecificBuiltinType(K: BuiltinType::Bool))
13718 return;
13719
13720 if (ObjC().isSignedCharBool(Ty: T) && !Source->isCharType() &&
13721 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13722 return ObjC().adornBoolConversionDiagWithTernaryFixit(
13723 SourceExpr: E, Builder: Diag(Loc: CC, DiagID: diag::warn_impcast_int_to_objc_signed_char_bool)
13724 << E->getType());
13725 }
13726 std::optional<IntRange> LikelySourceRange = TryGetExprRange(
13727 C&: Context, E, InConstantContext: isConstantEvaluatedContext(), /*Approximate=*/true);
13728 if (!LikelySourceRange)
13729 return;
13730
13731 IntRange SourceTypeRange =
13732 IntRange::forTargetOfCanonicalType(C&: Context, T: Source);
13733 IntRange TargetRange = IntRange::forTargetOfCanonicalType(C&: Context, T: Target);
13734
13735 if (LikelySourceRange->Width > TargetRange.Width) {
13736 // Check if target is a wrapping OBT - if so, don't warn about constant
13737 // conversion as this type may be used intentionally with implicit
13738 // truncation, especially during assignments.
13739 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
13740 if (TargetOBT->isWrapKind()) {
13741 return;
13742 }
13743 }
13744
13745 // Check if source expression has an explicit __ob_wrap cast because if so,
13746 // wrapping was explicitly requested and we shouldn't warn
13747 if (const auto *SourceOBT = E->getType()->getAs<OverflowBehaviorType>()) {
13748 if (SourceOBT->isWrapKind()) {
13749 return;
13750 }
13751 }
13752
13753 // If the source is a constant, use a default-on diagnostic.
13754 // TODO: this should happen for bitfield stores, too.
13755 Expr::EvalResult Result;
13756 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects,
13757 InConstantContext: isConstantEvaluatedContext())) {
13758 llvm::APSInt Value(32);
13759 Value = Result.Val.getInt();
13760
13761 if (SourceMgr.isInSystemMacro(loc: CC))
13762 return;
13763
13764 std::string PrettySourceValue = toString(I: Value, Radix: 10);
13765 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
13766
13767 DiagRuntimeBehavior(Loc: E->getExprLoc(), Statement: E,
13768 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
13769 << PrettySourceValue << PrettyTargetValue
13770 << E->getType() << T << E->getSourceRange()
13771 << SourceRange(CC));
13772 return;
13773 }
13774
13775 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13776 if (SourceMgr.isInSystemMacro(loc: CC))
13777 return;
13778
13779 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E)) {
13780 if (UO->getOpcode() == UO_Minus)
13781 return DiagnoseImpCast(
13782 S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_precision_on_negation);
13783 }
13784
13785 if (TargetRange.Width == 32 && Context.getIntWidth(T: E->getType()) == 64)
13786 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_integer_64_32,
13787 /* pruneControlFlow */ PruneControlFlow: true);
13788 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13789 diag: diag::warn_impcast_integer_precision);
13790 }
13791
13792 if (TargetRange.Width > SourceTypeRange.Width) {
13793 if (auto *UO = dyn_cast<UnaryOperator>(Val: E))
13794 if (UO->getOpcode() == UO_Minus)
13795 if (Source->isUnsignedIntegerType()) {
13796 if (Target->isUnsignedIntegerType())
13797 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13798 diag: diag::warn_impcast_high_order_zero_bits);
13799 if (Target->isSignedIntegerType())
13800 return DiagnoseImpCast(S&: *this, E, T, CContext: CC,
13801 diag: diag::warn_impcast_nonnegative_result);
13802 }
13803 }
13804
13805 if (TargetRange.Width == LikelySourceRange->Width &&
13806 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13807 Source->isSignedIntegerType()) {
13808 // Warn when doing a signed to signed conversion, warn if the positive
13809 // source value is exactly the width of the target type, which will
13810 // cause a negative value to be stored.
13811
13812 Expr::EvalResult Result;
13813 if (E->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects) &&
13814 !SourceMgr.isInSystemMacro(loc: CC)) {
13815 llvm::APSInt Value = Result.Val.getInt();
13816 if (isSameWidthConstantConversion(S&: *this, E, T, CC)) {
13817 std::string PrettySourceValue = toString(I: Value, Radix: 10);
13818 std::string PrettyTargetValue = PrettyPrintInRange(Value, Range: TargetRange);
13819
13820 Diag(Loc: E->getExprLoc(),
13821 PD: PDiag(DiagID: diag::warn_impcast_integer_precision_constant)
13822 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13823 << E->getSourceRange() << SourceRange(CC));
13824 return;
13825 }
13826 }
13827
13828 // Fall through for non-constants to give a sign conversion warning.
13829 }
13830
13831 if ((!isa<EnumType>(Val: Target) || !isa<EnumType>(Val: Source)) &&
13832 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
13833 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
13834 LikelySourceRange->Width == TargetRange.Width))) {
13835 if (SourceMgr.isInSystemMacro(loc: CC))
13836 return;
13837
13838 if (SourceBT && SourceBT->isInteger() && TargetBT &&
13839 TargetBT->isInteger() &&
13840 Source->isSignedIntegerType() == Target->isSignedIntegerType()) {
13841 return;
13842 }
13843
13844 unsigned DiagID = diag::warn_impcast_integer_sign;
13845
13846 // Traditionally, gcc has warned about this under -Wsign-compare.
13847 // We also want to warn about it in -Wconversion.
13848 // So if -Wconversion is off, use a completely identical diagnostic
13849 // in the sign-compare group.
13850 // The conditional-checking code will
13851 if (ICContext) {
13852 DiagID = diag::warn_impcast_integer_sign_conditional;
13853 *ICContext = true;
13854 }
13855
13856 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagID);
13857 }
13858
13859 // If we're implicitly converting from an integer into an enumeration, that
13860 // is valid in C but invalid in C++.
13861 QualType SourceType = E->getEnumCoercedType(Ctx: Context);
13862 const BuiltinType *CoercedSourceBT = SourceType->getAs<BuiltinType>();
13863 if (CoercedSourceBT && CoercedSourceBT->isInteger() && isa<EnumType>(Val: Target))
13864 return DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: diag::warn_impcast_int_to_enum);
13865
13866 // Diagnose conversions between different enumeration types.
13867 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13868 // type, to give us better diagnostics.
13869 Source = Context.getCanonicalType(T: SourceType).getTypePtr();
13870
13871 if (const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
13872 if (const EnumType *TargetEnum = Target->getAsCanonical<EnumType>())
13873 if (SourceEnum->getDecl()->hasNameForLinkage() &&
13874 TargetEnum->getDecl()->hasNameForLinkage() &&
13875 SourceEnum != TargetEnum) {
13876 if (SourceMgr.isInSystemMacro(loc: CC))
13877 return;
13878
13879 return DiagnoseImpCast(S&: *this, E, SourceType, T, CContext: CC,
13880 diag: diag::warn_impcast_different_enum_types);
13881 }
13882}
13883
13884static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13885 SourceLocation CC, QualType T);
13886
13887static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13888 SourceLocation CC, bool &ICContext) {
13889 E = E->IgnoreParenImpCasts();
13890 // Diagnose incomplete type for second or third operand in C.
13891 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType())
13892 S.RequireCompleteExprType(E, DiagID: diag::err_incomplete_type);
13893
13894 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: E))
13895 return CheckConditionalOperator(S, E: CO, CC, T);
13896
13897 AnalyzeImplicitConversions(S, E, CC);
13898 if (E->getType() != T)
13899 return S.CheckImplicitConversion(E, T, CC, ICContext: &ICContext);
13900}
13901
13902static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13903 SourceLocation CC, QualType T) {
13904 AnalyzeImplicitConversions(S, E: E->getCond(), CC: E->getQuestionLoc());
13905
13906 Expr *TrueExpr = E->getTrueExpr();
13907 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(Val: E))
13908 TrueExpr = BCO->getCommon();
13909
13910 bool Suspicious = false;
13911 CheckConditionalOperand(S, E: TrueExpr, T, CC, ICContext&: Suspicious);
13912 CheckConditionalOperand(S, E: E->getFalseExpr(), T, CC, ICContext&: Suspicious);
13913
13914 if (T->isBooleanType())
13915 DiagnoseIntInBoolContext(S, E);
13916
13917 // If -Wconversion would have warned about either of the candidates
13918 // for a signedness conversion to the context type...
13919 if (!Suspicious) return;
13920
13921 // ...but it's currently ignored...
13922 if (!S.Diags.isIgnored(DiagID: diag::warn_impcast_integer_sign_conditional, Loc: CC))
13923 return;
13924
13925 // ...then check whether it would have warned about either of the
13926 // candidates for a signedness conversion to the condition type.
13927 if (E->getType() == T) return;
13928
13929 Suspicious = false;
13930 S.CheckImplicitConversion(E: TrueExpr->IgnoreParenImpCasts(), T: E->getType(), CC,
13931 ICContext: &Suspicious);
13932 if (!Suspicious)
13933 S.CheckImplicitConversion(E: E->getFalseExpr()->IgnoreParenImpCasts(),
13934 T: E->getType(), CC, ICContext: &Suspicious);
13935}
13936
13937/// Check conversion of given expression to boolean.
13938/// Input argument E is a logical expression.
13939static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13940 // Run the bool-like conversion checks only for C since there bools are
13941 // still not used as the return type from "boolean" operators or as the input
13942 // type for conditional operators.
13943 if (S.getLangOpts().CPlusPlus)
13944 return;
13945 if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13946 return;
13947 S.CheckImplicitConversion(E: E->IgnoreParenImpCasts(), T: S.Context.BoolTy, CC);
13948}
13949
13950namespace {
13951struct AnalyzeImplicitConversionsWorkItem {
13952 Expr *E;
13953 SourceLocation CC;
13954 bool IsListInit;
13955};
13956}
13957
13958static void CheckCommaOperand(
13959 Sema &S, Expr *E, QualType T, SourceLocation CC,
13960 bool ExtraCheckForImplicitConversion,
13961 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13962 E = E->IgnoreParenImpCasts();
13963 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: false});
13964
13965 if (ExtraCheckForImplicitConversion && E->getType() != T)
13966 S.CheckImplicitConversion(E, T, CC);
13967}
13968
13969/// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13970/// that should be visited are added to WorkList.
13971static void AnalyzeImplicitConversions(
13972 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13973 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13974 Expr *OrigE = Item.E;
13975 SourceLocation CC = Item.CC;
13976
13977 QualType T = OrigE->getType();
13978 Expr *E = OrigE->IgnoreParenImpCasts();
13979
13980 // Propagate whether we are in a C++ list initialization expression.
13981 // If so, we do not issue warnings for implicit int-float conversion
13982 // precision loss, because C++11 narrowing already handles it.
13983 //
13984 // HLSL's initialization lists are special, so they shouldn't observe the C++
13985 // behavior here.
13986 bool IsListInit =
13987 Item.IsListInit || (isa<InitListExpr>(Val: OrigE) &&
13988 S.getLangOpts().CPlusPlus && !S.getLangOpts().HLSL);
13989
13990 if (E->isTypeDependent() || E->isValueDependent())
13991 return;
13992
13993 Expr *SourceExpr = E;
13994 // Examine, but don't traverse into the source expression of an
13995 // OpaqueValueExpr, since it may have multiple parents and we don't want to
13996 // emit duplicate diagnostics. Its fine to examine the form or attempt to
13997 // evaluate it in the context of checking the specific conversion to T though.
13998 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E))
13999 if (auto *Src = OVE->getSourceExpr())
14000 SourceExpr = Src;
14001
14002 if (const auto *UO = dyn_cast<UnaryOperator>(Val: SourceExpr))
14003 if (UO->getOpcode() == UO_Not &&
14004 UO->getSubExpr()->isKnownToHaveBooleanValue())
14005 S.Diag(Loc: UO->getBeginLoc(), DiagID: diag::warn_bitwise_negation_bool)
14006 << OrigE->getSourceRange() << T->isBooleanType()
14007 << FixItHint::CreateReplacement(RemoveRange: UO->getBeginLoc(), Code: "!");
14008
14009 if (auto *BO = dyn_cast<BinaryOperator>(Val: SourceExpr)) {
14010 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14011 BO->getLHS()->isKnownToHaveBooleanValue() &&
14012 BO->getRHS()->isKnownToHaveBooleanValue() &&
14013 BO->getLHS()->HasSideEffects(Ctx: S.Context) &&
14014 BO->getRHS()->HasSideEffects(Ctx: S.Context)) {
14015 SourceManager &SM = S.getSourceManager();
14016 const LangOptions &LO = S.getLangOpts();
14017 SourceLocation BLoc = BO->getOperatorLoc();
14018 SourceLocation ELoc = Lexer::getLocForEndOfToken(Loc: BLoc, Offset: 0, SM, LangOpts: LO);
14019 StringRef SR = clang::Lexer::getSourceText(
14020 Range: clang::CharSourceRange::getTokenRange(B: BLoc, E: ELoc), SM, LangOpts: LO);
14021 // To reduce false positives, only issue the diagnostic if the operator
14022 // is explicitly spelled as a punctuator. This suppresses the diagnostic
14023 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros
14024 // in C, along with other macro spellings the user might invent.
14025 if (SR.str() == "&" || SR.str() == "|") {
14026
14027 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::warn_bitwise_instead_of_logical)
14028 << (BO->getOpcode() == BO_And ? "&" : "|")
14029 << OrigE->getSourceRange()
14030 << FixItHint::CreateReplacement(
14031 RemoveRange: BO->getOperatorLoc(),
14032 Code: (BO->getOpcode() == BO_And ? "&&" : "||"));
14033 S.Diag(Loc: BO->getBeginLoc(), DiagID: diag::note_cast_operand_to_int);
14034 }
14035 } else if (BO->isCommaOp() && !S.getLangOpts().CPlusPlus) {
14036 /// Analyze the given comma operator. The basic idea behind the analysis
14037 /// is to analyze the left and right operands slightly differently. The
14038 /// left operand needs to check whether the operand itself has an implicit
14039 /// conversion, but not whether the left operand induces an implicit
14040 /// conversion for the entire comma expression itself. This is similar to
14041 /// how CheckConditionalOperand behaves; it's as-if the correct operand
14042 /// were directly used for the implicit conversion check.
14043 CheckCommaOperand(S, E: BO->getLHS(), T, CC: BO->getOperatorLoc(),
14044 /*ExtraCheckForImplicitConversion=*/false, WorkList);
14045 CheckCommaOperand(S, E: BO->getRHS(), T, CC: BO->getOperatorLoc(),
14046 /*ExtraCheckForImplicitConversion=*/true, WorkList);
14047 return;
14048 }
14049 }
14050
14051 // For conditional operators, we analyze the arguments as if they
14052 // were being fed directly into the output.
14053 if (auto *CO = dyn_cast<AbstractConditionalOperator>(Val: SourceExpr)) {
14054 CheckConditionalOperator(S, E: CO, CC, T);
14055 return;
14056 }
14057
14058 // Check implicit argument conversions for function calls.
14059 if (const auto *Call = dyn_cast<CallExpr>(Val: SourceExpr))
14060 CheckImplicitArgumentConversions(S, TheCall: Call, CC);
14061
14062 // Go ahead and check any implicit conversions we might have skipped.
14063 // The non-canonical typecheck is just an optimization;
14064 // CheckImplicitConversion will filter out dead implicit conversions.
14065 if (SourceExpr->getType() != T)
14066 S.CheckImplicitConversion(E: SourceExpr, T, CC, ICContext: nullptr, IsListInit);
14067
14068 // Now continue drilling into this expression.
14069
14070 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Val: E)) {
14071 // The bound subexpressions in a PseudoObjectExpr are not reachable
14072 // as transitive children.
14073 // FIXME: Use a more uniform representation for this.
14074 for (auto *SE : POE->semantics())
14075 if (auto *OVE = dyn_cast<OpaqueValueExpr>(Val: SE))
14076 WorkList.push_back(Elt: {.E: OVE->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
14077 }
14078
14079 // Skip past explicit casts.
14080 if (auto *CE = dyn_cast<ExplicitCastExpr>(Val: E)) {
14081 E = CE->getSubExpr();
14082 // In the special case of a C++ function-style cast with braces,
14083 // CXXFunctionalCastExpr has an InitListExpr as direct child with a single
14084 // initializer. This InitListExpr basically belongs to the cast itself, so
14085 // we skip it too. Specifically this is needed to silence -Wdouble-promotion
14086 if (isa<CXXFunctionalCastExpr>(Val: CE)) {
14087 if (auto *InitListE = dyn_cast<InitListExpr>(Val: E)) {
14088 if (InitListE->getNumInits() == 1) {
14089 E = InitListE->getInit(Init: 0);
14090 }
14091 }
14092 }
14093 E = E->IgnoreParenImpCasts();
14094 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
14095 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::warn_atomic_implicit_seq_cst);
14096 WorkList.push_back(Elt: {.E: E, .CC: CC, .IsListInit: IsListInit});
14097 return;
14098 }
14099
14100 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(Val: E)) {
14101 WorkList.push_back(Elt: {.E: OutArgE->getArgLValue(), .CC: CC, .IsListInit: IsListInit});
14102 // The base expression is only used to initialize the parameter for
14103 // arguments to `inout` parameters, so we only traverse down the base
14104 // expression for `inout` cases.
14105 if (OutArgE->isInOut())
14106 WorkList.push_back(
14107 Elt: {.E: OutArgE->getCastedTemporary()->getSourceExpr(), .CC: CC, .IsListInit: IsListInit});
14108 WorkList.push_back(Elt: {.E: OutArgE->getWritebackCast(), .CC: CC, .IsListInit: IsListInit});
14109 return;
14110 }
14111
14112 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
14113 // Do a somewhat different check with comparison operators.
14114 if (BO->isComparisonOp())
14115 return AnalyzeComparison(S, E: BO);
14116
14117 // And with simple assignments.
14118 if (BO->getOpcode() == BO_Assign)
14119 return AnalyzeAssignment(S, E: BO);
14120 // And with compound assignments.
14121 if (BO->isAssignmentOp())
14122 return AnalyzeCompoundAssignment(S, E: BO);
14123 }
14124
14125 // These break the otherwise-useful invariant below. Fortunately,
14126 // we don't really need to recurse into them, because any internal
14127 // expressions should have been analyzed already when they were
14128 // built into statements.
14129 if (isa<StmtExpr>(Val: E)) return;
14130
14131 // Don't descend into unevaluated contexts.
14132 if (isa<UnaryExprOrTypeTraitExpr>(Val: E)) return;
14133
14134 // Now just recurse over the expression's children.
14135 CC = E->getExprLoc();
14136 BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E);
14137 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
14138 for (Stmt *SubStmt : E->children()) {
14139 Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: SubStmt);
14140 if (!ChildExpr)
14141 continue;
14142
14143 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(Val: E))
14144 if (ChildExpr == CSE->getOperand())
14145 // Do not recurse over a CoroutineSuspendExpr's operand.
14146 // The operand is also a subexpression of getCommonExpr(), and
14147 // recursing into it directly would produce duplicate diagnostics.
14148 continue;
14149
14150 if (IsLogicalAndOperator &&
14151 isa<StringLiteral>(Val: ChildExpr->IgnoreParenImpCasts()))
14152 // Ignore checking string literals that are in logical and operators.
14153 // This is a common pattern for asserts.
14154 continue;
14155 WorkList.push_back(Elt: {.E: ChildExpr, .CC: CC, .IsListInit: IsListInit});
14156 }
14157
14158 if (BO && BO->isLogicalOp()) {
14159 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
14160 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
14161 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
14162
14163 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
14164 if (!IsLogicalAndOperator || !isa<StringLiteral>(Val: SubExpr))
14165 ::CheckBoolLikeConversion(S, E: SubExpr, CC: BO->getExprLoc());
14166 }
14167
14168 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(Val: E)) {
14169 if (U->getOpcode() == UO_LNot) {
14170 ::CheckBoolLikeConversion(S, E: U->getSubExpr(), CC);
14171 } else if (U->getOpcode() != UO_AddrOf) {
14172 if (U->getSubExpr()->getType()->isAtomicType())
14173 S.Diag(Loc: U->getSubExpr()->getBeginLoc(),
14174 DiagID: diag::warn_atomic_implicit_seq_cst);
14175 }
14176 }
14177}
14178
14179/// AnalyzeImplicitConversions - Find and report any interesting
14180/// implicit conversions in the given expression. There are a couple
14181/// of competing diagnostics here, -Wconversion and -Wsign-compare.
14182static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
14183 bool IsListInit/*= false*/) {
14184 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
14185 WorkList.push_back(Elt: {.E: OrigE, .CC: CC, .IsListInit: IsListInit});
14186 while (!WorkList.empty())
14187 AnalyzeImplicitConversions(S, Item: WorkList.pop_back_val(), WorkList);
14188}
14189
14190// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
14191// Returns true when emitting a warning about taking the address of a reference.
14192static bool CheckForReference(Sema &SemaRef, const Expr *E,
14193 const PartialDiagnostic &PD) {
14194 E = E->IgnoreParenImpCasts();
14195
14196 const FunctionDecl *FD = nullptr;
14197
14198 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
14199 if (!DRE->getDecl()->getType()->isReferenceType())
14200 return false;
14201 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
14202 if (!M->getMemberDecl()->getType()->isReferenceType())
14203 return false;
14204 } else if (const CallExpr *Call = dyn_cast<CallExpr>(Val: E)) {
14205 if (!Call->getCallReturnType(Ctx: SemaRef.Context)->isReferenceType())
14206 return false;
14207 FD = Call->getDirectCallee();
14208 } else {
14209 return false;
14210 }
14211
14212 SemaRef.Diag(Loc: E->getExprLoc(), PD);
14213
14214 // If possible, point to location of function.
14215 if (FD) {
14216 SemaRef.Diag(Loc: FD->getLocation(), DiagID: diag::note_reference_is_return_value) << FD;
14217 }
14218
14219 return true;
14220}
14221
14222// Returns true if the SourceLocation is expanded from any macro body.
14223// Returns false if the SourceLocation is invalid, is from not in a macro
14224// expansion, or is from expanded from a top-level macro argument.
14225static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
14226 if (Loc.isInvalid())
14227 return false;
14228
14229 while (Loc.isMacroID()) {
14230 if (SM.isMacroBodyExpansion(Loc))
14231 return true;
14232 Loc = SM.getImmediateMacroCallerLoc(Loc);
14233 }
14234
14235 return false;
14236}
14237
14238void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
14239 Expr::NullPointerConstantKind NullKind,
14240 bool IsEqual, SourceRange Range) {
14241 if (!E)
14242 return;
14243
14244 // Don't warn inside macros.
14245 if (E->getExprLoc().isMacroID()) {
14246 const SourceManager &SM = getSourceManager();
14247 if (IsInAnyMacroBody(SM, Loc: E->getExprLoc()) ||
14248 IsInAnyMacroBody(SM, Loc: Range.getBegin()))
14249 return;
14250 }
14251 E = E->IgnoreImpCasts();
14252
14253 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
14254
14255 if (isa<CXXThisExpr>(Val: E)) {
14256 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14257 : diag::warn_this_bool_conversion;
14258 Diag(Loc: E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
14259 return;
14260 }
14261
14262 bool IsAddressOf = false;
14263
14264 if (auto *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParens())) {
14265 if (UO->getOpcode() != UO_AddrOf)
14266 return;
14267 IsAddressOf = true;
14268 E = UO->getSubExpr();
14269 }
14270
14271 if (IsAddressOf) {
14272 unsigned DiagID = IsCompare
14273 ? diag::warn_address_of_reference_null_compare
14274 : diag::warn_address_of_reference_bool_conversion;
14275 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
14276 << IsEqual;
14277 if (CheckForReference(SemaRef&: *this, E, PD)) {
14278 return;
14279 }
14280 }
14281
14282 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
14283 bool IsParam = isa<NonNullAttr>(Val: NonnullAttr);
14284 std::string Str;
14285 llvm::raw_string_ostream S(Str);
14286 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
14287 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14288 : diag::warn_cast_nonnull_to_bool;
14289 Diag(Loc: E->getExprLoc(), DiagID) << IsParam << S.str()
14290 << E->getSourceRange() << Range << IsEqual;
14291 Diag(Loc: NonnullAttr->getLocation(), DiagID: diag::note_declared_nonnull) << IsParam;
14292 };
14293
14294 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
14295 if (auto *Call = dyn_cast<CallExpr>(Val: E->IgnoreParenImpCasts())) {
14296 if (auto *Callee = Call->getDirectCallee()) {
14297 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14298 ComplainAboutNonnullParamOrCall(A);
14299 return;
14300 }
14301 }
14302 }
14303
14304 // Complain if we are converting a lambda expression to a boolean value
14305 // outside of instantiation.
14306 if (!inTemplateInstantiation()) {
14307 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(Val: E)) {
14308 if (const auto *MRecordDecl = MCallExpr->getRecordDecl();
14309 MRecordDecl && MRecordDecl->isLambda()) {
14310 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_impcast_pointer_to_bool)
14311 << /*LambdaPointerConversionOperatorType=*/3
14312 << MRecordDecl->getSourceRange() << Range << IsEqual;
14313 return;
14314 }
14315 }
14316 }
14317
14318 // Expect to find a single Decl. Skip anything more complicated.
14319 ValueDecl *D = nullptr;
14320 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(Val: E)) {
14321 D = R->getDecl();
14322 } else if (MemberExpr *M = dyn_cast<MemberExpr>(Val: E)) {
14323 D = M->getMemberDecl();
14324 }
14325
14326 // Weak Decls can be null.
14327 if (!D || D->isWeak())
14328 return;
14329
14330 // Check for parameter decl with nonnull attribute
14331 if (const auto* PV = dyn_cast<ParmVarDecl>(Val: D)) {
14332 if (getCurFunction() &&
14333 !getCurFunction()->ModifiedNonNullParams.count(Ptr: PV)) {
14334 if (const Attr *A = PV->getAttr<NonNullAttr>()) {
14335 ComplainAboutNonnullParamOrCall(A);
14336 return;
14337 }
14338
14339 if (const auto *FD = dyn_cast<FunctionDecl>(Val: PV->getDeclContext())) {
14340 // Skip function template not specialized yet.
14341 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
14342 return;
14343 auto ParamIter = llvm::find(Range: FD->parameters(), Val: PV);
14344 assert(ParamIter != FD->param_end());
14345 unsigned ParamNo = std::distance(first: FD->param_begin(), last: ParamIter);
14346
14347 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
14348 if (!NonNull->args_size()) {
14349 ComplainAboutNonnullParamOrCall(NonNull);
14350 return;
14351 }
14352
14353 for (const ParamIdx &ArgNo : NonNull->args()) {
14354 if (ArgNo.getASTIndex() == ParamNo) {
14355 ComplainAboutNonnullParamOrCall(NonNull);
14356 return;
14357 }
14358 }
14359 }
14360 }
14361 }
14362 }
14363
14364 QualType T = D->getType();
14365 const bool IsArray = T->isArrayType();
14366 const bool IsFunction = T->isFunctionType();
14367
14368 // Address of function is used to silence the function warning.
14369 if (IsAddressOf && IsFunction) {
14370 return;
14371 }
14372
14373 // Found nothing.
14374 if (!IsAddressOf && !IsFunction && !IsArray)
14375 return;
14376
14377 // Pretty print the expression for the diagnostic.
14378 std::string Str;
14379 llvm::raw_string_ostream S(Str);
14380 E->printPretty(OS&: S, Helper: nullptr, Policy: getPrintingPolicy());
14381
14382 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14383 : diag::warn_impcast_pointer_to_bool;
14384 enum {
14385 AddressOf,
14386 FunctionPointer,
14387 ArrayPointer
14388 } DiagType;
14389 if (IsAddressOf)
14390 DiagType = AddressOf;
14391 else if (IsFunction)
14392 DiagType = FunctionPointer;
14393 else if (IsArray)
14394 DiagType = ArrayPointer;
14395 else
14396 llvm_unreachable("Could not determine diagnostic.");
14397 Diag(Loc: E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
14398 << Range << IsEqual;
14399
14400 if (!IsFunction)
14401 return;
14402
14403 // Suggest '&' to silence the function warning.
14404 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_warning_silence)
14405 << FixItHint::CreateInsertion(InsertionLoc: E->getBeginLoc(), Code: "&");
14406
14407 // Check to see if '()' fixit should be emitted.
14408 QualType ReturnType;
14409 UnresolvedSet<4> NonTemplateOverloads;
14410 tryExprAsCall(E&: *E, ZeroArgCallReturnTy&: ReturnType, NonTemplateOverloads);
14411 if (ReturnType.isNull())
14412 return;
14413
14414 if (IsCompare) {
14415 // There are two cases here. If there is null constant, the only suggest
14416 // for a pointer return type. If the null is 0, then suggest if the return
14417 // type is a pointer or an integer type.
14418 if (!ReturnType->isPointerType()) {
14419 if (NullKind == Expr::NPCK_ZeroExpression ||
14420 NullKind == Expr::NPCK_ZeroLiteral) {
14421 if (!ReturnType->isIntegerType())
14422 return;
14423 } else {
14424 return;
14425 }
14426 }
14427 } else { // !IsCompare
14428 // For function to bool, only suggest if the function pointer has bool
14429 // return type.
14430 if (!ReturnType->isSpecificBuiltinType(K: BuiltinType::Bool))
14431 return;
14432 }
14433 Diag(Loc: E->getExprLoc(), DiagID: diag::note_function_to_function_call)
14434 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: E->getEndLoc()), Code: "()");
14435}
14436
14437bool Sema::CheckOverflowBehaviorTypeConversion(Expr *E, QualType T,
14438 SourceLocation CC) {
14439 QualType Source = E->getType();
14440 QualType Target = T;
14441
14442 if (const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14443 if (Target->isIntegerType() && !Target->isOverflowBehaviorType()) {
14444 // Overflow behavior type is being stripped - issue warning
14445 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14446 Target->isUnsignedIntegerType()) {
14447 // For unsigned wrap to unsigned conversions, use pedantic version
14448 unsigned DiagId =
14449 InOverflowBehaviorAssignmentContext
14450 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14451 : diag::warn_impcast_overflow_behavior_pedantic;
14452 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14453 } else {
14454 unsigned DiagId = InOverflowBehaviorAssignmentContext
14455 ? diag::warn_impcast_overflow_behavior_assignment
14456 : diag::warn_impcast_overflow_behavior;
14457 DiagnoseImpCast(S&: *this, E, T, CContext: CC, diag: DiagId);
14458 }
14459 }
14460 }
14461
14462 if (const auto *TargetOBT = Target->getAs<OverflowBehaviorType>()) {
14463 if (TargetOBT->isWrapKind()) {
14464 return true;
14465 }
14466 }
14467
14468 return false;
14469}
14470
14471void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
14472 // Don't diagnose in unevaluated contexts.
14473 if (isUnevaluatedContext())
14474 return;
14475
14476 // Don't diagnose for value- or type-dependent expressions.
14477 if (E->isTypeDependent() || E->isValueDependent())
14478 return;
14479
14480 // Check for array bounds violations in cases where the check isn't triggered
14481 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
14482 // ArraySubscriptExpr is on the RHS of a variable initialization.
14483 CheckArrayAccess(E);
14484
14485 // This is not the right CC for (e.g.) a variable initialization.
14486 AnalyzeImplicitConversions(S&: *this, OrigE: E, CC);
14487}
14488
14489void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
14490 ::CheckBoolLikeConversion(S&: *this, E, CC);
14491}
14492
14493void Sema::CheckForIntOverflow (const Expr *E) {
14494 // Use a work list to deal with nested struct initializers.
14495 SmallVector<const Expr *, 2> Exprs(1, E);
14496
14497 do {
14498 const Expr *OriginalE = Exprs.pop_back_val();
14499 const Expr *E = OriginalE->IgnoreParenCasts();
14500
14501 if (isa<BinaryOperator>(Val: E) ||
14502 (isa<UnaryOperator>(Val: E) && cast<UnaryOperator>(Val: E)->canOverflow())) {
14503 E->EvaluateForOverflow(Ctx: Context);
14504 continue;
14505 }
14506
14507 if (const auto *InitList = dyn_cast<InitListExpr>(Val: OriginalE))
14508 Exprs.append(in_start: InitList->inits().begin(), in_end: InitList->inits().end());
14509 else if (isa<ObjCBoxedExpr>(Val: OriginalE))
14510 E->EvaluateForOverflow(Ctx: Context);
14511 else if (const auto *Call = dyn_cast<CallExpr>(Val: E))
14512 Exprs.append(in_start: Call->arg_begin(), in_end: Call->arg_end());
14513 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(Val: E))
14514 Exprs.append(in_start: Message->arg_begin(), in_end: Message->arg_end());
14515 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(Val: E))
14516 Exprs.append(in_start: Construct->arg_begin(), in_end: Construct->arg_end());
14517 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(Val: E))
14518 Exprs.push_back(Elt: Temporary->getSubExpr());
14519 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(Val: E))
14520 Exprs.push_back(Elt: Array->getIdx());
14521 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(Val: E))
14522 Exprs.push_back(Elt: Compound->getInitializer());
14523 else if (const auto *New = dyn_cast<CXXNewExpr>(Val: E);
14524 New && New->isArray()) {
14525 if (auto ArraySize = New->getArraySize())
14526 Exprs.push_back(Elt: *ArraySize);
14527 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: OriginalE))
14528 Exprs.push_back(Elt: MTE->getSubExpr());
14529 } while (!Exprs.empty());
14530}
14531
14532namespace {
14533
14534/// Visitor for expressions which looks for unsequenced operations on the
14535/// same object.
14536class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
14537 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14538
14539 /// A tree of sequenced regions within an expression. Two regions are
14540 /// unsequenced if one is an ancestor or a descendent of the other. When we
14541 /// finish processing an expression with sequencing, such as a comma
14542 /// expression, we fold its tree nodes into its parent, since they are
14543 /// unsequenced with respect to nodes we will visit later.
14544 class SequenceTree {
14545 struct Value {
14546 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
14547 unsigned Parent : 31;
14548 LLVM_PREFERRED_TYPE(bool)
14549 unsigned Merged : 1;
14550 };
14551 SmallVector<Value, 8> Values;
14552
14553 public:
14554 /// A region within an expression which may be sequenced with respect
14555 /// to some other region.
14556 class Seq {
14557 friend class SequenceTree;
14558
14559 unsigned Index;
14560
14561 explicit Seq(unsigned N) : Index(N) {}
14562
14563 public:
14564 Seq() : Index(0) {}
14565 };
14566
14567 SequenceTree() { Values.push_back(Elt: Value(0)); }
14568 Seq root() const { return Seq(0); }
14569
14570 /// Create a new sequence of operations, which is an unsequenced
14571 /// subset of \p Parent. This sequence of operations is sequenced with
14572 /// respect to other children of \p Parent.
14573 Seq allocate(Seq Parent) {
14574 Values.push_back(Elt: Value(Parent.Index));
14575 return Seq(Values.size() - 1);
14576 }
14577
14578 /// Merge a sequence of operations into its parent.
14579 void merge(Seq S) {
14580 Values[S.Index].Merged = true;
14581 }
14582
14583 /// Determine whether two operations are unsequenced. This operation
14584 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
14585 /// should have been merged into its parent as appropriate.
14586 bool isUnsequenced(Seq Cur, Seq Old) {
14587 unsigned C = representative(K: Cur.Index);
14588 unsigned Target = representative(K: Old.Index);
14589 while (C >= Target) {
14590 if (C == Target)
14591 return true;
14592 C = Values[C].Parent;
14593 }
14594 return false;
14595 }
14596
14597 private:
14598 /// Pick a representative for a sequence.
14599 unsigned representative(unsigned K) {
14600 if (Values[K].Merged)
14601 // Perform path compression as we go.
14602 return Values[K].Parent = representative(K: Values[K].Parent);
14603 return K;
14604 }
14605 };
14606
14607 /// An object for which we can track unsequenced uses.
14608 using Object = const NamedDecl *;
14609
14610 /// Different flavors of object usage which we track. We only track the
14611 /// least-sequenced usage of each kind.
14612 enum UsageKind {
14613 /// A read of an object. Multiple unsequenced reads are OK.
14614 UK_Use,
14615
14616 /// A modification of an object which is sequenced before the value
14617 /// computation of the expression, such as ++n in C++.
14618 UK_ModAsValue,
14619
14620 /// A modification of an object which is not sequenced before the value
14621 /// computation of the expression, such as n++.
14622 UK_ModAsSideEffect,
14623
14624 UK_Count = UK_ModAsSideEffect + 1
14625 };
14626
14627 /// Bundle together a sequencing region and the expression corresponding
14628 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
14629 struct Usage {
14630 const Expr *UsageExpr = nullptr;
14631 SequenceTree::Seq Seq;
14632
14633 Usage() = default;
14634 };
14635
14636 struct UsageInfo {
14637 Usage Uses[UK_Count];
14638
14639 /// Have we issued a diagnostic for this object already?
14640 bool Diagnosed = false;
14641
14642 UsageInfo();
14643 };
14644 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
14645
14646 Sema &SemaRef;
14647
14648 /// Sequenced regions within the expression.
14649 SequenceTree Tree;
14650
14651 /// Declaration modifications and references which we have seen.
14652 UsageInfoMap UsageMap;
14653
14654 /// The region we are currently within.
14655 SequenceTree::Seq Region;
14656
14657 /// Filled in with declarations which were modified as a side-effect
14658 /// (that is, post-increment operations).
14659 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
14660
14661 /// Expressions to check later. We defer checking these to reduce
14662 /// stack usage.
14663 SmallVectorImpl<const Expr *> &WorkList;
14664
14665 /// RAII object wrapping the visitation of a sequenced subexpression of an
14666 /// expression. At the end of this process, the side-effects of the evaluation
14667 /// become sequenced with respect to the value computation of the result, so
14668 /// we downgrade any UK_ModAsSideEffect within the evaluation to
14669 /// UK_ModAsValue.
14670 struct SequencedSubexpression {
14671 SequencedSubexpression(SequenceChecker &Self)
14672 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
14673 Self.ModAsSideEffect = &ModAsSideEffect;
14674 }
14675
14676 ~SequencedSubexpression() {
14677 for (const std::pair<Object, Usage> &M : llvm::reverse(C&: ModAsSideEffect)) {
14678 // Add a new usage with usage kind UK_ModAsValue, and then restore
14679 // the previous usage with UK_ModAsSideEffect (thus clearing it if
14680 // the previous one was empty).
14681 UsageInfo &UI = Self.UsageMap[M.first];
14682 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
14683 Self.addUsage(O: M.first, UI, UsageExpr: SideEffectUsage.UsageExpr, UK: UK_ModAsValue);
14684 SideEffectUsage = M.second;
14685 }
14686 Self.ModAsSideEffect = OldModAsSideEffect;
14687 }
14688
14689 SequenceChecker &Self;
14690 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
14691 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
14692 };
14693
14694 /// RAII object wrapping the visitation of a subexpression which we might
14695 /// choose to evaluate as a constant. If any subexpression is evaluated and
14696 /// found to be non-constant, this allows us to suppress the evaluation of
14697 /// the outer expression.
14698 class EvaluationTracker {
14699 public:
14700 EvaluationTracker(SequenceChecker &Self)
14701 : Self(Self), Prev(Self.EvalTracker) {
14702 Self.EvalTracker = this;
14703 }
14704
14705 ~EvaluationTracker() {
14706 Self.EvalTracker = Prev;
14707 if (Prev)
14708 Prev->EvalOK &= EvalOK;
14709 }
14710
14711 bool evaluate(const Expr *E, bool &Result) {
14712 if (!EvalOK || E->isValueDependent())
14713 return false;
14714 EvalOK = E->EvaluateAsBooleanCondition(
14715 Result, Ctx: Self.SemaRef.Context,
14716 InConstantContext: Self.SemaRef.isConstantEvaluatedContext());
14717 return EvalOK;
14718 }
14719
14720 private:
14721 SequenceChecker &Self;
14722 EvaluationTracker *Prev;
14723 bool EvalOK = true;
14724 } *EvalTracker = nullptr;
14725
14726 /// Find the object which is produced by the specified expression,
14727 /// if any.
14728 Object getObject(const Expr *E, bool Mod) const {
14729 E = E->IgnoreParenCasts();
14730 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) {
14731 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
14732 return getObject(E: UO->getSubExpr(), Mod);
14733 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
14734 if (BO->getOpcode() == BO_Comma)
14735 return getObject(E: BO->getRHS(), Mod);
14736 if (Mod && BO->isAssignmentOp())
14737 return getObject(E: BO->getLHS(), Mod);
14738 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
14739 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
14740 if (isa<CXXThisExpr>(Val: ME->getBase()->IgnoreParenCasts()))
14741 return ME->getMemberDecl();
14742 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
14743 // FIXME: If this is a reference, map through to its value.
14744 return DRE->getDecl();
14745 return nullptr;
14746 }
14747
14748 /// Note that an object \p O was modified or used by an expression
14749 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
14750 /// the object \p O as obtained via the \p UsageMap.
14751 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
14752 // Get the old usage for the given object and usage kind.
14753 Usage &U = UI.Uses[UK];
14754 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq)) {
14755 // If we have a modification as side effect and are in a sequenced
14756 // subexpression, save the old Usage so that we can restore it later
14757 // in SequencedSubexpression::~SequencedSubexpression.
14758 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
14759 ModAsSideEffect->push_back(Elt: std::make_pair(x&: O, y&: U));
14760 // Then record the new usage with the current sequencing region.
14761 U.UsageExpr = UsageExpr;
14762 U.Seq = Region;
14763 }
14764 }
14765
14766 /// Check whether a modification or use of an object \p O in an expression
14767 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
14768 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
14769 /// \p IsModMod is true when we are checking for a mod-mod unsequenced
14770 /// usage and false we are checking for a mod-use unsequenced usage.
14771 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
14772 UsageKind OtherKind, bool IsModMod) {
14773 if (UI.Diagnosed)
14774 return;
14775
14776 const Usage &U = UI.Uses[OtherKind];
14777 if (!U.UsageExpr || !Tree.isUnsequenced(Cur: Region, Old: U.Seq))
14778 return;
14779
14780 const Expr *Mod = U.UsageExpr;
14781 const Expr *ModOrUse = UsageExpr;
14782 if (OtherKind == UK_Use)
14783 std::swap(a&: Mod, b&: ModOrUse);
14784
14785 SemaRef.DiagRuntimeBehavior(
14786 Loc: Mod->getExprLoc(), Stmts: {Mod, ModOrUse},
14787 PD: SemaRef.PDiag(DiagID: IsModMod ? diag::warn_unsequenced_mod_mod
14788 : diag::warn_unsequenced_mod_use)
14789 << O << SourceRange(ModOrUse->getExprLoc()));
14790 UI.Diagnosed = true;
14791 }
14792
14793 // A note on note{Pre, Post}{Use, Mod}:
14794 //
14795 // (It helps to follow the algorithm with an expression such as
14796 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14797 // operations before C++17 and both are well-defined in C++17).
14798 //
14799 // When visiting a node which uses/modify an object we first call notePreUse
14800 // or notePreMod before visiting its sub-expression(s). At this point the
14801 // children of the current node have not yet been visited and so the eventual
14802 // uses/modifications resulting from the children of the current node have not
14803 // been recorded yet.
14804 //
14805 // We then visit the children of the current node. After that notePostUse or
14806 // notePostMod is called. These will 1) detect an unsequenced modification
14807 // as side effect (as in "k++ + k") and 2) add a new usage with the
14808 // appropriate usage kind.
14809 //
14810 // We also have to be careful that some operation sequences modification as
14811 // side effect as well (for example: || or ,). To account for this we wrap
14812 // the visitation of such a sub-expression (for example: the LHS of || or ,)
14813 // with SequencedSubexpression. SequencedSubexpression is an RAII object
14814 // which record usages which are modifications as side effect, and then
14815 // downgrade them (or more accurately restore the previous usage which was a
14816 // modification as side effect) when exiting the scope of the sequenced
14817 // subexpression.
14818
14819 void notePreUse(Object O, const Expr *UseExpr) {
14820 UsageInfo &UI = UsageMap[O];
14821 // Uses conflict with other modifications.
14822 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14823 }
14824
14825 void notePostUse(Object O, const Expr *UseExpr) {
14826 UsageInfo &UI = UsageMap[O];
14827 checkUsage(O, UI, UsageExpr: UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14828 /*IsModMod=*/false);
14829 addUsage(O, UI, UsageExpr: UseExpr, /*UsageKind=*/UK: UK_Use);
14830 }
14831
14832 void notePreMod(Object O, const Expr *ModExpr) {
14833 UsageInfo &UI = UsageMap[O];
14834 // Modifications conflict with other modifications and with uses.
14835 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14836 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14837 }
14838
14839 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14840 UsageInfo &UI = UsageMap[O];
14841 checkUsage(O, UI, UsageExpr: ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14842 /*IsModMod=*/true);
14843 addUsage(O, UI, UsageExpr: ModExpr, /*UsageKind=*/UK);
14844 }
14845
14846public:
14847 SequenceChecker(Sema &S, const Expr *E,
14848 SmallVectorImpl<const Expr *> &WorkList)
14849 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14850 Visit(S: E);
14851 // Silence a -Wunused-private-field since WorkList is now unused.
14852 // TODO: Evaluate if it can be used, and if not remove it.
14853 (void)this->WorkList;
14854 }
14855
14856 void VisitStmt(const Stmt *S) {
14857 // Skip all statements which aren't expressions for now.
14858 }
14859
14860 void VisitExpr(const Expr *E) {
14861 // By default, just recurse to evaluated subexpressions.
14862 Base::VisitStmt(S: E);
14863 }
14864
14865 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) {
14866 for (auto *Sub : CSE->children()) {
14867 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Val: Sub);
14868 if (!ChildExpr)
14869 continue;
14870
14871 if (ChildExpr == CSE->getOperand())
14872 // Do not recurse over a CoroutineSuspendExpr's operand.
14873 // The operand is also a subexpression of getCommonExpr(), and
14874 // recursing into it directly could confuse object management
14875 // for the sake of sequence tracking.
14876 continue;
14877
14878 Visit(S: Sub);
14879 }
14880 }
14881
14882 void VisitCastExpr(const CastExpr *E) {
14883 Object O = Object();
14884 if (E->getCastKind() == CK_LValueToRValue)
14885 O = getObject(E: E->getSubExpr(), Mod: false);
14886
14887 if (O)
14888 notePreUse(O, UseExpr: E);
14889 VisitExpr(E);
14890 if (O)
14891 notePostUse(O, UseExpr: E);
14892 }
14893
14894 void VisitSequencedExpressions(const Expr *SequencedBefore,
14895 const Expr *SequencedAfter) {
14896 SequenceTree::Seq BeforeRegion = Tree.allocate(Parent: Region);
14897 SequenceTree::Seq AfterRegion = Tree.allocate(Parent: Region);
14898 SequenceTree::Seq OldRegion = Region;
14899
14900 {
14901 SequencedSubexpression SeqBefore(*this);
14902 Region = BeforeRegion;
14903 Visit(S: SequencedBefore);
14904 }
14905
14906 Region = AfterRegion;
14907 Visit(S: SequencedAfter);
14908
14909 Region = OldRegion;
14910
14911 Tree.merge(S: BeforeRegion);
14912 Tree.merge(S: AfterRegion);
14913 }
14914
14915 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14916 // C++17 [expr.sub]p1:
14917 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14918 // expression E1 is sequenced before the expression E2.
14919 if (SemaRef.getLangOpts().CPlusPlus17)
14920 VisitSequencedExpressions(SequencedBefore: ASE->getLHS(), SequencedAfter: ASE->getRHS());
14921 else {
14922 Visit(S: ASE->getLHS());
14923 Visit(S: ASE->getRHS());
14924 }
14925 }
14926
14927 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14928 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14929 void VisitBinPtrMem(const BinaryOperator *BO) {
14930 // C++17 [expr.mptr.oper]p4:
14931 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14932 // the expression E1 is sequenced before the expression E2.
14933 if (SemaRef.getLangOpts().CPlusPlus17)
14934 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
14935 else {
14936 Visit(S: BO->getLHS());
14937 Visit(S: BO->getRHS());
14938 }
14939 }
14940
14941 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14942 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14943 void VisitBinShlShr(const BinaryOperator *BO) {
14944 // C++17 [expr.shift]p4:
14945 // The expression E1 is sequenced before the expression E2.
14946 if (SemaRef.getLangOpts().CPlusPlus17)
14947 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
14948 else {
14949 Visit(S: BO->getLHS());
14950 Visit(S: BO->getRHS());
14951 }
14952 }
14953
14954 void VisitBinComma(const BinaryOperator *BO) {
14955 // C++11 [expr.comma]p1:
14956 // Every value computation and side effect associated with the left
14957 // expression is sequenced before every value computation and side
14958 // effect associated with the right expression.
14959 VisitSequencedExpressions(SequencedBefore: BO->getLHS(), SequencedAfter: BO->getRHS());
14960 }
14961
14962 void VisitBinAssign(const BinaryOperator *BO) {
14963 SequenceTree::Seq RHSRegion;
14964 SequenceTree::Seq LHSRegion;
14965 if (SemaRef.getLangOpts().CPlusPlus17) {
14966 RHSRegion = Tree.allocate(Parent: Region);
14967 LHSRegion = Tree.allocate(Parent: Region);
14968 } else {
14969 RHSRegion = Region;
14970 LHSRegion = Region;
14971 }
14972 SequenceTree::Seq OldRegion = Region;
14973
14974 // C++11 [expr.ass]p1:
14975 // [...] the assignment is sequenced after the value computation
14976 // of the right and left operands, [...]
14977 //
14978 // so check it before inspecting the operands and update the
14979 // map afterwards.
14980 Object O = getObject(E: BO->getLHS(), /*Mod=*/true);
14981 if (O)
14982 notePreMod(O, ModExpr: BO);
14983
14984 if (SemaRef.getLangOpts().CPlusPlus17) {
14985 // C++17 [expr.ass]p1:
14986 // [...] The right operand is sequenced before the left operand. [...]
14987 {
14988 SequencedSubexpression SeqBefore(*this);
14989 Region = RHSRegion;
14990 Visit(S: BO->getRHS());
14991 }
14992
14993 Region = LHSRegion;
14994 Visit(S: BO->getLHS());
14995
14996 if (O && isa<CompoundAssignOperator>(Val: BO))
14997 notePostUse(O, UseExpr: BO);
14998
14999 } else {
15000 // C++11 does not specify any sequencing between the LHS and RHS.
15001 Region = LHSRegion;
15002 Visit(S: BO->getLHS());
15003
15004 if (O && isa<CompoundAssignOperator>(Val: BO))
15005 notePostUse(O, UseExpr: BO);
15006
15007 Region = RHSRegion;
15008 Visit(S: BO->getRHS());
15009 }
15010
15011 // C++11 [expr.ass]p1:
15012 // the assignment is sequenced [...] before the value computation of the
15013 // assignment expression.
15014 // C11 6.5.16/3 has no such rule.
15015 Region = OldRegion;
15016 if (O)
15017 notePostMod(O, ModExpr: BO,
15018 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15019 : UK_ModAsSideEffect);
15020 if (SemaRef.getLangOpts().CPlusPlus17) {
15021 Tree.merge(S: RHSRegion);
15022 Tree.merge(S: LHSRegion);
15023 }
15024 }
15025
15026 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
15027 VisitBinAssign(BO: CAO);
15028 }
15029
15030 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15031 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15032 void VisitUnaryPreIncDec(const UnaryOperator *UO) {
15033 Object O = getObject(E: UO->getSubExpr(), Mod: true);
15034 if (!O)
15035 return VisitExpr(E: UO);
15036
15037 notePreMod(O, ModExpr: UO);
15038 Visit(S: UO->getSubExpr());
15039 // C++11 [expr.pre.incr]p1:
15040 // the expression ++x is equivalent to x+=1
15041 notePostMod(O, ModExpr: UO,
15042 UK: SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
15043 : UK_ModAsSideEffect);
15044 }
15045
15046 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15047 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15048 void VisitUnaryPostIncDec(const UnaryOperator *UO) {
15049 Object O = getObject(E: UO->getSubExpr(), Mod: true);
15050 if (!O)
15051 return VisitExpr(E: UO);
15052
15053 notePreMod(O, ModExpr: UO);
15054 Visit(S: UO->getSubExpr());
15055 notePostMod(O, ModExpr: UO, UK: UK_ModAsSideEffect);
15056 }
15057
15058 void VisitBinLOr(const BinaryOperator *BO) {
15059 // C++11 [expr.log.or]p2:
15060 // If the second expression is evaluated, every value computation and
15061 // side effect associated with the first expression is sequenced before
15062 // every value computation and side effect associated with the
15063 // second expression.
15064 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
15065 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
15066 SequenceTree::Seq OldRegion = Region;
15067
15068 EvaluationTracker Eval(*this);
15069 {
15070 SequencedSubexpression Sequenced(*this);
15071 Region = LHSRegion;
15072 Visit(S: BO->getLHS());
15073 }
15074
15075 // C++11 [expr.log.or]p1:
15076 // [...] the second operand is not evaluated if the first operand
15077 // evaluates to true.
15078 bool EvalResult = false;
15079 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
15080 bool ShouldVisitRHS = !EvalOK || !EvalResult;
15081 if (ShouldVisitRHS) {
15082 Region = RHSRegion;
15083 Visit(S: BO->getRHS());
15084 }
15085
15086 Region = OldRegion;
15087 Tree.merge(S: LHSRegion);
15088 Tree.merge(S: RHSRegion);
15089 }
15090
15091 void VisitBinLAnd(const BinaryOperator *BO) {
15092 // C++11 [expr.log.and]p2:
15093 // If the second expression is evaluated, every value computation and
15094 // side effect associated with the first expression is sequenced before
15095 // every value computation and side effect associated with the
15096 // second expression.
15097 SequenceTree::Seq LHSRegion = Tree.allocate(Parent: Region);
15098 SequenceTree::Seq RHSRegion = Tree.allocate(Parent: Region);
15099 SequenceTree::Seq OldRegion = Region;
15100
15101 EvaluationTracker Eval(*this);
15102 {
15103 SequencedSubexpression Sequenced(*this);
15104 Region = LHSRegion;
15105 Visit(S: BO->getLHS());
15106 }
15107
15108 // C++11 [expr.log.and]p1:
15109 // [...] the second operand is not evaluated if the first operand is false.
15110 bool EvalResult = false;
15111 bool EvalOK = Eval.evaluate(E: BO->getLHS(), Result&: EvalResult);
15112 bool ShouldVisitRHS = !EvalOK || EvalResult;
15113 if (ShouldVisitRHS) {
15114 Region = RHSRegion;
15115 Visit(S: BO->getRHS());
15116 }
15117
15118 Region = OldRegion;
15119 Tree.merge(S: LHSRegion);
15120 Tree.merge(S: RHSRegion);
15121 }
15122
15123 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
15124 // C++11 [expr.cond]p1:
15125 // [...] Every value computation and side effect associated with the first
15126 // expression is sequenced before every value computation and side effect
15127 // associated with the second or third expression.
15128 SequenceTree::Seq ConditionRegion = Tree.allocate(Parent: Region);
15129
15130 // No sequencing is specified between the true and false expression.
15131 // However since exactly one of both is going to be evaluated we can
15132 // consider them to be sequenced. This is needed to avoid warning on
15133 // something like "x ? y+= 1 : y += 2;" in the case where we will visit
15134 // both the true and false expressions because we can't evaluate x.
15135 // This will still allow us to detect an expression like (pre C++17)
15136 // "(x ? y += 1 : y += 2) = y".
15137 //
15138 // We don't wrap the visitation of the true and false expression with
15139 // SequencedSubexpression because we don't want to downgrade modifications
15140 // as side effect in the true and false expressions after the visition
15141 // is done. (for example in the expression "(x ? y++ : y++) + y" we should
15142 // not warn between the two "y++", but we should warn between the "y++"
15143 // and the "y".
15144 SequenceTree::Seq TrueRegion = Tree.allocate(Parent: Region);
15145 SequenceTree::Seq FalseRegion = Tree.allocate(Parent: Region);
15146 SequenceTree::Seq OldRegion = Region;
15147
15148 EvaluationTracker Eval(*this);
15149 {
15150 SequencedSubexpression Sequenced(*this);
15151 Region = ConditionRegion;
15152 Visit(S: CO->getCond());
15153 }
15154
15155 // C++11 [expr.cond]p1:
15156 // [...] The first expression is contextually converted to bool (Clause 4).
15157 // It is evaluated and if it is true, the result of the conditional
15158 // expression is the value of the second expression, otherwise that of the
15159 // third expression. Only one of the second and third expressions is
15160 // evaluated. [...]
15161 bool EvalResult = false;
15162 bool EvalOK = Eval.evaluate(E: CO->getCond(), Result&: EvalResult);
15163 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15164 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15165 if (ShouldVisitTrueExpr) {
15166 Region = TrueRegion;
15167 Visit(S: CO->getTrueExpr());
15168 }
15169 if (ShouldVisitFalseExpr) {
15170 Region = FalseRegion;
15171 Visit(S: CO->getFalseExpr());
15172 }
15173
15174 Region = OldRegion;
15175 Tree.merge(S: ConditionRegion);
15176 Tree.merge(S: TrueRegion);
15177 Tree.merge(S: FalseRegion);
15178 }
15179
15180 void VisitCallExpr(const CallExpr *CE) {
15181 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
15182
15183 if (CE->isUnevaluatedBuiltinCall(Ctx: Context))
15184 return;
15185
15186 // C++11 [intro.execution]p15:
15187 // When calling a function [...], every value computation and side effect
15188 // associated with any argument expression, or with the postfix expression
15189 // designating the called function, is sequenced before execution of every
15190 // expression or statement in the body of the function [and thus before
15191 // the value computation of its result].
15192 SequencedSubexpression Sequenced(*this);
15193 SemaRef.runWithSufficientStackSpace(Loc: CE->getExprLoc(), Fn: [&] {
15194 // C++17 [expr.call]p5
15195 // The postfix-expression is sequenced before each expression in the
15196 // expression-list and any default argument. [...]
15197 SequenceTree::Seq CalleeRegion;
15198 SequenceTree::Seq OtherRegion;
15199 if (SemaRef.getLangOpts().CPlusPlus17) {
15200 CalleeRegion = Tree.allocate(Parent: Region);
15201 OtherRegion = Tree.allocate(Parent: Region);
15202 } else {
15203 CalleeRegion = Region;
15204 OtherRegion = Region;
15205 }
15206 SequenceTree::Seq OldRegion = Region;
15207
15208 // Visit the callee expression first.
15209 Region = CalleeRegion;
15210 if (SemaRef.getLangOpts().CPlusPlus17) {
15211 SequencedSubexpression Sequenced(*this);
15212 Visit(S: CE->getCallee());
15213 } else {
15214 Visit(S: CE->getCallee());
15215 }
15216
15217 // Then visit the argument expressions.
15218 Region = OtherRegion;
15219 for (const Expr *Argument : CE->arguments())
15220 Visit(S: Argument);
15221
15222 Region = OldRegion;
15223 if (SemaRef.getLangOpts().CPlusPlus17) {
15224 Tree.merge(S: CalleeRegion);
15225 Tree.merge(S: OtherRegion);
15226 }
15227 });
15228 }
15229
15230 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
15231 // C++17 [over.match.oper]p2:
15232 // [...] the operator notation is first transformed to the equivalent
15233 // function-call notation as summarized in Table 12 (where @ denotes one
15234 // of the operators covered in the specified subclause). However, the
15235 // operands are sequenced in the order prescribed for the built-in
15236 // operator (Clause 8).
15237 //
15238 // From the above only overloaded binary operators and overloaded call
15239 // operators have sequencing rules in C++17 that we need to handle
15240 // separately.
15241 if (!SemaRef.getLangOpts().CPlusPlus17 ||
15242 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
15243 return VisitCallExpr(CE: CXXOCE);
15244
15245 enum {
15246 NoSequencing,
15247 LHSBeforeRHS,
15248 RHSBeforeLHS,
15249 LHSBeforeRest
15250 } SequencingKind;
15251 switch (CXXOCE->getOperator()) {
15252 case OO_Equal:
15253 case OO_PlusEqual:
15254 case OO_MinusEqual:
15255 case OO_StarEqual:
15256 case OO_SlashEqual:
15257 case OO_PercentEqual:
15258 case OO_CaretEqual:
15259 case OO_AmpEqual:
15260 case OO_PipeEqual:
15261 case OO_LessLessEqual:
15262 case OO_GreaterGreaterEqual:
15263 SequencingKind = RHSBeforeLHS;
15264 break;
15265
15266 case OO_LessLess:
15267 case OO_GreaterGreater:
15268 case OO_AmpAmp:
15269 case OO_PipePipe:
15270 case OO_Comma:
15271 case OO_ArrowStar:
15272 case OO_Subscript:
15273 SequencingKind = LHSBeforeRHS;
15274 break;
15275
15276 case OO_Call:
15277 SequencingKind = LHSBeforeRest;
15278 break;
15279
15280 default:
15281 SequencingKind = NoSequencing;
15282 break;
15283 }
15284
15285 if (SequencingKind == NoSequencing)
15286 return VisitCallExpr(CE: CXXOCE);
15287
15288 // This is a call, so all subexpressions are sequenced before the result.
15289 SequencedSubexpression Sequenced(*this);
15290
15291 SemaRef.runWithSufficientStackSpace(Loc: CXXOCE->getExprLoc(), Fn: [&] {
15292 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15293 "Should only get there with C++17 and above!");
15294 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15295 "Should only get there with an overloaded binary operator"
15296 " or an overloaded call operator!");
15297
15298 if (SequencingKind == LHSBeforeRest) {
15299 assert(CXXOCE->getOperator() == OO_Call &&
15300 "We should only have an overloaded call operator here!");
15301
15302 // This is very similar to VisitCallExpr, except that we only have the
15303 // C++17 case. The postfix-expression is the first argument of the
15304 // CXXOperatorCallExpr. The expressions in the expression-list, if any,
15305 // are in the following arguments.
15306 //
15307 // Note that we intentionally do not visit the callee expression since
15308 // it is just a decayed reference to a function.
15309 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Parent: Region);
15310 SequenceTree::Seq ArgsRegion = Tree.allocate(Parent: Region);
15311 SequenceTree::Seq OldRegion = Region;
15312
15313 assert(CXXOCE->getNumArgs() >= 1 &&
15314 "An overloaded call operator must have at least one argument"
15315 " for the postfix-expression!");
15316 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15317 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15318 CXXOCE->getNumArgs() - 1);
15319
15320 // Visit the postfix-expression first.
15321 {
15322 Region = PostfixExprRegion;
15323 SequencedSubexpression Sequenced(*this);
15324 Visit(S: PostfixExpr);
15325 }
15326
15327 // Then visit the argument expressions.
15328 Region = ArgsRegion;
15329 for (const Expr *Arg : Args)
15330 Visit(S: Arg);
15331
15332 Region = OldRegion;
15333 Tree.merge(S: PostfixExprRegion);
15334 Tree.merge(S: ArgsRegion);
15335 } else {
15336 assert(CXXOCE->getNumArgs() == 2 &&
15337 "Should only have two arguments here!");
15338 assert((SequencingKind == LHSBeforeRHS ||
15339 SequencingKind == RHSBeforeLHS) &&
15340 "Unexpected sequencing kind!");
15341
15342 // We do not visit the callee expression since it is just a decayed
15343 // reference to a function.
15344 const Expr *E1 = CXXOCE->getArg(Arg: 0);
15345 const Expr *E2 = CXXOCE->getArg(Arg: 1);
15346 if (SequencingKind == RHSBeforeLHS)
15347 std::swap(a&: E1, b&: E2);
15348
15349 return VisitSequencedExpressions(SequencedBefore: E1, SequencedAfter: E2);
15350 }
15351 });
15352 }
15353
15354 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
15355 // This is a call, so all subexpressions are sequenced before the result.
15356 SequencedSubexpression Sequenced(*this);
15357
15358 if (!CCE->isListInitialization())
15359 return VisitExpr(E: CCE);
15360
15361 // In C++11, list initializations are sequenced.
15362 SequenceExpressionsInOrder(
15363 ExpressionList: llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs()));
15364 }
15365
15366 void VisitInitListExpr(const InitListExpr *ILE) {
15367 if (!SemaRef.getLangOpts().CPlusPlus11)
15368 return VisitExpr(E: ILE);
15369
15370 // In C++11, list initializations are sequenced.
15371 SequenceExpressionsInOrder(ExpressionList: ILE->inits());
15372 }
15373
15374 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) {
15375 // C++20 parenthesized list initializations are sequenced. See C++20
15376 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2.
15377 SequenceExpressionsInOrder(ExpressionList: PLIE->getInitExprs());
15378 }
15379
15380private:
15381 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) {
15382 SmallVector<SequenceTree::Seq, 32> Elts;
15383 SequenceTree::Seq Parent = Region;
15384 for (const Expr *E : ExpressionList) {
15385 if (!E)
15386 continue;
15387 Region = Tree.allocate(Parent);
15388 Elts.push_back(Elt: Region);
15389 Visit(S: E);
15390 }
15391
15392 // Forget that the initializers are sequenced.
15393 Region = Parent;
15394 for (unsigned I = 0; I < Elts.size(); ++I)
15395 Tree.merge(S: Elts[I]);
15396 }
15397};
15398
15399SequenceChecker::UsageInfo::UsageInfo() = default;
15400
15401} // namespace
15402
15403void Sema::CheckUnsequencedOperations(const Expr *E) {
15404 SmallVector<const Expr *, 8> WorkList;
15405 WorkList.push_back(Elt: E);
15406 while (!WorkList.empty()) {
15407 const Expr *Item = WorkList.pop_back_val();
15408 SequenceChecker(*this, Item, WorkList);
15409 }
15410}
15411
15412void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
15413 bool IsConstexpr) {
15414 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride,
15415 IsConstexpr || isa<ConstantExpr>(Val: E));
15416 CheckImplicitConversions(E, CC: CheckLoc);
15417 if (!E->isInstantiationDependent())
15418 CheckUnsequencedOperations(E);
15419 if (!IsConstexpr && !E->isValueDependent())
15420 CheckForIntOverflow(E);
15421}
15422
15423void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
15424 FieldDecl *BitField,
15425 Expr *Init) {
15426 (void) AnalyzeBitFieldAssignment(S&: *this, Bitfield: BitField, Init, InitLoc);
15427}
15428
15429static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
15430 SourceLocation Loc) {
15431 if (!PType->isVariablyModifiedType())
15432 return;
15433 if (const auto *PointerTy = dyn_cast<PointerType>(Val&: PType)) {
15434 diagnoseArrayStarInParamType(S, PType: PointerTy->getPointeeType(), Loc);
15435 return;
15436 }
15437 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(Val&: PType)) {
15438 diagnoseArrayStarInParamType(S, PType: ReferenceTy->getPointeeType(), Loc);
15439 return;
15440 }
15441 if (const auto *ParenTy = dyn_cast<ParenType>(Val&: PType)) {
15442 diagnoseArrayStarInParamType(S, PType: ParenTy->getInnerType(), Loc);
15443 return;
15444 }
15445
15446 const ArrayType *AT = S.Context.getAsArrayType(T: PType);
15447 if (!AT)
15448 return;
15449
15450 if (AT->getSizeModifier() != ArraySizeModifier::Star) {
15451 diagnoseArrayStarInParamType(S, PType: AT->getElementType(), Loc);
15452 return;
15453 }
15454
15455 S.Diag(Loc, DiagID: diag::err_array_star_in_function_definition);
15456}
15457
15458bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
15459 bool CheckParameterNames) {
15460 bool HasInvalidParm = false;
15461 for (ParmVarDecl *Param : Parameters) {
15462 assert(Param && "null in a parameter list");
15463 // C99 6.7.5.3p4: the parameters in a parameter type list in a
15464 // function declarator that is part of a function definition of
15465 // that function shall not have incomplete type.
15466 //
15467 // C++23 [dcl.fct.def.general]/p2
15468 // The type of a parameter [...] for a function definition
15469 // shall not be a (possibly cv-qualified) class type that is incomplete
15470 // or abstract within the function body unless the function is deleted.
15471 if (!Param->isInvalidDecl() &&
15472 (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
15473 DiagID: diag::err_typecheck_decl_incomplete_type) ||
15474 RequireNonAbstractType(Loc: Param->getBeginLoc(), T: Param->getOriginalType(),
15475 DiagID: diag::err_abstract_type_in_decl,
15476 Args: AbstractParamType))) {
15477 Param->setInvalidDecl();
15478 HasInvalidParm = true;
15479 }
15480
15481 // C99 6.9.1p5: If the declarator includes a parameter type list, the
15482 // declaration of each parameter shall include an identifier.
15483 if (CheckParameterNames && Param->getIdentifier() == nullptr &&
15484 !Param->isImplicit() && !getLangOpts().CPlusPlus) {
15485 // Diagnose this as an extension in C17 and earlier.
15486 if (!getLangOpts().C23)
15487 Diag(Loc: Param->getLocation(), DiagID: diag::ext_parameter_name_omitted_c23);
15488 }
15489
15490 // C99 6.7.5.3p12:
15491 // If the function declarator is not part of a definition of that
15492 // function, parameters may have incomplete type and may use the [*]
15493 // notation in their sequences of declarator specifiers to specify
15494 // variable length array types.
15495 QualType PType = Param->getOriginalType();
15496 // FIXME: This diagnostic should point the '[*]' if source-location
15497 // information is added for it.
15498 diagnoseArrayStarInParamType(S&: *this, PType, Loc: Param->getLocation());
15499
15500 // If the parameter is a c++ class type and it has to be destructed in the
15501 // callee function, declare the destructor so that it can be called by the
15502 // callee function. Do not perform any direct access check on the dtor here.
15503 if (!Param->isInvalidDecl()) {
15504 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15505 if (!ClassDecl->isInvalidDecl() &&
15506 !ClassDecl->hasIrrelevantDestructor() &&
15507 !ClassDecl->isDependentContext() &&
15508 ClassDecl->isParamDestroyedInCallee()) {
15509 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
15510 MarkFunctionReferenced(Loc: Param->getLocation(), Func: Destructor);
15511 DiagnoseUseOfDecl(D: Destructor, Locs: Param->getLocation());
15512 }
15513 }
15514 }
15515
15516 // Parameters with the pass_object_size attribute only need to be marked
15517 // constant at function definitions. Because we lack information about
15518 // whether we're on a declaration or definition when we're instantiating the
15519 // attribute, we need to check for constness here.
15520 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
15521 if (!Param->getType().isConstQualified())
15522 Diag(Loc: Param->getLocation(), DiagID: diag::err_attribute_pointers_only)
15523 << Attr->getSpelling() << 1;
15524
15525 // Check for parameter names shadowing fields from the class.
15526 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15527 // The owning context for the parameter should be the function, but we
15528 // want to see if this function's declaration context is a record.
15529 DeclContext *DC = Param->getDeclContext();
15530 if (DC && DC->isFunctionOrMethod()) {
15531 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC->getParent()))
15532 CheckShadowInheritedFields(Loc: Param->getLocation(), FieldName: Param->getDeclName(),
15533 RD, /*DeclIsField*/ false);
15534 }
15535 }
15536
15537 if (!Param->isInvalidDecl() &&
15538 Param->getOriginalType()->isWebAssemblyTableType()) {
15539 Param->setInvalidDecl();
15540 HasInvalidParm = true;
15541 Diag(Loc: Param->getLocation(), DiagID: diag::err_wasm_table_as_function_parameter);
15542 }
15543 }
15544
15545 return HasInvalidParm;
15546}
15547
15548std::optional<std::pair<
15549 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15550 *E,
15551 ASTContext
15552 &Ctx);
15553
15554/// Compute the alignment and offset of the base class object given the
15555/// derived-to-base cast expression and the alignment and offset of the derived
15556/// class object.
15557static std::pair<CharUnits, CharUnits>
15558getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
15559 CharUnits BaseAlignment, CharUnits Offset,
15560 ASTContext &Ctx) {
15561 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
15562 ++PathI) {
15563 const CXXBaseSpecifier *Base = *PathI;
15564 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
15565 if (Base->isVirtual()) {
15566 // The complete object may have a lower alignment than the non-virtual
15567 // alignment of the base, in which case the base may be misaligned. Choose
15568 // the smaller of the non-virtual alignment and BaseAlignment, which is a
15569 // conservative lower bound of the complete object alignment.
15570 CharUnits NonVirtualAlignment =
15571 Ctx.getASTRecordLayout(D: BaseDecl).getNonVirtualAlignment();
15572 BaseAlignment = std::min(a: BaseAlignment, b: NonVirtualAlignment);
15573 Offset = CharUnits::Zero();
15574 } else {
15575 const ASTRecordLayout &RL =
15576 Ctx.getASTRecordLayout(D: DerivedType->getAsCXXRecordDecl());
15577 Offset += RL.getBaseClassOffset(Base: BaseDecl);
15578 }
15579 DerivedType = Base->getType();
15580 }
15581
15582 return std::make_pair(x&: BaseAlignment, y&: Offset);
15583}
15584
15585/// Compute the alignment and offset of a binary additive operator.
15586static std::optional<std::pair<CharUnits, CharUnits>>
15587getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
15588 bool IsSub, ASTContext &Ctx) {
15589 QualType PointeeType = PtrE->getType()->getPointeeType();
15590
15591 if (!PointeeType->isConstantSizeType())
15592 return std::nullopt;
15593
15594 auto P = getBaseAlignmentAndOffsetFromPtr(E: PtrE, Ctx);
15595
15596 if (!P)
15597 return std::nullopt;
15598
15599 CharUnits EltSize = Ctx.getTypeSizeInChars(T: PointeeType);
15600 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
15601 CharUnits Offset = EltSize * IdxRes->getExtValue();
15602 if (IsSub)
15603 Offset = -Offset;
15604 return std::make_pair(x&: P->first, y: P->second + Offset);
15605 }
15606
15607 // If the integer expression isn't a constant expression, compute the lower
15608 // bound of the alignment using the alignment and offset of the pointer
15609 // expression and the element size.
15610 return std::make_pair(
15611 x: P->first.alignmentAtOffset(offset: P->second).alignmentAtOffset(offset: EltSize),
15612 y: CharUnits::Zero());
15613}
15614
15615/// This helper function takes an lvalue expression and returns the alignment of
15616/// a VarDecl and a constant offset from the VarDecl.
15617std::optional<std::pair<
15618 CharUnits,
15619 CharUnits>> static getBaseAlignmentAndOffsetFromLValue(const Expr *E,
15620 ASTContext &Ctx) {
15621 E = E->IgnoreParens();
15622 switch (E->getStmtClass()) {
15623 default:
15624 break;
15625 case Stmt::CStyleCastExprClass:
15626 case Stmt::CXXStaticCastExprClass:
15627 case Stmt::ImplicitCastExprClass: {
15628 auto *CE = cast<CastExpr>(Val: E);
15629 const Expr *From = CE->getSubExpr();
15630 switch (CE->getCastKind()) {
15631 default:
15632 break;
15633 case CK_NoOp:
15634 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15635 case CK_UncheckedDerivedToBase:
15636 case CK_DerivedToBase: {
15637 auto P = getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15638 if (!P)
15639 break;
15640 return getDerivedToBaseAlignmentAndOffset(CE, DerivedType: From->getType(), BaseAlignment: P->first,
15641 Offset: P->second, Ctx);
15642 }
15643 }
15644 break;
15645 }
15646 case Stmt::ArraySubscriptExprClass: {
15647 auto *ASE = cast<ArraySubscriptExpr>(Val: E);
15648 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: ASE->getBase(), IntE: ASE->getIdx(),
15649 IsSub: false, Ctx);
15650 }
15651 case Stmt::DeclRefExprClass: {
15652 if (auto *VD = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: E)->getDecl())) {
15653 // FIXME: If VD is captured by copy or is an escaping __block variable,
15654 // use the alignment of VD's type.
15655 if (!VD->getType()->isReferenceType()) {
15656 // Dependent alignment cannot be resolved -> bail out.
15657 if (VD->hasDependentAlignment())
15658 break;
15659 return std::make_pair(x: Ctx.getDeclAlign(D: VD), y: CharUnits::Zero());
15660 }
15661 if (VD->hasInit())
15662 return getBaseAlignmentAndOffsetFromLValue(E: VD->getInit(), Ctx);
15663 }
15664 break;
15665 }
15666 case Stmt::MemberExprClass: {
15667 auto *ME = cast<MemberExpr>(Val: E);
15668 auto *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
15669 if (!FD || FD->getType()->isReferenceType() ||
15670 FD->getParent()->isInvalidDecl())
15671 break;
15672 std::optional<std::pair<CharUnits, CharUnits>> P;
15673 if (ME->isArrow())
15674 P = getBaseAlignmentAndOffsetFromPtr(E: ME->getBase(), Ctx);
15675 else
15676 P = getBaseAlignmentAndOffsetFromLValue(E: ME->getBase(), Ctx);
15677 if (!P)
15678 break;
15679 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(D: FD->getParent());
15680 uint64_t Offset = Layout.getFieldOffset(FieldNo: FD->getFieldIndex());
15681 return std::make_pair(x&: P->first,
15682 y: P->second + CharUnits::fromQuantity(Quantity: Offset));
15683 }
15684 case Stmt::UnaryOperatorClass: {
15685 auto *UO = cast<UnaryOperator>(Val: E);
15686 switch (UO->getOpcode()) {
15687 default:
15688 break;
15689 case UO_Deref:
15690 return getBaseAlignmentAndOffsetFromPtr(E: UO->getSubExpr(), Ctx);
15691 }
15692 break;
15693 }
15694 case Stmt::BinaryOperatorClass: {
15695 auto *BO = cast<BinaryOperator>(Val: E);
15696 auto Opcode = BO->getOpcode();
15697 switch (Opcode) {
15698 default:
15699 break;
15700 case BO_Comma:
15701 return getBaseAlignmentAndOffsetFromLValue(E: BO->getRHS(), Ctx);
15702 }
15703 break;
15704 }
15705 }
15706 return std::nullopt;
15707}
15708
15709/// This helper function takes a pointer expression and returns the alignment of
15710/// a VarDecl and a constant offset from the VarDecl.
15711std::optional<std::pair<
15712 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr
15713 *E,
15714 ASTContext
15715 &Ctx) {
15716 E = E->IgnoreParens();
15717 switch (E->getStmtClass()) {
15718 default:
15719 break;
15720 case Stmt::CStyleCastExprClass:
15721 case Stmt::CXXStaticCastExprClass:
15722 case Stmt::ImplicitCastExprClass: {
15723 auto *CE = cast<CastExpr>(Val: E);
15724 const Expr *From = CE->getSubExpr();
15725 switch (CE->getCastKind()) {
15726 default:
15727 break;
15728 case CK_NoOp:
15729 return getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15730 case CK_ArrayToPointerDecay:
15731 return getBaseAlignmentAndOffsetFromLValue(E: From, Ctx);
15732 case CK_UncheckedDerivedToBase:
15733 case CK_DerivedToBase: {
15734 auto P = getBaseAlignmentAndOffsetFromPtr(E: From, Ctx);
15735 if (!P)
15736 break;
15737 return getDerivedToBaseAlignmentAndOffset(
15738 CE, DerivedType: From->getType()->getPointeeType(), BaseAlignment: P->first, Offset: P->second, Ctx);
15739 }
15740 }
15741 break;
15742 }
15743 case Stmt::CXXThisExprClass: {
15744 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
15745 CharUnits Alignment = Ctx.getASTRecordLayout(D: RD).getNonVirtualAlignment();
15746 return std::make_pair(x&: Alignment, y: CharUnits::Zero());
15747 }
15748 case Stmt::UnaryOperatorClass: {
15749 auto *UO = cast<UnaryOperator>(Val: E);
15750 if (UO->getOpcode() == UO_AddrOf)
15751 return getBaseAlignmentAndOffsetFromLValue(E: UO->getSubExpr(), Ctx);
15752 break;
15753 }
15754 case Stmt::BinaryOperatorClass: {
15755 auto *BO = cast<BinaryOperator>(Val: E);
15756 auto Opcode = BO->getOpcode();
15757 switch (Opcode) {
15758 default:
15759 break;
15760 case BO_Add:
15761 case BO_Sub: {
15762 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
15763 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
15764 std::swap(a&: LHS, b&: RHS);
15765 return getAlignmentAndOffsetFromBinAddOrSub(PtrE: LHS, IntE: RHS, IsSub: Opcode == BO_Sub,
15766 Ctx);
15767 }
15768 case BO_Comma:
15769 return getBaseAlignmentAndOffsetFromPtr(E: BO->getRHS(), Ctx);
15770 }
15771 break;
15772 }
15773 }
15774 return std::nullopt;
15775}
15776
15777static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
15778 // See if we can compute the alignment of a VarDecl and an offset from it.
15779 std::optional<std::pair<CharUnits, CharUnits>> P =
15780 getBaseAlignmentAndOffsetFromPtr(E, Ctx&: S.Context);
15781
15782 if (P)
15783 return P->first.alignmentAtOffset(offset: P->second);
15784
15785 // If that failed, return the type's alignment.
15786 return S.Context.getTypeAlignInChars(T: E->getType()->getPointeeType());
15787}
15788
15789void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
15790 // This is actually a lot of work to potentially be doing on every
15791 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
15792 if (getDiagnostics().isIgnored(DiagID: diag::warn_cast_align, Loc: TRange.getBegin()))
15793 return;
15794
15795 // Ignore dependent types.
15796 if (T->isDependentType() || Op->getType()->isDependentType())
15797 return;
15798
15799 // Require that the destination be a pointer type.
15800 const PointerType *DestPtr = T->getAs<PointerType>();
15801 if (!DestPtr) return;
15802
15803 // If the destination has alignment 1, we're done.
15804 QualType DestPointee = DestPtr->getPointeeType();
15805 if (DestPointee->isIncompleteType()) return;
15806 CharUnits DestAlign = Context.getTypeAlignInChars(T: DestPointee);
15807 if (DestAlign.isOne()) return;
15808
15809 // Require that the source be a pointer type.
15810 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
15811 if (!SrcPtr) return;
15812 QualType SrcPointee = SrcPtr->getPointeeType();
15813
15814 // Explicitly allow casts from cv void*. We already implicitly
15815 // allowed casts to cv void*, since they have alignment 1.
15816 // Also allow casts involving incomplete types, which implicitly
15817 // includes 'void'.
15818 if (SrcPointee->isIncompleteType()) return;
15819
15820 CharUnits SrcAlign = getPresumedAlignmentOfPointer(E: Op, S&: *this);
15821
15822 if (SrcAlign >= DestAlign) return;
15823
15824 Diag(Loc: TRange.getBegin(), DiagID: diag::warn_cast_align)
15825 << Op->getType() << T
15826 << static_cast<unsigned>(SrcAlign.getQuantity())
15827 << static_cast<unsigned>(DestAlign.getQuantity())
15828 << TRange << Op->getSourceRange();
15829}
15830
15831void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15832 const ArraySubscriptExpr *ASE,
15833 bool AllowOnePastEnd, bool IndexNegated) {
15834 // Already diagnosed by the constant evaluator.
15835 if (isConstantEvaluatedContext())
15836 return;
15837
15838 IndexExpr = IndexExpr->IgnoreParenImpCasts();
15839 if (IndexExpr->isValueDependent())
15840 return;
15841
15842 const Type *EffectiveType =
15843 BaseExpr->getType()->getPointeeOrArrayElementType();
15844 BaseExpr = BaseExpr->IgnoreParenCasts();
15845 const ConstantArrayType *ArrayTy =
15846 Context.getAsConstantArrayType(T: BaseExpr->getType());
15847
15848 LangOptions::StrictFlexArraysLevelKind
15849 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel();
15850
15851 const Type *BaseType =
15852 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15853 bool IsUnboundedArray =
15854 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike(
15855 Context, StrictFlexArraysLevel,
15856 /*IgnoreTemplateOrMacroSubstitution=*/true);
15857 if (EffectiveType->isDependentType() ||
15858 (!IsUnboundedArray && BaseType->isDependentType()))
15859 return;
15860
15861 Expr::EvalResult Result;
15862 if (!IndexExpr->EvaluateAsInt(Result, Ctx: Context, AllowSideEffects: Expr::SE_AllowSideEffects))
15863 return;
15864
15865 llvm::APSInt index = Result.Val.getInt();
15866 if (IndexNegated) {
15867 index.setIsUnsigned(false);
15868 index = -index;
15869 }
15870
15871 if (IsUnboundedArray) {
15872 if (EffectiveType->isFunctionType())
15873 return;
15874 if (index.isUnsigned() || !index.isNegative()) {
15875 const auto &ASTC = getASTContext();
15876 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
15877 AddrSpace: EffectiveType->getCanonicalTypeInternal().getAddressSpace());
15878 if (index.getBitWidth() < AddrBits)
15879 index = index.zext(width: AddrBits);
15880 std::optional<CharUnits> ElemCharUnits =
15881 ASTC.getTypeSizeInCharsIfKnown(Ty: EffectiveType);
15882 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15883 // pointer) bounds-checking isn't meaningful.
15884 if (!ElemCharUnits || ElemCharUnits->isZero())
15885 return;
15886 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15887 // If index has more active bits than address space, we already know
15888 // we have a bounds violation to warn about. Otherwise, compute
15889 // address of (index + 1)th element, and warn about bounds violation
15890 // only if that address exceeds address space.
15891 if (index.getActiveBits() <= AddrBits) {
15892 bool Overflow;
15893 llvm::APInt Product(index);
15894 Product += 1;
15895 Product = Product.umul_ov(RHS: ElemBytes, Overflow);
15896 if (!Overflow && Product.getActiveBits() <= AddrBits)
15897 return;
15898 }
15899
15900 // Need to compute max possible elements in address space, since that
15901 // is included in diag message.
15902 llvm::APInt MaxElems = llvm::APInt::getMaxValue(numBits: AddrBits);
15903 MaxElems = MaxElems.zext(width: std::max(a: AddrBits + 1, b: ElemBytes.getBitWidth()));
15904 MaxElems += 1;
15905 ElemBytes = ElemBytes.zextOrTrunc(width: MaxElems.getBitWidth());
15906 MaxElems = MaxElems.udiv(RHS: ElemBytes);
15907
15908 unsigned DiagID =
15909 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15910 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15911
15912 // Diag message shows element size in bits and in "bytes" (platform-
15913 // dependent CharUnits)
15914 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
15915 PD: PDiag(DiagID) << index << AddrBits
15916 << (unsigned)ASTC.toBits(CharSize: *ElemCharUnits)
15917 << ElemBytes << MaxElems
15918 << MaxElems.getZExtValue()
15919 << IndexExpr->getSourceRange());
15920
15921 const NamedDecl *ND = nullptr;
15922 // Try harder to find a NamedDecl to point at in the note.
15923 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
15924 BaseExpr = ASE->getBase()->IgnoreParenCasts();
15925 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
15926 ND = DRE->getDecl();
15927 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
15928 ND = ME->getMemberDecl();
15929
15930 if (ND)
15931 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
15932 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
15933 }
15934 return;
15935 }
15936
15937 if (index.isUnsigned() || !index.isNegative()) {
15938 // It is possible that the type of the base expression after
15939 // IgnoreParenCasts is incomplete, even though the type of the base
15940 // expression before IgnoreParenCasts is complete (see PR39746 for an
15941 // example). In this case we have no information about whether the array
15942 // access exceeds the array bounds. However we can still diagnose an array
15943 // access which precedes the array bounds.
15944 if (BaseType->isIncompleteType())
15945 return;
15946
15947 llvm::APInt size = ArrayTy->getSize();
15948
15949 if (BaseType != EffectiveType) {
15950 // Make sure we're comparing apples to apples when comparing index to
15951 // size.
15952 uint64_t ptrarith_typesize = Context.getTypeSize(T: EffectiveType);
15953 uint64_t array_typesize = Context.getTypeSize(T: BaseType);
15954
15955 // Handle ptrarith_typesize being zero, such as when casting to void*.
15956 // Use the size in bits (what "getTypeSize()" returns) rather than bytes.
15957 if (!ptrarith_typesize)
15958 ptrarith_typesize = Context.getCharWidth();
15959
15960 if (ptrarith_typesize != array_typesize) {
15961 // There's a cast to a different size type involved.
15962 uint64_t ratio = array_typesize / ptrarith_typesize;
15963
15964 // TODO: Be smarter about handling cases where array_typesize is not a
15965 // multiple of ptrarith_typesize.
15966 if (ptrarith_typesize * ratio == array_typesize)
15967 size *= llvm::APInt(size.getBitWidth(), ratio);
15968 }
15969 }
15970
15971 if (size.getBitWidth() > index.getBitWidth())
15972 index = index.zext(width: size.getBitWidth());
15973 else if (size.getBitWidth() < index.getBitWidth())
15974 size = size.zext(width: index.getBitWidth());
15975
15976 // For array subscripting the index must be less than size, but for pointer
15977 // arithmetic also allow the index (offset) to be equal to size since
15978 // computing the next address after the end of the array is legal and
15979 // commonly done e.g. in C++ iterators and range-based for loops.
15980 if (AllowOnePastEnd ? index.ule(RHS: size) : index.ult(RHS: size))
15981 return;
15982
15983 // Suppress the warning if the subscript expression (as identified by the
15984 // ']' location) and the index expression are both from macro expansions
15985 // within a system header.
15986 if (ASE) {
15987 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15988 Loc: ASE->getRBracketLoc());
15989 if (SourceMgr.isInSystemHeader(Loc: RBracketLoc)) {
15990 SourceLocation IndexLoc =
15991 SourceMgr.getSpellingLoc(Loc: IndexExpr->getBeginLoc());
15992 if (SourceMgr.isWrittenInSameFile(Loc1: RBracketLoc, Loc2: IndexLoc))
15993 return;
15994 }
15995 }
15996
15997 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15998 : diag::warn_ptr_arith_exceeds_bounds;
15999 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
16000 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType();
16001
16002 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16003 PD: PDiag(DiagID)
16004 << index << ArrayTy->desugar() << CastMsg
16005 << CastMsgTy << IndexExpr->getSourceRange());
16006 } else {
16007 unsigned DiagID = diag::warn_array_index_precedes_bounds;
16008 if (!ASE) {
16009 DiagID = diag::warn_ptr_arith_precedes_bounds;
16010 if (index.isNegative()) index = -index;
16011 }
16012
16013 DiagRuntimeBehavior(Loc: BaseExpr->getBeginLoc(), Statement: BaseExpr,
16014 PD: PDiag(DiagID) << index << IndexExpr->getSourceRange());
16015 }
16016
16017 const NamedDecl *ND = nullptr;
16018 // Try harder to find a NamedDecl to point at in the note.
16019 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: BaseExpr))
16020 BaseExpr = ASE->getBase()->IgnoreParenCasts();
16021 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: BaseExpr))
16022 ND = DRE->getDecl();
16023 if (const auto *ME = dyn_cast<MemberExpr>(Val: BaseExpr))
16024 ND = ME->getMemberDecl();
16025
16026 if (ND)
16027 DiagRuntimeBehavior(Loc: ND->getBeginLoc(), Statement: BaseExpr,
16028 PD: PDiag(DiagID: diag::note_array_declared_here) << ND);
16029}
16030
16031void Sema::CheckArrayAccess(const Expr *expr) {
16032 int AllowOnePastEnd = 0;
16033 while (expr) {
16034 expr = expr->IgnoreParenImpCasts();
16035 switch (expr->getStmtClass()) {
16036 case Stmt::ArraySubscriptExprClass: {
16037 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Val: expr);
16038 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getIdx(), ASE,
16039 AllowOnePastEnd: AllowOnePastEnd > 0);
16040 expr = ASE->getBase();
16041 break;
16042 }
16043 case Stmt::MemberExprClass: {
16044 expr = cast<MemberExpr>(Val: expr)->getBase();
16045 break;
16046 }
16047 case Stmt::CXXMemberCallExprClass: {
16048 expr = cast<CXXMemberCallExpr>(Val: expr)->getImplicitObjectArgument();
16049 break;
16050 }
16051 case Stmt::ArraySectionExprClass: {
16052 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(Val: expr);
16053 // FIXME: We should probably be checking all of the elements to the
16054 // 'length' here as well.
16055 if (ASE->getLowerBound())
16056 CheckArrayAccess(BaseExpr: ASE->getBase(), IndexExpr: ASE->getLowerBound(),
16057 /*ASE=*/nullptr, AllowOnePastEnd: AllowOnePastEnd > 0);
16058 return;
16059 }
16060 case Stmt::UnaryOperatorClass: {
16061 // Only unwrap the * and & unary operators
16062 const UnaryOperator *UO = cast<UnaryOperator>(Val: expr);
16063 expr = UO->getSubExpr();
16064 switch (UO->getOpcode()) {
16065 case UO_AddrOf:
16066 AllowOnePastEnd++;
16067 break;
16068 case UO_Deref:
16069 AllowOnePastEnd--;
16070 break;
16071 default:
16072 return;
16073 }
16074 break;
16075 }
16076 case Stmt::ConditionalOperatorClass: {
16077 const ConditionalOperator *cond = cast<ConditionalOperator>(Val: expr);
16078 if (const Expr *lhs = cond->getLHS())
16079 CheckArrayAccess(expr: lhs);
16080 if (const Expr *rhs = cond->getRHS())
16081 CheckArrayAccess(expr: rhs);
16082 return;
16083 }
16084 case Stmt::CXXOperatorCallExprClass: {
16085 const auto *OCE = cast<CXXOperatorCallExpr>(Val: expr);
16086 for (const auto *Arg : OCE->arguments())
16087 CheckArrayAccess(expr: Arg);
16088 return;
16089 }
16090 default:
16091 return;
16092 }
16093 }
16094}
16095
16096static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
16097 Expr *RHS, bool isProperty) {
16098 // Check if RHS is an Objective-C object literal, which also can get
16099 // immediately zapped in a weak reference. Note that we explicitly
16100 // allow ObjCStringLiterals, since those are designed to never really die.
16101 RHS = RHS->IgnoreParenImpCasts();
16102
16103 // This enum needs to match with the 'select' in
16104 // warn_objc_arc_literal_assign (off-by-1).
16105 SemaObjC::ObjCLiteralKind Kind = S.ObjC().CheckLiteralKind(FromE: RHS);
16106 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None)
16107 return false;
16108
16109 S.Diag(Loc, DiagID: diag::warn_arc_literal_assign)
16110 << (unsigned) Kind
16111 << (isProperty ? 0 : 1)
16112 << RHS->getSourceRange();
16113
16114 return true;
16115}
16116
16117static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
16118 Qualifiers::ObjCLifetime LT,
16119 Expr *RHS, bool isProperty) {
16120 // Strip off any implicit cast added to get to the one ARC-specific.
16121 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
16122 if (cast->getCastKind() == CK_ARCConsumeObject) {
16123 S.Diag(Loc, DiagID: diag::warn_arc_retained_assign)
16124 << (LT == Qualifiers::OCL_ExplicitNone)
16125 << (isProperty ? 0 : 1)
16126 << RHS->getSourceRange();
16127 return true;
16128 }
16129 RHS = cast->getSubExpr();
16130 }
16131
16132 if (LT == Qualifiers::OCL_Weak &&
16133 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
16134 return true;
16135
16136 return false;
16137}
16138
16139bool Sema::checkUnsafeAssigns(SourceLocation Loc,
16140 QualType LHS, Expr *RHS) {
16141 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
16142
16143 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
16144 return false;
16145
16146 if (checkUnsafeAssignObject(S&: *this, Loc, LT, RHS, isProperty: false))
16147 return true;
16148
16149 return false;
16150}
16151
16152void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
16153 Expr *LHS, Expr *RHS) {
16154 QualType LHSType;
16155 // PropertyRef on LHS type need be directly obtained from
16156 // its declaration as it has a PseudoType.
16157 ObjCPropertyRefExpr *PRE
16158 = dyn_cast<ObjCPropertyRefExpr>(Val: LHS->IgnoreParens());
16159 if (PRE && !PRE->isImplicitProperty()) {
16160 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16161 if (PD)
16162 LHSType = PD->getType();
16163 }
16164
16165 if (LHSType.isNull())
16166 LHSType = LHS->getType();
16167
16168 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
16169
16170 if (LT == Qualifiers::OCL_Weak) {
16171 if (!Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc))
16172 getCurFunction()->markSafeWeakUse(E: LHS);
16173 }
16174
16175 if (checkUnsafeAssigns(Loc, LHS: LHSType, RHS))
16176 return;
16177
16178 // FIXME. Check for other life times.
16179 if (LT != Qualifiers::OCL_None)
16180 return;
16181
16182 if (PRE) {
16183 if (PRE->isImplicitProperty())
16184 return;
16185 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
16186 if (!PD)
16187 return;
16188
16189 unsigned Attributes = PD->getPropertyAttributes();
16190 if (Attributes & ObjCPropertyAttribute::kind_assign) {
16191 // when 'assign' attribute was not explicitly specified
16192 // by user, ignore it and rely on property type itself
16193 // for lifetime info.
16194 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
16195 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
16196 LHSType->isObjCRetainableType())
16197 return;
16198
16199 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(Val: RHS)) {
16200 if (cast->getCastKind() == CK_ARCConsumeObject) {
16201 Diag(Loc, DiagID: diag::warn_arc_retained_property_assign)
16202 << RHS->getSourceRange();
16203 return;
16204 }
16205 RHS = cast->getSubExpr();
16206 }
16207 } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
16208 if (checkUnsafeAssignObject(S&: *this, Loc, LT: Qualifiers::OCL_Weak, RHS, isProperty: true))
16209 return;
16210 }
16211 }
16212}
16213
16214//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
16215
16216static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
16217 SourceLocation StmtLoc,
16218 const NullStmt *Body) {
16219 // Do not warn if the body is a macro that expands to nothing, e.g:
16220 //
16221 // #define CALL(x)
16222 // if (condition)
16223 // CALL(0);
16224 if (Body->hasLeadingEmptyMacro())
16225 return false;
16226
16227 // Get line numbers of statement and body.
16228 bool StmtLineInvalid;
16229 unsigned StmtLine = SourceMgr.getPresumedLineNumber(Loc: StmtLoc,
16230 Invalid: &StmtLineInvalid);
16231 if (StmtLineInvalid)
16232 return false;
16233
16234 bool BodyLineInvalid;
16235 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Loc: Body->getSemiLoc(),
16236 Invalid: &BodyLineInvalid);
16237 if (BodyLineInvalid)
16238 return false;
16239
16240 // Warn if null statement and body are on the same line.
16241 if (StmtLine != BodyLine)
16242 return false;
16243
16244 return true;
16245}
16246
16247void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
16248 const Stmt *Body,
16249 unsigned DiagID) {
16250 // Since this is a syntactic check, don't emit diagnostic for template
16251 // instantiations, this just adds noise.
16252 if (CurrentInstantiationScope)
16253 return;
16254
16255 // The body should be a null statement.
16256 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
16257 if (!NBody)
16258 return;
16259
16260 // Do the usual checks.
16261 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
16262 return;
16263
16264 Diag(Loc: NBody->getSemiLoc(), DiagID);
16265 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
16266}
16267
16268void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
16269 const Stmt *PossibleBody) {
16270 assert(!CurrentInstantiationScope); // Ensured by caller
16271
16272 SourceLocation StmtLoc;
16273 const Stmt *Body;
16274 unsigned DiagID;
16275 if (const ForStmt *FS = dyn_cast<ForStmt>(Val: S)) {
16276 StmtLoc = FS->getRParenLoc();
16277 Body = FS->getBody();
16278 DiagID = diag::warn_empty_for_body;
16279 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Val: S)) {
16280 StmtLoc = WS->getRParenLoc();
16281 Body = WS->getBody();
16282 DiagID = diag::warn_empty_while_body;
16283 } else
16284 return; // Neither `for' nor `while'.
16285
16286 // The body should be a null statement.
16287 const NullStmt *NBody = dyn_cast<NullStmt>(Val: Body);
16288 if (!NBody)
16289 return;
16290
16291 // Skip expensive checks if diagnostic is disabled.
16292 if (Diags.isIgnored(DiagID, Loc: NBody->getSemiLoc()))
16293 return;
16294
16295 // Do the usual checks.
16296 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, Body: NBody))
16297 return;
16298
16299 // `for(...);' and `while(...);' are popular idioms, so in order to keep
16300 // noise level low, emit diagnostics only if for/while is followed by a
16301 // CompoundStmt, e.g.:
16302 // for (int i = 0; i < n; i++);
16303 // {
16304 // a(i);
16305 // }
16306 // or if for/while is followed by a statement with more indentation
16307 // than for/while itself:
16308 // for (int i = 0; i < n; i++);
16309 // a(i);
16310 bool ProbableTypo = isa<CompoundStmt>(Val: PossibleBody);
16311 if (!ProbableTypo) {
16312 bool BodyColInvalid;
16313 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
16314 Loc: PossibleBody->getBeginLoc(), Invalid: &BodyColInvalid);
16315 if (BodyColInvalid)
16316 return;
16317
16318 bool StmtColInvalid;
16319 unsigned StmtCol =
16320 SourceMgr.getPresumedColumnNumber(Loc: S->getBeginLoc(), Invalid: &StmtColInvalid);
16321 if (StmtColInvalid)
16322 return;
16323
16324 if (BodyCol > StmtCol)
16325 ProbableTypo = true;
16326 }
16327
16328 if (ProbableTypo) {
16329 Diag(Loc: NBody->getSemiLoc(), DiagID);
16330 Diag(Loc: NBody->getSemiLoc(), DiagID: diag::note_empty_body_on_separate_line);
16331 }
16332}
16333
16334//===--- CHECK: Warn on self move with std::move. -------------------------===//
16335
16336void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16337 SourceLocation OpLoc) {
16338 if (Diags.isIgnored(DiagID: diag::warn_sizeof_pointer_expr_memaccess, Loc: OpLoc))
16339 return;
16340
16341 if (inTemplateInstantiation())
16342 return;
16343
16344 // Strip parens and casts away.
16345 LHSExpr = LHSExpr->IgnoreParenImpCasts();
16346 RHSExpr = RHSExpr->IgnoreParenImpCasts();
16347
16348 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue
16349 // which we can treat as an inlined std::move
16350 if (const auto *CE = dyn_cast<CallExpr>(Val: RHSExpr);
16351 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove())
16352 RHSExpr = CE->getArg(Arg: 0);
16353 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(Val: RHSExpr);
16354 CXXSCE && CXXSCE->isXValue())
16355 RHSExpr = CXXSCE->getSubExpr();
16356 else
16357 return;
16358
16359 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSExpr);
16360 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSExpr);
16361
16362 // Two DeclRefExpr's, check that the decls are the same.
16363 if (LHSDeclRef && RHSDeclRef) {
16364 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16365 return;
16366 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16367 RHSDeclRef->getDecl()->getCanonicalDecl())
16368 return;
16369
16370 auto D = Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16371 << LHSExpr->getType() << LHSExpr->getSourceRange()
16372 << RHSExpr->getSourceRange();
16373 if (const FieldDecl *F =
16374 getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDeclRef->getDecl()))
16375 D << 1 << F
16376 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "this->");
16377 else
16378 D << 0;
16379 return;
16380 }
16381
16382 // Member variables require a different approach to check for self moves.
16383 // MemberExpr's are the same if every nested MemberExpr refers to the same
16384 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16385 // the base Expr's are CXXThisExpr's.
16386 const Expr *LHSBase = LHSExpr;
16387 const Expr *RHSBase = RHSExpr;
16388 const MemberExpr *LHSME = dyn_cast<MemberExpr>(Val: LHSExpr);
16389 const MemberExpr *RHSME = dyn_cast<MemberExpr>(Val: RHSExpr);
16390 if (!LHSME || !RHSME)
16391 return;
16392
16393 while (LHSME && RHSME) {
16394 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16395 RHSME->getMemberDecl()->getCanonicalDecl())
16396 return;
16397
16398 LHSBase = LHSME->getBase();
16399 RHSBase = RHSME->getBase();
16400 LHSME = dyn_cast<MemberExpr>(Val: LHSBase);
16401 RHSME = dyn_cast<MemberExpr>(Val: RHSBase);
16402 }
16403
16404 LHSDeclRef = dyn_cast<DeclRefExpr>(Val: LHSBase);
16405 RHSDeclRef = dyn_cast<DeclRefExpr>(Val: RHSBase);
16406 if (LHSDeclRef && RHSDeclRef) {
16407 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16408 return;
16409 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16410 RHSDeclRef->getDecl()->getCanonicalDecl())
16411 return;
16412
16413 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16414 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16415 << RHSExpr->getSourceRange();
16416 return;
16417 }
16418
16419 if (isa<CXXThisExpr>(Val: LHSBase) && isa<CXXThisExpr>(Val: RHSBase))
16420 Diag(Loc: OpLoc, DiagID: diag::warn_self_move)
16421 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange()
16422 << RHSExpr->getSourceRange();
16423}
16424
16425//===--- Layout compatibility ----------------------------------------------//
16426
16427static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2);
16428
16429/// Check if two enumeration types are layout-compatible.
16430static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1,
16431 const EnumDecl *ED2) {
16432 // C++11 [dcl.enum] p8:
16433 // Two enumeration types are layout-compatible if they have the same
16434 // underlying type.
16435 return ED1->isComplete() && ED2->isComplete() &&
16436 C.hasSameType(T1: ED1->getIntegerType(), T2: ED2->getIntegerType());
16437}
16438
16439/// Check if two fields are layout-compatible.
16440/// Can be used on union members, which are exempt from alignment requirement
16441/// of common initial sequence.
16442static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1,
16443 const FieldDecl *Field2,
16444 bool AreUnionMembers = false) {
16445#ifndef NDEBUG
16446 CanQualType Field1Parent = C.getCanonicalTagType(Field1->getParent());
16447 CanQualType Field2Parent = C.getCanonicalTagType(Field2->getParent());
16448 assert(((Field1Parent->isStructureOrClassType() &&
16449 Field2Parent->isStructureOrClassType()) ||
16450 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16451 "Can't evaluate layout compatibility between a struct field and a "
16452 "union field.");
16453 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16454 (AreUnionMembers && Field1Parent->isUnionType())) &&
16455 "AreUnionMembers should be 'true' for union fields (only).");
16456#endif
16457
16458 if (!isLayoutCompatible(C, T1: Field1->getType(), T2: Field2->getType()))
16459 return false;
16460
16461 if (Field1->isBitField() != Field2->isBitField())
16462 return false;
16463
16464 if (Field1->isBitField()) {
16465 // Make sure that the bit-fields are the same length.
16466 unsigned Bits1 = Field1->getBitWidthValue();
16467 unsigned Bits2 = Field2->getBitWidthValue();
16468
16469 if (Bits1 != Bits2)
16470 return false;
16471 }
16472
16473 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() ||
16474 Field2->hasAttr<clang::NoUniqueAddressAttr>())
16475 return false;
16476
16477 if (!AreUnionMembers &&
16478 Field1->getMaxAlignment() != Field2->getMaxAlignment())
16479 return false;
16480
16481 return true;
16482}
16483
16484/// Check if two standard-layout structs are layout-compatible.
16485/// (C++11 [class.mem] p17)
16486static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1,
16487 const RecordDecl *RD2) {
16488 // Get to the class where the fields are declared
16489 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(Val: RD1))
16490 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16491
16492 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(Val: RD2))
16493 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16494
16495 // Check the fields.
16496 return llvm::equal(LRange: RD1->fields(), RRange: RD2->fields(),
16497 P: [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool {
16498 return isLayoutCompatible(C, Field1: F1, Field2: F2);
16499 });
16500}
16501
16502/// Check if two standard-layout unions are layout-compatible.
16503/// (C++11 [class.mem] p18)
16504static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1,
16505 const RecordDecl *RD2) {
16506 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields(llvm::from_range,
16507 RD2->fields());
16508
16509 for (auto *Field1 : RD1->fields()) {
16510 auto I = UnmatchedFields.begin();
16511 auto E = UnmatchedFields.end();
16512
16513 for ( ; I != E; ++I) {
16514 if (isLayoutCompatible(C, Field1, Field2: *I, /*IsUnionMember=*/AreUnionMembers: true)) {
16515 bool Result = UnmatchedFields.erase(Ptr: *I);
16516 (void) Result;
16517 assert(Result);
16518 break;
16519 }
16520 }
16521 if (I == E)
16522 return false;
16523 }
16524
16525 return UnmatchedFields.empty();
16526}
16527
16528static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1,
16529 const RecordDecl *RD2) {
16530 if (RD1->isUnion() != RD2->isUnion())
16531 return false;
16532
16533 if (RD1->isUnion())
16534 return isLayoutCompatibleUnion(C, RD1, RD2);
16535 else
16536 return isLayoutCompatibleStruct(C, RD1, RD2);
16537}
16538
16539/// Check if two types are layout-compatible in C++11 sense.
16540static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) {
16541 if (T1.isNull() || T2.isNull())
16542 return false;
16543
16544 // C++20 [basic.types] p11:
16545 // Two types cv1 T1 and cv2 T2 are layout-compatible types
16546 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1),
16547 // or layout-compatible standard-layout class types (11.4).
16548 T1 = T1.getCanonicalType().getUnqualifiedType();
16549 T2 = T2.getCanonicalType().getUnqualifiedType();
16550
16551 if (C.hasSameType(T1, T2))
16552 return true;
16553
16554 const Type::TypeClass TC1 = T1->getTypeClass();
16555 const Type::TypeClass TC2 = T2->getTypeClass();
16556
16557 if (TC1 != TC2)
16558 return false;
16559
16560 if (TC1 == Type::Enum)
16561 return isLayoutCompatible(C, ED1: T1->castAsEnumDecl(), ED2: T2->castAsEnumDecl());
16562 if (TC1 == Type::Record) {
16563 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16564 return false;
16565
16566 return isLayoutCompatible(C, RD1: T1->castAsRecordDecl(),
16567 RD2: T2->castAsRecordDecl());
16568 }
16569
16570 return false;
16571}
16572
16573bool Sema::IsLayoutCompatible(QualType T1, QualType T2) const {
16574 return isLayoutCompatible(C: getASTContext(), T1, T2);
16575}
16576
16577//===-------------- Pointer interconvertibility ----------------------------//
16578
16579bool Sema::IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base,
16580 const TypeSourceInfo *Derived) {
16581 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified();
16582 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified();
16583
16584 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() &&
16585 getASTContext().hasSameType(T1: BaseT, T2: DerivedT))
16586 return true;
16587
16588 if (!IsDerivedFrom(Loc: Derived->getTypeLoc().getBeginLoc(), Derived: DerivedT, Base: BaseT))
16589 return false;
16590
16591 // Per [basic.compound]/4.3, containing object has to be standard-layout.
16592 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout())
16593 return true;
16594
16595 return false;
16596}
16597
16598//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16599
16600/// Given a type tag expression find the type tag itself.
16601///
16602/// \param TypeExpr Type tag expression, as it appears in user's code.
16603///
16604/// \param VD Declaration of an identifier that appears in a type tag.
16605///
16606/// \param MagicValue Type tag magic value.
16607///
16608/// \param isConstantEvaluated whether the evalaution should be performed in
16609
16610/// constant context.
16611static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16612 const ValueDecl **VD, uint64_t *MagicValue,
16613 bool isConstantEvaluated) {
16614 while(true) {
16615 if (!TypeExpr)
16616 return false;
16617
16618 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16619
16620 switch (TypeExpr->getStmtClass()) {
16621 case Stmt::UnaryOperatorClass: {
16622 const UnaryOperator *UO = cast<UnaryOperator>(Val: TypeExpr);
16623 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16624 TypeExpr = UO->getSubExpr();
16625 continue;
16626 }
16627 return false;
16628 }
16629
16630 case Stmt::DeclRefExprClass: {
16631 const DeclRefExpr *DRE = cast<DeclRefExpr>(Val: TypeExpr);
16632 *VD = DRE->getDecl();
16633 return true;
16634 }
16635
16636 case Stmt::IntegerLiteralClass: {
16637 const IntegerLiteral *IL = cast<IntegerLiteral>(Val: TypeExpr);
16638 llvm::APInt MagicValueAPInt = IL->getValue();
16639 if (MagicValueAPInt.getActiveBits() <= 64) {
16640 *MagicValue = MagicValueAPInt.getZExtValue();
16641 return true;
16642 } else
16643 return false;
16644 }
16645
16646 case Stmt::BinaryConditionalOperatorClass:
16647 case Stmt::ConditionalOperatorClass: {
16648 const AbstractConditionalOperator *ACO =
16649 cast<AbstractConditionalOperator>(Val: TypeExpr);
16650 bool Result;
16651 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16652 InConstantContext: isConstantEvaluated)) {
16653 if (Result)
16654 TypeExpr = ACO->getTrueExpr();
16655 else
16656 TypeExpr = ACO->getFalseExpr();
16657 continue;
16658 }
16659 return false;
16660 }
16661
16662 case Stmt::BinaryOperatorClass: {
16663 const BinaryOperator *BO = cast<BinaryOperator>(Val: TypeExpr);
16664 if (BO->getOpcode() == BO_Comma) {
16665 TypeExpr = BO->getRHS();
16666 continue;
16667 }
16668 return false;
16669 }
16670
16671 default:
16672 return false;
16673 }
16674 }
16675}
16676
16677/// Retrieve the C type corresponding to type tag TypeExpr.
16678///
16679/// \param TypeExpr Expression that specifies a type tag.
16680///
16681/// \param MagicValues Registered magic values.
16682///
16683/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16684/// kind.
16685///
16686/// \param TypeInfo Information about the corresponding C type.
16687///
16688/// \param isConstantEvaluated whether the evalaution should be performed in
16689/// constant context.
16690///
16691/// \returns true if the corresponding C type was found.
16692static bool GetMatchingCType(
16693 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16694 const ASTContext &Ctx,
16695 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16696 *MagicValues,
16697 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16698 bool isConstantEvaluated) {
16699 FoundWrongKind = false;
16700
16701 // Variable declaration that has type_tag_for_datatype attribute.
16702 const ValueDecl *VD = nullptr;
16703
16704 uint64_t MagicValue;
16705
16706 if (!FindTypeTagExpr(TypeExpr, Ctx, VD: &VD, MagicValue: &MagicValue, isConstantEvaluated))
16707 return false;
16708
16709 if (VD) {
16710 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16711 if (I->getArgumentKind() != ArgumentKind) {
16712 FoundWrongKind = true;
16713 return false;
16714 }
16715 TypeInfo.Type = I->getMatchingCType();
16716 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16717 TypeInfo.MustBeNull = I->getMustBeNull();
16718 return true;
16719 }
16720 return false;
16721 }
16722
16723 if (!MagicValues)
16724 return false;
16725
16726 llvm::DenseMap<Sema::TypeTagMagicValue,
16727 Sema::TypeTagData>::const_iterator I =
16728 MagicValues->find(Val: std::make_pair(x&: ArgumentKind, y&: MagicValue));
16729 if (I == MagicValues->end())
16730 return false;
16731
16732 TypeInfo = I->second;
16733 return true;
16734}
16735
16736void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16737 uint64_t MagicValue, QualType Type,
16738 bool LayoutCompatible,
16739 bool MustBeNull) {
16740 if (!TypeTagForDatatypeMagicValues)
16741 TypeTagForDatatypeMagicValues.reset(
16742 p: new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16743
16744 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16745 (*TypeTagForDatatypeMagicValues)[Magic] =
16746 TypeTagData(Type, LayoutCompatible, MustBeNull);
16747}
16748
16749static bool IsSameCharType(QualType T1, QualType T2) {
16750 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16751 if (!BT1)
16752 return false;
16753
16754 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16755 if (!BT2)
16756 return false;
16757
16758 BuiltinType::Kind T1Kind = BT1->getKind();
16759 BuiltinType::Kind T2Kind = BT2->getKind();
16760
16761 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
16762 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
16763 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16764 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16765}
16766
16767void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16768 const ArrayRef<const Expr *> ExprArgs,
16769 SourceLocation CallSiteLoc) {
16770 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16771 bool IsPointerAttr = Attr->getIsPointer();
16772
16773 // Retrieve the argument representing the 'type_tag'.
16774 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16775 if (TypeTagIdxAST >= ExprArgs.size()) {
16776 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
16777 << 0 << Attr->getTypeTagIdx().getSourceIndex();
16778 return;
16779 }
16780 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16781 bool FoundWrongKind;
16782 TypeTagData TypeInfo;
16783 if (!GetMatchingCType(ArgumentKind, TypeExpr: TypeTagExpr, Ctx: Context,
16784 MagicValues: TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16785 TypeInfo, isConstantEvaluated: isConstantEvaluatedContext())) {
16786 if (FoundWrongKind)
16787 Diag(Loc: TypeTagExpr->getExprLoc(),
16788 DiagID: diag::warn_type_tag_for_datatype_wrong_kind)
16789 << TypeTagExpr->getSourceRange();
16790 return;
16791 }
16792
16793 // Retrieve the argument representing the 'arg_idx'.
16794 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16795 if (ArgumentIdxAST >= ExprArgs.size()) {
16796 Diag(Loc: CallSiteLoc, DiagID: diag::err_tag_index_out_of_range)
16797 << 1 << Attr->getArgumentIdx().getSourceIndex();
16798 return;
16799 }
16800 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16801 if (IsPointerAttr) {
16802 // Skip implicit cast of pointer to `void *' (as a function argument).
16803 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgumentExpr))
16804 if (ICE->getType()->isVoidPointerType() &&
16805 ICE->getCastKind() == CK_BitCast)
16806 ArgumentExpr = ICE->getSubExpr();
16807 }
16808 QualType ArgumentType = ArgumentExpr->getType();
16809
16810 // Passing a `void*' pointer shouldn't trigger a warning.
16811 if (IsPointerAttr && ArgumentType->isVoidPointerType())
16812 return;
16813
16814 if (TypeInfo.MustBeNull) {
16815 // Type tag with matching void type requires a null pointer.
16816 if (!ArgumentExpr->isNullPointerConstant(Ctx&: Context,
16817 NPC: Expr::NPC_ValueDependentIsNotNull)) {
16818 Diag(Loc: ArgumentExpr->getExprLoc(),
16819 DiagID: diag::warn_type_safety_null_pointer_required)
16820 << ArgumentKind->getName()
16821 << ArgumentExpr->getSourceRange()
16822 << TypeTagExpr->getSourceRange();
16823 }
16824 return;
16825 }
16826
16827 QualType RequiredType = TypeInfo.Type;
16828 if (IsPointerAttr)
16829 RequiredType = Context.getPointerType(T: RequiredType);
16830
16831 bool mismatch = false;
16832 if (!TypeInfo.LayoutCompatible) {
16833 mismatch = !Context.hasSameType(T1: ArgumentType, T2: RequiredType);
16834
16835 // C++11 [basic.fundamental] p1:
16836 // Plain char, signed char, and unsigned char are three distinct types.
16837 //
16838 // But we treat plain `char' as equivalent to `signed char' or `unsigned
16839 // char' depending on the current char signedness mode.
16840 if (mismatch)
16841 if ((IsPointerAttr && IsSameCharType(T1: ArgumentType->getPointeeType(),
16842 T2: RequiredType->getPointeeType())) ||
16843 (!IsPointerAttr && IsSameCharType(T1: ArgumentType, T2: RequiredType)))
16844 mismatch = false;
16845 } else
16846 if (IsPointerAttr)
16847 mismatch = !isLayoutCompatible(C: Context,
16848 T1: ArgumentType->getPointeeType(),
16849 T2: RequiredType->getPointeeType());
16850 else
16851 mismatch = !isLayoutCompatible(C: Context, T1: ArgumentType, T2: RequiredType);
16852
16853 if (mismatch)
16854 Diag(Loc: ArgumentExpr->getExprLoc(), DiagID: diag::warn_type_safety_type_mismatch)
16855 << ArgumentType << ArgumentKind
16856 << TypeInfo.LayoutCompatible << RequiredType
16857 << ArgumentExpr->getSourceRange()
16858 << TypeTagExpr->getSourceRange();
16859}
16860
16861void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16862 CharUnits Alignment) {
16863 currentEvaluationContext().MisalignedMembers.emplace_back(Args&: E, Args&: RD, Args&: MD,
16864 Args&: Alignment);
16865}
16866
16867void Sema::DiagnoseMisalignedMembers() {
16868 for (MisalignedMember &m : currentEvaluationContext().MisalignedMembers) {
16869 const NamedDecl *ND = m.RD;
16870 if (ND->getName().empty()) {
16871 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16872 ND = TD;
16873 }
16874 Diag(Loc: m.E->getBeginLoc(), DiagID: diag::warn_taking_address_of_packed_member)
16875 << m.MD << ND << m.E->getSourceRange();
16876 }
16877 currentEvaluationContext().MisalignedMembers.clear();
16878}
16879
16880void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16881 E = E->IgnoreParens();
16882 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType())
16883 return;
16884 if (isa<UnaryOperator>(Val: E) &&
16885 cast<UnaryOperator>(Val: E)->getOpcode() == UO_AddrOf) {
16886 auto *Op = cast<UnaryOperator>(Val: E)->getSubExpr()->IgnoreParens();
16887 if (isa<MemberExpr>(Val: Op)) {
16888 auto &MisalignedMembersForExpr =
16889 currentEvaluationContext().MisalignedMembers;
16890 auto *MA = llvm::find(Range&: MisalignedMembersForExpr, Val: MisalignedMember(Op));
16891 if (MA != MisalignedMembersForExpr.end() &&
16892 (T->isDependentType() || T->isIntegerType() ||
16893 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16894 Context.getTypeAlignInChars(
16895 T: T->getPointeeType()) <= MA->Alignment))))
16896 MisalignedMembersForExpr.erase(CI: MA);
16897 }
16898 }
16899}
16900
16901void Sema::RefersToMemberWithReducedAlignment(
16902 Expr *E,
16903 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16904 Action) {
16905 const auto *ME = dyn_cast<MemberExpr>(Val: E);
16906 if (!ME)
16907 return;
16908
16909 // No need to check expressions with an __unaligned-qualified type.
16910 if (E->getType().getQualifiers().hasUnaligned())
16911 return;
16912
16913 // For a chain of MemberExpr like "a.b.c.d" this list
16914 // will keep FieldDecl's like [d, c, b].
16915 SmallVector<FieldDecl *, 4> ReverseMemberChain;
16916 const MemberExpr *TopME = nullptr;
16917 bool AnyIsPacked = false;
16918 do {
16919 QualType BaseType = ME->getBase()->getType();
16920 if (BaseType->isDependentType())
16921 return;
16922 if (ME->isArrow())
16923 BaseType = BaseType->getPointeeType();
16924 auto *RD = BaseType->castAsRecordDecl();
16925 if (RD->isInvalidDecl())
16926 return;
16927
16928 ValueDecl *MD = ME->getMemberDecl();
16929 auto *FD = dyn_cast<FieldDecl>(Val: MD);
16930 // We do not care about non-data members.
16931 if (!FD || FD->isInvalidDecl())
16932 return;
16933
16934 AnyIsPacked =
16935 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16936 ReverseMemberChain.push_back(Elt: FD);
16937
16938 TopME = ME;
16939 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParens());
16940 } while (ME);
16941 assert(TopME && "We did not compute a topmost MemberExpr!");
16942
16943 // Not the scope of this diagnostic.
16944 if (!AnyIsPacked)
16945 return;
16946
16947 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16948 const auto *DRE = dyn_cast<DeclRefExpr>(Val: TopBase);
16949 // TODO: The innermost base of the member expression may be too complicated.
16950 // For now, just disregard these cases. This is left for future
16951 // improvement.
16952 if (!DRE && !isa<CXXThisExpr>(Val: TopBase))
16953 return;
16954
16955 // Alignment expected by the whole expression.
16956 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(T: E->getType());
16957
16958 // No need to do anything else with this case.
16959 if (ExpectedAlignment.isOne())
16960 return;
16961
16962 // Synthesize offset of the whole access.
16963 CharUnits Offset;
16964 for (const FieldDecl *FD : llvm::reverse(C&: ReverseMemberChain))
16965 Offset += Context.toCharUnitsFromBits(BitSize: Context.getFieldOffset(FD));
16966
16967 // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16968 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16969 T: Context.getCanonicalTagType(TD: ReverseMemberChain.back()->getParent()));
16970
16971 // The base expression of the innermost MemberExpr may give
16972 // stronger guarantees than the class containing the member.
16973 if (DRE && !TopME->isArrow()) {
16974 const ValueDecl *VD = DRE->getDecl();
16975 if (!VD->getType()->isReferenceType())
16976 CompleteObjectAlignment =
16977 std::max(a: CompleteObjectAlignment, b: Context.getDeclAlign(D: VD));
16978 }
16979
16980 // Check if the synthesized offset fulfills the alignment.
16981 if (!Offset.isMultipleOf(N: ExpectedAlignment) ||
16982 // It may fulfill the offset it but the effective alignment may still be
16983 // lower than the expected expression alignment.
16984 CompleteObjectAlignment < ExpectedAlignment) {
16985 // If this happens, we want to determine a sensible culprit of this.
16986 // Intuitively, watching the chain of member expressions from right to
16987 // left, we start with the required alignment (as required by the field
16988 // type) but some packed attribute in that chain has reduced the alignment.
16989 // It may happen that another packed structure increases it again. But if
16990 // we are here such increase has not been enough. So pointing the first
16991 // FieldDecl that either is packed or else its RecordDecl is,
16992 // seems reasonable.
16993 FieldDecl *FD = nullptr;
16994 CharUnits Alignment;
16995 for (FieldDecl *FDI : ReverseMemberChain) {
16996 if (FDI->hasAttr<PackedAttr>() ||
16997 FDI->getParent()->hasAttr<PackedAttr>()) {
16998 FD = FDI;
16999 Alignment = std::min(a: Context.getTypeAlignInChars(T: FD->getType()),
17000 b: Context.getTypeAlignInChars(
17001 T: Context.getCanonicalTagType(TD: FD->getParent())));
17002 break;
17003 }
17004 }
17005 assert(FD && "We did not find a packed FieldDecl!");
17006 Action(E, FD->getParent(), FD, Alignment);
17007 }
17008}
17009
17010void Sema::CheckAddressOfPackedMember(Expr *rhs) {
17011 using namespace std::placeholders;
17012
17013 RefersToMemberWithReducedAlignment(
17014 E: rhs, Action: std::bind(f: &Sema::AddPotentialMisalignedMembers, args: std::ref(t&: *this), args: _1,
17015 args: _2, args: _3, args: _4));
17016}
17017
17018bool Sema::PrepareBuiltinElementwiseMathOneArgCall(
17019 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17020 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17021 return true;
17022
17023 ExprResult A = BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: 0));
17024 if (A.isInvalid())
17025 return true;
17026
17027 TheCall->setArg(Arg: 0, ArgExpr: A.get());
17028 QualType TyA = A.get()->getType();
17029
17030 if (checkMathBuiltinElementType(S&: *this, Loc: A.get()->getBeginLoc(), ArgTy: TyA,
17031 ArgTyRestr, ArgOrdinal: 1))
17032 return true;
17033
17034 TheCall->setType(TyA);
17035 return false;
17036}
17037
17038bool Sema::BuiltinElementwiseMath(CallExpr *TheCall,
17039 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17040 if (auto Res = BuiltinVectorMath(TheCall, ArgTyRestr); Res.has_value()) {
17041 TheCall->setType(*Res);
17042 return false;
17043 }
17044 return true;
17045}
17046
17047bool Sema::BuiltinVectorToScalarMath(CallExpr *TheCall) {
17048 std::optional<QualType> Res = BuiltinVectorMath(TheCall);
17049 if (!Res)
17050 return true;
17051
17052 if (auto *VecTy0 = (*Res)->getAs<VectorType>())
17053 TheCall->setType(VecTy0->getElementType());
17054 else
17055 TheCall->setType(*Res);
17056
17057 return false;
17058}
17059
17060static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS,
17061 SourceLocation Loc) {
17062 QualType L = LHS->getEnumCoercedType(Ctx: S.Context),
17063 R = RHS->getEnumCoercedType(Ctx: S.Context);
17064 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() &&
17065 !S.Context.hasSameUnqualifiedType(T1: L, T2: R)) {
17066 return S.Diag(Loc, DiagID: diag::err_conv_mixed_enum_types)
17067 << LHS->getSourceRange() << RHS->getSourceRange()
17068 << /*Arithmetic Between*/ 0 << L << R;
17069 }
17070 return false;
17071}
17072
17073/// Check if all arguments have the same type. If the types don't match, emit an
17074/// error message and return true. Otherwise return false.
17075///
17076/// For scalars we directly compare their unqualified types. But even if we
17077/// compare unqualified vector types, a difference in qualifiers in the element
17078/// types can make the vector types be considered not equal. For example,
17079/// vector of 4 'const float' values vs vector of 4 'float' values.
17080/// So we compare unqualified types of their elements and number of elements.
17081static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef,
17082 ArrayRef<Expr *> Args) {
17083 assert(!Args.empty() && "Should have at least one argument.");
17084
17085 Expr *Arg0 = Args.front();
17086 QualType Ty0 = Arg0->getType();
17087
17088 auto EmitError = [&](Expr *ArgI) {
17089 SemaRef.Diag(Loc: Arg0->getBeginLoc(),
17090 DiagID: diag::err_typecheck_call_different_arg_types)
17091 << Arg0->getType() << ArgI->getType();
17092 };
17093
17094 // Compare scalar types.
17095 if (!Ty0->isVectorType()) {
17096 for (Expr *ArgI : Args.drop_front())
17097 if (!SemaRef.Context.hasSameUnqualifiedType(T1: Ty0, T2: ArgI->getType())) {
17098 EmitError(ArgI);
17099 return true;
17100 }
17101
17102 return false;
17103 }
17104
17105 // Compare vector types.
17106 const auto *Vec0 = Ty0->castAs<VectorType>();
17107 for (Expr *ArgI : Args.drop_front()) {
17108 const auto *VecI = ArgI->getType()->getAs<VectorType>();
17109 if (!VecI ||
17110 !SemaRef.Context.hasSameUnqualifiedType(T1: Vec0->getElementType(),
17111 T2: VecI->getElementType()) ||
17112 Vec0->getNumElements() != VecI->getNumElements()) {
17113 EmitError(ArgI);
17114 return true;
17115 }
17116 }
17117
17118 return false;
17119}
17120
17121std::optional<QualType>
17122Sema::BuiltinVectorMath(CallExpr *TheCall,
17123 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17124 if (checkArgCount(Call: TheCall, DesiredArgCount: 2))
17125 return std::nullopt;
17126
17127 if (checkBuiltinVectorMathMixedEnums(
17128 S&: *this, LHS: TheCall->getArg(Arg: 0), RHS: TheCall->getArg(Arg: 1), Loc: TheCall->getExprLoc()))
17129 return std::nullopt;
17130
17131 Expr *Args[2];
17132 for (int I = 0; I < 2; ++I) {
17133 ExprResult Converted =
17134 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
17135 if (Converted.isInvalid())
17136 return std::nullopt;
17137 Args[I] = Converted.get();
17138 }
17139
17140 SourceLocation LocA = Args[0]->getBeginLoc();
17141 QualType TyA = Args[0]->getType();
17142
17143 if (checkMathBuiltinElementType(S&: *this, Loc: LocA, ArgTy: TyA, ArgTyRestr, ArgOrdinal: 1))
17144 return std::nullopt;
17145
17146 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
17147 return std::nullopt;
17148
17149 TheCall->setArg(Arg: 0, ArgExpr: Args[0]);
17150 TheCall->setArg(Arg: 1, ArgExpr: Args[1]);
17151 return TyA;
17152}
17153
17154bool Sema::BuiltinElementwiseTernaryMath(
17155 CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17156 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
17157 return true;
17158
17159 SourceLocation Loc = TheCall->getExprLoc();
17160 if (checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 0),
17161 RHS: TheCall->getArg(Arg: 1), Loc) ||
17162 checkBuiltinVectorMathMixedEnums(S&: *this, LHS: TheCall->getArg(Arg: 1),
17163 RHS: TheCall->getArg(Arg: 2), Loc))
17164 return true;
17165
17166 Expr *Args[3];
17167 for (int I = 0; I < 3; ++I) {
17168 ExprResult Converted =
17169 BuiltinVectorMathConversions(S&: *this, E: TheCall->getArg(Arg: I));
17170 if (Converted.isInvalid())
17171 return true;
17172 Args[I] = Converted.get();
17173 }
17174
17175 int ArgOrdinal = 1;
17176 for (Expr *Arg : Args) {
17177 if (checkMathBuiltinElementType(S&: *this, Loc: Arg->getBeginLoc(), ArgTy: Arg->getType(),
17178 ArgTyRestr, ArgOrdinal: ArgOrdinal++))
17179 return true;
17180 }
17181
17182 if (checkBuiltinVectorMathArgTypes(SemaRef&: *this, Args))
17183 return true;
17184
17185 for (int I = 0; I < 3; ++I)
17186 TheCall->setArg(Arg: I, ArgExpr: Args[I]);
17187
17188 TheCall->setType(Args[0]->getType());
17189 return false;
17190}
17191
17192bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) {
17193 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17194 return true;
17195
17196 ExprResult A = UsualUnaryConversions(E: TheCall->getArg(Arg: 0));
17197 if (A.isInvalid())
17198 return true;
17199
17200 TheCall->setArg(Arg: 0, ArgExpr: A.get());
17201 return false;
17202}
17203
17204bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) {
17205 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17206 return true;
17207
17208 ExprResult Arg = TheCall->getArg(Arg: 0);
17209 QualType TyArg = Arg.get()->getType();
17210
17211 if (!TyArg->isBuiltinType() && !TyArg->isVectorType())
17212 return Diag(Loc: TheCall->getArg(Arg: 0)->getBeginLoc(),
17213 DiagID: diag::err_builtin_invalid_arg_type)
17214 << 1 << /* vector */ 2 << /* integer */ 1 << /* fp */ 1 << TyArg;
17215
17216 TheCall->setType(TyArg);
17217 return false;
17218}
17219
17220ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall,
17221 ExprResult CallResult) {
17222 if (checkArgCount(Call: TheCall, DesiredArgCount: 1))
17223 return ExprError();
17224
17225 ExprResult MatrixArg = DefaultLvalueConversion(E: TheCall->getArg(Arg: 0));
17226 if (MatrixArg.isInvalid())
17227 return MatrixArg;
17228 Expr *Matrix = MatrixArg.get();
17229
17230 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
17231 if (!MType) {
17232 Diag(Loc: Matrix->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17233 << 1 << /* matrix */ 3 << /* no int */ 0 << /* no fp */ 0
17234 << Matrix->getType();
17235 return ExprError();
17236 }
17237
17238 // Create returned matrix type by swapping rows and columns of the argument
17239 // matrix type.
17240 QualType ResultType = Context.getConstantMatrixType(
17241 ElementType: MType->getElementType(), NumRows: MType->getNumColumns(), NumColumns: MType->getNumRows());
17242
17243 // Change the return type to the type of the returned matrix.
17244 TheCall->setType(ResultType);
17245
17246 // Update call argument to use the possibly converted matrix argument.
17247 TheCall->setArg(Arg: 0, ArgExpr: Matrix);
17248 return CallResult;
17249}
17250
17251// Get and verify the matrix dimensions.
17252static std::optional<unsigned>
17253getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
17254 std::optional<llvm::APSInt> Value = Expr->getIntegerConstantExpr(Ctx: S.Context);
17255 if (!Value) {
17256 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_scalar_unsigned_arg)
17257 << Name;
17258 return {};
17259 }
17260 uint64_t Dim = Value->getZExtValue();
17261 if (Dim == 0 || Dim > S.Context.getLangOpts().MaxMatrixDimension) {
17262 S.Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_builtin_matrix_invalid_dimension)
17263 << Name << S.Context.getLangOpts().MaxMatrixDimension;
17264 return {};
17265 }
17266 return Dim;
17267}
17268
17269ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
17270 ExprResult CallResult) {
17271 if (!getLangOpts().MatrixTypes) {
17272 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
17273 return ExprError();
17274 }
17275
17276 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17277 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
17278 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
17279 << /*column*/ 1 << /*load*/ 0;
17280 return ExprError();
17281 }
17282
17283 if (checkArgCount(Call: TheCall, DesiredArgCount: 4))
17284 return ExprError();
17285
17286 unsigned PtrArgIdx = 0;
17287 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
17288 Expr *RowsExpr = TheCall->getArg(Arg: 1);
17289 Expr *ColumnsExpr = TheCall->getArg(Arg: 2);
17290 Expr *StrideExpr = TheCall->getArg(Arg: 3);
17291
17292 bool ArgError = false;
17293
17294 // Check pointer argument.
17295 {
17296 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
17297 if (PtrConv.isInvalid())
17298 return PtrConv;
17299 PtrExpr = PtrConv.get();
17300 TheCall->setArg(Arg: 0, ArgExpr: PtrExpr);
17301 if (PtrExpr->isTypeDependent()) {
17302 TheCall->setType(Context.DependentTy);
17303 return TheCall;
17304 }
17305 }
17306
17307 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17308 QualType ElementTy;
17309 if (!PtrTy) {
17310 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17311 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << /* no fp */ 0
17312 << PtrExpr->getType();
17313 ArgError = true;
17314 } else {
17315 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17316
17317 if (!ConstantMatrixType::isValidElementType(T: ElementTy, LangOpts: getLangOpts())) {
17318 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17319 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5
17320 << /* no fp */ 0 << PtrExpr->getType();
17321 ArgError = true;
17322 }
17323 }
17324
17325 // Apply default Lvalue conversions and convert the expression to size_t.
17326 auto ApplyArgumentConversions = [this](Expr *E) {
17327 ExprResult Conv = DefaultLvalueConversion(E);
17328 if (Conv.isInvalid())
17329 return Conv;
17330
17331 return tryConvertExprToType(E: Conv.get(), Ty: Context.getSizeType());
17332 };
17333
17334 // Apply conversion to row and column expressions.
17335 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17336 if (!RowsConv.isInvalid()) {
17337 RowsExpr = RowsConv.get();
17338 TheCall->setArg(Arg: 1, ArgExpr: RowsExpr);
17339 } else
17340 RowsExpr = nullptr;
17341
17342 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17343 if (!ColumnsConv.isInvalid()) {
17344 ColumnsExpr = ColumnsConv.get();
17345 TheCall->setArg(Arg: 2, ArgExpr: ColumnsExpr);
17346 } else
17347 ColumnsExpr = nullptr;
17348
17349 // If any part of the result matrix type is still pending, just use
17350 // Context.DependentTy, until all parts are resolved.
17351 if ((RowsExpr && RowsExpr->isTypeDependent()) ||
17352 (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
17353 TheCall->setType(Context.DependentTy);
17354 return CallResult;
17355 }
17356
17357 // Check row and column dimensions.
17358 std::optional<unsigned> MaybeRows;
17359 if (RowsExpr)
17360 MaybeRows = getAndVerifyMatrixDimension(Expr: RowsExpr, Name: "row", S&: *this);
17361
17362 std::optional<unsigned> MaybeColumns;
17363 if (ColumnsExpr)
17364 MaybeColumns = getAndVerifyMatrixDimension(Expr: ColumnsExpr, Name: "column", S&: *this);
17365
17366 // Check stride argument.
17367 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17368 if (StrideConv.isInvalid())
17369 return ExprError();
17370 StrideExpr = StrideConv.get();
17371 TheCall->setArg(Arg: 3, ArgExpr: StrideExpr);
17372
17373 if (MaybeRows) {
17374 if (std::optional<llvm::APSInt> Value =
17375 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
17376 uint64_t Stride = Value->getZExtValue();
17377 if (Stride < *MaybeRows) {
17378 Diag(Loc: StrideExpr->getBeginLoc(),
17379 DiagID: diag::err_builtin_matrix_stride_too_small);
17380 ArgError = true;
17381 }
17382 }
17383 }
17384
17385 if (ArgError || !MaybeRows || !MaybeColumns)
17386 return ExprError();
17387
17388 TheCall->setType(
17389 Context.getConstantMatrixType(ElementType: ElementTy, NumRows: *MaybeRows, NumColumns: *MaybeColumns));
17390 return CallResult;
17391}
17392
17393ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall,
17394 ExprResult CallResult) {
17395 if (!getLangOpts().MatrixTypes) {
17396 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_disabled);
17397 return ExprError();
17398 }
17399
17400 if (getLangOpts().getDefaultMatrixMemoryLayout() !=
17401 LangOptions::MatrixMemoryLayout::MatrixColMajor) {
17402 Diag(Loc: TheCall->getBeginLoc(), DiagID: diag::err_builtin_matrix_major_order_disabled)
17403 << /*column*/ 1 << /*store*/ 1;
17404 return ExprError();
17405 }
17406
17407 if (checkArgCount(Call: TheCall, DesiredArgCount: 3))
17408 return ExprError();
17409
17410 unsigned PtrArgIdx = 1;
17411 Expr *MatrixExpr = TheCall->getArg(Arg: 0);
17412 Expr *PtrExpr = TheCall->getArg(Arg: PtrArgIdx);
17413 Expr *StrideExpr = TheCall->getArg(Arg: 2);
17414
17415 bool ArgError = false;
17416
17417 {
17418 ExprResult MatrixConv = DefaultLvalueConversion(E: MatrixExpr);
17419 if (MatrixConv.isInvalid())
17420 return MatrixConv;
17421 MatrixExpr = MatrixConv.get();
17422 TheCall->setArg(Arg: 0, ArgExpr: MatrixExpr);
17423 }
17424 if (MatrixExpr->isTypeDependent()) {
17425 TheCall->setType(Context.DependentTy);
17426 return TheCall;
17427 }
17428
17429 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
17430 if (!MatrixTy) {
17431 Diag(Loc: MatrixExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17432 << 1 << /* matrix ty */ 3 << 0 << 0 << MatrixExpr->getType();
17433 ArgError = true;
17434 }
17435
17436 {
17437 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(E: PtrExpr);
17438 if (PtrConv.isInvalid())
17439 return PtrConv;
17440 PtrExpr = PtrConv.get();
17441 TheCall->setArg(Arg: 1, ArgExpr: PtrExpr);
17442 if (PtrExpr->isTypeDependent()) {
17443 TheCall->setType(Context.DependentTy);
17444 return TheCall;
17445 }
17446 }
17447
17448 // Check pointer argument.
17449 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
17450 if (!PtrTy) {
17451 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_invalid_arg_type)
17452 << PtrArgIdx + 1 << 0 << /* pointer to element ty */ 5 << 0
17453 << PtrExpr->getType();
17454 ArgError = true;
17455 } else {
17456 QualType ElementTy = PtrTy->getPointeeType();
17457 if (ElementTy.isConstQualified()) {
17458 Diag(Loc: PtrExpr->getBeginLoc(), DiagID: diag::err_builtin_matrix_store_to_const);
17459 ArgError = true;
17460 }
17461 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
17462 if (MatrixTy &&
17463 !Context.hasSameType(T1: ElementTy, T2: MatrixTy->getElementType())) {
17464 Diag(Loc: PtrExpr->getBeginLoc(),
17465 DiagID: diag::err_builtin_matrix_pointer_arg_mismatch)
17466 << ElementTy << MatrixTy->getElementType();
17467 ArgError = true;
17468 }
17469 }
17470
17471 // Apply default Lvalue conversions and convert the stride expression to
17472 // size_t.
17473 {
17474 ExprResult StrideConv = DefaultLvalueConversion(E: StrideExpr);
17475 if (StrideConv.isInvalid())
17476 return StrideConv;
17477
17478 StrideConv = tryConvertExprToType(E: StrideConv.get(), Ty: Context.getSizeType());
17479 if (StrideConv.isInvalid())
17480 return StrideConv;
17481 StrideExpr = StrideConv.get();
17482 TheCall->setArg(Arg: 2, ArgExpr: StrideExpr);
17483 }
17484
17485 // Check stride argument.
17486 if (MatrixTy) {
17487 if (std::optional<llvm::APSInt> Value =
17488 StrideExpr->getIntegerConstantExpr(Ctx: Context)) {
17489 uint64_t Stride = Value->getZExtValue();
17490 if (Stride < MatrixTy->getNumRows()) {
17491 Diag(Loc: StrideExpr->getBeginLoc(),
17492 DiagID: diag::err_builtin_matrix_stride_too_small);
17493 ArgError = true;
17494 }
17495 }
17496 }
17497
17498 if (ArgError)
17499 return ExprError();
17500
17501 return CallResult;
17502}
17503
17504void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc,
17505 const NamedDecl *Callee) {
17506 // This warning does not make sense in code that has no runtime behavior.
17507 if (isUnevaluatedContext())
17508 return;
17509
17510 const NamedDecl *Caller = getCurFunctionOrMethodDecl();
17511
17512 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>())
17513 return;
17514
17515 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17516 // all TCBs the callee is a part of.
17517 llvm::StringSet<> CalleeTCBs;
17518 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17519 CalleeTCBs.insert(key: A->getTCBName());
17520 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17521 CalleeTCBs.insert(key: A->getTCBName());
17522
17523 // Go through the TCBs the caller is a part of and emit warnings if Caller
17524 // is in a TCB that the Callee is not.
17525 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) {
17526 StringRef CallerTCB = A->getTCBName();
17527 if (CalleeTCBs.count(Key: CallerTCB) == 0) {
17528 this->Diag(Loc: CallExprLoc, DiagID: diag::warn_tcb_enforcement_violation)
17529 << Callee << CallerTCB;
17530 }
17531 }
17532}
17533