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/Attr.h" 18 #include "clang/AST/AttrIterator.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclBase.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclarationName.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/Expr.h" 27 #include "clang/AST/ExprCXX.h" 28 #include "clang/AST/ExprObjC.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/IgnoreExpr.h" 31 #include "clang/AST/NSAPI.h" 32 #include "clang/AST/NonTrivialTypeVisitor.h" 33 #include "clang/AST/OperationKinds.h" 34 #include "clang/AST/RecordLayout.h" 35 #include "clang/AST/Stmt.h" 36 #include "clang/AST/TemplateBase.h" 37 #include "clang/AST/Type.h" 38 #include "clang/AST/TypeLoc.h" 39 #include "clang/AST/UnresolvedSet.h" 40 #include "clang/Basic/AddressSpaces.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetInfo.h" 53 #include "clang/Basic/TypeTraits.h" 54 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 55 #include "clang/Sema/Initialization.h" 56 #include "clang/Sema/Lookup.h" 57 #include "clang/Sema/Ownership.h" 58 #include "clang/Sema/Scope.h" 59 #include "clang/Sema/ScopeInfo.h" 60 #include "clang/Sema/Sema.h" 61 #include "clang/Sema/SemaAMDGPU.h" 62 #include "clang/Sema/SemaARM.h" 63 #include "clang/Sema/SemaBPF.h" 64 #include "clang/Sema/SemaHLSL.h" 65 #include "clang/Sema/SemaHexagon.h" 66 #include "clang/Sema/SemaLoongArch.h" 67 #include "clang/Sema/SemaMIPS.h" 68 #include "clang/Sema/SemaNVPTX.h" 69 #include "clang/Sema/SemaObjC.h" 70 #include "clang/Sema/SemaOpenCL.h" 71 #include "clang/Sema/SemaPPC.h" 72 #include "clang/Sema/SemaRISCV.h" 73 #include "clang/Sema/SemaSPIRV.h" 74 #include "clang/Sema/SemaSystemZ.h" 75 #include "clang/Sema/SemaWasm.h" 76 #include "clang/Sema/SemaX86.h" 77 #include "llvm/ADT/APFloat.h" 78 #include "llvm/ADT/APInt.h" 79 #include "llvm/ADT/APSInt.h" 80 #include "llvm/ADT/ArrayRef.h" 81 #include "llvm/ADT/DenseMap.h" 82 #include "llvm/ADT/FoldingSet.h" 83 #include "llvm/ADT/STLExtras.h" 84 #include "llvm/ADT/SmallBitVector.h" 85 #include "llvm/ADT/SmallPtrSet.h" 86 #include "llvm/ADT/SmallString.h" 87 #include "llvm/ADT/SmallVector.h" 88 #include "llvm/ADT/StringExtras.h" 89 #include "llvm/ADT/StringRef.h" 90 #include "llvm/ADT/StringSet.h" 91 #include "llvm/ADT/StringSwitch.h" 92 #include "llvm/Support/AtomicOrdering.h" 93 #include "llvm/Support/Compiler.h" 94 #include "llvm/Support/ConvertUTF.h" 95 #include "llvm/Support/ErrorHandling.h" 96 #include "llvm/Support/Format.h" 97 #include "llvm/Support/Locale.h" 98 #include "llvm/Support/MathExtras.h" 99 #include "llvm/Support/SaveAndRestore.h" 100 #include "llvm/Support/raw_ostream.h" 101 #include "llvm/TargetParser/RISCVTargetParser.h" 102 #include "llvm/TargetParser/Triple.h" 103 #include <algorithm> 104 #include <cassert> 105 #include <cctype> 106 #include <cstddef> 107 #include <cstdint> 108 #include <functional> 109 #include <limits> 110 #include <optional> 111 #include <string> 112 #include <tuple> 113 #include <utility> 114 115 using namespace clang; 116 using namespace sema; 117 118 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 119 unsigned ByteNo) const { 120 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 121 Context.getTargetInfo()); 122 } 123 124 static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, 125 Sema::FormatArgumentPassingKind B) { 126 return (A << 8) | B; 127 } 128 129 bool Sema::checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount) { 130 unsigned ArgCount = Call->getNumArgs(); 131 if (ArgCount >= MinArgCount) 132 return false; 133 134 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_few_args) 135 << 0 /*function call*/ << MinArgCount << ArgCount 136 << /*is non object*/ 0 << Call->getSourceRange(); 137 } 138 139 bool Sema::checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount) { 140 unsigned ArgCount = Call->getNumArgs(); 141 if (ArgCount <= MaxArgCount) 142 return false; 143 return Diag(Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most) 144 << 0 /*function call*/ << MaxArgCount << ArgCount 145 << /*is non object*/ 0 << Call->getSourceRange(); 146 } 147 148 bool Sema::checkArgCountRange(CallExpr *Call, unsigned MinArgCount, 149 unsigned MaxArgCount) { 150 return checkArgCountAtLeast(Call, MinArgCount) || 151 checkArgCountAtMost(Call, MaxArgCount); 152 } 153 154 bool Sema::checkArgCount(CallExpr *Call, unsigned DesiredArgCount) { 155 unsigned ArgCount = Call->getNumArgs(); 156 if (ArgCount == DesiredArgCount) 157 return false; 158 159 if (checkArgCountAtLeast(Call, DesiredArgCount)) 160 return true; 161 assert(ArgCount > DesiredArgCount && "should have diagnosed this"); 162 163 // Highlight all the excess arguments. 164 SourceRange Range(Call->getArg(DesiredArgCount)->getBeginLoc(), 165 Call->getArg(ArgCount - 1)->getEndLoc()); 166 167 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args) 168 << 0 /*function call*/ << DesiredArgCount << ArgCount 169 << /*is non object*/ 0 << Call->getArg(1)->getSourceRange(); 170 } 171 172 static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S) { 173 bool HasError = false; 174 175 for (unsigned I = 0; I < Call->getNumArgs(); ++I) { 176 Expr *Arg = Call->getArg(I); 177 178 if (Arg->isValueDependent()) 179 continue; 180 181 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.Context); 182 int DiagMsgKind = -1; 183 // Arguments must be pointers to constant strings and cannot use '$'. 184 if (!ArgString.has_value()) 185 DiagMsgKind = 0; 186 else if (ArgString->find('$') != std::string::npos) 187 DiagMsgKind = 1; 188 189 if (DiagMsgKind >= 0) { 190 S.Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg) 191 << DiagMsgKind << Arg->getSourceRange(); 192 HasError = true; 193 } 194 } 195 196 return !HasError; 197 } 198 199 static bool convertArgumentToType(Sema &S, Expr *&Value, QualType Ty) { 200 if (Value->isTypeDependent()) 201 return false; 202 203 InitializedEntity Entity = 204 InitializedEntity::InitializeParameter(S.Context, Ty, false); 205 ExprResult Result = 206 S.PerformCopyInitialization(Entity, SourceLocation(), Value); 207 if (Result.isInvalid()) 208 return true; 209 Value = Result.get(); 210 return false; 211 } 212 213 /// Check that the first argument to __builtin_annotation is an integer 214 /// and the second argument is a non-wide string literal. 215 static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall) { 216 if (S.checkArgCount(TheCall, 2)) 217 return true; 218 219 // First argument should be an integer. 220 Expr *ValArg = TheCall->getArg(0); 221 QualType Ty = ValArg->getType(); 222 if (!Ty->isIntegerType()) { 223 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 224 << ValArg->getSourceRange(); 225 return true; 226 } 227 228 // Second argument should be a constant string. 229 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 230 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 231 if (!Literal || !Literal->isOrdinary()) { 232 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 233 << StrArg->getSourceRange(); 234 return true; 235 } 236 237 TheCall->setType(Ty); 238 return false; 239 } 240 241 static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 242 // We need at least one argument. 243 if (TheCall->getNumArgs() < 1) { 244 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 245 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0 246 << TheCall->getCallee()->getSourceRange(); 247 return true; 248 } 249 250 // All arguments should be wide string literals. 251 for (Expr *Arg : TheCall->arguments()) { 252 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 253 if (!Literal || !Literal->isWide()) { 254 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 255 << Arg->getSourceRange(); 256 return true; 257 } 258 } 259 260 return false; 261 } 262 263 /// Check that the argument to __builtin_addressof is a glvalue, and set the 264 /// result type to the corresponding pointer type. 265 static bool BuiltinAddressof(Sema &S, CallExpr *TheCall) { 266 if (S.checkArgCount(TheCall, 1)) 267 return true; 268 269 ExprResult Arg(TheCall->getArg(0)); 270 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 271 if (ResultType.isNull()) 272 return true; 273 274 TheCall->setArg(0, Arg.get()); 275 TheCall->setType(ResultType); 276 return false; 277 } 278 279 /// Check that the argument to __builtin_function_start is a function. 280 static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall) { 281 if (S.checkArgCount(TheCall, 1)) 282 return true; 283 284 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 285 if (Arg.isInvalid()) 286 return true; 287 288 TheCall->setArg(0, Arg.get()); 289 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>( 290 Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext())); 291 292 if (!FD) { 293 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type) 294 << TheCall->getSourceRange(); 295 return true; 296 } 297 298 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 299 TheCall->getBeginLoc()); 300 } 301 302 /// Check the number of arguments and set the result type to 303 /// the argument type. 304 static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 305 if (S.checkArgCount(TheCall, 1)) 306 return true; 307 308 TheCall->setType(TheCall->getArg(0)->getType()); 309 return false; 310 } 311 312 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 313 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 314 /// type (but not a function pointer) and that the alignment is a power-of-two. 315 static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 316 if (S.checkArgCount(TheCall, 2)) 317 return true; 318 319 clang::Expr *Source = TheCall->getArg(0); 320 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 321 322 auto IsValidIntegerType = [](QualType Ty) { 323 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 324 }; 325 QualType SrcTy = Source->getType(); 326 // We should also be able to use it with arrays (but not functions!). 327 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 328 SrcTy = S.Context.getDecayedType(SrcTy); 329 } 330 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 331 SrcTy->isFunctionPointerType()) { 332 // FIXME: this is not quite the right error message since we don't allow 333 // floating point types, or member pointers. 334 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 335 << SrcTy; 336 return true; 337 } 338 339 clang::Expr *AlignOp = TheCall->getArg(1); 340 if (!IsValidIntegerType(AlignOp->getType())) { 341 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 342 << AlignOp->getType(); 343 return true; 344 } 345 Expr::EvalResult AlignResult; 346 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 347 // We can't check validity of alignment if it is value dependent. 348 if (!AlignOp->isValueDependent() && 349 AlignOp->EvaluateAsInt(AlignResult, S.Context, 350 Expr::SE_AllowSideEffects)) { 351 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 352 llvm::APSInt MaxValue( 353 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 354 if (AlignValue < 1) { 355 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 356 return true; 357 } 358 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 359 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 360 << toString(MaxValue, 10); 361 return true; 362 } 363 if (!AlignValue.isPowerOf2()) { 364 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 365 return true; 366 } 367 if (AlignValue == 1) { 368 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 369 << IsBooleanAlignBuiltin; 370 } 371 } 372 373 ExprResult SrcArg = S.PerformCopyInitialization( 374 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 375 SourceLocation(), Source); 376 if (SrcArg.isInvalid()) 377 return true; 378 TheCall->setArg(0, SrcArg.get()); 379 ExprResult AlignArg = 380 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 381 S.Context, AlignOp->getType(), false), 382 SourceLocation(), AlignOp); 383 if (AlignArg.isInvalid()) 384 return true; 385 TheCall->setArg(1, AlignArg.get()); 386 // For align_up/align_down, the return type is the same as the (potentially 387 // decayed) argument type including qualifiers. For is_aligned(), the result 388 // is always bool. 389 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 390 return false; 391 } 392 393 static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID) { 394 if (S.checkArgCount(TheCall, 3)) 395 return true; 396 397 std::pair<unsigned, const char *> Builtins[] = { 398 { Builtin::BI__builtin_add_overflow, "ckd_add" }, 399 { Builtin::BI__builtin_sub_overflow, "ckd_sub" }, 400 { Builtin::BI__builtin_mul_overflow, "ckd_mul" }, 401 }; 402 403 bool CkdOperation = llvm::any_of(Builtins, [&](const std::pair<unsigned, 404 const char *> &P) { 405 return BuiltinID == P.first && TheCall->getExprLoc().isMacroID() && 406 Lexer::getImmediateMacroName(TheCall->getExprLoc(), 407 S.getSourceManager(), S.getLangOpts()) == P.second; 408 }); 409 410 auto ValidCkdIntType = [](QualType QT) { 411 // A valid checked integer type is an integer type other than a plain char, 412 // bool, a bit-precise type, or an enumeration type. 413 if (const auto *BT = QT.getCanonicalType()->getAs<BuiltinType>()) 414 return (BT->getKind() >= BuiltinType::Short && 415 BT->getKind() <= BuiltinType::Int128) || ( 416 BT->getKind() >= BuiltinType::UShort && 417 BT->getKind() <= BuiltinType::UInt128) || 418 BT->getKind() == BuiltinType::UChar || 419 BT->getKind() == BuiltinType::SChar; 420 return false; 421 }; 422 423 // First two arguments should be integers. 424 for (unsigned I = 0; I < 2; ++I) { 425 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 426 if (Arg.isInvalid()) return true; 427 TheCall->setArg(I, Arg.get()); 428 429 QualType Ty = Arg.get()->getType(); 430 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->isIntegerType(); 431 if (!IsValid) { 432 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 433 << CkdOperation << Ty << Arg.get()->getSourceRange(); 434 return true; 435 } 436 } 437 438 // Third argument should be a pointer to a non-const integer. 439 // IRGen correctly handles volatile, restrict, and address spaces, and 440 // the other qualifiers aren't possible. 441 { 442 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 443 if (Arg.isInvalid()) return true; 444 TheCall->setArg(2, Arg.get()); 445 446 QualType Ty = Arg.get()->getType(); 447 const auto *PtrTy = Ty->getAs<PointerType>(); 448 if (!PtrTy || 449 !PtrTy->getPointeeType()->isIntegerType() || 450 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) || 451 PtrTy->getPointeeType().isConstQualified()) { 452 S.Diag(Arg.get()->getBeginLoc(), 453 diag::err_overflow_builtin_must_be_ptr_int) 454 << CkdOperation << Ty << Arg.get()->getSourceRange(); 455 return true; 456 } 457 } 458 459 // Disallow signed bit-precise integer args larger than 128 bits to mul 460 // function until we improve backend support. 461 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 462 for (unsigned I = 0; I < 3; ++I) { 463 const auto Arg = TheCall->getArg(I); 464 // Third argument will be a pointer. 465 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 466 if (Ty->isBitIntType() && Ty->isSignedIntegerType() && 467 S.getASTContext().getIntWidth(Ty) > 128) 468 return S.Diag(Arg->getBeginLoc(), 469 diag::err_overflow_builtin_bit_int_max_size) 470 << 128; 471 } 472 } 473 474 return false; 475 } 476 477 namespace { 478 struct BuiltinDumpStructGenerator { 479 Sema &S; 480 CallExpr *TheCall; 481 SourceLocation Loc = TheCall->getBeginLoc(); 482 SmallVector<Expr *, 32> Actions; 483 DiagnosticErrorTrap ErrorTracker; 484 PrintingPolicy Policy; 485 486 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall) 487 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()), 488 Policy(S.Context.getPrintingPolicy()) { 489 Policy.AnonymousTagLocations = false; 490 } 491 492 Expr *makeOpaqueValueExpr(Expr *Inner) { 493 auto *OVE = new (S.Context) 494 OpaqueValueExpr(Loc, Inner->getType(), Inner->getValueKind(), 495 Inner->getObjectKind(), Inner); 496 Actions.push_back(OVE); 497 return OVE; 498 } 499 500 Expr *getStringLiteral(llvm::StringRef Str) { 501 Expr *Lit = S.Context.getPredefinedStringLiteralFromCache(Str); 502 // Wrap the literal in parentheses to attach a source location. 503 return new (S.Context) ParenExpr(Loc, Loc, Lit); 504 } 505 506 bool callPrintFunction(llvm::StringRef Format, 507 llvm::ArrayRef<Expr *> Exprs = {}) { 508 SmallVector<Expr *, 8> Args; 509 assert(TheCall->getNumArgs() >= 2); 510 Args.reserve((TheCall->getNumArgs() - 2) + /*Format*/ 1 + Exprs.size()); 511 Args.assign(TheCall->arg_begin() + 2, TheCall->arg_end()); 512 Args.push_back(getStringLiteral(Format)); 513 Args.insert(Args.end(), Exprs.begin(), Exprs.end()); 514 515 // Register a note to explain why we're performing the call. 516 Sema::CodeSynthesisContext Ctx; 517 Ctx.Kind = Sema::CodeSynthesisContext::BuildingBuiltinDumpStructCall; 518 Ctx.PointOfInstantiation = Loc; 519 Ctx.CallArgs = Args.data(); 520 Ctx.NumCallArgs = Args.size(); 521 S.pushCodeSynthesisContext(Ctx); 522 523 ExprResult RealCall = 524 S.BuildCallExpr(/*Scope=*/nullptr, TheCall->getArg(1), 525 TheCall->getBeginLoc(), Args, TheCall->getRParenLoc()); 526 527 S.popCodeSynthesisContext(); 528 if (!RealCall.isInvalid()) 529 Actions.push_back(RealCall.get()); 530 // Bail out if we've hit any errors, even if we managed to build the 531 // call. We don't want to produce more than one error. 532 return RealCall.isInvalid() || ErrorTracker.hasErrorOccurred(); 533 } 534 535 Expr *getIndentString(unsigned Depth) { 536 if (!Depth) 537 return nullptr; 538 539 llvm::SmallString<32> Indent; 540 Indent.resize(Depth * Policy.Indentation, ' '); 541 return getStringLiteral(Indent); 542 } 543 544 Expr *getTypeString(QualType T) { 545 return getStringLiteral(T.getAsString(Policy)); 546 } 547 548 bool appendFormatSpecifier(QualType T, llvm::SmallVectorImpl<char> &Str) { 549 llvm::raw_svector_ostream OS(Str); 550 551 // Format 'bool', 'char', 'signed char', 'unsigned char' as numbers, rather 552 // than trying to print a single character. 553 if (auto *BT = T->getAs<BuiltinType>()) { 554 switch (BT->getKind()) { 555 case BuiltinType::Bool: 556 OS << "%d"; 557 return true; 558 case BuiltinType::Char_U: 559 case BuiltinType::UChar: 560 OS << "%hhu"; 561 return true; 562 case BuiltinType::Char_S: 563 case BuiltinType::SChar: 564 OS << "%hhd"; 565 return true; 566 default: 567 break; 568 } 569 } 570 571 analyze_printf::PrintfSpecifier Specifier; 572 if (Specifier.fixType(T, S.getLangOpts(), S.Context, /*IsObjCLiteral=*/false)) { 573 // We were able to guess how to format this. 574 if (Specifier.getConversionSpecifier().getKind() == 575 analyze_printf::PrintfConversionSpecifier::sArg) { 576 // Wrap double-quotes around a '%s' specifier and limit its maximum 577 // length. Ideally we'd also somehow escape special characters in the 578 // contents but printf doesn't support that. 579 // FIXME: '%s' formatting is not safe in general. 580 OS << '"'; 581 Specifier.setPrecision(analyze_printf::OptionalAmount(32u)); 582 Specifier.toString(OS); 583 OS << '"'; 584 // FIXME: It would be nice to include a '...' if the string doesn't fit 585 // in the length limit. 586 } else { 587 Specifier.toString(OS); 588 } 589 return true; 590 } 591 592 if (T->isPointerType()) { 593 // Format all pointers with '%p'. 594 OS << "%p"; 595 return true; 596 } 597 598 return false; 599 } 600 601 bool dumpUnnamedRecord(const RecordDecl *RD, Expr *E, unsigned Depth) { 602 Expr *IndentLit = getIndentString(Depth); 603 Expr *TypeLit = getTypeString(S.Context.getRecordType(RD)); 604 if (IndentLit ? callPrintFunction("%s%s", {IndentLit, TypeLit}) 605 : callPrintFunction("%s", {TypeLit})) 606 return true; 607 608 return dumpRecordValue(RD, E, IndentLit, Depth); 609 } 610 611 // Dump a record value. E should be a pointer or lvalue referring to an RD. 612 bool dumpRecordValue(const RecordDecl *RD, Expr *E, Expr *RecordIndent, 613 unsigned Depth) { 614 // FIXME: Decide what to do if RD is a union. At least we should probably 615 // turn off printing `const char*` members with `%s`, because that is very 616 // likely to crash if that's not the active member. Whatever we decide, we 617 // should document it. 618 619 // Build an OpaqueValueExpr so we can refer to E more than once without 620 // triggering re-evaluation. 621 Expr *RecordArg = makeOpaqueValueExpr(E); 622 bool RecordArgIsPtr = RecordArg->getType()->isPointerType(); 623 624 if (callPrintFunction(" {\n")) 625 return true; 626 627 // Dump each base class, regardless of whether they're aggregates. 628 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 629 for (const auto &Base : CXXRD->bases()) { 630 QualType BaseType = 631 RecordArgIsPtr ? S.Context.getPointerType(Base.getType()) 632 : S.Context.getLValueReferenceType(Base.getType()); 633 ExprResult BasePtr = S.BuildCStyleCastExpr( 634 Loc, S.Context.getTrivialTypeSourceInfo(BaseType, Loc), Loc, 635 RecordArg); 636 if (BasePtr.isInvalid() || 637 dumpUnnamedRecord(Base.getType()->getAsRecordDecl(), BasePtr.get(), 638 Depth + 1)) 639 return true; 640 } 641 } 642 643 Expr *FieldIndentArg = getIndentString(Depth + 1); 644 645 // Dump each field. 646 for (auto *D : RD->decls()) { 647 auto *IFD = dyn_cast<IndirectFieldDecl>(D); 648 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D); 649 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion()) 650 continue; 651 652 llvm::SmallString<20> Format = llvm::StringRef("%s%s %s "); 653 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg, 654 getTypeString(FD->getType()), 655 getStringLiteral(FD->getName())}; 656 657 if (FD->isBitField()) { 658 Format += ": %zu "; 659 QualType SizeT = S.Context.getSizeType(); 660 llvm::APInt BitWidth(S.Context.getIntWidth(SizeT), 661 FD->getBitWidthValue()); 662 Args.push_back(IntegerLiteral::Create(S.Context, BitWidth, SizeT, Loc)); 663 } 664 665 Format += "="; 666 667 ExprResult Field = 668 IFD ? S.BuildAnonymousStructUnionMemberReference( 669 CXXScopeSpec(), Loc, IFD, 670 DeclAccessPair::make(IFD, AS_public), RecordArg, Loc) 671 : S.BuildFieldReferenceExpr( 672 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD, 673 DeclAccessPair::make(FD, AS_public), 674 DeclarationNameInfo(FD->getDeclName(), Loc)); 675 if (Field.isInvalid()) 676 return true; 677 678 auto *InnerRD = FD->getType()->getAsRecordDecl(); 679 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD); 680 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) { 681 // Recursively print the values of members of aggregate record type. 682 if (callPrintFunction(Format, Args) || 683 dumpRecordValue(InnerRD, Field.get(), FieldIndentArg, Depth + 1)) 684 return true; 685 } else { 686 Format += " "; 687 if (appendFormatSpecifier(FD->getType(), Format)) { 688 // We know how to print this field. 689 Args.push_back(Field.get()); 690 } else { 691 // We don't know how to print this field. Print out its address 692 // with a format specifier that a smart tool will be able to 693 // recognize and treat specially. 694 Format += "*%p"; 695 ExprResult FieldAddr = 696 S.BuildUnaryOp(nullptr, Loc, UO_AddrOf, Field.get()); 697 if (FieldAddr.isInvalid()) 698 return true; 699 Args.push_back(FieldAddr.get()); 700 } 701 Format += "\n"; 702 if (callPrintFunction(Format, Args)) 703 return true; 704 } 705 } 706 707 return RecordIndent ? callPrintFunction("%s}\n", RecordIndent) 708 : callPrintFunction("}\n"); 709 } 710 711 Expr *buildWrapper() { 712 auto *Wrapper = PseudoObjectExpr::Create(S.Context, TheCall, Actions, 713 PseudoObjectExpr::NoResult); 714 TheCall->setType(Wrapper->getType()); 715 TheCall->setValueKind(Wrapper->getValueKind()); 716 return Wrapper; 717 } 718 }; 719 } // namespace 720 721 static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall) { 722 if (S.checkArgCountAtLeast(TheCall, 2)) 723 return ExprError(); 724 725 ExprResult PtrArgResult = S.DefaultLvalueConversion(TheCall->getArg(0)); 726 if (PtrArgResult.isInvalid()) 727 return ExprError(); 728 TheCall->setArg(0, PtrArgResult.get()); 729 730 // First argument should be a pointer to a struct. 731 QualType PtrArgType = PtrArgResult.get()->getType(); 732 if (!PtrArgType->isPointerType() || 733 !PtrArgType->getPointeeType()->isRecordType()) { 734 S.Diag(PtrArgResult.get()->getBeginLoc(), 735 diag::err_expected_struct_pointer_argument) 736 << 1 << TheCall->getDirectCallee() << PtrArgType; 737 return ExprError(); 738 } 739 QualType Pointee = PtrArgType->getPointeeType(); 740 const RecordDecl *RD = Pointee->getAsRecordDecl(); 741 // Try to instantiate the class template as appropriate; otherwise, access to 742 // its data() may lead to a crash. 743 if (S.RequireCompleteType(PtrArgResult.get()->getBeginLoc(), Pointee, 744 diag::err_incomplete_type)) 745 return ExprError(); 746 // Second argument is a callable, but we can't fully validate it until we try 747 // calling it. 748 QualType FnArgType = TheCall->getArg(1)->getType(); 749 if (!FnArgType->isFunctionType() && !FnArgType->isFunctionPointerType() && 750 !FnArgType->isBlockPointerType() && 751 !(S.getLangOpts().CPlusPlus && FnArgType->isRecordType())) { 752 auto *BT = FnArgType->getAs<BuiltinType>(); 753 switch (BT ? BT->getKind() : BuiltinType::Void) { 754 case BuiltinType::Dependent: 755 case BuiltinType::Overload: 756 case BuiltinType::BoundMember: 757 case BuiltinType::PseudoObject: 758 case BuiltinType::UnknownAny: 759 case BuiltinType::BuiltinFn: 760 // This might be a callable. 761 break; 762 763 default: 764 S.Diag(TheCall->getArg(1)->getBeginLoc(), 765 diag::err_expected_callable_argument) 766 << 2 << TheCall->getDirectCallee() << FnArgType; 767 return ExprError(); 768 } 769 } 770 771 BuiltinDumpStructGenerator Generator(S, TheCall); 772 773 // Wrap parentheses around the given pointer. This is not necessary for 774 // correct code generation, but it means that when we pretty-print the call 775 // arguments in our diagnostics we will produce '(&s)->n' instead of the 776 // incorrect '&s->n'. 777 Expr *PtrArg = PtrArgResult.get(); 778 PtrArg = new (S.Context) 779 ParenExpr(PtrArg->getBeginLoc(), 780 S.getLocForEndOfToken(PtrArg->getEndLoc()), PtrArg); 781 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0)) 782 return ExprError(); 783 784 return Generator.buildWrapper(); 785 } 786 787 static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 788 if (S.checkArgCount(BuiltinCall, 2)) 789 return true; 790 791 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 792 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 793 Expr *Call = BuiltinCall->getArg(0); 794 Expr *Chain = BuiltinCall->getArg(1); 795 796 if (Call->getStmtClass() != Stmt::CallExprClass) { 797 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 798 << Call->getSourceRange(); 799 return true; 800 } 801 802 auto CE = cast<CallExpr>(Call); 803 if (CE->getCallee()->getType()->isBlockPointerType()) { 804 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 805 << Call->getSourceRange(); 806 return true; 807 } 808 809 const Decl *TargetDecl = CE->getCalleeDecl(); 810 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 811 if (FD->getBuiltinID()) { 812 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 813 << Call->getSourceRange(); 814 return true; 815 } 816 817 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 818 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 819 << Call->getSourceRange(); 820 return true; 821 } 822 823 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 824 if (ChainResult.isInvalid()) 825 return true; 826 if (!ChainResult.get()->getType()->isPointerType()) { 827 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 828 << Chain->getSourceRange(); 829 return true; 830 } 831 832 QualType ReturnTy = CE->getCallReturnType(S.Context); 833 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 834 QualType BuiltinTy = S.Context.getFunctionType( 835 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 836 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 837 838 Builtin = 839 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 840 841 BuiltinCall->setType(CE->getType()); 842 BuiltinCall->setValueKind(CE->getValueKind()); 843 BuiltinCall->setObjectKind(CE->getObjectKind()); 844 BuiltinCall->setCallee(Builtin); 845 BuiltinCall->setArg(1, ChainResult.get()); 846 847 return false; 848 } 849 850 namespace { 851 852 class ScanfDiagnosticFormatHandler 853 : public analyze_format_string::FormatStringHandler { 854 // Accepts the argument index (relative to the first destination index) of the 855 // argument whose size we want. 856 using ComputeSizeFunction = 857 llvm::function_ref<std::optional<llvm::APSInt>(unsigned)>; 858 859 // Accepts the argument index (relative to the first destination index), the 860 // destination size, and the source size). 861 using DiagnoseFunction = 862 llvm::function_ref<void(unsigned, unsigned, unsigned)>; 863 864 ComputeSizeFunction ComputeSizeArgument; 865 DiagnoseFunction Diagnose; 866 867 public: 868 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument, 869 DiagnoseFunction Diagnose) 870 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {} 871 872 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 873 const char *StartSpecifier, 874 unsigned specifierLen) override { 875 if (!FS.consumesDataArgument()) 876 return true; 877 878 unsigned NulByte = 0; 879 switch ((FS.getConversionSpecifier().getKind())) { 880 default: 881 return true; 882 case analyze_format_string::ConversionSpecifier::sArg: 883 case analyze_format_string::ConversionSpecifier::ScanListArg: 884 NulByte = 1; 885 break; 886 case analyze_format_string::ConversionSpecifier::cArg: 887 break; 888 } 889 890 analyze_format_string::OptionalAmount FW = FS.getFieldWidth(); 891 if (FW.getHowSpecified() != 892 analyze_format_string::OptionalAmount::HowSpecified::Constant) 893 return true; 894 895 unsigned SourceSize = FW.getConstantAmount() + NulByte; 896 897 std::optional<llvm::APSInt> DestSizeAPS = 898 ComputeSizeArgument(FS.getArgIndex()); 899 if (!DestSizeAPS) 900 return true; 901 902 unsigned DestSize = DestSizeAPS->getZExtValue(); 903 904 if (DestSize < SourceSize) 905 Diagnose(FS.getArgIndex(), DestSize, SourceSize); 906 907 return true; 908 } 909 }; 910 911 class EstimateSizeFormatHandler 912 : public analyze_format_string::FormatStringHandler { 913 size_t Size; 914 /// Whether the format string contains Linux kernel's format specifier 915 /// extension. 916 bool IsKernelCompatible = true; 917 918 public: 919 EstimateSizeFormatHandler(StringRef Format) 920 : Size(std::min(Format.find(0), Format.size()) + 921 1 /* null byte always written by sprintf */) {} 922 923 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 924 const char *, unsigned SpecifierLen, 925 const TargetInfo &) override { 926 927 const size_t FieldWidth = computeFieldWidth(FS); 928 const size_t Precision = computePrecision(FS); 929 930 // The actual format. 931 switch (FS.getConversionSpecifier().getKind()) { 932 // Just a char. 933 case analyze_format_string::ConversionSpecifier::cArg: 934 case analyze_format_string::ConversionSpecifier::CArg: 935 Size += std::max(FieldWidth, (size_t)1); 936 break; 937 // Just an integer. 938 case analyze_format_string::ConversionSpecifier::dArg: 939 case analyze_format_string::ConversionSpecifier::DArg: 940 case analyze_format_string::ConversionSpecifier::iArg: 941 case analyze_format_string::ConversionSpecifier::oArg: 942 case analyze_format_string::ConversionSpecifier::OArg: 943 case analyze_format_string::ConversionSpecifier::uArg: 944 case analyze_format_string::ConversionSpecifier::UArg: 945 case analyze_format_string::ConversionSpecifier::xArg: 946 case analyze_format_string::ConversionSpecifier::XArg: 947 Size += std::max(FieldWidth, Precision); 948 break; 949 950 // %g style conversion switches between %f or %e style dynamically. 951 // %g removes trailing zeros, and does not print decimal point if there are 952 // no digits that follow it. Thus %g can print a single digit. 953 // FIXME: If it is alternative form: 954 // For g and G conversions, trailing zeros are not removed from the result. 955 case analyze_format_string::ConversionSpecifier::gArg: 956 case analyze_format_string::ConversionSpecifier::GArg: 957 Size += 1; 958 break; 959 960 // Floating point number in the form '[+]ddd.ddd'. 961 case analyze_format_string::ConversionSpecifier::fArg: 962 case analyze_format_string::ConversionSpecifier::FArg: 963 Size += std::max(FieldWidth, 1 /* integer part */ + 964 (Precision ? 1 + Precision 965 : 0) /* period + decimal */); 966 break; 967 968 // Floating point number in the form '[-]d.ddde[+-]dd'. 969 case analyze_format_string::ConversionSpecifier::eArg: 970 case analyze_format_string::ConversionSpecifier::EArg: 971 Size += 972 std::max(FieldWidth, 973 1 /* integer part */ + 974 (Precision ? 1 + Precision : 0) /* period + decimal */ + 975 1 /* e or E letter */ + 2 /* exponent */); 976 break; 977 978 // Floating point number in the form '[-]0xh.hhhhp±dd'. 979 case analyze_format_string::ConversionSpecifier::aArg: 980 case analyze_format_string::ConversionSpecifier::AArg: 981 Size += 982 std::max(FieldWidth, 983 2 /* 0x */ + 1 /* integer part */ + 984 (Precision ? 1 + Precision : 0) /* period + decimal */ + 985 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 986 break; 987 988 // Just a string. 989 case analyze_format_string::ConversionSpecifier::sArg: 990 case analyze_format_string::ConversionSpecifier::SArg: 991 Size += FieldWidth; 992 break; 993 994 // Just a pointer in the form '0xddd'. 995 case analyze_format_string::ConversionSpecifier::pArg: 996 // Linux kernel has its own extesion for `%p` specifier. 997 // Kernel Document: 998 // https://docs.kernel.org/core-api/printk-formats.html#pointer-types 999 IsKernelCompatible = false; 1000 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 1001 break; 1002 1003 // A plain percent. 1004 case analyze_format_string::ConversionSpecifier::PercentArg: 1005 Size += 1; 1006 break; 1007 1008 default: 1009 break; 1010 } 1011 1012 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 1013 1014 if (FS.hasAlternativeForm()) { 1015 switch (FS.getConversionSpecifier().getKind()) { 1016 // For o conversion, it increases the precision, if and only if necessary, 1017 // to force the first digit of the result to be a zero 1018 // (if the value and precision are both 0, a single 0 is printed) 1019 case analyze_format_string::ConversionSpecifier::oArg: 1020 // For b conversion, a nonzero result has 0b prefixed to it. 1021 case analyze_format_string::ConversionSpecifier::bArg: 1022 // For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to 1023 // it. 1024 case analyze_format_string::ConversionSpecifier::xArg: 1025 case analyze_format_string::ConversionSpecifier::XArg: 1026 // Note: even when the prefix is added, if 1027 // (prefix_width <= FieldWidth - formatted_length) holds, 1028 // the prefix does not increase the format 1029 // size. e.g.(("%#3x", 0xf) is "0xf") 1030 1031 // If the result is zero, o, b, x, X adds nothing. 1032 break; 1033 // For a, A, e, E, f, F, g, and G conversions, 1034 // the result of converting a floating-point number always contains a 1035 // decimal-point 1036 case analyze_format_string::ConversionSpecifier::aArg: 1037 case analyze_format_string::ConversionSpecifier::AArg: 1038 case analyze_format_string::ConversionSpecifier::eArg: 1039 case analyze_format_string::ConversionSpecifier::EArg: 1040 case analyze_format_string::ConversionSpecifier::fArg: 1041 case analyze_format_string::ConversionSpecifier::FArg: 1042 case analyze_format_string::ConversionSpecifier::gArg: 1043 case analyze_format_string::ConversionSpecifier::GArg: 1044 Size += (Precision ? 0 : 1); 1045 break; 1046 // For other conversions, the behavior is undefined. 1047 default: 1048 break; 1049 } 1050 } 1051 assert(SpecifierLen <= Size && "no underflow"); 1052 Size -= SpecifierLen; 1053 return true; 1054 } 1055 1056 size_t getSizeLowerBound() const { return Size; } 1057 bool isKernelCompatible() const { return IsKernelCompatible; } 1058 1059 private: 1060 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 1061 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 1062 size_t FieldWidth = 0; 1063 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 1064 FieldWidth = FW.getConstantAmount(); 1065 return FieldWidth; 1066 } 1067 1068 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 1069 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 1070 size_t Precision = 0; 1071 1072 // See man 3 printf for default precision value based on the specifier. 1073 switch (FW.getHowSpecified()) { 1074 case analyze_format_string::OptionalAmount::NotSpecified: 1075 switch (FS.getConversionSpecifier().getKind()) { 1076 default: 1077 break; 1078 case analyze_format_string::ConversionSpecifier::dArg: // %d 1079 case analyze_format_string::ConversionSpecifier::DArg: // %D 1080 case analyze_format_string::ConversionSpecifier::iArg: // %i 1081 Precision = 1; 1082 break; 1083 case analyze_format_string::ConversionSpecifier::oArg: // %d 1084 case analyze_format_string::ConversionSpecifier::OArg: // %D 1085 case analyze_format_string::ConversionSpecifier::uArg: // %d 1086 case analyze_format_string::ConversionSpecifier::UArg: // %D 1087 case analyze_format_string::ConversionSpecifier::xArg: // %d 1088 case analyze_format_string::ConversionSpecifier::XArg: // %D 1089 Precision = 1; 1090 break; 1091 case analyze_format_string::ConversionSpecifier::fArg: // %f 1092 case analyze_format_string::ConversionSpecifier::FArg: // %F 1093 case analyze_format_string::ConversionSpecifier::eArg: // %e 1094 case analyze_format_string::ConversionSpecifier::EArg: // %E 1095 case analyze_format_string::ConversionSpecifier::gArg: // %g 1096 case analyze_format_string::ConversionSpecifier::GArg: // %G 1097 Precision = 6; 1098 break; 1099 case analyze_format_string::ConversionSpecifier::pArg: // %d 1100 Precision = 1; 1101 break; 1102 } 1103 break; 1104 case analyze_format_string::OptionalAmount::Constant: 1105 Precision = FW.getConstantAmount(); 1106 break; 1107 default: 1108 break; 1109 } 1110 return Precision; 1111 } 1112 }; 1113 1114 } // namespace 1115 1116 static bool ProcessFormatStringLiteral(const Expr *FormatExpr, 1117 StringRef &FormatStrRef, size_t &StrLen, 1118 ASTContext &Context) { 1119 if (const auto *Format = dyn_cast<StringLiteral>(FormatExpr); 1120 Format && (Format->isOrdinary() || Format->isUTF8())) { 1121 FormatStrRef = Format->getString(); 1122 const ConstantArrayType *T = 1123 Context.getAsConstantArrayType(Format->getType()); 1124 assert(T && "String literal not of constant array type!"); 1125 size_t TypeSize = T->getZExtSize(); 1126 // In case there's a null byte somewhere. 1127 StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 1128 return true; 1129 } 1130 return false; 1131 } 1132 1133 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 1134 CallExpr *TheCall) { 1135 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 1136 isConstantEvaluatedContext()) 1137 return; 1138 1139 bool UseDABAttr = false; 1140 const FunctionDecl *UseDecl = FD; 1141 1142 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>(); 1143 if (DABAttr) { 1144 UseDecl = DABAttr->getFunction(); 1145 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!"); 1146 UseDABAttr = true; 1147 } 1148 1149 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true); 1150 1151 if (!BuiltinID) 1152 return; 1153 1154 const TargetInfo &TI = getASTContext().getTargetInfo(); 1155 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 1156 1157 auto TranslateIndex = [&](unsigned Index) -> std::optional<unsigned> { 1158 // If we refer to a diagnose_as_builtin attribute, we need to change the 1159 // argument index to refer to the arguments of the called function. Unless 1160 // the index is out of bounds, which presumably means it's a variadic 1161 // function. 1162 if (!UseDABAttr) 1163 return Index; 1164 unsigned DABIndices = DABAttr->argIndices_size(); 1165 unsigned NewIndex = Index < DABIndices 1166 ? DABAttr->argIndices_begin()[Index] 1167 : Index - DABIndices + FD->getNumParams(); 1168 if (NewIndex >= TheCall->getNumArgs()) 1169 return std::nullopt; 1170 return NewIndex; 1171 }; 1172 1173 auto ComputeExplicitObjectSizeArgument = 1174 [&](unsigned Index) -> std::optional<llvm::APSInt> { 1175 std::optional<unsigned> IndexOptional = TranslateIndex(Index); 1176 if (!IndexOptional) 1177 return std::nullopt; 1178 unsigned NewIndex = *IndexOptional; 1179 Expr::EvalResult Result; 1180 Expr *SizeArg = TheCall->getArg(NewIndex); 1181 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 1182 return std::nullopt; 1183 llvm::APSInt Integer = Result.Val.getInt(); 1184 Integer.setIsUnsigned(true); 1185 return Integer; 1186 }; 1187 1188 auto ComputeSizeArgument = 1189 [&](unsigned Index) -> std::optional<llvm::APSInt> { 1190 // If the parameter has a pass_object_size attribute, then we should use its 1191 // (potentially) more strict checking mode. Otherwise, conservatively assume 1192 // type 0. 1193 int BOSType = 0; 1194 // This check can fail for variadic functions. 1195 if (Index < FD->getNumParams()) { 1196 if (const auto *POS = 1197 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 1198 BOSType = POS->getType(); 1199 } 1200 1201 std::optional<unsigned> IndexOptional = TranslateIndex(Index); 1202 if (!IndexOptional) 1203 return std::nullopt; 1204 unsigned NewIndex = *IndexOptional; 1205 1206 if (NewIndex >= TheCall->getNumArgs()) 1207 return std::nullopt; 1208 1209 const Expr *ObjArg = TheCall->getArg(NewIndex); 1210 uint64_t Result; 1211 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 1212 return std::nullopt; 1213 1214 // Get the object size in the target's size_t width. 1215 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 1216 }; 1217 1218 auto ComputeStrLenArgument = 1219 [&](unsigned Index) -> std::optional<llvm::APSInt> { 1220 std::optional<unsigned> IndexOptional = TranslateIndex(Index); 1221 if (!IndexOptional) 1222 return std::nullopt; 1223 unsigned NewIndex = *IndexOptional; 1224 1225 const Expr *ObjArg = TheCall->getArg(NewIndex); 1226 uint64_t Result; 1227 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 1228 return std::nullopt; 1229 // Add 1 for null byte. 1230 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 1231 }; 1232 1233 std::optional<llvm::APSInt> SourceSize; 1234 std::optional<llvm::APSInt> DestinationSize; 1235 unsigned DiagID = 0; 1236 bool IsChkVariant = false; 1237 1238 auto GetFunctionName = [&]() { 1239 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 1240 // Skim off the details of whichever builtin was called to produce a better 1241 // diagnostic, as it's unlikely that the user wrote the __builtin 1242 // explicitly. 1243 if (IsChkVariant) { 1244 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 1245 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 1246 } else { 1247 FunctionName.consume_front("__builtin_"); 1248 } 1249 return FunctionName; 1250 }; 1251 1252 switch (BuiltinID) { 1253 default: 1254 return; 1255 case Builtin::BI__builtin_strcpy: 1256 case Builtin::BIstrcpy: { 1257 DiagID = diag::warn_fortify_strlen_overflow; 1258 SourceSize = ComputeStrLenArgument(1); 1259 DestinationSize = ComputeSizeArgument(0); 1260 break; 1261 } 1262 1263 case Builtin::BI__builtin___strcpy_chk: { 1264 DiagID = diag::warn_fortify_strlen_overflow; 1265 SourceSize = ComputeStrLenArgument(1); 1266 DestinationSize = ComputeExplicitObjectSizeArgument(2); 1267 IsChkVariant = true; 1268 break; 1269 } 1270 1271 case Builtin::BIscanf: 1272 case Builtin::BIfscanf: 1273 case Builtin::BIsscanf: { 1274 unsigned FormatIndex = 1; 1275 unsigned DataIndex = 2; 1276 if (BuiltinID == Builtin::BIscanf) { 1277 FormatIndex = 0; 1278 DataIndex = 1; 1279 } 1280 1281 const auto *FormatExpr = 1282 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 1283 1284 StringRef FormatStrRef; 1285 size_t StrLen; 1286 if (!ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) 1287 return; 1288 1289 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize, 1290 unsigned SourceSize) { 1291 DiagID = diag::warn_fortify_scanf_overflow; 1292 unsigned Index = ArgIndex + DataIndex; 1293 StringRef FunctionName = GetFunctionName(); 1294 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall, 1295 PDiag(DiagID) << FunctionName << (Index + 1) 1296 << DestSize << SourceSize); 1297 }; 1298 1299 auto ShiftedComputeSizeArgument = [&](unsigned Index) { 1300 return ComputeSizeArgument(Index + DataIndex); 1301 }; 1302 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose); 1303 const char *FormatBytes = FormatStrRef.data(); 1304 analyze_format_string::ParseScanfString(H, FormatBytes, 1305 FormatBytes + StrLen, getLangOpts(), 1306 Context.getTargetInfo()); 1307 1308 // Unlike the other cases, in this one we have already issued the diagnostic 1309 // here, so no need to continue (because unlike the other cases, here the 1310 // diagnostic refers to the argument number). 1311 return; 1312 } 1313 1314 case Builtin::BIsprintf: 1315 case Builtin::BI__builtin___sprintf_chk: { 1316 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 1317 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 1318 1319 StringRef FormatStrRef; 1320 size_t StrLen; 1321 if (ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) { 1322 EstimateSizeFormatHandler H(FormatStrRef); 1323 const char *FormatBytes = FormatStrRef.data(); 1324 if (!analyze_format_string::ParsePrintfString( 1325 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 1326 Context.getTargetInfo(), false)) { 1327 DiagID = H.isKernelCompatible() 1328 ? diag::warn_format_overflow 1329 : diag::warn_format_overflow_non_kprintf; 1330 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 1331 .extOrTrunc(SizeTypeWidth); 1332 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 1333 DestinationSize = ComputeExplicitObjectSizeArgument(2); 1334 IsChkVariant = true; 1335 } else { 1336 DestinationSize = ComputeSizeArgument(0); 1337 } 1338 break; 1339 } 1340 } 1341 return; 1342 } 1343 case Builtin::BI__builtin___memcpy_chk: 1344 case Builtin::BI__builtin___memmove_chk: 1345 case Builtin::BI__builtin___memset_chk: 1346 case Builtin::BI__builtin___strlcat_chk: 1347 case Builtin::BI__builtin___strlcpy_chk: 1348 case Builtin::BI__builtin___strncat_chk: 1349 case Builtin::BI__builtin___strncpy_chk: 1350 case Builtin::BI__builtin___stpncpy_chk: 1351 case Builtin::BI__builtin___memccpy_chk: 1352 case Builtin::BI__builtin___mempcpy_chk: { 1353 DiagID = diag::warn_builtin_chk_overflow; 1354 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 1355 DestinationSize = 1356 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 1357 IsChkVariant = true; 1358 break; 1359 } 1360 1361 case Builtin::BI__builtin___snprintf_chk: 1362 case Builtin::BI__builtin___vsnprintf_chk: { 1363 DiagID = diag::warn_builtin_chk_overflow; 1364 SourceSize = ComputeExplicitObjectSizeArgument(1); 1365 DestinationSize = ComputeExplicitObjectSizeArgument(3); 1366 IsChkVariant = true; 1367 break; 1368 } 1369 1370 case Builtin::BIstrncat: 1371 case Builtin::BI__builtin_strncat: 1372 case Builtin::BIstrncpy: 1373 case Builtin::BI__builtin_strncpy: 1374 case Builtin::BIstpncpy: 1375 case Builtin::BI__builtin_stpncpy: { 1376 // Whether these functions overflow depends on the runtime strlen of the 1377 // string, not just the buffer size, so emitting the "always overflow" 1378 // diagnostic isn't quite right. We should still diagnose passing a buffer 1379 // size larger than the destination buffer though; this is a runtime abort 1380 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 1381 DiagID = diag::warn_fortify_source_size_mismatch; 1382 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 1383 DestinationSize = ComputeSizeArgument(0); 1384 break; 1385 } 1386 1387 case Builtin::BImemcpy: 1388 case Builtin::BI__builtin_memcpy: 1389 case Builtin::BImemmove: 1390 case Builtin::BI__builtin_memmove: 1391 case Builtin::BImemset: 1392 case Builtin::BI__builtin_memset: 1393 case Builtin::BImempcpy: 1394 case Builtin::BI__builtin_mempcpy: { 1395 DiagID = diag::warn_fortify_source_overflow; 1396 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 1397 DestinationSize = ComputeSizeArgument(0); 1398 break; 1399 } 1400 case Builtin::BIsnprintf: 1401 case Builtin::BI__builtin_snprintf: 1402 case Builtin::BIvsnprintf: 1403 case Builtin::BI__builtin_vsnprintf: { 1404 DiagID = diag::warn_fortify_source_size_mismatch; 1405 SourceSize = ComputeExplicitObjectSizeArgument(1); 1406 const auto *FormatExpr = TheCall->getArg(2)->IgnoreParenImpCasts(); 1407 StringRef FormatStrRef; 1408 size_t StrLen; 1409 if (SourceSize && 1410 ProcessFormatStringLiteral(FormatExpr, FormatStrRef, StrLen, Context)) { 1411 EstimateSizeFormatHandler H(FormatStrRef); 1412 const char *FormatBytes = FormatStrRef.data(); 1413 if (!analyze_format_string::ParsePrintfString( 1414 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 1415 Context.getTargetInfo(), /*isFreeBSDKPrintf=*/false)) { 1416 llvm::APSInt FormatSize = 1417 llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 1418 .extOrTrunc(SizeTypeWidth); 1419 if (FormatSize > *SourceSize && *SourceSize != 0) { 1420 unsigned TruncationDiagID = 1421 H.isKernelCompatible() ? diag::warn_format_truncation 1422 : diag::warn_format_truncation_non_kprintf; 1423 SmallString<16> SpecifiedSizeStr; 1424 SmallString<16> FormatSizeStr; 1425 SourceSize->toString(SpecifiedSizeStr, /*Radix=*/10); 1426 FormatSize.toString(FormatSizeStr, /*Radix=*/10); 1427 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 1428 PDiag(TruncationDiagID) 1429 << GetFunctionName() << SpecifiedSizeStr 1430 << FormatSizeStr); 1431 } 1432 } 1433 } 1434 DestinationSize = ComputeSizeArgument(0); 1435 } 1436 } 1437 1438 if (!SourceSize || !DestinationSize || 1439 llvm::APSInt::compareValues(*SourceSize, *DestinationSize) <= 0) 1440 return; 1441 1442 StringRef FunctionName = GetFunctionName(); 1443 1444 SmallString<16> DestinationStr; 1445 SmallString<16> SourceStr; 1446 DestinationSize->toString(DestinationStr, /*Radix=*/10); 1447 SourceSize->toString(SourceStr, /*Radix=*/10); 1448 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 1449 PDiag(DiagID) 1450 << FunctionName << DestinationStr << SourceStr); 1451 } 1452 1453 static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 1454 Scope::ScopeFlags NeededScopeFlags, 1455 unsigned DiagID) { 1456 // Scopes aren't available during instantiation. Fortunately, builtin 1457 // functions cannot be template args so they cannot be formed through template 1458 // instantiation. Therefore checking once during the parse is sufficient. 1459 if (SemaRef.inTemplateInstantiation()) 1460 return false; 1461 1462 Scope *S = SemaRef.getCurScope(); 1463 while (S && !S->isSEHExceptScope()) 1464 S = S->getParent(); 1465 if (!S || !(S->getFlags() & NeededScopeFlags)) { 1466 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 1467 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 1468 << DRE->getDecl()->getIdentifier(); 1469 return true; 1470 } 1471 1472 return false; 1473 } 1474 1475 // In OpenCL, __builtin_alloca_* should return a pointer to address space 1476 // that corresponds to the stack address space i.e private address space. 1477 static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall) { 1478 QualType RT = TheCall->getType(); 1479 assert((RT->isPointerType() && !(RT->getPointeeType().hasAddressSpace())) && 1480 "__builtin_alloca has invalid address space"); 1481 1482 RT = RT->getPointeeType(); 1483 RT = S.Context.getAddrSpaceQualType(RT, LangAS::opencl_private); 1484 TheCall->setType(S.Context.getPointerType(RT)); 1485 } 1486 1487 namespace { 1488 enum PointerAuthOpKind { 1489 PAO_Strip, 1490 PAO_Sign, 1491 PAO_Auth, 1492 PAO_SignGeneric, 1493 PAO_Discriminator, 1494 PAO_BlendPointer, 1495 PAO_BlendInteger 1496 }; 1497 } 1498 1499 bool Sema::checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range) { 1500 if (getLangOpts().PointerAuthIntrinsics) 1501 return false; 1502 1503 Diag(Loc, diag::err_ptrauth_disabled) << Range; 1504 return true; 1505 } 1506 1507 static bool checkPointerAuthEnabled(Sema &S, Expr *E) { 1508 return S.checkPointerAuthEnabled(E->getExprLoc(), E->getSourceRange()); 1509 } 1510 1511 static bool checkPointerAuthKey(Sema &S, Expr *&Arg) { 1512 // Convert it to type 'int'. 1513 if (convertArgumentToType(S, Arg, S.Context.IntTy)) 1514 return true; 1515 1516 // Value-dependent expressions are okay; wait for template instantiation. 1517 if (Arg->isValueDependent()) 1518 return false; 1519 1520 unsigned KeyValue; 1521 return S.checkConstantPointerAuthKey(Arg, KeyValue); 1522 } 1523 1524 bool Sema::checkConstantPointerAuthKey(Expr *Arg, unsigned &Result) { 1525 // Attempt to constant-evaluate the expression. 1526 std::optional<llvm::APSInt> KeyValue = Arg->getIntegerConstantExpr(Context); 1527 if (!KeyValue) { 1528 Diag(Arg->getExprLoc(), diag::err_expr_not_ice) 1529 << 0 << Arg->getSourceRange(); 1530 return true; 1531 } 1532 1533 // Ask the target to validate the key parameter. 1534 if (!Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) { 1535 llvm::SmallString<32> Value; 1536 { 1537 llvm::raw_svector_ostream Str(Value); 1538 Str << *KeyValue; 1539 } 1540 1541 Diag(Arg->getExprLoc(), diag::err_ptrauth_invalid_key) 1542 << Value << Arg->getSourceRange(); 1543 return true; 1544 } 1545 1546 Result = KeyValue->getZExtValue(); 1547 return false; 1548 } 1549 1550 static std::pair<const ValueDecl *, CharUnits> 1551 findConstantBaseAndOffset(Sema &S, Expr *E) { 1552 // Must evaluate as a pointer. 1553 Expr::EvalResult Result; 1554 if (!E->EvaluateAsRValue(Result, S.Context) || !Result.Val.isLValue()) 1555 return {nullptr, CharUnits()}; 1556 1557 const auto *BaseDecl = 1558 Result.Val.getLValueBase().dyn_cast<const ValueDecl *>(); 1559 if (!BaseDecl) 1560 return {nullptr, CharUnits()}; 1561 1562 return {BaseDecl, Result.Val.getLValueOffset()}; 1563 } 1564 1565 static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind, 1566 bool RequireConstant = false) { 1567 if (Arg->hasPlaceholderType()) { 1568 ExprResult R = S.CheckPlaceholderExpr(Arg); 1569 if (R.isInvalid()) 1570 return true; 1571 Arg = R.get(); 1572 } 1573 1574 auto AllowsPointer = [](PointerAuthOpKind OpKind) { 1575 return OpKind != PAO_BlendInteger; 1576 }; 1577 auto AllowsInteger = [](PointerAuthOpKind OpKind) { 1578 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger || 1579 OpKind == PAO_SignGeneric; 1580 }; 1581 1582 // Require the value to have the right range of type. 1583 QualType ExpectedTy; 1584 if (AllowsPointer(OpKind) && Arg->getType()->isPointerType()) { 1585 ExpectedTy = Arg->getType().getUnqualifiedType(); 1586 } else if (AllowsPointer(OpKind) && Arg->getType()->isNullPtrType()) { 1587 ExpectedTy = S.Context.VoidPtrTy; 1588 } else if (AllowsInteger(OpKind) && 1589 Arg->getType()->isIntegralOrUnscopedEnumerationType()) { 1590 ExpectedTy = S.Context.getUIntPtrType(); 1591 1592 } else { 1593 // Diagnose the failures. 1594 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_value_bad_type) 1595 << unsigned(OpKind == PAO_Discriminator ? 1 1596 : OpKind == PAO_BlendPointer ? 2 1597 : OpKind == PAO_BlendInteger ? 3 1598 : 0) 1599 << unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0) 1600 << Arg->getType() << Arg->getSourceRange(); 1601 return true; 1602 } 1603 1604 // Convert to that type. This should just be an lvalue-to-rvalue 1605 // conversion. 1606 if (convertArgumentToType(S, Arg, ExpectedTy)) 1607 return true; 1608 1609 if (!RequireConstant) { 1610 // Warn about null pointers for non-generic sign and auth operations. 1611 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) && 1612 Arg->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull)) { 1613 S.Diag(Arg->getExprLoc(), OpKind == PAO_Sign 1614 ? diag::warn_ptrauth_sign_null_pointer 1615 : diag::warn_ptrauth_auth_null_pointer) 1616 << Arg->getSourceRange(); 1617 } 1618 1619 return false; 1620 } 1621 1622 // Perform special checking on the arguments to ptrauth_sign_constant. 1623 1624 // The main argument. 1625 if (OpKind == PAO_Sign) { 1626 // Require the value we're signing to have a special form. 1627 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Arg); 1628 bool Invalid; 1629 1630 // Must be rooted in a declaration reference. 1631 if (!BaseDecl) 1632 Invalid = true; 1633 1634 // If it's a function declaration, we can't have an offset. 1635 else if (isa<FunctionDecl>(BaseDecl)) 1636 Invalid = !Offset.isZero(); 1637 1638 // Otherwise we're fine. 1639 else 1640 Invalid = false; 1641 1642 if (Invalid) 1643 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_pointer); 1644 return Invalid; 1645 } 1646 1647 // The discriminator argument. 1648 assert(OpKind == PAO_Discriminator); 1649 1650 // Must be a pointer or integer or blend thereof. 1651 Expr *Pointer = nullptr; 1652 Expr *Integer = nullptr; 1653 if (auto *Call = dyn_cast<CallExpr>(Arg->IgnoreParens())) { 1654 if (Call->getBuiltinCallee() == 1655 Builtin::BI__builtin_ptrauth_blend_discriminator) { 1656 Pointer = Call->getArg(0); 1657 Integer = Call->getArg(1); 1658 } 1659 } 1660 if (!Pointer && !Integer) { 1661 if (Arg->getType()->isPointerType()) 1662 Pointer = Arg; 1663 else 1664 Integer = Arg; 1665 } 1666 1667 // Check the pointer. 1668 bool Invalid = false; 1669 if (Pointer) { 1670 assert(Pointer->getType()->isPointerType()); 1671 1672 // TODO: if we're initializing a global, check that the address is 1673 // somehow related to what we're initializing. This probably will 1674 // never really be feasible and we'll have to catch it at link-time. 1675 auto [BaseDecl, Offset] = findConstantBaseAndOffset(S, Pointer); 1676 if (!BaseDecl || !isa<VarDecl>(BaseDecl)) 1677 Invalid = true; 1678 } 1679 1680 // Check the integer. 1681 if (Integer) { 1682 assert(Integer->getType()->isIntegerType()); 1683 if (!Integer->isEvaluatable(S.Context)) 1684 Invalid = true; 1685 } 1686 1687 if (Invalid) 1688 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_bad_constant_discriminator); 1689 return Invalid; 1690 } 1691 1692 static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call) { 1693 if (S.checkArgCount(Call, 2)) 1694 return ExprError(); 1695 if (checkPointerAuthEnabled(S, Call)) 1696 return ExprError(); 1697 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Strip) || 1698 checkPointerAuthKey(S, Call->getArgs()[1])) 1699 return ExprError(); 1700 1701 Call->setType(Call->getArgs()[0]->getType()); 1702 return Call; 1703 } 1704 1705 static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call) { 1706 if (S.checkArgCount(Call, 2)) 1707 return ExprError(); 1708 if (checkPointerAuthEnabled(S, Call)) 1709 return ExprError(); 1710 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_BlendPointer) || 1711 checkPointerAuthValue(S, Call->getArgs()[1], PAO_BlendInteger)) 1712 return ExprError(); 1713 1714 Call->setType(S.Context.getUIntPtrType()); 1715 return Call; 1716 } 1717 1718 static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call) { 1719 if (S.checkArgCount(Call, 2)) 1720 return ExprError(); 1721 if (checkPointerAuthEnabled(S, Call)) 1722 return ExprError(); 1723 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_SignGeneric) || 1724 checkPointerAuthValue(S, Call->getArgs()[1], PAO_Discriminator)) 1725 return ExprError(); 1726 1727 Call->setType(S.Context.getUIntPtrType()); 1728 return Call; 1729 } 1730 1731 static ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call, 1732 PointerAuthOpKind OpKind, 1733 bool RequireConstant) { 1734 if (S.checkArgCount(Call, 3)) 1735 return ExprError(); 1736 if (checkPointerAuthEnabled(S, Call)) 1737 return ExprError(); 1738 if (checkPointerAuthValue(S, Call->getArgs()[0], OpKind, RequireConstant) || 1739 checkPointerAuthKey(S, Call->getArgs()[1]) || 1740 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator, 1741 RequireConstant)) 1742 return ExprError(); 1743 1744 Call->setType(Call->getArgs()[0]->getType()); 1745 return Call; 1746 } 1747 1748 static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call) { 1749 if (S.checkArgCount(Call, 5)) 1750 return ExprError(); 1751 if (checkPointerAuthEnabled(S, Call)) 1752 return ExprError(); 1753 if (checkPointerAuthValue(S, Call->getArgs()[0], PAO_Auth) || 1754 checkPointerAuthKey(S, Call->getArgs()[1]) || 1755 checkPointerAuthValue(S, Call->getArgs()[2], PAO_Discriminator) || 1756 checkPointerAuthKey(S, Call->getArgs()[3]) || 1757 checkPointerAuthValue(S, Call->getArgs()[4], PAO_Discriminator)) 1758 return ExprError(); 1759 1760 Call->setType(Call->getArgs()[0]->getType()); 1761 return Call; 1762 } 1763 1764 static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call) { 1765 if (checkPointerAuthEnabled(S, Call)) 1766 return ExprError(); 1767 1768 // We've already performed normal call type-checking. 1769 const Expr *Arg = Call->getArg(0)->IgnoreParenImpCasts(); 1770 1771 // Operand must be an ordinary or UTF-8 string literal. 1772 const auto *Literal = dyn_cast<StringLiteral>(Arg); 1773 if (!Literal || Literal->getCharByteWidth() != 1) { 1774 S.Diag(Arg->getExprLoc(), diag::err_ptrauth_string_not_literal) 1775 << (Literal ? 1 : 0) << Arg->getSourceRange(); 1776 return ExprError(); 1777 } 1778 1779 return Call; 1780 } 1781 1782 static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall) { 1783 if (S.checkArgCount(TheCall, 1)) 1784 return ExprError(); 1785 1786 // Compute __builtin_launder's parameter type from the argument. 1787 // The parameter type is: 1788 // * The type of the argument if it's not an array or function type, 1789 // Otherwise, 1790 // * The decayed argument type. 1791 QualType ParamTy = [&]() { 1792 QualType ArgTy = TheCall->getArg(0)->getType(); 1793 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1794 return S.Context.getPointerType(Ty->getElementType()); 1795 if (ArgTy->isFunctionType()) { 1796 return S.Context.getPointerType(ArgTy); 1797 } 1798 return ArgTy; 1799 }(); 1800 1801 TheCall->setType(ParamTy); 1802 1803 auto DiagSelect = [&]() -> std::optional<unsigned> { 1804 if (!ParamTy->isPointerType()) 1805 return 0; 1806 if (ParamTy->isFunctionPointerType()) 1807 return 1; 1808 if (ParamTy->isVoidPointerType()) 1809 return 2; 1810 return std::optional<unsigned>{}; 1811 }(); 1812 if (DiagSelect) { 1813 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1814 << *DiagSelect << TheCall->getSourceRange(); 1815 return ExprError(); 1816 } 1817 1818 // We either have an incomplete class type, or we have a class template 1819 // whose instantiation has not been forced. Example: 1820 // 1821 // template <class T> struct Foo { T value; }; 1822 // Foo<int> *p = nullptr; 1823 // auto *d = __builtin_launder(p); 1824 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1825 diag::err_incomplete_type)) 1826 return ExprError(); 1827 1828 assert(ParamTy->getPointeeType()->isObjectType() && 1829 "Unhandled non-object pointer case"); 1830 1831 InitializedEntity Entity = 1832 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1833 ExprResult Arg = 1834 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1835 if (Arg.isInvalid()) 1836 return ExprError(); 1837 TheCall->setArg(0, Arg.get()); 1838 1839 return TheCall; 1840 } 1841 1842 static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall) { 1843 if (S.checkArgCount(TheCall, 1)) 1844 return ExprError(); 1845 1846 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1847 if (Arg.isInvalid()) 1848 return ExprError(); 1849 QualType ParamTy = Arg.get()->getType(); 1850 TheCall->setArg(0, Arg.get()); 1851 TheCall->setType(S.Context.BoolTy); 1852 1853 // Only accept pointers to objects as arguments, which should have object 1854 // pointer or void pointer types. 1855 if (const auto *PT = ParamTy->getAs<PointerType>()) { 1856 // LWG4138: Function pointer types not allowed 1857 if (PT->getPointeeType()->isFunctionType()) { 1858 S.Diag(TheCall->getArg(0)->getExprLoc(), 1859 diag::err_builtin_is_within_lifetime_invalid_arg) 1860 << 1; 1861 return ExprError(); 1862 } 1863 // Disallow VLAs too since those shouldn't be able to 1864 // be a template parameter for `std::is_within_lifetime` 1865 if (PT->getPointeeType()->isVariableArrayType()) { 1866 S.Diag(TheCall->getArg(0)->getExprLoc(), diag::err_vla_unsupported) 1867 << 1 << "__builtin_is_within_lifetime"; 1868 return ExprError(); 1869 } 1870 } else { 1871 S.Diag(TheCall->getArg(0)->getExprLoc(), 1872 diag::err_builtin_is_within_lifetime_invalid_arg) 1873 << 0; 1874 return ExprError(); 1875 } 1876 1877 return TheCall; 1878 } 1879 1880 // Emit an error and return true if the current object format type is in the 1881 // list of unsupported types. 1882 static bool CheckBuiltinTargetNotInUnsupported( 1883 Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1884 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) { 1885 llvm::Triple::ObjectFormatType CurObjFormat = 1886 S.getASTContext().getTargetInfo().getTriple().getObjectFormat(); 1887 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) { 1888 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1889 << TheCall->getSourceRange(); 1890 return true; 1891 } 1892 return false; 1893 } 1894 1895 // Emit an error and return true if the current architecture is not in the list 1896 // of supported architectures. 1897 static bool 1898 CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall, 1899 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1900 llvm::Triple::ArchType CurArch = 1901 S.getASTContext().getTargetInfo().getTriple().getArch(); 1902 if (llvm::is_contained(SupportedArchs, CurArch)) 1903 return false; 1904 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1905 << TheCall->getSourceRange(); 1906 return true; 1907 } 1908 1909 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1910 SourceLocation CallSiteLoc); 1911 1912 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1913 CallExpr *TheCall) { 1914 switch (TI.getTriple().getArch()) { 1915 default: 1916 // Some builtins don't require additional checking, so just consider these 1917 // acceptable. 1918 return false; 1919 case llvm::Triple::arm: 1920 case llvm::Triple::armeb: 1921 case llvm::Triple::thumb: 1922 case llvm::Triple::thumbeb: 1923 return ARM().CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1924 case llvm::Triple::aarch64: 1925 case llvm::Triple::aarch64_32: 1926 case llvm::Triple::aarch64_be: 1927 return ARM().CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1928 case llvm::Triple::bpfeb: 1929 case llvm::Triple::bpfel: 1930 return BPF().CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1931 case llvm::Triple::hexagon: 1932 return Hexagon().CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1933 case llvm::Triple::mips: 1934 case llvm::Triple::mipsel: 1935 case llvm::Triple::mips64: 1936 case llvm::Triple::mips64el: 1937 return MIPS().CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1938 case llvm::Triple::spirv: 1939 return SPIRV().CheckSPIRVBuiltinFunctionCall(BuiltinID, TheCall); 1940 case llvm::Triple::systemz: 1941 return SystemZ().CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1942 case llvm::Triple::x86: 1943 case llvm::Triple::x86_64: 1944 return X86().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall); 1945 case llvm::Triple::ppc: 1946 case llvm::Triple::ppcle: 1947 case llvm::Triple::ppc64: 1948 case llvm::Triple::ppc64le: 1949 return PPC().CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1950 case llvm::Triple::amdgcn: 1951 return AMDGPU().CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1952 case llvm::Triple::riscv32: 1953 case llvm::Triple::riscv64: 1954 return RISCV().CheckBuiltinFunctionCall(TI, BuiltinID, TheCall); 1955 case llvm::Triple::loongarch32: 1956 case llvm::Triple::loongarch64: 1957 return LoongArch().CheckLoongArchBuiltinFunctionCall(TI, BuiltinID, 1958 TheCall); 1959 case llvm::Triple::wasm32: 1960 case llvm::Triple::wasm64: 1961 return Wasm().CheckWebAssemblyBuiltinFunctionCall(TI, BuiltinID, TheCall); 1962 case llvm::Triple::nvptx: 1963 case llvm::Triple::nvptx64: 1964 return NVPTX().CheckNVPTXBuiltinFunctionCall(TI, BuiltinID, TheCall); 1965 } 1966 } 1967 1968 // Check if \p Ty is a valid type for the elementwise math builtins. If it is 1969 // not a valid type, emit an error message and return true. Otherwise return 1970 // false. 1971 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, 1972 QualType ArgTy, int ArgIndex) { 1973 if (!ArgTy->getAs<VectorType>() && 1974 !ConstantMatrixType::isValidElementType(ArgTy)) { 1975 return S.Diag(Loc, diag::err_builtin_invalid_arg_type) 1976 << ArgIndex << /* vector, integer or float ty*/ 0 << ArgTy; 1977 } 1978 1979 return false; 1980 } 1981 1982 static bool checkFPMathBuiltinElementType(Sema &S, SourceLocation Loc, 1983 QualType ArgTy, int ArgIndex) { 1984 QualType EltTy = ArgTy; 1985 if (auto *VecTy = EltTy->getAs<VectorType>()) 1986 EltTy = VecTy->getElementType(); 1987 1988 if (!EltTy->isRealFloatingType()) { 1989 return S.Diag(Loc, diag::err_builtin_invalid_arg_type) 1990 << ArgIndex << /* vector or float ty*/ 5 << ArgTy; 1991 } 1992 1993 return false; 1994 } 1995 1996 /// BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *). 1997 /// This checks that the target supports the builtin and that the string 1998 /// argument is constant and valid. 1999 static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall, 2000 const TargetInfo *AuxTI, unsigned BuiltinID) { 2001 assert((BuiltinID == Builtin::BI__builtin_cpu_supports || 2002 BuiltinID == Builtin::BI__builtin_cpu_is) && 2003 "Expecting __builtin_cpu_..."); 2004 2005 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports; 2006 const TargetInfo *TheTI = &TI; 2007 auto SupportsBI = [=](const TargetInfo *TInfo) { 2008 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) || 2009 (!IsCPUSupports && TInfo->supportsCpuIs())); 2010 }; 2011 if (!SupportsBI(&TI) && SupportsBI(AuxTI)) 2012 TheTI = AuxTI; 2013 2014 if ((!IsCPUSupports && !TheTI->supportsCpuIs()) || 2015 (IsCPUSupports && !TheTI->supportsCpuSupports())) 2016 return S.Diag(TheCall->getBeginLoc(), 2017 TI.getTriple().isOSAIX() 2018 ? diag::err_builtin_aix_os_unsupported 2019 : diag::err_builtin_target_unsupported) 2020 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 2021 2022 Expr *Arg = TheCall->getArg(0)->IgnoreParenImpCasts(); 2023 // Check if the argument is a string literal. 2024 if (!isa<StringLiteral>(Arg)) 2025 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 2026 << Arg->getSourceRange(); 2027 2028 // Check the contents of the string. 2029 StringRef Feature = cast<StringLiteral>(Arg)->getString(); 2030 if (IsCPUSupports && !TheTI->validateCpuSupports(Feature)) { 2031 S.Diag(TheCall->getBeginLoc(), diag::warn_invalid_cpu_supports) 2032 << Arg->getSourceRange(); 2033 return false; 2034 } 2035 if (!IsCPUSupports && !TheTI->validateCpuIs(Feature)) 2036 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 2037 << Arg->getSourceRange(); 2038 return false; 2039 } 2040 2041 /// Checks that __builtin_popcountg was called with a single argument, which is 2042 /// an unsigned integer. 2043 static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall) { 2044 if (S.checkArgCount(TheCall, 1)) 2045 return true; 2046 2047 ExprResult ArgRes = S.DefaultLvalueConversion(TheCall->getArg(0)); 2048 if (ArgRes.isInvalid()) 2049 return true; 2050 2051 Expr *Arg = ArgRes.get(); 2052 TheCall->setArg(0, Arg); 2053 2054 QualType ArgTy = Arg->getType(); 2055 2056 if (!ArgTy->isUnsignedIntegerType()) { 2057 S.Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2058 << 1 << /*unsigned integer ty*/ 7 << ArgTy; 2059 return true; 2060 } 2061 return false; 2062 } 2063 2064 /// Checks that __builtin_{clzg,ctzg} was called with a first argument, which is 2065 /// an unsigned integer, and an optional second argument, which is promoted to 2066 /// an 'int'. 2067 static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall) { 2068 if (S.checkArgCountRange(TheCall, 1, 2)) 2069 return true; 2070 2071 ExprResult Arg0Res = S.DefaultLvalueConversion(TheCall->getArg(0)); 2072 if (Arg0Res.isInvalid()) 2073 return true; 2074 2075 Expr *Arg0 = Arg0Res.get(); 2076 TheCall->setArg(0, Arg0); 2077 2078 QualType Arg0Ty = Arg0->getType(); 2079 2080 if (!Arg0Ty->isUnsignedIntegerType()) { 2081 S.Diag(Arg0->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2082 << 1 << /*unsigned integer ty*/ 7 << Arg0Ty; 2083 return true; 2084 } 2085 2086 if (TheCall->getNumArgs() > 1) { 2087 ExprResult Arg1Res = S.UsualUnaryConversions(TheCall->getArg(1)); 2088 if (Arg1Res.isInvalid()) 2089 return true; 2090 2091 Expr *Arg1 = Arg1Res.get(); 2092 TheCall->setArg(1, Arg1); 2093 2094 QualType Arg1Ty = Arg1->getType(); 2095 2096 if (!Arg1Ty->isSpecificBuiltinType(BuiltinType::Int)) { 2097 S.Diag(Arg1->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2098 << 2 << /*'int' ty*/ 8 << Arg1Ty; 2099 return true; 2100 } 2101 } 2102 2103 return false; 2104 } 2105 2106 ExprResult 2107 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 2108 CallExpr *TheCall) { 2109 ExprResult TheCallResult(TheCall); 2110 2111 // Find out if any arguments are required to be integer constant expressions. 2112 unsigned ICEArguments = 0; 2113 ASTContext::GetBuiltinTypeError Error; 2114 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 2115 if (Error != ASTContext::GE_None) 2116 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 2117 2118 // If any arguments are required to be ICE's, check and diagnose. 2119 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 2120 // Skip arguments not required to be ICE's. 2121 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 2122 2123 llvm::APSInt Result; 2124 // If we don't have enough arguments, continue so we can issue better 2125 // diagnostic in checkArgCount(...) 2126 if (ArgNo < TheCall->getNumArgs() && 2127 BuiltinConstantArg(TheCall, ArgNo, Result)) 2128 return true; 2129 ICEArguments &= ~(1 << ArgNo); 2130 } 2131 2132 FPOptions FPO; 2133 switch (BuiltinID) { 2134 case Builtin::BI__builtin_cpu_supports: 2135 case Builtin::BI__builtin_cpu_is: 2136 if (BuiltinCpu(*this, Context.getTargetInfo(), TheCall, 2137 Context.getAuxTargetInfo(), BuiltinID)) 2138 return ExprError(); 2139 break; 2140 case Builtin::BI__builtin_cpu_init: 2141 if (!Context.getTargetInfo().supportsCpuInit()) { 2142 Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 2143 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 2144 return ExprError(); 2145 } 2146 break; 2147 case Builtin::BI__builtin___CFStringMakeConstantString: 2148 // CFStringMakeConstantString is currently not implemented for GOFF (i.e., 2149 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported 2150 if (CheckBuiltinTargetNotInUnsupported( 2151 *this, BuiltinID, TheCall, 2152 {llvm::Triple::GOFF, llvm::Triple::XCOFF})) 2153 return ExprError(); 2154 assert(TheCall->getNumArgs() == 1 && 2155 "Wrong # arguments to builtin CFStringMakeConstantString"); 2156 if (ObjC().CheckObjCString(TheCall->getArg(0))) 2157 return ExprError(); 2158 break; 2159 case Builtin::BI__builtin_ms_va_start: 2160 case Builtin::BI__builtin_stdarg_start: 2161 case Builtin::BI__builtin_va_start: 2162 if (BuiltinVAStart(BuiltinID, TheCall)) 2163 return ExprError(); 2164 break; 2165 case Builtin::BI__va_start: { 2166 switch (Context.getTargetInfo().getTriple().getArch()) { 2167 case llvm::Triple::aarch64: 2168 case llvm::Triple::arm: 2169 case llvm::Triple::thumb: 2170 if (BuiltinVAStartARMMicrosoft(TheCall)) 2171 return ExprError(); 2172 break; 2173 default: 2174 if (BuiltinVAStart(BuiltinID, TheCall)) 2175 return ExprError(); 2176 break; 2177 } 2178 break; 2179 } 2180 2181 // The acquire, release, and no fence variants are ARM and AArch64 only. 2182 case Builtin::BI_interlockedbittestandset_acq: 2183 case Builtin::BI_interlockedbittestandset_rel: 2184 case Builtin::BI_interlockedbittestandset_nf: 2185 case Builtin::BI_interlockedbittestandreset_acq: 2186 case Builtin::BI_interlockedbittestandreset_rel: 2187 case Builtin::BI_interlockedbittestandreset_nf: 2188 if (CheckBuiltinTargetInSupported( 2189 *this, TheCall, 2190 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 2191 return ExprError(); 2192 break; 2193 2194 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 2195 case Builtin::BI_bittest64: 2196 case Builtin::BI_bittestandcomplement64: 2197 case Builtin::BI_bittestandreset64: 2198 case Builtin::BI_bittestandset64: 2199 case Builtin::BI_interlockedbittestandreset64: 2200 case Builtin::BI_interlockedbittestandset64: 2201 if (CheckBuiltinTargetInSupported( 2202 *this, TheCall, 2203 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb, 2204 llvm::Triple::aarch64, llvm::Triple::amdgcn})) 2205 return ExprError(); 2206 break; 2207 2208 case Builtin::BI__builtin_set_flt_rounds: 2209 if (CheckBuiltinTargetInSupported( 2210 *this, TheCall, 2211 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm, 2212 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgcn, 2213 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle, 2214 llvm::Triple::ppc64le})) 2215 return ExprError(); 2216 break; 2217 2218 case Builtin::BI__builtin_isgreater: 2219 case Builtin::BI__builtin_isgreaterequal: 2220 case Builtin::BI__builtin_isless: 2221 case Builtin::BI__builtin_islessequal: 2222 case Builtin::BI__builtin_islessgreater: 2223 case Builtin::BI__builtin_isunordered: 2224 if (BuiltinUnorderedCompare(TheCall, BuiltinID)) 2225 return ExprError(); 2226 break; 2227 case Builtin::BI__builtin_fpclassify: 2228 if (BuiltinFPClassification(TheCall, 6, BuiltinID)) 2229 return ExprError(); 2230 break; 2231 case Builtin::BI__builtin_isfpclass: 2232 if (BuiltinFPClassification(TheCall, 2, BuiltinID)) 2233 return ExprError(); 2234 break; 2235 case Builtin::BI__builtin_isfinite: 2236 case Builtin::BI__builtin_isinf: 2237 case Builtin::BI__builtin_isinf_sign: 2238 case Builtin::BI__builtin_isnan: 2239 case Builtin::BI__builtin_issignaling: 2240 case Builtin::BI__builtin_isnormal: 2241 case Builtin::BI__builtin_issubnormal: 2242 case Builtin::BI__builtin_iszero: 2243 case Builtin::BI__builtin_signbit: 2244 case Builtin::BI__builtin_signbitf: 2245 case Builtin::BI__builtin_signbitl: 2246 if (BuiltinFPClassification(TheCall, 1, BuiltinID)) 2247 return ExprError(); 2248 break; 2249 case Builtin::BI__builtin_shufflevector: 2250 return BuiltinShuffleVector(TheCall); 2251 // TheCall will be freed by the smart pointer here, but that's fine, since 2252 // BuiltinShuffleVector guts it, but then doesn't release it. 2253 case Builtin::BI__builtin_prefetch: 2254 if (BuiltinPrefetch(TheCall)) 2255 return ExprError(); 2256 break; 2257 case Builtin::BI__builtin_alloca_with_align: 2258 case Builtin::BI__builtin_alloca_with_align_uninitialized: 2259 if (BuiltinAllocaWithAlign(TheCall)) 2260 return ExprError(); 2261 [[fallthrough]]; 2262 case Builtin::BI__builtin_alloca: 2263 case Builtin::BI__builtin_alloca_uninitialized: 2264 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 2265 << TheCall->getDirectCallee(); 2266 if (getLangOpts().OpenCL) { 2267 builtinAllocaAddrSpace(*this, TheCall); 2268 } 2269 break; 2270 case Builtin::BI__arithmetic_fence: 2271 if (BuiltinArithmeticFence(TheCall)) 2272 return ExprError(); 2273 break; 2274 case Builtin::BI__assume: 2275 case Builtin::BI__builtin_assume: 2276 if (BuiltinAssume(TheCall)) 2277 return ExprError(); 2278 break; 2279 case Builtin::BI__builtin_assume_aligned: 2280 if (BuiltinAssumeAligned(TheCall)) 2281 return ExprError(); 2282 break; 2283 case Builtin::BI__builtin_dynamic_object_size: 2284 case Builtin::BI__builtin_object_size: 2285 if (BuiltinConstantArgRange(TheCall, 1, 0, 3)) 2286 return ExprError(); 2287 break; 2288 case Builtin::BI__builtin_longjmp: 2289 if (BuiltinLongjmp(TheCall)) 2290 return ExprError(); 2291 break; 2292 case Builtin::BI__builtin_setjmp: 2293 if (BuiltinSetjmp(TheCall)) 2294 return ExprError(); 2295 break; 2296 case Builtin::BI__builtin_classify_type: 2297 if (checkArgCount(TheCall, 1)) 2298 return true; 2299 TheCall->setType(Context.IntTy); 2300 break; 2301 case Builtin::BI__builtin_complex: 2302 if (BuiltinComplex(TheCall)) 2303 return ExprError(); 2304 break; 2305 case Builtin::BI__builtin_constant_p: { 2306 if (checkArgCount(TheCall, 1)) 2307 return true; 2308 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 2309 if (Arg.isInvalid()) return true; 2310 TheCall->setArg(0, Arg.get()); 2311 TheCall->setType(Context.IntTy); 2312 break; 2313 } 2314 case Builtin::BI__builtin_launder: 2315 return BuiltinLaunder(*this, TheCall); 2316 case Builtin::BI__builtin_is_within_lifetime: 2317 return BuiltinIsWithinLifetime(*this, TheCall); 2318 case Builtin::BI__sync_fetch_and_add: 2319 case Builtin::BI__sync_fetch_and_add_1: 2320 case Builtin::BI__sync_fetch_and_add_2: 2321 case Builtin::BI__sync_fetch_and_add_4: 2322 case Builtin::BI__sync_fetch_and_add_8: 2323 case Builtin::BI__sync_fetch_and_add_16: 2324 case Builtin::BI__sync_fetch_and_sub: 2325 case Builtin::BI__sync_fetch_and_sub_1: 2326 case Builtin::BI__sync_fetch_and_sub_2: 2327 case Builtin::BI__sync_fetch_and_sub_4: 2328 case Builtin::BI__sync_fetch_and_sub_8: 2329 case Builtin::BI__sync_fetch_and_sub_16: 2330 case Builtin::BI__sync_fetch_and_or: 2331 case Builtin::BI__sync_fetch_and_or_1: 2332 case Builtin::BI__sync_fetch_and_or_2: 2333 case Builtin::BI__sync_fetch_and_or_4: 2334 case Builtin::BI__sync_fetch_and_or_8: 2335 case Builtin::BI__sync_fetch_and_or_16: 2336 case Builtin::BI__sync_fetch_and_and: 2337 case Builtin::BI__sync_fetch_and_and_1: 2338 case Builtin::BI__sync_fetch_and_and_2: 2339 case Builtin::BI__sync_fetch_and_and_4: 2340 case Builtin::BI__sync_fetch_and_and_8: 2341 case Builtin::BI__sync_fetch_and_and_16: 2342 case Builtin::BI__sync_fetch_and_xor: 2343 case Builtin::BI__sync_fetch_and_xor_1: 2344 case Builtin::BI__sync_fetch_and_xor_2: 2345 case Builtin::BI__sync_fetch_and_xor_4: 2346 case Builtin::BI__sync_fetch_and_xor_8: 2347 case Builtin::BI__sync_fetch_and_xor_16: 2348 case Builtin::BI__sync_fetch_and_nand: 2349 case Builtin::BI__sync_fetch_and_nand_1: 2350 case Builtin::BI__sync_fetch_and_nand_2: 2351 case Builtin::BI__sync_fetch_and_nand_4: 2352 case Builtin::BI__sync_fetch_and_nand_8: 2353 case Builtin::BI__sync_fetch_and_nand_16: 2354 case Builtin::BI__sync_add_and_fetch: 2355 case Builtin::BI__sync_add_and_fetch_1: 2356 case Builtin::BI__sync_add_and_fetch_2: 2357 case Builtin::BI__sync_add_and_fetch_4: 2358 case Builtin::BI__sync_add_and_fetch_8: 2359 case Builtin::BI__sync_add_and_fetch_16: 2360 case Builtin::BI__sync_sub_and_fetch: 2361 case Builtin::BI__sync_sub_and_fetch_1: 2362 case Builtin::BI__sync_sub_and_fetch_2: 2363 case Builtin::BI__sync_sub_and_fetch_4: 2364 case Builtin::BI__sync_sub_and_fetch_8: 2365 case Builtin::BI__sync_sub_and_fetch_16: 2366 case Builtin::BI__sync_and_and_fetch: 2367 case Builtin::BI__sync_and_and_fetch_1: 2368 case Builtin::BI__sync_and_and_fetch_2: 2369 case Builtin::BI__sync_and_and_fetch_4: 2370 case Builtin::BI__sync_and_and_fetch_8: 2371 case Builtin::BI__sync_and_and_fetch_16: 2372 case Builtin::BI__sync_or_and_fetch: 2373 case Builtin::BI__sync_or_and_fetch_1: 2374 case Builtin::BI__sync_or_and_fetch_2: 2375 case Builtin::BI__sync_or_and_fetch_4: 2376 case Builtin::BI__sync_or_and_fetch_8: 2377 case Builtin::BI__sync_or_and_fetch_16: 2378 case Builtin::BI__sync_xor_and_fetch: 2379 case Builtin::BI__sync_xor_and_fetch_1: 2380 case Builtin::BI__sync_xor_and_fetch_2: 2381 case Builtin::BI__sync_xor_and_fetch_4: 2382 case Builtin::BI__sync_xor_and_fetch_8: 2383 case Builtin::BI__sync_xor_and_fetch_16: 2384 case Builtin::BI__sync_nand_and_fetch: 2385 case Builtin::BI__sync_nand_and_fetch_1: 2386 case Builtin::BI__sync_nand_and_fetch_2: 2387 case Builtin::BI__sync_nand_and_fetch_4: 2388 case Builtin::BI__sync_nand_and_fetch_8: 2389 case Builtin::BI__sync_nand_and_fetch_16: 2390 case Builtin::BI__sync_val_compare_and_swap: 2391 case Builtin::BI__sync_val_compare_and_swap_1: 2392 case Builtin::BI__sync_val_compare_and_swap_2: 2393 case Builtin::BI__sync_val_compare_and_swap_4: 2394 case Builtin::BI__sync_val_compare_and_swap_8: 2395 case Builtin::BI__sync_val_compare_and_swap_16: 2396 case Builtin::BI__sync_bool_compare_and_swap: 2397 case Builtin::BI__sync_bool_compare_and_swap_1: 2398 case Builtin::BI__sync_bool_compare_and_swap_2: 2399 case Builtin::BI__sync_bool_compare_and_swap_4: 2400 case Builtin::BI__sync_bool_compare_and_swap_8: 2401 case Builtin::BI__sync_bool_compare_and_swap_16: 2402 case Builtin::BI__sync_lock_test_and_set: 2403 case Builtin::BI__sync_lock_test_and_set_1: 2404 case Builtin::BI__sync_lock_test_and_set_2: 2405 case Builtin::BI__sync_lock_test_and_set_4: 2406 case Builtin::BI__sync_lock_test_and_set_8: 2407 case Builtin::BI__sync_lock_test_and_set_16: 2408 case Builtin::BI__sync_lock_release: 2409 case Builtin::BI__sync_lock_release_1: 2410 case Builtin::BI__sync_lock_release_2: 2411 case Builtin::BI__sync_lock_release_4: 2412 case Builtin::BI__sync_lock_release_8: 2413 case Builtin::BI__sync_lock_release_16: 2414 case Builtin::BI__sync_swap: 2415 case Builtin::BI__sync_swap_1: 2416 case Builtin::BI__sync_swap_2: 2417 case Builtin::BI__sync_swap_4: 2418 case Builtin::BI__sync_swap_8: 2419 case Builtin::BI__sync_swap_16: 2420 return BuiltinAtomicOverloaded(TheCallResult); 2421 case Builtin::BI__sync_synchronize: 2422 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 2423 << TheCall->getCallee()->getSourceRange(); 2424 break; 2425 case Builtin::BI__builtin_nontemporal_load: 2426 case Builtin::BI__builtin_nontemporal_store: 2427 return BuiltinNontemporalOverloaded(TheCallResult); 2428 case Builtin::BI__builtin_memcpy_inline: { 2429 clang::Expr *SizeOp = TheCall->getArg(2); 2430 // We warn about copying to or from `nullptr` pointers when `size` is 2431 // greater than 0. When `size` is value dependent we cannot evaluate its 2432 // value so we bail out. 2433 if (SizeOp->isValueDependent()) 2434 break; 2435 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) { 2436 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 2437 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 2438 } 2439 break; 2440 } 2441 case Builtin::BI__builtin_memset_inline: { 2442 clang::Expr *SizeOp = TheCall->getArg(2); 2443 // We warn about filling to `nullptr` pointers when `size` is greater than 2444 // 0. When `size` is value dependent we cannot evaluate its value so we bail 2445 // out. 2446 if (SizeOp->isValueDependent()) 2447 break; 2448 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) 2449 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 2450 break; 2451 } 2452 #define BUILTIN(ID, TYPE, ATTRS) 2453 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 2454 case Builtin::BI##ID: \ 2455 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 2456 #include "clang/Basic/Builtins.inc" 2457 case Builtin::BI__annotation: 2458 if (BuiltinMSVCAnnotation(*this, TheCall)) 2459 return ExprError(); 2460 break; 2461 case Builtin::BI__builtin_annotation: 2462 if (BuiltinAnnotation(*this, TheCall)) 2463 return ExprError(); 2464 break; 2465 case Builtin::BI__builtin_addressof: 2466 if (BuiltinAddressof(*this, TheCall)) 2467 return ExprError(); 2468 break; 2469 case Builtin::BI__builtin_function_start: 2470 if (BuiltinFunctionStart(*this, TheCall)) 2471 return ExprError(); 2472 break; 2473 case Builtin::BI__builtin_is_aligned: 2474 case Builtin::BI__builtin_align_up: 2475 case Builtin::BI__builtin_align_down: 2476 if (BuiltinAlignment(*this, TheCall, BuiltinID)) 2477 return ExprError(); 2478 break; 2479 case Builtin::BI__builtin_add_overflow: 2480 case Builtin::BI__builtin_sub_overflow: 2481 case Builtin::BI__builtin_mul_overflow: 2482 if (BuiltinOverflow(*this, TheCall, BuiltinID)) 2483 return ExprError(); 2484 break; 2485 case Builtin::BI__builtin_operator_new: 2486 case Builtin::BI__builtin_operator_delete: { 2487 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 2488 ExprResult Res = 2489 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 2490 if (Res.isInvalid()) 2491 CorrectDelayedTyposInExpr(TheCallResult.get()); 2492 return Res; 2493 } 2494 case Builtin::BI__builtin_dump_struct: 2495 return BuiltinDumpStruct(*this, TheCall); 2496 case Builtin::BI__builtin_expect_with_probability: { 2497 // We first want to ensure we are called with 3 arguments 2498 if (checkArgCount(TheCall, 3)) 2499 return ExprError(); 2500 // then check probability is constant float in range [0.0, 1.0] 2501 const Expr *ProbArg = TheCall->getArg(2); 2502 SmallVector<PartialDiagnosticAt, 8> Notes; 2503 Expr::EvalResult Eval; 2504 Eval.Diag = &Notes; 2505 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 2506 !Eval.Val.isFloat()) { 2507 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 2508 << ProbArg->getSourceRange(); 2509 for (const PartialDiagnosticAt &PDiag : Notes) 2510 Diag(PDiag.first, PDiag.second); 2511 return ExprError(); 2512 } 2513 llvm::APFloat Probability = Eval.Val.getFloat(); 2514 bool LoseInfo = false; 2515 Probability.convert(llvm::APFloat::IEEEdouble(), 2516 llvm::RoundingMode::Dynamic, &LoseInfo); 2517 if (!(Probability >= llvm::APFloat(0.0) && 2518 Probability <= llvm::APFloat(1.0))) { 2519 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 2520 << ProbArg->getSourceRange(); 2521 return ExprError(); 2522 } 2523 break; 2524 } 2525 case Builtin::BI__builtin_preserve_access_index: 2526 if (BuiltinPreserveAI(*this, TheCall)) 2527 return ExprError(); 2528 break; 2529 case Builtin::BI__builtin_call_with_static_chain: 2530 if (BuiltinCallWithStaticChain(*this, TheCall)) 2531 return ExprError(); 2532 break; 2533 case Builtin::BI__exception_code: 2534 case Builtin::BI_exception_code: 2535 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 2536 diag::err_seh___except_block)) 2537 return ExprError(); 2538 break; 2539 case Builtin::BI__exception_info: 2540 case Builtin::BI_exception_info: 2541 if (BuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 2542 diag::err_seh___except_filter)) 2543 return ExprError(); 2544 break; 2545 case Builtin::BI__GetExceptionInfo: 2546 if (checkArgCount(TheCall, 1)) 2547 return ExprError(); 2548 2549 if (CheckCXXThrowOperand( 2550 TheCall->getBeginLoc(), 2551 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 2552 TheCall)) 2553 return ExprError(); 2554 2555 TheCall->setType(Context.VoidPtrTy); 2556 break; 2557 case Builtin::BIaddressof: 2558 case Builtin::BI__addressof: 2559 case Builtin::BIforward: 2560 case Builtin::BIforward_like: 2561 case Builtin::BImove: 2562 case Builtin::BImove_if_noexcept: 2563 case Builtin::BIas_const: { 2564 // These are all expected to be of the form 2565 // T &/&&/* f(U &/&&) 2566 // where T and U only differ in qualification. 2567 if (checkArgCount(TheCall, 1)) 2568 return ExprError(); 2569 QualType Param = FDecl->getParamDecl(0)->getType(); 2570 QualType Result = FDecl->getReturnType(); 2571 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof || 2572 BuiltinID == Builtin::BI__addressof; 2573 if (!(Param->isReferenceType() && 2574 (ReturnsPointer ? Result->isAnyPointerType() 2575 : Result->isReferenceType()) && 2576 Context.hasSameUnqualifiedType(Param->getPointeeType(), 2577 Result->getPointeeType()))) { 2578 Diag(TheCall->getBeginLoc(), diag::err_builtin_move_forward_unsupported) 2579 << FDecl; 2580 return ExprError(); 2581 } 2582 break; 2583 } 2584 case Builtin::BI__builtin_ptrauth_strip: 2585 return PointerAuthStrip(*this, TheCall); 2586 case Builtin::BI__builtin_ptrauth_blend_discriminator: 2587 return PointerAuthBlendDiscriminator(*this, TheCall); 2588 case Builtin::BI__builtin_ptrauth_sign_constant: 2589 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign, 2590 /*RequireConstant=*/true); 2591 case Builtin::BI__builtin_ptrauth_sign_unauthenticated: 2592 return PointerAuthSignOrAuth(*this, TheCall, PAO_Sign, 2593 /*RequireConstant=*/false); 2594 case Builtin::BI__builtin_ptrauth_auth: 2595 return PointerAuthSignOrAuth(*this, TheCall, PAO_Auth, 2596 /*RequireConstant=*/false); 2597 case Builtin::BI__builtin_ptrauth_sign_generic_data: 2598 return PointerAuthSignGenericData(*this, TheCall); 2599 case Builtin::BI__builtin_ptrauth_auth_and_resign: 2600 return PointerAuthAuthAndResign(*this, TheCall); 2601 case Builtin::BI__builtin_ptrauth_string_discriminator: 2602 return PointerAuthStringDiscriminator(*this, TheCall); 2603 // OpenCL v2.0, s6.13.16 - Pipe functions 2604 case Builtin::BIread_pipe: 2605 case Builtin::BIwrite_pipe: 2606 // Since those two functions are declared with var args, we need a semantic 2607 // check for the argument. 2608 if (OpenCL().checkBuiltinRWPipe(TheCall)) 2609 return ExprError(); 2610 break; 2611 case Builtin::BIreserve_read_pipe: 2612 case Builtin::BIreserve_write_pipe: 2613 case Builtin::BIwork_group_reserve_read_pipe: 2614 case Builtin::BIwork_group_reserve_write_pipe: 2615 if (OpenCL().checkBuiltinReserveRWPipe(TheCall)) 2616 return ExprError(); 2617 break; 2618 case Builtin::BIsub_group_reserve_read_pipe: 2619 case Builtin::BIsub_group_reserve_write_pipe: 2620 if (OpenCL().checkSubgroupExt(TheCall) || 2621 OpenCL().checkBuiltinReserveRWPipe(TheCall)) 2622 return ExprError(); 2623 break; 2624 case Builtin::BIcommit_read_pipe: 2625 case Builtin::BIcommit_write_pipe: 2626 case Builtin::BIwork_group_commit_read_pipe: 2627 case Builtin::BIwork_group_commit_write_pipe: 2628 if (OpenCL().checkBuiltinCommitRWPipe(TheCall)) 2629 return ExprError(); 2630 break; 2631 case Builtin::BIsub_group_commit_read_pipe: 2632 case Builtin::BIsub_group_commit_write_pipe: 2633 if (OpenCL().checkSubgroupExt(TheCall) || 2634 OpenCL().checkBuiltinCommitRWPipe(TheCall)) 2635 return ExprError(); 2636 break; 2637 case Builtin::BIget_pipe_num_packets: 2638 case Builtin::BIget_pipe_max_packets: 2639 if (OpenCL().checkBuiltinPipePackets(TheCall)) 2640 return ExprError(); 2641 break; 2642 case Builtin::BIto_global: 2643 case Builtin::BIto_local: 2644 case Builtin::BIto_private: 2645 if (OpenCL().checkBuiltinToAddr(BuiltinID, TheCall)) 2646 return ExprError(); 2647 break; 2648 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 2649 case Builtin::BIenqueue_kernel: 2650 if (OpenCL().checkBuiltinEnqueueKernel(TheCall)) 2651 return ExprError(); 2652 break; 2653 case Builtin::BIget_kernel_work_group_size: 2654 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 2655 if (OpenCL().checkBuiltinKernelWorkGroupSize(TheCall)) 2656 return ExprError(); 2657 break; 2658 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 2659 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 2660 if (OpenCL().checkBuiltinNDRangeAndBlock(TheCall)) 2661 return ExprError(); 2662 break; 2663 case Builtin::BI__builtin_os_log_format: 2664 Cleanup.setExprNeedsCleanups(true); 2665 [[fallthrough]]; 2666 case Builtin::BI__builtin_os_log_format_buffer_size: 2667 if (BuiltinOSLogFormat(TheCall)) 2668 return ExprError(); 2669 break; 2670 case Builtin::BI__builtin_frame_address: 2671 case Builtin::BI__builtin_return_address: { 2672 if (BuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 2673 return ExprError(); 2674 2675 // -Wframe-address warning if non-zero passed to builtin 2676 // return/frame address. 2677 Expr::EvalResult Result; 2678 if (!TheCall->getArg(0)->isValueDependent() && 2679 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 2680 Result.Val.getInt() != 0) 2681 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 2682 << ((BuiltinID == Builtin::BI__builtin_return_address) 2683 ? "__builtin_return_address" 2684 : "__builtin_frame_address") 2685 << TheCall->getSourceRange(); 2686 break; 2687 } 2688 2689 case Builtin::BI__builtin_nondeterministic_value: { 2690 if (BuiltinNonDeterministicValue(TheCall)) 2691 return ExprError(); 2692 break; 2693 } 2694 2695 // __builtin_elementwise_abs restricts the element type to signed integers or 2696 // floating point types only. 2697 case Builtin::BI__builtin_elementwise_abs: { 2698 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall)) 2699 return ExprError(); 2700 2701 QualType ArgTy = TheCall->getArg(0)->getType(); 2702 QualType EltTy = ArgTy; 2703 2704 if (auto *VecTy = EltTy->getAs<VectorType>()) 2705 EltTy = VecTy->getElementType(); 2706 if (EltTy->isUnsignedIntegerType()) { 2707 Diag(TheCall->getArg(0)->getBeginLoc(), 2708 diag::err_builtin_invalid_arg_type) 2709 << 1 << /* signed integer or float ty*/ 3 << ArgTy; 2710 return ExprError(); 2711 } 2712 break; 2713 } 2714 2715 // These builtins restrict the element type to floating point 2716 // types only. 2717 case Builtin::BI__builtin_elementwise_acos: 2718 case Builtin::BI__builtin_elementwise_asin: 2719 case Builtin::BI__builtin_elementwise_atan: 2720 case Builtin::BI__builtin_elementwise_ceil: 2721 case Builtin::BI__builtin_elementwise_cos: 2722 case Builtin::BI__builtin_elementwise_cosh: 2723 case Builtin::BI__builtin_elementwise_exp: 2724 case Builtin::BI__builtin_elementwise_exp2: 2725 case Builtin::BI__builtin_elementwise_floor: 2726 case Builtin::BI__builtin_elementwise_log: 2727 case Builtin::BI__builtin_elementwise_log2: 2728 case Builtin::BI__builtin_elementwise_log10: 2729 case Builtin::BI__builtin_elementwise_roundeven: 2730 case Builtin::BI__builtin_elementwise_round: 2731 case Builtin::BI__builtin_elementwise_rint: 2732 case Builtin::BI__builtin_elementwise_nearbyint: 2733 case Builtin::BI__builtin_elementwise_sin: 2734 case Builtin::BI__builtin_elementwise_sinh: 2735 case Builtin::BI__builtin_elementwise_sqrt: 2736 case Builtin::BI__builtin_elementwise_tan: 2737 case Builtin::BI__builtin_elementwise_tanh: 2738 case Builtin::BI__builtin_elementwise_trunc: 2739 case Builtin::BI__builtin_elementwise_canonicalize: { 2740 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall)) 2741 return ExprError(); 2742 2743 QualType ArgTy = TheCall->getArg(0)->getType(); 2744 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(), 2745 ArgTy, 1)) 2746 return ExprError(); 2747 break; 2748 } 2749 case Builtin::BI__builtin_elementwise_fma: { 2750 if (BuiltinElementwiseTernaryMath(TheCall)) 2751 return ExprError(); 2752 break; 2753 } 2754 2755 // These builtins restrict the element type to floating point 2756 // types only, and take in two arguments. 2757 case Builtin::BI__builtin_elementwise_minimum: 2758 case Builtin::BI__builtin_elementwise_maximum: 2759 case Builtin::BI__builtin_elementwise_atan2: 2760 case Builtin::BI__builtin_elementwise_fmod: 2761 case Builtin::BI__builtin_elementwise_pow: { 2762 if (BuiltinElementwiseMath(TheCall, /*FPOnly=*/true)) 2763 return ExprError(); 2764 break; 2765 } 2766 2767 // These builtins restrict the element type to integer 2768 // types only. 2769 case Builtin::BI__builtin_elementwise_add_sat: 2770 case Builtin::BI__builtin_elementwise_sub_sat: { 2771 if (BuiltinElementwiseMath(TheCall)) 2772 return ExprError(); 2773 2774 const Expr *Arg = TheCall->getArg(0); 2775 QualType ArgTy = Arg->getType(); 2776 QualType EltTy = ArgTy; 2777 2778 if (auto *VecTy = EltTy->getAs<VectorType>()) 2779 EltTy = VecTy->getElementType(); 2780 2781 if (!EltTy->isIntegerType()) { 2782 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2783 << 1 << /* integer ty */ 6 << ArgTy; 2784 return ExprError(); 2785 } 2786 break; 2787 } 2788 2789 case Builtin::BI__builtin_elementwise_min: 2790 case Builtin::BI__builtin_elementwise_max: 2791 if (BuiltinElementwiseMath(TheCall)) 2792 return ExprError(); 2793 break; 2794 case Builtin::BI__builtin_elementwise_popcount: 2795 case Builtin::BI__builtin_elementwise_bitreverse: { 2796 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall)) 2797 return ExprError(); 2798 2799 const Expr *Arg = TheCall->getArg(0); 2800 QualType ArgTy = Arg->getType(); 2801 QualType EltTy = ArgTy; 2802 2803 if (auto *VecTy = EltTy->getAs<VectorType>()) 2804 EltTy = VecTy->getElementType(); 2805 2806 if (!EltTy->isIntegerType()) { 2807 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2808 << 1 << /* integer ty */ 6 << ArgTy; 2809 return ExprError(); 2810 } 2811 break; 2812 } 2813 2814 case Builtin::BI__builtin_elementwise_copysign: { 2815 if (checkArgCount(TheCall, 2)) 2816 return ExprError(); 2817 2818 ExprResult Magnitude = UsualUnaryConversions(TheCall->getArg(0)); 2819 ExprResult Sign = UsualUnaryConversions(TheCall->getArg(1)); 2820 if (Magnitude.isInvalid() || Sign.isInvalid()) 2821 return ExprError(); 2822 2823 QualType MagnitudeTy = Magnitude.get()->getType(); 2824 QualType SignTy = Sign.get()->getType(); 2825 if (checkFPMathBuiltinElementType(*this, TheCall->getArg(0)->getBeginLoc(), 2826 MagnitudeTy, 1) || 2827 checkFPMathBuiltinElementType(*this, TheCall->getArg(1)->getBeginLoc(), 2828 SignTy, 2)) { 2829 return ExprError(); 2830 } 2831 2832 if (MagnitudeTy.getCanonicalType() != SignTy.getCanonicalType()) { 2833 return Diag(Sign.get()->getBeginLoc(), 2834 diag::err_typecheck_call_different_arg_types) 2835 << MagnitudeTy << SignTy; 2836 } 2837 2838 TheCall->setArg(0, Magnitude.get()); 2839 TheCall->setArg(1, Sign.get()); 2840 TheCall->setType(Magnitude.get()->getType()); 2841 break; 2842 } 2843 case Builtin::BI__builtin_reduce_max: 2844 case Builtin::BI__builtin_reduce_min: { 2845 if (PrepareBuiltinReduceMathOneArgCall(TheCall)) 2846 return ExprError(); 2847 2848 const Expr *Arg = TheCall->getArg(0); 2849 const auto *TyA = Arg->getType()->getAs<VectorType>(); 2850 2851 QualType ElTy; 2852 if (TyA) 2853 ElTy = TyA->getElementType(); 2854 else if (Arg->getType()->isSizelessVectorType()) 2855 ElTy = Arg->getType()->getSizelessVectorEltType(Context); 2856 2857 if (ElTy.isNull()) { 2858 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2859 << 1 << /* vector ty*/ 4 << Arg->getType(); 2860 return ExprError(); 2861 } 2862 2863 TheCall->setType(ElTy); 2864 break; 2865 } 2866 case Builtin::BI__builtin_reduce_maximum: 2867 case Builtin::BI__builtin_reduce_minimum: { 2868 if (PrepareBuiltinReduceMathOneArgCall(TheCall)) 2869 return ExprError(); 2870 2871 const Expr *Arg = TheCall->getArg(0); 2872 const auto *TyA = Arg->getType()->getAs<VectorType>(); 2873 2874 QualType ElTy; 2875 if (TyA) 2876 ElTy = TyA->getElementType(); 2877 else if (Arg->getType()->isSizelessVectorType()) 2878 ElTy = Arg->getType()->getSizelessVectorEltType(Context); 2879 2880 if (ElTy.isNull() || !ElTy->isFloatingType()) { 2881 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2882 << 1 << /* vector of floating points */ 9 << Arg->getType(); 2883 return ExprError(); 2884 } 2885 2886 TheCall->setType(ElTy); 2887 break; 2888 } 2889 2890 // These builtins support vectors of integers only. 2891 // TODO: ADD/MUL should support floating-point types. 2892 case Builtin::BI__builtin_reduce_add: 2893 case Builtin::BI__builtin_reduce_mul: 2894 case Builtin::BI__builtin_reduce_xor: 2895 case Builtin::BI__builtin_reduce_or: 2896 case Builtin::BI__builtin_reduce_and: { 2897 if (PrepareBuiltinReduceMathOneArgCall(TheCall)) 2898 return ExprError(); 2899 2900 const Expr *Arg = TheCall->getArg(0); 2901 const auto *TyA = Arg->getType()->getAs<VectorType>(); 2902 2903 QualType ElTy; 2904 if (TyA) 2905 ElTy = TyA->getElementType(); 2906 else if (Arg->getType()->isSizelessVectorType()) 2907 ElTy = Arg->getType()->getSizelessVectorEltType(Context); 2908 2909 if (ElTy.isNull() || !ElTy->isIntegerType()) { 2910 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2911 << 1 << /* vector of integers */ 6 << Arg->getType(); 2912 return ExprError(); 2913 } 2914 2915 TheCall->setType(ElTy); 2916 break; 2917 } 2918 2919 case Builtin::BI__builtin_matrix_transpose: 2920 return BuiltinMatrixTranspose(TheCall, TheCallResult); 2921 2922 case Builtin::BI__builtin_matrix_column_major_load: 2923 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 2924 2925 case Builtin::BI__builtin_matrix_column_major_store: 2926 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 2927 2928 case Builtin::BI__builtin_verbose_trap: 2929 if (!checkBuiltinVerboseTrap(TheCall, *this)) 2930 return ExprError(); 2931 break; 2932 2933 case Builtin::BI__builtin_get_device_side_mangled_name: { 2934 auto Check = [](CallExpr *TheCall) { 2935 if (TheCall->getNumArgs() != 1) 2936 return false; 2937 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 2938 if (!DRE) 2939 return false; 2940 auto *D = DRE->getDecl(); 2941 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 2942 return false; 2943 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 2944 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2945 }; 2946 if (!Check(TheCall)) { 2947 Diag(TheCall->getBeginLoc(), 2948 diag::err_hip_invalid_args_builtin_mangled_name); 2949 return ExprError(); 2950 } 2951 break; 2952 } 2953 case Builtin::BI__builtin_popcountg: 2954 if (BuiltinPopcountg(*this, TheCall)) 2955 return ExprError(); 2956 break; 2957 case Builtin::BI__builtin_clzg: 2958 case Builtin::BI__builtin_ctzg: 2959 if (BuiltinCountZeroBitsGeneric(*this, TheCall)) 2960 return ExprError(); 2961 break; 2962 2963 case Builtin::BI__builtin_allow_runtime_check: { 2964 Expr *Arg = TheCall->getArg(0); 2965 // Check if the argument is a string literal. 2966 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) { 2967 Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 2968 << Arg->getSourceRange(); 2969 return ExprError(); 2970 } 2971 break; 2972 } 2973 case Builtin::BI__builtin_counted_by_ref: 2974 if (BuiltinCountedByRef(TheCall)) 2975 return ExprError(); 2976 break; 2977 } 2978 2979 if (getLangOpts().HLSL && HLSL().CheckBuiltinFunctionCall(BuiltinID, TheCall)) 2980 return ExprError(); 2981 2982 // Since the target specific builtins for each arch overlap, only check those 2983 // of the arch we are compiling for. 2984 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2985 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2986 assert(Context.getAuxTargetInfo() && 2987 "Aux Target Builtin, but not an aux target?"); 2988 2989 if (CheckTSBuiltinFunctionCall( 2990 *Context.getAuxTargetInfo(), 2991 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2992 return ExprError(); 2993 } else { 2994 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2995 TheCall)) 2996 return ExprError(); 2997 } 2998 } 2999 3000 return TheCallResult; 3001 } 3002 3003 bool Sema::ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3004 llvm::APSInt Result; 3005 // We can't check the value of a dependent argument. 3006 Expr *Arg = TheCall->getArg(ArgNum); 3007 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3008 return false; 3009 3010 // Check constant-ness first. 3011 if (BuiltinConstantArg(TheCall, ArgNum, Result)) 3012 return true; 3013 3014 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3015 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3016 return false; 3017 3018 return Diag(TheCall->getBeginLoc(), 3019 diag::err_argument_not_contiguous_bit_field) 3020 << ArgNum << Arg->getSourceRange(); 3021 } 3022 3023 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3024 bool IsVariadic, FormatStringInfo *FSI) { 3025 if (Format->getFirstArg() == 0) 3026 FSI->ArgPassingKind = FAPK_VAList; 3027 else if (IsVariadic) 3028 FSI->ArgPassingKind = FAPK_Variadic; 3029 else 3030 FSI->ArgPassingKind = FAPK_Fixed; 3031 FSI->FormatIdx = Format->getFormatIdx() - 1; 3032 FSI->FirstDataArg = 3033 FSI->ArgPassingKind == FAPK_VAList ? 0 : Format->getFirstArg() - 1; 3034 3035 // The way the format attribute works in GCC, the implicit this argument 3036 // of member functions is counted. However, it doesn't appear in our own 3037 // lists, so decrement format_idx in that case. 3038 if (IsCXXMember) { 3039 if(FSI->FormatIdx == 0) 3040 return false; 3041 --FSI->FormatIdx; 3042 if (FSI->FirstDataArg != 0) 3043 --FSI->FirstDataArg; 3044 } 3045 return true; 3046 } 3047 3048 /// Checks if a the given expression evaluates to null. 3049 /// 3050 /// Returns true if the value evaluates to null. 3051 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3052 // Treat (smart) pointers constructed from nullptr as null, whether we can 3053 // const-evaluate them or not. 3054 // This must happen first: the smart pointer expr might have _Nonnull type! 3055 if (isa<CXXNullPtrLiteralExpr>( 3056 IgnoreExprNodes(Expr, IgnoreImplicitAsWrittenSingleStep, 3057 IgnoreElidableImplicitConstructorSingleStep))) 3058 return true; 3059 3060 // If the expression has non-null type, it doesn't evaluate to null. 3061 if (auto nullability = Expr->IgnoreImplicit()->getType()->getNullability()) { 3062 if (*nullability == NullabilityKind::NonNull) 3063 return false; 3064 } 3065 3066 // As a special case, transparent unions initialized with zero are 3067 // considered null for the purposes of the nonnull attribute. 3068 if (const RecordType *UT = Expr->getType()->getAsUnionType(); 3069 UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) { 3070 if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(Expr)) 3071 if (const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer())) 3072 Expr = ILE->getInit(0); 3073 } 3074 3075 bool Result; 3076 return (!Expr->isValueDependent() && 3077 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3078 !Result); 3079 } 3080 3081 static void CheckNonNullArgument(Sema &S, 3082 const Expr *ArgExpr, 3083 SourceLocation CallSiteLoc) { 3084 if (CheckNonNullExpr(S, ArgExpr)) 3085 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3086 S.PDiag(diag::warn_null_arg) 3087 << ArgExpr->getSourceRange()); 3088 } 3089 3090 /// Determine whether the given type has a non-null nullability annotation. 3091 static bool isNonNullType(QualType type) { 3092 if (auto nullability = type->getNullability()) 3093 return *nullability == NullabilityKind::NonNull; 3094 3095 return false; 3096 } 3097 3098 static void CheckNonNullArguments(Sema &S, 3099 const NamedDecl *FDecl, 3100 const FunctionProtoType *Proto, 3101 ArrayRef<const Expr *> Args, 3102 SourceLocation CallSiteLoc) { 3103 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3104 3105 // Already checked by constant evaluator. 3106 if (S.isConstantEvaluatedContext()) 3107 return; 3108 // Check the attributes attached to the method/function itself. 3109 llvm::SmallBitVector NonNullArgs; 3110 if (FDecl) { 3111 // Handle the nonnull attribute on the function/method declaration itself. 3112 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 3113 if (!NonNull->args_size()) { 3114 // Easy case: all pointer arguments are nonnull. 3115 for (const auto *Arg : Args) 3116 if (S.isValidPointerAttrType(Arg->getType())) 3117 CheckNonNullArgument(S, Arg, CallSiteLoc); 3118 return; 3119 } 3120 3121 for (const ParamIdx &Idx : NonNull->args()) { 3122 unsigned IdxAST = Idx.getASTIndex(); 3123 if (IdxAST >= Args.size()) 3124 continue; 3125 if (NonNullArgs.empty()) 3126 NonNullArgs.resize(Args.size()); 3127 NonNullArgs.set(IdxAST); 3128 } 3129 } 3130 } 3131 3132 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 3133 // Handle the nonnull attribute on the parameters of the 3134 // function/method. 3135 ArrayRef<ParmVarDecl*> parms; 3136 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 3137 parms = FD->parameters(); 3138 else 3139 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 3140 3141 unsigned ParamIndex = 0; 3142 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 3143 I != E; ++I, ++ParamIndex) { 3144 const ParmVarDecl *PVD = *I; 3145 if (PVD->hasAttr<NonNullAttr>() || isNonNullType(PVD->getType())) { 3146 if (NonNullArgs.empty()) 3147 NonNullArgs.resize(Args.size()); 3148 3149 NonNullArgs.set(ParamIndex); 3150 } 3151 } 3152 } else { 3153 // If we have a non-function, non-method declaration but no 3154 // function prototype, try to dig out the function prototype. 3155 if (!Proto) { 3156 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 3157 QualType type = VD->getType().getNonReferenceType(); 3158 if (auto pointerType = type->getAs<PointerType>()) 3159 type = pointerType->getPointeeType(); 3160 else if (auto blockType = type->getAs<BlockPointerType>()) 3161 type = blockType->getPointeeType(); 3162 // FIXME: data member pointers? 3163 3164 // Dig out the function prototype, if there is one. 3165 Proto = type->getAs<FunctionProtoType>(); 3166 } 3167 } 3168 3169 // Fill in non-null argument information from the nullability 3170 // information on the parameter types (if we have them). 3171 if (Proto) { 3172 unsigned Index = 0; 3173 for (auto paramType : Proto->getParamTypes()) { 3174 if (isNonNullType(paramType)) { 3175 if (NonNullArgs.empty()) 3176 NonNullArgs.resize(Args.size()); 3177 3178 NonNullArgs.set(Index); 3179 } 3180 3181 ++Index; 3182 } 3183 } 3184 } 3185 3186 // Check for non-null arguments. 3187 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 3188 ArgIndex != ArgIndexEnd; ++ArgIndex) { 3189 if (NonNullArgs[ArgIndex]) 3190 CheckNonNullArgument(S, Args[ArgIndex], Args[ArgIndex]->getExprLoc()); 3191 } 3192 } 3193 3194 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 3195 StringRef ParamName, QualType ArgTy, 3196 QualType ParamTy) { 3197 3198 // If a function accepts a pointer or reference type 3199 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 3200 return; 3201 3202 // If the parameter is a pointer type, get the pointee type for the 3203 // argument too. If the parameter is a reference type, don't try to get 3204 // the pointee type for the argument. 3205 if (ParamTy->isPointerType()) 3206 ArgTy = ArgTy->getPointeeType(); 3207 3208 // Remove reference or pointer 3209 ParamTy = ParamTy->getPointeeType(); 3210 3211 // Find expected alignment, and the actual alignment of the passed object. 3212 // getTypeAlignInChars requires complete types 3213 if (ArgTy.isNull() || ParamTy->isDependentType() || 3214 ParamTy->isIncompleteType() || ArgTy->isIncompleteType() || 3215 ParamTy->isUndeducedType() || ArgTy->isUndeducedType()) 3216 return; 3217 3218 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 3219 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 3220 3221 // If the argument is less aligned than the parameter, there is a 3222 // potential alignment issue. 3223 if (ArgAlign < ParamAlign) 3224 Diag(Loc, diag::warn_param_mismatched_alignment) 3225 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 3226 << ParamName << (FDecl != nullptr) << FDecl; 3227 } 3228 3229 void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction, 3230 const Expr *ThisArg, 3231 ArrayRef<const Expr *> Args) { 3232 if (!FD || Args.empty()) 3233 return; 3234 auto GetArgAt = [&](int Idx) -> const Expr * { 3235 if (Idx == LifetimeCaptureByAttr::GLOBAL || 3236 Idx == LifetimeCaptureByAttr::UNKNOWN) 3237 return nullptr; 3238 if (IsMemberFunction && Idx == 0) 3239 return ThisArg; 3240 return Args[Idx - IsMemberFunction]; 3241 }; 3242 auto HandleCaptureByAttr = [&](const LifetimeCaptureByAttr *Attr, 3243 unsigned ArgIdx) { 3244 if (!Attr) 3245 return; 3246 3247 Expr *Captured = const_cast<Expr *>(GetArgAt(ArgIdx)); 3248 for (int CapturingParamIdx : Attr->params()) { 3249 // lifetime_capture_by(this) case is handled in the lifetimebound expr 3250 // initialization codepath. 3251 if (CapturingParamIdx == LifetimeCaptureByAttr::THIS && 3252 isa<CXXConstructorDecl>(FD)) 3253 continue; 3254 Expr *Capturing = const_cast<Expr *>(GetArgAt(CapturingParamIdx)); 3255 CapturingEntity CE{Capturing}; 3256 // Ensure that 'Captured' outlives the 'Capturing' entity. 3257 checkCaptureByLifetime(*this, CE, Captured); 3258 } 3259 }; 3260 for (unsigned I = 0; I < FD->getNumParams(); ++I) 3261 HandleCaptureByAttr(FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>(), 3262 I + IsMemberFunction); 3263 // Check when the implicit object param is captured. 3264 if (IsMemberFunction) { 3265 TypeSourceInfo *TSI = FD->getTypeSourceInfo(); 3266 if (!TSI) 3267 return; 3268 AttributedTypeLoc ATL; 3269 for (TypeLoc TL = TSI->getTypeLoc(); 3270 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 3271 TL = ATL.getModifiedLoc()) 3272 HandleCaptureByAttr(ATL.getAttrAs<LifetimeCaptureByAttr>(), 0); 3273 } 3274 } 3275 3276 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 3277 const Expr *ThisArg, ArrayRef<const Expr *> Args, 3278 bool IsMemberFunction, SourceLocation Loc, 3279 SourceRange Range, VariadicCallType CallType) { 3280 // FIXME: We should check as much as we can in the template definition. 3281 if (CurContext->isDependentContext()) 3282 return; 3283 3284 // Printf and scanf checking. 3285 llvm::SmallBitVector CheckedVarArgs; 3286 if (FDecl) { 3287 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3288 // Only create vector if there are format attributes. 3289 CheckedVarArgs.resize(Args.size()); 3290 3291 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 3292 CheckedVarArgs); 3293 } 3294 } 3295 3296 // Refuse POD arguments that weren't caught by the format string 3297 // checks above. 3298 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 3299 if (CallType != VariadicDoesNotApply && 3300 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 3301 unsigned NumParams = Proto ? Proto->getNumParams() 3302 : isa_and_nonnull<FunctionDecl>(FDecl) 3303 ? cast<FunctionDecl>(FDecl)->getNumParams() 3304 : isa_and_nonnull<ObjCMethodDecl>(FDecl) 3305 ? cast<ObjCMethodDecl>(FDecl)->param_size() 3306 : 0; 3307 3308 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 3309 // Args[ArgIdx] can be null in malformed code. 3310 if (const Expr *Arg = Args[ArgIdx]) { 3311 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 3312 checkVariadicArgument(Arg, CallType); 3313 } 3314 } 3315 } 3316 if (FD) 3317 checkLifetimeCaptureBy(FD, IsMemberFunction, ThisArg, Args); 3318 if (FDecl || Proto) { 3319 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 3320 3321 // Type safety checking. 3322 if (FDecl) { 3323 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 3324 CheckArgumentWithTypeTag(I, Args, Loc); 3325 } 3326 } 3327 3328 // Check that passed arguments match the alignment of original arguments. 3329 // Try to get the missing prototype from the declaration. 3330 if (!Proto && FDecl) { 3331 const auto *FT = FDecl->getFunctionType(); 3332 if (isa_and_nonnull<FunctionProtoType>(FT)) 3333 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 3334 } 3335 if (Proto) { 3336 // For variadic functions, we may have more args than parameters. 3337 // For some K&R functions, we may have less args than parameters. 3338 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 3339 bool IsScalableRet = Proto->getReturnType()->isSizelessVectorType(); 3340 bool IsScalableArg = false; 3341 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 3342 // Args[ArgIdx] can be null in malformed code. 3343 if (const Expr *Arg = Args[ArgIdx]) { 3344 if (Arg->containsErrors()) 3345 continue; 3346 3347 if (Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg && 3348 FDecl->hasLinkage() && 3349 FDecl->getFormalLinkage() != Linkage::Internal && 3350 CallType == VariadicDoesNotApply) 3351 PPC().checkAIXMemberAlignment((Arg->getExprLoc()), Arg); 3352 3353 QualType ParamTy = Proto->getParamType(ArgIdx); 3354 if (ParamTy->isSizelessVectorType()) 3355 IsScalableArg = true; 3356 QualType ArgTy = Arg->getType(); 3357 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 3358 ArgTy, ParamTy); 3359 } 3360 } 3361 3362 // If the callee has an AArch64 SME attribute to indicate that it is an 3363 // __arm_streaming function, then the caller requires SME to be available. 3364 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo(); 3365 if (ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask) { 3366 if (auto *CallerFD = dyn_cast<FunctionDecl>(CurContext)) { 3367 llvm::StringMap<bool> CallerFeatureMap; 3368 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD); 3369 if (!CallerFeatureMap.contains("sme")) 3370 Diag(Loc, diag::err_sme_call_in_non_sme_target); 3371 } else if (!Context.getTargetInfo().hasFeature("sme")) { 3372 Diag(Loc, diag::err_sme_call_in_non_sme_target); 3373 } 3374 } 3375 3376 // If the call requires a streaming-mode change and has scalable vector 3377 // arguments or return values, then warn the user that the streaming and 3378 // non-streaming vector lengths may be different. 3379 const auto *CallerFD = dyn_cast<FunctionDecl>(CurContext); 3380 if (CallerFD && (!FD || !FD->getBuiltinID()) && 3381 (IsScalableArg || IsScalableRet)) { 3382 bool IsCalleeStreaming = 3383 ExtInfo.AArch64SMEAttributes & FunctionType::SME_PStateSMEnabledMask; 3384 bool IsCalleeStreamingCompatible = 3385 ExtInfo.AArch64SMEAttributes & 3386 FunctionType::SME_PStateSMCompatibleMask; 3387 SemaARM::ArmStreamingType CallerFnType = getArmStreamingFnType(CallerFD); 3388 if (!IsCalleeStreamingCompatible && 3389 (CallerFnType == SemaARM::ArmStreamingCompatible || 3390 ((CallerFnType == SemaARM::ArmStreaming) ^ IsCalleeStreaming))) { 3391 if (IsScalableArg) 3392 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming) 3393 << /*IsArg=*/true; 3394 if (IsScalableRet) 3395 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming) 3396 << /*IsArg=*/false; 3397 } 3398 } 3399 3400 FunctionType::ArmStateValue CalleeArmZAState = 3401 FunctionType::getArmZAState(ExtInfo.AArch64SMEAttributes); 3402 FunctionType::ArmStateValue CalleeArmZT0State = 3403 FunctionType::getArmZT0State(ExtInfo.AArch64SMEAttributes); 3404 if (CalleeArmZAState != FunctionType::ARM_None || 3405 CalleeArmZT0State != FunctionType::ARM_None) { 3406 bool CallerHasZAState = false; 3407 bool CallerHasZT0State = false; 3408 if (CallerFD) { 3409 auto *Attr = CallerFD->getAttr<ArmNewAttr>(); 3410 if (Attr && Attr->isNewZA()) 3411 CallerHasZAState = true; 3412 if (Attr && Attr->isNewZT0()) 3413 CallerHasZT0State = true; 3414 if (const auto *FPT = CallerFD->getType()->getAs<FunctionProtoType>()) { 3415 CallerHasZAState |= 3416 FunctionType::getArmZAState( 3417 FPT->getExtProtoInfo().AArch64SMEAttributes) != 3418 FunctionType::ARM_None; 3419 CallerHasZT0State |= 3420 FunctionType::getArmZT0State( 3421 FPT->getExtProtoInfo().AArch64SMEAttributes) != 3422 FunctionType::ARM_None; 3423 } 3424 } 3425 3426 if (CalleeArmZAState != FunctionType::ARM_None && !CallerHasZAState) 3427 Diag(Loc, diag::err_sme_za_call_no_za_state); 3428 3429 if (CalleeArmZT0State != FunctionType::ARM_None && !CallerHasZT0State) 3430 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state); 3431 3432 if (CallerHasZAState && CalleeArmZAState == FunctionType::ARM_None && 3433 CalleeArmZT0State != FunctionType::ARM_None) { 3434 Diag(Loc, diag::err_sme_unimplemented_za_save_restore); 3435 Diag(Loc, diag::note_sme_use_preserves_za); 3436 } 3437 } 3438 } 3439 3440 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 3441 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 3442 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 3443 if (!Arg->isValueDependent()) { 3444 Expr::EvalResult Align; 3445 if (Arg->EvaluateAsInt(Align, Context)) { 3446 const llvm::APSInt &I = Align.Val.getInt(); 3447 if (!I.isPowerOf2()) 3448 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 3449 << Arg->getSourceRange(); 3450 3451 if (I > Sema::MaximumAlignment) 3452 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 3453 << Arg->getSourceRange() << Sema::MaximumAlignment; 3454 } 3455 } 3456 } 3457 3458 if (FD) 3459 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 3460 } 3461 3462 void Sema::CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc) { 3463 if (ConceptDecl *Decl = AutoT->getTypeConstraintConcept()) { 3464 DiagnoseUseOfDecl(Decl, Loc); 3465 } 3466 } 3467 3468 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 3469 ArrayRef<const Expr *> Args, 3470 const FunctionProtoType *Proto, 3471 SourceLocation Loc) { 3472 VariadicCallType CallType = 3473 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 3474 3475 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 3476 CheckArgAlignment( 3477 Loc, FDecl, "'this'", Context.getPointerType(ThisType), 3478 Context.getPointerType(Ctor->getFunctionObjectParameterType())); 3479 3480 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 3481 Loc, SourceRange(), CallType); 3482 } 3483 3484 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 3485 const FunctionProtoType *Proto) { 3486 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 3487 isa<CXXMethodDecl>(FDecl); 3488 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 3489 IsMemberOperatorCall; 3490 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 3491 TheCall->getCallee()); 3492 Expr** Args = TheCall->getArgs(); 3493 unsigned NumArgs = TheCall->getNumArgs(); 3494 3495 Expr *ImplicitThis = nullptr; 3496 if (IsMemberOperatorCall && !FDecl->hasCXXExplicitFunctionObjectParameter()) { 3497 // If this is a call to a member operator, hide the first 3498 // argument from checkCall. 3499 // FIXME: Our choice of AST representation here is less than ideal. 3500 ImplicitThis = Args[0]; 3501 ++Args; 3502 --NumArgs; 3503 } else if (IsMemberFunction && !FDecl->isStatic() && 3504 !FDecl->hasCXXExplicitFunctionObjectParameter()) 3505 ImplicitThis = 3506 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 3507 3508 if (ImplicitThis) { 3509 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 3510 // used. 3511 QualType ThisType = ImplicitThis->getType(); 3512 if (!ThisType->isPointerType()) { 3513 assert(!ThisType->isReferenceType()); 3514 ThisType = Context.getPointerType(ThisType); 3515 } 3516 3517 QualType ThisTypeFromDecl = Context.getPointerType( 3518 cast<CXXMethodDecl>(FDecl)->getFunctionObjectParameterType()); 3519 3520 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 3521 ThisTypeFromDecl); 3522 } 3523 3524 checkCall(FDecl, Proto, ImplicitThis, llvm::ArrayRef(Args, NumArgs), 3525 IsMemberFunction, TheCall->getRParenLoc(), 3526 TheCall->getCallee()->getSourceRange(), CallType); 3527 3528 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 3529 // None of the checks below are needed for functions that don't have 3530 // simple names (e.g., C++ conversion functions). 3531 if (!FnInfo) 3532 return false; 3533 3534 // Enforce TCB except for builtin calls, which are always allowed. 3535 if (FDecl->getBuiltinID() == 0) 3536 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl); 3537 3538 CheckAbsoluteValueFunction(TheCall, FDecl); 3539 CheckMaxUnsignedZero(TheCall, FDecl); 3540 CheckInfNaNFunction(TheCall, FDecl); 3541 3542 if (getLangOpts().ObjC) 3543 ObjC().DiagnoseCStringFormatDirectiveInCFAPI(FDecl, Args, NumArgs); 3544 3545 unsigned CMId = FDecl->getMemoryFunctionKind(); 3546 3547 // Handle memory setting and copying functions. 3548 switch (CMId) { 3549 case 0: 3550 return false; 3551 case Builtin::BIstrlcpy: // fallthrough 3552 case Builtin::BIstrlcat: 3553 CheckStrlcpycatArguments(TheCall, FnInfo); 3554 break; 3555 case Builtin::BIstrncat: 3556 CheckStrncatArguments(TheCall, FnInfo); 3557 break; 3558 case Builtin::BIfree: 3559 CheckFreeArguments(TheCall); 3560 break; 3561 default: 3562 CheckMemaccessArguments(TheCall, CMId, FnInfo); 3563 } 3564 3565 return false; 3566 } 3567 3568 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 3569 const FunctionProtoType *Proto) { 3570 QualType Ty; 3571 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 3572 Ty = V->getType().getNonReferenceType(); 3573 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 3574 Ty = F->getType().getNonReferenceType(); 3575 else 3576 return false; 3577 3578 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 3579 !Ty->isFunctionProtoType()) 3580 return false; 3581 3582 VariadicCallType CallType; 3583 if (!Proto || !Proto->isVariadic()) { 3584 CallType = VariadicDoesNotApply; 3585 } else if (Ty->isBlockPointerType()) { 3586 CallType = VariadicBlock; 3587 } else { // Ty->isFunctionPointerType() 3588 CallType = VariadicFunction; 3589 } 3590 3591 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 3592 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 3593 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 3594 TheCall->getCallee()->getSourceRange(), CallType); 3595 3596 return false; 3597 } 3598 3599 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 3600 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 3601 TheCall->getCallee()); 3602 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 3603 llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 3604 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 3605 TheCall->getCallee()->getSourceRange(), CallType); 3606 3607 return false; 3608 } 3609 3610 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 3611 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 3612 return false; 3613 3614 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 3615 switch (Op) { 3616 case AtomicExpr::AO__c11_atomic_init: 3617 case AtomicExpr::AO__opencl_atomic_init: 3618 llvm_unreachable("There is no ordering argument for an init"); 3619 3620 case AtomicExpr::AO__c11_atomic_load: 3621 case AtomicExpr::AO__opencl_atomic_load: 3622 case AtomicExpr::AO__hip_atomic_load: 3623 case AtomicExpr::AO__atomic_load_n: 3624 case AtomicExpr::AO__atomic_load: 3625 case AtomicExpr::AO__scoped_atomic_load_n: 3626 case AtomicExpr::AO__scoped_atomic_load: 3627 return OrderingCABI != llvm::AtomicOrderingCABI::release && 3628 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 3629 3630 case AtomicExpr::AO__c11_atomic_store: 3631 case AtomicExpr::AO__opencl_atomic_store: 3632 case AtomicExpr::AO__hip_atomic_store: 3633 case AtomicExpr::AO__atomic_store: 3634 case AtomicExpr::AO__atomic_store_n: 3635 case AtomicExpr::AO__scoped_atomic_store: 3636 case AtomicExpr::AO__scoped_atomic_store_n: 3637 case AtomicExpr::AO__atomic_clear: 3638 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 3639 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 3640 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 3641 3642 default: 3643 return true; 3644 } 3645 } 3646 3647 ExprResult Sema::AtomicOpsOverloaded(ExprResult TheCallResult, 3648 AtomicExpr::AtomicOp Op) { 3649 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 3650 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 3651 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 3652 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 3653 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 3654 Op); 3655 } 3656 3657 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 3658 SourceLocation RParenLoc, MultiExprArg Args, 3659 AtomicExpr::AtomicOp Op, 3660 AtomicArgumentOrder ArgOrder) { 3661 // All the non-OpenCL operations take one of the following forms. 3662 // The OpenCL operations take the __c11 forms with one extra argument for 3663 // synchronization scope. 3664 enum { 3665 // C __c11_atomic_init(A *, C) 3666 Init, 3667 3668 // C __c11_atomic_load(A *, int) 3669 Load, 3670 3671 // void __atomic_load(A *, CP, int) 3672 LoadCopy, 3673 3674 // void __atomic_store(A *, CP, int) 3675 Copy, 3676 3677 // C __c11_atomic_add(A *, M, int) 3678 Arithmetic, 3679 3680 // C __atomic_exchange_n(A *, CP, int) 3681 Xchg, 3682 3683 // void __atomic_exchange(A *, C *, CP, int) 3684 GNUXchg, 3685 3686 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 3687 C11CmpXchg, 3688 3689 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 3690 GNUCmpXchg, 3691 3692 // bool __atomic_test_and_set(A *, int) 3693 TestAndSetByte, 3694 3695 // void __atomic_clear(A *, int) 3696 ClearByte, 3697 } Form = Init; 3698 3699 const unsigned NumForm = ClearByte + 1; 3700 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2}; 3701 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0}; 3702 // where: 3703 // C is an appropriate type, 3704 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 3705 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 3706 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 3707 // the int parameters are for orderings. 3708 3709 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 3710 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 3711 "need to update code for modified forms"); 3712 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 && 3713 AtomicExpr::AO__atomic_xor_fetch + 1 == 3714 AtomicExpr::AO__c11_atomic_compare_exchange_strong, 3715 "need to update code for modified C11 atomics"); 3716 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong && 3717 Op <= AtomicExpr::AO__opencl_atomic_store; 3718 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong && 3719 Op <= AtomicExpr::AO__hip_atomic_store; 3720 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch && 3721 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch; 3722 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong && 3723 Op <= AtomicExpr::AO__c11_atomic_store) || 3724 IsOpenCL; 3725 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 3726 Op == AtomicExpr::AO__atomic_store_n || 3727 Op == AtomicExpr::AO__atomic_exchange_n || 3728 Op == AtomicExpr::AO__atomic_compare_exchange_n || 3729 Op == AtomicExpr::AO__scoped_atomic_load_n || 3730 Op == AtomicExpr::AO__scoped_atomic_store_n || 3731 Op == AtomicExpr::AO__scoped_atomic_exchange_n || 3732 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n; 3733 // Bit mask for extra allowed value types other than integers for atomic 3734 // arithmetic operations. Add/sub allow pointer and floating point. Min/max 3735 // allow floating point. 3736 enum ArithOpExtraValueType { 3737 AOEVT_None = 0, 3738 AOEVT_Pointer = 1, 3739 AOEVT_FP = 2, 3740 }; 3741 unsigned ArithAllows = AOEVT_None; 3742 3743 switch (Op) { 3744 case AtomicExpr::AO__c11_atomic_init: 3745 case AtomicExpr::AO__opencl_atomic_init: 3746 Form = Init; 3747 break; 3748 3749 case AtomicExpr::AO__c11_atomic_load: 3750 case AtomicExpr::AO__opencl_atomic_load: 3751 case AtomicExpr::AO__hip_atomic_load: 3752 case AtomicExpr::AO__atomic_load_n: 3753 case AtomicExpr::AO__scoped_atomic_load_n: 3754 Form = Load; 3755 break; 3756 3757 case AtomicExpr::AO__atomic_load: 3758 case AtomicExpr::AO__scoped_atomic_load: 3759 Form = LoadCopy; 3760 break; 3761 3762 case AtomicExpr::AO__c11_atomic_store: 3763 case AtomicExpr::AO__opencl_atomic_store: 3764 case AtomicExpr::AO__hip_atomic_store: 3765 case AtomicExpr::AO__atomic_store: 3766 case AtomicExpr::AO__atomic_store_n: 3767 case AtomicExpr::AO__scoped_atomic_store: 3768 case AtomicExpr::AO__scoped_atomic_store_n: 3769 Form = Copy; 3770 break; 3771 case AtomicExpr::AO__atomic_fetch_add: 3772 case AtomicExpr::AO__atomic_fetch_sub: 3773 case AtomicExpr::AO__atomic_add_fetch: 3774 case AtomicExpr::AO__atomic_sub_fetch: 3775 case AtomicExpr::AO__scoped_atomic_fetch_add: 3776 case AtomicExpr::AO__scoped_atomic_fetch_sub: 3777 case AtomicExpr::AO__scoped_atomic_add_fetch: 3778 case AtomicExpr::AO__scoped_atomic_sub_fetch: 3779 case AtomicExpr::AO__c11_atomic_fetch_add: 3780 case AtomicExpr::AO__c11_atomic_fetch_sub: 3781 case AtomicExpr::AO__opencl_atomic_fetch_add: 3782 case AtomicExpr::AO__opencl_atomic_fetch_sub: 3783 case AtomicExpr::AO__hip_atomic_fetch_add: 3784 case AtomicExpr::AO__hip_atomic_fetch_sub: 3785 ArithAllows = AOEVT_Pointer | AOEVT_FP; 3786 Form = Arithmetic; 3787 break; 3788 case AtomicExpr::AO__atomic_fetch_max: 3789 case AtomicExpr::AO__atomic_fetch_min: 3790 case AtomicExpr::AO__atomic_max_fetch: 3791 case AtomicExpr::AO__atomic_min_fetch: 3792 case AtomicExpr::AO__scoped_atomic_fetch_max: 3793 case AtomicExpr::AO__scoped_atomic_fetch_min: 3794 case AtomicExpr::AO__scoped_atomic_max_fetch: 3795 case AtomicExpr::AO__scoped_atomic_min_fetch: 3796 case AtomicExpr::AO__c11_atomic_fetch_max: 3797 case AtomicExpr::AO__c11_atomic_fetch_min: 3798 case AtomicExpr::AO__opencl_atomic_fetch_max: 3799 case AtomicExpr::AO__opencl_atomic_fetch_min: 3800 case AtomicExpr::AO__hip_atomic_fetch_max: 3801 case AtomicExpr::AO__hip_atomic_fetch_min: 3802 ArithAllows = AOEVT_FP; 3803 Form = Arithmetic; 3804 break; 3805 case AtomicExpr::AO__c11_atomic_fetch_and: 3806 case AtomicExpr::AO__c11_atomic_fetch_or: 3807 case AtomicExpr::AO__c11_atomic_fetch_xor: 3808 case AtomicExpr::AO__hip_atomic_fetch_and: 3809 case AtomicExpr::AO__hip_atomic_fetch_or: 3810 case AtomicExpr::AO__hip_atomic_fetch_xor: 3811 case AtomicExpr::AO__c11_atomic_fetch_nand: 3812 case AtomicExpr::AO__opencl_atomic_fetch_and: 3813 case AtomicExpr::AO__opencl_atomic_fetch_or: 3814 case AtomicExpr::AO__opencl_atomic_fetch_xor: 3815 case AtomicExpr::AO__atomic_fetch_and: 3816 case AtomicExpr::AO__atomic_fetch_or: 3817 case AtomicExpr::AO__atomic_fetch_xor: 3818 case AtomicExpr::AO__atomic_fetch_nand: 3819 case AtomicExpr::AO__atomic_and_fetch: 3820 case AtomicExpr::AO__atomic_or_fetch: 3821 case AtomicExpr::AO__atomic_xor_fetch: 3822 case AtomicExpr::AO__atomic_nand_fetch: 3823 case AtomicExpr::AO__scoped_atomic_fetch_and: 3824 case AtomicExpr::AO__scoped_atomic_fetch_or: 3825 case AtomicExpr::AO__scoped_atomic_fetch_xor: 3826 case AtomicExpr::AO__scoped_atomic_fetch_nand: 3827 case AtomicExpr::AO__scoped_atomic_and_fetch: 3828 case AtomicExpr::AO__scoped_atomic_or_fetch: 3829 case AtomicExpr::AO__scoped_atomic_xor_fetch: 3830 case AtomicExpr::AO__scoped_atomic_nand_fetch: 3831 Form = Arithmetic; 3832 break; 3833 3834 case AtomicExpr::AO__c11_atomic_exchange: 3835 case AtomicExpr::AO__hip_atomic_exchange: 3836 case AtomicExpr::AO__opencl_atomic_exchange: 3837 case AtomicExpr::AO__atomic_exchange_n: 3838 case AtomicExpr::AO__scoped_atomic_exchange_n: 3839 Form = Xchg; 3840 break; 3841 3842 case AtomicExpr::AO__atomic_exchange: 3843 case AtomicExpr::AO__scoped_atomic_exchange: 3844 Form = GNUXchg; 3845 break; 3846 3847 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 3848 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 3849 case AtomicExpr::AO__hip_atomic_compare_exchange_strong: 3850 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 3851 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 3852 case AtomicExpr::AO__hip_atomic_compare_exchange_weak: 3853 Form = C11CmpXchg; 3854 break; 3855 3856 case AtomicExpr::AO__atomic_compare_exchange: 3857 case AtomicExpr::AO__atomic_compare_exchange_n: 3858 case AtomicExpr::AO__scoped_atomic_compare_exchange: 3859 case AtomicExpr::AO__scoped_atomic_compare_exchange_n: 3860 Form = GNUCmpXchg; 3861 break; 3862 3863 case AtomicExpr::AO__atomic_test_and_set: 3864 Form = TestAndSetByte; 3865 break; 3866 3867 case AtomicExpr::AO__atomic_clear: 3868 Form = ClearByte; 3869 break; 3870 } 3871 3872 unsigned AdjustedNumArgs = NumArgs[Form]; 3873 if ((IsOpenCL || IsHIP || IsScoped) && 3874 Op != AtomicExpr::AO__opencl_atomic_init) 3875 ++AdjustedNumArgs; 3876 // Check we have the right number of arguments. 3877 if (Args.size() < AdjustedNumArgs) { 3878 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 3879 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 3880 << /*is non object*/ 0 << ExprRange; 3881 return ExprError(); 3882 } else if (Args.size() > AdjustedNumArgs) { 3883 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 3884 diag::err_typecheck_call_too_many_args) 3885 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 3886 << /*is non object*/ 0 << ExprRange; 3887 return ExprError(); 3888 } 3889 3890 // Inspect the first argument of the atomic operation. 3891 Expr *Ptr = Args[0]; 3892 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 3893 if (ConvertedPtr.isInvalid()) 3894 return ExprError(); 3895 3896 Ptr = ConvertedPtr.get(); 3897 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 3898 if (!pointerType) { 3899 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 3900 << Ptr->getType() << 0 << Ptr->getSourceRange(); 3901 return ExprError(); 3902 } 3903 3904 // For a __c11 builtin, this should be a pointer to an _Atomic type. 3905 QualType AtomTy = pointerType->getPointeeType(); // 'A' 3906 QualType ValType = AtomTy; // 'C' 3907 if (IsC11) { 3908 if (!AtomTy->isAtomicType()) { 3909 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 3910 << Ptr->getType() << Ptr->getSourceRange(); 3911 return ExprError(); 3912 } 3913 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 3914 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 3915 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 3916 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 3917 << Ptr->getSourceRange(); 3918 return ExprError(); 3919 } 3920 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 3921 } else if (Form != Load && Form != LoadCopy) { 3922 if (ValType.isConstQualified()) { 3923 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 3924 << Ptr->getType() << Ptr->getSourceRange(); 3925 return ExprError(); 3926 } 3927 } 3928 3929 if (Form != TestAndSetByte && Form != ClearByte) { 3930 // Pointer to object of size zero is not allowed. 3931 if (RequireCompleteType(Ptr->getBeginLoc(), AtomTy, 3932 diag::err_incomplete_type)) 3933 return ExprError(); 3934 3935 if (Context.getTypeInfoInChars(AtomTy).Width.isZero()) { 3936 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 3937 << Ptr->getType() << 1 << Ptr->getSourceRange(); 3938 return ExprError(); 3939 } 3940 } else { 3941 // The __atomic_clear and __atomic_test_and_set intrinsics accept any 3942 // non-const pointer type, including void* and pointers to incomplete 3943 // structs, but only access the first byte. 3944 AtomTy = Context.CharTy; 3945 AtomTy = AtomTy.withCVRQualifiers( 3946 pointerType->getPointeeType().getCVRQualifiers()); 3947 QualType PointerQT = Context.getPointerType(AtomTy); 3948 pointerType = PointerQT->getAs<PointerType>(); 3949 Ptr = ImpCastExprToType(Ptr, PointerQT, CK_BitCast).get(); 3950 ValType = AtomTy; 3951 } 3952 3953 // For an arithmetic operation, the implied arithmetic must be well-formed. 3954 if (Form == Arithmetic) { 3955 // GCC does not enforce these rules for GNU atomics, but we do to help catch 3956 // trivial type errors. 3957 auto IsAllowedValueType = [&](QualType ValType, 3958 unsigned AllowedType) -> bool { 3959 if (ValType->isIntegerType()) 3960 return true; 3961 if (ValType->isPointerType()) 3962 return AllowedType & AOEVT_Pointer; 3963 if (!(ValType->isFloatingType() && (AllowedType & AOEVT_FP))) 3964 return false; 3965 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 3966 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 3967 &Context.getTargetInfo().getLongDoubleFormat() == 3968 &llvm::APFloat::x87DoubleExtended()) 3969 return false; 3970 return true; 3971 }; 3972 if (!IsAllowedValueType(ValType, ArithAllows)) { 3973 auto DID = ArithAllows & AOEVT_FP 3974 ? (ArithAllows & AOEVT_Pointer 3975 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp 3976 : diag::err_atomic_op_needs_atomic_int_or_fp) 3977 : diag::err_atomic_op_needs_atomic_int; 3978 Diag(ExprRange.getBegin(), DID) 3979 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3980 return ExprError(); 3981 } 3982 if (IsC11 && ValType->isPointerType() && 3983 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 3984 diag::err_incomplete_type)) { 3985 return ExprError(); 3986 } 3987 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 3988 // For __atomic_*_n operations, the value type must be a scalar integral or 3989 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 3990 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 3991 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 3992 return ExprError(); 3993 } 3994 3995 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 3996 !AtomTy->isScalarType()) { 3997 // For GNU atomics, require a trivially-copyable type. This is not part of 3998 // the GNU atomics specification but we enforce it for consistency with 3999 // other atomics which generally all require a trivially-copyable type. This 4000 // is because atomics just copy bits. 4001 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4002 << Ptr->getType() << Ptr->getSourceRange(); 4003 return ExprError(); 4004 } 4005 4006 switch (ValType.getObjCLifetime()) { 4007 case Qualifiers::OCL_None: 4008 case Qualifiers::OCL_ExplicitNone: 4009 // okay 4010 break; 4011 4012 case Qualifiers::OCL_Weak: 4013 case Qualifiers::OCL_Strong: 4014 case Qualifiers::OCL_Autoreleasing: 4015 // FIXME: Can this happen? By this point, ValType should be known 4016 // to be trivially copyable. 4017 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4018 << ValType << Ptr->getSourceRange(); 4019 return ExprError(); 4020 } 4021 4022 // All atomic operations have an overload which takes a pointer to a volatile 4023 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4024 // into the result or the other operands. Similarly atomic_load takes a 4025 // pointer to a const 'A'. 4026 ValType.removeLocalVolatile(); 4027 ValType.removeLocalConst(); 4028 QualType ResultType = ValType; 4029 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init || 4030 Form == ClearByte) 4031 ResultType = Context.VoidTy; 4032 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte) 4033 ResultType = Context.BoolTy; 4034 4035 // The type of a parameter passed 'by value'. In the GNU atomics, such 4036 // arguments are actually passed as pointers. 4037 QualType ByValType = ValType; // 'CP' 4038 bool IsPassedByAddress = false; 4039 if (!IsC11 && !IsHIP && !IsN) { 4040 ByValType = Ptr->getType(); 4041 IsPassedByAddress = true; 4042 } 4043 4044 SmallVector<Expr *, 5> APIOrderedArgs; 4045 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4046 APIOrderedArgs.push_back(Args[0]); 4047 switch (Form) { 4048 case Init: 4049 case Load: 4050 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4051 break; 4052 case LoadCopy: 4053 case Copy: 4054 case Arithmetic: 4055 case Xchg: 4056 APIOrderedArgs.push_back(Args[2]); // Val1 4057 APIOrderedArgs.push_back(Args[1]); // Order 4058 break; 4059 case GNUXchg: 4060 APIOrderedArgs.push_back(Args[2]); // Val1 4061 APIOrderedArgs.push_back(Args[3]); // Val2 4062 APIOrderedArgs.push_back(Args[1]); // Order 4063 break; 4064 case C11CmpXchg: 4065 APIOrderedArgs.push_back(Args[2]); // Val1 4066 APIOrderedArgs.push_back(Args[4]); // Val2 4067 APIOrderedArgs.push_back(Args[1]); // Order 4068 APIOrderedArgs.push_back(Args[3]); // OrderFail 4069 break; 4070 case GNUCmpXchg: 4071 APIOrderedArgs.push_back(Args[2]); // Val1 4072 APIOrderedArgs.push_back(Args[4]); // Val2 4073 APIOrderedArgs.push_back(Args[5]); // Weak 4074 APIOrderedArgs.push_back(Args[1]); // Order 4075 APIOrderedArgs.push_back(Args[3]); // OrderFail 4076 break; 4077 case TestAndSetByte: 4078 case ClearByte: 4079 APIOrderedArgs.push_back(Args[1]); // Order 4080 break; 4081 } 4082 } else 4083 APIOrderedArgs.append(Args.begin(), Args.end()); 4084 4085 // The first argument's non-CV pointer type is used to deduce the type of 4086 // subsequent arguments, except for: 4087 // - weak flag (always converted to bool) 4088 // - memory order (always converted to int) 4089 // - scope (always converted to int) 4090 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4091 QualType Ty; 4092 if (i < NumVals[Form] + 1) { 4093 switch (i) { 4094 case 0: 4095 // The first argument is always a pointer. It has a fixed type. 4096 // It is always dereferenced, a nullptr is undefined. 4097 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4098 // Nothing else to do: we already know all we want about this pointer. 4099 continue; 4100 case 1: 4101 // The second argument is the non-atomic operand. For arithmetic, this 4102 // is always passed by value, and for a compare_exchange it is always 4103 // passed by address. For the rest, GNU uses by-address and C11 uses 4104 // by-value. 4105 assert(Form != Load); 4106 if (Form == Arithmetic && ValType->isPointerType()) 4107 Ty = Context.getPointerDiffType(); 4108 else if (Form == Init || Form == Arithmetic) 4109 Ty = ValType; 4110 else if (Form == Copy || Form == Xchg) { 4111 if (IsPassedByAddress) { 4112 // The value pointer is always dereferenced, a nullptr is undefined. 4113 CheckNonNullArgument(*this, APIOrderedArgs[i], 4114 ExprRange.getBegin()); 4115 } 4116 Ty = ByValType; 4117 } else { 4118 Expr *ValArg = APIOrderedArgs[i]; 4119 // The value pointer is always dereferenced, a nullptr is undefined. 4120 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4121 LangAS AS = LangAS::Default; 4122 // Keep address space of non-atomic pointer type. 4123 if (const PointerType *PtrTy = 4124 ValArg->getType()->getAs<PointerType>()) { 4125 AS = PtrTy->getPointeeType().getAddressSpace(); 4126 } 4127 Ty = Context.getPointerType( 4128 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4129 } 4130 break; 4131 case 2: 4132 // The third argument to compare_exchange / GNU exchange is the desired 4133 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4134 if (IsPassedByAddress) 4135 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4136 Ty = ByValType; 4137 break; 4138 case 3: 4139 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4140 Ty = Context.BoolTy; 4141 break; 4142 } 4143 } else { 4144 // The order(s) and scope are always converted to int. 4145 Ty = Context.IntTy; 4146 } 4147 4148 InitializedEntity Entity = 4149 InitializedEntity::InitializeParameter(Context, Ty, false); 4150 ExprResult Arg = APIOrderedArgs[i]; 4151 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4152 if (Arg.isInvalid()) 4153 return true; 4154 APIOrderedArgs[i] = Arg.get(); 4155 } 4156 4157 // Permute the arguments into a 'consistent' order. 4158 SmallVector<Expr*, 5> SubExprs; 4159 SubExprs.push_back(Ptr); 4160 switch (Form) { 4161 case Init: 4162 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4163 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4164 break; 4165 case Load: 4166 case TestAndSetByte: 4167 case ClearByte: 4168 SubExprs.push_back(APIOrderedArgs[1]); // Order 4169 break; 4170 case LoadCopy: 4171 case Copy: 4172 case Arithmetic: 4173 case Xchg: 4174 SubExprs.push_back(APIOrderedArgs[2]); // Order 4175 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4176 break; 4177 case GNUXchg: 4178 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4179 SubExprs.push_back(APIOrderedArgs[3]); // Order 4180 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4181 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4182 break; 4183 case C11CmpXchg: 4184 SubExprs.push_back(APIOrderedArgs[3]); // Order 4185 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4186 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 4187 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4188 break; 4189 case GNUCmpXchg: 4190 SubExprs.push_back(APIOrderedArgs[4]); // Order 4191 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4192 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 4193 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4194 SubExprs.push_back(APIOrderedArgs[3]); // Weak 4195 break; 4196 } 4197 4198 // If the memory orders are constants, check they are valid. 4199 if (SubExprs.size() >= 2 && Form != Init) { 4200 std::optional<llvm::APSInt> Success = 4201 SubExprs[1]->getIntegerConstantExpr(Context); 4202 if (Success && !isValidOrderingForOp(Success->getSExtValue(), Op)) { 4203 Diag(SubExprs[1]->getBeginLoc(), 4204 diag::warn_atomic_op_has_invalid_memory_order) 4205 << /*success=*/(Form == C11CmpXchg || Form == GNUCmpXchg) 4206 << SubExprs[1]->getSourceRange(); 4207 } 4208 if (SubExprs.size() >= 5) { 4209 if (std::optional<llvm::APSInt> Failure = 4210 SubExprs[3]->getIntegerConstantExpr(Context)) { 4211 if (!llvm::is_contained( 4212 {llvm::AtomicOrderingCABI::relaxed, 4213 llvm::AtomicOrderingCABI::consume, 4214 llvm::AtomicOrderingCABI::acquire, 4215 llvm::AtomicOrderingCABI::seq_cst}, 4216 (llvm::AtomicOrderingCABI)Failure->getSExtValue())) { 4217 Diag(SubExprs[3]->getBeginLoc(), 4218 diag::warn_atomic_op_has_invalid_memory_order) 4219 << /*failure=*/2 << SubExprs[3]->getSourceRange(); 4220 } 4221 } 4222 } 4223 } 4224 4225 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4226 auto *Scope = Args[Args.size() - 1]; 4227 if (std::optional<llvm::APSInt> Result = 4228 Scope->getIntegerConstantExpr(Context)) { 4229 if (!ScopeModel->isValid(Result->getZExtValue())) 4230 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4231 << Scope->getSourceRange(); 4232 } 4233 SubExprs.push_back(Scope); 4234 } 4235 4236 AtomicExpr *AE = new (Context) 4237 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 4238 4239 if ((Op == AtomicExpr::AO__c11_atomic_load || 4240 Op == AtomicExpr::AO__c11_atomic_store || 4241 Op == AtomicExpr::AO__opencl_atomic_load || 4242 Op == AtomicExpr::AO__hip_atomic_load || 4243 Op == AtomicExpr::AO__opencl_atomic_store || 4244 Op == AtomicExpr::AO__hip_atomic_store) && 4245 Context.AtomicUsesUnsupportedLibcall(AE)) 4246 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4247 << ((Op == AtomicExpr::AO__c11_atomic_load || 4248 Op == AtomicExpr::AO__opencl_atomic_load || 4249 Op == AtomicExpr::AO__hip_atomic_load) 4250 ? 0 4251 : 1); 4252 4253 if (ValType->isBitIntType()) { 4254 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit); 4255 return ExprError(); 4256 } 4257 4258 return AE; 4259 } 4260 4261 /// checkBuiltinArgument - Given a call to a builtin function, perform 4262 /// normal type-checking on the given argument, updating the call in 4263 /// place. This is useful when a builtin function requires custom 4264 /// type-checking for some of its arguments but not necessarily all of 4265 /// them. 4266 /// 4267 /// Returns true on error. 4268 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4269 FunctionDecl *Fn = E->getDirectCallee(); 4270 assert(Fn && "builtin call without direct callee!"); 4271 4272 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4273 InitializedEntity Entity = 4274 InitializedEntity::InitializeParameter(S.Context, Param); 4275 4276 ExprResult Arg = E->getArg(ArgIndex); 4277 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4278 if (Arg.isInvalid()) 4279 return true; 4280 4281 E->setArg(ArgIndex, Arg.get()); 4282 return false; 4283 } 4284 4285 ExprResult Sema::BuiltinAtomicOverloaded(ExprResult TheCallResult) { 4286 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4287 Expr *Callee = TheCall->getCallee(); 4288 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4289 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4290 4291 // Ensure that we have at least one argument to do type inference from. 4292 if (TheCall->getNumArgs() < 1) { 4293 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4294 << 0 << 1 << TheCall->getNumArgs() << /*is non object*/ 0 4295 << Callee->getSourceRange(); 4296 return ExprError(); 4297 } 4298 4299 // Inspect the first argument of the atomic builtin. This should always be 4300 // a pointer type, whose element is an integral scalar or pointer type. 4301 // Because it is a pointer type, we don't have to worry about any implicit 4302 // casts here. 4303 // FIXME: We don't allow floating point scalars as input. 4304 Expr *FirstArg = TheCall->getArg(0); 4305 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4306 if (FirstArgResult.isInvalid()) 4307 return ExprError(); 4308 FirstArg = FirstArgResult.get(); 4309 TheCall->setArg(0, FirstArg); 4310 4311 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4312 if (!pointerType) { 4313 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4314 << FirstArg->getType() << 0 << FirstArg->getSourceRange(); 4315 return ExprError(); 4316 } 4317 4318 QualType ValType = pointerType->getPointeeType(); 4319 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4320 !ValType->isBlockPointerType()) { 4321 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4322 << FirstArg->getType() << 0 << FirstArg->getSourceRange(); 4323 return ExprError(); 4324 } 4325 4326 if (ValType.isConstQualified()) { 4327 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4328 << FirstArg->getType() << FirstArg->getSourceRange(); 4329 return ExprError(); 4330 } 4331 4332 switch (ValType.getObjCLifetime()) { 4333 case Qualifiers::OCL_None: 4334 case Qualifiers::OCL_ExplicitNone: 4335 // okay 4336 break; 4337 4338 case Qualifiers::OCL_Weak: 4339 case Qualifiers::OCL_Strong: 4340 case Qualifiers::OCL_Autoreleasing: 4341 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4342 << ValType << FirstArg->getSourceRange(); 4343 return ExprError(); 4344 } 4345 4346 // Strip any qualifiers off ValType. 4347 ValType = ValType.getUnqualifiedType(); 4348 4349 // The majority of builtins return a value, but a few have special return 4350 // types, so allow them to override appropriately below. 4351 QualType ResultType = ValType; 4352 4353 // We need to figure out which concrete builtin this maps onto. For example, 4354 // __sync_fetch_and_add with a 2 byte object turns into 4355 // __sync_fetch_and_add_2. 4356 #define BUILTIN_ROW(x) \ 4357 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4358 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4359 4360 static const unsigned BuiltinIndices[][5] = { 4361 BUILTIN_ROW(__sync_fetch_and_add), 4362 BUILTIN_ROW(__sync_fetch_and_sub), 4363 BUILTIN_ROW(__sync_fetch_and_or), 4364 BUILTIN_ROW(__sync_fetch_and_and), 4365 BUILTIN_ROW(__sync_fetch_and_xor), 4366 BUILTIN_ROW(__sync_fetch_and_nand), 4367 4368 BUILTIN_ROW(__sync_add_and_fetch), 4369 BUILTIN_ROW(__sync_sub_and_fetch), 4370 BUILTIN_ROW(__sync_and_and_fetch), 4371 BUILTIN_ROW(__sync_or_and_fetch), 4372 BUILTIN_ROW(__sync_xor_and_fetch), 4373 BUILTIN_ROW(__sync_nand_and_fetch), 4374 4375 BUILTIN_ROW(__sync_val_compare_and_swap), 4376 BUILTIN_ROW(__sync_bool_compare_and_swap), 4377 BUILTIN_ROW(__sync_lock_test_and_set), 4378 BUILTIN_ROW(__sync_lock_release), 4379 BUILTIN_ROW(__sync_swap) 4380 }; 4381 #undef BUILTIN_ROW 4382 4383 // Determine the index of the size. 4384 unsigned SizeIndex; 4385 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4386 case 1: SizeIndex = 0; break; 4387 case 2: SizeIndex = 1; break; 4388 case 4: SizeIndex = 2; break; 4389 case 8: SizeIndex = 3; break; 4390 case 16: SizeIndex = 4; break; 4391 default: 4392 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4393 << FirstArg->getType() << FirstArg->getSourceRange(); 4394 return ExprError(); 4395 } 4396 4397 // Each of these builtins has one pointer argument, followed by some number of 4398 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4399 // that we ignore. Find out which row of BuiltinIndices to read from as well 4400 // as the number of fixed args. 4401 unsigned BuiltinID = FDecl->getBuiltinID(); 4402 unsigned BuiltinIndex, NumFixed = 1; 4403 bool WarnAboutSemanticsChange = false; 4404 switch (BuiltinID) { 4405 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4406 case Builtin::BI__sync_fetch_and_add: 4407 case Builtin::BI__sync_fetch_and_add_1: 4408 case Builtin::BI__sync_fetch_and_add_2: 4409 case Builtin::BI__sync_fetch_and_add_4: 4410 case Builtin::BI__sync_fetch_and_add_8: 4411 case Builtin::BI__sync_fetch_and_add_16: 4412 BuiltinIndex = 0; 4413 break; 4414 4415 case Builtin::BI__sync_fetch_and_sub: 4416 case Builtin::BI__sync_fetch_and_sub_1: 4417 case Builtin::BI__sync_fetch_and_sub_2: 4418 case Builtin::BI__sync_fetch_and_sub_4: 4419 case Builtin::BI__sync_fetch_and_sub_8: 4420 case Builtin::BI__sync_fetch_and_sub_16: 4421 BuiltinIndex = 1; 4422 break; 4423 4424 case Builtin::BI__sync_fetch_and_or: 4425 case Builtin::BI__sync_fetch_and_or_1: 4426 case Builtin::BI__sync_fetch_and_or_2: 4427 case Builtin::BI__sync_fetch_and_or_4: 4428 case Builtin::BI__sync_fetch_and_or_8: 4429 case Builtin::BI__sync_fetch_and_or_16: 4430 BuiltinIndex = 2; 4431 break; 4432 4433 case Builtin::BI__sync_fetch_and_and: 4434 case Builtin::BI__sync_fetch_and_and_1: 4435 case Builtin::BI__sync_fetch_and_and_2: 4436 case Builtin::BI__sync_fetch_and_and_4: 4437 case Builtin::BI__sync_fetch_and_and_8: 4438 case Builtin::BI__sync_fetch_and_and_16: 4439 BuiltinIndex = 3; 4440 break; 4441 4442 case Builtin::BI__sync_fetch_and_xor: 4443 case Builtin::BI__sync_fetch_and_xor_1: 4444 case Builtin::BI__sync_fetch_and_xor_2: 4445 case Builtin::BI__sync_fetch_and_xor_4: 4446 case Builtin::BI__sync_fetch_and_xor_8: 4447 case Builtin::BI__sync_fetch_and_xor_16: 4448 BuiltinIndex = 4; 4449 break; 4450 4451 case Builtin::BI__sync_fetch_and_nand: 4452 case Builtin::BI__sync_fetch_and_nand_1: 4453 case Builtin::BI__sync_fetch_and_nand_2: 4454 case Builtin::BI__sync_fetch_and_nand_4: 4455 case Builtin::BI__sync_fetch_and_nand_8: 4456 case Builtin::BI__sync_fetch_and_nand_16: 4457 BuiltinIndex = 5; 4458 WarnAboutSemanticsChange = true; 4459 break; 4460 4461 case Builtin::BI__sync_add_and_fetch: 4462 case Builtin::BI__sync_add_and_fetch_1: 4463 case Builtin::BI__sync_add_and_fetch_2: 4464 case Builtin::BI__sync_add_and_fetch_4: 4465 case Builtin::BI__sync_add_and_fetch_8: 4466 case Builtin::BI__sync_add_and_fetch_16: 4467 BuiltinIndex = 6; 4468 break; 4469 4470 case Builtin::BI__sync_sub_and_fetch: 4471 case Builtin::BI__sync_sub_and_fetch_1: 4472 case Builtin::BI__sync_sub_and_fetch_2: 4473 case Builtin::BI__sync_sub_and_fetch_4: 4474 case Builtin::BI__sync_sub_and_fetch_8: 4475 case Builtin::BI__sync_sub_and_fetch_16: 4476 BuiltinIndex = 7; 4477 break; 4478 4479 case Builtin::BI__sync_and_and_fetch: 4480 case Builtin::BI__sync_and_and_fetch_1: 4481 case Builtin::BI__sync_and_and_fetch_2: 4482 case Builtin::BI__sync_and_and_fetch_4: 4483 case Builtin::BI__sync_and_and_fetch_8: 4484 case Builtin::BI__sync_and_and_fetch_16: 4485 BuiltinIndex = 8; 4486 break; 4487 4488 case Builtin::BI__sync_or_and_fetch: 4489 case Builtin::BI__sync_or_and_fetch_1: 4490 case Builtin::BI__sync_or_and_fetch_2: 4491 case Builtin::BI__sync_or_and_fetch_4: 4492 case Builtin::BI__sync_or_and_fetch_8: 4493 case Builtin::BI__sync_or_and_fetch_16: 4494 BuiltinIndex = 9; 4495 break; 4496 4497 case Builtin::BI__sync_xor_and_fetch: 4498 case Builtin::BI__sync_xor_and_fetch_1: 4499 case Builtin::BI__sync_xor_and_fetch_2: 4500 case Builtin::BI__sync_xor_and_fetch_4: 4501 case Builtin::BI__sync_xor_and_fetch_8: 4502 case Builtin::BI__sync_xor_and_fetch_16: 4503 BuiltinIndex = 10; 4504 break; 4505 4506 case Builtin::BI__sync_nand_and_fetch: 4507 case Builtin::BI__sync_nand_and_fetch_1: 4508 case Builtin::BI__sync_nand_and_fetch_2: 4509 case Builtin::BI__sync_nand_and_fetch_4: 4510 case Builtin::BI__sync_nand_and_fetch_8: 4511 case Builtin::BI__sync_nand_and_fetch_16: 4512 BuiltinIndex = 11; 4513 WarnAboutSemanticsChange = true; 4514 break; 4515 4516 case Builtin::BI__sync_val_compare_and_swap: 4517 case Builtin::BI__sync_val_compare_and_swap_1: 4518 case Builtin::BI__sync_val_compare_and_swap_2: 4519 case Builtin::BI__sync_val_compare_and_swap_4: 4520 case Builtin::BI__sync_val_compare_and_swap_8: 4521 case Builtin::BI__sync_val_compare_and_swap_16: 4522 BuiltinIndex = 12; 4523 NumFixed = 2; 4524 break; 4525 4526 case Builtin::BI__sync_bool_compare_and_swap: 4527 case Builtin::BI__sync_bool_compare_and_swap_1: 4528 case Builtin::BI__sync_bool_compare_and_swap_2: 4529 case Builtin::BI__sync_bool_compare_and_swap_4: 4530 case Builtin::BI__sync_bool_compare_and_swap_8: 4531 case Builtin::BI__sync_bool_compare_and_swap_16: 4532 BuiltinIndex = 13; 4533 NumFixed = 2; 4534 ResultType = Context.BoolTy; 4535 break; 4536 4537 case Builtin::BI__sync_lock_test_and_set: 4538 case Builtin::BI__sync_lock_test_and_set_1: 4539 case Builtin::BI__sync_lock_test_and_set_2: 4540 case Builtin::BI__sync_lock_test_and_set_4: 4541 case Builtin::BI__sync_lock_test_and_set_8: 4542 case Builtin::BI__sync_lock_test_and_set_16: 4543 BuiltinIndex = 14; 4544 break; 4545 4546 case Builtin::BI__sync_lock_release: 4547 case Builtin::BI__sync_lock_release_1: 4548 case Builtin::BI__sync_lock_release_2: 4549 case Builtin::BI__sync_lock_release_4: 4550 case Builtin::BI__sync_lock_release_8: 4551 case Builtin::BI__sync_lock_release_16: 4552 BuiltinIndex = 15; 4553 NumFixed = 0; 4554 ResultType = Context.VoidTy; 4555 break; 4556 4557 case Builtin::BI__sync_swap: 4558 case Builtin::BI__sync_swap_1: 4559 case Builtin::BI__sync_swap_2: 4560 case Builtin::BI__sync_swap_4: 4561 case Builtin::BI__sync_swap_8: 4562 case Builtin::BI__sync_swap_16: 4563 BuiltinIndex = 16; 4564 break; 4565 } 4566 4567 // Now that we know how many fixed arguments we expect, first check that we 4568 // have at least that many. 4569 if (TheCall->getNumArgs() < 1+NumFixed) { 4570 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4571 << 0 << 1 + NumFixed << TheCall->getNumArgs() << /*is non object*/ 0 4572 << Callee->getSourceRange(); 4573 return ExprError(); 4574 } 4575 4576 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 4577 << Callee->getSourceRange(); 4578 4579 if (WarnAboutSemanticsChange) { 4580 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 4581 << Callee->getSourceRange(); 4582 } 4583 4584 // Get the decl for the concrete builtin from this, we can tell what the 4585 // concrete integer type we should convert to is. 4586 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 4587 StringRef NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 4588 FunctionDecl *NewBuiltinDecl; 4589 if (NewBuiltinID == BuiltinID) 4590 NewBuiltinDecl = FDecl; 4591 else { 4592 // Perform builtin lookup to avoid redeclaring it. 4593 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 4594 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 4595 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 4596 assert(Res.getFoundDecl()); 4597 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 4598 if (!NewBuiltinDecl) 4599 return ExprError(); 4600 } 4601 4602 // The first argument --- the pointer --- has a fixed type; we 4603 // deduce the types of the rest of the arguments accordingly. Walk 4604 // the remaining arguments, converting them to the deduced value type. 4605 for (unsigned i = 0; i != NumFixed; ++i) { 4606 ExprResult Arg = TheCall->getArg(i+1); 4607 4608 // GCC does an implicit conversion to the pointer or integer ValType. This 4609 // can fail in some cases (1i -> int**), check for this error case now. 4610 // Initialize the argument. 4611 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4612 ValType, /*consume*/ false); 4613 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4614 if (Arg.isInvalid()) 4615 return ExprError(); 4616 4617 // Okay, we have something that *can* be converted to the right type. Check 4618 // to see if there is a potentially weird extension going on here. This can 4619 // happen when you do an atomic operation on something like an char* and 4620 // pass in 42. The 42 gets converted to char. This is even more strange 4621 // for things like 45.123 -> char, etc. 4622 // FIXME: Do this check. 4623 TheCall->setArg(i+1, Arg.get()); 4624 } 4625 4626 // Create a new DeclRefExpr to refer to the new decl. 4627 DeclRefExpr *NewDRE = DeclRefExpr::Create( 4628 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 4629 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 4630 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 4631 4632 // Set the callee in the CallExpr. 4633 // FIXME: This loses syntactic information. 4634 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 4635 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 4636 CK_BuiltinFnToFnPtr); 4637 TheCall->setCallee(PromotedCall.get()); 4638 4639 // Change the result type of the call to match the original value type. This 4640 // is arbitrary, but the codegen for these builtins ins design to handle it 4641 // gracefully. 4642 TheCall->setType(ResultType); 4643 4644 // Prohibit problematic uses of bit-precise integer types with atomic 4645 // builtins. The arguments would have already been converted to the first 4646 // argument's type, so only need to check the first argument. 4647 const auto *BitIntValType = ValType->getAs<BitIntType>(); 4648 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) { 4649 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 4650 return ExprError(); 4651 } 4652 4653 return TheCallResult; 4654 } 4655 4656 ExprResult Sema::BuiltinNontemporalOverloaded(ExprResult TheCallResult) { 4657 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 4658 DeclRefExpr *DRE = 4659 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4660 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4661 unsigned BuiltinID = FDecl->getBuiltinID(); 4662 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 4663 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 4664 "Unexpected nontemporal load/store builtin!"); 4665 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 4666 unsigned numArgs = isStore ? 2 : 1; 4667 4668 // Ensure that we have the proper number of arguments. 4669 if (checkArgCount(TheCall, numArgs)) 4670 return ExprError(); 4671 4672 // Inspect the last argument of the nontemporal builtin. This should always 4673 // be a pointer type, from which we imply the type of the memory access. 4674 // Because it is a pointer type, we don't have to worry about any implicit 4675 // casts here. 4676 Expr *PointerArg = TheCall->getArg(numArgs - 1); 4677 ExprResult PointerArgResult = 4678 DefaultFunctionArrayLvalueConversion(PointerArg); 4679 4680 if (PointerArgResult.isInvalid()) 4681 return ExprError(); 4682 PointerArg = PointerArgResult.get(); 4683 TheCall->setArg(numArgs - 1, PointerArg); 4684 4685 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 4686 if (!pointerType) { 4687 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 4688 << PointerArg->getType() << PointerArg->getSourceRange(); 4689 return ExprError(); 4690 } 4691 4692 QualType ValType = pointerType->getPointeeType(); 4693 4694 // Strip any qualifiers off ValType. 4695 ValType = ValType.getUnqualifiedType(); 4696 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4697 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 4698 !ValType->isVectorType()) { 4699 Diag(DRE->getBeginLoc(), 4700 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 4701 << PointerArg->getType() << PointerArg->getSourceRange(); 4702 return ExprError(); 4703 } 4704 4705 if (!isStore) { 4706 TheCall->setType(ValType); 4707 return TheCallResult; 4708 } 4709 4710 ExprResult ValArg = TheCall->getArg(0); 4711 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4712 Context, ValType, /*consume*/ false); 4713 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 4714 if (ValArg.isInvalid()) 4715 return ExprError(); 4716 4717 TheCall->setArg(0, ValArg.get()); 4718 TheCall->setType(Context.VoidTy); 4719 return TheCallResult; 4720 } 4721 4722 /// CheckObjCString - Checks that the format string argument to the os_log() 4723 /// and os_trace() functions is correct, and converts it to const char *. 4724 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 4725 Arg = Arg->IgnoreParenCasts(); 4726 auto *Literal = dyn_cast<StringLiteral>(Arg); 4727 if (!Literal) { 4728 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 4729 Literal = ObjcLiteral->getString(); 4730 } 4731 } 4732 4733 if (!Literal || (!Literal->isOrdinary() && !Literal->isUTF8())) { 4734 return ExprError( 4735 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 4736 << Arg->getSourceRange()); 4737 } 4738 4739 ExprResult Result(Literal); 4740 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 4741 InitializedEntity Entity = 4742 InitializedEntity::InitializeParameter(Context, ResultTy, false); 4743 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 4744 return Result; 4745 } 4746 4747 /// Check that the user is calling the appropriate va_start builtin for the 4748 /// target and calling convention. 4749 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 4750 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 4751 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 4752 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 4753 TT.getArch() == llvm::Triple::aarch64_32); 4754 bool IsWindows = TT.isOSWindows(); 4755 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 4756 if (IsX64 || IsAArch64) { 4757 CallingConv CC = CC_C; 4758 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 4759 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 4760 if (IsMSVAStart) { 4761 // Don't allow this in System V ABI functions. 4762 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 4763 return S.Diag(Fn->getBeginLoc(), 4764 diag::err_ms_va_start_used_in_sysv_function); 4765 } else { 4766 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 4767 // On x64 Windows, don't allow this in System V ABI functions. 4768 // (Yes, that means there's no corresponding way to support variadic 4769 // System V ABI functions on Windows.) 4770 if ((IsWindows && CC == CC_X86_64SysV) || 4771 (!IsWindows && CC == CC_Win64)) 4772 return S.Diag(Fn->getBeginLoc(), 4773 diag::err_va_start_used_in_wrong_abi_function) 4774 << !IsWindows; 4775 } 4776 return false; 4777 } 4778 4779 if (IsMSVAStart) 4780 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 4781 return false; 4782 } 4783 4784 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 4785 ParmVarDecl **LastParam = nullptr) { 4786 // Determine whether the current function, block, or obj-c method is variadic 4787 // and get its parameter list. 4788 bool IsVariadic = false; 4789 ArrayRef<ParmVarDecl *> Params; 4790 DeclContext *Caller = S.CurContext; 4791 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 4792 IsVariadic = Block->isVariadic(); 4793 Params = Block->parameters(); 4794 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 4795 IsVariadic = FD->isVariadic(); 4796 Params = FD->parameters(); 4797 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 4798 IsVariadic = MD->isVariadic(); 4799 // FIXME: This isn't correct for methods (results in bogus warning). 4800 Params = MD->parameters(); 4801 } else if (isa<CapturedDecl>(Caller)) { 4802 // We don't support va_start in a CapturedDecl. 4803 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 4804 return true; 4805 } else { 4806 // This must be some other declcontext that parses exprs. 4807 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 4808 return true; 4809 } 4810 4811 if (!IsVariadic) { 4812 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 4813 return true; 4814 } 4815 4816 if (LastParam) 4817 *LastParam = Params.empty() ? nullptr : Params.back(); 4818 4819 return false; 4820 } 4821 4822 bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 4823 Expr *Fn = TheCall->getCallee(); 4824 4825 if (checkVAStartABI(*this, BuiltinID, Fn)) 4826 return true; 4827 4828 // In C23 mode, va_start only needs one argument. However, the builtin still 4829 // requires two arguments (which matches the behavior of the GCC builtin), 4830 // <stdarg.h> passes `0` as the second argument in C23 mode. 4831 if (checkArgCount(TheCall, 2)) 4832 return true; 4833 4834 // Type-check the first argument normally. 4835 if (checkBuiltinArgument(*this, TheCall, 0)) 4836 return true; 4837 4838 // Check that the current function is variadic, and get its last parameter. 4839 ParmVarDecl *LastParam; 4840 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 4841 return true; 4842 4843 // Verify that the second argument to the builtin is the last argument of the 4844 // current function or method. In C23 mode, if the second argument is an 4845 // integer constant expression with value 0, then we don't bother with this 4846 // check. 4847 bool SecondArgIsLastNamedArgument = false; 4848 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 4849 if (std::optional<llvm::APSInt> Val = 4850 TheCall->getArg(1)->getIntegerConstantExpr(Context); 4851 Val && LangOpts.C23 && *Val == 0) 4852 return false; 4853 4854 // These are valid if SecondArgIsLastNamedArgument is false after the next 4855 // block. 4856 QualType Type; 4857 SourceLocation ParamLoc; 4858 bool IsCRegister = false; 4859 4860 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 4861 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 4862 SecondArgIsLastNamedArgument = PV == LastParam; 4863 4864 Type = PV->getType(); 4865 ParamLoc = PV->getLocation(); 4866 IsCRegister = 4867 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 4868 } 4869 } 4870 4871 if (!SecondArgIsLastNamedArgument) 4872 Diag(TheCall->getArg(1)->getBeginLoc(), 4873 diag::warn_second_arg_of_va_start_not_last_named_param); 4874 else if (IsCRegister || Type->isReferenceType() || 4875 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 4876 // Promotable integers are UB, but enumerations need a bit of 4877 // extra checking to see what their promotable type actually is. 4878 if (!Context.isPromotableIntegerType(Type)) 4879 return false; 4880 if (!Type->isEnumeralType()) 4881 return true; 4882 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 4883 return !(ED && 4884 Context.typesAreCompatible(ED->getPromotionType(), Type)); 4885 }()) { 4886 unsigned Reason = 0; 4887 if (Type->isReferenceType()) Reason = 1; 4888 else if (IsCRegister) Reason = 2; 4889 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 4890 Diag(ParamLoc, diag::note_parameter_type) << Type; 4891 } 4892 4893 return false; 4894 } 4895 4896 bool Sema::BuiltinVAStartARMMicrosoft(CallExpr *Call) { 4897 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { 4898 const LangOptions &LO = getLangOpts(); 4899 4900 if (LO.CPlusPlus) 4901 return Arg->getType() 4902 .getCanonicalType() 4903 .getTypePtr() 4904 ->getPointeeType() 4905 .withoutLocalFastQualifiers() == Context.CharTy; 4906 4907 // In C, allow aliasing through `char *`, this is required for AArch64 at 4908 // least. 4909 return true; 4910 }; 4911 4912 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 4913 // const char *named_addr); 4914 4915 Expr *Func = Call->getCallee(); 4916 4917 if (Call->getNumArgs() < 3) 4918 return Diag(Call->getEndLoc(), 4919 diag::err_typecheck_call_too_few_args_at_least) 4920 << 0 /*function call*/ << 3 << Call->getNumArgs() 4921 << /*is non object*/ 0; 4922 4923 // Type-check the first argument normally. 4924 if (checkBuiltinArgument(*this, Call, 0)) 4925 return true; 4926 4927 // Check that the current function is variadic. 4928 if (checkVAStartIsInVariadicFunction(*this, Func)) 4929 return true; 4930 4931 // __va_start on Windows does not validate the parameter qualifiers 4932 4933 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 4934 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 4935 4936 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 4937 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 4938 4939 const QualType &ConstCharPtrTy = 4940 Context.getPointerType(Context.CharTy.withConst()); 4941 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) 4942 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 4943 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 4944 << 0 /* qualifier difference */ 4945 << 3 /* parameter mismatch */ 4946 << 2 << Arg1->getType() << ConstCharPtrTy; 4947 4948 const QualType SizeTy = Context.getSizeType(); 4949 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 4950 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 4951 << Arg2->getType() << SizeTy << 1 /* different class */ 4952 << 0 /* qualifier difference */ 4953 << 3 /* parameter mismatch */ 4954 << 3 << Arg2->getType() << SizeTy; 4955 4956 return false; 4957 } 4958 4959 bool Sema::BuiltinUnorderedCompare(CallExpr *TheCall, unsigned BuiltinID) { 4960 if (checkArgCount(TheCall, 2)) 4961 return true; 4962 4963 if (BuiltinID == Builtin::BI__builtin_isunordered && 4964 TheCall->getFPFeaturesInEffect(getLangOpts()).getNoHonorNaNs()) 4965 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled) 4966 << 1 << 0 << TheCall->getSourceRange(); 4967 4968 ExprResult OrigArg0 = TheCall->getArg(0); 4969 ExprResult OrigArg1 = TheCall->getArg(1); 4970 4971 // Do standard promotions between the two arguments, returning their common 4972 // type. 4973 QualType Res = UsualArithmeticConversions( 4974 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 4975 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 4976 return true; 4977 4978 // Make sure any conversions are pushed back into the call; this is 4979 // type safe since unordered compare builtins are declared as "_Bool 4980 // foo(...)". 4981 TheCall->setArg(0, OrigArg0.get()); 4982 TheCall->setArg(1, OrigArg1.get()); 4983 4984 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 4985 return false; 4986 4987 // If the common type isn't a real floating type, then the arguments were 4988 // invalid for this operation. 4989 if (Res.isNull() || !Res->isRealFloatingType()) 4990 return Diag(OrigArg0.get()->getBeginLoc(), 4991 diag::err_typecheck_call_invalid_ordered_compare) 4992 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 4993 << SourceRange(OrigArg0.get()->getBeginLoc(), 4994 OrigArg1.get()->getEndLoc()); 4995 4996 return false; 4997 } 4998 4999 bool Sema::BuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs, 5000 unsigned BuiltinID) { 5001 if (checkArgCount(TheCall, NumArgs)) 5002 return true; 5003 5004 FPOptions FPO = TheCall->getFPFeaturesInEffect(getLangOpts()); 5005 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite || 5006 BuiltinID == Builtin::BI__builtin_isinf || 5007 BuiltinID == Builtin::BI__builtin_isinf_sign)) 5008 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled) 5009 << 0 << 0 << TheCall->getSourceRange(); 5010 5011 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan || 5012 BuiltinID == Builtin::BI__builtin_isunordered)) 5013 Diag(TheCall->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled) 5014 << 1 << 0 << TheCall->getSourceRange(); 5015 5016 bool IsFPClass = NumArgs == 2; 5017 5018 // Find out position of floating-point argument. 5019 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1; 5020 5021 // We can count on all parameters preceding the floating-point just being int. 5022 // Try all of those. 5023 for (unsigned i = 0; i < FPArgNo; ++i) { 5024 Expr *Arg = TheCall->getArg(i); 5025 5026 if (Arg->isTypeDependent()) 5027 return false; 5028 5029 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, 5030 AssignmentAction::Passing); 5031 5032 if (Res.isInvalid()) 5033 return true; 5034 TheCall->setArg(i, Res.get()); 5035 } 5036 5037 Expr *OrigArg = TheCall->getArg(FPArgNo); 5038 5039 if (OrigArg->isTypeDependent()) 5040 return false; 5041 5042 // Usual Unary Conversions will convert half to float, which we want for 5043 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5044 // type how it is, but do normal L->Rvalue conversions. 5045 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) { 5046 ExprResult Res = UsualUnaryConversions(OrigArg); 5047 5048 if (!Res.isUsable()) 5049 return true; 5050 OrigArg = Res.get(); 5051 } else { 5052 ExprResult Res = DefaultFunctionArrayLvalueConversion(OrigArg); 5053 5054 if (!Res.isUsable()) 5055 return true; 5056 OrigArg = Res.get(); 5057 } 5058 TheCall->setArg(FPArgNo, OrigArg); 5059 5060 QualType VectorResultTy; 5061 QualType ElementTy = OrigArg->getType(); 5062 // TODO: When all classification function are implemented with is_fpclass, 5063 // vector argument can be supported in all of them. 5064 if (ElementTy->isVectorType() && IsFPClass) { 5065 VectorResultTy = GetSignedVectorType(ElementTy); 5066 ElementTy = ElementTy->castAs<VectorType>()->getElementType(); 5067 } 5068 5069 // This operation requires a non-_Complex floating-point number. 5070 if (!ElementTy->isRealFloatingType()) 5071 return Diag(OrigArg->getBeginLoc(), 5072 diag::err_typecheck_call_invalid_unary_fp) 5073 << OrigArg->getType() << OrigArg->getSourceRange(); 5074 5075 // __builtin_isfpclass has integer parameter that specify test mask. It is 5076 // passed in (...), so it should be analyzed completely here. 5077 if (IsFPClass) 5078 if (BuiltinConstantArgRange(TheCall, 1, 0, llvm::fcAllFlags)) 5079 return true; 5080 5081 // TODO: enable this code to all classification functions. 5082 if (IsFPClass) { 5083 QualType ResultTy; 5084 if (!VectorResultTy.isNull()) 5085 ResultTy = VectorResultTy; 5086 else 5087 ResultTy = Context.IntTy; 5088 TheCall->setType(ResultTy); 5089 } 5090 5091 return false; 5092 } 5093 5094 bool Sema::BuiltinComplex(CallExpr *TheCall) { 5095 if (checkArgCount(TheCall, 2)) 5096 return true; 5097 5098 bool Dependent = false; 5099 for (unsigned I = 0; I != 2; ++I) { 5100 Expr *Arg = TheCall->getArg(I); 5101 QualType T = Arg->getType(); 5102 if (T->isDependentType()) { 5103 Dependent = true; 5104 continue; 5105 } 5106 5107 // Despite supporting _Complex int, GCC requires a real floating point type 5108 // for the operands of __builtin_complex. 5109 if (!T->isRealFloatingType()) { 5110 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 5111 << Arg->getType() << Arg->getSourceRange(); 5112 } 5113 5114 ExprResult Converted = DefaultLvalueConversion(Arg); 5115 if (Converted.isInvalid()) 5116 return true; 5117 TheCall->setArg(I, Converted.get()); 5118 } 5119 5120 if (Dependent) { 5121 TheCall->setType(Context.DependentTy); 5122 return false; 5123 } 5124 5125 Expr *Real = TheCall->getArg(0); 5126 Expr *Imag = TheCall->getArg(1); 5127 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 5128 return Diag(Real->getBeginLoc(), 5129 diag::err_typecheck_call_different_arg_types) 5130 << Real->getType() << Imag->getType() 5131 << Real->getSourceRange() << Imag->getSourceRange(); 5132 } 5133 5134 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 5135 // don't allow this builtin to form those types either. 5136 // FIXME: Should we allow these types? 5137 if (Real->getType()->isFloat16Type()) 5138 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 5139 << "_Float16"; 5140 if (Real->getType()->isHalfType()) 5141 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 5142 << "half"; 5143 5144 TheCall->setType(Context.getComplexType(Real->getType())); 5145 return false; 5146 } 5147 5148 /// BuiltinShuffleVector - Handle __builtin_shufflevector. 5149 // This is declared to take (...), so we have to check everything. 5150 ExprResult Sema::BuiltinShuffleVector(CallExpr *TheCall) { 5151 if (TheCall->getNumArgs() < 2) 5152 return ExprError(Diag(TheCall->getEndLoc(), 5153 diag::err_typecheck_call_too_few_args_at_least) 5154 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5155 << /*is non object*/ 0 << TheCall->getSourceRange()); 5156 5157 // Determine which of the following types of shufflevector we're checking: 5158 // 1) unary, vector mask: (lhs, mask) 5159 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5160 QualType resType = TheCall->getArg(0)->getType(); 5161 unsigned numElements = 0; 5162 5163 if (!TheCall->getArg(0)->isTypeDependent() && 5164 !TheCall->getArg(1)->isTypeDependent()) { 5165 QualType LHSType = TheCall->getArg(0)->getType(); 5166 QualType RHSType = TheCall->getArg(1)->getType(); 5167 5168 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5169 return ExprError( 5170 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5171 << TheCall->getDirectCallee() << /*isMorethantwoArgs*/ false 5172 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5173 TheCall->getArg(1)->getEndLoc())); 5174 5175 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5176 unsigned numResElements = TheCall->getNumArgs() - 2; 5177 5178 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5179 // with mask. If so, verify that RHS is an integer vector type with the 5180 // same number of elts as lhs. 5181 if (TheCall->getNumArgs() == 2) { 5182 if (!RHSType->hasIntegerRepresentation() || 5183 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5184 return ExprError(Diag(TheCall->getBeginLoc(), 5185 diag::err_vec_builtin_incompatible_vector) 5186 << TheCall->getDirectCallee() 5187 << /*isMorethantwoArgs*/ false 5188 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5189 TheCall->getArg(1)->getEndLoc())); 5190 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5191 return ExprError(Diag(TheCall->getBeginLoc(), 5192 diag::err_vec_builtin_incompatible_vector) 5193 << TheCall->getDirectCallee() 5194 << /*isMorethantwoArgs*/ false 5195 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5196 TheCall->getArg(1)->getEndLoc())); 5197 } else if (numElements != numResElements) { 5198 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5199 resType = 5200 Context.getVectorType(eltType, numResElements, VectorKind::Generic); 5201 } 5202 } 5203 5204 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5205 if (TheCall->getArg(i)->isTypeDependent() || 5206 TheCall->getArg(i)->isValueDependent()) 5207 continue; 5208 5209 std::optional<llvm::APSInt> Result; 5210 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 5211 return ExprError(Diag(TheCall->getBeginLoc(), 5212 diag::err_shufflevector_nonconstant_argument) 5213 << TheCall->getArg(i)->getSourceRange()); 5214 5215 // Allow -1 which will be translated to undef in the IR. 5216 if (Result->isSigned() && Result->isAllOnes()) 5217 continue; 5218 5219 if (Result->getActiveBits() > 64 || 5220 Result->getZExtValue() >= numElements * 2) 5221 return ExprError(Diag(TheCall->getBeginLoc(), 5222 diag::err_shufflevector_argument_too_large) 5223 << TheCall->getArg(i)->getSourceRange()); 5224 } 5225 5226 SmallVector<Expr*, 32> exprs; 5227 5228 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5229 exprs.push_back(TheCall->getArg(i)); 5230 TheCall->setArg(i, nullptr); 5231 } 5232 5233 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5234 TheCall->getCallee()->getBeginLoc(), 5235 TheCall->getRParenLoc()); 5236 } 5237 5238 ExprResult Sema::ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5239 SourceLocation BuiltinLoc, 5240 SourceLocation RParenLoc) { 5241 ExprValueKind VK = VK_PRValue; 5242 ExprObjectKind OK = OK_Ordinary; 5243 QualType DstTy = TInfo->getType(); 5244 QualType SrcTy = E->getType(); 5245 5246 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5247 return ExprError(Diag(BuiltinLoc, 5248 diag::err_convertvector_non_vector) 5249 << E->getSourceRange()); 5250 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5251 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type) 5252 << "second" 5253 << "__builtin_convertvector"); 5254 5255 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5256 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 5257 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 5258 if (SrcElts != DstElts) 5259 return ExprError(Diag(BuiltinLoc, 5260 diag::err_convertvector_incompatible_vector) 5261 << E->getSourceRange()); 5262 } 5263 5264 return new (Context) class ConvertVectorExpr(E, TInfo, DstTy, VK, OK, 5265 BuiltinLoc, RParenLoc); 5266 } 5267 5268 bool Sema::BuiltinPrefetch(CallExpr *TheCall) { 5269 unsigned NumArgs = TheCall->getNumArgs(); 5270 5271 if (NumArgs > 3) 5272 return Diag(TheCall->getEndLoc(), 5273 diag::err_typecheck_call_too_many_args_at_most) 5274 << 0 /*function call*/ << 3 << NumArgs << /*is non object*/ 0 5275 << TheCall->getSourceRange(); 5276 5277 // Argument 0 is checked for us and the remaining arguments must be 5278 // constant integers. 5279 for (unsigned i = 1; i != NumArgs; ++i) 5280 if (BuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5281 return true; 5282 5283 return false; 5284 } 5285 5286 bool Sema::BuiltinArithmeticFence(CallExpr *TheCall) { 5287 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 5288 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 5289 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 5290 if (checkArgCount(TheCall, 1)) 5291 return true; 5292 Expr *Arg = TheCall->getArg(0); 5293 if (Arg->isInstantiationDependent()) 5294 return false; 5295 5296 QualType ArgTy = Arg->getType(); 5297 if (!ArgTy->hasFloatingRepresentation()) 5298 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 5299 << ArgTy; 5300 if (Arg->isLValue()) { 5301 ExprResult FirstArg = DefaultLvalueConversion(Arg); 5302 TheCall->setArg(0, FirstArg.get()); 5303 } 5304 TheCall->setType(TheCall->getArg(0)->getType()); 5305 return false; 5306 } 5307 5308 bool Sema::BuiltinAssume(CallExpr *TheCall) { 5309 Expr *Arg = TheCall->getArg(0); 5310 if (Arg->isInstantiationDependent()) return false; 5311 5312 if (Arg->HasSideEffects(Context)) 5313 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5314 << Arg->getSourceRange() 5315 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5316 5317 return false; 5318 } 5319 5320 bool Sema::BuiltinAllocaWithAlign(CallExpr *TheCall) { 5321 // The alignment must be a constant integer. 5322 Expr *Arg = TheCall->getArg(1); 5323 5324 // We can't check the value of a dependent argument. 5325 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5326 if (const auto *UE = 5327 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5328 if (UE->getKind() == UETT_AlignOf || 5329 UE->getKind() == UETT_PreferredAlignOf) 5330 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5331 << Arg->getSourceRange(); 5332 5333 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5334 5335 if (!Result.isPowerOf2()) 5336 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5337 << Arg->getSourceRange(); 5338 5339 if (Result < Context.getCharWidth()) 5340 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5341 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5342 5343 if (Result > std::numeric_limits<int32_t>::max()) 5344 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5345 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5346 } 5347 5348 return false; 5349 } 5350 5351 bool Sema::BuiltinAssumeAligned(CallExpr *TheCall) { 5352 if (checkArgCountRange(TheCall, 2, 3)) 5353 return true; 5354 5355 unsigned NumArgs = TheCall->getNumArgs(); 5356 Expr *FirstArg = TheCall->getArg(0); 5357 5358 { 5359 ExprResult FirstArgResult = 5360 DefaultFunctionArrayLvalueConversion(FirstArg); 5361 if (!FirstArgResult.get()->getType()->isPointerType()) { 5362 Diag(TheCall->getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg) 5363 << TheCall->getSourceRange(); 5364 return true; 5365 } 5366 TheCall->setArg(0, FirstArgResult.get()); 5367 } 5368 5369 // The alignment must be a constant integer. 5370 Expr *SecondArg = TheCall->getArg(1); 5371 5372 // We can't check the value of a dependent argument. 5373 if (!SecondArg->isValueDependent()) { 5374 llvm::APSInt Result; 5375 if (BuiltinConstantArg(TheCall, 1, Result)) 5376 return true; 5377 5378 if (!Result.isPowerOf2()) 5379 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5380 << SecondArg->getSourceRange(); 5381 5382 if (Result > Sema::MaximumAlignment) 5383 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 5384 << SecondArg->getSourceRange() << Sema::MaximumAlignment; 5385 } 5386 5387 if (NumArgs > 2) { 5388 Expr *ThirdArg = TheCall->getArg(2); 5389 if (convertArgumentToType(*this, ThirdArg, Context.getSizeType())) 5390 return true; 5391 TheCall->setArg(2, ThirdArg); 5392 } 5393 5394 return false; 5395 } 5396 5397 bool Sema::BuiltinOSLogFormat(CallExpr *TheCall) { 5398 unsigned BuiltinID = 5399 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5400 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5401 5402 unsigned NumArgs = TheCall->getNumArgs(); 5403 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5404 if (NumArgs < NumRequiredArgs) { 5405 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5406 << 0 /* function call */ << NumRequiredArgs << NumArgs 5407 << /*is non object*/ 0 << TheCall->getSourceRange(); 5408 } 5409 if (NumArgs >= NumRequiredArgs + 0x100) { 5410 return Diag(TheCall->getEndLoc(), 5411 diag::err_typecheck_call_too_many_args_at_most) 5412 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5413 << /*is non object*/ 0 << TheCall->getSourceRange(); 5414 } 5415 unsigned i = 0; 5416 5417 // For formatting call, check buffer arg. 5418 if (!IsSizeCall) { 5419 ExprResult Arg(TheCall->getArg(i)); 5420 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5421 Context, Context.VoidPtrTy, false); 5422 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5423 if (Arg.isInvalid()) 5424 return true; 5425 TheCall->setArg(i, Arg.get()); 5426 i++; 5427 } 5428 5429 // Check string literal arg. 5430 unsigned FormatIdx = i; 5431 { 5432 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5433 if (Arg.isInvalid()) 5434 return true; 5435 TheCall->setArg(i, Arg.get()); 5436 i++; 5437 } 5438 5439 // Make sure variadic args are scalar. 5440 unsigned FirstDataArg = i; 5441 while (i < NumArgs) { 5442 ExprResult Arg = DefaultVariadicArgumentPromotion( 5443 TheCall->getArg(i), VariadicFunction, nullptr); 5444 if (Arg.isInvalid()) 5445 return true; 5446 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5447 if (ArgSize.getQuantity() >= 0x100) { 5448 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5449 << i << (int)ArgSize.getQuantity() << 0xff 5450 << TheCall->getSourceRange(); 5451 } 5452 TheCall->setArg(i, Arg.get()); 5453 i++; 5454 } 5455 5456 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5457 // call to avoid duplicate diagnostics. 5458 if (!IsSizeCall) { 5459 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 5460 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 5461 bool Success = CheckFormatArguments( 5462 Args, FAPK_Variadic, FormatIdx, FirstDataArg, FST_OSLog, 5463 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 5464 CheckedVarArgs); 5465 if (!Success) 5466 return true; 5467 } 5468 5469 if (IsSizeCall) { 5470 TheCall->setType(Context.getSizeType()); 5471 } else { 5472 TheCall->setType(Context.VoidPtrTy); 5473 } 5474 return false; 5475 } 5476 5477 bool Sema::BuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5478 llvm::APSInt &Result) { 5479 Expr *Arg = TheCall->getArg(ArgNum); 5480 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5481 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5482 5483 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5484 5485 std::optional<llvm::APSInt> R; 5486 if (!(R = Arg->getIntegerConstantExpr(Context))) 5487 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 5488 << FDecl->getDeclName() << Arg->getSourceRange(); 5489 Result = *R; 5490 return false; 5491 } 5492 5493 bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, 5494 int High, bool RangeIsError) { 5495 if (isConstantEvaluatedContext()) 5496 return false; 5497 llvm::APSInt Result; 5498 5499 // We can't check the value of a dependent argument. 5500 Expr *Arg = TheCall->getArg(ArgNum); 5501 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5502 return false; 5503 5504 // Check constant-ness first. 5505 if (BuiltinConstantArg(TheCall, ArgNum, Result)) 5506 return true; 5507 5508 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 5509 if (RangeIsError) 5510 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 5511 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 5512 else 5513 // Defer the warning until we know if the code will be emitted so that 5514 // dead code can ignore this. 5515 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 5516 PDiag(diag::warn_argument_invalid_range) 5517 << toString(Result, 10) << Low << High 5518 << Arg->getSourceRange()); 5519 } 5520 5521 return false; 5522 } 5523 5524 bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 5525 unsigned Num) { 5526 llvm::APSInt Result; 5527 5528 // We can't check the value of a dependent argument. 5529 Expr *Arg = TheCall->getArg(ArgNum); 5530 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5531 return false; 5532 5533 // Check constant-ness first. 5534 if (BuiltinConstantArg(TheCall, ArgNum, Result)) 5535 return true; 5536 5537 if (Result.getSExtValue() % Num != 0) 5538 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 5539 << Num << Arg->getSourceRange(); 5540 5541 return false; 5542 } 5543 5544 bool Sema::BuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 5545 llvm::APSInt Result; 5546 5547 // We can't check the value of a dependent argument. 5548 Expr *Arg = TheCall->getArg(ArgNum); 5549 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5550 return false; 5551 5552 // Check constant-ness first. 5553 if (BuiltinConstantArg(TheCall, ArgNum, Result)) 5554 return true; 5555 5556 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 5557 // and only if x is a power of 2. 5558 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 5559 return false; 5560 5561 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 5562 << Arg->getSourceRange(); 5563 } 5564 5565 static bool IsShiftedByte(llvm::APSInt Value) { 5566 if (Value.isNegative()) 5567 return false; 5568 5569 // Check if it's a shifted byte, by shifting it down 5570 while (true) { 5571 // If the value fits in the bottom byte, the check passes. 5572 if (Value < 0x100) 5573 return true; 5574 5575 // Otherwise, if the value has _any_ bits in the bottom byte, the check 5576 // fails. 5577 if ((Value & 0xFF) != 0) 5578 return false; 5579 5580 // If the bottom 8 bits are all 0, but something above that is nonzero, 5581 // then shifting the value right by 8 bits won't affect whether it's a 5582 // shifted byte or not. So do that, and go round again. 5583 Value >>= 8; 5584 } 5585 } 5586 5587 bool Sema::BuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 5588 unsigned ArgBits) { 5589 llvm::APSInt Result; 5590 5591 // We can't check the value of a dependent argument. 5592 Expr *Arg = TheCall->getArg(ArgNum); 5593 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5594 return false; 5595 5596 // Check constant-ness first. 5597 if (BuiltinConstantArg(TheCall, ArgNum, Result)) 5598 return true; 5599 5600 // Truncate to the given size. 5601 Result = Result.getLoBits(ArgBits); 5602 Result.setIsUnsigned(true); 5603 5604 if (IsShiftedByte(Result)) 5605 return false; 5606 5607 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 5608 << Arg->getSourceRange(); 5609 } 5610 5611 bool Sema::BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, 5612 unsigned ArgBits) { 5613 llvm::APSInt Result; 5614 5615 // We can't check the value of a dependent argument. 5616 Expr *Arg = TheCall->getArg(ArgNum); 5617 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5618 return false; 5619 5620 // Check constant-ness first. 5621 if (BuiltinConstantArg(TheCall, ArgNum, Result)) 5622 return true; 5623 5624 // Truncate to the given size. 5625 Result = Result.getLoBits(ArgBits); 5626 Result.setIsUnsigned(true); 5627 5628 // Check to see if it's in either of the required forms. 5629 if (IsShiftedByte(Result) || 5630 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 5631 return false; 5632 5633 return Diag(TheCall->getBeginLoc(), 5634 diag::err_argument_not_shifted_byte_or_xxff) 5635 << Arg->getSourceRange(); 5636 } 5637 5638 bool Sema::BuiltinLongjmp(CallExpr *TheCall) { 5639 if (!Context.getTargetInfo().hasSjLjLowering()) 5640 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 5641 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 5642 5643 Expr *Arg = TheCall->getArg(1); 5644 llvm::APSInt Result; 5645 5646 // TODO: This is less than ideal. Overload this to take a value. 5647 if (BuiltinConstantArg(TheCall, 1, Result)) 5648 return true; 5649 5650 if (Result != 1) 5651 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 5652 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 5653 5654 return false; 5655 } 5656 5657 bool Sema::BuiltinSetjmp(CallExpr *TheCall) { 5658 if (!Context.getTargetInfo().hasSjLjLowering()) 5659 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 5660 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 5661 return false; 5662 } 5663 5664 bool Sema::BuiltinCountedByRef(CallExpr *TheCall) { 5665 if (checkArgCount(TheCall, 1)) 5666 return true; 5667 5668 ExprResult ArgRes = UsualUnaryConversions(TheCall->getArg(0)); 5669 if (ArgRes.isInvalid()) 5670 return true; 5671 5672 // For simplicity, we support only limited expressions for the argument. 5673 // Specifically a pointer to a flexible array member:'ptr->array'. This 5674 // allows us to reject arguments with complex casting, which really shouldn't 5675 // be a huge problem. 5676 const Expr *Arg = ArgRes.get()->IgnoreParenImpCasts(); 5677 if (!isa<PointerType>(Arg->getType()) && !Arg->getType()->isArrayType()) 5678 return Diag(Arg->getBeginLoc(), 5679 diag::err_builtin_counted_by_ref_must_be_flex_array_member) 5680 << Arg->getSourceRange(); 5681 5682 if (Arg->HasSideEffects(Context)) 5683 return Diag(Arg->getBeginLoc(), 5684 diag::err_builtin_counted_by_ref_has_side_effects) 5685 << Arg->getSourceRange(); 5686 5687 if (const auto *ME = dyn_cast<MemberExpr>(Arg)) { 5688 if (!ME->isFlexibleArrayMemberLike( 5689 Context, getLangOpts().getStrictFlexArraysLevel())) 5690 return Diag(Arg->getBeginLoc(), 5691 diag::err_builtin_counted_by_ref_must_be_flex_array_member) 5692 << Arg->getSourceRange(); 5693 5694 if (auto *CATy = 5695 ME->getMemberDecl()->getType()->getAs<CountAttributedType>(); 5696 CATy && CATy->getKind() == CountAttributedType::CountedBy) { 5697 const auto *FAMDecl = cast<FieldDecl>(ME->getMemberDecl()); 5698 if (const FieldDecl *CountFD = FAMDecl->findCountedByField()) { 5699 TheCall->setType(Context.getPointerType(CountFD->getType())); 5700 return false; 5701 } 5702 } 5703 } else { 5704 return Diag(Arg->getBeginLoc(), 5705 diag::err_builtin_counted_by_ref_must_be_flex_array_member) 5706 << Arg->getSourceRange(); 5707 } 5708 5709 TheCall->setType(Context.getPointerType(Context.VoidTy)); 5710 return false; 5711 } 5712 5713 /// The result of __builtin_counted_by_ref cannot be assigned to a variable. 5714 /// It allows leaking and modification of bounds safety information. 5715 bool Sema::CheckInvalidBuiltinCountedByRef(const Expr *E, 5716 BuiltinCountedByRefKind K) { 5717 const CallExpr *CE = 5718 E ? dyn_cast<CallExpr>(E->IgnoreParenImpCasts()) : nullptr; 5719 if (!CE || CE->getBuiltinCallee() != Builtin::BI__builtin_counted_by_ref) 5720 return false; 5721 5722 switch (K) { 5723 case AssignmentKind: 5724 case InitializerKind: 5725 Diag(E->getExprLoc(), 5726 diag::err_builtin_counted_by_ref_cannot_leak_reference) 5727 << 0 << E->getSourceRange(); 5728 break; 5729 case FunctionArgKind: 5730 Diag(E->getExprLoc(), 5731 diag::err_builtin_counted_by_ref_cannot_leak_reference) 5732 << 1 << E->getSourceRange(); 5733 break; 5734 case ReturnArgKind: 5735 Diag(E->getExprLoc(), 5736 diag::err_builtin_counted_by_ref_cannot_leak_reference) 5737 << 2 << E->getSourceRange(); 5738 break; 5739 case ArraySubscriptKind: 5740 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use) 5741 << 0 << E->getSourceRange(); 5742 break; 5743 case BinaryExprKind: 5744 Diag(E->getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use) 5745 << 1 << E->getSourceRange(); 5746 break; 5747 } 5748 5749 return true; 5750 } 5751 5752 namespace { 5753 5754 class UncoveredArgHandler { 5755 enum { Unknown = -1, AllCovered = -2 }; 5756 5757 signed FirstUncoveredArg = Unknown; 5758 SmallVector<const Expr *, 4> DiagnosticExprs; 5759 5760 public: 5761 UncoveredArgHandler() = default; 5762 5763 bool hasUncoveredArg() const { 5764 return (FirstUncoveredArg >= 0); 5765 } 5766 5767 unsigned getUncoveredArg() const { 5768 assert(hasUncoveredArg() && "no uncovered argument"); 5769 return FirstUncoveredArg; 5770 } 5771 5772 void setAllCovered() { 5773 // A string has been found with all arguments covered, so clear out 5774 // the diagnostics. 5775 DiagnosticExprs.clear(); 5776 FirstUncoveredArg = AllCovered; 5777 } 5778 5779 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 5780 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 5781 5782 // Don't update if a previous string covers all arguments. 5783 if (FirstUncoveredArg == AllCovered) 5784 return; 5785 5786 // UncoveredArgHandler tracks the highest uncovered argument index 5787 // and with it all the strings that match this index. 5788 if (NewFirstUncoveredArg == FirstUncoveredArg) 5789 DiagnosticExprs.push_back(StrExpr); 5790 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 5791 DiagnosticExprs.clear(); 5792 DiagnosticExprs.push_back(StrExpr); 5793 FirstUncoveredArg = NewFirstUncoveredArg; 5794 } 5795 } 5796 5797 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 5798 }; 5799 5800 enum StringLiteralCheckType { 5801 SLCT_NotALiteral, 5802 SLCT_UncheckedLiteral, 5803 SLCT_CheckedLiteral 5804 }; 5805 5806 } // namespace 5807 5808 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 5809 BinaryOperatorKind BinOpKind, 5810 bool AddendIsRight) { 5811 unsigned BitWidth = Offset.getBitWidth(); 5812 unsigned AddendBitWidth = Addend.getBitWidth(); 5813 // There might be negative interim results. 5814 if (Addend.isUnsigned()) { 5815 Addend = Addend.zext(++AddendBitWidth); 5816 Addend.setIsSigned(true); 5817 } 5818 // Adjust the bit width of the APSInts. 5819 if (AddendBitWidth > BitWidth) { 5820 Offset = Offset.sext(AddendBitWidth); 5821 BitWidth = AddendBitWidth; 5822 } else if (BitWidth > AddendBitWidth) { 5823 Addend = Addend.sext(BitWidth); 5824 } 5825 5826 bool Ov = false; 5827 llvm::APSInt ResOffset = Offset; 5828 if (BinOpKind == BO_Add) 5829 ResOffset = Offset.sadd_ov(Addend, Ov); 5830 else { 5831 assert(AddendIsRight && BinOpKind == BO_Sub && 5832 "operator must be add or sub with addend on the right"); 5833 ResOffset = Offset.ssub_ov(Addend, Ov); 5834 } 5835 5836 // We add an offset to a pointer here so we should support an offset as big as 5837 // possible. 5838 if (Ov) { 5839 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 5840 "index (intermediate) result too big"); 5841 Offset = Offset.sext(2 * BitWidth); 5842 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 5843 return; 5844 } 5845 5846 Offset = ResOffset; 5847 } 5848 5849 namespace { 5850 5851 // This is a wrapper class around StringLiteral to support offsetted string 5852 // literals as format strings. It takes the offset into account when returning 5853 // the string and its length or the source locations to display notes correctly. 5854 class FormatStringLiteral { 5855 const StringLiteral *FExpr; 5856 int64_t Offset; 5857 5858 public: 5859 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 5860 : FExpr(fexpr), Offset(Offset) {} 5861 5862 StringRef getString() const { 5863 return FExpr->getString().drop_front(Offset); 5864 } 5865 5866 unsigned getByteLength() const { 5867 return FExpr->getByteLength() - getCharByteWidth() * Offset; 5868 } 5869 5870 unsigned getLength() const { return FExpr->getLength() - Offset; } 5871 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 5872 5873 StringLiteralKind getKind() const { return FExpr->getKind(); } 5874 5875 QualType getType() const { return FExpr->getType(); } 5876 5877 bool isAscii() const { return FExpr->isOrdinary(); } 5878 bool isWide() const { return FExpr->isWide(); } 5879 bool isUTF8() const { return FExpr->isUTF8(); } 5880 bool isUTF16() const { return FExpr->isUTF16(); } 5881 bool isUTF32() const { return FExpr->isUTF32(); } 5882 bool isPascal() const { return FExpr->isPascal(); } 5883 5884 SourceLocation getLocationOfByte( 5885 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 5886 const TargetInfo &Target, unsigned *StartToken = nullptr, 5887 unsigned *StartTokenByteOffset = nullptr) const { 5888 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 5889 StartToken, StartTokenByteOffset); 5890 } 5891 5892 SourceLocation getBeginLoc() const LLVM_READONLY { 5893 return FExpr->getBeginLoc().getLocWithOffset(Offset); 5894 } 5895 5896 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 5897 }; 5898 5899 } // namespace 5900 5901 static void CheckFormatString( 5902 Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr, 5903 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK, 5904 unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, 5905 bool inFunctionCall, Sema::VariadicCallType CallType, 5906 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, 5907 bool IgnoreStringsWithoutSpecifiers); 5908 5909 static const Expr *maybeConstEvalStringLiteral(ASTContext &Context, 5910 const Expr *E); 5911 5912 // Determine if an expression is a string literal or constant string. 5913 // If this function returns false on the arguments to a function expecting a 5914 // format string, we will usually need to emit a warning. 5915 // True string literals are then checked by CheckFormatString. 5916 static StringLiteralCheckType 5917 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 5918 Sema::FormatArgumentPassingKind APK, unsigned format_idx, 5919 unsigned firstDataArg, Sema::FormatStringType Type, 5920 Sema::VariadicCallType CallType, bool InFunctionCall, 5921 llvm::SmallBitVector &CheckedVarArgs, 5922 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, 5923 bool IgnoreStringsWithoutSpecifiers = false) { 5924 if (S.isConstantEvaluatedContext()) 5925 return SLCT_NotALiteral; 5926 tryAgain: 5927 assert(Offset.isSigned() && "invalid offset"); 5928 5929 if (E->isTypeDependent() || E->isValueDependent()) 5930 return SLCT_NotALiteral; 5931 5932 E = E->IgnoreParenCasts(); 5933 5934 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 5935 // Technically -Wformat-nonliteral does not warn about this case. 5936 // The behavior of printf and friends in this case is implementation 5937 // dependent. Ideally if the format string cannot be null then 5938 // it should have a 'nonnull' attribute in the function prototype. 5939 return SLCT_UncheckedLiteral; 5940 5941 switch (E->getStmtClass()) { 5942 case Stmt::InitListExprClass: 5943 // Handle expressions like {"foobar"}. 5944 if (const clang::Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) { 5945 return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg, 5946 Type, CallType, /*InFunctionCall*/ false, 5947 CheckedVarArgs, UncoveredArg, Offset, 5948 IgnoreStringsWithoutSpecifiers); 5949 } 5950 return SLCT_NotALiteral; 5951 case Stmt::BinaryConditionalOperatorClass: 5952 case Stmt::ConditionalOperatorClass: { 5953 // The expression is a literal if both sub-expressions were, and it was 5954 // completely checked only if both sub-expressions were checked. 5955 const AbstractConditionalOperator *C = 5956 cast<AbstractConditionalOperator>(E); 5957 5958 // Determine whether it is necessary to check both sub-expressions, for 5959 // example, because the condition expression is a constant that can be 5960 // evaluated at compile time. 5961 bool CheckLeft = true, CheckRight = true; 5962 5963 bool Cond; 5964 if (C->getCond()->EvaluateAsBooleanCondition( 5965 Cond, S.getASTContext(), S.isConstantEvaluatedContext())) { 5966 if (Cond) 5967 CheckRight = false; 5968 else 5969 CheckLeft = false; 5970 } 5971 5972 // We need to maintain the offsets for the right and the left hand side 5973 // separately to check if every possible indexed expression is a valid 5974 // string literal. They might have different offsets for different string 5975 // literals in the end. 5976 StringLiteralCheckType Left; 5977 if (!CheckLeft) 5978 Left = SLCT_UncheckedLiteral; 5979 else { 5980 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, APK, format_idx, 5981 firstDataArg, Type, CallType, InFunctionCall, 5982 CheckedVarArgs, UncoveredArg, Offset, 5983 IgnoreStringsWithoutSpecifiers); 5984 if (Left == SLCT_NotALiteral || !CheckRight) { 5985 return Left; 5986 } 5987 } 5988 5989 StringLiteralCheckType Right = checkFormatStringExpr( 5990 S, C->getFalseExpr(), Args, APK, format_idx, firstDataArg, Type, 5991 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 5992 IgnoreStringsWithoutSpecifiers); 5993 5994 return (CheckLeft && Left < Right) ? Left : Right; 5995 } 5996 5997 case Stmt::ImplicitCastExprClass: 5998 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 5999 goto tryAgain; 6000 6001 case Stmt::OpaqueValueExprClass: 6002 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6003 E = src; 6004 goto tryAgain; 6005 } 6006 return SLCT_NotALiteral; 6007 6008 case Stmt::PredefinedExprClass: 6009 // While __func__, etc., are technically not string literals, they 6010 // cannot contain format specifiers and thus are not a security 6011 // liability. 6012 return SLCT_UncheckedLiteral; 6013 6014 case Stmt::DeclRefExprClass: { 6015 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6016 6017 // As an exception, do not flag errors for variables binding to 6018 // const string literals. 6019 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6020 bool isConstant = false; 6021 QualType T = DR->getType(); 6022 6023 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6024 isConstant = AT->getElementType().isConstant(S.Context); 6025 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6026 isConstant = T.isConstant(S.Context) && 6027 PT->getPointeeType().isConstant(S.Context); 6028 } else if (T->isObjCObjectPointerType()) { 6029 // In ObjC, there is usually no "const ObjectPointer" type, 6030 // so don't check if the pointee type is constant. 6031 isConstant = T.isConstant(S.Context); 6032 } 6033 6034 if (isConstant) { 6035 if (const Expr *Init = VD->getAnyInitializer()) { 6036 // Look through initializers like const char c[] = { "foo" } 6037 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6038 if (InitList->isStringLiteralInit()) 6039 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6040 } 6041 return checkFormatStringExpr( 6042 S, Init, Args, APK, format_idx, firstDataArg, Type, CallType, 6043 /*InFunctionCall*/ false, CheckedVarArgs, UncoveredArg, Offset); 6044 } 6045 } 6046 6047 // When the format argument is an argument of this function, and this 6048 // function also has the format attribute, there are several interactions 6049 // for which there shouldn't be a warning. For instance, when calling 6050 // v*printf from a function that has the printf format attribute, we 6051 // should not emit a warning about using `fmt`, even though it's not 6052 // constant, because the arguments have already been checked for the 6053 // caller of `logmessage`: 6054 // 6055 // __attribute__((format(printf, 1, 2))) 6056 // void logmessage(char const *fmt, ...) { 6057 // va_list ap; 6058 // va_start(ap, fmt); 6059 // vprintf(fmt, ap); /* do not emit a warning about "fmt" */ 6060 // ... 6061 // } 6062 // 6063 // Another interaction that we need to support is calling a variadic 6064 // format function from a format function that has fixed arguments. For 6065 // instance: 6066 // 6067 // __attribute__((format(printf, 1, 2))) 6068 // void logstring(char const *fmt, char const *str) { 6069 // printf(fmt, str); /* do not emit a warning about "fmt" */ 6070 // } 6071 // 6072 // Same (and perhaps more relatably) for the variadic template case: 6073 // 6074 // template<typename... Args> 6075 // __attribute__((format(printf, 1, 2))) 6076 // void log(const char *fmt, Args&&... args) { 6077 // printf(fmt, forward<Args>(args)...); 6078 // /* do not emit a warning about "fmt" */ 6079 // } 6080 // 6081 // Due to implementation difficulty, we only check the format, not the 6082 // format arguments, in all cases. 6083 // 6084 if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) { 6085 if (const auto *D = dyn_cast<Decl>(PV->getDeclContext())) { 6086 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) { 6087 bool IsCXXMember = false; 6088 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) 6089 IsCXXMember = MD->isInstance(); 6090 6091 bool IsVariadic = false; 6092 if (const FunctionType *FnTy = D->getFunctionType()) 6093 IsVariadic = cast<FunctionProtoType>(FnTy)->isVariadic(); 6094 else if (const auto *BD = dyn_cast<BlockDecl>(D)) 6095 IsVariadic = BD->isVariadic(); 6096 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) 6097 IsVariadic = OMD->isVariadic(); 6098 6099 Sema::FormatStringInfo CallerFSI; 6100 if (Sema::getFormatStringInfo(PVFormat, IsCXXMember, IsVariadic, 6101 &CallerFSI)) { 6102 // We also check if the formats are compatible. 6103 // We can't pass a 'scanf' string to a 'printf' function. 6104 if (PV->getFunctionScopeIndex() == CallerFSI.FormatIdx && 6105 Type == S.GetFormatStringType(PVFormat)) { 6106 // Lastly, check that argument passing kinds transition in a 6107 // way that makes sense: 6108 // from a caller with FAPK_VAList, allow FAPK_VAList 6109 // from a caller with FAPK_Fixed, allow FAPK_Fixed 6110 // from a caller with FAPK_Fixed, allow FAPK_Variadic 6111 // from a caller with FAPK_Variadic, allow FAPK_VAList 6112 switch (combineFAPK(CallerFSI.ArgPassingKind, APK)) { 6113 case combineFAPK(Sema::FAPK_VAList, Sema::FAPK_VAList): 6114 case combineFAPK(Sema::FAPK_Fixed, Sema::FAPK_Fixed): 6115 case combineFAPK(Sema::FAPK_Fixed, Sema::FAPK_Variadic): 6116 case combineFAPK(Sema::FAPK_Variadic, Sema::FAPK_VAList): 6117 return SLCT_UncheckedLiteral; 6118 } 6119 } 6120 } 6121 } 6122 } 6123 } 6124 } 6125 6126 return SLCT_NotALiteral; 6127 } 6128 6129 case Stmt::CallExprClass: 6130 case Stmt::CXXMemberCallExprClass: { 6131 const CallExpr *CE = cast<CallExpr>(E); 6132 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6133 bool IsFirst = true; 6134 StringLiteralCheckType CommonResult; 6135 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6136 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6137 StringLiteralCheckType Result = checkFormatStringExpr( 6138 S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType, 6139 InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6140 IgnoreStringsWithoutSpecifiers); 6141 if (IsFirst) { 6142 CommonResult = Result; 6143 IsFirst = false; 6144 } 6145 } 6146 if (!IsFirst) 6147 return CommonResult; 6148 6149 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6150 unsigned BuiltinID = FD->getBuiltinID(); 6151 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6152 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6153 const Expr *Arg = CE->getArg(0); 6154 return checkFormatStringExpr( 6155 S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType, 6156 InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6157 IgnoreStringsWithoutSpecifiers); 6158 } 6159 } 6160 } 6161 if (const Expr *SLE = maybeConstEvalStringLiteral(S.Context, E)) 6162 return checkFormatStringExpr(S, SLE, Args, APK, format_idx, firstDataArg, 6163 Type, CallType, /*InFunctionCall*/ false, 6164 CheckedVarArgs, UncoveredArg, Offset, 6165 IgnoreStringsWithoutSpecifiers); 6166 return SLCT_NotALiteral; 6167 } 6168 case Stmt::ObjCMessageExprClass: { 6169 const auto *ME = cast<ObjCMessageExpr>(E); 6170 if (const auto *MD = ME->getMethodDecl()) { 6171 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 6172 // As a special case heuristic, if we're using the method -[NSBundle 6173 // localizedStringForKey:value:table:], ignore any key strings that lack 6174 // format specifiers. The idea is that if the key doesn't have any 6175 // format specifiers then its probably just a key to map to the 6176 // localized strings. If it does have format specifiers though, then its 6177 // likely that the text of the key is the format string in the 6178 // programmer's language, and should be checked. 6179 const ObjCInterfaceDecl *IFace; 6180 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 6181 IFace->getIdentifier()->isStr("NSBundle") && 6182 MD->getSelector().isKeywordSelector( 6183 {"localizedStringForKey", "value", "table"})) { 6184 IgnoreStringsWithoutSpecifiers = true; 6185 } 6186 6187 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6188 return checkFormatStringExpr( 6189 S, Arg, Args, APK, format_idx, firstDataArg, Type, CallType, 6190 InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6191 IgnoreStringsWithoutSpecifiers); 6192 } 6193 } 6194 6195 return SLCT_NotALiteral; 6196 } 6197 case Stmt::ObjCStringLiteralClass: 6198 case Stmt::StringLiteralClass: { 6199 const StringLiteral *StrE = nullptr; 6200 6201 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6202 StrE = ObjCFExpr->getString(); 6203 else 6204 StrE = cast<StringLiteral>(E); 6205 6206 if (StrE) { 6207 if (Offset.isNegative() || Offset > StrE->getLength()) { 6208 // TODO: It would be better to have an explicit warning for out of 6209 // bounds literals. 6210 return SLCT_NotALiteral; 6211 } 6212 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6213 CheckFormatString(S, &FStr, E, Args, APK, format_idx, firstDataArg, Type, 6214 InFunctionCall, CallType, CheckedVarArgs, UncoveredArg, 6215 IgnoreStringsWithoutSpecifiers); 6216 return SLCT_CheckedLiteral; 6217 } 6218 6219 return SLCT_NotALiteral; 6220 } 6221 case Stmt::BinaryOperatorClass: { 6222 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6223 6224 // A string literal + an int offset is still a string literal. 6225 if (BinOp->isAdditiveOp()) { 6226 Expr::EvalResult LResult, RResult; 6227 6228 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 6229 LResult, S.Context, Expr::SE_NoSideEffects, 6230 S.isConstantEvaluatedContext()); 6231 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 6232 RResult, S.Context, Expr::SE_NoSideEffects, 6233 S.isConstantEvaluatedContext()); 6234 6235 if (LIsInt != RIsInt) { 6236 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6237 6238 if (LIsInt) { 6239 if (BinOpKind == BO_Add) { 6240 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6241 E = BinOp->getRHS(); 6242 goto tryAgain; 6243 } 6244 } else { 6245 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6246 E = BinOp->getLHS(); 6247 goto tryAgain; 6248 } 6249 } 6250 } 6251 6252 return SLCT_NotALiteral; 6253 } 6254 case Stmt::UnaryOperatorClass: { 6255 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6256 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6257 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6258 Expr::EvalResult IndexResult; 6259 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 6260 Expr::SE_NoSideEffects, 6261 S.isConstantEvaluatedContext())) { 6262 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6263 /*RHS is int*/ true); 6264 E = ASE->getBase(); 6265 goto tryAgain; 6266 } 6267 } 6268 6269 return SLCT_NotALiteral; 6270 } 6271 6272 default: 6273 return SLCT_NotALiteral; 6274 } 6275 } 6276 6277 // If this expression can be evaluated at compile-time, 6278 // check if the result is a StringLiteral and return it 6279 // otherwise return nullptr 6280 static const Expr *maybeConstEvalStringLiteral(ASTContext &Context, 6281 const Expr *E) { 6282 Expr::EvalResult Result; 6283 if (E->EvaluateAsRValue(Result, Context) && Result.Val.isLValue()) { 6284 const auto *LVE = Result.Val.getLValueBase().dyn_cast<const Expr *>(); 6285 if (isa_and_nonnull<StringLiteral>(LVE)) 6286 return LVE; 6287 } 6288 return nullptr; 6289 } 6290 6291 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6292 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6293 .Case("scanf", FST_Scanf) 6294 .Cases("printf", "printf0", "syslog", FST_Printf) 6295 .Cases("NSString", "CFString", FST_NSString) 6296 .Case("strftime", FST_Strftime) 6297 .Case("strfmon", FST_Strfmon) 6298 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6299 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6300 .Case("os_trace", FST_OSLog) 6301 .Case("os_log", FST_OSLog) 6302 .Default(FST_Unknown); 6303 } 6304 6305 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6306 ArrayRef<const Expr *> Args, bool IsCXXMember, 6307 VariadicCallType CallType, SourceLocation Loc, 6308 SourceRange Range, 6309 llvm::SmallBitVector &CheckedVarArgs) { 6310 FormatStringInfo FSI; 6311 if (getFormatStringInfo(Format, IsCXXMember, CallType != VariadicDoesNotApply, 6312 &FSI)) 6313 return CheckFormatArguments(Args, FSI.ArgPassingKind, FSI.FormatIdx, 6314 FSI.FirstDataArg, GetFormatStringType(Format), 6315 CallType, Loc, Range, CheckedVarArgs); 6316 return false; 6317 } 6318 6319 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6320 Sema::FormatArgumentPassingKind APK, 6321 unsigned format_idx, unsigned firstDataArg, 6322 FormatStringType Type, 6323 VariadicCallType CallType, SourceLocation Loc, 6324 SourceRange Range, 6325 llvm::SmallBitVector &CheckedVarArgs) { 6326 // CHECK: printf/scanf-like function is called with no format string. 6327 if (format_idx >= Args.size()) { 6328 Diag(Loc, diag::warn_missing_format_string) << Range; 6329 return false; 6330 } 6331 6332 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6333 6334 // CHECK: format string is not a string literal. 6335 // 6336 // Dynamically generated format strings are difficult to 6337 // automatically vet at compile time. Requiring that format strings 6338 // are string literals: (1) permits the checking of format strings by 6339 // the compiler and thereby (2) can practically remove the source of 6340 // many format string exploits. 6341 6342 // Format string can be either ObjC string (e.g. @"%d") or 6343 // C string (e.g. "%d") 6344 // ObjC string uses the same format specifiers as C string, so we can use 6345 // the same format string checking logic for both ObjC and C strings. 6346 UncoveredArgHandler UncoveredArg; 6347 StringLiteralCheckType CT = checkFormatStringExpr( 6348 *this, OrigFormatExpr, Args, APK, format_idx, firstDataArg, Type, 6349 CallType, 6350 /*IsFunctionCall*/ true, CheckedVarArgs, UncoveredArg, 6351 /*no string offset*/ llvm::APSInt(64, false) = 0); 6352 6353 // Generate a diagnostic where an uncovered argument is detected. 6354 if (UncoveredArg.hasUncoveredArg()) { 6355 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6356 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6357 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6358 } 6359 6360 if (CT != SLCT_NotALiteral) 6361 // Literal format string found, check done! 6362 return CT == SLCT_CheckedLiteral; 6363 6364 // Strftime is particular as it always uses a single 'time' argument, 6365 // so it is safe to pass a non-literal string. 6366 if (Type == FST_Strftime) 6367 return false; 6368 6369 // Do not emit diag when the string param is a macro expansion and the 6370 // format is either NSString or CFString. This is a hack to prevent 6371 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6372 // which are usually used in place of NS and CF string literals. 6373 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6374 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6375 return false; 6376 6377 // If there are no arguments specified, warn with -Wformat-security, otherwise 6378 // warn only with -Wformat-nonliteral. 6379 if (Args.size() == firstDataArg) { 6380 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6381 << OrigFormatExpr->getSourceRange(); 6382 switch (Type) { 6383 default: 6384 break; 6385 case FST_Kprintf: 6386 case FST_FreeBSDKPrintf: 6387 case FST_Printf: 6388 case FST_Syslog: 6389 Diag(FormatLoc, diag::note_format_security_fixit) 6390 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6391 break; 6392 case FST_NSString: 6393 Diag(FormatLoc, diag::note_format_security_fixit) 6394 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6395 break; 6396 } 6397 } else { 6398 Diag(FormatLoc, diag::warn_format_nonliteral) 6399 << OrigFormatExpr->getSourceRange(); 6400 } 6401 return false; 6402 } 6403 6404 namespace { 6405 6406 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6407 protected: 6408 Sema &S; 6409 const FormatStringLiteral *FExpr; 6410 const Expr *OrigFormatExpr; 6411 const Sema::FormatStringType FSType; 6412 const unsigned FirstDataArg; 6413 const unsigned NumDataArgs; 6414 const char *Beg; // Start of format string. 6415 const Sema::FormatArgumentPassingKind ArgPassingKind; 6416 ArrayRef<const Expr *> Args; 6417 unsigned FormatIdx; 6418 llvm::SmallBitVector CoveredArgs; 6419 bool usesPositionalArgs = false; 6420 bool atFirstArg = true; 6421 bool inFunctionCall; 6422 Sema::VariadicCallType CallType; 6423 llvm::SmallBitVector &CheckedVarArgs; 6424 UncoveredArgHandler &UncoveredArg; 6425 6426 public: 6427 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6428 const Expr *origFormatExpr, 6429 const Sema::FormatStringType type, unsigned firstDataArg, 6430 unsigned numDataArgs, const char *beg, 6431 Sema::FormatArgumentPassingKind APK, 6432 ArrayRef<const Expr *> Args, unsigned formatIdx, 6433 bool inFunctionCall, Sema::VariadicCallType callType, 6434 llvm::SmallBitVector &CheckedVarArgs, 6435 UncoveredArgHandler &UncoveredArg) 6436 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 6437 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 6438 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx), 6439 inFunctionCall(inFunctionCall), CallType(callType), 6440 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 6441 CoveredArgs.resize(numDataArgs); 6442 CoveredArgs.reset(); 6443 } 6444 6445 void DoneProcessing(); 6446 6447 void HandleIncompleteSpecifier(const char *startSpecifier, 6448 unsigned specifierLen) override; 6449 6450 void HandleInvalidLengthModifier( 6451 const analyze_format_string::FormatSpecifier &FS, 6452 const analyze_format_string::ConversionSpecifier &CS, 6453 const char *startSpecifier, unsigned specifierLen, 6454 unsigned DiagID); 6455 6456 void HandleNonStandardLengthModifier( 6457 const analyze_format_string::FormatSpecifier &FS, 6458 const char *startSpecifier, unsigned specifierLen); 6459 6460 void HandleNonStandardConversionSpecifier( 6461 const analyze_format_string::ConversionSpecifier &CS, 6462 const char *startSpecifier, unsigned specifierLen); 6463 6464 void HandlePosition(const char *startPos, unsigned posLen) override; 6465 6466 void HandleInvalidPosition(const char *startSpecifier, 6467 unsigned specifierLen, 6468 analyze_format_string::PositionContext p) override; 6469 6470 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 6471 6472 void HandleNullChar(const char *nullCharacter) override; 6473 6474 template <typename Range> 6475 static void 6476 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 6477 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 6478 bool IsStringLocation, Range StringRange, 6479 ArrayRef<FixItHint> Fixit = {}); 6480 6481 protected: 6482 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 6483 const char *startSpec, 6484 unsigned specifierLen, 6485 const char *csStart, unsigned csLen); 6486 6487 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 6488 const char *startSpec, 6489 unsigned specifierLen); 6490 6491 SourceRange getFormatStringRange(); 6492 CharSourceRange getSpecifierRange(const char *startSpecifier, 6493 unsigned specifierLen); 6494 SourceLocation getLocationOfByte(const char *x); 6495 6496 const Expr *getDataArg(unsigned i) const; 6497 6498 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 6499 const analyze_format_string::ConversionSpecifier &CS, 6500 const char *startSpecifier, unsigned specifierLen, 6501 unsigned argIndex); 6502 6503 template <typename Range> 6504 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 6505 bool IsStringLocation, Range StringRange, 6506 ArrayRef<FixItHint> Fixit = {}); 6507 }; 6508 6509 } // namespace 6510 6511 SourceRange CheckFormatHandler::getFormatStringRange() { 6512 return OrigFormatExpr->getSourceRange(); 6513 } 6514 6515 CharSourceRange CheckFormatHandler:: 6516 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 6517 SourceLocation Start = getLocationOfByte(startSpecifier); 6518 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 6519 6520 // Advance the end SourceLocation by one due to half-open ranges. 6521 End = End.getLocWithOffset(1); 6522 6523 return CharSourceRange::getCharRange(Start, End); 6524 } 6525 6526 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 6527 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 6528 S.getLangOpts(), S.Context.getTargetInfo()); 6529 } 6530 6531 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 6532 unsigned specifierLen){ 6533 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 6534 getLocationOfByte(startSpecifier), 6535 /*IsStringLocation*/true, 6536 getSpecifierRange(startSpecifier, specifierLen)); 6537 } 6538 6539 void CheckFormatHandler::HandleInvalidLengthModifier( 6540 const analyze_format_string::FormatSpecifier &FS, 6541 const analyze_format_string::ConversionSpecifier &CS, 6542 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 6543 using namespace analyze_format_string; 6544 6545 const LengthModifier &LM = FS.getLengthModifier(); 6546 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6547 6548 // See if we know how to fix this length modifier. 6549 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6550 if (FixedLM) { 6551 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6552 getLocationOfByte(LM.getStart()), 6553 /*IsStringLocation*/true, 6554 getSpecifierRange(startSpecifier, specifierLen)); 6555 6556 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6557 << FixedLM->toString() 6558 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6559 6560 } else { 6561 FixItHint Hint; 6562 if (DiagID == diag::warn_format_nonsensical_length) 6563 Hint = FixItHint::CreateRemoval(LMRange); 6564 6565 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 6566 getLocationOfByte(LM.getStart()), 6567 /*IsStringLocation*/true, 6568 getSpecifierRange(startSpecifier, specifierLen), 6569 Hint); 6570 } 6571 } 6572 6573 void CheckFormatHandler::HandleNonStandardLengthModifier( 6574 const analyze_format_string::FormatSpecifier &FS, 6575 const char *startSpecifier, unsigned specifierLen) { 6576 using namespace analyze_format_string; 6577 6578 const LengthModifier &LM = FS.getLengthModifier(); 6579 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 6580 6581 // See if we know how to fix this length modifier. 6582 std::optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 6583 if (FixedLM) { 6584 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6585 << LM.toString() << 0, 6586 getLocationOfByte(LM.getStart()), 6587 /*IsStringLocation*/true, 6588 getSpecifierRange(startSpecifier, specifierLen)); 6589 6590 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 6591 << FixedLM->toString() 6592 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 6593 6594 } else { 6595 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6596 << LM.toString() << 0, 6597 getLocationOfByte(LM.getStart()), 6598 /*IsStringLocation*/true, 6599 getSpecifierRange(startSpecifier, specifierLen)); 6600 } 6601 } 6602 6603 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 6604 const analyze_format_string::ConversionSpecifier &CS, 6605 const char *startSpecifier, unsigned specifierLen) { 6606 using namespace analyze_format_string; 6607 6608 // See if we know how to fix this conversion specifier. 6609 std::optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 6610 if (FixedCS) { 6611 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6612 << CS.toString() << /*conversion specifier*/1, 6613 getLocationOfByte(CS.getStart()), 6614 /*IsStringLocation*/true, 6615 getSpecifierRange(startSpecifier, specifierLen)); 6616 6617 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 6618 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 6619 << FixedCS->toString() 6620 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 6621 } else { 6622 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 6623 << CS.toString() << /*conversion specifier*/1, 6624 getLocationOfByte(CS.getStart()), 6625 /*IsStringLocation*/true, 6626 getSpecifierRange(startSpecifier, specifierLen)); 6627 } 6628 } 6629 6630 void CheckFormatHandler::HandlePosition(const char *startPos, 6631 unsigned posLen) { 6632 if (!S.getDiagnostics().isIgnored( 6633 diag::warn_format_non_standard_positional_arg, SourceLocation())) 6634 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 6635 getLocationOfByte(startPos), 6636 /*IsStringLocation*/ true, 6637 getSpecifierRange(startPos, posLen)); 6638 } 6639 6640 void CheckFormatHandler::HandleInvalidPosition( 6641 const char *startSpecifier, unsigned specifierLen, 6642 analyze_format_string::PositionContext p) { 6643 if (!S.getDiagnostics().isIgnored( 6644 diag::warn_format_invalid_positional_specifier, SourceLocation())) 6645 EmitFormatDiagnostic( 6646 S.PDiag(diag::warn_format_invalid_positional_specifier) << (unsigned)p, 6647 getLocationOfByte(startSpecifier), /*IsStringLocation*/ true, 6648 getSpecifierRange(startSpecifier, specifierLen)); 6649 } 6650 6651 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 6652 unsigned posLen) { 6653 if (!S.getDiagnostics().isIgnored(diag::warn_format_zero_positional_specifier, 6654 SourceLocation())) 6655 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 6656 getLocationOfByte(startPos), 6657 /*IsStringLocation*/ true, 6658 getSpecifierRange(startPos, posLen)); 6659 } 6660 6661 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 6662 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 6663 // The presence of a null character is likely an error. 6664 EmitFormatDiagnostic( 6665 S.PDiag(diag::warn_printf_format_string_contains_null_char), 6666 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 6667 getFormatStringRange()); 6668 } 6669 } 6670 6671 // Note that this may return NULL if there was an error parsing or building 6672 // one of the argument expressions. 6673 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 6674 return Args[FirstDataArg + i]; 6675 } 6676 6677 void CheckFormatHandler::DoneProcessing() { 6678 // Does the number of data arguments exceed the number of 6679 // format conversions in the format string? 6680 if (ArgPassingKind != Sema::FAPK_VAList) { 6681 // Find any arguments that weren't covered. 6682 CoveredArgs.flip(); 6683 signed notCoveredArg = CoveredArgs.find_first(); 6684 if (notCoveredArg >= 0) { 6685 assert((unsigned)notCoveredArg < NumDataArgs); 6686 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 6687 } else { 6688 UncoveredArg.setAllCovered(); 6689 } 6690 } 6691 } 6692 6693 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 6694 const Expr *ArgExpr) { 6695 assert(hasUncoveredArg() && !DiagnosticExprs.empty() && 6696 "Invalid state"); 6697 6698 if (!ArgExpr) 6699 return; 6700 6701 SourceLocation Loc = ArgExpr->getBeginLoc(); 6702 6703 if (S.getSourceManager().isInSystemMacro(Loc)) 6704 return; 6705 6706 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 6707 for (auto E : DiagnosticExprs) 6708 PDiag << E->getSourceRange(); 6709 6710 CheckFormatHandler::EmitFormatDiagnostic( 6711 S, IsFunctionCall, DiagnosticExprs[0], 6712 PDiag, Loc, /*IsStringLocation*/false, 6713 DiagnosticExprs[0]->getSourceRange()); 6714 } 6715 6716 bool 6717 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 6718 SourceLocation Loc, 6719 const char *startSpec, 6720 unsigned specifierLen, 6721 const char *csStart, 6722 unsigned csLen) { 6723 bool keepGoing = true; 6724 if (argIndex < NumDataArgs) { 6725 // Consider the argument coverered, even though the specifier doesn't 6726 // make sense. 6727 CoveredArgs.set(argIndex); 6728 } 6729 else { 6730 // If argIndex exceeds the number of data arguments we 6731 // don't issue a warning because that is just a cascade of warnings (and 6732 // they may have intended '%%' anyway). We don't want to continue processing 6733 // the format string after this point, however, as we will like just get 6734 // gibberish when trying to match arguments. 6735 keepGoing = false; 6736 } 6737 6738 StringRef Specifier(csStart, csLen); 6739 6740 // If the specifier in non-printable, it could be the first byte of a UTF-8 6741 // sequence. In that case, print the UTF-8 code point. If not, print the byte 6742 // hex value. 6743 std::string CodePointStr; 6744 if (!llvm::sys::locale::isPrint(*csStart)) { 6745 llvm::UTF32 CodePoint; 6746 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 6747 const llvm::UTF8 *E = 6748 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 6749 llvm::ConversionResult Result = 6750 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 6751 6752 if (Result != llvm::conversionOK) { 6753 unsigned char FirstChar = *csStart; 6754 CodePoint = (llvm::UTF32)FirstChar; 6755 } 6756 6757 llvm::raw_string_ostream OS(CodePointStr); 6758 if (CodePoint < 256) 6759 OS << "\\x" << llvm::format("%02x", CodePoint); 6760 else if (CodePoint <= 0xFFFF) 6761 OS << "\\u" << llvm::format("%04x", CodePoint); 6762 else 6763 OS << "\\U" << llvm::format("%08x", CodePoint); 6764 Specifier = CodePointStr; 6765 } 6766 6767 EmitFormatDiagnostic( 6768 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 6769 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 6770 6771 return keepGoing; 6772 } 6773 6774 void 6775 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 6776 const char *startSpec, 6777 unsigned specifierLen) { 6778 EmitFormatDiagnostic( 6779 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 6780 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 6781 } 6782 6783 bool 6784 CheckFormatHandler::CheckNumArgs( 6785 const analyze_format_string::FormatSpecifier &FS, 6786 const analyze_format_string::ConversionSpecifier &CS, 6787 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 6788 6789 if (argIndex >= NumDataArgs) { 6790 PartialDiagnostic PDiag = FS.usesPositionalArg() 6791 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 6792 << (argIndex+1) << NumDataArgs) 6793 : S.PDiag(diag::warn_printf_insufficient_data_args); 6794 EmitFormatDiagnostic( 6795 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 6796 getSpecifierRange(startSpecifier, specifierLen)); 6797 6798 // Since more arguments than conversion tokens are given, by extension 6799 // all arguments are covered, so mark this as so. 6800 UncoveredArg.setAllCovered(); 6801 return false; 6802 } 6803 return true; 6804 } 6805 6806 template<typename Range> 6807 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 6808 SourceLocation Loc, 6809 bool IsStringLocation, 6810 Range StringRange, 6811 ArrayRef<FixItHint> FixIt) { 6812 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 6813 Loc, IsStringLocation, StringRange, FixIt); 6814 } 6815 6816 /// If the format string is not within the function call, emit a note 6817 /// so that the function call and string are in diagnostic messages. 6818 /// 6819 /// \param InFunctionCall if true, the format string is within the function 6820 /// call and only one diagnostic message will be produced. Otherwise, an 6821 /// extra note will be emitted pointing to location of the format string. 6822 /// 6823 /// \param ArgumentExpr the expression that is passed as the format string 6824 /// argument in the function call. Used for getting locations when two 6825 /// diagnostics are emitted. 6826 /// 6827 /// \param PDiag the callee should already have provided any strings for the 6828 /// diagnostic message. This function only adds locations and fixits 6829 /// to diagnostics. 6830 /// 6831 /// \param Loc primary location for diagnostic. If two diagnostics are 6832 /// required, one will be at Loc and a new SourceLocation will be created for 6833 /// the other one. 6834 /// 6835 /// \param IsStringLocation if true, Loc points to the format string should be 6836 /// used for the note. Otherwise, Loc points to the argument list and will 6837 /// be used with PDiag. 6838 /// 6839 /// \param StringRange some or all of the string to highlight. This is 6840 /// templated so it can accept either a CharSourceRange or a SourceRange. 6841 /// 6842 /// \param FixIt optional fix it hint for the format string. 6843 template <typename Range> 6844 void CheckFormatHandler::EmitFormatDiagnostic( 6845 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 6846 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 6847 Range StringRange, ArrayRef<FixItHint> FixIt) { 6848 if (InFunctionCall) { 6849 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 6850 D << StringRange; 6851 D << FixIt; 6852 } else { 6853 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 6854 << ArgumentExpr->getSourceRange(); 6855 6856 const Sema::SemaDiagnosticBuilder &Note = 6857 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 6858 diag::note_format_string_defined); 6859 6860 Note << StringRange; 6861 Note << FixIt; 6862 } 6863 } 6864 6865 //===--- CHECK: Printf format string checking -----------------------------===// 6866 6867 namespace { 6868 6869 class CheckPrintfHandler : public CheckFormatHandler { 6870 public: 6871 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 6872 const Expr *origFormatExpr, 6873 const Sema::FormatStringType type, unsigned firstDataArg, 6874 unsigned numDataArgs, bool isObjC, const char *beg, 6875 Sema::FormatArgumentPassingKind APK, 6876 ArrayRef<const Expr *> Args, unsigned formatIdx, 6877 bool inFunctionCall, Sema::VariadicCallType CallType, 6878 llvm::SmallBitVector &CheckedVarArgs, 6879 UncoveredArgHandler &UncoveredArg) 6880 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 6881 numDataArgs, beg, APK, Args, formatIdx, 6882 inFunctionCall, CallType, CheckedVarArgs, 6883 UncoveredArg) {} 6884 6885 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 6886 6887 /// Returns true if '%@' specifiers are allowed in the format string. 6888 bool allowsObjCArg() const { 6889 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 6890 FSType == Sema::FST_OSTrace; 6891 } 6892 6893 bool HandleInvalidPrintfConversionSpecifier( 6894 const analyze_printf::PrintfSpecifier &FS, 6895 const char *startSpecifier, 6896 unsigned specifierLen) override; 6897 6898 void handleInvalidMaskType(StringRef MaskType) override; 6899 6900 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 6901 const char *startSpecifier, unsigned specifierLen, 6902 const TargetInfo &Target) override; 6903 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 6904 const char *StartSpecifier, 6905 unsigned SpecifierLen, 6906 const Expr *E); 6907 6908 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 6909 const char *startSpecifier, unsigned specifierLen); 6910 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 6911 const analyze_printf::OptionalAmount &Amt, 6912 unsigned type, 6913 const char *startSpecifier, unsigned specifierLen); 6914 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 6915 const analyze_printf::OptionalFlag &flag, 6916 const char *startSpecifier, unsigned specifierLen); 6917 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 6918 const analyze_printf::OptionalFlag &ignoredFlag, 6919 const analyze_printf::OptionalFlag &flag, 6920 const char *startSpecifier, unsigned specifierLen); 6921 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 6922 const Expr *E); 6923 6924 void HandleEmptyObjCModifierFlag(const char *startFlag, 6925 unsigned flagLen) override; 6926 6927 void HandleInvalidObjCModifierFlag(const char *startFlag, 6928 unsigned flagLen) override; 6929 6930 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 6931 const char *flagsEnd, 6932 const char *conversionPosition) 6933 override; 6934 }; 6935 6936 } // namespace 6937 6938 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 6939 const analyze_printf::PrintfSpecifier &FS, 6940 const char *startSpecifier, 6941 unsigned specifierLen) { 6942 const analyze_printf::PrintfConversionSpecifier &CS = 6943 FS.getConversionSpecifier(); 6944 6945 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 6946 getLocationOfByte(CS.getStart()), 6947 startSpecifier, specifierLen, 6948 CS.getStart(), CS.getLength()); 6949 } 6950 6951 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 6952 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 6953 } 6954 6955 bool CheckPrintfHandler::HandleAmount( 6956 const analyze_format_string::OptionalAmount &Amt, unsigned k, 6957 const char *startSpecifier, unsigned specifierLen) { 6958 if (Amt.hasDataArgument()) { 6959 if (ArgPassingKind != Sema::FAPK_VAList) { 6960 unsigned argIndex = Amt.getArgIndex(); 6961 if (argIndex >= NumDataArgs) { 6962 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 6963 << k, 6964 getLocationOfByte(Amt.getStart()), 6965 /*IsStringLocation*/ true, 6966 getSpecifierRange(startSpecifier, specifierLen)); 6967 // Don't do any more checking. We will just emit 6968 // spurious errors. 6969 return false; 6970 } 6971 6972 // Type check the data argument. It should be an 'int'. 6973 // Although not in conformance with C99, we also allow the argument to be 6974 // an 'unsigned int' as that is a reasonably safe case. GCC also 6975 // doesn't emit a warning for that case. 6976 CoveredArgs.set(argIndex); 6977 const Expr *Arg = getDataArg(argIndex); 6978 if (!Arg) 6979 return false; 6980 6981 QualType T = Arg->getType(); 6982 6983 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 6984 assert(AT.isValid()); 6985 6986 if (!AT.matchesType(S.Context, T)) { 6987 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 6988 << k << AT.getRepresentativeTypeName(S.Context) 6989 << T << Arg->getSourceRange(), 6990 getLocationOfByte(Amt.getStart()), 6991 /*IsStringLocation*/true, 6992 getSpecifierRange(startSpecifier, specifierLen)); 6993 // Don't do any more checking. We will just emit 6994 // spurious errors. 6995 return false; 6996 } 6997 } 6998 } 6999 return true; 7000 } 7001 7002 void CheckPrintfHandler::HandleInvalidAmount( 7003 const analyze_printf::PrintfSpecifier &FS, 7004 const analyze_printf::OptionalAmount &Amt, 7005 unsigned type, 7006 const char *startSpecifier, 7007 unsigned specifierLen) { 7008 const analyze_printf::PrintfConversionSpecifier &CS = 7009 FS.getConversionSpecifier(); 7010 7011 FixItHint fixit = 7012 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7013 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7014 Amt.getConstantLength())) 7015 : FixItHint(); 7016 7017 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7018 << type << CS.toString(), 7019 getLocationOfByte(Amt.getStart()), 7020 /*IsStringLocation*/true, 7021 getSpecifierRange(startSpecifier, specifierLen), 7022 fixit); 7023 } 7024 7025 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7026 const analyze_printf::OptionalFlag &flag, 7027 const char *startSpecifier, 7028 unsigned specifierLen) { 7029 // Warn about pointless flag with a fixit removal. 7030 const analyze_printf::PrintfConversionSpecifier &CS = 7031 FS.getConversionSpecifier(); 7032 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7033 << flag.toString() << CS.toString(), 7034 getLocationOfByte(flag.getPosition()), 7035 /*IsStringLocation*/true, 7036 getSpecifierRange(startSpecifier, specifierLen), 7037 FixItHint::CreateRemoval( 7038 getSpecifierRange(flag.getPosition(), 1))); 7039 } 7040 7041 void CheckPrintfHandler::HandleIgnoredFlag( 7042 const analyze_printf::PrintfSpecifier &FS, 7043 const analyze_printf::OptionalFlag &ignoredFlag, 7044 const analyze_printf::OptionalFlag &flag, 7045 const char *startSpecifier, 7046 unsigned specifierLen) { 7047 // Warn about ignored flag with a fixit removal. 7048 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7049 << ignoredFlag.toString() << flag.toString(), 7050 getLocationOfByte(ignoredFlag.getPosition()), 7051 /*IsStringLocation*/true, 7052 getSpecifierRange(startSpecifier, specifierLen), 7053 FixItHint::CreateRemoval( 7054 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7055 } 7056 7057 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7058 unsigned flagLen) { 7059 // Warn about an empty flag. 7060 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7061 getLocationOfByte(startFlag), 7062 /*IsStringLocation*/true, 7063 getSpecifierRange(startFlag, flagLen)); 7064 } 7065 7066 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7067 unsigned flagLen) { 7068 // Warn about an invalid flag. 7069 auto Range = getSpecifierRange(startFlag, flagLen); 7070 StringRef flag(startFlag, flagLen); 7071 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7072 getLocationOfByte(startFlag), 7073 /*IsStringLocation*/true, 7074 Range, FixItHint::CreateRemoval(Range)); 7075 } 7076 7077 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7078 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7079 // Warn about using '[...]' without a '@' conversion. 7080 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7081 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7082 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7083 getLocationOfByte(conversionPosition), 7084 /*IsStringLocation*/true, 7085 Range, FixItHint::CreateRemoval(Range)); 7086 } 7087 7088 // Determines if the specified is a C++ class or struct containing 7089 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7090 // "c_str()"). 7091 template<typename MemberKind> 7092 static llvm::SmallPtrSet<MemberKind*, 1> 7093 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7094 const RecordType *RT = Ty->getAs<RecordType>(); 7095 llvm::SmallPtrSet<MemberKind*, 1> Results; 7096 7097 if (!RT) 7098 return Results; 7099 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7100 if (!RD || !RD->getDefinition()) 7101 return Results; 7102 7103 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7104 Sema::LookupMemberName); 7105 R.suppressDiagnostics(); 7106 7107 // We just need to include all members of the right kind turned up by the 7108 // filter, at this point. 7109 if (S.LookupQualifiedName(R, RT->getDecl())) 7110 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7111 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7112 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7113 Results.insert(FK); 7114 } 7115 return Results; 7116 } 7117 7118 /// Check if we could call '.c_str()' on an object. 7119 /// 7120 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7121 /// allow the call, or if it would be ambiguous). 7122 bool Sema::hasCStrMethod(const Expr *E) { 7123 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7124 7125 MethodSet Results = 7126 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7127 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7128 MI != ME; ++MI) 7129 if ((*MI)->getMinRequiredArguments() == 0) 7130 return true; 7131 return false; 7132 } 7133 7134 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7135 // better diagnostic if so. AT is assumed to be valid. 7136 // Returns true when a c_str() conversion method is found. 7137 bool CheckPrintfHandler::checkForCStrMembers( 7138 const analyze_printf::ArgType &AT, const Expr *E) { 7139 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7140 7141 MethodSet Results = 7142 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7143 7144 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7145 MI != ME; ++MI) { 7146 const CXXMethodDecl *Method = *MI; 7147 if (Method->getMinRequiredArguments() == 0 && 7148 AT.matchesType(S.Context, Method->getReturnType())) { 7149 // FIXME: Suggest parens if the expression needs them. 7150 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7151 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7152 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7153 return true; 7154 } 7155 } 7156 7157 return false; 7158 } 7159 7160 bool CheckPrintfHandler::HandlePrintfSpecifier( 7161 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier, 7162 unsigned specifierLen, const TargetInfo &Target) { 7163 using namespace analyze_format_string; 7164 using namespace analyze_printf; 7165 7166 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7167 7168 if (FS.consumesDataArgument()) { 7169 if (atFirstArg) { 7170 atFirstArg = false; 7171 usesPositionalArgs = FS.usesPositionalArg(); 7172 } 7173 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7174 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7175 startSpecifier, specifierLen); 7176 return false; 7177 } 7178 } 7179 7180 // First check if the field width, precision, and conversion specifier 7181 // have matching data arguments. 7182 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7183 startSpecifier, specifierLen)) { 7184 return false; 7185 } 7186 7187 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7188 startSpecifier, specifierLen)) { 7189 return false; 7190 } 7191 7192 if (!CS.consumesDataArgument()) { 7193 // FIXME: Technically specifying a precision or field width here 7194 // makes no sense. Worth issuing a warning at some point. 7195 return true; 7196 } 7197 7198 // Consume the argument. 7199 unsigned argIndex = FS.getArgIndex(); 7200 if (argIndex < NumDataArgs) { 7201 // The check to see if the argIndex is valid will come later. 7202 // We set the bit here because we may exit early from this 7203 // function if we encounter some other error. 7204 CoveredArgs.set(argIndex); 7205 } 7206 7207 // FreeBSD kernel extensions. 7208 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7209 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7210 // We need at least two arguments. 7211 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7212 return false; 7213 7214 // Claim the second argument. 7215 CoveredArgs.set(argIndex + 1); 7216 7217 // Type check the first argument (int for %b, pointer for %D) 7218 const Expr *Ex = getDataArg(argIndex); 7219 const analyze_printf::ArgType &AT = 7220 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7221 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7222 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7223 EmitFormatDiagnostic( 7224 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7225 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7226 << false << Ex->getSourceRange(), 7227 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7228 getSpecifierRange(startSpecifier, specifierLen)); 7229 7230 // Type check the second argument (char * for both %b and %D) 7231 Ex = getDataArg(argIndex + 1); 7232 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7233 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7234 EmitFormatDiagnostic( 7235 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7236 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7237 << false << Ex->getSourceRange(), 7238 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7239 getSpecifierRange(startSpecifier, specifierLen)); 7240 7241 return true; 7242 } 7243 7244 // Check for using an Objective-C specific conversion specifier 7245 // in a non-ObjC literal. 7246 if (!allowsObjCArg() && CS.isObjCArg()) { 7247 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7248 specifierLen); 7249 } 7250 7251 // %P can only be used with os_log. 7252 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7253 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7254 specifierLen); 7255 } 7256 7257 // %n is not allowed with os_log. 7258 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7259 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7260 getLocationOfByte(CS.getStart()), 7261 /*IsStringLocation*/ false, 7262 getSpecifierRange(startSpecifier, specifierLen)); 7263 7264 return true; 7265 } 7266 7267 // Only scalars are allowed for os_trace. 7268 if (FSType == Sema::FST_OSTrace && 7269 (CS.getKind() == ConversionSpecifier::PArg || 7270 CS.getKind() == ConversionSpecifier::sArg || 7271 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7272 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7273 specifierLen); 7274 } 7275 7276 // Check for use of public/private annotation outside of os_log(). 7277 if (FSType != Sema::FST_OSLog) { 7278 if (FS.isPublic().isSet()) { 7279 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7280 << "public", 7281 getLocationOfByte(FS.isPublic().getPosition()), 7282 /*IsStringLocation*/ false, 7283 getSpecifierRange(startSpecifier, specifierLen)); 7284 } 7285 if (FS.isPrivate().isSet()) { 7286 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7287 << "private", 7288 getLocationOfByte(FS.isPrivate().getPosition()), 7289 /*IsStringLocation*/ false, 7290 getSpecifierRange(startSpecifier, specifierLen)); 7291 } 7292 } 7293 7294 const llvm::Triple &Triple = Target.getTriple(); 7295 if (CS.getKind() == ConversionSpecifier::nArg && 7296 (Triple.isAndroid() || Triple.isOSFuchsia())) { 7297 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported), 7298 getLocationOfByte(CS.getStart()), 7299 /*IsStringLocation*/ false, 7300 getSpecifierRange(startSpecifier, specifierLen)); 7301 } 7302 7303 // Check for invalid use of field width 7304 if (!FS.hasValidFieldWidth()) { 7305 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7306 startSpecifier, specifierLen); 7307 } 7308 7309 // Check for invalid use of precision 7310 if (!FS.hasValidPrecision()) { 7311 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7312 startSpecifier, specifierLen); 7313 } 7314 7315 // Precision is mandatory for %P specifier. 7316 if (CS.getKind() == ConversionSpecifier::PArg && 7317 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7318 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7319 getLocationOfByte(startSpecifier), 7320 /*IsStringLocation*/ false, 7321 getSpecifierRange(startSpecifier, specifierLen)); 7322 } 7323 7324 // Check each flag does not conflict with any other component. 7325 if (!FS.hasValidThousandsGroupingPrefix()) 7326 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7327 if (!FS.hasValidLeadingZeros()) 7328 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7329 if (!FS.hasValidPlusPrefix()) 7330 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7331 if (!FS.hasValidSpacePrefix()) 7332 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7333 if (!FS.hasValidAlternativeForm()) 7334 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7335 if (!FS.hasValidLeftJustified()) 7336 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7337 7338 // Check that flags are not ignored by another flag 7339 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7340 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7341 startSpecifier, specifierLen); 7342 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7343 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7344 startSpecifier, specifierLen); 7345 7346 // Check the length modifier is valid with the given conversion specifier. 7347 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 7348 S.getLangOpts())) 7349 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7350 diag::warn_format_nonsensical_length); 7351 else if (!FS.hasStandardLengthModifier()) 7352 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7353 else if (!FS.hasStandardLengthConversionCombination()) 7354 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7355 diag::warn_format_non_standard_conversion_spec); 7356 7357 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7358 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7359 7360 // The remaining checks depend on the data arguments. 7361 if (ArgPassingKind == Sema::FAPK_VAList) 7362 return true; 7363 7364 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7365 return false; 7366 7367 const Expr *Arg = getDataArg(argIndex); 7368 if (!Arg) 7369 return true; 7370 7371 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7372 } 7373 7374 static bool requiresParensToAddCast(const Expr *E) { 7375 // FIXME: We should have a general way to reason about operator 7376 // precedence and whether parens are actually needed here. 7377 // Take care of a few common cases where they aren't. 7378 const Expr *Inside = E->IgnoreImpCasts(); 7379 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7380 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7381 7382 switch (Inside->getStmtClass()) { 7383 case Stmt::ArraySubscriptExprClass: 7384 case Stmt::CallExprClass: 7385 case Stmt::CharacterLiteralClass: 7386 case Stmt::CXXBoolLiteralExprClass: 7387 case Stmt::DeclRefExprClass: 7388 case Stmt::FloatingLiteralClass: 7389 case Stmt::IntegerLiteralClass: 7390 case Stmt::MemberExprClass: 7391 case Stmt::ObjCArrayLiteralClass: 7392 case Stmt::ObjCBoolLiteralExprClass: 7393 case Stmt::ObjCBoxedExprClass: 7394 case Stmt::ObjCDictionaryLiteralClass: 7395 case Stmt::ObjCEncodeExprClass: 7396 case Stmt::ObjCIvarRefExprClass: 7397 case Stmt::ObjCMessageExprClass: 7398 case Stmt::ObjCPropertyRefExprClass: 7399 case Stmt::ObjCStringLiteralClass: 7400 case Stmt::ObjCSubscriptRefExprClass: 7401 case Stmt::ParenExprClass: 7402 case Stmt::StringLiteralClass: 7403 case Stmt::UnaryOperatorClass: 7404 return false; 7405 default: 7406 return true; 7407 } 7408 } 7409 7410 static std::pair<QualType, StringRef> 7411 shouldNotPrintDirectly(const ASTContext &Context, 7412 QualType IntendedTy, 7413 const Expr *E) { 7414 // Use a 'while' to peel off layers of typedefs. 7415 QualType TyTy = IntendedTy; 7416 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7417 StringRef Name = UserTy->getDecl()->getName(); 7418 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7419 .Case("CFIndex", Context.getNSIntegerType()) 7420 .Case("NSInteger", Context.getNSIntegerType()) 7421 .Case("NSUInteger", Context.getNSUIntegerType()) 7422 .Case("SInt32", Context.IntTy) 7423 .Case("UInt32", Context.UnsignedIntTy) 7424 .Default(QualType()); 7425 7426 if (!CastTy.isNull()) 7427 return std::make_pair(CastTy, Name); 7428 7429 TyTy = UserTy->desugar(); 7430 } 7431 7432 // Strip parens if necessary. 7433 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7434 return shouldNotPrintDirectly(Context, 7435 PE->getSubExpr()->getType(), 7436 PE->getSubExpr()); 7437 7438 // If this is a conditional expression, then its result type is constructed 7439 // via usual arithmetic conversions and thus there might be no necessary 7440 // typedef sugar there. Recurse to operands to check for NSInteger & 7441 // Co. usage condition. 7442 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7443 QualType TrueTy, FalseTy; 7444 StringRef TrueName, FalseName; 7445 7446 std::tie(TrueTy, TrueName) = 7447 shouldNotPrintDirectly(Context, 7448 CO->getTrueExpr()->getType(), 7449 CO->getTrueExpr()); 7450 std::tie(FalseTy, FalseName) = 7451 shouldNotPrintDirectly(Context, 7452 CO->getFalseExpr()->getType(), 7453 CO->getFalseExpr()); 7454 7455 if (TrueTy == FalseTy) 7456 return std::make_pair(TrueTy, TrueName); 7457 else if (TrueTy.isNull()) 7458 return std::make_pair(FalseTy, FalseName); 7459 else if (FalseTy.isNull()) 7460 return std::make_pair(TrueTy, TrueName); 7461 } 7462 7463 return std::make_pair(QualType(), StringRef()); 7464 } 7465 7466 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 7467 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 7468 /// type do not count. 7469 static bool 7470 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 7471 QualType From = ICE->getSubExpr()->getType(); 7472 QualType To = ICE->getType(); 7473 // It's an integer promotion if the destination type is the promoted 7474 // source type. 7475 if (ICE->getCastKind() == CK_IntegralCast && 7476 S.Context.isPromotableIntegerType(From) && 7477 S.Context.getPromotedIntegerType(From) == To) 7478 return true; 7479 // Look through vector types, since we do default argument promotion for 7480 // those in OpenCL. 7481 if (const auto *VecTy = From->getAs<ExtVectorType>()) 7482 From = VecTy->getElementType(); 7483 if (const auto *VecTy = To->getAs<ExtVectorType>()) 7484 To = VecTy->getElementType(); 7485 // It's a floating promotion if the source type is a lower rank. 7486 return ICE->getCastKind() == CK_FloatingCast && 7487 S.Context.getFloatingTypeOrder(From, To) < 0; 7488 } 7489 7490 static analyze_format_string::ArgType::MatchKind 7491 handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match, 7492 DiagnosticsEngine &Diags, SourceLocation Loc) { 7493 if (Match == analyze_format_string::ArgType::NoMatchSignedness) { 7494 Match = 7495 Diags.isIgnored( 7496 diag::warn_format_conversion_argument_type_mismatch_signedness, Loc) 7497 ? analyze_format_string::ArgType::Match 7498 : analyze_format_string::ArgType::NoMatch; 7499 } 7500 return Match; 7501 } 7502 7503 bool 7504 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7505 const char *StartSpecifier, 7506 unsigned SpecifierLen, 7507 const Expr *E) { 7508 using namespace analyze_format_string; 7509 using namespace analyze_printf; 7510 7511 // Now type check the data expression that matches the 7512 // format specifier. 7513 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 7514 if (!AT.isValid()) 7515 return true; 7516 7517 QualType ExprTy = E->getType(); 7518 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 7519 ExprTy = TET->getUnderlyingExpr()->getType(); 7520 } 7521 7522 // When using the format attribute in C++, you can receive a function or an 7523 // array that will necessarily decay to a pointer when passed to the final 7524 // format consumer. Apply decay before type comparison. 7525 if (ExprTy->canDecayToPointerType()) 7526 ExprTy = S.Context.getDecayedType(ExprTy); 7527 7528 // Diagnose attempts to print a boolean value as a character. Unlike other 7529 // -Wformat diagnostics, this is fine from a type perspective, but it still 7530 // doesn't make sense. 7531 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 7532 E->isKnownToHaveBooleanValue()) { 7533 const CharSourceRange &CSR = 7534 getSpecifierRange(StartSpecifier, SpecifierLen); 7535 SmallString<4> FSString; 7536 llvm::raw_svector_ostream os(FSString); 7537 FS.toString(os); 7538 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 7539 << FSString, 7540 E->getExprLoc(), false, CSR); 7541 return true; 7542 } 7543 7544 // Diagnose attempts to use '%P' with ObjC object types, which will result in 7545 // dumping raw class data (like is-a pointer), not actual data. 7546 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::PArg && 7547 ExprTy->isObjCObjectPointerType()) { 7548 const CharSourceRange &CSR = 7549 getSpecifierRange(StartSpecifier, SpecifierLen); 7550 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_with_objc_pointer), 7551 E->getExprLoc(), false, CSR); 7552 return true; 7553 } 7554 7555 ArgType::MatchKind ImplicitMatch = ArgType::NoMatch; 7556 ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 7557 ArgType::MatchKind OrigMatch = Match; 7558 7559 Match = handleFormatSignedness(Match, S.getDiagnostics(), E->getExprLoc()); 7560 if (Match == ArgType::Match) 7561 return true; 7562 7563 // NoMatchPromotionTypeConfusion should be only returned in ImplictCastExpr 7564 assert(Match != ArgType::NoMatchPromotionTypeConfusion); 7565 7566 // Look through argument promotions for our error message's reported type. 7567 // This includes the integral and floating promotions, but excludes array 7568 // and function pointer decay (seeing that an argument intended to be a 7569 // string has type 'char [6]' is probably more confusing than 'char *') and 7570 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 7571 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7572 if (isArithmeticArgumentPromotion(S, ICE)) { 7573 E = ICE->getSubExpr(); 7574 ExprTy = E->getType(); 7575 7576 // Check if we didn't match because of an implicit cast from a 'char' 7577 // or 'short' to an 'int'. This is done because printf is a varargs 7578 // function. 7579 if (ICE->getType() == S.Context.IntTy || 7580 ICE->getType() == S.Context.UnsignedIntTy) { 7581 // All further checking is done on the subexpression 7582 ImplicitMatch = AT.matchesType(S.Context, ExprTy); 7583 if (OrigMatch == ArgType::NoMatchSignedness && 7584 ImplicitMatch != ArgType::NoMatchSignedness) 7585 // If the original match was a signedness match this match on the 7586 // implicit cast type also need to be signedness match otherwise we 7587 // might introduce new unexpected warnings from -Wformat-signedness. 7588 return true; 7589 ImplicitMatch = handleFormatSignedness( 7590 ImplicitMatch, S.getDiagnostics(), E->getExprLoc()); 7591 if (ImplicitMatch == ArgType::Match) 7592 return true; 7593 } 7594 } 7595 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 7596 // Special case for 'a', which has type 'int' in C. 7597 // Note, however, that we do /not/ want to treat multibyte constants like 7598 // 'MooV' as characters! This form is deprecated but still exists. In 7599 // addition, don't treat expressions as of type 'char' if one byte length 7600 // modifier is provided. 7601 if (ExprTy == S.Context.IntTy && 7602 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 7603 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) { 7604 ExprTy = S.Context.CharTy; 7605 // To improve check results, we consider a character literal in C 7606 // to be a 'char' rather than an 'int'. 'printf("%hd", 'a');' is 7607 // more likely a type confusion situation, so we will suggest to 7608 // use '%hhd' instead by discarding the MatchPromotion. 7609 if (Match == ArgType::MatchPromotion) 7610 Match = ArgType::NoMatch; 7611 } 7612 } 7613 if (Match == ArgType::MatchPromotion) { 7614 // WG14 N2562 only clarified promotions in *printf 7615 // For NSLog in ObjC, just preserve -Wformat behavior 7616 if (!S.getLangOpts().ObjC && 7617 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion && 7618 ImplicitMatch != ArgType::NoMatchTypeConfusion) 7619 return true; 7620 Match = ArgType::NoMatch; 7621 } 7622 if (ImplicitMatch == ArgType::NoMatchPedantic || 7623 ImplicitMatch == ArgType::NoMatchTypeConfusion) 7624 Match = ImplicitMatch; 7625 assert(Match != ArgType::MatchPromotion); 7626 7627 // Look through unscoped enums to their underlying type. 7628 bool IsEnum = false; 7629 bool IsScopedEnum = false; 7630 QualType IntendedTy = ExprTy; 7631 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 7632 IntendedTy = EnumTy->getDecl()->getIntegerType(); 7633 if (EnumTy->isUnscopedEnumerationType()) { 7634 ExprTy = IntendedTy; 7635 // This controls whether we're talking about the underlying type or not, 7636 // which we only want to do when it's an unscoped enum. 7637 IsEnum = true; 7638 } else { 7639 IsScopedEnum = true; 7640 } 7641 } 7642 7643 // %C in an Objective-C context prints a unichar, not a wchar_t. 7644 // If the argument is an integer of some kind, believe the %C and suggest 7645 // a cast instead of changing the conversion specifier. 7646 if (isObjCContext() && 7647 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 7648 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 7649 !ExprTy->isCharType()) { 7650 // 'unichar' is defined as a typedef of unsigned short, but we should 7651 // prefer using the typedef if it is visible. 7652 IntendedTy = S.Context.UnsignedShortTy; 7653 7654 // While we are here, check if the value is an IntegerLiteral that happens 7655 // to be within the valid range. 7656 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 7657 const llvm::APInt &V = IL->getValue(); 7658 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 7659 return true; 7660 } 7661 7662 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 7663 Sema::LookupOrdinaryName); 7664 if (S.LookupName(Result, S.getCurScope())) { 7665 NamedDecl *ND = Result.getFoundDecl(); 7666 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 7667 if (TD->getUnderlyingType() == IntendedTy) 7668 IntendedTy = S.Context.getTypedefType(TD); 7669 } 7670 } 7671 } 7672 7673 // Special-case some of Darwin's platform-independence types by suggesting 7674 // casts to primitive types that are known to be large enough. 7675 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 7676 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 7677 QualType CastTy; 7678 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 7679 if (!CastTy.isNull()) { 7680 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 7681 // (long in ASTContext). Only complain to pedants or when they're the 7682 // underlying type of a scoped enum (which always needs a cast). 7683 if (!IsScopedEnum && 7684 (CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 7685 (AT.isSizeT() || AT.isPtrdiffT()) && 7686 AT.matchesType(S.Context, CastTy)) 7687 Match = ArgType::NoMatchPedantic; 7688 IntendedTy = CastTy; 7689 ShouldNotPrintDirectly = true; 7690 } 7691 } 7692 7693 // We may be able to offer a FixItHint if it is a supported type. 7694 PrintfSpecifier fixedFS = FS; 7695 bool Success = 7696 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 7697 7698 if (Success) { 7699 // Get the fix string from the fixed format specifier 7700 SmallString<16> buf; 7701 llvm::raw_svector_ostream os(buf); 7702 fixedFS.toString(os); 7703 7704 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 7705 7706 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) { 7707 unsigned Diag; 7708 switch (Match) { 7709 case ArgType::Match: 7710 case ArgType::MatchPromotion: 7711 case ArgType::NoMatchPromotionTypeConfusion: 7712 case ArgType::NoMatchSignedness: 7713 llvm_unreachable("expected non-matching"); 7714 case ArgType::NoMatchPedantic: 7715 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 7716 break; 7717 case ArgType::NoMatchTypeConfusion: 7718 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 7719 break; 7720 case ArgType::NoMatch: 7721 Diag = diag::warn_format_conversion_argument_type_mismatch; 7722 break; 7723 } 7724 7725 // In this case, the specifier is wrong and should be changed to match 7726 // the argument. 7727 EmitFormatDiagnostic(S.PDiag(Diag) 7728 << AT.getRepresentativeTypeName(S.Context) 7729 << IntendedTy << IsEnum << E->getSourceRange(), 7730 E->getBeginLoc(), 7731 /*IsStringLocation*/ false, SpecRange, 7732 FixItHint::CreateReplacement(SpecRange, os.str())); 7733 } else { 7734 // The canonical type for formatting this value is different from the 7735 // actual type of the expression. (This occurs, for example, with Darwin's 7736 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 7737 // should be printed as 'long' for 64-bit compatibility.) 7738 // Rather than emitting a normal format/argument mismatch, we want to 7739 // add a cast to the recommended type (and correct the format string 7740 // if necessary). We should also do so for scoped enumerations. 7741 SmallString<16> CastBuf; 7742 llvm::raw_svector_ostream CastFix(CastBuf); 7743 CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "("); 7744 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 7745 CastFix << (S.LangOpts.CPlusPlus ? ">" : ")"); 7746 7747 SmallVector<FixItHint,4> Hints; 7748 ArgType::MatchKind IntendedMatch = AT.matchesType(S.Context, IntendedTy); 7749 IntendedMatch = handleFormatSignedness(IntendedMatch, S.getDiagnostics(), 7750 E->getExprLoc()); 7751 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly) 7752 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 7753 7754 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 7755 // If there's already a cast present, just replace it. 7756 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 7757 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 7758 7759 } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) { 7760 // If the expression has high enough precedence, 7761 // just write the C-style cast. 7762 Hints.push_back( 7763 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7764 } else { 7765 // Otherwise, add parens around the expression as well as the cast. 7766 CastFix << "("; 7767 Hints.push_back( 7768 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 7769 7770 // We don't use getLocForEndOfToken because it returns invalid source 7771 // locations for macro expansions (by design). 7772 SourceLocation EndLoc = S.SourceMgr.getSpellingLoc(E->getEndLoc()); 7773 SourceLocation After = EndLoc.getLocWithOffset( 7774 Lexer::MeasureTokenLength(EndLoc, S.SourceMgr, S.LangOpts)); 7775 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 7776 } 7777 7778 if (ShouldNotPrintDirectly && !IsScopedEnum) { 7779 // The expression has a type that should not be printed directly. 7780 // We extract the name from the typedef because we don't want to show 7781 // the underlying type in the diagnostic. 7782 StringRef Name; 7783 if (const auto *TypedefTy = ExprTy->getAs<TypedefType>()) 7784 Name = TypedefTy->getDecl()->getName(); 7785 else 7786 Name = CastTyName; 7787 unsigned Diag = Match == ArgType::NoMatchPedantic 7788 ? diag::warn_format_argument_needs_cast_pedantic 7789 : diag::warn_format_argument_needs_cast; 7790 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 7791 << E->getSourceRange(), 7792 E->getBeginLoc(), /*IsStringLocation=*/false, 7793 SpecRange, Hints); 7794 } else { 7795 // In this case, the expression could be printed using a different 7796 // specifier, but we've decided that the specifier is probably correct 7797 // and we should cast instead. Just use the normal warning message. 7798 7799 unsigned Diag = 7800 IsScopedEnum 7801 ? diag::warn_format_conversion_argument_type_mismatch_pedantic 7802 : diag::warn_format_conversion_argument_type_mismatch; 7803 7804 EmitFormatDiagnostic( 7805 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 7806 << IsEnum << E->getSourceRange(), 7807 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 7808 } 7809 } 7810 } else { 7811 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 7812 SpecifierLen); 7813 // Since the warning for passing non-POD types to variadic functions 7814 // was deferred until now, we emit a warning for non-POD 7815 // arguments here. 7816 bool EmitTypeMismatch = false; 7817 switch (S.isValidVarArgType(ExprTy)) { 7818 case Sema::VAK_Valid: 7819 case Sema::VAK_ValidInCXX11: { 7820 unsigned Diag; 7821 switch (Match) { 7822 case ArgType::Match: 7823 case ArgType::MatchPromotion: 7824 case ArgType::NoMatchPromotionTypeConfusion: 7825 case ArgType::NoMatchSignedness: 7826 llvm_unreachable("expected non-matching"); 7827 case ArgType::NoMatchPedantic: 7828 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 7829 break; 7830 case ArgType::NoMatchTypeConfusion: 7831 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 7832 break; 7833 case ArgType::NoMatch: 7834 Diag = diag::warn_format_conversion_argument_type_mismatch; 7835 break; 7836 } 7837 7838 EmitFormatDiagnostic( 7839 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 7840 << IsEnum << CSR << E->getSourceRange(), 7841 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7842 break; 7843 } 7844 case Sema::VAK_Undefined: 7845 case Sema::VAK_MSVCUndefined: 7846 if (CallType == Sema::VariadicDoesNotApply) { 7847 EmitTypeMismatch = true; 7848 } else { 7849 EmitFormatDiagnostic( 7850 S.PDiag(diag::warn_non_pod_vararg_with_format_string) 7851 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 7852 << AT.getRepresentativeTypeName(S.Context) << CSR 7853 << E->getSourceRange(), 7854 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7855 checkForCStrMembers(AT, E); 7856 } 7857 break; 7858 7859 case Sema::VAK_Invalid: 7860 if (CallType == Sema::VariadicDoesNotApply) 7861 EmitTypeMismatch = true; 7862 else if (ExprTy->isObjCObjectType()) 7863 EmitFormatDiagnostic( 7864 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 7865 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 7866 << AT.getRepresentativeTypeName(S.Context) << CSR 7867 << E->getSourceRange(), 7868 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 7869 else 7870 // FIXME: If this is an initializer list, suggest removing the braces 7871 // or inserting a cast to the target type. 7872 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 7873 << isa<InitListExpr>(E) << ExprTy << CallType 7874 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 7875 break; 7876 } 7877 7878 if (EmitTypeMismatch) { 7879 // The function is not variadic, so we do not generate warnings about 7880 // being allowed to pass that object as a variadic argument. Instead, 7881 // since there are inherently no printf specifiers for types which cannot 7882 // be passed as variadic arguments, emit a plain old specifier mismatch 7883 // argument. 7884 EmitFormatDiagnostic( 7885 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7886 << AT.getRepresentativeTypeName(S.Context) << ExprTy << false 7887 << E->getSourceRange(), 7888 E->getBeginLoc(), false, CSR); 7889 } 7890 7891 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 7892 "format string specifier index out of range"); 7893 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 7894 } 7895 7896 return true; 7897 } 7898 7899 //===--- CHECK: Scanf format string checking ------------------------------===// 7900 7901 namespace { 7902 7903 class CheckScanfHandler : public CheckFormatHandler { 7904 public: 7905 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 7906 const Expr *origFormatExpr, Sema::FormatStringType type, 7907 unsigned firstDataArg, unsigned numDataArgs, 7908 const char *beg, Sema::FormatArgumentPassingKind APK, 7909 ArrayRef<const Expr *> Args, unsigned formatIdx, 7910 bool inFunctionCall, Sema::VariadicCallType CallType, 7911 llvm::SmallBitVector &CheckedVarArgs, 7912 UncoveredArgHandler &UncoveredArg) 7913 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7914 numDataArgs, beg, APK, Args, formatIdx, 7915 inFunctionCall, CallType, CheckedVarArgs, 7916 UncoveredArg) {} 7917 7918 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 7919 const char *startSpecifier, 7920 unsigned specifierLen) override; 7921 7922 bool HandleInvalidScanfConversionSpecifier( 7923 const analyze_scanf::ScanfSpecifier &FS, 7924 const char *startSpecifier, 7925 unsigned specifierLen) override; 7926 7927 void HandleIncompleteScanList(const char *start, const char *end) override; 7928 }; 7929 7930 } // namespace 7931 7932 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 7933 const char *end) { 7934 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 7935 getLocationOfByte(end), /*IsStringLocation*/true, 7936 getSpecifierRange(start, end - start)); 7937 } 7938 7939 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 7940 const analyze_scanf::ScanfSpecifier &FS, 7941 const char *startSpecifier, 7942 unsigned specifierLen) { 7943 const analyze_scanf::ScanfConversionSpecifier &CS = 7944 FS.getConversionSpecifier(); 7945 7946 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7947 getLocationOfByte(CS.getStart()), 7948 startSpecifier, specifierLen, 7949 CS.getStart(), CS.getLength()); 7950 } 7951 7952 bool CheckScanfHandler::HandleScanfSpecifier( 7953 const analyze_scanf::ScanfSpecifier &FS, 7954 const char *startSpecifier, 7955 unsigned specifierLen) { 7956 using namespace analyze_scanf; 7957 using namespace analyze_format_string; 7958 7959 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 7960 7961 // Handle case where '%' and '*' don't consume an argument. These shouldn't 7962 // be used to decide if we are using positional arguments consistently. 7963 if (FS.consumesDataArgument()) { 7964 if (atFirstArg) { 7965 atFirstArg = false; 7966 usesPositionalArgs = FS.usesPositionalArg(); 7967 } 7968 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7969 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7970 startSpecifier, specifierLen); 7971 return false; 7972 } 7973 } 7974 7975 // Check if the field with is non-zero. 7976 const OptionalAmount &Amt = FS.getFieldWidth(); 7977 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 7978 if (Amt.getConstantAmount() == 0) { 7979 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 7980 Amt.getConstantLength()); 7981 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 7982 getLocationOfByte(Amt.getStart()), 7983 /*IsStringLocation*/true, R, 7984 FixItHint::CreateRemoval(R)); 7985 } 7986 } 7987 7988 if (!FS.consumesDataArgument()) { 7989 // FIXME: Technically specifying a precision or field width here 7990 // makes no sense. Worth issuing a warning at some point. 7991 return true; 7992 } 7993 7994 // Consume the argument. 7995 unsigned argIndex = FS.getArgIndex(); 7996 if (argIndex < NumDataArgs) { 7997 // The check to see if the argIndex is valid will come later. 7998 // We set the bit here because we may exit early from this 7999 // function if we encounter some other error. 8000 CoveredArgs.set(argIndex); 8001 } 8002 8003 // Check the length modifier is valid with the given conversion specifier. 8004 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8005 S.getLangOpts())) 8006 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8007 diag::warn_format_nonsensical_length); 8008 else if (!FS.hasStandardLengthModifier()) 8009 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8010 else if (!FS.hasStandardLengthConversionCombination()) 8011 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8012 diag::warn_format_non_standard_conversion_spec); 8013 8014 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8015 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8016 8017 // The remaining checks depend on the data arguments. 8018 if (ArgPassingKind == Sema::FAPK_VAList) 8019 return true; 8020 8021 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8022 return false; 8023 8024 // Check that the argument type matches the format specifier. 8025 const Expr *Ex = getDataArg(argIndex); 8026 if (!Ex) 8027 return true; 8028 8029 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8030 8031 if (!AT.isValid()) { 8032 return true; 8033 } 8034 8035 analyze_format_string::ArgType::MatchKind Match = 8036 AT.matchesType(S.Context, Ex->getType()); 8037 Match = handleFormatSignedness(Match, S.getDiagnostics(), Ex->getExprLoc()); 8038 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8039 if (Match == analyze_format_string::ArgType::Match) 8040 return true; 8041 8042 ScanfSpecifier fixedFS = FS; 8043 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8044 S.getLangOpts(), S.Context); 8045 8046 unsigned Diag = 8047 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8048 : diag::warn_format_conversion_argument_type_mismatch; 8049 8050 if (Success) { 8051 // Get the fix string from the fixed format specifier. 8052 SmallString<128> buf; 8053 llvm::raw_svector_ostream os(buf); 8054 fixedFS.toString(os); 8055 8056 EmitFormatDiagnostic( 8057 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8058 << Ex->getType() << false << Ex->getSourceRange(), 8059 Ex->getBeginLoc(), 8060 /*IsStringLocation*/ false, 8061 getSpecifierRange(startSpecifier, specifierLen), 8062 FixItHint::CreateReplacement( 8063 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8064 } else { 8065 EmitFormatDiagnostic(S.PDiag(Diag) 8066 << AT.getRepresentativeTypeName(S.Context) 8067 << Ex->getType() << false << Ex->getSourceRange(), 8068 Ex->getBeginLoc(), 8069 /*IsStringLocation*/ false, 8070 getSpecifierRange(startSpecifier, specifierLen)); 8071 } 8072 8073 return true; 8074 } 8075 8076 static void CheckFormatString( 8077 Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr, 8078 ArrayRef<const Expr *> Args, Sema::FormatArgumentPassingKind APK, 8079 unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, 8080 bool inFunctionCall, Sema::VariadicCallType CallType, 8081 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, 8082 bool IgnoreStringsWithoutSpecifiers) { 8083 // CHECK: is the format string a wide literal? 8084 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8085 CheckFormatHandler::EmitFormatDiagnostic( 8086 S, inFunctionCall, Args[format_idx], 8087 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8088 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8089 return; 8090 } 8091 8092 // Str - The format string. NOTE: this is NOT null-terminated! 8093 StringRef StrRef = FExpr->getString(); 8094 const char *Str = StrRef.data(); 8095 // Account for cases where the string literal is truncated in a declaration. 8096 const ConstantArrayType *T = 8097 S.Context.getAsConstantArrayType(FExpr->getType()); 8098 assert(T && "String literal not of constant array type!"); 8099 size_t TypeSize = T->getZExtSize(); 8100 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8101 const unsigned numDataArgs = Args.size() - firstDataArg; 8102 8103 if (IgnoreStringsWithoutSpecifiers && 8104 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8105 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8106 return; 8107 8108 // Emit a warning if the string literal is truncated and does not contain an 8109 // embedded null character. 8110 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) { 8111 CheckFormatHandler::EmitFormatDiagnostic( 8112 S, inFunctionCall, Args[format_idx], 8113 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8114 FExpr->getBeginLoc(), 8115 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8116 return; 8117 } 8118 8119 // CHECK: empty format string? 8120 if (StrLen == 0 && numDataArgs > 0) { 8121 CheckFormatHandler::EmitFormatDiagnostic( 8122 S, inFunctionCall, Args[format_idx], 8123 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8124 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8125 return; 8126 } 8127 8128 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8129 Type == Sema::FST_Kprintf || Type == Sema::FST_FreeBSDKPrintf || 8130 Type == Sema::FST_OSLog || Type == Sema::FST_OSTrace || 8131 Type == Sema::FST_Syslog) { 8132 CheckPrintfHandler H( 8133 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8134 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, APK, 8135 Args, format_idx, inFunctionCall, CallType, CheckedVarArgs, 8136 UncoveredArg); 8137 8138 if (!analyze_format_string::ParsePrintfString( 8139 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo(), 8140 Type == Sema::FST_Kprintf || Type == Sema::FST_FreeBSDKPrintf)) 8141 H.DoneProcessing(); 8142 } else if (Type == Sema::FST_Scanf) { 8143 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8144 numDataArgs, Str, APK, Args, format_idx, inFunctionCall, 8145 CallType, CheckedVarArgs, UncoveredArg); 8146 8147 if (!analyze_format_string::ParseScanfString( 8148 H, Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8149 H.DoneProcessing(); 8150 } // TODO: handle other formats 8151 } 8152 8153 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8154 // Str - The format string. NOTE: this is NOT null-terminated! 8155 StringRef StrRef = FExpr->getString(); 8156 const char *Str = StrRef.data(); 8157 // Account for cases where the string literal is truncated in a declaration. 8158 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8159 assert(T && "String literal not of constant array type!"); 8160 size_t TypeSize = T->getZExtSize(); 8161 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8162 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8163 getLangOpts(), 8164 Context.getTargetInfo()); 8165 } 8166 8167 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8168 8169 // Returns the related absolute value function that is larger, of 0 if one 8170 // does not exist. 8171 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8172 switch (AbsFunction) { 8173 default: 8174 return 0; 8175 8176 case Builtin::BI__builtin_abs: 8177 return Builtin::BI__builtin_labs; 8178 case Builtin::BI__builtin_labs: 8179 return Builtin::BI__builtin_llabs; 8180 case Builtin::BI__builtin_llabs: 8181 return 0; 8182 8183 case Builtin::BI__builtin_fabsf: 8184 return Builtin::BI__builtin_fabs; 8185 case Builtin::BI__builtin_fabs: 8186 return Builtin::BI__builtin_fabsl; 8187 case Builtin::BI__builtin_fabsl: 8188 return 0; 8189 8190 case Builtin::BI__builtin_cabsf: 8191 return Builtin::BI__builtin_cabs; 8192 case Builtin::BI__builtin_cabs: 8193 return Builtin::BI__builtin_cabsl; 8194 case Builtin::BI__builtin_cabsl: 8195 return 0; 8196 8197 case Builtin::BIabs: 8198 return Builtin::BIlabs; 8199 case Builtin::BIlabs: 8200 return Builtin::BIllabs; 8201 case Builtin::BIllabs: 8202 return 0; 8203 8204 case Builtin::BIfabsf: 8205 return Builtin::BIfabs; 8206 case Builtin::BIfabs: 8207 return Builtin::BIfabsl; 8208 case Builtin::BIfabsl: 8209 return 0; 8210 8211 case Builtin::BIcabsf: 8212 return Builtin::BIcabs; 8213 case Builtin::BIcabs: 8214 return Builtin::BIcabsl; 8215 case Builtin::BIcabsl: 8216 return 0; 8217 } 8218 } 8219 8220 // Returns the argument type of the absolute value function. 8221 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8222 unsigned AbsType) { 8223 if (AbsType == 0) 8224 return QualType(); 8225 8226 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8227 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8228 if (Error != ASTContext::GE_None) 8229 return QualType(); 8230 8231 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8232 if (!FT) 8233 return QualType(); 8234 8235 if (FT->getNumParams() != 1) 8236 return QualType(); 8237 8238 return FT->getParamType(0); 8239 } 8240 8241 // Returns the best absolute value function, or zero, based on type and 8242 // current absolute value function. 8243 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8244 unsigned AbsFunctionKind) { 8245 unsigned BestKind = 0; 8246 uint64_t ArgSize = Context.getTypeSize(ArgType); 8247 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8248 Kind = getLargerAbsoluteValueFunction(Kind)) { 8249 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8250 if (Context.getTypeSize(ParamType) >= ArgSize) { 8251 if (BestKind == 0) 8252 BestKind = Kind; 8253 else if (Context.hasSameType(ParamType, ArgType)) { 8254 BestKind = Kind; 8255 break; 8256 } 8257 } 8258 } 8259 return BestKind; 8260 } 8261 8262 enum AbsoluteValueKind { 8263 AVK_Integer, 8264 AVK_Floating, 8265 AVK_Complex 8266 }; 8267 8268 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8269 if (T->isIntegralOrEnumerationType()) 8270 return AVK_Integer; 8271 if (T->isRealFloatingType()) 8272 return AVK_Floating; 8273 if (T->isAnyComplexType()) 8274 return AVK_Complex; 8275 8276 llvm_unreachable("Type not integer, floating, or complex"); 8277 } 8278 8279 // Changes the absolute value function to a different type. Preserves whether 8280 // the function is a builtin. 8281 static unsigned changeAbsFunction(unsigned AbsKind, 8282 AbsoluteValueKind ValueKind) { 8283 switch (ValueKind) { 8284 case AVK_Integer: 8285 switch (AbsKind) { 8286 default: 8287 return 0; 8288 case Builtin::BI__builtin_fabsf: 8289 case Builtin::BI__builtin_fabs: 8290 case Builtin::BI__builtin_fabsl: 8291 case Builtin::BI__builtin_cabsf: 8292 case Builtin::BI__builtin_cabs: 8293 case Builtin::BI__builtin_cabsl: 8294 return Builtin::BI__builtin_abs; 8295 case Builtin::BIfabsf: 8296 case Builtin::BIfabs: 8297 case Builtin::BIfabsl: 8298 case Builtin::BIcabsf: 8299 case Builtin::BIcabs: 8300 case Builtin::BIcabsl: 8301 return Builtin::BIabs; 8302 } 8303 case AVK_Floating: 8304 switch (AbsKind) { 8305 default: 8306 return 0; 8307 case Builtin::BI__builtin_abs: 8308 case Builtin::BI__builtin_labs: 8309 case Builtin::BI__builtin_llabs: 8310 case Builtin::BI__builtin_cabsf: 8311 case Builtin::BI__builtin_cabs: 8312 case Builtin::BI__builtin_cabsl: 8313 return Builtin::BI__builtin_fabsf; 8314 case Builtin::BIabs: 8315 case Builtin::BIlabs: 8316 case Builtin::BIllabs: 8317 case Builtin::BIcabsf: 8318 case Builtin::BIcabs: 8319 case Builtin::BIcabsl: 8320 return Builtin::BIfabsf; 8321 } 8322 case AVK_Complex: 8323 switch (AbsKind) { 8324 default: 8325 return 0; 8326 case Builtin::BI__builtin_abs: 8327 case Builtin::BI__builtin_labs: 8328 case Builtin::BI__builtin_llabs: 8329 case Builtin::BI__builtin_fabsf: 8330 case Builtin::BI__builtin_fabs: 8331 case Builtin::BI__builtin_fabsl: 8332 return Builtin::BI__builtin_cabsf; 8333 case Builtin::BIabs: 8334 case Builtin::BIlabs: 8335 case Builtin::BIllabs: 8336 case Builtin::BIfabsf: 8337 case Builtin::BIfabs: 8338 case Builtin::BIfabsl: 8339 return Builtin::BIcabsf; 8340 } 8341 } 8342 llvm_unreachable("Unable to convert function"); 8343 } 8344 8345 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8346 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8347 if (!FnInfo) 8348 return 0; 8349 8350 switch (FDecl->getBuiltinID()) { 8351 default: 8352 return 0; 8353 case Builtin::BI__builtin_abs: 8354 case Builtin::BI__builtin_fabs: 8355 case Builtin::BI__builtin_fabsf: 8356 case Builtin::BI__builtin_fabsl: 8357 case Builtin::BI__builtin_labs: 8358 case Builtin::BI__builtin_llabs: 8359 case Builtin::BI__builtin_cabs: 8360 case Builtin::BI__builtin_cabsf: 8361 case Builtin::BI__builtin_cabsl: 8362 case Builtin::BIabs: 8363 case Builtin::BIlabs: 8364 case Builtin::BIllabs: 8365 case Builtin::BIfabs: 8366 case Builtin::BIfabsf: 8367 case Builtin::BIfabsl: 8368 case Builtin::BIcabs: 8369 case Builtin::BIcabsf: 8370 case Builtin::BIcabsl: 8371 return FDecl->getBuiltinID(); 8372 } 8373 llvm_unreachable("Unknown Builtin type"); 8374 } 8375 8376 // If the replacement is valid, emit a note with replacement function. 8377 // Additionally, suggest including the proper header if not already included. 8378 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8379 unsigned AbsKind, QualType ArgType) { 8380 bool EmitHeaderHint = true; 8381 const char *HeaderName = nullptr; 8382 StringRef FunctionName; 8383 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8384 FunctionName = "std::abs"; 8385 if (ArgType->isIntegralOrEnumerationType()) { 8386 HeaderName = "cstdlib"; 8387 } else if (ArgType->isRealFloatingType()) { 8388 HeaderName = "cmath"; 8389 } else { 8390 llvm_unreachable("Invalid Type"); 8391 } 8392 8393 // Lookup all std::abs 8394 if (NamespaceDecl *Std = S.getStdNamespace()) { 8395 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8396 R.suppressDiagnostics(); 8397 S.LookupQualifiedName(R, Std); 8398 8399 for (const auto *I : R) { 8400 const FunctionDecl *FDecl = nullptr; 8401 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8402 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8403 } else { 8404 FDecl = dyn_cast<FunctionDecl>(I); 8405 } 8406 if (!FDecl) 8407 continue; 8408 8409 // Found std::abs(), check that they are the right ones. 8410 if (FDecl->getNumParams() != 1) 8411 continue; 8412 8413 // Check that the parameter type can handle the argument. 8414 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8415 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8416 S.Context.getTypeSize(ArgType) <= 8417 S.Context.getTypeSize(ParamType)) { 8418 // Found a function, don't need the header hint. 8419 EmitHeaderHint = false; 8420 break; 8421 } 8422 } 8423 } 8424 } else { 8425 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8426 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8427 8428 if (HeaderName) { 8429 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8430 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8431 R.suppressDiagnostics(); 8432 S.LookupName(R, S.getCurScope()); 8433 8434 if (R.isSingleResult()) { 8435 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8436 if (FD && FD->getBuiltinID() == AbsKind) { 8437 EmitHeaderHint = false; 8438 } else { 8439 return; 8440 } 8441 } else if (!R.empty()) { 8442 return; 8443 } 8444 } 8445 } 8446 8447 S.Diag(Loc, diag::note_replace_abs_function) 8448 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8449 8450 if (!HeaderName) 8451 return; 8452 8453 if (!EmitHeaderHint) 8454 return; 8455 8456 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8457 << FunctionName; 8458 } 8459 8460 template <std::size_t StrLen> 8461 static bool IsStdFunction(const FunctionDecl *FDecl, 8462 const char (&Str)[StrLen]) { 8463 if (!FDecl) 8464 return false; 8465 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8466 return false; 8467 if (!FDecl->isInStdNamespace()) 8468 return false; 8469 8470 return true; 8471 } 8472 8473 enum class MathCheck { NaN, Inf }; 8474 static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check) { 8475 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) { 8476 return std::any_of(names.begin(), names.end(), [&](llvm::StringRef name) { 8477 return calleeName == name; 8478 }); 8479 }; 8480 8481 switch (Check) { 8482 case MathCheck::NaN: 8483 return MatchesAny({"__builtin_nan", "__builtin_nanf", "__builtin_nanl", 8484 "__builtin_nanf16", "__builtin_nanf128"}); 8485 case MathCheck::Inf: 8486 return MatchesAny({"__builtin_inf", "__builtin_inff", "__builtin_infl", 8487 "__builtin_inff16", "__builtin_inff128"}); 8488 } 8489 llvm_unreachable("unknown MathCheck"); 8490 } 8491 8492 static bool IsInfinityFunction(const FunctionDecl *FDecl) { 8493 if (FDecl->getName() != "infinity") 8494 return false; 8495 8496 if (const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) { 8497 const CXXRecordDecl *RDecl = MDecl->getParent(); 8498 if (RDecl->getName() != "numeric_limits") 8499 return false; 8500 8501 if (const NamespaceDecl *NSDecl = 8502 dyn_cast<NamespaceDecl>(RDecl->getDeclContext())) 8503 return NSDecl->isStdNamespace(); 8504 } 8505 8506 return false; 8507 } 8508 8509 void Sema::CheckInfNaNFunction(const CallExpr *Call, 8510 const FunctionDecl *FDecl) { 8511 if (!FDecl->getIdentifier()) 8512 return; 8513 8514 FPOptions FPO = Call->getFPFeaturesInEffect(getLangOpts()); 8515 if (FPO.getNoHonorNaNs() && 8516 (IsStdFunction(FDecl, "isnan") || IsStdFunction(FDecl, "isunordered") || 8517 IsInfOrNanFunction(FDecl->getName(), MathCheck::NaN))) { 8518 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled) 8519 << 1 << 0 << Call->getSourceRange(); 8520 return; 8521 } 8522 8523 if (FPO.getNoHonorInfs() && 8524 (IsStdFunction(FDecl, "isinf") || IsStdFunction(FDecl, "isfinite") || 8525 IsInfinityFunction(FDecl) || 8526 IsInfOrNanFunction(FDecl->getName(), MathCheck::Inf))) { 8527 Diag(Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled) 8528 << 0 << 0 << Call->getSourceRange(); 8529 } 8530 } 8531 8532 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8533 const FunctionDecl *FDecl) { 8534 if (Call->getNumArgs() != 1) 8535 return; 8536 8537 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8538 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8539 if (AbsKind == 0 && !IsStdAbs) 8540 return; 8541 8542 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8543 QualType ParamType = Call->getArg(0)->getType(); 8544 8545 // Unsigned types cannot be negative. Suggest removing the absolute value 8546 // function call. 8547 if (ArgType->isUnsignedIntegerType()) { 8548 StringRef FunctionName = 8549 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8550 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8551 Diag(Call->getExprLoc(), diag::note_remove_abs) 8552 << FunctionName 8553 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8554 return; 8555 } 8556 8557 // Taking the absolute value of a pointer is very suspicious, they probably 8558 // wanted to index into an array, dereference a pointer, call a function, etc. 8559 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8560 unsigned DiagType = 0; 8561 if (ArgType->isFunctionType()) 8562 DiagType = 1; 8563 else if (ArgType->isArrayType()) 8564 DiagType = 2; 8565 8566 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8567 return; 8568 } 8569 8570 // std::abs has overloads which prevent most of the absolute value problems 8571 // from occurring. 8572 if (IsStdAbs) 8573 return; 8574 8575 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8576 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8577 8578 // The argument and parameter are the same kind. Check if they are the right 8579 // size. 8580 if (ArgValueKind == ParamValueKind) { 8581 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8582 return; 8583 8584 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8585 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8586 << FDecl << ArgType << ParamType; 8587 8588 if (NewAbsKind == 0) 8589 return; 8590 8591 emitReplacement(*this, Call->getExprLoc(), 8592 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8593 return; 8594 } 8595 8596 // ArgValueKind != ParamValueKind 8597 // The wrong type of absolute value function was used. Attempt to find the 8598 // proper one. 8599 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8600 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8601 if (NewAbsKind == 0) 8602 return; 8603 8604 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8605 << FDecl << ParamValueKind << ArgValueKind; 8606 8607 emitReplacement(*this, Call->getExprLoc(), 8608 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8609 } 8610 8611 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8612 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8613 const FunctionDecl *FDecl) { 8614 if (!Call || !FDecl) return; 8615 8616 // Ignore template specializations and macros. 8617 if (inTemplateInstantiation()) return; 8618 if (Call->getExprLoc().isMacroID()) return; 8619 8620 // Only care about the one template argument, two function parameter std::max 8621 if (Call->getNumArgs() != 2) return; 8622 if (!IsStdFunction(FDecl, "max")) return; 8623 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8624 if (!ArgList) return; 8625 if (ArgList->size() != 1) return; 8626 8627 // Check that template type argument is unsigned integer. 8628 const auto& TA = ArgList->get(0); 8629 if (TA.getKind() != TemplateArgument::Type) return; 8630 QualType ArgType = TA.getAsType(); 8631 if (!ArgType->isUnsignedIntegerType()) return; 8632 8633 // See if either argument is a literal zero. 8634 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8635 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8636 if (!MTE) return false; 8637 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 8638 if (!Num) return false; 8639 if (Num->getValue() != 0) return false; 8640 return true; 8641 }; 8642 8643 const Expr *FirstArg = Call->getArg(0); 8644 const Expr *SecondArg = Call->getArg(1); 8645 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8646 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 8647 8648 // Only warn when exactly one argument is zero. 8649 if (IsFirstArgZero == IsSecondArgZero) return; 8650 8651 SourceRange FirstRange = FirstArg->getSourceRange(); 8652 SourceRange SecondRange = SecondArg->getSourceRange(); 8653 8654 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 8655 8656 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 8657 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 8658 8659 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 8660 SourceRange RemovalRange; 8661 if (IsFirstArgZero) { 8662 RemovalRange = SourceRange(FirstRange.getBegin(), 8663 SecondRange.getBegin().getLocWithOffset(-1)); 8664 } else { 8665 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 8666 SecondRange.getEnd()); 8667 } 8668 8669 Diag(Call->getExprLoc(), diag::note_remove_max_call) 8670 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 8671 << FixItHint::CreateRemoval(RemovalRange); 8672 } 8673 8674 //===--- CHECK: Standard memory functions ---------------------------------===// 8675 8676 /// Takes the expression passed to the size_t parameter of functions 8677 /// such as memcmp, strncat, etc and warns if it's a comparison. 8678 /// 8679 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 8680 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 8681 IdentifierInfo *FnName, 8682 SourceLocation FnLoc, 8683 SourceLocation RParenLoc) { 8684 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 8685 if (!Size) 8686 return false; 8687 8688 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 8689 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 8690 return false; 8691 8692 SourceRange SizeRange = Size->getSourceRange(); 8693 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 8694 << SizeRange << FnName; 8695 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 8696 << FnName 8697 << FixItHint::CreateInsertion( 8698 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 8699 << FixItHint::CreateRemoval(RParenLoc); 8700 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 8701 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 8702 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 8703 ")"); 8704 8705 return true; 8706 } 8707 8708 /// Determine whether the given type is or contains a dynamic class type 8709 /// (e.g., whether it has a vtable). 8710 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 8711 bool &IsContained) { 8712 // Look through array types while ignoring qualifiers. 8713 const Type *Ty = T->getBaseElementTypeUnsafe(); 8714 IsContained = false; 8715 8716 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 8717 RD = RD ? RD->getDefinition() : nullptr; 8718 if (!RD || RD->isInvalidDecl()) 8719 return nullptr; 8720 8721 if (RD->isDynamicClass()) 8722 return RD; 8723 8724 // Check all the fields. If any bases were dynamic, the class is dynamic. 8725 // It's impossible for a class to transitively contain itself by value, so 8726 // infinite recursion is impossible. 8727 for (auto *FD : RD->fields()) { 8728 bool SubContained; 8729 if (const CXXRecordDecl *ContainedRD = 8730 getContainedDynamicClass(FD->getType(), SubContained)) { 8731 IsContained = true; 8732 return ContainedRD; 8733 } 8734 } 8735 8736 return nullptr; 8737 } 8738 8739 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 8740 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 8741 if (Unary->getKind() == UETT_SizeOf) 8742 return Unary; 8743 return nullptr; 8744 } 8745 8746 /// If E is a sizeof expression, returns its argument expression, 8747 /// otherwise returns NULL. 8748 static const Expr *getSizeOfExprArg(const Expr *E) { 8749 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8750 if (!SizeOf->isArgumentType()) 8751 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 8752 return nullptr; 8753 } 8754 8755 /// If E is a sizeof expression, returns its argument type. 8756 static QualType getSizeOfArgType(const Expr *E) { 8757 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 8758 return SizeOf->getTypeOfArgument(); 8759 return QualType(); 8760 } 8761 8762 namespace { 8763 8764 struct SearchNonTrivialToInitializeField 8765 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 8766 using Super = 8767 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 8768 8769 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 8770 8771 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 8772 SourceLocation SL) { 8773 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8774 asDerived().visitArray(PDIK, AT, SL); 8775 return; 8776 } 8777 8778 Super::visitWithKind(PDIK, FT, SL); 8779 } 8780 8781 void visitARCStrong(QualType FT, SourceLocation SL) { 8782 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8783 } 8784 void visitARCWeak(QualType FT, SourceLocation SL) { 8785 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 8786 } 8787 void visitStruct(QualType FT, SourceLocation SL) { 8788 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8789 visit(FD->getType(), FD->getLocation()); 8790 } 8791 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 8792 const ArrayType *AT, SourceLocation SL) { 8793 visit(getContext().getBaseElementType(AT), SL); 8794 } 8795 void visitTrivial(QualType FT, SourceLocation SL) {} 8796 8797 static void diag(QualType RT, const Expr *E, Sema &S) { 8798 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 8799 } 8800 8801 ASTContext &getContext() { return S.getASTContext(); } 8802 8803 const Expr *E; 8804 Sema &S; 8805 }; 8806 8807 struct SearchNonTrivialToCopyField 8808 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 8809 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 8810 8811 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 8812 8813 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 8814 SourceLocation SL) { 8815 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 8816 asDerived().visitArray(PCK, AT, SL); 8817 return; 8818 } 8819 8820 Super::visitWithKind(PCK, FT, SL); 8821 } 8822 8823 void visitARCStrong(QualType FT, SourceLocation SL) { 8824 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8825 } 8826 void visitARCWeak(QualType FT, SourceLocation SL) { 8827 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 8828 } 8829 void visitStruct(QualType FT, SourceLocation SL) { 8830 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 8831 visit(FD->getType(), FD->getLocation()); 8832 } 8833 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 8834 SourceLocation SL) { 8835 visit(getContext().getBaseElementType(AT), SL); 8836 } 8837 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 8838 SourceLocation SL) {} 8839 void visitTrivial(QualType FT, SourceLocation SL) {} 8840 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 8841 8842 static void diag(QualType RT, const Expr *E, Sema &S) { 8843 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 8844 } 8845 8846 ASTContext &getContext() { return S.getASTContext(); } 8847 8848 const Expr *E; 8849 Sema &S; 8850 }; 8851 8852 } 8853 8854 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 8855 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 8856 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 8857 8858 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 8859 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 8860 return false; 8861 8862 return doesExprLikelyComputeSize(BO->getLHS()) || 8863 doesExprLikelyComputeSize(BO->getRHS()); 8864 } 8865 8866 return getAsSizeOfExpr(SizeofExpr) != nullptr; 8867 } 8868 8869 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 8870 /// 8871 /// \code 8872 /// #define MACRO 0 8873 /// foo(MACRO); 8874 /// foo(0); 8875 /// \endcode 8876 /// 8877 /// This should return true for the first call to foo, but not for the second 8878 /// (regardless of whether foo is a macro or function). 8879 static bool isArgumentExpandedFromMacro(SourceManager &SM, 8880 SourceLocation CallLoc, 8881 SourceLocation ArgLoc) { 8882 if (!CallLoc.isMacroID()) 8883 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 8884 8885 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 8886 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 8887 } 8888 8889 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 8890 /// last two arguments transposed. 8891 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 8892 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 8893 return; 8894 8895 const Expr *SizeArg = 8896 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 8897 8898 auto isLiteralZero = [](const Expr *E) { 8899 return (isa<IntegerLiteral>(E) && 8900 cast<IntegerLiteral>(E)->getValue() == 0) || 8901 (isa<CharacterLiteral>(E) && 8902 cast<CharacterLiteral>(E)->getValue() == 0); 8903 }; 8904 8905 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 8906 SourceLocation CallLoc = Call->getRParenLoc(); 8907 SourceManager &SM = S.getSourceManager(); 8908 if (isLiteralZero(SizeArg) && 8909 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 8910 8911 SourceLocation DiagLoc = SizeArg->getExprLoc(); 8912 8913 // Some platforms #define bzero to __builtin_memset. See if this is the 8914 // case, and if so, emit a better diagnostic. 8915 if (BId == Builtin::BIbzero || 8916 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 8917 CallLoc, SM, S.getLangOpts()) == "bzero")) { 8918 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 8919 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 8920 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 8921 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 8922 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 8923 } 8924 return; 8925 } 8926 8927 // If the second argument to a memset is a sizeof expression and the third 8928 // isn't, this is also likely an error. This should catch 8929 // 'memset(buf, sizeof(buf), 0xff)'. 8930 if (BId == Builtin::BImemset && 8931 doesExprLikelyComputeSize(Call->getArg(1)) && 8932 !doesExprLikelyComputeSize(Call->getArg(2))) { 8933 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 8934 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 8935 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 8936 return; 8937 } 8938 } 8939 8940 void Sema::CheckMemaccessArguments(const CallExpr *Call, 8941 unsigned BId, 8942 IdentifierInfo *FnName) { 8943 assert(BId != 0); 8944 8945 // It is possible to have a non-standard definition of memset. Validate 8946 // we have enough arguments, and if not, abort further checking. 8947 unsigned ExpectedNumArgs = 8948 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 8949 if (Call->getNumArgs() < ExpectedNumArgs) 8950 return; 8951 8952 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 8953 BId == Builtin::BIstrndup ? 1 : 2); 8954 unsigned LenArg = 8955 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 8956 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 8957 8958 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 8959 Call->getBeginLoc(), Call->getRParenLoc())) 8960 return; 8961 8962 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 8963 CheckMemaccessSize(*this, BId, Call); 8964 8965 // We have special checking when the length is a sizeof expression. 8966 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 8967 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 8968 llvm::FoldingSetNodeID SizeOfArgID; 8969 8970 // Although widely used, 'bzero' is not a standard function. Be more strict 8971 // with the argument types before allowing diagnostics and only allow the 8972 // form bzero(ptr, sizeof(...)). 8973 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8974 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 8975 return; 8976 8977 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 8978 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 8979 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 8980 8981 QualType DestTy = Dest->getType(); 8982 QualType PointeeTy; 8983 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 8984 PointeeTy = DestPtrTy->getPointeeType(); 8985 8986 // Never warn about void type pointers. This can be used to suppress 8987 // false positives. 8988 if (PointeeTy->isVoidType()) 8989 continue; 8990 8991 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 8992 // actually comparing the expressions for equality. Because computing the 8993 // expression IDs can be expensive, we only do this if the diagnostic is 8994 // enabled. 8995 if (SizeOfArg && 8996 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 8997 SizeOfArg->getExprLoc())) { 8998 // We only compute IDs for expressions if the warning is enabled, and 8999 // cache the sizeof arg's ID. 9000 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9001 SizeOfArg->Profile(SizeOfArgID, Context, true); 9002 llvm::FoldingSetNodeID DestID; 9003 Dest->Profile(DestID, Context, true); 9004 if (DestID == SizeOfArgID) { 9005 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9006 // over sizeof(src) as well. 9007 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9008 StringRef ReadableName = FnName->getName(); 9009 9010 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9011 if (UnaryOp->getOpcode() == UO_AddrOf) 9012 ActionIdx = 1; // If its an address-of operator, just remove it. 9013 if (!PointeeTy->isIncompleteType() && 9014 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9015 ActionIdx = 2; // If the pointee's size is sizeof(char), 9016 // suggest an explicit length. 9017 9018 // If the function is defined as a builtin macro, do not show macro 9019 // expansion. 9020 SourceLocation SL = SizeOfArg->getExprLoc(); 9021 SourceRange DSR = Dest->getSourceRange(); 9022 SourceRange SSR = SizeOfArg->getSourceRange(); 9023 SourceManager &SM = getSourceManager(); 9024 9025 if (SM.isMacroArgExpansion(SL)) { 9026 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9027 SL = SM.getSpellingLoc(SL); 9028 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9029 SM.getSpellingLoc(DSR.getEnd())); 9030 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9031 SM.getSpellingLoc(SSR.getEnd())); 9032 } 9033 9034 DiagRuntimeBehavior(SL, SizeOfArg, 9035 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9036 << ReadableName 9037 << PointeeTy 9038 << DestTy 9039 << DSR 9040 << SSR); 9041 DiagRuntimeBehavior(SL, SizeOfArg, 9042 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9043 << ActionIdx 9044 << SSR); 9045 9046 break; 9047 } 9048 } 9049 9050 // Also check for cases where the sizeof argument is the exact same 9051 // type as the memory argument, and where it points to a user-defined 9052 // record type. 9053 if (SizeOfArgTy != QualType()) { 9054 if (PointeeTy->isRecordType() && 9055 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9056 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9057 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9058 << FnName << SizeOfArgTy << ArgIdx 9059 << PointeeTy << Dest->getSourceRange() 9060 << LenExpr->getSourceRange()); 9061 break; 9062 } 9063 } 9064 } else if (DestTy->isArrayType()) { 9065 PointeeTy = DestTy; 9066 } 9067 9068 if (PointeeTy == QualType()) 9069 continue; 9070 9071 // Always complain about dynamic classes. 9072 bool IsContained; 9073 if (const CXXRecordDecl *ContainedRD = 9074 getContainedDynamicClass(PointeeTy, IsContained)) { 9075 9076 unsigned OperationType = 0; 9077 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9078 // "overwritten" if we're warning about the destination for any call 9079 // but memcmp; otherwise a verb appropriate to the call. 9080 if (ArgIdx != 0 || IsCmp) { 9081 if (BId == Builtin::BImemcpy) 9082 OperationType = 1; 9083 else if(BId == Builtin::BImemmove) 9084 OperationType = 2; 9085 else if (IsCmp) 9086 OperationType = 3; 9087 } 9088 9089 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9090 PDiag(diag::warn_dyn_class_memaccess) 9091 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9092 << IsContained << ContainedRD << OperationType 9093 << Call->getCallee()->getSourceRange()); 9094 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9095 BId != Builtin::BImemset) 9096 DiagRuntimeBehavior( 9097 Dest->getExprLoc(), Dest, 9098 PDiag(diag::warn_arc_object_memaccess) 9099 << ArgIdx << FnName << PointeeTy 9100 << Call->getCallee()->getSourceRange()); 9101 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9102 9103 // FIXME: Do not consider incomplete types even though they may be 9104 // completed later. GCC does not diagnose such code, but we may want to 9105 // consider diagnosing it in the future, perhaps under a different, but 9106 // related, diagnostic group. 9107 bool MayBeTriviallyCopyableCXXRecord = 9108 RT->isIncompleteType() || 9109 RT->desugar().isTriviallyCopyableType(Context); 9110 9111 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9112 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9113 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9114 PDiag(diag::warn_cstruct_memaccess) 9115 << ArgIdx << FnName << PointeeTy << 0); 9116 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9117 } else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9118 !MayBeTriviallyCopyableCXXRecord && ArgIdx == 0) { 9119 // FIXME: Limiting this warning to dest argument until we decide 9120 // whether it's valid for source argument too. 9121 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9122 PDiag(diag::warn_cxxstruct_memaccess) 9123 << FnName << PointeeTy); 9124 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9125 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9126 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9127 PDiag(diag::warn_cstruct_memaccess) 9128 << ArgIdx << FnName << PointeeTy << 1); 9129 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9130 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9131 !MayBeTriviallyCopyableCXXRecord && ArgIdx == 0) { 9132 // FIXME: Limiting this warning to dest argument until we decide 9133 // whether it's valid for source argument too. 9134 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9135 PDiag(diag::warn_cxxstruct_memaccess) 9136 << FnName << PointeeTy); 9137 } else { 9138 continue; 9139 } 9140 } else 9141 continue; 9142 9143 DiagRuntimeBehavior( 9144 Dest->getExprLoc(), Dest, 9145 PDiag(diag::note_bad_memaccess_silence) 9146 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9147 break; 9148 } 9149 } 9150 9151 // A little helper routine: ignore addition and subtraction of integer literals. 9152 // This intentionally does not ignore all integer constant expressions because 9153 // we don't want to remove sizeof(). 9154 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9155 Ex = Ex->IgnoreParenCasts(); 9156 9157 while (true) { 9158 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9159 if (!BO || !BO->isAdditiveOp()) 9160 break; 9161 9162 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9163 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9164 9165 if (isa<IntegerLiteral>(RHS)) 9166 Ex = LHS; 9167 else if (isa<IntegerLiteral>(LHS)) 9168 Ex = RHS; 9169 else 9170 break; 9171 } 9172 9173 return Ex; 9174 } 9175 9176 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9177 ASTContext &Context) { 9178 // Only handle constant-sized or VLAs, but not flexible members. 9179 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9180 // Only issue the FIXIT for arrays of size > 1. 9181 if (CAT->getZExtSize() <= 1) 9182 return false; 9183 } else if (!Ty->isVariableArrayType()) { 9184 return false; 9185 } 9186 return true; 9187 } 9188 9189 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9190 IdentifierInfo *FnName) { 9191 9192 // Don't crash if the user has the wrong number of arguments 9193 unsigned NumArgs = Call->getNumArgs(); 9194 if ((NumArgs != 3) && (NumArgs != 4)) 9195 return; 9196 9197 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9198 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9199 const Expr *CompareWithSrc = nullptr; 9200 9201 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9202 Call->getBeginLoc(), Call->getRParenLoc())) 9203 return; 9204 9205 // Look for 'strlcpy(dst, x, sizeof(x))' 9206 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9207 CompareWithSrc = Ex; 9208 else { 9209 // Look for 'strlcpy(dst, x, strlen(x))' 9210 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9211 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9212 SizeCall->getNumArgs() == 1) 9213 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9214 } 9215 } 9216 9217 if (!CompareWithSrc) 9218 return; 9219 9220 // Determine if the argument to sizeof/strlen is equal to the source 9221 // argument. In principle there's all kinds of things you could do 9222 // here, for instance creating an == expression and evaluating it with 9223 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9224 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9225 if (!SrcArgDRE) 9226 return; 9227 9228 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9229 if (!CompareWithSrcDRE || 9230 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9231 return; 9232 9233 const Expr *OriginalSizeArg = Call->getArg(2); 9234 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9235 << OriginalSizeArg->getSourceRange() << FnName; 9236 9237 // Output a FIXIT hint if the destination is an array (rather than a 9238 // pointer to an array). This could be enhanced to handle some 9239 // pointers if we know the actual size, like if DstArg is 'array+2' 9240 // we could say 'sizeof(array)-2'. 9241 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9242 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9243 return; 9244 9245 SmallString<128> sizeString; 9246 llvm::raw_svector_ostream OS(sizeString); 9247 OS << "sizeof("; 9248 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9249 OS << ")"; 9250 9251 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9252 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9253 OS.str()); 9254 } 9255 9256 /// Check if two expressions refer to the same declaration. 9257 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9258 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9259 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9260 return D1->getDecl() == D2->getDecl(); 9261 return false; 9262 } 9263 9264 static const Expr *getStrlenExprArg(const Expr *E) { 9265 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9266 const FunctionDecl *FD = CE->getDirectCallee(); 9267 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9268 return nullptr; 9269 return CE->getArg(0)->IgnoreParenCasts(); 9270 } 9271 return nullptr; 9272 } 9273 9274 void Sema::CheckStrncatArguments(const CallExpr *CE, 9275 IdentifierInfo *FnName) { 9276 // Don't crash if the user has the wrong number of arguments. 9277 if (CE->getNumArgs() < 3) 9278 return; 9279 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9280 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9281 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9282 9283 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9284 CE->getRParenLoc())) 9285 return; 9286 9287 // Identify common expressions, which are wrongly used as the size argument 9288 // to strncat and may lead to buffer overflows. 9289 unsigned PatternType = 0; 9290 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9291 // - sizeof(dst) 9292 if (referToTheSameDecl(SizeOfArg, DstArg)) 9293 PatternType = 1; 9294 // - sizeof(src) 9295 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9296 PatternType = 2; 9297 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9298 if (BE->getOpcode() == BO_Sub) { 9299 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9300 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9301 // - sizeof(dst) - strlen(dst) 9302 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9303 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9304 PatternType = 1; 9305 // - sizeof(src) - (anything) 9306 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9307 PatternType = 2; 9308 } 9309 } 9310 9311 if (PatternType == 0) 9312 return; 9313 9314 // Generate the diagnostic. 9315 SourceLocation SL = LenArg->getBeginLoc(); 9316 SourceRange SR = LenArg->getSourceRange(); 9317 SourceManager &SM = getSourceManager(); 9318 9319 // If the function is defined as a builtin macro, do not show macro expansion. 9320 if (SM.isMacroArgExpansion(SL)) { 9321 SL = SM.getSpellingLoc(SL); 9322 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9323 SM.getSpellingLoc(SR.getEnd())); 9324 } 9325 9326 // Check if the destination is an array (rather than a pointer to an array). 9327 QualType DstTy = DstArg->getType(); 9328 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9329 Context); 9330 if (!isKnownSizeArray) { 9331 if (PatternType == 1) 9332 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9333 else 9334 Diag(SL, diag::warn_strncat_src_size) << SR; 9335 return; 9336 } 9337 9338 if (PatternType == 1) 9339 Diag(SL, diag::warn_strncat_large_size) << SR; 9340 else 9341 Diag(SL, diag::warn_strncat_src_size) << SR; 9342 9343 SmallString<128> sizeString; 9344 llvm::raw_svector_ostream OS(sizeString); 9345 OS << "sizeof("; 9346 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9347 OS << ") - "; 9348 OS << "strlen("; 9349 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9350 OS << ") - 1"; 9351 9352 Diag(SL, diag::note_strncat_wrong_size) 9353 << FixItHint::CreateReplacement(SR, OS.str()); 9354 } 9355 9356 namespace { 9357 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 9358 const UnaryOperator *UnaryExpr, const Decl *D) { 9359 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 9360 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 9361 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 9362 return; 9363 } 9364 } 9365 9366 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 9367 const UnaryOperator *UnaryExpr) { 9368 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 9369 const Decl *D = Lvalue->getDecl(); 9370 if (isa<DeclaratorDecl>(D)) 9371 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 9372 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 9373 } 9374 9375 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 9376 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 9377 Lvalue->getMemberDecl()); 9378 } 9379 9380 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 9381 const UnaryOperator *UnaryExpr) { 9382 const auto *Lambda = dyn_cast<LambdaExpr>( 9383 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 9384 if (!Lambda) 9385 return; 9386 9387 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 9388 << CalleeName << 2 /*object: lambda expression*/; 9389 } 9390 9391 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 9392 const DeclRefExpr *Lvalue) { 9393 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 9394 if (Var == nullptr) 9395 return; 9396 9397 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 9398 << CalleeName << 0 /*object: */ << Var; 9399 } 9400 9401 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 9402 const CastExpr *Cast) { 9403 SmallString<128> SizeString; 9404 llvm::raw_svector_ostream OS(SizeString); 9405 9406 clang::CastKind Kind = Cast->getCastKind(); 9407 if (Kind == clang::CK_BitCast && 9408 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 9409 return; 9410 if (Kind == clang::CK_IntegralToPointer && 9411 !isa<IntegerLiteral>( 9412 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 9413 return; 9414 9415 switch (Cast->getCastKind()) { 9416 case clang::CK_BitCast: 9417 case clang::CK_IntegralToPointer: 9418 case clang::CK_FunctionToPointerDecay: 9419 OS << '\''; 9420 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 9421 OS << '\''; 9422 break; 9423 default: 9424 return; 9425 } 9426 9427 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 9428 << CalleeName << 0 /*object: */ << OS.str(); 9429 } 9430 } // namespace 9431 9432 void Sema::CheckFreeArguments(const CallExpr *E) { 9433 const std::string CalleeName = 9434 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 9435 9436 { // Prefer something that doesn't involve a cast to make things simpler. 9437 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 9438 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 9439 switch (UnaryExpr->getOpcode()) { 9440 case UnaryOperator::Opcode::UO_AddrOf: 9441 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 9442 case UnaryOperator::Opcode::UO_Plus: 9443 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 9444 default: 9445 break; 9446 } 9447 9448 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 9449 if (Lvalue->getType()->isArrayType()) 9450 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 9451 9452 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 9453 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 9454 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 9455 return; 9456 } 9457 9458 if (isa<BlockExpr>(Arg)) { 9459 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 9460 << CalleeName << 1 /*object: block*/; 9461 return; 9462 } 9463 } 9464 // Maybe the cast was important, check after the other cases. 9465 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 9466 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 9467 } 9468 9469 void 9470 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9471 SourceLocation ReturnLoc, 9472 bool isObjCMethod, 9473 const AttrVec *Attrs, 9474 const FunctionDecl *FD) { 9475 // Check if the return value is null but should not be. 9476 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9477 (!isObjCMethod && isNonNullType(lhsType))) && 9478 CheckNonNullExpr(*this, RetValExp)) 9479 Diag(ReturnLoc, diag::warn_null_ret) 9480 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9481 9482 // C++11 [basic.stc.dynamic.allocation]p4: 9483 // If an allocation function declared with a non-throwing 9484 // exception-specification fails to allocate storage, it shall return 9485 // a null pointer. Any other allocation function that fails to allocate 9486 // storage shall indicate failure only by throwing an exception [...] 9487 if (FD) { 9488 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9489 if (Op == OO_New || Op == OO_Array_New) { 9490 const FunctionProtoType *Proto 9491 = FD->getType()->castAs<FunctionProtoType>(); 9492 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9493 CheckNonNullExpr(*this, RetValExp)) 9494 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9495 << FD << getLangOpts().CPlusPlus11; 9496 } 9497 } 9498 9499 if (RetValExp && RetValExp->getType()->isWebAssemblyTableType()) { 9500 Diag(ReturnLoc, diag::err_wasm_table_art) << 1; 9501 } 9502 9503 // PPC MMA non-pointer types are not allowed as return type. Checking the type 9504 // here prevent the user from using a PPC MMA type as trailing return type. 9505 if (Context.getTargetInfo().getTriple().isPPC64()) 9506 PPC().CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 9507 } 9508 9509 void Sema::CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, 9510 BinaryOperatorKind Opcode) { 9511 if (!BinaryOperator::isEqualityOp(Opcode)) 9512 return; 9513 9514 // Match and capture subexpressions such as "(float) X == 0.1". 9515 FloatingLiteral *FPLiteral; 9516 CastExpr *FPCast; 9517 auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) { 9518 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens()); 9519 FPCast = dyn_cast<CastExpr>(R->IgnoreParens()); 9520 return FPLiteral && FPCast; 9521 }; 9522 9523 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) { 9524 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>(); 9525 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>(); 9526 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() && 9527 TargetTy->isFloatingPoint()) { 9528 bool Lossy; 9529 llvm::APFloat TargetC = FPLiteral->getValue(); 9530 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)), 9531 llvm::APFloat::rmNearestTiesToEven, &Lossy); 9532 if (Lossy) { 9533 // If the literal cannot be represented in the source type, then a 9534 // check for == is always false and check for != is always true. 9535 Diag(Loc, diag::warn_float_compare_literal) 9536 << (Opcode == BO_EQ) << QualType(SourceTy, 0) 9537 << LHS->getSourceRange() << RHS->getSourceRange(); 9538 return; 9539 } 9540 } 9541 } 9542 9543 // Match a more general floating-point equality comparison (-Wfloat-equal). 9544 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9545 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9546 9547 // Special case: check for x == x (which is OK). 9548 // Do not emit warnings for such cases. 9549 if (auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9550 if (auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9551 if (DRL->getDecl() == DRR->getDecl()) 9552 return; 9553 9554 // Special case: check for comparisons against literals that can be exactly 9555 // represented by APFloat. In such cases, do not emit a warning. This 9556 // is a heuristic: often comparison against such literals are used to 9557 // detect if a value in a variable has not changed. This clearly can 9558 // lead to false negatives. 9559 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9560 if (FLL->isExact()) 9561 return; 9562 } else 9563 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9564 if (FLR->isExact()) 9565 return; 9566 9567 // Check for comparisons with builtin types. 9568 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9569 if (CL->getBuiltinCallee()) 9570 return; 9571 9572 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9573 if (CR->getBuiltinCallee()) 9574 return; 9575 9576 // Emit the diagnostic. 9577 Diag(Loc, diag::warn_floatingpoint_eq) 9578 << LHS->getSourceRange() << RHS->getSourceRange(); 9579 } 9580 9581 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9582 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9583 9584 namespace { 9585 9586 /// Structure recording the 'active' range of an integer-valued 9587 /// expression. 9588 struct IntRange { 9589 /// The number of bits active in the int. Note that this includes exactly one 9590 /// sign bit if !NonNegative. 9591 unsigned Width; 9592 9593 /// True if the int is known not to have negative values. If so, all leading 9594 /// bits before Width are known zero, otherwise they are known to be the 9595 /// same as the MSB within Width. 9596 bool NonNegative; 9597 9598 IntRange(unsigned Width, bool NonNegative) 9599 : Width(Width), NonNegative(NonNegative) {} 9600 9601 /// Number of bits excluding the sign bit. 9602 unsigned valueBits() const { 9603 return NonNegative ? Width : Width - 1; 9604 } 9605 9606 /// Returns the range of the bool type. 9607 static IntRange forBoolType() { 9608 return IntRange(1, true); 9609 } 9610 9611 /// Returns the range of an opaque value of the given integral type. 9612 static IntRange forValueOfType(ASTContext &C, QualType T) { 9613 return forValueOfCanonicalType(C, 9614 T->getCanonicalTypeInternal().getTypePtr()); 9615 } 9616 9617 /// Returns the range of an opaque value of a canonical integral type. 9618 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9619 assert(T->isCanonicalUnqualified()); 9620 9621 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9622 T = VT->getElementType().getTypePtr(); 9623 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9624 T = CT->getElementType().getTypePtr(); 9625 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9626 T = AT->getValueType().getTypePtr(); 9627 9628 if (!C.getLangOpts().CPlusPlus) { 9629 // For enum types in C code, use the underlying datatype. 9630 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9631 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9632 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9633 // For enum types in C++, use the known bit width of the enumerators. 9634 EnumDecl *Enum = ET->getDecl(); 9635 // In C++11, enums can have a fixed underlying type. Use this type to 9636 // compute the range. 9637 if (Enum->isFixed()) { 9638 return IntRange(C.getIntWidth(QualType(T, 0)), 9639 !ET->isSignedIntegerOrEnumerationType()); 9640 } 9641 9642 unsigned NumPositive = Enum->getNumPositiveBits(); 9643 unsigned NumNegative = Enum->getNumNegativeBits(); 9644 9645 if (NumNegative == 0) 9646 return IntRange(NumPositive, true/*NonNegative*/); 9647 else 9648 return IntRange(std::max(NumPositive + 1, NumNegative), 9649 false/*NonNegative*/); 9650 } 9651 9652 if (const auto *EIT = dyn_cast<BitIntType>(T)) 9653 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 9654 9655 const BuiltinType *BT = cast<BuiltinType>(T); 9656 assert(BT->isInteger()); 9657 9658 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9659 } 9660 9661 /// Returns the "target" range of a canonical integral type, i.e. 9662 /// the range of values expressible in the type. 9663 /// 9664 /// This matches forValueOfCanonicalType except that enums have the 9665 /// full range of their type, not the range of their enumerators. 9666 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9667 assert(T->isCanonicalUnqualified()); 9668 9669 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9670 T = VT->getElementType().getTypePtr(); 9671 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9672 T = CT->getElementType().getTypePtr(); 9673 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9674 T = AT->getValueType().getTypePtr(); 9675 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9676 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9677 9678 if (const auto *EIT = dyn_cast<BitIntType>(T)) 9679 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 9680 9681 const BuiltinType *BT = cast<BuiltinType>(T); 9682 assert(BT->isInteger()); 9683 9684 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9685 } 9686 9687 /// Returns the supremum of two ranges: i.e. their conservative merge. 9688 static IntRange join(IntRange L, IntRange R) { 9689 bool Unsigned = L.NonNegative && R.NonNegative; 9690 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 9691 L.NonNegative && R.NonNegative); 9692 } 9693 9694 /// Return the range of a bitwise-AND of the two ranges. 9695 static IntRange bit_and(IntRange L, IntRange R) { 9696 unsigned Bits = std::max(L.Width, R.Width); 9697 bool NonNegative = false; 9698 if (L.NonNegative) { 9699 Bits = std::min(Bits, L.Width); 9700 NonNegative = true; 9701 } 9702 if (R.NonNegative) { 9703 Bits = std::min(Bits, R.Width); 9704 NonNegative = true; 9705 } 9706 return IntRange(Bits, NonNegative); 9707 } 9708 9709 /// Return the range of a sum of the two ranges. 9710 static IntRange sum(IntRange L, IntRange R) { 9711 bool Unsigned = L.NonNegative && R.NonNegative; 9712 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 9713 Unsigned); 9714 } 9715 9716 /// Return the range of a difference of the two ranges. 9717 static IntRange difference(IntRange L, IntRange R) { 9718 // We need a 1-bit-wider range if: 9719 // 1) LHS can be negative: least value can be reduced. 9720 // 2) RHS can be negative: greatest value can be increased. 9721 bool CanWiden = !L.NonNegative || !R.NonNegative; 9722 bool Unsigned = L.NonNegative && R.Width == 0; 9723 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 9724 !Unsigned, 9725 Unsigned); 9726 } 9727 9728 /// Return the range of a product of the two ranges. 9729 static IntRange product(IntRange L, IntRange R) { 9730 // If both LHS and RHS can be negative, we can form 9731 // -2^L * -2^R = 2^(L + R) 9732 // which requires L + R + 1 value bits to represent. 9733 bool CanWiden = !L.NonNegative && !R.NonNegative; 9734 bool Unsigned = L.NonNegative && R.NonNegative; 9735 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 9736 Unsigned); 9737 } 9738 9739 /// Return the range of a remainder operation between the two ranges. 9740 static IntRange rem(IntRange L, IntRange R) { 9741 // The result of a remainder can't be larger than the result of 9742 // either side. The sign of the result is the sign of the LHS. 9743 bool Unsigned = L.NonNegative; 9744 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 9745 Unsigned); 9746 } 9747 }; 9748 9749 } // namespace 9750 9751 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9752 unsigned MaxWidth) { 9753 if (value.isSigned() && value.isNegative()) 9754 return IntRange(value.getSignificantBits(), false); 9755 9756 if (value.getBitWidth() > MaxWidth) 9757 value = value.trunc(MaxWidth); 9758 9759 // isNonNegative() just checks the sign bit without considering 9760 // signedness. 9761 return IntRange(value.getActiveBits(), true); 9762 } 9763 9764 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9765 unsigned MaxWidth) { 9766 if (result.isInt()) 9767 return GetValueRange(C, result.getInt(), MaxWidth); 9768 9769 if (result.isVector()) { 9770 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9771 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9772 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9773 R = IntRange::join(R, El); 9774 } 9775 return R; 9776 } 9777 9778 if (result.isComplexInt()) { 9779 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9780 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9781 return IntRange::join(R, I); 9782 } 9783 9784 // This can happen with lossless casts to intptr_t of "based" lvalues. 9785 // Assume it might use arbitrary bits. 9786 // FIXME: The only reason we need to pass the type in here is to get 9787 // the sign right on this one case. It would be nice if APValue 9788 // preserved this. 9789 assert(result.isLValue() || result.isAddrLabelDiff()); 9790 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9791 } 9792 9793 static QualType GetExprType(const Expr *E) { 9794 QualType Ty = E->getType(); 9795 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9796 Ty = AtomicRHS->getValueType(); 9797 return Ty; 9798 } 9799 9800 /// Attempts to estimate an approximate range for the given integer expression. 9801 /// Returns a range if successful, otherwise it returns \c std::nullopt if a 9802 /// reliable estimation cannot be determined. 9803 /// 9804 /// \param MaxWidth The width to which the value will be truncated. 9805 /// \param InConstantContext If \c true, interpret the expression within a 9806 /// constant context. 9807 /// \param Approximate If \c true, provide a likely range of values by assuming 9808 /// that arithmetic on narrower types remains within those types. 9809 /// If \c false, return a range that includes all possible values 9810 /// resulting from the expression. 9811 /// \returns A range of values that the expression might take, or 9812 /// std::nullopt if a reliable estimation cannot be determined. 9813 static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E, 9814 unsigned MaxWidth, 9815 bool InConstantContext, 9816 bool Approximate) { 9817 E = E->IgnoreParens(); 9818 9819 // Try a full evaluation first. 9820 Expr::EvalResult result; 9821 if (E->EvaluateAsRValue(result, C, InConstantContext)) 9822 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9823 9824 // I think we only want to look through implicit casts here; if the 9825 // user has an explicit widening cast, we should treat the value as 9826 // being of the new, wider type. 9827 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9828 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9829 return TryGetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 9830 Approximate); 9831 9832 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9833 9834 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9835 CE->getCastKind() == CK_BooleanToSignedIntegral; 9836 9837 // Assume that non-integer casts can span the full range of the type. 9838 if (!isIntegerCast) 9839 return OutputTypeRange; 9840 9841 std::optional<IntRange> SubRange = TryGetExprRange( 9842 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width), 9843 InConstantContext, Approximate); 9844 if (!SubRange) 9845 return std::nullopt; 9846 9847 // Bail out if the subexpr's range is as wide as the cast type. 9848 if (SubRange->Width >= OutputTypeRange.Width) 9849 return OutputTypeRange; 9850 9851 // Otherwise, we take the smaller width, and we're non-negative if 9852 // either the output type or the subexpr is. 9853 return IntRange(SubRange->Width, 9854 SubRange->NonNegative || OutputTypeRange.NonNegative); 9855 } 9856 9857 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9858 // If we can fold the condition, just take that operand. 9859 bool CondResult; 9860 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9861 return TryGetExprRange( 9862 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth, 9863 InConstantContext, Approximate); 9864 9865 // Otherwise, conservatively merge. 9866 // TryGetExprRange requires an integer expression, but a throw expression 9867 // results in a void type. 9868 Expr *TrueExpr = CO->getTrueExpr(); 9869 if (TrueExpr->getType()->isVoidType()) 9870 return std::nullopt; 9871 9872 std::optional<IntRange> L = 9873 TryGetExprRange(C, TrueExpr, MaxWidth, InConstantContext, Approximate); 9874 if (!L) 9875 return std::nullopt; 9876 9877 Expr *FalseExpr = CO->getFalseExpr(); 9878 if (FalseExpr->getType()->isVoidType()) 9879 return std::nullopt; 9880 9881 std::optional<IntRange> R = 9882 TryGetExprRange(C, FalseExpr, MaxWidth, InConstantContext, Approximate); 9883 if (!R) 9884 return std::nullopt; 9885 9886 return IntRange::join(*L, *R); 9887 } 9888 9889 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9890 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 9891 9892 switch (BO->getOpcode()) { 9893 case BO_Cmp: 9894 llvm_unreachable("builtin <=> should have class type"); 9895 9896 // Boolean-valued operations are single-bit and positive. 9897 case BO_LAnd: 9898 case BO_LOr: 9899 case BO_LT: 9900 case BO_GT: 9901 case BO_LE: 9902 case BO_GE: 9903 case BO_EQ: 9904 case BO_NE: 9905 return IntRange::forBoolType(); 9906 9907 // The type of the assignments is the type of the LHS, so the RHS 9908 // is not necessarily the same type. 9909 case BO_MulAssign: 9910 case BO_DivAssign: 9911 case BO_RemAssign: 9912 case BO_AddAssign: 9913 case BO_SubAssign: 9914 case BO_XorAssign: 9915 case BO_OrAssign: 9916 // TODO: bitfields? 9917 return IntRange::forValueOfType(C, GetExprType(E)); 9918 9919 // Simple assignments just pass through the RHS, which will have 9920 // been coerced to the LHS type. 9921 case BO_Assign: 9922 // TODO: bitfields? 9923 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 9924 Approximate); 9925 9926 // Operations with opaque sources are black-listed. 9927 case BO_PtrMemD: 9928 case BO_PtrMemI: 9929 return IntRange::forValueOfType(C, GetExprType(E)); 9930 9931 // Bitwise-and uses the *infinum* of the two source ranges. 9932 case BO_And: 9933 case BO_AndAssign: 9934 Combine = IntRange::bit_and; 9935 break; 9936 9937 // Left shift gets black-listed based on a judgement call. 9938 case BO_Shl: 9939 // ...except that we want to treat '1 << (blah)' as logically 9940 // positive. It's an important idiom. 9941 if (IntegerLiteral *I 9942 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9943 if (I->getValue() == 1) { 9944 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9945 return IntRange(R.Width, /*NonNegative*/ true); 9946 } 9947 } 9948 [[fallthrough]]; 9949 9950 case BO_ShlAssign: 9951 return IntRange::forValueOfType(C, GetExprType(E)); 9952 9953 // Right shift by a constant can narrow its left argument. 9954 case BO_Shr: 9955 case BO_ShrAssign: { 9956 std::optional<IntRange> L = TryGetExprRange( 9957 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate); 9958 if (!L) 9959 return std::nullopt; 9960 9961 // If the shift amount is a positive constant, drop the width by 9962 // that much. 9963 if (std::optional<llvm::APSInt> shift = 9964 BO->getRHS()->getIntegerConstantExpr(C)) { 9965 if (shift->isNonNegative()) { 9966 if (shift->uge(L->Width)) 9967 L->Width = (L->NonNegative ? 0 : 1); 9968 else 9969 L->Width -= shift->getZExtValue(); 9970 } 9971 } 9972 9973 return L; 9974 } 9975 9976 // Comma acts as its right operand. 9977 case BO_Comma: 9978 return TryGetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 9979 Approximate); 9980 9981 case BO_Add: 9982 if (!Approximate) 9983 Combine = IntRange::sum; 9984 break; 9985 9986 case BO_Sub: 9987 if (BO->getLHS()->getType()->isPointerType()) 9988 return IntRange::forValueOfType(C, GetExprType(E)); 9989 if (!Approximate) 9990 Combine = IntRange::difference; 9991 break; 9992 9993 case BO_Mul: 9994 if (!Approximate) 9995 Combine = IntRange::product; 9996 break; 9997 9998 // The width of a division result is mostly determined by the size 9999 // of the LHS. 10000 case BO_Div: { 10001 // Don't 'pre-truncate' the operands. 10002 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10003 std::optional<IntRange> L = TryGetExprRange( 10004 C, BO->getLHS(), opWidth, InConstantContext, Approximate); 10005 if (!L) 10006 return std::nullopt; 10007 10008 // If the divisor is constant, use that. 10009 if (std::optional<llvm::APSInt> divisor = 10010 BO->getRHS()->getIntegerConstantExpr(C)) { 10011 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 10012 if (log2 >= L->Width) 10013 L->Width = (L->NonNegative ? 0 : 1); 10014 else 10015 L->Width = std::min(L->Width - log2, MaxWidth); 10016 return L; 10017 } 10018 10019 // Otherwise, just use the LHS's width. 10020 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 10021 // could be -1. 10022 std::optional<IntRange> R = TryGetExprRange( 10023 C, BO->getRHS(), opWidth, InConstantContext, Approximate); 10024 if (!R) 10025 return std::nullopt; 10026 10027 return IntRange(L->Width, L->NonNegative && R->NonNegative); 10028 } 10029 10030 case BO_Rem: 10031 Combine = IntRange::rem; 10032 break; 10033 10034 // The default behavior is okay for these. 10035 case BO_Xor: 10036 case BO_Or: 10037 break; 10038 } 10039 10040 // Combine the two ranges, but limit the result to the type in which we 10041 // performed the computation. 10042 QualType T = GetExprType(E); 10043 unsigned opWidth = C.getIntWidth(T); 10044 std::optional<IntRange> L = TryGetExprRange(C, BO->getLHS(), opWidth, 10045 InConstantContext, Approximate); 10046 if (!L) 10047 return std::nullopt; 10048 10049 std::optional<IntRange> R = TryGetExprRange(C, BO->getRHS(), opWidth, 10050 InConstantContext, Approximate); 10051 if (!R) 10052 return std::nullopt; 10053 10054 IntRange C = Combine(*L, *R); 10055 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 10056 C.Width = std::min(C.Width, MaxWidth); 10057 return C; 10058 } 10059 10060 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10061 switch (UO->getOpcode()) { 10062 // Boolean-valued operations are white-listed. 10063 case UO_LNot: 10064 return IntRange::forBoolType(); 10065 10066 // Operations with opaque sources are black-listed. 10067 case UO_Deref: 10068 case UO_AddrOf: // should be impossible 10069 return IntRange::forValueOfType(C, GetExprType(E)); 10070 10071 default: 10072 return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 10073 Approximate); 10074 } 10075 } 10076 10077 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10078 return TryGetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 10079 Approximate); 10080 10081 if (const auto *BitField = E->getSourceBitField()) 10082 return IntRange(BitField->getBitWidthValue(), 10083 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10084 10085 if (GetExprType(E)->isVoidType()) 10086 return std::nullopt; 10087 10088 return IntRange::forValueOfType(C, GetExprType(E)); 10089 } 10090 10091 static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E, 10092 bool InConstantContext, 10093 bool Approximate) { 10094 return TryGetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 10095 Approximate); 10096 } 10097 10098 /// Checks whether the given value, which currently has the given 10099 /// source semantics, has the same value when coerced through the 10100 /// target semantics. 10101 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10102 const llvm::fltSemantics &Src, 10103 const llvm::fltSemantics &Tgt) { 10104 llvm::APFloat truncated = value; 10105 10106 bool ignored; 10107 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10108 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10109 10110 return truncated.bitwiseIsEqual(value); 10111 } 10112 10113 /// Checks whether the given value, which currently has the given 10114 /// source semantics, has the same value when coerced through the 10115 /// target semantics. 10116 /// 10117 /// The value might be a vector of floats (or a complex number). 10118 static bool IsSameFloatAfterCast(const APValue &value, 10119 const llvm::fltSemantics &Src, 10120 const llvm::fltSemantics &Tgt) { 10121 if (value.isFloat()) 10122 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10123 10124 if (value.isVector()) { 10125 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10126 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10127 return false; 10128 return true; 10129 } 10130 10131 assert(value.isComplexFloat()); 10132 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10133 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10134 } 10135 10136 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10137 bool IsListInit = false); 10138 10139 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10140 // Suppress cases where we are comparing against an enum constant. 10141 if (const DeclRefExpr *DR = 10142 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10143 if (isa<EnumConstantDecl>(DR->getDecl())) 10144 return true; 10145 10146 // Suppress cases where the value is expanded from a macro, unless that macro 10147 // is how a language represents a boolean literal. This is the case in both C 10148 // and Objective-C. 10149 SourceLocation BeginLoc = E->getBeginLoc(); 10150 if (BeginLoc.isMacroID()) { 10151 StringRef MacroName = Lexer::getImmediateMacroName( 10152 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10153 return MacroName != "YES" && MacroName != "NO" && 10154 MacroName != "true" && MacroName != "false"; 10155 } 10156 10157 return false; 10158 } 10159 10160 static bool isKnownToHaveUnsignedValue(Expr *E) { 10161 return E->getType()->isIntegerType() && 10162 (!E->getType()->isSignedIntegerType() || 10163 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10164 } 10165 10166 namespace { 10167 /// The promoted range of values of a type. In general this has the 10168 /// following structure: 10169 /// 10170 /// |-----------| . . . |-----------| 10171 /// ^ ^ ^ ^ 10172 /// Min HoleMin HoleMax Max 10173 /// 10174 /// ... where there is only a hole if a signed type is promoted to unsigned 10175 /// (in which case Min and Max are the smallest and largest representable 10176 /// values). 10177 struct PromotedRange { 10178 // Min, or HoleMax if there is a hole. 10179 llvm::APSInt PromotedMin; 10180 // Max, or HoleMin if there is a hole. 10181 llvm::APSInt PromotedMax; 10182 10183 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10184 if (R.Width == 0) 10185 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10186 else if (R.Width >= BitWidth && !Unsigned) { 10187 // Promotion made the type *narrower*. This happens when promoting 10188 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10189 // Treat all values of 'signed int' as being in range for now. 10190 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10191 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10192 } else { 10193 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10194 .extOrTrunc(BitWidth); 10195 PromotedMin.setIsUnsigned(Unsigned); 10196 10197 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10198 .extOrTrunc(BitWidth); 10199 PromotedMax.setIsUnsigned(Unsigned); 10200 } 10201 } 10202 10203 // Determine whether this range is contiguous (has no hole). 10204 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10205 10206 // Where a constant value is within the range. 10207 enum ComparisonResult { 10208 LT = 0x1, 10209 LE = 0x2, 10210 GT = 0x4, 10211 GE = 0x8, 10212 EQ = 0x10, 10213 NE = 0x20, 10214 InRangeFlag = 0x40, 10215 10216 Less = LE | LT | NE, 10217 Min = LE | InRangeFlag, 10218 InRange = InRangeFlag, 10219 Max = GE | InRangeFlag, 10220 Greater = GE | GT | NE, 10221 10222 OnlyValue = LE | GE | EQ | InRangeFlag, 10223 InHole = NE 10224 }; 10225 10226 ComparisonResult compare(const llvm::APSInt &Value) const { 10227 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10228 Value.isUnsigned() == PromotedMin.isUnsigned()); 10229 if (!isContiguous()) { 10230 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10231 if (Value.isMinValue()) return Min; 10232 if (Value.isMaxValue()) return Max; 10233 if (Value >= PromotedMin) return InRange; 10234 if (Value <= PromotedMax) return InRange; 10235 return InHole; 10236 } 10237 10238 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10239 case -1: return Less; 10240 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10241 case 1: 10242 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10243 case -1: return InRange; 10244 case 0: return Max; 10245 case 1: return Greater; 10246 } 10247 } 10248 10249 llvm_unreachable("impossible compare result"); 10250 } 10251 10252 static std::optional<StringRef> 10253 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10254 if (Op == BO_Cmp) { 10255 ComparisonResult LTFlag = LT, GTFlag = GT; 10256 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10257 10258 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10259 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10260 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10261 return std::nullopt; 10262 } 10263 10264 ComparisonResult TrueFlag, FalseFlag; 10265 if (Op == BO_EQ) { 10266 TrueFlag = EQ; 10267 FalseFlag = NE; 10268 } else if (Op == BO_NE) { 10269 TrueFlag = NE; 10270 FalseFlag = EQ; 10271 } else { 10272 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10273 TrueFlag = LT; 10274 FalseFlag = GE; 10275 } else { 10276 TrueFlag = GT; 10277 FalseFlag = LE; 10278 } 10279 if (Op == BO_GE || Op == BO_LE) 10280 std::swap(TrueFlag, FalseFlag); 10281 } 10282 if (R & TrueFlag) 10283 return StringRef("true"); 10284 if (R & FalseFlag) 10285 return StringRef("false"); 10286 return std::nullopt; 10287 } 10288 }; 10289 } 10290 10291 static bool HasEnumType(Expr *E) { 10292 // Strip off implicit integral promotions. 10293 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10294 if (ICE->getCastKind() != CK_IntegralCast && 10295 ICE->getCastKind() != CK_NoOp) 10296 break; 10297 E = ICE->getSubExpr(); 10298 } 10299 10300 return E->getType()->isEnumeralType(); 10301 } 10302 10303 static int classifyConstantValue(Expr *Constant) { 10304 // The values of this enumeration are used in the diagnostics 10305 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10306 enum ConstantValueKind { 10307 Miscellaneous = 0, 10308 LiteralTrue, 10309 LiteralFalse 10310 }; 10311 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10312 return BL->getValue() ? ConstantValueKind::LiteralTrue 10313 : ConstantValueKind::LiteralFalse; 10314 return ConstantValueKind::Miscellaneous; 10315 } 10316 10317 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10318 Expr *Constant, Expr *Other, 10319 const llvm::APSInt &Value, 10320 bool RhsConstant) { 10321 if (S.inTemplateInstantiation()) 10322 return false; 10323 10324 Expr *OriginalOther = Other; 10325 10326 Constant = Constant->IgnoreParenImpCasts(); 10327 Other = Other->IgnoreParenImpCasts(); 10328 10329 // Suppress warnings on tautological comparisons between values of the same 10330 // enumeration type. There are only two ways we could warn on this: 10331 // - If the constant is outside the range of representable values of 10332 // the enumeration. In such a case, we should warn about the cast 10333 // to enumeration type, not about the comparison. 10334 // - If the constant is the maximum / minimum in-range value. For an 10335 // enumeratin type, such comparisons can be meaningful and useful. 10336 if (Constant->getType()->isEnumeralType() && 10337 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10338 return false; 10339 10340 std::optional<IntRange> OtherValueRange = TryGetExprRange( 10341 S.Context, Other, S.isConstantEvaluatedContext(), /*Approximate=*/false); 10342 if (!OtherValueRange) 10343 return false; 10344 10345 QualType OtherT = Other->getType(); 10346 if (const auto *AT = OtherT->getAs<AtomicType>()) 10347 OtherT = AT->getValueType(); 10348 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 10349 10350 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10351 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 10352 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10353 S.ObjC().NSAPIObj->isObjCBOOLType(OtherT) && 10354 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10355 10356 // Whether we're treating Other as being a bool because of the form of 10357 // expression despite it having another type (typically 'int' in C). 10358 bool OtherIsBooleanDespiteType = 10359 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10360 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10361 OtherTypeRange = *OtherValueRange = IntRange::forBoolType(); 10362 10363 // Check if all values in the range of possible values of this expression 10364 // lead to the same comparison outcome. 10365 PromotedRange OtherPromotedValueRange(*OtherValueRange, Value.getBitWidth(), 10366 Value.isUnsigned()); 10367 auto Cmp = OtherPromotedValueRange.compare(Value); 10368 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10369 if (!Result) 10370 return false; 10371 10372 // Also consider the range determined by the type alone. This allows us to 10373 // classify the warning under the proper diagnostic group. 10374 bool TautologicalTypeCompare = false; 10375 { 10376 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 10377 Value.isUnsigned()); 10378 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 10379 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 10380 RhsConstant)) { 10381 TautologicalTypeCompare = true; 10382 Cmp = TypeCmp; 10383 Result = TypeResult; 10384 } 10385 } 10386 10387 // Don't warn if the non-constant operand actually always evaluates to the 10388 // same value. 10389 if (!TautologicalTypeCompare && OtherValueRange->Width == 0) 10390 return false; 10391 10392 // Suppress the diagnostic for an in-range comparison if the constant comes 10393 // from a macro or enumerator. We don't want to diagnose 10394 // 10395 // some_long_value <= INT_MAX 10396 // 10397 // when sizeof(int) == sizeof(long). 10398 bool InRange = Cmp & PromotedRange::InRangeFlag; 10399 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10400 return false; 10401 10402 // A comparison of an unsigned bit-field against 0 is really a type problem, 10403 // even though at the type level the bit-field might promote to 'signed int'. 10404 if (Other->refersToBitField() && InRange && Value == 0 && 10405 Other->getType()->isUnsignedIntegerOrEnumerationType()) 10406 TautologicalTypeCompare = true; 10407 10408 // If this is a comparison to an enum constant, include that 10409 // constant in the diagnostic. 10410 const EnumConstantDecl *ED = nullptr; 10411 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10412 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10413 10414 // Should be enough for uint128 (39 decimal digits) 10415 SmallString<64> PrettySourceValue; 10416 llvm::raw_svector_ostream OS(PrettySourceValue); 10417 if (ED) { 10418 OS << '\'' << *ED << "' (" << Value << ")"; 10419 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10420 Constant->IgnoreParenImpCasts())) { 10421 OS << (BL->getValue() ? "YES" : "NO"); 10422 } else { 10423 OS << Value; 10424 } 10425 10426 if (!TautologicalTypeCompare) { 10427 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 10428 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative 10429 << E->getOpcodeStr() << OS.str() << *Result 10430 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10431 return true; 10432 } 10433 10434 if (IsObjCSignedCharBool) { 10435 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10436 S.PDiag(diag::warn_tautological_compare_objc_bool) 10437 << OS.str() << *Result); 10438 return true; 10439 } 10440 10441 // FIXME: We use a somewhat different formatting for the in-range cases and 10442 // cases involving boolean values for historical reasons. We should pick a 10443 // consistent way of presenting these diagnostics. 10444 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10445 10446 S.DiagRuntimeBehavior( 10447 E->getOperatorLoc(), E, 10448 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10449 : diag::warn_tautological_bool_compare) 10450 << OS.str() << classifyConstantValue(Constant) << OtherT 10451 << OtherIsBooleanDespiteType << *Result 10452 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10453 } else { 10454 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 10455 unsigned Diag = 10456 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10457 ? (HasEnumType(OriginalOther) 10458 ? diag::warn_unsigned_enum_always_true_comparison 10459 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 10460 : diag::warn_unsigned_always_true_comparison) 10461 : diag::warn_tautological_constant_compare; 10462 10463 S.Diag(E->getOperatorLoc(), Diag) 10464 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10465 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10466 } 10467 10468 return true; 10469 } 10470 10471 /// Analyze the operands of the given comparison. Implements the 10472 /// fallback case from AnalyzeComparison. 10473 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10474 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10475 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10476 } 10477 10478 /// Implements -Wsign-compare. 10479 /// 10480 /// \param E the binary operator to check for warnings 10481 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10482 // The type the comparison is being performed in. 10483 QualType T = E->getLHS()->getType(); 10484 10485 // Only analyze comparison operators where both sides have been converted to 10486 // the same type. 10487 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10488 return AnalyzeImpConvsInComparison(S, E); 10489 10490 // Don't analyze value-dependent comparisons directly. 10491 if (E->isValueDependent()) 10492 return AnalyzeImpConvsInComparison(S, E); 10493 10494 Expr *LHS = E->getLHS(); 10495 Expr *RHS = E->getRHS(); 10496 10497 if (T->isIntegralType(S.Context)) { 10498 std::optional<llvm::APSInt> RHSValue = 10499 RHS->getIntegerConstantExpr(S.Context); 10500 std::optional<llvm::APSInt> LHSValue = 10501 LHS->getIntegerConstantExpr(S.Context); 10502 10503 // We don't care about expressions whose result is a constant. 10504 if (RHSValue && LHSValue) 10505 return AnalyzeImpConvsInComparison(S, E); 10506 10507 // We only care about expressions where just one side is literal 10508 if ((bool)RHSValue ^ (bool)LHSValue) { 10509 // Is the constant on the RHS or LHS? 10510 const bool RhsConstant = (bool)RHSValue; 10511 Expr *Const = RhsConstant ? RHS : LHS; 10512 Expr *Other = RhsConstant ? LHS : RHS; 10513 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 10514 10515 // Check whether an integer constant comparison results in a value 10516 // of 'true' or 'false'. 10517 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10518 return AnalyzeImpConvsInComparison(S, E); 10519 } 10520 } 10521 10522 if (!T->hasUnsignedIntegerRepresentation()) { 10523 // We don't do anything special if this isn't an unsigned integral 10524 // comparison: we're only interested in integral comparisons, and 10525 // signed comparisons only happen in cases we don't care to warn about. 10526 return AnalyzeImpConvsInComparison(S, E); 10527 } 10528 10529 LHS = LHS->IgnoreParenImpCasts(); 10530 RHS = RHS->IgnoreParenImpCasts(); 10531 10532 if (!S.getLangOpts().CPlusPlus) { 10533 // Avoid warning about comparison of integers with different signs when 10534 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10535 // the type of `E`. 10536 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10537 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10538 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10539 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10540 } 10541 10542 // Check to see if one of the (unmodified) operands is of different 10543 // signedness. 10544 Expr *signedOperand, *unsignedOperand; 10545 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10546 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10547 "unsigned comparison between two signed integer expressions?"); 10548 signedOperand = LHS; 10549 unsignedOperand = RHS; 10550 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10551 signedOperand = RHS; 10552 unsignedOperand = LHS; 10553 } else { 10554 return AnalyzeImpConvsInComparison(S, E); 10555 } 10556 10557 // Otherwise, calculate the effective range of the signed operand. 10558 std::optional<IntRange> signedRange = 10559 TryGetExprRange(S.Context, signedOperand, S.isConstantEvaluatedContext(), 10560 /*Approximate=*/true); 10561 if (!signedRange) 10562 return; 10563 10564 // Go ahead and analyze implicit conversions in the operands. Note 10565 // that we skip the implicit conversions on both sides. 10566 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10567 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10568 10569 // If the signed range is non-negative, -Wsign-compare won't fire. 10570 if (signedRange->NonNegative) 10571 return; 10572 10573 // For (in)equality comparisons, if the unsigned operand is a 10574 // constant which cannot collide with a overflowed signed operand, 10575 // then reinterpreting the signed operand as unsigned will not 10576 // change the result of the comparison. 10577 if (E->isEqualityOp()) { 10578 unsigned comparisonWidth = S.Context.getIntWidth(T); 10579 std::optional<IntRange> unsignedRange = TryGetExprRange( 10580 S.Context, unsignedOperand, S.isConstantEvaluatedContext(), 10581 /*Approximate=*/true); 10582 if (!unsignedRange) 10583 return; 10584 10585 // We should never be unable to prove that the unsigned operand is 10586 // non-negative. 10587 assert(unsignedRange->NonNegative && "unsigned range includes negative?"); 10588 10589 if (unsignedRange->Width < comparisonWidth) 10590 return; 10591 } 10592 10593 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10594 S.PDiag(diag::warn_mixed_sign_comparison) 10595 << LHS->getType() << RHS->getType() 10596 << LHS->getSourceRange() << RHS->getSourceRange()); 10597 } 10598 10599 /// Analyzes an attempt to assign the given value to a bitfield. 10600 /// 10601 /// Returns true if there was something fishy about the attempt. 10602 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10603 SourceLocation InitLoc) { 10604 assert(Bitfield->isBitField()); 10605 if (Bitfield->isInvalidDecl()) 10606 return false; 10607 10608 // White-list bool bitfields. 10609 QualType BitfieldType = Bitfield->getType(); 10610 if (BitfieldType->isBooleanType()) 10611 return false; 10612 10613 if (BitfieldType->isEnumeralType()) { 10614 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10615 // If the underlying enum type was not explicitly specified as an unsigned 10616 // type and the enum contain only positive values, MSVC++ will cause an 10617 // inconsistency by storing this as a signed type. 10618 if (S.getLangOpts().CPlusPlus11 && 10619 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10620 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10621 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10622 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10623 << BitfieldEnumDecl; 10624 } 10625 } 10626 10627 // Ignore value- or type-dependent expressions. 10628 if (Bitfield->getBitWidth()->isValueDependent() || 10629 Bitfield->getBitWidth()->isTypeDependent() || 10630 Init->isValueDependent() || 10631 Init->isTypeDependent()) 10632 return false; 10633 10634 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10635 unsigned FieldWidth = Bitfield->getBitWidthValue(); 10636 10637 Expr::EvalResult Result; 10638 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10639 Expr::SE_AllowSideEffects)) { 10640 // The RHS is not constant. If the RHS has an enum type, make sure the 10641 // bitfield is wide enough to hold all the values of the enum without 10642 // truncation. 10643 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10644 EnumDecl *ED = EnumTy->getDecl(); 10645 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10646 10647 // Enum types are implicitly signed on Windows, so check if there are any 10648 // negative enumerators to see if the enum was intended to be signed or 10649 // not. 10650 bool SignedEnum = ED->getNumNegativeBits() > 0; 10651 10652 // Check for surprising sign changes when assigning enum values to a 10653 // bitfield of different signedness. If the bitfield is signed and we 10654 // have exactly the right number of bits to store this unsigned enum, 10655 // suggest changing the enum to an unsigned type. This typically happens 10656 // on Windows where unfixed enums always use an underlying type of 'int'. 10657 unsigned DiagID = 0; 10658 if (SignedEnum && !SignedBitfield) { 10659 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10660 } else if (SignedBitfield && !SignedEnum && 10661 ED->getNumPositiveBits() == FieldWidth) { 10662 DiagID = diag::warn_signed_bitfield_enum_conversion; 10663 } 10664 10665 if (DiagID) { 10666 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10667 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10668 SourceRange TypeRange = 10669 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10670 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10671 << SignedEnum << TypeRange; 10672 } 10673 10674 // Compute the required bitwidth. If the enum has negative values, we need 10675 // one more bit than the normal number of positive bits to represent the 10676 // sign bit. 10677 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10678 ED->getNumNegativeBits()) 10679 : ED->getNumPositiveBits(); 10680 10681 // Check the bitwidth. 10682 if (BitsNeeded > FieldWidth) { 10683 Expr *WidthExpr = Bitfield->getBitWidth(); 10684 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10685 << Bitfield << ED; 10686 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10687 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10688 } 10689 } 10690 10691 return false; 10692 } 10693 10694 llvm::APSInt Value = Result.Val.getInt(); 10695 10696 unsigned OriginalWidth = Value.getBitWidth(); 10697 10698 // In C, the macro 'true' from stdbool.h will evaluate to '1'; To reduce 10699 // false positives where the user is demonstrating they intend to use the 10700 // bit-field as a Boolean, check to see if the value is 1 and we're assigning 10701 // to a one-bit bit-field to see if the value came from a macro named 'true'. 10702 bool OneAssignedToOneBitBitfield = FieldWidth == 1 && Value == 1; 10703 if (OneAssignedToOneBitBitfield && !S.LangOpts.CPlusPlus) { 10704 SourceLocation MaybeMacroLoc = OriginalInit->getBeginLoc(); 10705 if (S.SourceMgr.isInSystemMacro(MaybeMacroLoc) && 10706 S.findMacroSpelling(MaybeMacroLoc, "true")) 10707 return false; 10708 } 10709 10710 if (!Value.isSigned() || Value.isNegative()) 10711 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10712 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10713 OriginalWidth = Value.getSignificantBits(); 10714 10715 if (OriginalWidth <= FieldWidth) 10716 return false; 10717 10718 // Compute the value which the bitfield will contain. 10719 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10720 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10721 10722 // Check whether the stored value is equal to the original value. 10723 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10724 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10725 return false; 10726 10727 std::string PrettyValue = toString(Value, 10); 10728 std::string PrettyTrunc = toString(TruncatedValue, 10); 10729 10730 S.Diag(InitLoc, OneAssignedToOneBitBitfield 10731 ? diag::warn_impcast_single_bit_bitield_precision_constant 10732 : diag::warn_impcast_bitfield_precision_constant) 10733 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10734 << Init->getSourceRange(); 10735 10736 return true; 10737 } 10738 10739 /// Analyze the given simple or compound assignment for warning-worthy 10740 /// operations. 10741 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10742 // Just recurse on the LHS. 10743 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10744 10745 // We want to recurse on the RHS as normal unless we're assigning to 10746 // a bitfield. 10747 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10748 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10749 E->getOperatorLoc())) { 10750 // Recurse, ignoring any implicit conversions on the RHS. 10751 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10752 E->getOperatorLoc()); 10753 } 10754 } 10755 10756 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10757 10758 // Diagnose implicitly sequentially-consistent atomic assignment. 10759 if (E->getLHS()->getType()->isAtomicType()) 10760 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10761 } 10762 10763 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10764 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10765 SourceLocation CContext, unsigned diag, 10766 bool pruneControlFlow = false) { 10767 if (pruneControlFlow) { 10768 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10769 S.PDiag(diag) 10770 << SourceType << T << E->getSourceRange() 10771 << SourceRange(CContext)); 10772 return; 10773 } 10774 S.Diag(E->getExprLoc(), diag) 10775 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10776 } 10777 10778 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10779 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10780 SourceLocation CContext, 10781 unsigned diag, bool pruneControlFlow = false) { 10782 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10783 } 10784 10785 /// Diagnose an implicit cast from a floating point value to an integer value. 10786 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10787 SourceLocation CContext) { 10788 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10789 const bool PruneWarnings = S.inTemplateInstantiation(); 10790 10791 Expr *InnerE = E->IgnoreParenImpCasts(); 10792 // We also want to warn on, e.g., "int i = -1.234" 10793 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10794 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10795 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10796 10797 const bool IsLiteral = 10798 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10799 10800 llvm::APFloat Value(0.0); 10801 bool IsConstant = 10802 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10803 if (!IsConstant) { 10804 if (S.ObjC().isSignedCharBool(T)) { 10805 return S.ObjC().adornBoolConversionDiagWithTernaryFixit( 10806 E, S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 10807 << E->getType()); 10808 } 10809 10810 return DiagnoseImpCast(S, E, T, CContext, 10811 diag::warn_impcast_float_integer, PruneWarnings); 10812 } 10813 10814 bool isExact = false; 10815 10816 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10817 T->hasUnsignedIntegerRepresentation()); 10818 llvm::APFloat::opStatus Result = Value.convertToInteger( 10819 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10820 10821 // FIXME: Force the precision of the source value down so we don't print 10822 // digits which are usually useless (we don't really care here if we 10823 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10824 // would automatically print the shortest representation, but it's a bit 10825 // tricky to implement. 10826 SmallString<16> PrettySourceValue; 10827 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10828 precision = (precision * 59 + 195) / 196; 10829 Value.toString(PrettySourceValue, precision); 10830 10831 if (S.ObjC().isSignedCharBool(T) && IntegerValue != 0 && IntegerValue != 1) { 10832 return S.ObjC().adornBoolConversionDiagWithTernaryFixit( 10833 E, S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 10834 << PrettySourceValue); 10835 } 10836 10837 if (Result == llvm::APFloat::opOK && isExact) { 10838 if (IsLiteral) return; 10839 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10840 PruneWarnings); 10841 } 10842 10843 // Conversion of a floating-point value to a non-bool integer where the 10844 // integral part cannot be represented by the integer type is undefined. 10845 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10846 return DiagnoseImpCast( 10847 S, E, T, CContext, 10848 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10849 : diag::warn_impcast_float_to_integer_out_of_range, 10850 PruneWarnings); 10851 10852 unsigned DiagID = 0; 10853 if (IsLiteral) { 10854 // Warn on floating point literal to integer. 10855 DiagID = diag::warn_impcast_literal_float_to_integer; 10856 } else if (IntegerValue == 0) { 10857 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10858 return DiagnoseImpCast(S, E, T, CContext, 10859 diag::warn_impcast_float_integer, PruneWarnings); 10860 } 10861 // Warn on non-zero to zero conversion. 10862 DiagID = diag::warn_impcast_float_to_integer_zero; 10863 } else { 10864 if (IntegerValue.isUnsigned()) { 10865 if (!IntegerValue.isMaxValue()) { 10866 return DiagnoseImpCast(S, E, T, CContext, 10867 diag::warn_impcast_float_integer, PruneWarnings); 10868 } 10869 } else { // IntegerValue.isSigned() 10870 if (!IntegerValue.isMaxSignedValue() && 10871 !IntegerValue.isMinSignedValue()) { 10872 return DiagnoseImpCast(S, E, T, CContext, 10873 diag::warn_impcast_float_integer, PruneWarnings); 10874 } 10875 } 10876 // Warn on evaluatable floating point expression to integer conversion. 10877 DiagID = diag::warn_impcast_float_to_integer; 10878 } 10879 10880 SmallString<16> PrettyTargetValue; 10881 if (IsBool) 10882 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10883 else 10884 IntegerValue.toString(PrettyTargetValue); 10885 10886 if (PruneWarnings) { 10887 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10888 S.PDiag(DiagID) 10889 << E->getType() << T.getUnqualifiedType() 10890 << PrettySourceValue << PrettyTargetValue 10891 << E->getSourceRange() << SourceRange(CContext)); 10892 } else { 10893 S.Diag(E->getExprLoc(), DiagID) 10894 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10895 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10896 } 10897 } 10898 10899 /// Analyze the given compound assignment for the possible losing of 10900 /// floating-point precision. 10901 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10902 assert(isa<CompoundAssignOperator>(E) && 10903 "Must be compound assignment operation"); 10904 // Recurse on the LHS and RHS in here 10905 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10906 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10907 10908 if (E->getLHS()->getType()->isAtomicType()) 10909 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10910 10911 // Now check the outermost expression 10912 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10913 const auto *RBT = cast<CompoundAssignOperator>(E) 10914 ->getComputationResultType() 10915 ->getAs<BuiltinType>(); 10916 10917 // The below checks assume source is floating point. 10918 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10919 10920 // If source is floating point but target is an integer. 10921 if (ResultBT->isInteger()) 10922 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 10923 E->getExprLoc(), diag::warn_impcast_float_integer); 10924 10925 if (!ResultBT->isFloatingPoint()) 10926 return; 10927 10928 // If both source and target are floating points, warn about losing precision. 10929 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 10930 QualType(ResultBT, 0), QualType(RBT, 0)); 10931 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10932 // warn about dropping FP rank. 10933 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10934 diag::warn_impcast_float_result_precision); 10935 } 10936 10937 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10938 IntRange Range) { 10939 if (!Range.Width) return "0"; 10940 10941 llvm::APSInt ValueInRange = Value; 10942 ValueInRange.setIsSigned(!Range.NonNegative); 10943 ValueInRange = ValueInRange.trunc(Range.Width); 10944 return toString(ValueInRange, 10); 10945 } 10946 10947 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10948 if (!isa<ImplicitCastExpr>(Ex)) 10949 return false; 10950 10951 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10952 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10953 const Type *Source = 10954 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10955 if (Target->isDependentType()) 10956 return false; 10957 10958 const BuiltinType *FloatCandidateBT = 10959 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10960 const Type *BoolCandidateType = ToBool ? Target : Source; 10961 10962 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10963 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10964 } 10965 10966 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10967 SourceLocation CC) { 10968 unsigned NumArgs = TheCall->getNumArgs(); 10969 for (unsigned i = 0; i < NumArgs; ++i) { 10970 Expr *CurrA = TheCall->getArg(i); 10971 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10972 continue; 10973 10974 bool IsSwapped = ((i > 0) && 10975 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10976 IsSwapped |= ((i < (NumArgs - 1)) && 10977 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10978 if (IsSwapped) { 10979 // Warn on this floating-point to bool conversion. 10980 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10981 CurrA->getType(), CC, 10982 diag::warn_impcast_floating_point_to_bool); 10983 } 10984 } 10985 } 10986 10987 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10988 SourceLocation CC) { 10989 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10990 E->getExprLoc())) 10991 return; 10992 10993 // Don't warn on functions which have return type nullptr_t. 10994 if (isa<CallExpr>(E)) 10995 return; 10996 10997 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10998 const Expr *NewE = E->IgnoreParenImpCasts(); 10999 bool IsGNUNullExpr = isa<GNUNullExpr>(NewE); 11000 bool HasNullPtrType = NewE->getType()->isNullPtrType(); 11001 if (!IsGNUNullExpr && !HasNullPtrType) 11002 return; 11003 11004 // Return if target type is a safe conversion. 11005 if (T->isAnyPointerType() || T->isBlockPointerType() || 11006 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11007 return; 11008 11009 SourceLocation Loc = E->getSourceRange().getBegin(); 11010 11011 // Venture through the macro stacks to get to the source of macro arguments. 11012 // The new location is a better location than the complete location that was 11013 // passed in. 11014 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11015 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11016 11017 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11018 if (IsGNUNullExpr && Loc.isMacroID()) { 11019 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11020 Loc, S.SourceMgr, S.getLangOpts()); 11021 if (MacroName == "NULL") 11022 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11023 } 11024 11025 // Only warn if the null and context location are in the same macro expansion. 11026 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11027 return; 11028 11029 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11030 << HasNullPtrType << T << SourceRange(CC) 11031 << FixItHint::CreateReplacement(Loc, 11032 S.getFixItZeroLiteralForType(T, Loc)); 11033 } 11034 11035 // Helper function to filter out cases for constant width constant conversion. 11036 // Don't warn on char array initialization or for non-decimal values. 11037 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11038 SourceLocation CC) { 11039 // If initializing from a constant, and the constant starts with '0', 11040 // then it is a binary, octal, or hexadecimal. Allow these constants 11041 // to fill all the bits, even if there is a sign change. 11042 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11043 const char FirstLiteralCharacter = 11044 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11045 if (FirstLiteralCharacter == '0') 11046 return false; 11047 } 11048 11049 // If the CC location points to a '{', and the type is char, then assume 11050 // assume it is an array initialization. 11051 if (CC.isValid() && T->isCharType()) { 11052 const char FirstContextCharacter = 11053 S.getSourceManager().getCharacterData(CC)[0]; 11054 if (FirstContextCharacter == '{') 11055 return false; 11056 } 11057 11058 return true; 11059 } 11060 11061 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11062 const auto *IL = dyn_cast<IntegerLiteral>(E); 11063 if (!IL) { 11064 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11065 if (UO->getOpcode() == UO_Minus) 11066 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11067 } 11068 } 11069 11070 return IL; 11071 } 11072 11073 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11074 E = E->IgnoreParenImpCasts(); 11075 SourceLocation ExprLoc = E->getExprLoc(); 11076 11077 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11078 BinaryOperator::Opcode Opc = BO->getOpcode(); 11079 Expr::EvalResult Result; 11080 // Do not diagnose unsigned shifts. 11081 if (Opc == BO_Shl) { 11082 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11083 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11084 if (LHS && LHS->getValue() == 0) 11085 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11086 else if (!E->isValueDependent() && LHS && RHS && 11087 RHS->getValue().isNonNegative() && 11088 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11089 S.Diag(ExprLoc, diag::warn_left_shift_always) 11090 << (Result.Val.getInt() != 0); 11091 else if (E->getType()->isSignedIntegerType()) 11092 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11093 } 11094 } 11095 11096 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11097 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11098 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11099 if (!LHS || !RHS) 11100 return; 11101 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11102 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11103 // Do not diagnose common idioms. 11104 return; 11105 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11106 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11107 } 11108 } 11109 11110 void Sema::CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC, 11111 bool *ICContext, bool IsListInit) { 11112 if (E->isTypeDependent() || E->isValueDependent()) return; 11113 11114 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr(); 11115 const Type *Target = Context.getCanonicalType(T).getTypePtr(); 11116 if (Source == Target) return; 11117 if (Target->isDependentType()) return; 11118 11119 // If the conversion context location is invalid don't complain. We also 11120 // don't want to emit a warning if the issue occurs from the expansion of 11121 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11122 // delay this check as long as possible. Once we detect we are in that 11123 // scenario, we just return. 11124 if (CC.isInvalid()) 11125 return; 11126 11127 if (Source->isAtomicType()) 11128 Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11129 11130 // Diagnose implicit casts to bool. 11131 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11132 if (isa<StringLiteral>(E)) 11133 // Warn on string literal to bool. Checks for string literals in logical 11134 // and expressions, for instance, assert(0 && "error here"), are 11135 // prevented by a check in AnalyzeImplicitConversions(). 11136 return DiagnoseImpCast(*this, E, T, CC, 11137 diag::warn_impcast_string_literal_to_bool); 11138 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11139 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11140 // This covers the literal expressions that evaluate to Objective-C 11141 // objects. 11142 return DiagnoseImpCast(*this, E, T, CC, 11143 diag::warn_impcast_objective_c_literal_to_bool); 11144 } 11145 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11146 // Warn on pointer to bool conversion that is always true. 11147 DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11148 SourceRange(CC)); 11149 } 11150 } 11151 11152 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11153 // is a typedef for signed char (macOS), then that constant value has to be 1 11154 // or 0. 11155 if (ObjC().isSignedCharBool(T) && Source->isIntegralType(Context)) { 11156 Expr::EvalResult Result; 11157 if (E->EvaluateAsInt(Result, getASTContext(), Expr::SE_AllowSideEffects)) { 11158 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11159 ObjC().adornBoolConversionDiagWithTernaryFixit( 11160 E, Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11161 << toString(Result.Val.getInt(), 10)); 11162 } 11163 return; 11164 } 11165 } 11166 11167 // Check implicit casts from Objective-C collection literals to specialized 11168 // collection types, e.g., NSArray<NSString *> *. 11169 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11170 ObjC().checkArrayLiteral(QualType(Target, 0), ArrayLiteral); 11171 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11172 ObjC().checkDictionaryLiteral(QualType(Target, 0), DictionaryLiteral); 11173 11174 // Strip vector types. 11175 if (isa<VectorType>(Source)) { 11176 if (Target->isSveVLSBuiltinType() && 11177 (Context.areCompatibleSveTypes(QualType(Target, 0), 11178 QualType(Source, 0)) || 11179 Context.areLaxCompatibleSveTypes(QualType(Target, 0), 11180 QualType(Source, 0)))) 11181 return; 11182 11183 if (Target->isRVVVLSBuiltinType() && 11184 (Context.areCompatibleRVVTypes(QualType(Target, 0), 11185 QualType(Source, 0)) || 11186 Context.areLaxCompatibleRVVTypes(QualType(Target, 0), 11187 QualType(Source, 0)))) 11188 return; 11189 11190 if (!isa<VectorType>(Target)) { 11191 if (SourceMgr.isInSystemMacro(CC)) 11192 return; 11193 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_vector_scalar); 11194 } else if (getLangOpts().HLSL && 11195 Target->castAs<VectorType>()->getNumElements() < 11196 Source->castAs<VectorType>()->getNumElements()) { 11197 // Diagnose vector truncation but don't return. We may also want to 11198 // diagnose an element conversion. 11199 DiagnoseImpCast(*this, E, T, CC, 11200 diag::warn_hlsl_impcast_vector_truncation); 11201 } 11202 11203 // If the vector cast is cast between two vectors of the same size, it is 11204 // a bitcast, not a conversion, except under HLSL where it is a conversion. 11205 if (!getLangOpts().HLSL && 11206 Context.getTypeSize(Source) == Context.getTypeSize(Target)) 11207 return; 11208 11209 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11210 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11211 } 11212 if (auto VecTy = dyn_cast<VectorType>(Target)) 11213 Target = VecTy->getElementType().getTypePtr(); 11214 11215 // Strip complex types. 11216 if (isa<ComplexType>(Source)) { 11217 if (!isa<ComplexType>(Target)) { 11218 if (SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11219 return; 11220 11221 return DiagnoseImpCast(*this, E, T, CC, 11222 getLangOpts().CPlusPlus 11223 ? diag::err_impcast_complex_scalar 11224 : diag::warn_impcast_complex_scalar); 11225 } 11226 11227 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11228 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11229 } 11230 11231 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11232 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11233 11234 // Strip SVE vector types 11235 if (SourceBT && SourceBT->isSveVLSBuiltinType()) { 11236 // Need the original target type for vector type checks 11237 const Type *OriginalTarget = Context.getCanonicalType(T).getTypePtr(); 11238 // Handle conversion from scalable to fixed when msve-vector-bits is 11239 // specified 11240 if (Context.areCompatibleSveTypes(QualType(OriginalTarget, 0), 11241 QualType(Source, 0)) || 11242 Context.areLaxCompatibleSveTypes(QualType(OriginalTarget, 0), 11243 QualType(Source, 0))) 11244 return; 11245 11246 // If the vector cast is cast between two vectors of the same size, it is 11247 // a bitcast, not a conversion. 11248 if (Context.getTypeSize(Source) == Context.getTypeSize(Target)) 11249 return; 11250 11251 Source = SourceBT->getSveEltType(Context).getTypePtr(); 11252 } 11253 11254 if (TargetBT && TargetBT->isSveVLSBuiltinType()) 11255 Target = TargetBT->getSveEltType(Context).getTypePtr(); 11256 11257 // If the source is floating point... 11258 if (SourceBT && SourceBT->isFloatingPoint()) { 11259 // ...and the target is floating point... 11260 if (TargetBT && TargetBT->isFloatingPoint()) { 11261 // ...then warn if we're dropping FP rank. 11262 11263 int Order = getASTContext().getFloatingTypeSemanticOrder( 11264 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11265 if (Order > 0) { 11266 // Don't warn about float constants that are precisely 11267 // representable in the target type. 11268 Expr::EvalResult result; 11269 if (E->EvaluateAsRValue(result, Context)) { 11270 // Value might be a float, a float vector, or a float complex. 11271 if (IsSameFloatAfterCast( 11272 result.Val, 11273 Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11274 Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11275 return; 11276 } 11277 11278 if (SourceMgr.isInSystemMacro(CC)) 11279 return; 11280 11281 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_float_precision); 11282 } 11283 // ... or possibly if we're increasing rank, too 11284 else if (Order < 0) { 11285 if (SourceMgr.isInSystemMacro(CC)) 11286 return; 11287 11288 DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_double_promotion); 11289 } 11290 return; 11291 } 11292 11293 // If the target is integral, always warn. 11294 if (TargetBT && TargetBT->isInteger()) { 11295 if (SourceMgr.isInSystemMacro(CC)) 11296 return; 11297 11298 DiagnoseFloatingImpCast(*this, E, T, CC); 11299 } 11300 11301 // Detect the case where a call result is converted from floating-point to 11302 // to bool, and the final argument to the call is converted from bool, to 11303 // discover this typo: 11304 // 11305 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11306 // 11307 // FIXME: This is an incredibly special case; is there some more general 11308 // way to detect this class of misplaced-parentheses bug? 11309 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11310 // Check last argument of function call to see if it is an 11311 // implicit cast from a type matching the type the result 11312 // is being cast to. 11313 CallExpr *CEx = cast<CallExpr>(E); 11314 if (unsigned NumArgs = CEx->getNumArgs()) { 11315 Expr *LastA = CEx->getArg(NumArgs - 1); 11316 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11317 if (isa<ImplicitCastExpr>(LastA) && 11318 InnerE->getType()->isBooleanType()) { 11319 // Warn on this floating-point to bool conversion 11320 DiagnoseImpCast(*this, E, T, CC, 11321 diag::warn_impcast_floating_point_to_bool); 11322 } 11323 } 11324 } 11325 return; 11326 } 11327 11328 // Valid casts involving fixed point types should be accounted for here. 11329 if (Source->isFixedPointType()) { 11330 if (Target->isUnsaturatedFixedPointType()) { 11331 Expr::EvalResult Result; 11332 if (E->EvaluateAsFixedPoint(Result, Context, Expr::SE_AllowSideEffects, 11333 isConstantEvaluatedContext())) { 11334 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 11335 llvm::APFixedPoint MaxVal = Context.getFixedPointMax(T); 11336 llvm::APFixedPoint MinVal = Context.getFixedPointMin(T); 11337 if (Value > MaxVal || Value < MinVal) { 11338 DiagRuntimeBehavior(E->getExprLoc(), E, 11339 PDiag(diag::warn_impcast_fixed_point_range) 11340 << Value.toString() << T 11341 << E->getSourceRange() 11342 << clang::SourceRange(CC)); 11343 return; 11344 } 11345 } 11346 } else if (Target->isIntegerType()) { 11347 Expr::EvalResult Result; 11348 if (!isConstantEvaluatedContext() && 11349 E->EvaluateAsFixedPoint(Result, Context, Expr::SE_AllowSideEffects)) { 11350 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 11351 11352 bool Overflowed; 11353 llvm::APSInt IntResult = FXResult.convertToInt( 11354 Context.getIntWidth(T), Target->isSignedIntegerOrEnumerationType(), 11355 &Overflowed); 11356 11357 if (Overflowed) { 11358 DiagRuntimeBehavior(E->getExprLoc(), E, 11359 PDiag(diag::warn_impcast_fixed_point_range) 11360 << FXResult.toString() << T 11361 << E->getSourceRange() 11362 << clang::SourceRange(CC)); 11363 return; 11364 } 11365 } 11366 } 11367 } else if (Target->isUnsaturatedFixedPointType()) { 11368 if (Source->isIntegerType()) { 11369 Expr::EvalResult Result; 11370 if (!isConstantEvaluatedContext() && 11371 E->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) { 11372 llvm::APSInt Value = Result.Val.getInt(); 11373 11374 bool Overflowed; 11375 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 11376 Value, Context.getFixedPointSemantics(T), &Overflowed); 11377 11378 if (Overflowed) { 11379 DiagRuntimeBehavior(E->getExprLoc(), E, 11380 PDiag(diag::warn_impcast_fixed_point_range) 11381 << toString(Value, /*Radix=*/10) << T 11382 << E->getSourceRange() 11383 << clang::SourceRange(CC)); 11384 return; 11385 } 11386 } 11387 } 11388 } 11389 11390 // If we are casting an integer type to a floating point type without 11391 // initialization-list syntax, we might lose accuracy if the floating 11392 // point type has a narrower significand than the integer type. 11393 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11394 TargetBT->isFloatingType() && !IsListInit) { 11395 // Determine the number of precision bits in the source integer type. 11396 std::optional<IntRange> SourceRange = 11397 TryGetExprRange(Context, E, isConstantEvaluatedContext(), 11398 /*Approximate=*/true); 11399 if (!SourceRange) 11400 return; 11401 unsigned int SourcePrecision = SourceRange->Width; 11402 11403 // Determine the number of precision bits in the 11404 // target floating point type. 11405 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11406 Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11407 11408 if (SourcePrecision > 0 && TargetPrecision > 0 && 11409 SourcePrecision > TargetPrecision) { 11410 11411 if (std::optional<llvm::APSInt> SourceInt = 11412 E->getIntegerConstantExpr(Context)) { 11413 // If the source integer is a constant, convert it to the target 11414 // floating point type. Issue a warning if the value changes 11415 // during the whole conversion. 11416 llvm::APFloat TargetFloatValue( 11417 Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11418 llvm::APFloat::opStatus ConversionStatus = 11419 TargetFloatValue.convertFromAPInt( 11420 *SourceInt, SourceBT->isSignedInteger(), 11421 llvm::APFloat::rmNearestTiesToEven); 11422 11423 if (ConversionStatus != llvm::APFloat::opOK) { 11424 SmallString<32> PrettySourceValue; 11425 SourceInt->toString(PrettySourceValue, 10); 11426 SmallString<32> PrettyTargetValue; 11427 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11428 11429 DiagRuntimeBehavior( 11430 E->getExprLoc(), E, 11431 PDiag(diag::warn_impcast_integer_float_precision_constant) 11432 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11433 << E->getSourceRange() << clang::SourceRange(CC)); 11434 } 11435 } else { 11436 // Otherwise, the implicit conversion may lose precision. 11437 DiagnoseImpCast(*this, E, T, CC, 11438 diag::warn_impcast_integer_float_precision); 11439 } 11440 } 11441 } 11442 11443 DiagnoseNullConversion(*this, E, T, CC); 11444 11445 DiscardMisalignedMemberAddress(Target, E); 11446 11447 if (Target->isBooleanType()) 11448 DiagnoseIntInBoolContext(*this, E); 11449 11450 if (!Source->isIntegerType() || !Target->isIntegerType()) 11451 return; 11452 11453 // TODO: remove this early return once the false positives for constant->bool 11454 // in templates, macros, etc, are reduced or removed. 11455 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11456 return; 11457 11458 if (ObjC().isSignedCharBool(T) && !Source->isCharType() && 11459 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11460 return ObjC().adornBoolConversionDiagWithTernaryFixit( 11461 E, Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11462 << E->getType()); 11463 } 11464 std::optional<IntRange> LikelySourceRange = TryGetExprRange( 11465 Context, E, isConstantEvaluatedContext(), /*Approximate=*/true); 11466 if (!LikelySourceRange) 11467 return; 11468 11469 IntRange SourceTypeRange = 11470 IntRange::forTargetOfCanonicalType(Context, Source); 11471 IntRange TargetRange = IntRange::forTargetOfCanonicalType(Context, Target); 11472 11473 if (LikelySourceRange->Width > TargetRange.Width) { 11474 // If the source is a constant, use a default-on diagnostic. 11475 // TODO: this should happen for bitfield stores, too. 11476 Expr::EvalResult Result; 11477 if (E->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects, 11478 isConstantEvaluatedContext())) { 11479 llvm::APSInt Value(32); 11480 Value = Result.Val.getInt(); 11481 11482 if (SourceMgr.isInSystemMacro(CC)) 11483 return; 11484 11485 std::string PrettySourceValue = toString(Value, 10); 11486 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11487 11488 DiagRuntimeBehavior(E->getExprLoc(), E, 11489 PDiag(diag::warn_impcast_integer_precision_constant) 11490 << PrettySourceValue << PrettyTargetValue 11491 << E->getType() << T << E->getSourceRange() 11492 << SourceRange(CC)); 11493 return; 11494 } 11495 11496 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11497 if (SourceMgr.isInSystemMacro(CC)) 11498 return; 11499 11500 if (TargetRange.Width == 32 && Context.getIntWidth(E->getType()) == 64) 11501 return DiagnoseImpCast(*this, E, T, CC, diag::warn_impcast_integer_64_32, 11502 /* pruneControlFlow */ true); 11503 return DiagnoseImpCast(*this, E, T, CC, 11504 diag::warn_impcast_integer_precision); 11505 } 11506 11507 if (TargetRange.Width > SourceTypeRange.Width) { 11508 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11509 if (UO->getOpcode() == UO_Minus) 11510 if (Source->isUnsignedIntegerType()) { 11511 if (Target->isUnsignedIntegerType()) 11512 return DiagnoseImpCast(*this, E, T, CC, 11513 diag::warn_impcast_high_order_zero_bits); 11514 if (Target->isSignedIntegerType()) 11515 return DiagnoseImpCast(*this, E, T, CC, 11516 diag::warn_impcast_nonnegative_result); 11517 } 11518 } 11519 11520 if (TargetRange.Width == LikelySourceRange->Width && 11521 !TargetRange.NonNegative && LikelySourceRange->NonNegative && 11522 Source->isSignedIntegerType()) { 11523 // Warn when doing a signed to signed conversion, warn if the positive 11524 // source value is exactly the width of the target type, which will 11525 // cause a negative value to be stored. 11526 11527 Expr::EvalResult Result; 11528 if (E->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects) && 11529 !SourceMgr.isInSystemMacro(CC)) { 11530 llvm::APSInt Value = Result.Val.getInt(); 11531 if (isSameWidthConstantConversion(*this, E, T, CC)) { 11532 std::string PrettySourceValue = toString(Value, 10); 11533 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11534 11535 Diag(E->getExprLoc(), 11536 PDiag(diag::warn_impcast_integer_precision_constant) 11537 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11538 << E->getSourceRange() << SourceRange(CC)); 11539 return; 11540 } 11541 } 11542 11543 // Fall through for non-constants to give a sign conversion warning. 11544 } 11545 11546 if ((!isa<EnumType>(Target) || !isa<EnumType>(Source)) && 11547 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) || 11548 (!TargetRange.NonNegative && LikelySourceRange->NonNegative && 11549 LikelySourceRange->Width == TargetRange.Width))) { 11550 if (SourceMgr.isInSystemMacro(CC)) 11551 return; 11552 11553 if (SourceBT && SourceBT->isInteger() && TargetBT && 11554 TargetBT->isInteger() && 11555 Source->isSignedIntegerType() == Target->isSignedIntegerType()) { 11556 return; 11557 } 11558 11559 unsigned DiagID = diag::warn_impcast_integer_sign; 11560 11561 // Traditionally, gcc has warned about this under -Wsign-compare. 11562 // We also want to warn about it in -Wconversion. 11563 // So if -Wconversion is off, use a completely identical diagnostic 11564 // in the sign-compare group. 11565 // The conditional-checking code will 11566 if (ICContext) { 11567 DiagID = diag::warn_impcast_integer_sign_conditional; 11568 *ICContext = true; 11569 } 11570 11571 return DiagnoseImpCast(*this, E, T, CC, DiagID); 11572 } 11573 11574 // Diagnose conversions between different enumeration types. 11575 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11576 // type, to give us better diagnostics. 11577 QualType SourceType = E->getEnumCoercedType(Context); 11578 Source = Context.getCanonicalType(SourceType).getTypePtr(); 11579 11580 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11581 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11582 if (SourceEnum->getDecl()->hasNameForLinkage() && 11583 TargetEnum->getDecl()->hasNameForLinkage() && 11584 SourceEnum != TargetEnum) { 11585 if (SourceMgr.isInSystemMacro(CC)) 11586 return; 11587 11588 return DiagnoseImpCast(*this, E, SourceType, T, CC, 11589 diag::warn_impcast_different_enum_types); 11590 } 11591 } 11592 11593 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 11594 SourceLocation CC, QualType T); 11595 11596 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11597 SourceLocation CC, bool &ICContext) { 11598 E = E->IgnoreParenImpCasts(); 11599 // Diagnose incomplete type for second or third operand in C. 11600 if (!S.getLangOpts().CPlusPlus && E->getType()->isRecordType()) 11601 S.RequireCompleteExprType(E, diag::err_incomplete_type); 11602 11603 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 11604 return CheckConditionalOperator(S, CO, CC, T); 11605 11606 AnalyzeImplicitConversions(S, E, CC); 11607 if (E->getType() != T) 11608 return S.CheckImplicitConversion(E, T, CC, &ICContext); 11609 } 11610 11611 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 11612 SourceLocation CC, QualType T) { 11613 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11614 11615 Expr *TrueExpr = E->getTrueExpr(); 11616 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 11617 TrueExpr = BCO->getCommon(); 11618 11619 bool Suspicious = false; 11620 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 11621 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11622 11623 if (T->isBooleanType()) 11624 DiagnoseIntInBoolContext(S, E); 11625 11626 // If -Wconversion would have warned about either of the candidates 11627 // for a signedness conversion to the context type... 11628 if (!Suspicious) return; 11629 11630 // ...but it's currently ignored... 11631 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11632 return; 11633 11634 // ...then check whether it would have warned about either of the 11635 // candidates for a signedness conversion to the condition type. 11636 if (E->getType() == T) return; 11637 11638 Suspicious = false; 11639 S.CheckImplicitConversion(TrueExpr->IgnoreParenImpCasts(), E->getType(), CC, 11640 &Suspicious); 11641 if (!Suspicious) 11642 S.CheckImplicitConversion(E->getFalseExpr()->IgnoreParenImpCasts(), 11643 E->getType(), CC, &Suspicious); 11644 } 11645 11646 /// Check conversion of given expression to boolean. 11647 /// Input argument E is a logical expression. 11648 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11649 // Run the bool-like conversion checks only for C since there bools are 11650 // still not used as the return type from "boolean" operators or as the input 11651 // type for conditional operators. 11652 if (S.getLangOpts().CPlusPlus) 11653 return; 11654 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11655 return; 11656 S.CheckImplicitConversion(E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11657 } 11658 11659 namespace { 11660 struct AnalyzeImplicitConversionsWorkItem { 11661 Expr *E; 11662 SourceLocation CC; 11663 bool IsListInit; 11664 }; 11665 } 11666 11667 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 11668 /// that should be visited are added to WorkList. 11669 static void AnalyzeImplicitConversions( 11670 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 11671 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 11672 Expr *OrigE = Item.E; 11673 SourceLocation CC = Item.CC; 11674 11675 QualType T = OrigE->getType(); 11676 Expr *E = OrigE->IgnoreParenImpCasts(); 11677 11678 // Propagate whether we are in a C++ list initialization expression. 11679 // If so, we do not issue warnings for implicit int-float conversion 11680 // precision loss, because C++11 narrowing already handles it. 11681 bool IsListInit = Item.IsListInit || 11682 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 11683 11684 if (E->isTypeDependent() || E->isValueDependent()) 11685 return; 11686 11687 Expr *SourceExpr = E; 11688 // Examine, but don't traverse into the source expression of an 11689 // OpaqueValueExpr, since it may have multiple parents and we don't want to 11690 // emit duplicate diagnostics. Its fine to examine the form or attempt to 11691 // evaluate it in the context of checking the specific conversion to T though. 11692 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11693 if (auto *Src = OVE->getSourceExpr()) 11694 SourceExpr = Src; 11695 11696 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 11697 if (UO->getOpcode() == UO_Not && 11698 UO->getSubExpr()->isKnownToHaveBooleanValue()) 11699 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 11700 << OrigE->getSourceRange() << T->isBooleanType() 11701 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 11702 11703 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) 11704 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && 11705 BO->getLHS()->isKnownToHaveBooleanValue() && 11706 BO->getRHS()->isKnownToHaveBooleanValue() && 11707 BO->getLHS()->HasSideEffects(S.Context) && 11708 BO->getRHS()->HasSideEffects(S.Context)) { 11709 SourceManager &SM = S.getSourceManager(); 11710 const LangOptions &LO = S.getLangOpts(); 11711 SourceLocation BLoc = BO->getOperatorLoc(); 11712 SourceLocation ELoc = Lexer::getLocForEndOfToken(BLoc, 0, SM, LO); 11713 StringRef SR = clang::Lexer::getSourceText( 11714 clang::CharSourceRange::getTokenRange(BLoc, ELoc), SM, LO); 11715 // To reduce false positives, only issue the diagnostic if the operator 11716 // is explicitly spelled as a punctuator. This suppresses the diagnostic 11717 // when using 'bitand' or 'bitor' either as keywords in C++ or as macros 11718 // in C, along with other macro spellings the user might invent. 11719 if (SR.str() == "&" || SR.str() == "|") { 11720 11721 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) 11722 << (BO->getOpcode() == BO_And ? "&" : "|") 11723 << OrigE->getSourceRange() 11724 << FixItHint::CreateReplacement( 11725 BO->getOperatorLoc(), 11726 (BO->getOpcode() == BO_And ? "&&" : "||")); 11727 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int); 11728 } 11729 } 11730 11731 // For conditional operators, we analyze the arguments as if they 11732 // were being fed directly into the output. 11733 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 11734 CheckConditionalOperator(S, CO, CC, T); 11735 return; 11736 } 11737 11738 // Check implicit argument conversions for function calls. 11739 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 11740 CheckImplicitArgumentConversions(S, Call, CC); 11741 11742 // Go ahead and check any implicit conversions we might have skipped. 11743 // The non-canonical typecheck is just an optimization; 11744 // CheckImplicitConversion will filter out dead implicit conversions. 11745 if (SourceExpr->getType() != T) 11746 S.CheckImplicitConversion(SourceExpr, T, CC, nullptr, IsListInit); 11747 11748 // Now continue drilling into this expression. 11749 11750 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11751 // The bound subexpressions in a PseudoObjectExpr are not reachable 11752 // as transitive children. 11753 // FIXME: Use a more uniform representation for this. 11754 for (auto *SE : POE->semantics()) 11755 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11756 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 11757 } 11758 11759 // Skip past explicit casts. 11760 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11761 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11762 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11763 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11764 WorkList.push_back({E, CC, IsListInit}); 11765 return; 11766 } 11767 11768 if (auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) { 11769 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit}); 11770 // The base expression is only used to initialize the parameter for 11771 // arguments to `inout` parameters, so we only traverse down the base 11772 // expression for `inout` cases. 11773 if (OutArgE->isInOut()) 11774 WorkList.push_back( 11775 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit}); 11776 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit}); 11777 return; 11778 } 11779 11780 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11781 // Do a somewhat different check with comparison operators. 11782 if (BO->isComparisonOp()) 11783 return AnalyzeComparison(S, BO); 11784 11785 // And with simple assignments. 11786 if (BO->getOpcode() == BO_Assign) 11787 return AnalyzeAssignment(S, BO); 11788 // And with compound assignments. 11789 if (BO->isAssignmentOp()) 11790 return AnalyzeCompoundAssignment(S, BO); 11791 } 11792 11793 // These break the otherwise-useful invariant below. Fortunately, 11794 // we don't really need to recurse into them, because any internal 11795 // expressions should have been analyzed already when they were 11796 // built into statements. 11797 if (isa<StmtExpr>(E)) return; 11798 11799 // Don't descend into unevaluated contexts. 11800 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11801 11802 // Now just recurse over the expression's children. 11803 CC = E->getExprLoc(); 11804 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11805 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11806 for (Stmt *SubStmt : E->children()) { 11807 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11808 if (!ChildExpr) 11809 continue; 11810 11811 if (auto *CSE = dyn_cast<CoroutineSuspendExpr>(E)) 11812 if (ChildExpr == CSE->getOperand()) 11813 // Do not recurse over a CoroutineSuspendExpr's operand. 11814 // The operand is also a subexpression of getCommonExpr(), and 11815 // recursing into it directly would produce duplicate diagnostics. 11816 continue; 11817 11818 if (IsLogicalAndOperator && 11819 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11820 // Ignore checking string literals that are in logical and operators. 11821 // This is a common pattern for asserts. 11822 continue; 11823 WorkList.push_back({ChildExpr, CC, IsListInit}); 11824 } 11825 11826 if (BO && BO->isLogicalOp()) { 11827 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11828 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11829 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11830 11831 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11832 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11833 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11834 } 11835 11836 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11837 if (U->getOpcode() == UO_LNot) { 11838 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11839 } else if (U->getOpcode() != UO_AddrOf) { 11840 if (U->getSubExpr()->getType()->isAtomicType()) 11841 S.Diag(U->getSubExpr()->getBeginLoc(), 11842 diag::warn_atomic_implicit_seq_cst); 11843 } 11844 } 11845 } 11846 11847 /// AnalyzeImplicitConversions - Find and report any interesting 11848 /// implicit conversions in the given expression. There are a couple 11849 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11850 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 11851 bool IsListInit/*= false*/) { 11852 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 11853 WorkList.push_back({OrigE, CC, IsListInit}); 11854 while (!WorkList.empty()) 11855 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 11856 } 11857 11858 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11859 // Returns true when emitting a warning about taking the address of a reference. 11860 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11861 const PartialDiagnostic &PD) { 11862 E = E->IgnoreParenImpCasts(); 11863 11864 const FunctionDecl *FD = nullptr; 11865 11866 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11867 if (!DRE->getDecl()->getType()->isReferenceType()) 11868 return false; 11869 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11870 if (!M->getMemberDecl()->getType()->isReferenceType()) 11871 return false; 11872 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11873 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11874 return false; 11875 FD = Call->getDirectCallee(); 11876 } else { 11877 return false; 11878 } 11879 11880 SemaRef.Diag(E->getExprLoc(), PD); 11881 11882 // If possible, point to location of function. 11883 if (FD) { 11884 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11885 } 11886 11887 return true; 11888 } 11889 11890 // Returns true if the SourceLocation is expanded from any macro body. 11891 // Returns false if the SourceLocation is invalid, is from not in a macro 11892 // expansion, or is from expanded from a top-level macro argument. 11893 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11894 if (Loc.isInvalid()) 11895 return false; 11896 11897 while (Loc.isMacroID()) { 11898 if (SM.isMacroBodyExpansion(Loc)) 11899 return true; 11900 Loc = SM.getImmediateMacroCallerLoc(Loc); 11901 } 11902 11903 return false; 11904 } 11905 11906 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11907 Expr::NullPointerConstantKind NullKind, 11908 bool IsEqual, SourceRange Range) { 11909 if (!E) 11910 return; 11911 11912 // Don't warn inside macros. 11913 if (E->getExprLoc().isMacroID()) { 11914 const SourceManager &SM = getSourceManager(); 11915 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11916 IsInAnyMacroBody(SM, Range.getBegin())) 11917 return; 11918 } 11919 E = E->IgnoreImpCasts(); 11920 11921 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11922 11923 if (isa<CXXThisExpr>(E)) { 11924 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11925 : diag::warn_this_bool_conversion; 11926 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11927 return; 11928 } 11929 11930 bool IsAddressOf = false; 11931 11932 if (auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) { 11933 if (UO->getOpcode() != UO_AddrOf) 11934 return; 11935 IsAddressOf = true; 11936 E = UO->getSubExpr(); 11937 } 11938 11939 if (IsAddressOf) { 11940 unsigned DiagID = IsCompare 11941 ? diag::warn_address_of_reference_null_compare 11942 : diag::warn_address_of_reference_bool_conversion; 11943 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11944 << IsEqual; 11945 if (CheckForReference(*this, E, PD)) { 11946 return; 11947 } 11948 } 11949 11950 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11951 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11952 std::string Str; 11953 llvm::raw_string_ostream S(Str); 11954 E->printPretty(S, nullptr, getPrintingPolicy()); 11955 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11956 : diag::warn_cast_nonnull_to_bool; 11957 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11958 << E->getSourceRange() << Range << IsEqual; 11959 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11960 }; 11961 11962 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11963 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11964 if (auto *Callee = Call->getDirectCallee()) { 11965 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11966 ComplainAboutNonnullParamOrCall(A); 11967 return; 11968 } 11969 } 11970 } 11971 11972 // Complain if we are converting a lambda expression to a boolean value 11973 // outside of instantiation. 11974 if (!inTemplateInstantiation()) { 11975 if (const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) { 11976 if (const auto *MRecordDecl = MCallExpr->getRecordDecl(); 11977 MRecordDecl && MRecordDecl->isLambda()) { 11978 Diag(E->getExprLoc(), diag::warn_impcast_pointer_to_bool) 11979 << /*LambdaPointerConversionOperatorType=*/3 11980 << MRecordDecl->getSourceRange() << Range << IsEqual; 11981 return; 11982 } 11983 } 11984 } 11985 11986 // Expect to find a single Decl. Skip anything more complicated. 11987 ValueDecl *D = nullptr; 11988 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11989 D = R->getDecl(); 11990 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11991 D = M->getMemberDecl(); 11992 } 11993 11994 // Weak Decls can be null. 11995 if (!D || D->isWeak()) 11996 return; 11997 11998 // Check for parameter decl with nonnull attribute 11999 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12000 if (getCurFunction() && 12001 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12002 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12003 ComplainAboutNonnullParamOrCall(A); 12004 return; 12005 } 12006 12007 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12008 // Skip function template not specialized yet. 12009 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12010 return; 12011 auto ParamIter = llvm::find(FD->parameters(), PV); 12012 assert(ParamIter != FD->param_end()); 12013 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12014 12015 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12016 if (!NonNull->args_size()) { 12017 ComplainAboutNonnullParamOrCall(NonNull); 12018 return; 12019 } 12020 12021 for (const ParamIdx &ArgNo : NonNull->args()) { 12022 if (ArgNo.getASTIndex() == ParamNo) { 12023 ComplainAboutNonnullParamOrCall(NonNull); 12024 return; 12025 } 12026 } 12027 } 12028 } 12029 } 12030 } 12031 12032 QualType T = D->getType(); 12033 const bool IsArray = T->isArrayType(); 12034 const bool IsFunction = T->isFunctionType(); 12035 12036 // Address of function is used to silence the function warning. 12037 if (IsAddressOf && IsFunction) { 12038 return; 12039 } 12040 12041 // Found nothing. 12042 if (!IsAddressOf && !IsFunction && !IsArray) 12043 return; 12044 12045 // Pretty print the expression for the diagnostic. 12046 std::string Str; 12047 llvm::raw_string_ostream S(Str); 12048 E->printPretty(S, nullptr, getPrintingPolicy()); 12049 12050 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12051 : diag::warn_impcast_pointer_to_bool; 12052 enum { 12053 AddressOf, 12054 FunctionPointer, 12055 ArrayPointer 12056 } DiagType; 12057 if (IsAddressOf) 12058 DiagType = AddressOf; 12059 else if (IsFunction) 12060 DiagType = FunctionPointer; 12061 else if (IsArray) 12062 DiagType = ArrayPointer; 12063 else 12064 llvm_unreachable("Could not determine diagnostic."); 12065 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12066 << Range << IsEqual; 12067 12068 if (!IsFunction) 12069 return; 12070 12071 // Suggest '&' to silence the function warning. 12072 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12073 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12074 12075 // Check to see if '()' fixit should be emitted. 12076 QualType ReturnType; 12077 UnresolvedSet<4> NonTemplateOverloads; 12078 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12079 if (ReturnType.isNull()) 12080 return; 12081 12082 if (IsCompare) { 12083 // There are two cases here. If there is null constant, the only suggest 12084 // for a pointer return type. If the null is 0, then suggest if the return 12085 // type is a pointer or an integer type. 12086 if (!ReturnType->isPointerType()) { 12087 if (NullKind == Expr::NPCK_ZeroExpression || 12088 NullKind == Expr::NPCK_ZeroLiteral) { 12089 if (!ReturnType->isIntegerType()) 12090 return; 12091 } else { 12092 return; 12093 } 12094 } 12095 } else { // !IsCompare 12096 // For function to bool, only suggest if the function pointer has bool 12097 // return type. 12098 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12099 return; 12100 } 12101 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12102 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12103 } 12104 12105 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12106 // Don't diagnose in unevaluated contexts. 12107 if (isUnevaluatedContext()) 12108 return; 12109 12110 // Don't diagnose for value- or type-dependent expressions. 12111 if (E->isTypeDependent() || E->isValueDependent()) 12112 return; 12113 12114 // Check for array bounds violations in cases where the check isn't triggered 12115 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12116 // ArraySubscriptExpr is on the RHS of a variable initialization. 12117 CheckArrayAccess(E); 12118 12119 // This is not the right CC for (e.g.) a variable initialization. 12120 AnalyzeImplicitConversions(*this, E, CC); 12121 } 12122 12123 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12124 ::CheckBoolLikeConversion(*this, E, CC); 12125 } 12126 12127 void Sema::CheckForIntOverflow (const Expr *E) { 12128 // Use a work list to deal with nested struct initializers. 12129 SmallVector<const Expr *, 2> Exprs(1, E); 12130 12131 do { 12132 const Expr *OriginalE = Exprs.pop_back_val(); 12133 const Expr *E = OriginalE->IgnoreParenCasts(); 12134 12135 if (isa<BinaryOperator, UnaryOperator>(E)) { 12136 E->EvaluateForOverflow(Context); 12137 continue; 12138 } 12139 12140 if (const auto *InitList = dyn_cast<InitListExpr>(OriginalE)) 12141 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12142 else if (isa<ObjCBoxedExpr>(OriginalE)) 12143 E->EvaluateForOverflow(Context); 12144 else if (const auto *Call = dyn_cast<CallExpr>(E)) 12145 Exprs.append(Call->arg_begin(), Call->arg_end()); 12146 else if (const auto *Message = dyn_cast<ObjCMessageExpr>(E)) 12147 Exprs.append(Message->arg_begin(), Message->arg_end()); 12148 else if (const auto *Construct = dyn_cast<CXXConstructExpr>(E)) 12149 Exprs.append(Construct->arg_begin(), Construct->arg_end()); 12150 else if (const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E)) 12151 Exprs.push_back(Temporary->getSubExpr()); 12152 else if (const auto *Array = dyn_cast<ArraySubscriptExpr>(E)) 12153 Exprs.push_back(Array->getIdx()); 12154 else if (const auto *Compound = dyn_cast<CompoundLiteralExpr>(E)) 12155 Exprs.push_back(Compound->getInitializer()); 12156 else if (const auto *New = dyn_cast<CXXNewExpr>(E); 12157 New && New->isArray()) { 12158 if (auto ArraySize = New->getArraySize()) 12159 Exprs.push_back(*ArraySize); 12160 } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE)) 12161 Exprs.push_back(MTE->getSubExpr()); 12162 } while (!Exprs.empty()); 12163 } 12164 12165 namespace { 12166 12167 /// Visitor for expressions which looks for unsequenced operations on the 12168 /// same object. 12169 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12170 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12171 12172 /// A tree of sequenced regions within an expression. Two regions are 12173 /// unsequenced if one is an ancestor or a descendent of the other. When we 12174 /// finish processing an expression with sequencing, such as a comma 12175 /// expression, we fold its tree nodes into its parent, since they are 12176 /// unsequenced with respect to nodes we will visit later. 12177 class SequenceTree { 12178 struct Value { 12179 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12180 unsigned Parent : 31; 12181 LLVM_PREFERRED_TYPE(bool) 12182 unsigned Merged : 1; 12183 }; 12184 SmallVector<Value, 8> Values; 12185 12186 public: 12187 /// A region within an expression which may be sequenced with respect 12188 /// to some other region. 12189 class Seq { 12190 friend class SequenceTree; 12191 12192 unsigned Index; 12193 12194 explicit Seq(unsigned N) : Index(N) {} 12195 12196 public: 12197 Seq() : Index(0) {} 12198 }; 12199 12200 SequenceTree() { Values.push_back(Value(0)); } 12201 Seq root() const { return Seq(0); } 12202 12203 /// Create a new sequence of operations, which is an unsequenced 12204 /// subset of \p Parent. This sequence of operations is sequenced with 12205 /// respect to other children of \p Parent. 12206 Seq allocate(Seq Parent) { 12207 Values.push_back(Value(Parent.Index)); 12208 return Seq(Values.size() - 1); 12209 } 12210 12211 /// Merge a sequence of operations into its parent. 12212 void merge(Seq S) { 12213 Values[S.Index].Merged = true; 12214 } 12215 12216 /// Determine whether two operations are unsequenced. This operation 12217 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12218 /// should have been merged into its parent as appropriate. 12219 bool isUnsequenced(Seq Cur, Seq Old) { 12220 unsigned C = representative(Cur.Index); 12221 unsigned Target = representative(Old.Index); 12222 while (C >= Target) { 12223 if (C == Target) 12224 return true; 12225 C = Values[C].Parent; 12226 } 12227 return false; 12228 } 12229 12230 private: 12231 /// Pick a representative for a sequence. 12232 unsigned representative(unsigned K) { 12233 if (Values[K].Merged) 12234 // Perform path compression as we go. 12235 return Values[K].Parent = representative(Values[K].Parent); 12236 return K; 12237 } 12238 }; 12239 12240 /// An object for which we can track unsequenced uses. 12241 using Object = const NamedDecl *; 12242 12243 /// Different flavors of object usage which we track. We only track the 12244 /// least-sequenced usage of each kind. 12245 enum UsageKind { 12246 /// A read of an object. Multiple unsequenced reads are OK. 12247 UK_Use, 12248 12249 /// A modification of an object which is sequenced before the value 12250 /// computation of the expression, such as ++n in C++. 12251 UK_ModAsValue, 12252 12253 /// A modification of an object which is not sequenced before the value 12254 /// computation of the expression, such as n++. 12255 UK_ModAsSideEffect, 12256 12257 UK_Count = UK_ModAsSideEffect + 1 12258 }; 12259 12260 /// Bundle together a sequencing region and the expression corresponding 12261 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12262 struct Usage { 12263 const Expr *UsageExpr = nullptr; 12264 SequenceTree::Seq Seq; 12265 12266 Usage() = default; 12267 }; 12268 12269 struct UsageInfo { 12270 Usage Uses[UK_Count]; 12271 12272 /// Have we issued a diagnostic for this object already? 12273 bool Diagnosed = false; 12274 12275 UsageInfo(); 12276 }; 12277 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12278 12279 Sema &SemaRef; 12280 12281 /// Sequenced regions within the expression. 12282 SequenceTree Tree; 12283 12284 /// Declaration modifications and references which we have seen. 12285 UsageInfoMap UsageMap; 12286 12287 /// The region we are currently within. 12288 SequenceTree::Seq Region; 12289 12290 /// Filled in with declarations which were modified as a side-effect 12291 /// (that is, post-increment operations). 12292 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12293 12294 /// Expressions to check later. We defer checking these to reduce 12295 /// stack usage. 12296 SmallVectorImpl<const Expr *> &WorkList; 12297 12298 /// RAII object wrapping the visitation of a sequenced subexpression of an 12299 /// expression. At the end of this process, the side-effects of the evaluation 12300 /// become sequenced with respect to the value computation of the result, so 12301 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12302 /// UK_ModAsValue. 12303 struct SequencedSubexpression { 12304 SequencedSubexpression(SequenceChecker &Self) 12305 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12306 Self.ModAsSideEffect = &ModAsSideEffect; 12307 } 12308 12309 ~SequencedSubexpression() { 12310 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12311 // Add a new usage with usage kind UK_ModAsValue, and then restore 12312 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12313 // the previous one was empty). 12314 UsageInfo &UI = Self.UsageMap[M.first]; 12315 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12316 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12317 SideEffectUsage = M.second; 12318 } 12319 Self.ModAsSideEffect = OldModAsSideEffect; 12320 } 12321 12322 SequenceChecker &Self; 12323 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12324 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12325 }; 12326 12327 /// RAII object wrapping the visitation of a subexpression which we might 12328 /// choose to evaluate as a constant. If any subexpression is evaluated and 12329 /// found to be non-constant, this allows us to suppress the evaluation of 12330 /// the outer expression. 12331 class EvaluationTracker { 12332 public: 12333 EvaluationTracker(SequenceChecker &Self) 12334 : Self(Self), Prev(Self.EvalTracker) { 12335 Self.EvalTracker = this; 12336 } 12337 12338 ~EvaluationTracker() { 12339 Self.EvalTracker = Prev; 12340 if (Prev) 12341 Prev->EvalOK &= EvalOK; 12342 } 12343 12344 bool evaluate(const Expr *E, bool &Result) { 12345 if (!EvalOK || E->isValueDependent()) 12346 return false; 12347 EvalOK = E->EvaluateAsBooleanCondition( 12348 Result, Self.SemaRef.Context, 12349 Self.SemaRef.isConstantEvaluatedContext()); 12350 return EvalOK; 12351 } 12352 12353 private: 12354 SequenceChecker &Self; 12355 EvaluationTracker *Prev; 12356 bool EvalOK = true; 12357 } *EvalTracker = nullptr; 12358 12359 /// Find the object which is produced by the specified expression, 12360 /// if any. 12361 Object getObject(const Expr *E, bool Mod) const { 12362 E = E->IgnoreParenCasts(); 12363 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12364 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12365 return getObject(UO->getSubExpr(), Mod); 12366 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12367 if (BO->getOpcode() == BO_Comma) 12368 return getObject(BO->getRHS(), Mod); 12369 if (Mod && BO->isAssignmentOp()) 12370 return getObject(BO->getLHS(), Mod); 12371 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12372 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12373 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12374 return ME->getMemberDecl(); 12375 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12376 // FIXME: If this is a reference, map through to its value. 12377 return DRE->getDecl(); 12378 return nullptr; 12379 } 12380 12381 /// Note that an object \p O was modified or used by an expression 12382 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12383 /// the object \p O as obtained via the \p UsageMap. 12384 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12385 // Get the old usage for the given object and usage kind. 12386 Usage &U = UI.Uses[UK]; 12387 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12388 // If we have a modification as side effect and are in a sequenced 12389 // subexpression, save the old Usage so that we can restore it later 12390 // in SequencedSubexpression::~SequencedSubexpression. 12391 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12392 ModAsSideEffect->push_back(std::make_pair(O, U)); 12393 // Then record the new usage with the current sequencing region. 12394 U.UsageExpr = UsageExpr; 12395 U.Seq = Region; 12396 } 12397 } 12398 12399 /// Check whether a modification or use of an object \p O in an expression 12400 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12401 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12402 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12403 /// usage and false we are checking for a mod-use unsequenced usage. 12404 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12405 UsageKind OtherKind, bool IsModMod) { 12406 if (UI.Diagnosed) 12407 return; 12408 12409 const Usage &U = UI.Uses[OtherKind]; 12410 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12411 return; 12412 12413 const Expr *Mod = U.UsageExpr; 12414 const Expr *ModOrUse = UsageExpr; 12415 if (OtherKind == UK_Use) 12416 std::swap(Mod, ModOrUse); 12417 12418 SemaRef.DiagRuntimeBehavior( 12419 Mod->getExprLoc(), {Mod, ModOrUse}, 12420 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12421 : diag::warn_unsequenced_mod_use) 12422 << O << SourceRange(ModOrUse->getExprLoc())); 12423 UI.Diagnosed = true; 12424 } 12425 12426 // A note on note{Pre, Post}{Use, Mod}: 12427 // 12428 // (It helps to follow the algorithm with an expression such as 12429 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12430 // operations before C++17 and both are well-defined in C++17). 12431 // 12432 // When visiting a node which uses/modify an object we first call notePreUse 12433 // or notePreMod before visiting its sub-expression(s). At this point the 12434 // children of the current node have not yet been visited and so the eventual 12435 // uses/modifications resulting from the children of the current node have not 12436 // been recorded yet. 12437 // 12438 // We then visit the children of the current node. After that notePostUse or 12439 // notePostMod is called. These will 1) detect an unsequenced modification 12440 // as side effect (as in "k++ + k") and 2) add a new usage with the 12441 // appropriate usage kind. 12442 // 12443 // We also have to be careful that some operation sequences modification as 12444 // side effect as well (for example: || or ,). To account for this we wrap 12445 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12446 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12447 // which record usages which are modifications as side effect, and then 12448 // downgrade them (or more accurately restore the previous usage which was a 12449 // modification as side effect) when exiting the scope of the sequenced 12450 // subexpression. 12451 12452 void notePreUse(Object O, const Expr *UseExpr) { 12453 UsageInfo &UI = UsageMap[O]; 12454 // Uses conflict with other modifications. 12455 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12456 } 12457 12458 void notePostUse(Object O, const Expr *UseExpr) { 12459 UsageInfo &UI = UsageMap[O]; 12460 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12461 /*IsModMod=*/false); 12462 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12463 } 12464 12465 void notePreMod(Object O, const Expr *ModExpr) { 12466 UsageInfo &UI = UsageMap[O]; 12467 // Modifications conflict with other modifications and with uses. 12468 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12469 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12470 } 12471 12472 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12473 UsageInfo &UI = UsageMap[O]; 12474 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12475 /*IsModMod=*/true); 12476 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12477 } 12478 12479 public: 12480 SequenceChecker(Sema &S, const Expr *E, 12481 SmallVectorImpl<const Expr *> &WorkList) 12482 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12483 Visit(E); 12484 // Silence a -Wunused-private-field since WorkList is now unused. 12485 // TODO: Evaluate if it can be used, and if not remove it. 12486 (void)this->WorkList; 12487 } 12488 12489 void VisitStmt(const Stmt *S) { 12490 // Skip all statements which aren't expressions for now. 12491 } 12492 12493 void VisitExpr(const Expr *E) { 12494 // By default, just recurse to evaluated subexpressions. 12495 Base::VisitStmt(E); 12496 } 12497 12498 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *CSE) { 12499 for (auto *Sub : CSE->children()) { 12500 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub); 12501 if (!ChildExpr) 12502 continue; 12503 12504 if (ChildExpr == CSE->getOperand()) 12505 // Do not recurse over a CoroutineSuspendExpr's operand. 12506 // The operand is also a subexpression of getCommonExpr(), and 12507 // recursing into it directly could confuse object management 12508 // for the sake of sequence tracking. 12509 continue; 12510 12511 Visit(Sub); 12512 } 12513 } 12514 12515 void VisitCastExpr(const CastExpr *E) { 12516 Object O = Object(); 12517 if (E->getCastKind() == CK_LValueToRValue) 12518 O = getObject(E->getSubExpr(), false); 12519 12520 if (O) 12521 notePreUse(O, E); 12522 VisitExpr(E); 12523 if (O) 12524 notePostUse(O, E); 12525 } 12526 12527 void VisitSequencedExpressions(const Expr *SequencedBefore, 12528 const Expr *SequencedAfter) { 12529 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12530 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12531 SequenceTree::Seq OldRegion = Region; 12532 12533 { 12534 SequencedSubexpression SeqBefore(*this); 12535 Region = BeforeRegion; 12536 Visit(SequencedBefore); 12537 } 12538 12539 Region = AfterRegion; 12540 Visit(SequencedAfter); 12541 12542 Region = OldRegion; 12543 12544 Tree.merge(BeforeRegion); 12545 Tree.merge(AfterRegion); 12546 } 12547 12548 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12549 // C++17 [expr.sub]p1: 12550 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12551 // expression E1 is sequenced before the expression E2. 12552 if (SemaRef.getLangOpts().CPlusPlus17) 12553 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12554 else { 12555 Visit(ASE->getLHS()); 12556 Visit(ASE->getRHS()); 12557 } 12558 } 12559 12560 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12561 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12562 void VisitBinPtrMem(const BinaryOperator *BO) { 12563 // C++17 [expr.mptr.oper]p4: 12564 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12565 // the expression E1 is sequenced before the expression E2. 12566 if (SemaRef.getLangOpts().CPlusPlus17) 12567 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12568 else { 12569 Visit(BO->getLHS()); 12570 Visit(BO->getRHS()); 12571 } 12572 } 12573 12574 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12575 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12576 void VisitBinShlShr(const BinaryOperator *BO) { 12577 // C++17 [expr.shift]p4: 12578 // The expression E1 is sequenced before the expression E2. 12579 if (SemaRef.getLangOpts().CPlusPlus17) 12580 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12581 else { 12582 Visit(BO->getLHS()); 12583 Visit(BO->getRHS()); 12584 } 12585 } 12586 12587 void VisitBinComma(const BinaryOperator *BO) { 12588 // C++11 [expr.comma]p1: 12589 // Every value computation and side effect associated with the left 12590 // expression is sequenced before every value computation and side 12591 // effect associated with the right expression. 12592 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12593 } 12594 12595 void VisitBinAssign(const BinaryOperator *BO) { 12596 SequenceTree::Seq RHSRegion; 12597 SequenceTree::Seq LHSRegion; 12598 if (SemaRef.getLangOpts().CPlusPlus17) { 12599 RHSRegion = Tree.allocate(Region); 12600 LHSRegion = Tree.allocate(Region); 12601 } else { 12602 RHSRegion = Region; 12603 LHSRegion = Region; 12604 } 12605 SequenceTree::Seq OldRegion = Region; 12606 12607 // C++11 [expr.ass]p1: 12608 // [...] the assignment is sequenced after the value computation 12609 // of the right and left operands, [...] 12610 // 12611 // so check it before inspecting the operands and update the 12612 // map afterwards. 12613 Object O = getObject(BO->getLHS(), /*Mod=*/true); 12614 if (O) 12615 notePreMod(O, BO); 12616 12617 if (SemaRef.getLangOpts().CPlusPlus17) { 12618 // C++17 [expr.ass]p1: 12619 // [...] The right operand is sequenced before the left operand. [...] 12620 { 12621 SequencedSubexpression SeqBefore(*this); 12622 Region = RHSRegion; 12623 Visit(BO->getRHS()); 12624 } 12625 12626 Region = LHSRegion; 12627 Visit(BO->getLHS()); 12628 12629 if (O && isa<CompoundAssignOperator>(BO)) 12630 notePostUse(O, BO); 12631 12632 } else { 12633 // C++11 does not specify any sequencing between the LHS and RHS. 12634 Region = LHSRegion; 12635 Visit(BO->getLHS()); 12636 12637 if (O && isa<CompoundAssignOperator>(BO)) 12638 notePostUse(O, BO); 12639 12640 Region = RHSRegion; 12641 Visit(BO->getRHS()); 12642 } 12643 12644 // C++11 [expr.ass]p1: 12645 // the assignment is sequenced [...] before the value computation of the 12646 // assignment expression. 12647 // C11 6.5.16/3 has no such rule. 12648 Region = OldRegion; 12649 if (O) 12650 notePostMod(O, BO, 12651 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12652 : UK_ModAsSideEffect); 12653 if (SemaRef.getLangOpts().CPlusPlus17) { 12654 Tree.merge(RHSRegion); 12655 Tree.merge(LHSRegion); 12656 } 12657 } 12658 12659 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 12660 VisitBinAssign(CAO); 12661 } 12662 12663 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12664 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12665 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 12666 Object O = getObject(UO->getSubExpr(), true); 12667 if (!O) 12668 return VisitExpr(UO); 12669 12670 notePreMod(O, UO); 12671 Visit(UO->getSubExpr()); 12672 // C++11 [expr.pre.incr]p1: 12673 // the expression ++x is equivalent to x+=1 12674 notePostMod(O, UO, 12675 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12676 : UK_ModAsSideEffect); 12677 } 12678 12679 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12680 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12681 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 12682 Object O = getObject(UO->getSubExpr(), true); 12683 if (!O) 12684 return VisitExpr(UO); 12685 12686 notePreMod(O, UO); 12687 Visit(UO->getSubExpr()); 12688 notePostMod(O, UO, UK_ModAsSideEffect); 12689 } 12690 12691 void VisitBinLOr(const BinaryOperator *BO) { 12692 // C++11 [expr.log.or]p2: 12693 // If the second expression is evaluated, every value computation and 12694 // side effect associated with the first expression is sequenced before 12695 // every value computation and side effect associated with the 12696 // second expression. 12697 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12698 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12699 SequenceTree::Seq OldRegion = Region; 12700 12701 EvaluationTracker Eval(*this); 12702 { 12703 SequencedSubexpression Sequenced(*this); 12704 Region = LHSRegion; 12705 Visit(BO->getLHS()); 12706 } 12707 12708 // C++11 [expr.log.or]p1: 12709 // [...] the second operand is not evaluated if the first operand 12710 // evaluates to true. 12711 bool EvalResult = false; 12712 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12713 bool ShouldVisitRHS = !EvalOK || !EvalResult; 12714 if (ShouldVisitRHS) { 12715 Region = RHSRegion; 12716 Visit(BO->getRHS()); 12717 } 12718 12719 Region = OldRegion; 12720 Tree.merge(LHSRegion); 12721 Tree.merge(RHSRegion); 12722 } 12723 12724 void VisitBinLAnd(const BinaryOperator *BO) { 12725 // C++11 [expr.log.and]p2: 12726 // If the second expression is evaluated, every value computation and 12727 // side effect associated with the first expression is sequenced before 12728 // every value computation and side effect associated with the 12729 // second expression. 12730 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12731 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12732 SequenceTree::Seq OldRegion = Region; 12733 12734 EvaluationTracker Eval(*this); 12735 { 12736 SequencedSubexpression Sequenced(*this); 12737 Region = LHSRegion; 12738 Visit(BO->getLHS()); 12739 } 12740 12741 // C++11 [expr.log.and]p1: 12742 // [...] the second operand is not evaluated if the first operand is false. 12743 bool EvalResult = false; 12744 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12745 bool ShouldVisitRHS = !EvalOK || EvalResult; 12746 if (ShouldVisitRHS) { 12747 Region = RHSRegion; 12748 Visit(BO->getRHS()); 12749 } 12750 12751 Region = OldRegion; 12752 Tree.merge(LHSRegion); 12753 Tree.merge(RHSRegion); 12754 } 12755 12756 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 12757 // C++11 [expr.cond]p1: 12758 // [...] Every value computation and side effect associated with the first 12759 // expression is sequenced before every value computation and side effect 12760 // associated with the second or third expression. 12761 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 12762 12763 // No sequencing is specified between the true and false expression. 12764 // However since exactly one of both is going to be evaluated we can 12765 // consider them to be sequenced. This is needed to avoid warning on 12766 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 12767 // both the true and false expressions because we can't evaluate x. 12768 // This will still allow us to detect an expression like (pre C++17) 12769 // "(x ? y += 1 : y += 2) = y". 12770 // 12771 // We don't wrap the visitation of the true and false expression with 12772 // SequencedSubexpression because we don't want to downgrade modifications 12773 // as side effect in the true and false expressions after the visition 12774 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 12775 // not warn between the two "y++", but we should warn between the "y++" 12776 // and the "y". 12777 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 12778 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 12779 SequenceTree::Seq OldRegion = Region; 12780 12781 EvaluationTracker Eval(*this); 12782 { 12783 SequencedSubexpression Sequenced(*this); 12784 Region = ConditionRegion; 12785 Visit(CO->getCond()); 12786 } 12787 12788 // C++11 [expr.cond]p1: 12789 // [...] The first expression is contextually converted to bool (Clause 4). 12790 // It is evaluated and if it is true, the result of the conditional 12791 // expression is the value of the second expression, otherwise that of the 12792 // third expression. Only one of the second and third expressions is 12793 // evaluated. [...] 12794 bool EvalResult = false; 12795 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 12796 bool ShouldVisitTrueExpr = !EvalOK || EvalResult; 12797 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult; 12798 if (ShouldVisitTrueExpr) { 12799 Region = TrueRegion; 12800 Visit(CO->getTrueExpr()); 12801 } 12802 if (ShouldVisitFalseExpr) { 12803 Region = FalseRegion; 12804 Visit(CO->getFalseExpr()); 12805 } 12806 12807 Region = OldRegion; 12808 Tree.merge(ConditionRegion); 12809 Tree.merge(TrueRegion); 12810 Tree.merge(FalseRegion); 12811 } 12812 12813 void VisitCallExpr(const CallExpr *CE) { 12814 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12815 12816 if (CE->isUnevaluatedBuiltinCall(Context)) 12817 return; 12818 12819 // C++11 [intro.execution]p15: 12820 // When calling a function [...], every value computation and side effect 12821 // associated with any argument expression, or with the postfix expression 12822 // designating the called function, is sequenced before execution of every 12823 // expression or statement in the body of the function [and thus before 12824 // the value computation of its result]. 12825 SequencedSubexpression Sequenced(*this); 12826 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 12827 // C++17 [expr.call]p5 12828 // The postfix-expression is sequenced before each expression in the 12829 // expression-list and any default argument. [...] 12830 SequenceTree::Seq CalleeRegion; 12831 SequenceTree::Seq OtherRegion; 12832 if (SemaRef.getLangOpts().CPlusPlus17) { 12833 CalleeRegion = Tree.allocate(Region); 12834 OtherRegion = Tree.allocate(Region); 12835 } else { 12836 CalleeRegion = Region; 12837 OtherRegion = Region; 12838 } 12839 SequenceTree::Seq OldRegion = Region; 12840 12841 // Visit the callee expression first. 12842 Region = CalleeRegion; 12843 if (SemaRef.getLangOpts().CPlusPlus17) { 12844 SequencedSubexpression Sequenced(*this); 12845 Visit(CE->getCallee()); 12846 } else { 12847 Visit(CE->getCallee()); 12848 } 12849 12850 // Then visit the argument expressions. 12851 Region = OtherRegion; 12852 for (const Expr *Argument : CE->arguments()) 12853 Visit(Argument); 12854 12855 Region = OldRegion; 12856 if (SemaRef.getLangOpts().CPlusPlus17) { 12857 Tree.merge(CalleeRegion); 12858 Tree.merge(OtherRegion); 12859 } 12860 }); 12861 } 12862 12863 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 12864 // C++17 [over.match.oper]p2: 12865 // [...] the operator notation is first transformed to the equivalent 12866 // function-call notation as summarized in Table 12 (where @ denotes one 12867 // of the operators covered in the specified subclause). However, the 12868 // operands are sequenced in the order prescribed for the built-in 12869 // operator (Clause 8). 12870 // 12871 // From the above only overloaded binary operators and overloaded call 12872 // operators have sequencing rules in C++17 that we need to handle 12873 // separately. 12874 if (!SemaRef.getLangOpts().CPlusPlus17 || 12875 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 12876 return VisitCallExpr(CXXOCE); 12877 12878 enum { 12879 NoSequencing, 12880 LHSBeforeRHS, 12881 RHSBeforeLHS, 12882 LHSBeforeRest 12883 } SequencingKind; 12884 switch (CXXOCE->getOperator()) { 12885 case OO_Equal: 12886 case OO_PlusEqual: 12887 case OO_MinusEqual: 12888 case OO_StarEqual: 12889 case OO_SlashEqual: 12890 case OO_PercentEqual: 12891 case OO_CaretEqual: 12892 case OO_AmpEqual: 12893 case OO_PipeEqual: 12894 case OO_LessLessEqual: 12895 case OO_GreaterGreaterEqual: 12896 SequencingKind = RHSBeforeLHS; 12897 break; 12898 12899 case OO_LessLess: 12900 case OO_GreaterGreater: 12901 case OO_AmpAmp: 12902 case OO_PipePipe: 12903 case OO_Comma: 12904 case OO_ArrowStar: 12905 case OO_Subscript: 12906 SequencingKind = LHSBeforeRHS; 12907 break; 12908 12909 case OO_Call: 12910 SequencingKind = LHSBeforeRest; 12911 break; 12912 12913 default: 12914 SequencingKind = NoSequencing; 12915 break; 12916 } 12917 12918 if (SequencingKind == NoSequencing) 12919 return VisitCallExpr(CXXOCE); 12920 12921 // This is a call, so all subexpressions are sequenced before the result. 12922 SequencedSubexpression Sequenced(*this); 12923 12924 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 12925 assert(SemaRef.getLangOpts().CPlusPlus17 && 12926 "Should only get there with C++17 and above!"); 12927 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 12928 "Should only get there with an overloaded binary operator" 12929 " or an overloaded call operator!"); 12930 12931 if (SequencingKind == LHSBeforeRest) { 12932 assert(CXXOCE->getOperator() == OO_Call && 12933 "We should only have an overloaded call operator here!"); 12934 12935 // This is very similar to VisitCallExpr, except that we only have the 12936 // C++17 case. The postfix-expression is the first argument of the 12937 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 12938 // are in the following arguments. 12939 // 12940 // Note that we intentionally do not visit the callee expression since 12941 // it is just a decayed reference to a function. 12942 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 12943 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 12944 SequenceTree::Seq OldRegion = Region; 12945 12946 assert(CXXOCE->getNumArgs() >= 1 && 12947 "An overloaded call operator must have at least one argument" 12948 " for the postfix-expression!"); 12949 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 12950 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 12951 CXXOCE->getNumArgs() - 1); 12952 12953 // Visit the postfix-expression first. 12954 { 12955 Region = PostfixExprRegion; 12956 SequencedSubexpression Sequenced(*this); 12957 Visit(PostfixExpr); 12958 } 12959 12960 // Then visit the argument expressions. 12961 Region = ArgsRegion; 12962 for (const Expr *Arg : Args) 12963 Visit(Arg); 12964 12965 Region = OldRegion; 12966 Tree.merge(PostfixExprRegion); 12967 Tree.merge(ArgsRegion); 12968 } else { 12969 assert(CXXOCE->getNumArgs() == 2 && 12970 "Should only have two arguments here!"); 12971 assert((SequencingKind == LHSBeforeRHS || 12972 SequencingKind == RHSBeforeLHS) && 12973 "Unexpected sequencing kind!"); 12974 12975 // We do not visit the callee expression since it is just a decayed 12976 // reference to a function. 12977 const Expr *E1 = CXXOCE->getArg(0); 12978 const Expr *E2 = CXXOCE->getArg(1); 12979 if (SequencingKind == RHSBeforeLHS) 12980 std::swap(E1, E2); 12981 12982 return VisitSequencedExpressions(E1, E2); 12983 } 12984 }); 12985 } 12986 12987 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 12988 // This is a call, so all subexpressions are sequenced before the result. 12989 SequencedSubexpression Sequenced(*this); 12990 12991 if (!CCE->isListInitialization()) 12992 return VisitExpr(CCE); 12993 12994 // In C++11, list initializations are sequenced. 12995 SequenceExpressionsInOrder( 12996 llvm::ArrayRef(CCE->getArgs(), CCE->getNumArgs())); 12997 } 12998 12999 void VisitInitListExpr(const InitListExpr *ILE) { 13000 if (!SemaRef.getLangOpts().CPlusPlus11) 13001 return VisitExpr(ILE); 13002 13003 // In C++11, list initializations are sequenced. 13004 SequenceExpressionsInOrder(ILE->inits()); 13005 } 13006 13007 void VisitCXXParenListInitExpr(const CXXParenListInitExpr *PLIE) { 13008 // C++20 parenthesized list initializations are sequenced. See C++20 13009 // [decl.init.general]p16.5 and [decl.init.general]p16.6.2.2. 13010 SequenceExpressionsInOrder(PLIE->getInitExprs()); 13011 } 13012 13013 private: 13014 void SequenceExpressionsInOrder(ArrayRef<const Expr *> ExpressionList) { 13015 SmallVector<SequenceTree::Seq, 32> Elts; 13016 SequenceTree::Seq Parent = Region; 13017 for (const Expr *E : ExpressionList) { 13018 if (!E) 13019 continue; 13020 Region = Tree.allocate(Parent); 13021 Elts.push_back(Region); 13022 Visit(E); 13023 } 13024 13025 // Forget that the initializers are sequenced. 13026 Region = Parent; 13027 for (unsigned I = 0; I < Elts.size(); ++I) 13028 Tree.merge(Elts[I]); 13029 } 13030 }; 13031 13032 SequenceChecker::UsageInfo::UsageInfo() = default; 13033 13034 } // namespace 13035 13036 void Sema::CheckUnsequencedOperations(const Expr *E) { 13037 SmallVector<const Expr *, 8> WorkList; 13038 WorkList.push_back(E); 13039 while (!WorkList.empty()) { 13040 const Expr *Item = WorkList.pop_back_val(); 13041 SequenceChecker(*this, Item, WorkList); 13042 } 13043 } 13044 13045 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13046 bool IsConstexpr) { 13047 llvm::SaveAndRestore ConstantContext(isConstantEvaluatedOverride, 13048 IsConstexpr || isa<ConstantExpr>(E)); 13049 CheckImplicitConversions(E, CheckLoc); 13050 if (!E->isInstantiationDependent()) 13051 CheckUnsequencedOperations(E); 13052 if (!IsConstexpr && !E->isValueDependent()) 13053 CheckForIntOverflow(E); 13054 DiagnoseMisalignedMembers(); 13055 } 13056 13057 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13058 FieldDecl *BitField, 13059 Expr *Init) { 13060 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13061 } 13062 13063 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13064 SourceLocation Loc) { 13065 if (!PType->isVariablyModifiedType()) 13066 return; 13067 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13068 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13069 return; 13070 } 13071 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13072 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13073 return; 13074 } 13075 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13076 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13077 return; 13078 } 13079 13080 const ArrayType *AT = S.Context.getAsArrayType(PType); 13081 if (!AT) 13082 return; 13083 13084 if (AT->getSizeModifier() != ArraySizeModifier::Star) { 13085 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13086 return; 13087 } 13088 13089 S.Diag(Loc, diag::err_array_star_in_function_definition); 13090 } 13091 13092 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13093 bool CheckParameterNames) { 13094 bool HasInvalidParm = false; 13095 for (ParmVarDecl *Param : Parameters) { 13096 assert(Param && "null in a parameter list"); 13097 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13098 // function declarator that is part of a function definition of 13099 // that function shall not have incomplete type. 13100 // 13101 // C++23 [dcl.fct.def.general]/p2 13102 // The type of a parameter [...] for a function definition 13103 // shall not be a (possibly cv-qualified) class type that is incomplete 13104 // or abstract within the function body unless the function is deleted. 13105 if (!Param->isInvalidDecl() && 13106 (RequireCompleteType(Param->getLocation(), Param->getType(), 13107 diag::err_typecheck_decl_incomplete_type) || 13108 RequireNonAbstractType(Param->getBeginLoc(), Param->getOriginalType(), 13109 diag::err_abstract_type_in_decl, 13110 AbstractParamType))) { 13111 Param->setInvalidDecl(); 13112 HasInvalidParm = true; 13113 } 13114 13115 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13116 // declaration of each parameter shall include an identifier. 13117 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13118 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13119 // Diagnose this as an extension in C17 and earlier. 13120 if (!getLangOpts().C23) 13121 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23); 13122 } 13123 13124 // C99 6.7.5.3p12: 13125 // If the function declarator is not part of a definition of that 13126 // function, parameters may have incomplete type and may use the [*] 13127 // notation in their sequences of declarator specifiers to specify 13128 // variable length array types. 13129 QualType PType = Param->getOriginalType(); 13130 // FIXME: This diagnostic should point the '[*]' if source-location 13131 // information is added for it. 13132 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13133 13134 // If the parameter is a c++ class type and it has to be destructed in the 13135 // callee function, declare the destructor so that it can be called by the 13136 // callee function. Do not perform any direct access check on the dtor here. 13137 if (!Param->isInvalidDecl()) { 13138 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13139 if (!ClassDecl->isInvalidDecl() && 13140 !ClassDecl->hasIrrelevantDestructor() && 13141 !ClassDecl->isDependentContext() && 13142 ClassDecl->isParamDestroyedInCallee()) { 13143 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13144 MarkFunctionReferenced(Param->getLocation(), Destructor); 13145 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13146 } 13147 } 13148 } 13149 13150 // Parameters with the pass_object_size attribute only need to be marked 13151 // constant at function definitions. Because we lack information about 13152 // whether we're on a declaration or definition when we're instantiating the 13153 // attribute, we need to check for constness here. 13154 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13155 if (!Param->getType().isConstQualified()) 13156 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13157 << Attr->getSpelling() << 1; 13158 13159 // Check for parameter names shadowing fields from the class. 13160 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13161 // The owning context for the parameter should be the function, but we 13162 // want to see if this function's declaration context is a record. 13163 DeclContext *DC = Param->getDeclContext(); 13164 if (DC && DC->isFunctionOrMethod()) { 13165 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13166 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13167 RD, /*DeclIsField*/ false); 13168 } 13169 } 13170 13171 if (!Param->isInvalidDecl() && 13172 Param->getOriginalType()->isWebAssemblyTableType()) { 13173 Param->setInvalidDecl(); 13174 HasInvalidParm = true; 13175 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter); 13176 } 13177 } 13178 13179 return HasInvalidParm; 13180 } 13181 13182 std::optional<std::pair< 13183 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr 13184 *E, 13185 ASTContext 13186 &Ctx); 13187 13188 /// Compute the alignment and offset of the base class object given the 13189 /// derived-to-base cast expression and the alignment and offset of the derived 13190 /// class object. 13191 static std::pair<CharUnits, CharUnits> 13192 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 13193 CharUnits BaseAlignment, CharUnits Offset, 13194 ASTContext &Ctx) { 13195 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 13196 ++PathI) { 13197 const CXXBaseSpecifier *Base = *PathI; 13198 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 13199 if (Base->isVirtual()) { 13200 // The complete object may have a lower alignment than the non-virtual 13201 // alignment of the base, in which case the base may be misaligned. Choose 13202 // the smaller of the non-virtual alignment and BaseAlignment, which is a 13203 // conservative lower bound of the complete object alignment. 13204 CharUnits NonVirtualAlignment = 13205 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 13206 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 13207 Offset = CharUnits::Zero(); 13208 } else { 13209 const ASTRecordLayout &RL = 13210 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 13211 Offset += RL.getBaseClassOffset(BaseDecl); 13212 } 13213 DerivedType = Base->getType(); 13214 } 13215 13216 return std::make_pair(BaseAlignment, Offset); 13217 } 13218 13219 /// Compute the alignment and offset of a binary additive operator. 13220 static std::optional<std::pair<CharUnits, CharUnits>> 13221 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 13222 bool IsSub, ASTContext &Ctx) { 13223 QualType PointeeType = PtrE->getType()->getPointeeType(); 13224 13225 if (!PointeeType->isConstantSizeType()) 13226 return std::nullopt; 13227 13228 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 13229 13230 if (!P) 13231 return std::nullopt; 13232 13233 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 13234 if (std::optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 13235 CharUnits Offset = EltSize * IdxRes->getExtValue(); 13236 if (IsSub) 13237 Offset = -Offset; 13238 return std::make_pair(P->first, P->second + Offset); 13239 } 13240 13241 // If the integer expression isn't a constant expression, compute the lower 13242 // bound of the alignment using the alignment and offset of the pointer 13243 // expression and the element size. 13244 return std::make_pair( 13245 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 13246 CharUnits::Zero()); 13247 } 13248 13249 /// This helper function takes an lvalue expression and returns the alignment of 13250 /// a VarDecl and a constant offset from the VarDecl. 13251 std::optional<std::pair< 13252 CharUnits, 13253 CharUnits>> static getBaseAlignmentAndOffsetFromLValue(const Expr *E, 13254 ASTContext &Ctx) { 13255 E = E->IgnoreParens(); 13256 switch (E->getStmtClass()) { 13257 default: 13258 break; 13259 case Stmt::CStyleCastExprClass: 13260 case Stmt::CXXStaticCastExprClass: 13261 case Stmt::ImplicitCastExprClass: { 13262 auto *CE = cast<CastExpr>(E); 13263 const Expr *From = CE->getSubExpr(); 13264 switch (CE->getCastKind()) { 13265 default: 13266 break; 13267 case CK_NoOp: 13268 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13269 case CK_UncheckedDerivedToBase: 13270 case CK_DerivedToBase: { 13271 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13272 if (!P) 13273 break; 13274 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 13275 P->second, Ctx); 13276 } 13277 } 13278 break; 13279 } 13280 case Stmt::ArraySubscriptExprClass: { 13281 auto *ASE = cast<ArraySubscriptExpr>(E); 13282 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 13283 false, Ctx); 13284 } 13285 case Stmt::DeclRefExprClass: { 13286 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 13287 // FIXME: If VD is captured by copy or is an escaping __block variable, 13288 // use the alignment of VD's type. 13289 if (!VD->getType()->isReferenceType()) { 13290 // Dependent alignment cannot be resolved -> bail out. 13291 if (VD->hasDependentAlignment()) 13292 break; 13293 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 13294 } 13295 if (VD->hasInit()) 13296 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 13297 } 13298 break; 13299 } 13300 case Stmt::MemberExprClass: { 13301 auto *ME = cast<MemberExpr>(E); 13302 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 13303 if (!FD || FD->getType()->isReferenceType() || 13304 FD->getParent()->isInvalidDecl()) 13305 break; 13306 std::optional<std::pair<CharUnits, CharUnits>> P; 13307 if (ME->isArrow()) 13308 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 13309 else 13310 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 13311 if (!P) 13312 break; 13313 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 13314 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 13315 return std::make_pair(P->first, 13316 P->second + CharUnits::fromQuantity(Offset)); 13317 } 13318 case Stmt::UnaryOperatorClass: { 13319 auto *UO = cast<UnaryOperator>(E); 13320 switch (UO->getOpcode()) { 13321 default: 13322 break; 13323 case UO_Deref: 13324 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 13325 } 13326 break; 13327 } 13328 case Stmt::BinaryOperatorClass: { 13329 auto *BO = cast<BinaryOperator>(E); 13330 auto Opcode = BO->getOpcode(); 13331 switch (Opcode) { 13332 default: 13333 break; 13334 case BO_Comma: 13335 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 13336 } 13337 break; 13338 } 13339 } 13340 return std::nullopt; 13341 } 13342 13343 /// This helper function takes a pointer expression and returns the alignment of 13344 /// a VarDecl and a constant offset from the VarDecl. 13345 std::optional<std::pair< 13346 CharUnits, CharUnits>> static getBaseAlignmentAndOffsetFromPtr(const Expr 13347 *E, 13348 ASTContext 13349 &Ctx) { 13350 E = E->IgnoreParens(); 13351 switch (E->getStmtClass()) { 13352 default: 13353 break; 13354 case Stmt::CStyleCastExprClass: 13355 case Stmt::CXXStaticCastExprClass: 13356 case Stmt::ImplicitCastExprClass: { 13357 auto *CE = cast<CastExpr>(E); 13358 const Expr *From = CE->getSubExpr(); 13359 switch (CE->getCastKind()) { 13360 default: 13361 break; 13362 case CK_NoOp: 13363 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13364 case CK_ArrayToPointerDecay: 13365 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13366 case CK_UncheckedDerivedToBase: 13367 case CK_DerivedToBase: { 13368 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13369 if (!P) 13370 break; 13371 return getDerivedToBaseAlignmentAndOffset( 13372 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 13373 } 13374 } 13375 break; 13376 } 13377 case Stmt::CXXThisExprClass: { 13378 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 13379 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 13380 return std::make_pair(Alignment, CharUnits::Zero()); 13381 } 13382 case Stmt::UnaryOperatorClass: { 13383 auto *UO = cast<UnaryOperator>(E); 13384 if (UO->getOpcode() == UO_AddrOf) 13385 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 13386 break; 13387 } 13388 case Stmt::BinaryOperatorClass: { 13389 auto *BO = cast<BinaryOperator>(E); 13390 auto Opcode = BO->getOpcode(); 13391 switch (Opcode) { 13392 default: 13393 break; 13394 case BO_Add: 13395 case BO_Sub: { 13396 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 13397 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 13398 std::swap(LHS, RHS); 13399 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 13400 Ctx); 13401 } 13402 case BO_Comma: 13403 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 13404 } 13405 break; 13406 } 13407 } 13408 return std::nullopt; 13409 } 13410 13411 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 13412 // See if we can compute the alignment of a VarDecl and an offset from it. 13413 std::optional<std::pair<CharUnits, CharUnits>> P = 13414 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 13415 13416 if (P) 13417 return P->first.alignmentAtOffset(P->second); 13418 13419 // If that failed, return the type's alignment. 13420 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 13421 } 13422 13423 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13424 // This is actually a lot of work to potentially be doing on every 13425 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13426 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13427 return; 13428 13429 // Ignore dependent types. 13430 if (T->isDependentType() || Op->getType()->isDependentType()) 13431 return; 13432 13433 // Require that the destination be a pointer type. 13434 const PointerType *DestPtr = T->getAs<PointerType>(); 13435 if (!DestPtr) return; 13436 13437 // If the destination has alignment 1, we're done. 13438 QualType DestPointee = DestPtr->getPointeeType(); 13439 if (DestPointee->isIncompleteType()) return; 13440 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13441 if (DestAlign.isOne()) return; 13442 13443 // Require that the source be a pointer type. 13444 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13445 if (!SrcPtr) return; 13446 QualType SrcPointee = SrcPtr->getPointeeType(); 13447 13448 // Explicitly allow casts from cv void*. We already implicitly 13449 // allowed casts to cv void*, since they have alignment 1. 13450 // Also allow casts involving incomplete types, which implicitly 13451 // includes 'void'. 13452 if (SrcPointee->isIncompleteType()) return; 13453 13454 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 13455 13456 if (SrcAlign >= DestAlign) return; 13457 13458 Diag(TRange.getBegin(), diag::warn_cast_align) 13459 << Op->getType() << T 13460 << static_cast<unsigned>(SrcAlign.getQuantity()) 13461 << static_cast<unsigned>(DestAlign.getQuantity()) 13462 << TRange << Op->getSourceRange(); 13463 } 13464 13465 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13466 const ArraySubscriptExpr *ASE, 13467 bool AllowOnePastEnd, bool IndexNegated) { 13468 // Already diagnosed by the constant evaluator. 13469 if (isConstantEvaluatedContext()) 13470 return; 13471 13472 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13473 if (IndexExpr->isValueDependent()) 13474 return; 13475 13476 const Type *EffectiveType = 13477 BaseExpr->getType()->getPointeeOrArrayElementType(); 13478 BaseExpr = BaseExpr->IgnoreParenCasts(); 13479 const ConstantArrayType *ArrayTy = 13480 Context.getAsConstantArrayType(BaseExpr->getType()); 13481 13482 LangOptions::StrictFlexArraysLevelKind 13483 StrictFlexArraysLevel = getLangOpts().getStrictFlexArraysLevel(); 13484 13485 const Type *BaseType = 13486 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 13487 bool IsUnboundedArray = 13488 BaseType == nullptr || BaseExpr->isFlexibleArrayMemberLike( 13489 Context, StrictFlexArraysLevel, 13490 /*IgnoreTemplateOrMacroSubstitution=*/true); 13491 if (EffectiveType->isDependentType() || 13492 (!IsUnboundedArray && BaseType->isDependentType())) 13493 return; 13494 13495 Expr::EvalResult Result; 13496 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13497 return; 13498 13499 llvm::APSInt index = Result.Val.getInt(); 13500 if (IndexNegated) { 13501 index.setIsUnsigned(false); 13502 index = -index; 13503 } 13504 13505 if (IsUnboundedArray) { 13506 if (EffectiveType->isFunctionType()) 13507 return; 13508 if (index.isUnsigned() || !index.isNegative()) { 13509 const auto &ASTC = getASTContext(); 13510 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth( 13511 EffectiveType->getCanonicalTypeInternal().getAddressSpace()); 13512 if (index.getBitWidth() < AddrBits) 13513 index = index.zext(AddrBits); 13514 std::optional<CharUnits> ElemCharUnits = 13515 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 13516 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 13517 // pointer) bounds-checking isn't meaningful. 13518 if (!ElemCharUnits || ElemCharUnits->isZero()) 13519 return; 13520 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 13521 // If index has more active bits than address space, we already know 13522 // we have a bounds violation to warn about. Otherwise, compute 13523 // address of (index + 1)th element, and warn about bounds violation 13524 // only if that address exceeds address space. 13525 if (index.getActiveBits() <= AddrBits) { 13526 bool Overflow; 13527 llvm::APInt Product(index); 13528 Product += 1; 13529 Product = Product.umul_ov(ElemBytes, Overflow); 13530 if (!Overflow && Product.getActiveBits() <= AddrBits) 13531 return; 13532 } 13533 13534 // Need to compute max possible elements in address space, since that 13535 // is included in diag message. 13536 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 13537 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 13538 MaxElems += 1; 13539 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 13540 MaxElems = MaxElems.udiv(ElemBytes); 13541 13542 unsigned DiagID = 13543 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 13544 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 13545 13546 // Diag message shows element size in bits and in "bytes" (platform- 13547 // dependent CharUnits) 13548 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13549 PDiag(DiagID) 13550 << toString(index, 10, true) << AddrBits 13551 << (unsigned)ASTC.toBits(*ElemCharUnits) 13552 << toString(ElemBytes, 10, false) 13553 << toString(MaxElems, 10, false) 13554 << (unsigned)MaxElems.getLimitedValue(~0U) 13555 << IndexExpr->getSourceRange()); 13556 13557 const NamedDecl *ND = nullptr; 13558 // Try harder to find a NamedDecl to point at in the note. 13559 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13560 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13561 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13562 ND = DRE->getDecl(); 13563 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 13564 ND = ME->getMemberDecl(); 13565 13566 if (ND) 13567 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13568 PDiag(diag::note_array_declared_here) << ND); 13569 } 13570 return; 13571 } 13572 13573 if (index.isUnsigned() || !index.isNegative()) { 13574 // It is possible that the type of the base expression after 13575 // IgnoreParenCasts is incomplete, even though the type of the base 13576 // expression before IgnoreParenCasts is complete (see PR39746 for an 13577 // example). In this case we have no information about whether the array 13578 // access exceeds the array bounds. However we can still diagnose an array 13579 // access which precedes the array bounds. 13580 if (BaseType->isIncompleteType()) 13581 return; 13582 13583 llvm::APInt size = ArrayTy->getSize(); 13584 13585 if (BaseType != EffectiveType) { 13586 // Make sure we're comparing apples to apples when comparing index to 13587 // size. 13588 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13589 uint64_t array_typesize = Context.getTypeSize(BaseType); 13590 13591 // Handle ptrarith_typesize being zero, such as when casting to void*. 13592 // Use the size in bits (what "getTypeSize()" returns) rather than bytes. 13593 if (!ptrarith_typesize) 13594 ptrarith_typesize = Context.getCharWidth(); 13595 13596 if (ptrarith_typesize != array_typesize) { 13597 // There's a cast to a different size type involved. 13598 uint64_t ratio = array_typesize / ptrarith_typesize; 13599 13600 // TODO: Be smarter about handling cases where array_typesize is not a 13601 // multiple of ptrarith_typesize. 13602 if (ptrarith_typesize * ratio == array_typesize) 13603 size *= llvm::APInt(size.getBitWidth(), ratio); 13604 } 13605 } 13606 13607 if (size.getBitWidth() > index.getBitWidth()) 13608 index = index.zext(size.getBitWidth()); 13609 else if (size.getBitWidth() < index.getBitWidth()) 13610 size = size.zext(index.getBitWidth()); 13611 13612 // For array subscripting the index must be less than size, but for pointer 13613 // arithmetic also allow the index (offset) to be equal to size since 13614 // computing the next address after the end of the array is legal and 13615 // commonly done e.g. in C++ iterators and range-based for loops. 13616 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13617 return; 13618 13619 // Suppress the warning if the subscript expression (as identified by the 13620 // ']' location) and the index expression are both from macro expansions 13621 // within a system header. 13622 if (ASE) { 13623 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13624 ASE->getRBracketLoc()); 13625 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13626 SourceLocation IndexLoc = 13627 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13628 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13629 return; 13630 } 13631 } 13632 13633 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 13634 : diag::warn_ptr_arith_exceeds_bounds; 13635 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1; 13636 QualType CastMsgTy = ASE ? ASE->getLHS()->getType() : QualType(); 13637 13638 DiagRuntimeBehavior( 13639 BaseExpr->getBeginLoc(), BaseExpr, 13640 PDiag(DiagID) << toString(index, 10, true) << ArrayTy->desugar() 13641 << CastMsg << CastMsgTy << IndexExpr->getSourceRange()); 13642 } else { 13643 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13644 if (!ASE) { 13645 DiagID = diag::warn_ptr_arith_precedes_bounds; 13646 if (index.isNegative()) index = -index; 13647 } 13648 13649 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13650 PDiag(DiagID) << toString(index, 10, true) 13651 << IndexExpr->getSourceRange()); 13652 } 13653 13654 const NamedDecl *ND = nullptr; 13655 // Try harder to find a NamedDecl to point at in the note. 13656 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13657 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13658 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13659 ND = DRE->getDecl(); 13660 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 13661 ND = ME->getMemberDecl(); 13662 13663 if (ND) 13664 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13665 PDiag(diag::note_array_declared_here) << ND); 13666 } 13667 13668 void Sema::CheckArrayAccess(const Expr *expr) { 13669 int AllowOnePastEnd = 0; 13670 while (expr) { 13671 expr = expr->IgnoreParenImpCasts(); 13672 switch (expr->getStmtClass()) { 13673 case Stmt::ArraySubscriptExprClass: { 13674 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13675 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13676 AllowOnePastEnd > 0); 13677 expr = ASE->getBase(); 13678 break; 13679 } 13680 case Stmt::MemberExprClass: { 13681 expr = cast<MemberExpr>(expr)->getBase(); 13682 break; 13683 } 13684 case Stmt::ArraySectionExprClass: { 13685 const ArraySectionExpr *ASE = cast<ArraySectionExpr>(expr); 13686 // FIXME: We should probably be checking all of the elements to the 13687 // 'length' here as well. 13688 if (ASE->getLowerBound()) 13689 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13690 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13691 return; 13692 } 13693 case Stmt::UnaryOperatorClass: { 13694 // Only unwrap the * and & unary operators 13695 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13696 expr = UO->getSubExpr(); 13697 switch (UO->getOpcode()) { 13698 case UO_AddrOf: 13699 AllowOnePastEnd++; 13700 break; 13701 case UO_Deref: 13702 AllowOnePastEnd--; 13703 break; 13704 default: 13705 return; 13706 } 13707 break; 13708 } 13709 case Stmt::ConditionalOperatorClass: { 13710 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13711 if (const Expr *lhs = cond->getLHS()) 13712 CheckArrayAccess(lhs); 13713 if (const Expr *rhs = cond->getRHS()) 13714 CheckArrayAccess(rhs); 13715 return; 13716 } 13717 case Stmt::CXXOperatorCallExprClass: { 13718 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13719 for (const auto *Arg : OCE->arguments()) 13720 CheckArrayAccess(Arg); 13721 return; 13722 } 13723 default: 13724 return; 13725 } 13726 } 13727 } 13728 13729 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 13730 Expr *RHS, bool isProperty) { 13731 // Check if RHS is an Objective-C object literal, which also can get 13732 // immediately zapped in a weak reference. Note that we explicitly 13733 // allow ObjCStringLiterals, since those are designed to never really die. 13734 RHS = RHS->IgnoreParenImpCasts(); 13735 13736 // This enum needs to match with the 'select' in 13737 // warn_objc_arc_literal_assign (off-by-1). 13738 SemaObjC::ObjCLiteralKind Kind = S.ObjC().CheckLiteralKind(RHS); 13739 if (Kind == SemaObjC::LK_String || Kind == SemaObjC::LK_None) 13740 return false; 13741 13742 S.Diag(Loc, diag::warn_arc_literal_assign) 13743 << (unsigned) Kind 13744 << (isProperty ? 0 : 1) 13745 << RHS->getSourceRange(); 13746 13747 return true; 13748 } 13749 13750 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 13751 Qualifiers::ObjCLifetime LT, 13752 Expr *RHS, bool isProperty) { 13753 // Strip off any implicit cast added to get to the one ARC-specific. 13754 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13755 if (cast->getCastKind() == CK_ARCConsumeObject) { 13756 S.Diag(Loc, diag::warn_arc_retained_assign) 13757 << (LT == Qualifiers::OCL_ExplicitNone) 13758 << (isProperty ? 0 : 1) 13759 << RHS->getSourceRange(); 13760 return true; 13761 } 13762 RHS = cast->getSubExpr(); 13763 } 13764 13765 if (LT == Qualifiers::OCL_Weak && 13766 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 13767 return true; 13768 13769 return false; 13770 } 13771 13772 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 13773 QualType LHS, Expr *RHS) { 13774 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 13775 13776 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 13777 return false; 13778 13779 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 13780 return true; 13781 13782 return false; 13783 } 13784 13785 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 13786 Expr *LHS, Expr *RHS) { 13787 QualType LHSType; 13788 // PropertyRef on LHS type need be directly obtained from 13789 // its declaration as it has a PseudoType. 13790 ObjCPropertyRefExpr *PRE 13791 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 13792 if (PRE && !PRE->isImplicitProperty()) { 13793 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13794 if (PD) 13795 LHSType = PD->getType(); 13796 } 13797 13798 if (LHSType.isNull()) 13799 LHSType = LHS->getType(); 13800 13801 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 13802 13803 if (LT == Qualifiers::OCL_Weak) { 13804 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 13805 getCurFunction()->markSafeWeakUse(LHS); 13806 } 13807 13808 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 13809 return; 13810 13811 // FIXME. Check for other life times. 13812 if (LT != Qualifiers::OCL_None) 13813 return; 13814 13815 if (PRE) { 13816 if (PRE->isImplicitProperty()) 13817 return; 13818 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13819 if (!PD) 13820 return; 13821 13822 unsigned Attributes = PD->getPropertyAttributes(); 13823 if (Attributes & ObjCPropertyAttribute::kind_assign) { 13824 // when 'assign' attribute was not explicitly specified 13825 // by user, ignore it and rely on property type itself 13826 // for lifetime info. 13827 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 13828 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 13829 LHSType->isObjCRetainableType()) 13830 return; 13831 13832 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13833 if (cast->getCastKind() == CK_ARCConsumeObject) { 13834 Diag(Loc, diag::warn_arc_retained_property_assign) 13835 << RHS->getSourceRange(); 13836 return; 13837 } 13838 RHS = cast->getSubExpr(); 13839 } 13840 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 13841 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 13842 return; 13843 } 13844 } 13845 } 13846 13847 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 13848 13849 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 13850 SourceLocation StmtLoc, 13851 const NullStmt *Body) { 13852 // Do not warn if the body is a macro that expands to nothing, e.g: 13853 // 13854 // #define CALL(x) 13855 // if (condition) 13856 // CALL(0); 13857 if (Body->hasLeadingEmptyMacro()) 13858 return false; 13859 13860 // Get line numbers of statement and body. 13861 bool StmtLineInvalid; 13862 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 13863 &StmtLineInvalid); 13864 if (StmtLineInvalid) 13865 return false; 13866 13867 bool BodyLineInvalid; 13868 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 13869 &BodyLineInvalid); 13870 if (BodyLineInvalid) 13871 return false; 13872 13873 // Warn if null statement and body are on the same line. 13874 if (StmtLine != BodyLine) 13875 return false; 13876 13877 return true; 13878 } 13879 13880 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 13881 const Stmt *Body, 13882 unsigned DiagID) { 13883 // Since this is a syntactic check, don't emit diagnostic for template 13884 // instantiations, this just adds noise. 13885 if (CurrentInstantiationScope) 13886 return; 13887 13888 // The body should be a null statement. 13889 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13890 if (!NBody) 13891 return; 13892 13893 // Do the usual checks. 13894 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13895 return; 13896 13897 Diag(NBody->getSemiLoc(), DiagID); 13898 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13899 } 13900 13901 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 13902 const Stmt *PossibleBody) { 13903 assert(!CurrentInstantiationScope); // Ensured by caller 13904 13905 SourceLocation StmtLoc; 13906 const Stmt *Body; 13907 unsigned DiagID; 13908 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 13909 StmtLoc = FS->getRParenLoc(); 13910 Body = FS->getBody(); 13911 DiagID = diag::warn_empty_for_body; 13912 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 13913 StmtLoc = WS->getRParenLoc(); 13914 Body = WS->getBody(); 13915 DiagID = diag::warn_empty_while_body; 13916 } else 13917 return; // Neither `for' nor `while'. 13918 13919 // The body should be a null statement. 13920 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13921 if (!NBody) 13922 return; 13923 13924 // Skip expensive checks if diagnostic is disabled. 13925 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 13926 return; 13927 13928 // Do the usual checks. 13929 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13930 return; 13931 13932 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13933 // noise level low, emit diagnostics only if for/while is followed by a 13934 // CompoundStmt, e.g.: 13935 // for (int i = 0; i < n; i++); 13936 // { 13937 // a(i); 13938 // } 13939 // or if for/while is followed by a statement with more indentation 13940 // than for/while itself: 13941 // for (int i = 0; i < n; i++); 13942 // a(i); 13943 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13944 if (!ProbableTypo) { 13945 bool BodyColInvalid; 13946 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13947 PossibleBody->getBeginLoc(), &BodyColInvalid); 13948 if (BodyColInvalid) 13949 return; 13950 13951 bool StmtColInvalid; 13952 unsigned StmtCol = 13953 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13954 if (StmtColInvalid) 13955 return; 13956 13957 if (BodyCol > StmtCol) 13958 ProbableTypo = true; 13959 } 13960 13961 if (ProbableTypo) { 13962 Diag(NBody->getSemiLoc(), DiagID); 13963 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13964 } 13965 } 13966 13967 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13968 13969 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13970 SourceLocation OpLoc) { 13971 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13972 return; 13973 13974 if (inTemplateInstantiation()) 13975 return; 13976 13977 // Strip parens and casts away. 13978 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13979 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13980 13981 // Check for a call to std::move or for a static_cast<T&&>(..) to an xvalue 13982 // which we can treat as an inlined std::move 13983 if (const auto *CE = dyn_cast<CallExpr>(RHSExpr); 13984 CE && CE->getNumArgs() == 1 && CE->isCallToStdMove()) 13985 RHSExpr = CE->getArg(0); 13986 else if (const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr); 13987 CXXSCE && CXXSCE->isXValue()) 13988 RHSExpr = CXXSCE->getSubExpr(); 13989 else 13990 return; 13991 13992 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13993 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13994 13995 // Two DeclRefExpr's, check that the decls are the same. 13996 if (LHSDeclRef && RHSDeclRef) { 13997 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13998 return; 13999 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14000 RHSDeclRef->getDecl()->getCanonicalDecl()) 14001 return; 14002 14003 auto D = Diag(OpLoc, diag::warn_self_move) 14004 << LHSExpr->getType() << LHSExpr->getSourceRange() 14005 << RHSExpr->getSourceRange(); 14006 if (const FieldDecl *F = 14007 getSelfAssignmentClassMemberCandidate(RHSDeclRef->getDecl())) 14008 D << 1 << F 14009 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->"); 14010 else 14011 D << 0; 14012 return; 14013 } 14014 14015 // Member variables require a different approach to check for self moves. 14016 // MemberExpr's are the same if every nested MemberExpr refers to the same 14017 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14018 // the base Expr's are CXXThisExpr's. 14019 const Expr *LHSBase = LHSExpr; 14020 const Expr *RHSBase = RHSExpr; 14021 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14022 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14023 if (!LHSME || !RHSME) 14024 return; 14025 14026 while (LHSME && RHSME) { 14027 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14028 RHSME->getMemberDecl()->getCanonicalDecl()) 14029 return; 14030 14031 LHSBase = LHSME->getBase(); 14032 RHSBase = RHSME->getBase(); 14033 LHSME = dyn_cast<MemberExpr>(LHSBase); 14034 RHSME = dyn_cast<MemberExpr>(RHSBase); 14035 } 14036 14037 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14038 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14039 if (LHSDeclRef && RHSDeclRef) { 14040 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14041 return; 14042 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14043 RHSDeclRef->getDecl()->getCanonicalDecl()) 14044 return; 14045 14046 Diag(OpLoc, diag::warn_self_move) 14047 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange() 14048 << RHSExpr->getSourceRange(); 14049 return; 14050 } 14051 14052 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14053 Diag(OpLoc, diag::warn_self_move) 14054 << LHSExpr->getType() << 0 << LHSExpr->getSourceRange() 14055 << RHSExpr->getSourceRange(); 14056 } 14057 14058 //===--- Layout compatibility ----------------------------------------------// 14059 14060 static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2); 14061 14062 /// Check if two enumeration types are layout-compatible. 14063 static bool isLayoutCompatible(const ASTContext &C, const EnumDecl *ED1, 14064 const EnumDecl *ED2) { 14065 // C++11 [dcl.enum] p8: 14066 // Two enumeration types are layout-compatible if they have the same 14067 // underlying type. 14068 return ED1->isComplete() && ED2->isComplete() && 14069 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14070 } 14071 14072 /// Check if two fields are layout-compatible. 14073 /// Can be used on union members, which are exempt from alignment requirement 14074 /// of common initial sequence. 14075 static bool isLayoutCompatible(const ASTContext &C, const FieldDecl *Field1, 14076 const FieldDecl *Field2, 14077 bool AreUnionMembers = false) { 14078 [[maybe_unused]] const Type *Field1Parent = 14079 Field1->getParent()->getTypeForDecl(); 14080 [[maybe_unused]] const Type *Field2Parent = 14081 Field2->getParent()->getTypeForDecl(); 14082 assert(((Field1Parent->isStructureOrClassType() && 14083 Field2Parent->isStructureOrClassType()) || 14084 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) && 14085 "Can't evaluate layout compatibility between a struct field and a " 14086 "union field."); 14087 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) || 14088 (AreUnionMembers && Field1Parent->isUnionType())) && 14089 "AreUnionMembers should be 'true' for union fields (only)."); 14090 14091 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14092 return false; 14093 14094 if (Field1->isBitField() != Field2->isBitField()) 14095 return false; 14096 14097 if (Field1->isBitField()) { 14098 // Make sure that the bit-fields are the same length. 14099 unsigned Bits1 = Field1->getBitWidthValue(); 14100 unsigned Bits2 = Field2->getBitWidthValue(); 14101 14102 if (Bits1 != Bits2) 14103 return false; 14104 } 14105 14106 if (Field1->hasAttr<clang::NoUniqueAddressAttr>() || 14107 Field2->hasAttr<clang::NoUniqueAddressAttr>()) 14108 return false; 14109 14110 if (!AreUnionMembers && 14111 Field1->getMaxAlignment() != Field2->getMaxAlignment()) 14112 return false; 14113 14114 return true; 14115 } 14116 14117 /// Check if two standard-layout structs are layout-compatible. 14118 /// (C++11 [class.mem] p17) 14119 static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1, 14120 const RecordDecl *RD2) { 14121 // Get to the class where the fields are declared 14122 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) 14123 RD1 = D1CXX->getStandardLayoutBaseWithFields(); 14124 14125 if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) 14126 RD2 = D2CXX->getStandardLayoutBaseWithFields(); 14127 14128 // Check the fields. 14129 return llvm::equal(RD1->fields(), RD2->fields(), 14130 [&C](const FieldDecl *F1, const FieldDecl *F2) -> bool { 14131 return isLayoutCompatible(C, F1, F2); 14132 }); 14133 } 14134 14135 /// Check if two standard-layout unions are layout-compatible. 14136 /// (C++11 [class.mem] p18) 14137 static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1, 14138 const RecordDecl *RD2) { 14139 llvm::SmallPtrSet<const FieldDecl *, 8> UnmatchedFields; 14140 for (auto *Field2 : RD2->fields()) 14141 UnmatchedFields.insert(Field2); 14142 14143 for (auto *Field1 : RD1->fields()) { 14144 auto I = UnmatchedFields.begin(); 14145 auto E = UnmatchedFields.end(); 14146 14147 for ( ; I != E; ++I) { 14148 if (isLayoutCompatible(C, Field1, *I, /*IsUnionMember=*/true)) { 14149 bool Result = UnmatchedFields.erase(*I); 14150 (void) Result; 14151 assert(Result); 14152 break; 14153 } 14154 } 14155 if (I == E) 14156 return false; 14157 } 14158 14159 return UnmatchedFields.empty(); 14160 } 14161 14162 static bool isLayoutCompatible(const ASTContext &C, const RecordDecl *RD1, 14163 const RecordDecl *RD2) { 14164 if (RD1->isUnion() != RD2->isUnion()) 14165 return false; 14166 14167 if (RD1->isUnion()) 14168 return isLayoutCompatibleUnion(C, RD1, RD2); 14169 else 14170 return isLayoutCompatibleStruct(C, RD1, RD2); 14171 } 14172 14173 /// Check if two types are layout-compatible in C++11 sense. 14174 static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2) { 14175 if (T1.isNull() || T2.isNull()) 14176 return false; 14177 14178 // C++20 [basic.types] p11: 14179 // Two types cv1 T1 and cv2 T2 are layout-compatible types 14180 // if T1 and T2 are the same type, layout-compatible enumerations (9.7.1), 14181 // or layout-compatible standard-layout class types (11.4). 14182 T1 = T1.getCanonicalType().getUnqualifiedType(); 14183 T2 = T2.getCanonicalType().getUnqualifiedType(); 14184 14185 if (C.hasSameType(T1, T2)) 14186 return true; 14187 14188 const Type::TypeClass TC1 = T1->getTypeClass(); 14189 const Type::TypeClass TC2 = T2->getTypeClass(); 14190 14191 if (TC1 != TC2) 14192 return false; 14193 14194 if (TC1 == Type::Enum) { 14195 return isLayoutCompatible(C, 14196 cast<EnumType>(T1)->getDecl(), 14197 cast<EnumType>(T2)->getDecl()); 14198 } else if (TC1 == Type::Record) { 14199 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14200 return false; 14201 14202 return isLayoutCompatible(C, 14203 cast<RecordType>(T1)->getDecl(), 14204 cast<RecordType>(T2)->getDecl()); 14205 } 14206 14207 return false; 14208 } 14209 14210 bool Sema::IsLayoutCompatible(QualType T1, QualType T2) const { 14211 return isLayoutCompatible(getASTContext(), T1, T2); 14212 } 14213 14214 //===-------------- Pointer interconvertibility ----------------------------// 14215 14216 bool Sema::IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base, 14217 const TypeSourceInfo *Derived) { 14218 QualType BaseT = Base->getType()->getCanonicalTypeUnqualified(); 14219 QualType DerivedT = Derived->getType()->getCanonicalTypeUnqualified(); 14220 14221 if (BaseT->isStructureOrClassType() && DerivedT->isStructureOrClassType() && 14222 getASTContext().hasSameType(BaseT, DerivedT)) 14223 return true; 14224 14225 if (!IsDerivedFrom(Derived->getTypeLoc().getBeginLoc(), DerivedT, BaseT)) 14226 return false; 14227 14228 // Per [basic.compound]/4.3, containing object has to be standard-layout. 14229 if (DerivedT->getAsCXXRecordDecl()->isStandardLayout()) 14230 return true; 14231 14232 return false; 14233 } 14234 14235 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14236 14237 /// Given a type tag expression find the type tag itself. 14238 /// 14239 /// \param TypeExpr Type tag expression, as it appears in user's code. 14240 /// 14241 /// \param VD Declaration of an identifier that appears in a type tag. 14242 /// 14243 /// \param MagicValue Type tag magic value. 14244 /// 14245 /// \param isConstantEvaluated whether the evalaution should be performed in 14246 14247 /// constant context. 14248 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14249 const ValueDecl **VD, uint64_t *MagicValue, 14250 bool isConstantEvaluated) { 14251 while(true) { 14252 if (!TypeExpr) 14253 return false; 14254 14255 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14256 14257 switch (TypeExpr->getStmtClass()) { 14258 case Stmt::UnaryOperatorClass: { 14259 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14260 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14261 TypeExpr = UO->getSubExpr(); 14262 continue; 14263 } 14264 return false; 14265 } 14266 14267 case Stmt::DeclRefExprClass: { 14268 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14269 *VD = DRE->getDecl(); 14270 return true; 14271 } 14272 14273 case Stmt::IntegerLiteralClass: { 14274 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14275 llvm::APInt MagicValueAPInt = IL->getValue(); 14276 if (MagicValueAPInt.getActiveBits() <= 64) { 14277 *MagicValue = MagicValueAPInt.getZExtValue(); 14278 return true; 14279 } else 14280 return false; 14281 } 14282 14283 case Stmt::BinaryConditionalOperatorClass: 14284 case Stmt::ConditionalOperatorClass: { 14285 const AbstractConditionalOperator *ACO = 14286 cast<AbstractConditionalOperator>(TypeExpr); 14287 bool Result; 14288 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14289 isConstantEvaluated)) { 14290 if (Result) 14291 TypeExpr = ACO->getTrueExpr(); 14292 else 14293 TypeExpr = ACO->getFalseExpr(); 14294 continue; 14295 } 14296 return false; 14297 } 14298 14299 case Stmt::BinaryOperatorClass: { 14300 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14301 if (BO->getOpcode() == BO_Comma) { 14302 TypeExpr = BO->getRHS(); 14303 continue; 14304 } 14305 return false; 14306 } 14307 14308 default: 14309 return false; 14310 } 14311 } 14312 } 14313 14314 /// Retrieve the C type corresponding to type tag TypeExpr. 14315 /// 14316 /// \param TypeExpr Expression that specifies a type tag. 14317 /// 14318 /// \param MagicValues Registered magic values. 14319 /// 14320 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14321 /// kind. 14322 /// 14323 /// \param TypeInfo Information about the corresponding C type. 14324 /// 14325 /// \param isConstantEvaluated whether the evalaution should be performed in 14326 /// constant context. 14327 /// 14328 /// \returns true if the corresponding C type was found. 14329 static bool GetMatchingCType( 14330 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14331 const ASTContext &Ctx, 14332 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14333 *MagicValues, 14334 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14335 bool isConstantEvaluated) { 14336 FoundWrongKind = false; 14337 14338 // Variable declaration that has type_tag_for_datatype attribute. 14339 const ValueDecl *VD = nullptr; 14340 14341 uint64_t MagicValue; 14342 14343 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14344 return false; 14345 14346 if (VD) { 14347 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14348 if (I->getArgumentKind() != ArgumentKind) { 14349 FoundWrongKind = true; 14350 return false; 14351 } 14352 TypeInfo.Type = I->getMatchingCType(); 14353 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14354 TypeInfo.MustBeNull = I->getMustBeNull(); 14355 return true; 14356 } 14357 return false; 14358 } 14359 14360 if (!MagicValues) 14361 return false; 14362 14363 llvm::DenseMap<Sema::TypeTagMagicValue, 14364 Sema::TypeTagData>::const_iterator I = 14365 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14366 if (I == MagicValues->end()) 14367 return false; 14368 14369 TypeInfo = I->second; 14370 return true; 14371 } 14372 14373 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14374 uint64_t MagicValue, QualType Type, 14375 bool LayoutCompatible, 14376 bool MustBeNull) { 14377 if (!TypeTagForDatatypeMagicValues) 14378 TypeTagForDatatypeMagicValues.reset( 14379 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14380 14381 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14382 (*TypeTagForDatatypeMagicValues)[Magic] = 14383 TypeTagData(Type, LayoutCompatible, MustBeNull); 14384 } 14385 14386 static bool IsSameCharType(QualType T1, QualType T2) { 14387 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14388 if (!BT1) 14389 return false; 14390 14391 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14392 if (!BT2) 14393 return false; 14394 14395 BuiltinType::Kind T1Kind = BT1->getKind(); 14396 BuiltinType::Kind T2Kind = BT2->getKind(); 14397 14398 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14399 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14400 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14401 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14402 } 14403 14404 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14405 const ArrayRef<const Expr *> ExprArgs, 14406 SourceLocation CallSiteLoc) { 14407 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14408 bool IsPointerAttr = Attr->getIsPointer(); 14409 14410 // Retrieve the argument representing the 'type_tag'. 14411 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14412 if (TypeTagIdxAST >= ExprArgs.size()) { 14413 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14414 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14415 return; 14416 } 14417 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14418 bool FoundWrongKind; 14419 TypeTagData TypeInfo; 14420 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14421 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14422 TypeInfo, isConstantEvaluatedContext())) { 14423 if (FoundWrongKind) 14424 Diag(TypeTagExpr->getExprLoc(), 14425 diag::warn_type_tag_for_datatype_wrong_kind) 14426 << TypeTagExpr->getSourceRange(); 14427 return; 14428 } 14429 14430 // Retrieve the argument representing the 'arg_idx'. 14431 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14432 if (ArgumentIdxAST >= ExprArgs.size()) { 14433 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14434 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14435 return; 14436 } 14437 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14438 if (IsPointerAttr) { 14439 // Skip implicit cast of pointer to `void *' (as a function argument). 14440 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14441 if (ICE->getType()->isVoidPointerType() && 14442 ICE->getCastKind() == CK_BitCast) 14443 ArgumentExpr = ICE->getSubExpr(); 14444 } 14445 QualType ArgumentType = ArgumentExpr->getType(); 14446 14447 // Passing a `void*' pointer shouldn't trigger a warning. 14448 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14449 return; 14450 14451 if (TypeInfo.MustBeNull) { 14452 // Type tag with matching void type requires a null pointer. 14453 if (!ArgumentExpr->isNullPointerConstant(Context, 14454 Expr::NPC_ValueDependentIsNotNull)) { 14455 Diag(ArgumentExpr->getExprLoc(), 14456 diag::warn_type_safety_null_pointer_required) 14457 << ArgumentKind->getName() 14458 << ArgumentExpr->getSourceRange() 14459 << TypeTagExpr->getSourceRange(); 14460 } 14461 return; 14462 } 14463 14464 QualType RequiredType = TypeInfo.Type; 14465 if (IsPointerAttr) 14466 RequiredType = Context.getPointerType(RequiredType); 14467 14468 bool mismatch = false; 14469 if (!TypeInfo.LayoutCompatible) { 14470 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14471 14472 // C++11 [basic.fundamental] p1: 14473 // Plain char, signed char, and unsigned char are three distinct types. 14474 // 14475 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14476 // char' depending on the current char signedness mode. 14477 if (mismatch) 14478 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14479 RequiredType->getPointeeType())) || 14480 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14481 mismatch = false; 14482 } else 14483 if (IsPointerAttr) 14484 mismatch = !isLayoutCompatible(Context, 14485 ArgumentType->getPointeeType(), 14486 RequiredType->getPointeeType()); 14487 else 14488 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14489 14490 if (mismatch) 14491 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14492 << ArgumentType << ArgumentKind 14493 << TypeInfo.LayoutCompatible << RequiredType 14494 << ArgumentExpr->getSourceRange() 14495 << TypeTagExpr->getSourceRange(); 14496 } 14497 14498 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14499 CharUnits Alignment) { 14500 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14501 } 14502 14503 void Sema::DiagnoseMisalignedMembers() { 14504 for (MisalignedMember &m : MisalignedMembers) { 14505 const NamedDecl *ND = m.RD; 14506 if (ND->getName().empty()) { 14507 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14508 ND = TD; 14509 } 14510 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14511 << m.MD << ND << m.E->getSourceRange(); 14512 } 14513 MisalignedMembers.clear(); 14514 } 14515 14516 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14517 E = E->IgnoreParens(); 14518 if (!T->isPointerType() && !T->isIntegerType() && !T->isDependentType()) 14519 return; 14520 if (isa<UnaryOperator>(E) && 14521 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14522 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14523 if (isa<MemberExpr>(Op)) { 14524 auto *MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14525 if (MA != MisalignedMembers.end() && 14526 (T->isDependentType() || T->isIntegerType() || 14527 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14528 Context.getTypeAlignInChars( 14529 T->getPointeeType()) <= MA->Alignment)))) 14530 MisalignedMembers.erase(MA); 14531 } 14532 } 14533 } 14534 14535 void Sema::RefersToMemberWithReducedAlignment( 14536 Expr *E, 14537 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14538 Action) { 14539 const auto *ME = dyn_cast<MemberExpr>(E); 14540 if (!ME) 14541 return; 14542 14543 // No need to check expressions with an __unaligned-qualified type. 14544 if (E->getType().getQualifiers().hasUnaligned()) 14545 return; 14546 14547 // For a chain of MemberExpr like "a.b.c.d" this list 14548 // will keep FieldDecl's like [d, c, b]. 14549 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14550 const MemberExpr *TopME = nullptr; 14551 bool AnyIsPacked = false; 14552 do { 14553 QualType BaseType = ME->getBase()->getType(); 14554 if (BaseType->isDependentType()) 14555 return; 14556 if (ME->isArrow()) 14557 BaseType = BaseType->getPointeeType(); 14558 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 14559 if (RD->isInvalidDecl()) 14560 return; 14561 14562 ValueDecl *MD = ME->getMemberDecl(); 14563 auto *FD = dyn_cast<FieldDecl>(MD); 14564 // We do not care about non-data members. 14565 if (!FD || FD->isInvalidDecl()) 14566 return; 14567 14568 AnyIsPacked = 14569 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14570 ReverseMemberChain.push_back(FD); 14571 14572 TopME = ME; 14573 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14574 } while (ME); 14575 assert(TopME && "We did not compute a topmost MemberExpr!"); 14576 14577 // Not the scope of this diagnostic. 14578 if (!AnyIsPacked) 14579 return; 14580 14581 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14582 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14583 // TODO: The innermost base of the member expression may be too complicated. 14584 // For now, just disregard these cases. This is left for future 14585 // improvement. 14586 if (!DRE && !isa<CXXThisExpr>(TopBase)) 14587 return; 14588 14589 // Alignment expected by the whole expression. 14590 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 14591 14592 // No need to do anything else with this case. 14593 if (ExpectedAlignment.isOne()) 14594 return; 14595 14596 // Synthesize offset of the whole access. 14597 CharUnits Offset; 14598 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain)) 14599 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD)); 14600 14601 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 14602 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 14603 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 14604 14605 // The base expression of the innermost MemberExpr may give 14606 // stronger guarantees than the class containing the member. 14607 if (DRE && !TopME->isArrow()) { 14608 const ValueDecl *VD = DRE->getDecl(); 14609 if (!VD->getType()->isReferenceType()) 14610 CompleteObjectAlignment = 14611 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 14612 } 14613 14614 // Check if the synthesized offset fulfills the alignment. 14615 if (Offset % ExpectedAlignment != 0 || 14616 // It may fulfill the offset it but the effective alignment may still be 14617 // lower than the expected expression alignment. 14618 CompleteObjectAlignment < ExpectedAlignment) { 14619 // If this happens, we want to determine a sensible culprit of this. 14620 // Intuitively, watching the chain of member expressions from right to 14621 // left, we start with the required alignment (as required by the field 14622 // type) but some packed attribute in that chain has reduced the alignment. 14623 // It may happen that another packed structure increases it again. But if 14624 // we are here such increase has not been enough. So pointing the first 14625 // FieldDecl that either is packed or else its RecordDecl is, 14626 // seems reasonable. 14627 FieldDecl *FD = nullptr; 14628 CharUnits Alignment; 14629 for (FieldDecl *FDI : ReverseMemberChain) { 14630 if (FDI->hasAttr<PackedAttr>() || 14631 FDI->getParent()->hasAttr<PackedAttr>()) { 14632 FD = FDI; 14633 Alignment = std::min( 14634 Context.getTypeAlignInChars(FD->getType()), 14635 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 14636 break; 14637 } 14638 } 14639 assert(FD && "We did not find a packed FieldDecl!"); 14640 Action(E, FD->getParent(), FD, Alignment); 14641 } 14642 } 14643 14644 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 14645 using namespace std::placeholders; 14646 14647 RefersToMemberWithReducedAlignment( 14648 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 14649 _2, _3, _4)); 14650 } 14651 14652 // Performs a similar job to Sema::UsualUnaryConversions, but without any 14653 // implicit promotion of integral/enumeration types. 14654 static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E) { 14655 // First, convert to an r-value. 14656 ExprResult Res = S.DefaultFunctionArrayLvalueConversion(E); 14657 if (Res.isInvalid()) 14658 return ExprError(); 14659 14660 // Promote floating-point types. 14661 return S.UsualUnaryFPConversions(Res.get()); 14662 } 14663 14664 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) { 14665 if (checkArgCount(TheCall, 1)) 14666 return true; 14667 14668 ExprResult A = BuiltinVectorMathConversions(*this, TheCall->getArg(0)); 14669 if (A.isInvalid()) 14670 return true; 14671 14672 TheCall->setArg(0, A.get()); 14673 QualType TyA = A.get()->getType(); 14674 14675 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA, 1)) 14676 return true; 14677 14678 TheCall->setType(TyA); 14679 return false; 14680 } 14681 14682 bool Sema::BuiltinElementwiseMath(CallExpr *TheCall, bool FPOnly) { 14683 if (auto Res = BuiltinVectorMath(TheCall, FPOnly); Res.has_value()) { 14684 TheCall->setType(*Res); 14685 return false; 14686 } 14687 return true; 14688 } 14689 14690 bool Sema::BuiltinVectorToScalarMath(CallExpr *TheCall) { 14691 std::optional<QualType> Res = BuiltinVectorMath(TheCall); 14692 if (!Res) 14693 return true; 14694 14695 if (auto *VecTy0 = (*Res)->getAs<VectorType>()) 14696 TheCall->setType(VecTy0->getElementType()); 14697 else 14698 TheCall->setType(*Res); 14699 14700 return false; 14701 } 14702 14703 static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS, 14704 SourceLocation Loc) { 14705 QualType L = LHS->getEnumCoercedType(S.Context), 14706 R = RHS->getEnumCoercedType(S.Context); 14707 if (L->isUnscopedEnumerationType() && R->isUnscopedEnumerationType() && 14708 !S.Context.hasSameUnqualifiedType(L, R)) { 14709 return S.Diag(Loc, diag::err_conv_mixed_enum_types_cxx26) 14710 << LHS->getSourceRange() << RHS->getSourceRange() 14711 << /*Arithmetic Between*/ 0 << L << R; 14712 } 14713 return false; 14714 } 14715 14716 std::optional<QualType> Sema::BuiltinVectorMath(CallExpr *TheCall, 14717 bool FPOnly) { 14718 if (checkArgCount(TheCall, 2)) 14719 return std::nullopt; 14720 14721 if (checkBuiltinVectorMathMixedEnums( 14722 *this, TheCall->getArg(0), TheCall->getArg(1), TheCall->getExprLoc())) 14723 return std::nullopt; 14724 14725 Expr *Args[2]; 14726 for (int I = 0; I < 2; ++I) { 14727 ExprResult Converted = 14728 BuiltinVectorMathConversions(*this, TheCall->getArg(I)); 14729 if (Converted.isInvalid()) 14730 return std::nullopt; 14731 Args[I] = Converted.get(); 14732 } 14733 14734 SourceLocation LocA = Args[0]->getBeginLoc(); 14735 QualType TyA = Args[0]->getType(); 14736 QualType TyB = Args[1]->getType(); 14737 14738 if (TyA.getCanonicalType() != TyB.getCanonicalType()) { 14739 Diag(LocA, diag::err_typecheck_call_different_arg_types) << TyA << TyB; 14740 return std::nullopt; 14741 } 14742 14743 if (FPOnly) { 14744 if (checkFPMathBuiltinElementType(*this, LocA, TyA, 1)) 14745 return std::nullopt; 14746 } else { 14747 if (checkMathBuiltinElementType(*this, LocA, TyA, 1)) 14748 return std::nullopt; 14749 } 14750 14751 TheCall->setArg(0, Args[0]); 14752 TheCall->setArg(1, Args[1]); 14753 return TyA; 14754 } 14755 14756 bool Sema::BuiltinElementwiseTernaryMath(CallExpr *TheCall, 14757 bool CheckForFloatArgs) { 14758 if (checkArgCount(TheCall, 3)) 14759 return true; 14760 14761 SourceLocation Loc = TheCall->getExprLoc(); 14762 if (checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(0), 14763 TheCall->getArg(1), Loc) || 14764 checkBuiltinVectorMathMixedEnums(*this, TheCall->getArg(1), 14765 TheCall->getArg(2), Loc)) 14766 return true; 14767 14768 Expr *Args[3]; 14769 for (int I = 0; I < 3; ++I) { 14770 ExprResult Converted = 14771 BuiltinVectorMathConversions(*this, TheCall->getArg(I)); 14772 if (Converted.isInvalid()) 14773 return true; 14774 Args[I] = Converted.get(); 14775 } 14776 14777 if (CheckForFloatArgs) { 14778 int ArgOrdinal = 1; 14779 for (Expr *Arg : Args) { 14780 if (checkFPMathBuiltinElementType(*this, Arg->getBeginLoc(), 14781 Arg->getType(), ArgOrdinal++)) 14782 return true; 14783 } 14784 } else { 14785 int ArgOrdinal = 1; 14786 for (Expr *Arg : Args) { 14787 if (checkMathBuiltinElementType(*this, Arg->getBeginLoc(), Arg->getType(), 14788 ArgOrdinal++)) 14789 return true; 14790 } 14791 } 14792 14793 for (int I = 1; I < 3; ++I) { 14794 if (Args[0]->getType().getCanonicalType() != 14795 Args[I]->getType().getCanonicalType()) { 14796 return Diag(Args[0]->getBeginLoc(), 14797 diag::err_typecheck_call_different_arg_types) 14798 << Args[0]->getType() << Args[I]->getType(); 14799 } 14800 14801 TheCall->setArg(I, Args[I]); 14802 } 14803 14804 TheCall->setType(Args[0]->getType()); 14805 return false; 14806 } 14807 14808 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) { 14809 if (checkArgCount(TheCall, 1)) 14810 return true; 14811 14812 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 14813 if (A.isInvalid()) 14814 return true; 14815 14816 TheCall->setArg(0, A.get()); 14817 return false; 14818 } 14819 14820 bool Sema::BuiltinNonDeterministicValue(CallExpr *TheCall) { 14821 if (checkArgCount(TheCall, 1)) 14822 return true; 14823 14824 ExprResult Arg = TheCall->getArg(0); 14825 QualType TyArg = Arg.get()->getType(); 14826 14827 if (!TyArg->isBuiltinType() && !TyArg->isVectorType()) 14828 return Diag(TheCall->getArg(0)->getBeginLoc(), diag::err_builtin_invalid_arg_type) 14829 << 1 << /*vector, integer or floating point ty*/ 0 << TyArg; 14830 14831 TheCall->setType(TyArg); 14832 return false; 14833 } 14834 14835 ExprResult Sema::BuiltinMatrixTranspose(CallExpr *TheCall, 14836 ExprResult CallResult) { 14837 if (checkArgCount(TheCall, 1)) 14838 return ExprError(); 14839 14840 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 14841 if (MatrixArg.isInvalid()) 14842 return MatrixArg; 14843 Expr *Matrix = MatrixArg.get(); 14844 14845 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 14846 if (!MType) { 14847 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type) 14848 << 1 << /* matrix ty*/ 1 << Matrix->getType(); 14849 return ExprError(); 14850 } 14851 14852 // Create returned matrix type by swapping rows and columns of the argument 14853 // matrix type. 14854 QualType ResultType = Context.getConstantMatrixType( 14855 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 14856 14857 // Change the return type to the type of the returned matrix. 14858 TheCall->setType(ResultType); 14859 14860 // Update call argument to use the possibly converted matrix argument. 14861 TheCall->setArg(0, Matrix); 14862 return CallResult; 14863 } 14864 14865 // Get and verify the matrix dimensions. 14866 static std::optional<unsigned> 14867 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 14868 SourceLocation ErrorPos; 14869 std::optional<llvm::APSInt> Value = 14870 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 14871 if (!Value) { 14872 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 14873 << Name; 14874 return {}; 14875 } 14876 uint64_t Dim = Value->getZExtValue(); 14877 if (!ConstantMatrixType::isDimensionValid(Dim)) { 14878 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 14879 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 14880 return {}; 14881 } 14882 return Dim; 14883 } 14884 14885 ExprResult Sema::BuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 14886 ExprResult CallResult) { 14887 if (!getLangOpts().MatrixTypes) { 14888 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 14889 return ExprError(); 14890 } 14891 14892 if (checkArgCount(TheCall, 4)) 14893 return ExprError(); 14894 14895 unsigned PtrArgIdx = 0; 14896 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 14897 Expr *RowsExpr = TheCall->getArg(1); 14898 Expr *ColumnsExpr = TheCall->getArg(2); 14899 Expr *StrideExpr = TheCall->getArg(3); 14900 14901 bool ArgError = false; 14902 14903 // Check pointer argument. 14904 { 14905 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 14906 if (PtrConv.isInvalid()) 14907 return PtrConv; 14908 PtrExpr = PtrConv.get(); 14909 TheCall->setArg(0, PtrExpr); 14910 if (PtrExpr->isTypeDependent()) { 14911 TheCall->setType(Context.DependentTy); 14912 return TheCall; 14913 } 14914 } 14915 14916 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 14917 QualType ElementTy; 14918 if (!PtrTy) { 14919 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 14920 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 14921 ArgError = true; 14922 } else { 14923 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 14924 14925 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 14926 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 14927 << PtrArgIdx + 1 << /* pointer to element ty*/ 2 14928 << PtrExpr->getType(); 14929 ArgError = true; 14930 } 14931 } 14932 14933 // Apply default Lvalue conversions and convert the expression to size_t. 14934 auto ApplyArgumentConversions = [this](Expr *E) { 14935 ExprResult Conv = DefaultLvalueConversion(E); 14936 if (Conv.isInvalid()) 14937 return Conv; 14938 14939 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 14940 }; 14941 14942 // Apply conversion to row and column expressions. 14943 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 14944 if (!RowsConv.isInvalid()) { 14945 RowsExpr = RowsConv.get(); 14946 TheCall->setArg(1, RowsExpr); 14947 } else 14948 RowsExpr = nullptr; 14949 14950 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 14951 if (!ColumnsConv.isInvalid()) { 14952 ColumnsExpr = ColumnsConv.get(); 14953 TheCall->setArg(2, ColumnsExpr); 14954 } else 14955 ColumnsExpr = nullptr; 14956 14957 // If any part of the result matrix type is still pending, just use 14958 // Context.DependentTy, until all parts are resolved. 14959 if ((RowsExpr && RowsExpr->isTypeDependent()) || 14960 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 14961 TheCall->setType(Context.DependentTy); 14962 return CallResult; 14963 } 14964 14965 // Check row and column dimensions. 14966 std::optional<unsigned> MaybeRows; 14967 if (RowsExpr) 14968 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 14969 14970 std::optional<unsigned> MaybeColumns; 14971 if (ColumnsExpr) 14972 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 14973 14974 // Check stride argument. 14975 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 14976 if (StrideConv.isInvalid()) 14977 return ExprError(); 14978 StrideExpr = StrideConv.get(); 14979 TheCall->setArg(3, StrideExpr); 14980 14981 if (MaybeRows) { 14982 if (std::optional<llvm::APSInt> Value = 14983 StrideExpr->getIntegerConstantExpr(Context)) { 14984 uint64_t Stride = Value->getZExtValue(); 14985 if (Stride < *MaybeRows) { 14986 Diag(StrideExpr->getBeginLoc(), 14987 diag::err_builtin_matrix_stride_too_small); 14988 ArgError = true; 14989 } 14990 } 14991 } 14992 14993 if (ArgError || !MaybeRows || !MaybeColumns) 14994 return ExprError(); 14995 14996 TheCall->setType( 14997 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 14998 return CallResult; 14999 } 15000 15001 ExprResult Sema::BuiltinMatrixColumnMajorStore(CallExpr *TheCall, 15002 ExprResult CallResult) { 15003 if (checkArgCount(TheCall, 3)) 15004 return ExprError(); 15005 15006 unsigned PtrArgIdx = 1; 15007 Expr *MatrixExpr = TheCall->getArg(0); 15008 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15009 Expr *StrideExpr = TheCall->getArg(2); 15010 15011 bool ArgError = false; 15012 15013 { 15014 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 15015 if (MatrixConv.isInvalid()) 15016 return MatrixConv; 15017 MatrixExpr = MatrixConv.get(); 15018 TheCall->setArg(0, MatrixExpr); 15019 } 15020 if (MatrixExpr->isTypeDependent()) { 15021 TheCall->setType(Context.DependentTy); 15022 return TheCall; 15023 } 15024 15025 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 15026 if (!MatrixTy) { 15027 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 15028 << 1 << /*matrix ty */ 1 << MatrixExpr->getType(); 15029 ArgError = true; 15030 } 15031 15032 { 15033 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15034 if (PtrConv.isInvalid()) 15035 return PtrConv; 15036 PtrExpr = PtrConv.get(); 15037 TheCall->setArg(1, PtrExpr); 15038 if (PtrExpr->isTypeDependent()) { 15039 TheCall->setType(Context.DependentTy); 15040 return TheCall; 15041 } 15042 } 15043 15044 // Check pointer argument. 15045 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15046 if (!PtrTy) { 15047 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 15048 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 15049 ArgError = true; 15050 } else { 15051 QualType ElementTy = PtrTy->getPointeeType(); 15052 if (ElementTy.isConstQualified()) { 15053 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 15054 ArgError = true; 15055 } 15056 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 15057 if (MatrixTy && 15058 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 15059 Diag(PtrExpr->getBeginLoc(), 15060 diag::err_builtin_matrix_pointer_arg_mismatch) 15061 << ElementTy << MatrixTy->getElementType(); 15062 ArgError = true; 15063 } 15064 } 15065 15066 // Apply default Lvalue conversions and convert the stride expression to 15067 // size_t. 15068 { 15069 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 15070 if (StrideConv.isInvalid()) 15071 return StrideConv; 15072 15073 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 15074 if (StrideConv.isInvalid()) 15075 return StrideConv; 15076 StrideExpr = StrideConv.get(); 15077 TheCall->setArg(2, StrideExpr); 15078 } 15079 15080 // Check stride argument. 15081 if (MatrixTy) { 15082 if (std::optional<llvm::APSInt> Value = 15083 StrideExpr->getIntegerConstantExpr(Context)) { 15084 uint64_t Stride = Value->getZExtValue(); 15085 if (Stride < MatrixTy->getNumRows()) { 15086 Diag(StrideExpr->getBeginLoc(), 15087 diag::err_builtin_matrix_stride_too_small); 15088 ArgError = true; 15089 } 15090 } 15091 } 15092 15093 if (ArgError) 15094 return ExprError(); 15095 15096 return CallResult; 15097 } 15098 15099 void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc, 15100 const NamedDecl *Callee) { 15101 // This warning does not make sense in code that has no runtime behavior. 15102 if (isUnevaluatedContext()) 15103 return; 15104 15105 const NamedDecl *Caller = getCurFunctionOrMethodDecl(); 15106 15107 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>()) 15108 return; 15109 15110 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 15111 // all TCBs the callee is a part of. 15112 llvm::StringSet<> CalleeTCBs; 15113 for (const auto *A : Callee->specific_attrs<EnforceTCBAttr>()) 15114 CalleeTCBs.insert(A->getTCBName()); 15115 for (const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>()) 15116 CalleeTCBs.insert(A->getTCBName()); 15117 15118 // Go through the TCBs the caller is a part of and emit warnings if Caller 15119 // is in a TCB that the Callee is not. 15120 for (const auto *A : Caller->specific_attrs<EnforceTCBAttr>()) { 15121 StringRef CallerTCB = A->getTCBName(); 15122 if (CalleeTCBs.count(CallerTCB) == 0) { 15123 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation) 15124 << Callee << CallerTCB; 15125 } 15126 } 15127 } 15128