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 "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.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/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSwitch.h" 79 #include "llvm/ADT/Triple.h" 80 #include "llvm/Support/AtomicOrdering.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/ConvertUTF.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/Locale.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/SaveAndRestore.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstddef> 93 #include <cstdint> 94 #include <functional> 95 #include <limits> 96 #include <string> 97 #include <tuple> 98 #include <utility> 99 100 using namespace clang; 101 using namespace sema; 102 103 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 104 unsigned ByteNo) const { 105 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 106 Context.getTargetInfo()); 107 } 108 109 /// Checks that a call expression's argument count is the desired number. 110 /// This is useful when doing custom type-checking. Returns true on error. 111 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 112 unsigned argCount = call->getNumArgs(); 113 if (argCount == desiredArgCount) return false; 114 115 if (argCount < desiredArgCount) 116 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 117 << 0 /*function call*/ << desiredArgCount << argCount 118 << call->getSourceRange(); 119 120 // Highlight all the excess arguments. 121 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 122 call->getArg(argCount - 1)->getEndLoc()); 123 124 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 125 << 0 /*function call*/ << desiredArgCount << argCount 126 << call->getArg(1)->getSourceRange(); 127 } 128 129 /// Check that the first argument to __builtin_annotation is an integer 130 /// and the second argument is a non-wide string literal. 131 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 132 if (checkArgCount(S, TheCall, 2)) 133 return true; 134 135 // First argument should be an integer. 136 Expr *ValArg = TheCall->getArg(0); 137 QualType Ty = ValArg->getType(); 138 if (!Ty->isIntegerType()) { 139 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 140 << ValArg->getSourceRange(); 141 return true; 142 } 143 144 // Second argument should be a constant string. 145 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 146 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 147 if (!Literal || !Literal->isAscii()) { 148 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 149 << StrArg->getSourceRange(); 150 return true; 151 } 152 153 TheCall->setType(Ty); 154 return false; 155 } 156 157 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 158 // We need at least one argument. 159 if (TheCall->getNumArgs() < 1) { 160 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 161 << 0 << 1 << TheCall->getNumArgs() 162 << TheCall->getCallee()->getSourceRange(); 163 return true; 164 } 165 166 // All arguments should be wide string literals. 167 for (Expr *Arg : TheCall->arguments()) { 168 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 169 if (!Literal || !Literal->isWide()) { 170 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 171 << Arg->getSourceRange(); 172 return true; 173 } 174 } 175 176 return false; 177 } 178 179 /// Check that the argument to __builtin_addressof is a glvalue, and set the 180 /// result type to the corresponding pointer type. 181 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 182 if (checkArgCount(S, TheCall, 1)) 183 return true; 184 185 ExprResult Arg(TheCall->getArg(0)); 186 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 187 if (ResultType.isNull()) 188 return true; 189 190 TheCall->setArg(0, Arg.get()); 191 TheCall->setType(ResultType); 192 return false; 193 } 194 195 /// Check the number of arguments and set the result type to 196 /// the argument type. 197 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 198 if (checkArgCount(S, TheCall, 1)) 199 return true; 200 201 TheCall->setType(TheCall->getArg(0)->getType()); 202 return false; 203 } 204 205 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 206 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 207 /// type (but not a function pointer) and that the alignment is a power-of-two. 208 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 209 if (checkArgCount(S, TheCall, 2)) 210 return true; 211 212 clang::Expr *Source = TheCall->getArg(0); 213 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 214 215 auto IsValidIntegerType = [](QualType Ty) { 216 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 217 }; 218 QualType SrcTy = Source->getType(); 219 // We should also be able to use it with arrays (but not functions!). 220 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 221 SrcTy = S.Context.getDecayedType(SrcTy); 222 } 223 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 224 SrcTy->isFunctionPointerType()) { 225 // FIXME: this is not quite the right error message since we don't allow 226 // floating point types, or member pointers. 227 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 228 << SrcTy; 229 return true; 230 } 231 232 clang::Expr *AlignOp = TheCall->getArg(1); 233 if (!IsValidIntegerType(AlignOp->getType())) { 234 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 235 << AlignOp->getType(); 236 return true; 237 } 238 Expr::EvalResult AlignResult; 239 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 240 // We can't check validity of alignment if it is type dependent. 241 if (!AlignOp->isInstantiationDependent() && 242 AlignOp->EvaluateAsInt(AlignResult, S.Context, 243 Expr::SE_AllowSideEffects)) { 244 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 245 llvm::APSInt MaxValue( 246 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 247 if (AlignValue < 1) { 248 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 249 return true; 250 } 251 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 252 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 253 << MaxValue.toString(10); 254 return true; 255 } 256 if (!AlignValue.isPowerOf2()) { 257 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 258 return true; 259 } 260 if (AlignValue == 1) { 261 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 262 << IsBooleanAlignBuiltin; 263 } 264 } 265 266 ExprResult SrcArg = S.PerformCopyInitialization( 267 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 268 SourceLocation(), Source); 269 if (SrcArg.isInvalid()) 270 return true; 271 TheCall->setArg(0, SrcArg.get()); 272 ExprResult AlignArg = 273 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 274 S.Context, AlignOp->getType(), false), 275 SourceLocation(), AlignOp); 276 if (AlignArg.isInvalid()) 277 return true; 278 TheCall->setArg(1, AlignArg.get()); 279 // For align_up/align_down, the return type is the same as the (potentially 280 // decayed) argument type including qualifiers. For is_aligned(), the result 281 // is always bool. 282 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 283 return false; 284 } 285 286 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 287 unsigned BuiltinID) { 288 if (checkArgCount(S, TheCall, 3)) 289 return true; 290 291 // First two arguments should be integers. 292 for (unsigned I = 0; I < 2; ++I) { 293 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 294 if (Arg.isInvalid()) return true; 295 TheCall->setArg(I, Arg.get()); 296 297 QualType Ty = Arg.get()->getType(); 298 if (!Ty->isIntegerType()) { 299 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 300 << Ty << Arg.get()->getSourceRange(); 301 return true; 302 } 303 } 304 305 // Third argument should be a pointer to a non-const integer. 306 // IRGen correctly handles volatile, restrict, and address spaces, and 307 // the other qualifiers aren't possible. 308 { 309 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 310 if (Arg.isInvalid()) return true; 311 TheCall->setArg(2, Arg.get()); 312 313 QualType Ty = Arg.get()->getType(); 314 const auto *PtrTy = Ty->getAs<PointerType>(); 315 if (!PtrTy || 316 !PtrTy->getPointeeType()->isIntegerType() || 317 PtrTy->getPointeeType().isConstQualified()) { 318 S.Diag(Arg.get()->getBeginLoc(), 319 diag::err_overflow_builtin_must_be_ptr_int) 320 << Ty << Arg.get()->getSourceRange(); 321 return true; 322 } 323 } 324 325 // Disallow signed ExtIntType args larger than 128 bits to mul function until 326 // we improve backend support. 327 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 328 for (unsigned I = 0; I < 3; ++I) { 329 const auto Arg = TheCall->getArg(I); 330 // Third argument will be a pointer. 331 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 332 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 333 S.getASTContext().getIntWidth(Ty) > 128) 334 return S.Diag(Arg->getBeginLoc(), 335 diag::err_overflow_builtin_ext_int_max_size) 336 << 128; 337 } 338 } 339 340 return false; 341 } 342 343 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 344 if (checkArgCount(S, BuiltinCall, 2)) 345 return true; 346 347 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 348 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 349 Expr *Call = BuiltinCall->getArg(0); 350 Expr *Chain = BuiltinCall->getArg(1); 351 352 if (Call->getStmtClass() != Stmt::CallExprClass) { 353 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 354 << Call->getSourceRange(); 355 return true; 356 } 357 358 auto CE = cast<CallExpr>(Call); 359 if (CE->getCallee()->getType()->isBlockPointerType()) { 360 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 361 << Call->getSourceRange(); 362 return true; 363 } 364 365 const Decl *TargetDecl = CE->getCalleeDecl(); 366 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 367 if (FD->getBuiltinID()) { 368 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 369 << Call->getSourceRange(); 370 return true; 371 } 372 373 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 374 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 375 << Call->getSourceRange(); 376 return true; 377 } 378 379 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 380 if (ChainResult.isInvalid()) 381 return true; 382 if (!ChainResult.get()->getType()->isPointerType()) { 383 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 384 << Chain->getSourceRange(); 385 return true; 386 } 387 388 QualType ReturnTy = CE->getCallReturnType(S.Context); 389 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 390 QualType BuiltinTy = S.Context.getFunctionType( 391 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 392 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 393 394 Builtin = 395 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 396 397 BuiltinCall->setType(CE->getType()); 398 BuiltinCall->setValueKind(CE->getValueKind()); 399 BuiltinCall->setObjectKind(CE->getObjectKind()); 400 BuiltinCall->setCallee(Builtin); 401 BuiltinCall->setArg(1, ChainResult.get()); 402 403 return false; 404 } 405 406 namespace { 407 408 class EstimateSizeFormatHandler 409 : public analyze_format_string::FormatStringHandler { 410 size_t Size; 411 412 public: 413 EstimateSizeFormatHandler(StringRef Format) 414 : Size(std::min(Format.find(0), Format.size()) + 415 1 /* null byte always written by sprintf */) {} 416 417 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 418 const char *, unsigned SpecifierLen) override { 419 420 const size_t FieldWidth = computeFieldWidth(FS); 421 const size_t Precision = computePrecision(FS); 422 423 // The actual format. 424 switch (FS.getConversionSpecifier().getKind()) { 425 // Just a char. 426 case analyze_format_string::ConversionSpecifier::cArg: 427 case analyze_format_string::ConversionSpecifier::CArg: 428 Size += std::max(FieldWidth, (size_t)1); 429 break; 430 // Just an integer. 431 case analyze_format_string::ConversionSpecifier::dArg: 432 case analyze_format_string::ConversionSpecifier::DArg: 433 case analyze_format_string::ConversionSpecifier::iArg: 434 case analyze_format_string::ConversionSpecifier::oArg: 435 case analyze_format_string::ConversionSpecifier::OArg: 436 case analyze_format_string::ConversionSpecifier::uArg: 437 case analyze_format_string::ConversionSpecifier::UArg: 438 case analyze_format_string::ConversionSpecifier::xArg: 439 case analyze_format_string::ConversionSpecifier::XArg: 440 Size += std::max(FieldWidth, Precision); 441 break; 442 443 // %g style conversion switches between %f or %e style dynamically. 444 // %f always takes less space, so default to it. 445 case analyze_format_string::ConversionSpecifier::gArg: 446 case analyze_format_string::ConversionSpecifier::GArg: 447 448 // Floating point number in the form '[+]ddd.ddd'. 449 case analyze_format_string::ConversionSpecifier::fArg: 450 case analyze_format_string::ConversionSpecifier::FArg: 451 Size += std::max(FieldWidth, 1 /* integer part */ + 452 (Precision ? 1 + Precision 453 : 0) /* period + decimal */); 454 break; 455 456 // Floating point number in the form '[-]d.ddde[+-]dd'. 457 case analyze_format_string::ConversionSpecifier::eArg: 458 case analyze_format_string::ConversionSpecifier::EArg: 459 Size += 460 std::max(FieldWidth, 461 1 /* integer part */ + 462 (Precision ? 1 + Precision : 0) /* period + decimal */ + 463 1 /* e or E letter */ + 2 /* exponent */); 464 break; 465 466 // Floating point number in the form '[-]0xh.hhhhp±dd'. 467 case analyze_format_string::ConversionSpecifier::aArg: 468 case analyze_format_string::ConversionSpecifier::AArg: 469 Size += 470 std::max(FieldWidth, 471 2 /* 0x */ + 1 /* integer part */ + 472 (Precision ? 1 + Precision : 0) /* period + decimal */ + 473 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 474 break; 475 476 // Just a string. 477 case analyze_format_string::ConversionSpecifier::sArg: 478 case analyze_format_string::ConversionSpecifier::SArg: 479 Size += FieldWidth; 480 break; 481 482 // Just a pointer in the form '0xddd'. 483 case analyze_format_string::ConversionSpecifier::pArg: 484 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 485 break; 486 487 // A plain percent. 488 case analyze_format_string::ConversionSpecifier::PercentArg: 489 Size += 1; 490 break; 491 492 default: 493 break; 494 } 495 496 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 497 498 if (FS.hasAlternativeForm()) { 499 switch (FS.getConversionSpecifier().getKind()) { 500 default: 501 break; 502 // Force a leading '0'. 503 case analyze_format_string::ConversionSpecifier::oArg: 504 Size += 1; 505 break; 506 // Force a leading '0x'. 507 case analyze_format_string::ConversionSpecifier::xArg: 508 case analyze_format_string::ConversionSpecifier::XArg: 509 Size += 2; 510 break; 511 // Force a period '.' before decimal, even if precision is 0. 512 case analyze_format_string::ConversionSpecifier::aArg: 513 case analyze_format_string::ConversionSpecifier::AArg: 514 case analyze_format_string::ConversionSpecifier::eArg: 515 case analyze_format_string::ConversionSpecifier::EArg: 516 case analyze_format_string::ConversionSpecifier::fArg: 517 case analyze_format_string::ConversionSpecifier::FArg: 518 case analyze_format_string::ConversionSpecifier::gArg: 519 case analyze_format_string::ConversionSpecifier::GArg: 520 Size += (Precision ? 0 : 1); 521 break; 522 } 523 } 524 assert(SpecifierLen <= Size && "no underflow"); 525 Size -= SpecifierLen; 526 return true; 527 } 528 529 size_t getSizeLowerBound() const { return Size; } 530 531 private: 532 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 533 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 534 size_t FieldWidth = 0; 535 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 536 FieldWidth = FW.getConstantAmount(); 537 return FieldWidth; 538 } 539 540 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 541 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 542 size_t Precision = 0; 543 544 // See man 3 printf for default precision value based on the specifier. 545 switch (FW.getHowSpecified()) { 546 case analyze_format_string::OptionalAmount::NotSpecified: 547 switch (FS.getConversionSpecifier().getKind()) { 548 default: 549 break; 550 case analyze_format_string::ConversionSpecifier::dArg: // %d 551 case analyze_format_string::ConversionSpecifier::DArg: // %D 552 case analyze_format_string::ConversionSpecifier::iArg: // %i 553 Precision = 1; 554 break; 555 case analyze_format_string::ConversionSpecifier::oArg: // %d 556 case analyze_format_string::ConversionSpecifier::OArg: // %D 557 case analyze_format_string::ConversionSpecifier::uArg: // %d 558 case analyze_format_string::ConversionSpecifier::UArg: // %D 559 case analyze_format_string::ConversionSpecifier::xArg: // %d 560 case analyze_format_string::ConversionSpecifier::XArg: // %D 561 Precision = 1; 562 break; 563 case analyze_format_string::ConversionSpecifier::fArg: // %f 564 case analyze_format_string::ConversionSpecifier::FArg: // %F 565 case analyze_format_string::ConversionSpecifier::eArg: // %e 566 case analyze_format_string::ConversionSpecifier::EArg: // %E 567 case analyze_format_string::ConversionSpecifier::gArg: // %g 568 case analyze_format_string::ConversionSpecifier::GArg: // %G 569 Precision = 6; 570 break; 571 case analyze_format_string::ConversionSpecifier::pArg: // %d 572 Precision = 1; 573 break; 574 } 575 break; 576 case analyze_format_string::OptionalAmount::Constant: 577 Precision = FW.getConstantAmount(); 578 break; 579 default: 580 break; 581 } 582 return Precision; 583 } 584 }; 585 586 } // namespace 587 588 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 589 /// __builtin_*_chk function, then use the object size argument specified in the 590 /// source. Otherwise, infer the object size using __builtin_object_size. 591 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 592 CallExpr *TheCall) { 593 // FIXME: There are some more useful checks we could be doing here: 594 // - Evaluate strlen of strcpy arguments, use as object size. 595 596 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 597 isConstantEvaluated()) 598 return; 599 600 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 601 if (!BuiltinID) 602 return; 603 604 const TargetInfo &TI = getASTContext().getTargetInfo(); 605 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 606 607 unsigned DiagID = 0; 608 bool IsChkVariant = false; 609 Optional<llvm::APSInt> UsedSize; 610 unsigned SizeIndex, ObjectIndex; 611 switch (BuiltinID) { 612 default: 613 return; 614 case Builtin::BIsprintf: 615 case Builtin::BI__builtin___sprintf_chk: { 616 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 617 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 618 619 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 620 621 if (!Format->isAscii() && !Format->isUTF8()) 622 return; 623 624 StringRef FormatStrRef = Format->getString(); 625 EstimateSizeFormatHandler H(FormatStrRef); 626 const char *FormatBytes = FormatStrRef.data(); 627 const ConstantArrayType *T = 628 Context.getAsConstantArrayType(Format->getType()); 629 assert(T && "String literal not of constant array type!"); 630 size_t TypeSize = T->getSize().getZExtValue(); 631 632 // In case there's a null byte somewhere. 633 size_t StrLen = 634 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 635 if (!analyze_format_string::ParsePrintfString( 636 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 637 Context.getTargetInfo(), false)) { 638 DiagID = diag::warn_fortify_source_format_overflow; 639 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 640 .extOrTrunc(SizeTypeWidth); 641 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 642 IsChkVariant = true; 643 ObjectIndex = 2; 644 } else { 645 IsChkVariant = false; 646 ObjectIndex = 0; 647 } 648 break; 649 } 650 } 651 return; 652 } 653 case Builtin::BI__builtin___memcpy_chk: 654 case Builtin::BI__builtin___memmove_chk: 655 case Builtin::BI__builtin___memset_chk: 656 case Builtin::BI__builtin___strlcat_chk: 657 case Builtin::BI__builtin___strlcpy_chk: 658 case Builtin::BI__builtin___strncat_chk: 659 case Builtin::BI__builtin___strncpy_chk: 660 case Builtin::BI__builtin___stpncpy_chk: 661 case Builtin::BI__builtin___memccpy_chk: 662 case Builtin::BI__builtin___mempcpy_chk: { 663 DiagID = diag::warn_builtin_chk_overflow; 664 IsChkVariant = true; 665 SizeIndex = TheCall->getNumArgs() - 2; 666 ObjectIndex = TheCall->getNumArgs() - 1; 667 break; 668 } 669 670 case Builtin::BI__builtin___snprintf_chk: 671 case Builtin::BI__builtin___vsnprintf_chk: { 672 DiagID = diag::warn_builtin_chk_overflow; 673 IsChkVariant = true; 674 SizeIndex = 1; 675 ObjectIndex = 3; 676 break; 677 } 678 679 case Builtin::BIstrncat: 680 case Builtin::BI__builtin_strncat: 681 case Builtin::BIstrncpy: 682 case Builtin::BI__builtin_strncpy: 683 case Builtin::BIstpncpy: 684 case Builtin::BI__builtin_stpncpy: { 685 // Whether these functions overflow depends on the runtime strlen of the 686 // string, not just the buffer size, so emitting the "always overflow" 687 // diagnostic isn't quite right. We should still diagnose passing a buffer 688 // size larger than the destination buffer though; this is a runtime abort 689 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 690 DiagID = diag::warn_fortify_source_size_mismatch; 691 SizeIndex = TheCall->getNumArgs() - 1; 692 ObjectIndex = 0; 693 break; 694 } 695 696 case Builtin::BImemcpy: 697 case Builtin::BI__builtin_memcpy: 698 case Builtin::BImemmove: 699 case Builtin::BI__builtin_memmove: 700 case Builtin::BImemset: 701 case Builtin::BI__builtin_memset: 702 case Builtin::BImempcpy: 703 case Builtin::BI__builtin_mempcpy: { 704 DiagID = diag::warn_fortify_source_overflow; 705 SizeIndex = TheCall->getNumArgs() - 1; 706 ObjectIndex = 0; 707 break; 708 } 709 case Builtin::BIsnprintf: 710 case Builtin::BI__builtin_snprintf: 711 case Builtin::BIvsnprintf: 712 case Builtin::BI__builtin_vsnprintf: { 713 DiagID = diag::warn_fortify_source_size_mismatch; 714 SizeIndex = 1; 715 ObjectIndex = 0; 716 break; 717 } 718 } 719 720 llvm::APSInt ObjectSize; 721 // For __builtin___*_chk, the object size is explicitly provided by the caller 722 // (usually using __builtin_object_size). Use that value to check this call. 723 if (IsChkVariant) { 724 Expr::EvalResult Result; 725 Expr *SizeArg = TheCall->getArg(ObjectIndex); 726 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 727 return; 728 ObjectSize = Result.Val.getInt(); 729 730 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 731 } else { 732 // If the parameter has a pass_object_size attribute, then we should use its 733 // (potentially) more strict checking mode. Otherwise, conservatively assume 734 // type 0. 735 int BOSType = 0; 736 if (const auto *POS = 737 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 738 BOSType = POS->getType(); 739 740 Expr *ObjArg = TheCall->getArg(ObjectIndex); 741 uint64_t Result; 742 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 743 return; 744 // Get the object size in the target's size_t width. 745 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 746 } 747 748 // Evaluate the number of bytes of the object that this call will use. 749 if (!UsedSize) { 750 Expr::EvalResult Result; 751 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 752 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 753 return; 754 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 755 } 756 757 if (UsedSize.getValue().ule(ObjectSize)) 758 return; 759 760 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 761 // Skim off the details of whichever builtin was called to produce a better 762 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 763 if (IsChkVariant) { 764 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 765 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 766 } else if (FunctionName.startswith("__builtin_")) { 767 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 768 } 769 770 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 771 PDiag(DiagID) 772 << FunctionName << ObjectSize.toString(/*Radix=*/10) 773 << UsedSize.getValue().toString(/*Radix=*/10)); 774 } 775 776 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 777 Scope::ScopeFlags NeededScopeFlags, 778 unsigned DiagID) { 779 // Scopes aren't available during instantiation. Fortunately, builtin 780 // functions cannot be template args so they cannot be formed through template 781 // instantiation. Therefore checking once during the parse is sufficient. 782 if (SemaRef.inTemplateInstantiation()) 783 return false; 784 785 Scope *S = SemaRef.getCurScope(); 786 while (S && !S->isSEHExceptScope()) 787 S = S->getParent(); 788 if (!S || !(S->getFlags() & NeededScopeFlags)) { 789 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 790 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 791 << DRE->getDecl()->getIdentifier(); 792 return true; 793 } 794 795 return false; 796 } 797 798 static inline bool isBlockPointer(Expr *Arg) { 799 return Arg->getType()->isBlockPointerType(); 800 } 801 802 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 803 /// void*, which is a requirement of device side enqueue. 804 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 805 const BlockPointerType *BPT = 806 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 807 ArrayRef<QualType> Params = 808 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 809 unsigned ArgCounter = 0; 810 bool IllegalParams = false; 811 // Iterate through the block parameters until either one is found that is not 812 // a local void*, or the block is valid. 813 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 814 I != E; ++I, ++ArgCounter) { 815 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 816 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 817 LangAS::opencl_local) { 818 // Get the location of the error. If a block literal has been passed 819 // (BlockExpr) then we can point straight to the offending argument, 820 // else we just point to the variable reference. 821 SourceLocation ErrorLoc; 822 if (isa<BlockExpr>(BlockArg)) { 823 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 824 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 825 } else if (isa<DeclRefExpr>(BlockArg)) { 826 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 827 } 828 S.Diag(ErrorLoc, 829 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 830 IllegalParams = true; 831 } 832 } 833 834 return IllegalParams; 835 } 836 837 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 838 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 839 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 840 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 841 return true; 842 } 843 return false; 844 } 845 846 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 847 if (checkArgCount(S, TheCall, 2)) 848 return true; 849 850 if (checkOpenCLSubgroupExt(S, TheCall)) 851 return true; 852 853 // First argument is an ndrange_t type. 854 Expr *NDRangeArg = TheCall->getArg(0); 855 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 856 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 857 << TheCall->getDirectCallee() << "'ndrange_t'"; 858 return true; 859 } 860 861 Expr *BlockArg = TheCall->getArg(1); 862 if (!isBlockPointer(BlockArg)) { 863 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 864 << TheCall->getDirectCallee() << "block"; 865 return true; 866 } 867 return checkOpenCLBlockArgs(S, BlockArg); 868 } 869 870 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 871 /// get_kernel_work_group_size 872 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 873 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 874 if (checkArgCount(S, TheCall, 1)) 875 return true; 876 877 Expr *BlockArg = TheCall->getArg(0); 878 if (!isBlockPointer(BlockArg)) { 879 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 880 << TheCall->getDirectCallee() << "block"; 881 return true; 882 } 883 return checkOpenCLBlockArgs(S, BlockArg); 884 } 885 886 /// Diagnose integer type and any valid implicit conversion to it. 887 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 888 const QualType &IntType); 889 890 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 891 unsigned Start, unsigned End) { 892 bool IllegalParams = false; 893 for (unsigned I = Start; I <= End; ++I) 894 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 895 S.Context.getSizeType()); 896 return IllegalParams; 897 } 898 899 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 900 /// 'local void*' parameter of passed block. 901 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 902 Expr *BlockArg, 903 unsigned NumNonVarArgs) { 904 const BlockPointerType *BPT = 905 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 906 unsigned NumBlockParams = 907 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 908 unsigned TotalNumArgs = TheCall->getNumArgs(); 909 910 // For each argument passed to the block, a corresponding uint needs to 911 // be passed to describe the size of the local memory. 912 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 913 S.Diag(TheCall->getBeginLoc(), 914 diag::err_opencl_enqueue_kernel_local_size_args); 915 return true; 916 } 917 918 // Check that the sizes of the local memory are specified by integers. 919 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 920 TotalNumArgs - 1); 921 } 922 923 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 924 /// overload formats specified in Table 6.13.17.1. 925 /// int enqueue_kernel(queue_t queue, 926 /// kernel_enqueue_flags_t flags, 927 /// const ndrange_t ndrange, 928 /// void (^block)(void)) 929 /// int enqueue_kernel(queue_t queue, 930 /// kernel_enqueue_flags_t flags, 931 /// const ndrange_t ndrange, 932 /// uint num_events_in_wait_list, 933 /// clk_event_t *event_wait_list, 934 /// clk_event_t *event_ret, 935 /// void (^block)(void)) 936 /// int enqueue_kernel(queue_t queue, 937 /// kernel_enqueue_flags_t flags, 938 /// const ndrange_t ndrange, 939 /// void (^block)(local void*, ...), 940 /// uint size0, ...) 941 /// int enqueue_kernel(queue_t queue, 942 /// kernel_enqueue_flags_t flags, 943 /// const ndrange_t ndrange, 944 /// uint num_events_in_wait_list, 945 /// clk_event_t *event_wait_list, 946 /// clk_event_t *event_ret, 947 /// void (^block)(local void*, ...), 948 /// uint size0, ...) 949 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 950 unsigned NumArgs = TheCall->getNumArgs(); 951 952 if (NumArgs < 4) { 953 S.Diag(TheCall->getBeginLoc(), 954 diag::err_typecheck_call_too_few_args_at_least) 955 << 0 << 4 << NumArgs; 956 return true; 957 } 958 959 Expr *Arg0 = TheCall->getArg(0); 960 Expr *Arg1 = TheCall->getArg(1); 961 Expr *Arg2 = TheCall->getArg(2); 962 Expr *Arg3 = TheCall->getArg(3); 963 964 // First argument always needs to be a queue_t type. 965 if (!Arg0->getType()->isQueueT()) { 966 S.Diag(TheCall->getArg(0)->getBeginLoc(), 967 diag::err_opencl_builtin_expected_type) 968 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 969 return true; 970 } 971 972 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 973 if (!Arg1->getType()->isIntegerType()) { 974 S.Diag(TheCall->getArg(1)->getBeginLoc(), 975 diag::err_opencl_builtin_expected_type) 976 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 977 return true; 978 } 979 980 // Third argument is always an ndrange_t type. 981 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 982 S.Diag(TheCall->getArg(2)->getBeginLoc(), 983 diag::err_opencl_builtin_expected_type) 984 << TheCall->getDirectCallee() << "'ndrange_t'"; 985 return true; 986 } 987 988 // With four arguments, there is only one form that the function could be 989 // called in: no events and no variable arguments. 990 if (NumArgs == 4) { 991 // check that the last argument is the right block type. 992 if (!isBlockPointer(Arg3)) { 993 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 994 << TheCall->getDirectCallee() << "block"; 995 return true; 996 } 997 // we have a block type, check the prototype 998 const BlockPointerType *BPT = 999 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1000 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1001 S.Diag(Arg3->getBeginLoc(), 1002 diag::err_opencl_enqueue_kernel_blocks_no_args); 1003 return true; 1004 } 1005 return false; 1006 } 1007 // we can have block + varargs. 1008 if (isBlockPointer(Arg3)) 1009 return (checkOpenCLBlockArgs(S, Arg3) || 1010 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1011 // last two cases with either exactly 7 args or 7 args and varargs. 1012 if (NumArgs >= 7) { 1013 // check common block argument. 1014 Expr *Arg6 = TheCall->getArg(6); 1015 if (!isBlockPointer(Arg6)) { 1016 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1017 << TheCall->getDirectCallee() << "block"; 1018 return true; 1019 } 1020 if (checkOpenCLBlockArgs(S, Arg6)) 1021 return true; 1022 1023 // Forth argument has to be any integer type. 1024 if (!Arg3->getType()->isIntegerType()) { 1025 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1026 diag::err_opencl_builtin_expected_type) 1027 << TheCall->getDirectCallee() << "integer"; 1028 return true; 1029 } 1030 // check remaining common arguments. 1031 Expr *Arg4 = TheCall->getArg(4); 1032 Expr *Arg5 = TheCall->getArg(5); 1033 1034 // Fifth argument is always passed as a pointer to clk_event_t. 1035 if (!Arg4->isNullPointerConstant(S.Context, 1036 Expr::NPC_ValueDependentIsNotNull) && 1037 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1038 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1039 diag::err_opencl_builtin_expected_type) 1040 << TheCall->getDirectCallee() 1041 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1042 return true; 1043 } 1044 1045 // Sixth argument is always passed as a pointer to clk_event_t. 1046 if (!Arg5->isNullPointerConstant(S.Context, 1047 Expr::NPC_ValueDependentIsNotNull) && 1048 !(Arg5->getType()->isPointerType() && 1049 Arg5->getType()->getPointeeType()->isClkEventT())) { 1050 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1051 diag::err_opencl_builtin_expected_type) 1052 << TheCall->getDirectCallee() 1053 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1054 return true; 1055 } 1056 1057 if (NumArgs == 7) 1058 return false; 1059 1060 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1061 } 1062 1063 // None of the specific case has been detected, give generic error 1064 S.Diag(TheCall->getBeginLoc(), 1065 diag::err_opencl_enqueue_kernel_incorrect_args); 1066 return true; 1067 } 1068 1069 /// Returns OpenCL access qual. 1070 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1071 return D->getAttr<OpenCLAccessAttr>(); 1072 } 1073 1074 /// Returns true if pipe element type is different from the pointer. 1075 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1076 const Expr *Arg0 = Call->getArg(0); 1077 // First argument type should always be pipe. 1078 if (!Arg0->getType()->isPipeType()) { 1079 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1080 << Call->getDirectCallee() << Arg0->getSourceRange(); 1081 return true; 1082 } 1083 OpenCLAccessAttr *AccessQual = 1084 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1085 // Validates the access qualifier is compatible with the call. 1086 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1087 // read_only and write_only, and assumed to be read_only if no qualifier is 1088 // specified. 1089 switch (Call->getDirectCallee()->getBuiltinID()) { 1090 case Builtin::BIread_pipe: 1091 case Builtin::BIreserve_read_pipe: 1092 case Builtin::BIcommit_read_pipe: 1093 case Builtin::BIwork_group_reserve_read_pipe: 1094 case Builtin::BIsub_group_reserve_read_pipe: 1095 case Builtin::BIwork_group_commit_read_pipe: 1096 case Builtin::BIsub_group_commit_read_pipe: 1097 if (!(!AccessQual || AccessQual->isReadOnly())) { 1098 S.Diag(Arg0->getBeginLoc(), 1099 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1100 << "read_only" << Arg0->getSourceRange(); 1101 return true; 1102 } 1103 break; 1104 case Builtin::BIwrite_pipe: 1105 case Builtin::BIreserve_write_pipe: 1106 case Builtin::BIcommit_write_pipe: 1107 case Builtin::BIwork_group_reserve_write_pipe: 1108 case Builtin::BIsub_group_reserve_write_pipe: 1109 case Builtin::BIwork_group_commit_write_pipe: 1110 case Builtin::BIsub_group_commit_write_pipe: 1111 if (!(AccessQual && AccessQual->isWriteOnly())) { 1112 S.Diag(Arg0->getBeginLoc(), 1113 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1114 << "write_only" << Arg0->getSourceRange(); 1115 return true; 1116 } 1117 break; 1118 default: 1119 break; 1120 } 1121 return false; 1122 } 1123 1124 /// Returns true if pipe element type is different from the pointer. 1125 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1126 const Expr *Arg0 = Call->getArg(0); 1127 const Expr *ArgIdx = Call->getArg(Idx); 1128 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1129 const QualType EltTy = PipeTy->getElementType(); 1130 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1131 // The Idx argument should be a pointer and the type of the pointer and 1132 // the type of pipe element should also be the same. 1133 if (!ArgTy || 1134 !S.Context.hasSameType( 1135 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1136 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1137 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1138 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1139 return true; 1140 } 1141 return false; 1142 } 1143 1144 // Performs semantic analysis for the read/write_pipe call. 1145 // \param S Reference to the semantic analyzer. 1146 // \param Call A pointer to the builtin call. 1147 // \return True if a semantic error has been found, false otherwise. 1148 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1149 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1150 // functions have two forms. 1151 switch (Call->getNumArgs()) { 1152 case 2: 1153 if (checkOpenCLPipeArg(S, Call)) 1154 return true; 1155 // The call with 2 arguments should be 1156 // read/write_pipe(pipe T, T*). 1157 // Check packet type T. 1158 if (checkOpenCLPipePacketType(S, Call, 1)) 1159 return true; 1160 break; 1161 1162 case 4: { 1163 if (checkOpenCLPipeArg(S, Call)) 1164 return true; 1165 // The call with 4 arguments should be 1166 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1167 // Check reserve_id_t. 1168 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1169 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1170 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1171 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1172 return true; 1173 } 1174 1175 // Check the index. 1176 const Expr *Arg2 = Call->getArg(2); 1177 if (!Arg2->getType()->isIntegerType() && 1178 !Arg2->getType()->isUnsignedIntegerType()) { 1179 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1180 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1181 << Arg2->getType() << Arg2->getSourceRange(); 1182 return true; 1183 } 1184 1185 // Check packet type T. 1186 if (checkOpenCLPipePacketType(S, Call, 3)) 1187 return true; 1188 } break; 1189 default: 1190 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1191 << Call->getDirectCallee() << Call->getSourceRange(); 1192 return true; 1193 } 1194 1195 return false; 1196 } 1197 1198 // Performs a semantic analysis on the {work_group_/sub_group_ 1199 // /_}reserve_{read/write}_pipe 1200 // \param S Reference to the semantic analyzer. 1201 // \param Call The call to the builtin function to be analyzed. 1202 // \return True if a semantic error was found, false otherwise. 1203 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1204 if (checkArgCount(S, Call, 2)) 1205 return true; 1206 1207 if (checkOpenCLPipeArg(S, Call)) 1208 return true; 1209 1210 // Check the reserve size. 1211 if (!Call->getArg(1)->getType()->isIntegerType() && 1212 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1213 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1214 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1215 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1216 return true; 1217 } 1218 1219 // Since return type of reserve_read/write_pipe built-in function is 1220 // reserve_id_t, which is not defined in the builtin def file , we used int 1221 // as return type and need to override the return type of these functions. 1222 Call->setType(S.Context.OCLReserveIDTy); 1223 1224 return false; 1225 } 1226 1227 // Performs a semantic analysis on {work_group_/sub_group_ 1228 // /_}commit_{read/write}_pipe 1229 // \param S Reference to the semantic analyzer. 1230 // \param Call The call to the builtin function to be analyzed. 1231 // \return True if a semantic error was found, false otherwise. 1232 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1233 if (checkArgCount(S, Call, 2)) 1234 return true; 1235 1236 if (checkOpenCLPipeArg(S, Call)) 1237 return true; 1238 1239 // Check reserve_id_t. 1240 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1241 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1242 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1243 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1244 return true; 1245 } 1246 1247 return false; 1248 } 1249 1250 // Performs a semantic analysis on the call to built-in Pipe 1251 // Query Functions. 1252 // \param S Reference to the semantic analyzer. 1253 // \param Call The call to the builtin function to be analyzed. 1254 // \return True if a semantic error was found, false otherwise. 1255 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1256 if (checkArgCount(S, Call, 1)) 1257 return true; 1258 1259 if (!Call->getArg(0)->getType()->isPipeType()) { 1260 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1261 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1262 return true; 1263 } 1264 1265 return false; 1266 } 1267 1268 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1269 // Performs semantic analysis for the to_global/local/private call. 1270 // \param S Reference to the semantic analyzer. 1271 // \param BuiltinID ID of the builtin function. 1272 // \param Call A pointer to the builtin call. 1273 // \return True if a semantic error has been found, false otherwise. 1274 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1275 CallExpr *Call) { 1276 if (Call->getNumArgs() != 1) { 1277 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 1278 << Call->getDirectCallee() << Call->getSourceRange(); 1279 return true; 1280 } 1281 1282 auto RT = Call->getArg(0)->getType(); 1283 if (!RT->isPointerType() || RT->getPointeeType() 1284 .getAddressSpace() == LangAS::opencl_constant) { 1285 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1286 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1287 return true; 1288 } 1289 1290 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1291 S.Diag(Call->getArg(0)->getBeginLoc(), 1292 diag::warn_opencl_generic_address_space_arg) 1293 << Call->getDirectCallee()->getNameInfo().getAsString() 1294 << Call->getArg(0)->getSourceRange(); 1295 } 1296 1297 RT = RT->getPointeeType(); 1298 auto Qual = RT.getQualifiers(); 1299 switch (BuiltinID) { 1300 case Builtin::BIto_global: 1301 Qual.setAddressSpace(LangAS::opencl_global); 1302 break; 1303 case Builtin::BIto_local: 1304 Qual.setAddressSpace(LangAS::opencl_local); 1305 break; 1306 case Builtin::BIto_private: 1307 Qual.setAddressSpace(LangAS::opencl_private); 1308 break; 1309 default: 1310 llvm_unreachable("Invalid builtin function"); 1311 } 1312 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1313 RT.getUnqualifiedType(), Qual))); 1314 1315 return false; 1316 } 1317 1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1319 if (checkArgCount(S, TheCall, 1)) 1320 return ExprError(); 1321 1322 // Compute __builtin_launder's parameter type from the argument. 1323 // The parameter type is: 1324 // * The type of the argument if it's not an array or function type, 1325 // Otherwise, 1326 // * The decayed argument type. 1327 QualType ParamTy = [&]() { 1328 QualType ArgTy = TheCall->getArg(0)->getType(); 1329 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1330 return S.Context.getPointerType(Ty->getElementType()); 1331 if (ArgTy->isFunctionType()) { 1332 return S.Context.getPointerType(ArgTy); 1333 } 1334 return ArgTy; 1335 }(); 1336 1337 TheCall->setType(ParamTy); 1338 1339 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1340 if (!ParamTy->isPointerType()) 1341 return 0; 1342 if (ParamTy->isFunctionPointerType()) 1343 return 1; 1344 if (ParamTy->isVoidPointerType()) 1345 return 2; 1346 return llvm::Optional<unsigned>{}; 1347 }(); 1348 if (DiagSelect.hasValue()) { 1349 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1350 << DiagSelect.getValue() << TheCall->getSourceRange(); 1351 return ExprError(); 1352 } 1353 1354 // We either have an incomplete class type, or we have a class template 1355 // whose instantiation has not been forced. Example: 1356 // 1357 // template <class T> struct Foo { T value; }; 1358 // Foo<int> *p = nullptr; 1359 // auto *d = __builtin_launder(p); 1360 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1361 diag::err_incomplete_type)) 1362 return ExprError(); 1363 1364 assert(ParamTy->getPointeeType()->isObjectType() && 1365 "Unhandled non-object pointer case"); 1366 1367 InitializedEntity Entity = 1368 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1369 ExprResult Arg = 1370 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1371 if (Arg.isInvalid()) 1372 return ExprError(); 1373 TheCall->setArg(0, Arg.get()); 1374 1375 return TheCall; 1376 } 1377 1378 // Emit an error and return true if the current architecture is not in the list 1379 // of supported architectures. 1380 static bool 1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1382 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1383 llvm::Triple::ArchType CurArch = 1384 S.getASTContext().getTargetInfo().getTriple().getArch(); 1385 if (llvm::is_contained(SupportedArchs, CurArch)) 1386 return false; 1387 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1388 << TheCall->getSourceRange(); 1389 return true; 1390 } 1391 1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1393 SourceLocation CallSiteLoc); 1394 1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1396 CallExpr *TheCall) { 1397 switch (TI.getTriple().getArch()) { 1398 default: 1399 // Some builtins don't require additional checking, so just consider these 1400 // acceptable. 1401 return false; 1402 case llvm::Triple::arm: 1403 case llvm::Triple::armeb: 1404 case llvm::Triple::thumb: 1405 case llvm::Triple::thumbeb: 1406 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1407 case llvm::Triple::aarch64: 1408 case llvm::Triple::aarch64_32: 1409 case llvm::Triple::aarch64_be: 1410 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1411 case llvm::Triple::bpfeb: 1412 case llvm::Triple::bpfel: 1413 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1414 case llvm::Triple::hexagon: 1415 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1416 case llvm::Triple::mips: 1417 case llvm::Triple::mipsel: 1418 case llvm::Triple::mips64: 1419 case llvm::Triple::mips64el: 1420 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1421 case llvm::Triple::systemz: 1422 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1423 case llvm::Triple::x86: 1424 case llvm::Triple::x86_64: 1425 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1426 case llvm::Triple::ppc: 1427 case llvm::Triple::ppc64: 1428 case llvm::Triple::ppc64le: 1429 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1430 case llvm::Triple::amdgcn: 1431 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1432 } 1433 } 1434 1435 ExprResult 1436 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1437 CallExpr *TheCall) { 1438 ExprResult TheCallResult(TheCall); 1439 1440 // Find out if any arguments are required to be integer constant expressions. 1441 unsigned ICEArguments = 0; 1442 ASTContext::GetBuiltinTypeError Error; 1443 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1444 if (Error != ASTContext::GE_None) 1445 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1446 1447 // If any arguments are required to be ICE's, check and diagnose. 1448 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1449 // Skip arguments not required to be ICE's. 1450 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1451 1452 llvm::APSInt Result; 1453 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1454 return true; 1455 ICEArguments &= ~(1 << ArgNo); 1456 } 1457 1458 switch (BuiltinID) { 1459 case Builtin::BI__builtin___CFStringMakeConstantString: 1460 assert(TheCall->getNumArgs() == 1 && 1461 "Wrong # arguments to builtin CFStringMakeConstantString"); 1462 if (CheckObjCString(TheCall->getArg(0))) 1463 return ExprError(); 1464 break; 1465 case Builtin::BI__builtin_ms_va_start: 1466 case Builtin::BI__builtin_stdarg_start: 1467 case Builtin::BI__builtin_va_start: 1468 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1469 return ExprError(); 1470 break; 1471 case Builtin::BI__va_start: { 1472 switch (Context.getTargetInfo().getTriple().getArch()) { 1473 case llvm::Triple::aarch64: 1474 case llvm::Triple::arm: 1475 case llvm::Triple::thumb: 1476 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1477 return ExprError(); 1478 break; 1479 default: 1480 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1481 return ExprError(); 1482 break; 1483 } 1484 break; 1485 } 1486 1487 // The acquire, release, and no fence variants are ARM and AArch64 only. 1488 case Builtin::BI_interlockedbittestandset_acq: 1489 case Builtin::BI_interlockedbittestandset_rel: 1490 case Builtin::BI_interlockedbittestandset_nf: 1491 case Builtin::BI_interlockedbittestandreset_acq: 1492 case Builtin::BI_interlockedbittestandreset_rel: 1493 case Builtin::BI_interlockedbittestandreset_nf: 1494 if (CheckBuiltinTargetSupport( 1495 *this, BuiltinID, TheCall, 1496 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1497 return ExprError(); 1498 break; 1499 1500 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1501 case Builtin::BI_bittest64: 1502 case Builtin::BI_bittestandcomplement64: 1503 case Builtin::BI_bittestandreset64: 1504 case Builtin::BI_bittestandset64: 1505 case Builtin::BI_interlockedbittestandreset64: 1506 case Builtin::BI_interlockedbittestandset64: 1507 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1508 {llvm::Triple::x86_64, llvm::Triple::arm, 1509 llvm::Triple::thumb, llvm::Triple::aarch64})) 1510 return ExprError(); 1511 break; 1512 1513 case Builtin::BI__builtin_isgreater: 1514 case Builtin::BI__builtin_isgreaterequal: 1515 case Builtin::BI__builtin_isless: 1516 case Builtin::BI__builtin_islessequal: 1517 case Builtin::BI__builtin_islessgreater: 1518 case Builtin::BI__builtin_isunordered: 1519 if (SemaBuiltinUnorderedCompare(TheCall)) 1520 return ExprError(); 1521 break; 1522 case Builtin::BI__builtin_fpclassify: 1523 if (SemaBuiltinFPClassification(TheCall, 6)) 1524 return ExprError(); 1525 break; 1526 case Builtin::BI__builtin_isfinite: 1527 case Builtin::BI__builtin_isinf: 1528 case Builtin::BI__builtin_isinf_sign: 1529 case Builtin::BI__builtin_isnan: 1530 case Builtin::BI__builtin_isnormal: 1531 case Builtin::BI__builtin_signbit: 1532 case Builtin::BI__builtin_signbitf: 1533 case Builtin::BI__builtin_signbitl: 1534 if (SemaBuiltinFPClassification(TheCall, 1)) 1535 return ExprError(); 1536 break; 1537 case Builtin::BI__builtin_shufflevector: 1538 return SemaBuiltinShuffleVector(TheCall); 1539 // TheCall will be freed by the smart pointer here, but that's fine, since 1540 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1541 case Builtin::BI__builtin_prefetch: 1542 if (SemaBuiltinPrefetch(TheCall)) 1543 return ExprError(); 1544 break; 1545 case Builtin::BI__builtin_alloca_with_align: 1546 if (SemaBuiltinAllocaWithAlign(TheCall)) 1547 return ExprError(); 1548 LLVM_FALLTHROUGH; 1549 case Builtin::BI__builtin_alloca: 1550 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1551 << TheCall->getDirectCallee(); 1552 break; 1553 case Builtin::BI__assume: 1554 case Builtin::BI__builtin_assume: 1555 if (SemaBuiltinAssume(TheCall)) 1556 return ExprError(); 1557 break; 1558 case Builtin::BI__builtin_assume_aligned: 1559 if (SemaBuiltinAssumeAligned(TheCall)) 1560 return ExprError(); 1561 break; 1562 case Builtin::BI__builtin_dynamic_object_size: 1563 case Builtin::BI__builtin_object_size: 1564 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1565 return ExprError(); 1566 break; 1567 case Builtin::BI__builtin_longjmp: 1568 if (SemaBuiltinLongjmp(TheCall)) 1569 return ExprError(); 1570 break; 1571 case Builtin::BI__builtin_setjmp: 1572 if (SemaBuiltinSetjmp(TheCall)) 1573 return ExprError(); 1574 break; 1575 case Builtin::BI_setjmp: 1576 case Builtin::BI_setjmpex: 1577 if (checkArgCount(*this, TheCall, 1)) 1578 return true; 1579 break; 1580 case Builtin::BI__builtin_classify_type: 1581 if (checkArgCount(*this, TheCall, 1)) return true; 1582 TheCall->setType(Context.IntTy); 1583 break; 1584 case Builtin::BI__builtin_constant_p: { 1585 if (checkArgCount(*this, TheCall, 1)) return true; 1586 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1587 if (Arg.isInvalid()) return true; 1588 TheCall->setArg(0, Arg.get()); 1589 TheCall->setType(Context.IntTy); 1590 break; 1591 } 1592 case Builtin::BI__builtin_launder: 1593 return SemaBuiltinLaunder(*this, TheCall); 1594 case Builtin::BI__sync_fetch_and_add: 1595 case Builtin::BI__sync_fetch_and_add_1: 1596 case Builtin::BI__sync_fetch_and_add_2: 1597 case Builtin::BI__sync_fetch_and_add_4: 1598 case Builtin::BI__sync_fetch_and_add_8: 1599 case Builtin::BI__sync_fetch_and_add_16: 1600 case Builtin::BI__sync_fetch_and_sub: 1601 case Builtin::BI__sync_fetch_and_sub_1: 1602 case Builtin::BI__sync_fetch_and_sub_2: 1603 case Builtin::BI__sync_fetch_and_sub_4: 1604 case Builtin::BI__sync_fetch_and_sub_8: 1605 case Builtin::BI__sync_fetch_and_sub_16: 1606 case Builtin::BI__sync_fetch_and_or: 1607 case Builtin::BI__sync_fetch_and_or_1: 1608 case Builtin::BI__sync_fetch_and_or_2: 1609 case Builtin::BI__sync_fetch_and_or_4: 1610 case Builtin::BI__sync_fetch_and_or_8: 1611 case Builtin::BI__sync_fetch_and_or_16: 1612 case Builtin::BI__sync_fetch_and_and: 1613 case Builtin::BI__sync_fetch_and_and_1: 1614 case Builtin::BI__sync_fetch_and_and_2: 1615 case Builtin::BI__sync_fetch_and_and_4: 1616 case Builtin::BI__sync_fetch_and_and_8: 1617 case Builtin::BI__sync_fetch_and_and_16: 1618 case Builtin::BI__sync_fetch_and_xor: 1619 case Builtin::BI__sync_fetch_and_xor_1: 1620 case Builtin::BI__sync_fetch_and_xor_2: 1621 case Builtin::BI__sync_fetch_and_xor_4: 1622 case Builtin::BI__sync_fetch_and_xor_8: 1623 case Builtin::BI__sync_fetch_and_xor_16: 1624 case Builtin::BI__sync_fetch_and_nand: 1625 case Builtin::BI__sync_fetch_and_nand_1: 1626 case Builtin::BI__sync_fetch_and_nand_2: 1627 case Builtin::BI__sync_fetch_and_nand_4: 1628 case Builtin::BI__sync_fetch_and_nand_8: 1629 case Builtin::BI__sync_fetch_and_nand_16: 1630 case Builtin::BI__sync_add_and_fetch: 1631 case Builtin::BI__sync_add_and_fetch_1: 1632 case Builtin::BI__sync_add_and_fetch_2: 1633 case Builtin::BI__sync_add_and_fetch_4: 1634 case Builtin::BI__sync_add_and_fetch_8: 1635 case Builtin::BI__sync_add_and_fetch_16: 1636 case Builtin::BI__sync_sub_and_fetch: 1637 case Builtin::BI__sync_sub_and_fetch_1: 1638 case Builtin::BI__sync_sub_and_fetch_2: 1639 case Builtin::BI__sync_sub_and_fetch_4: 1640 case Builtin::BI__sync_sub_and_fetch_8: 1641 case Builtin::BI__sync_sub_and_fetch_16: 1642 case Builtin::BI__sync_and_and_fetch: 1643 case Builtin::BI__sync_and_and_fetch_1: 1644 case Builtin::BI__sync_and_and_fetch_2: 1645 case Builtin::BI__sync_and_and_fetch_4: 1646 case Builtin::BI__sync_and_and_fetch_8: 1647 case Builtin::BI__sync_and_and_fetch_16: 1648 case Builtin::BI__sync_or_and_fetch: 1649 case Builtin::BI__sync_or_and_fetch_1: 1650 case Builtin::BI__sync_or_and_fetch_2: 1651 case Builtin::BI__sync_or_and_fetch_4: 1652 case Builtin::BI__sync_or_and_fetch_8: 1653 case Builtin::BI__sync_or_and_fetch_16: 1654 case Builtin::BI__sync_xor_and_fetch: 1655 case Builtin::BI__sync_xor_and_fetch_1: 1656 case Builtin::BI__sync_xor_and_fetch_2: 1657 case Builtin::BI__sync_xor_and_fetch_4: 1658 case Builtin::BI__sync_xor_and_fetch_8: 1659 case Builtin::BI__sync_xor_and_fetch_16: 1660 case Builtin::BI__sync_nand_and_fetch: 1661 case Builtin::BI__sync_nand_and_fetch_1: 1662 case Builtin::BI__sync_nand_and_fetch_2: 1663 case Builtin::BI__sync_nand_and_fetch_4: 1664 case Builtin::BI__sync_nand_and_fetch_8: 1665 case Builtin::BI__sync_nand_and_fetch_16: 1666 case Builtin::BI__sync_val_compare_and_swap: 1667 case Builtin::BI__sync_val_compare_and_swap_1: 1668 case Builtin::BI__sync_val_compare_and_swap_2: 1669 case Builtin::BI__sync_val_compare_and_swap_4: 1670 case Builtin::BI__sync_val_compare_and_swap_8: 1671 case Builtin::BI__sync_val_compare_and_swap_16: 1672 case Builtin::BI__sync_bool_compare_and_swap: 1673 case Builtin::BI__sync_bool_compare_and_swap_1: 1674 case Builtin::BI__sync_bool_compare_and_swap_2: 1675 case Builtin::BI__sync_bool_compare_and_swap_4: 1676 case Builtin::BI__sync_bool_compare_and_swap_8: 1677 case Builtin::BI__sync_bool_compare_and_swap_16: 1678 case Builtin::BI__sync_lock_test_and_set: 1679 case Builtin::BI__sync_lock_test_and_set_1: 1680 case Builtin::BI__sync_lock_test_and_set_2: 1681 case Builtin::BI__sync_lock_test_and_set_4: 1682 case Builtin::BI__sync_lock_test_and_set_8: 1683 case Builtin::BI__sync_lock_test_and_set_16: 1684 case Builtin::BI__sync_lock_release: 1685 case Builtin::BI__sync_lock_release_1: 1686 case Builtin::BI__sync_lock_release_2: 1687 case Builtin::BI__sync_lock_release_4: 1688 case Builtin::BI__sync_lock_release_8: 1689 case Builtin::BI__sync_lock_release_16: 1690 case Builtin::BI__sync_swap: 1691 case Builtin::BI__sync_swap_1: 1692 case Builtin::BI__sync_swap_2: 1693 case Builtin::BI__sync_swap_4: 1694 case Builtin::BI__sync_swap_8: 1695 case Builtin::BI__sync_swap_16: 1696 return SemaBuiltinAtomicOverloaded(TheCallResult); 1697 case Builtin::BI__sync_synchronize: 1698 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1699 << TheCall->getCallee()->getSourceRange(); 1700 break; 1701 case Builtin::BI__builtin_nontemporal_load: 1702 case Builtin::BI__builtin_nontemporal_store: 1703 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1704 case Builtin::BI__builtin_memcpy_inline: { 1705 clang::Expr *SizeOp = TheCall->getArg(2); 1706 // We warn about copying to or from `nullptr` pointers when `size` is 1707 // greater than 0. When `size` is value dependent we cannot evaluate its 1708 // value so we bail out. 1709 if (SizeOp->isValueDependent()) 1710 break; 1711 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1712 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1713 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1714 } 1715 break; 1716 } 1717 #define BUILTIN(ID, TYPE, ATTRS) 1718 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1719 case Builtin::BI##ID: \ 1720 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1721 #include "clang/Basic/Builtins.def" 1722 case Builtin::BI__annotation: 1723 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1724 return ExprError(); 1725 break; 1726 case Builtin::BI__builtin_annotation: 1727 if (SemaBuiltinAnnotation(*this, TheCall)) 1728 return ExprError(); 1729 break; 1730 case Builtin::BI__builtin_addressof: 1731 if (SemaBuiltinAddressof(*this, TheCall)) 1732 return ExprError(); 1733 break; 1734 case Builtin::BI__builtin_is_aligned: 1735 case Builtin::BI__builtin_align_up: 1736 case Builtin::BI__builtin_align_down: 1737 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1738 return ExprError(); 1739 break; 1740 case Builtin::BI__builtin_add_overflow: 1741 case Builtin::BI__builtin_sub_overflow: 1742 case Builtin::BI__builtin_mul_overflow: 1743 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1744 return ExprError(); 1745 break; 1746 case Builtin::BI__builtin_operator_new: 1747 case Builtin::BI__builtin_operator_delete: { 1748 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1749 ExprResult Res = 1750 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1751 if (Res.isInvalid()) 1752 CorrectDelayedTyposInExpr(TheCallResult.get()); 1753 return Res; 1754 } 1755 case Builtin::BI__builtin_dump_struct: { 1756 // We first want to ensure we are called with 2 arguments 1757 if (checkArgCount(*this, TheCall, 2)) 1758 return ExprError(); 1759 // Ensure that the first argument is of type 'struct XX *' 1760 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1761 const QualType PtrArgType = PtrArg->getType(); 1762 if (!PtrArgType->isPointerType() || 1763 !PtrArgType->getPointeeType()->isRecordType()) { 1764 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1765 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1766 << "structure pointer"; 1767 return ExprError(); 1768 } 1769 1770 // Ensure that the second argument is of type 'FunctionType' 1771 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1772 const QualType FnPtrArgType = FnPtrArg->getType(); 1773 if (!FnPtrArgType->isPointerType()) { 1774 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1775 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1776 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1777 return ExprError(); 1778 } 1779 1780 const auto *FuncType = 1781 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1782 1783 if (!FuncType) { 1784 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1785 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1786 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1787 return ExprError(); 1788 } 1789 1790 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1791 if (!FT->getNumParams()) { 1792 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1793 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1794 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1795 return ExprError(); 1796 } 1797 QualType PT = FT->getParamType(0); 1798 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1799 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1800 !PT->getPointeeType().isConstQualified()) { 1801 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1802 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1803 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1804 return ExprError(); 1805 } 1806 } 1807 1808 TheCall->setType(Context.IntTy); 1809 break; 1810 } 1811 case Builtin::BI__builtin_expect_with_probability: { 1812 // We first want to ensure we are called with 3 arguments 1813 if (checkArgCount(*this, TheCall, 3)) 1814 return ExprError(); 1815 // then check probability is constant float in range [0.0, 1.0] 1816 const Expr *ProbArg = TheCall->getArg(2); 1817 SmallVector<PartialDiagnosticAt, 8> Notes; 1818 Expr::EvalResult Eval; 1819 Eval.Diag = &Notes; 1820 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 1821 Context)) || 1822 !Eval.Val.isFloat()) { 1823 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1824 << ProbArg->getSourceRange(); 1825 for (const PartialDiagnosticAt &PDiag : Notes) 1826 Diag(PDiag.first, PDiag.second); 1827 return ExprError(); 1828 } 1829 llvm::APFloat Probability = Eval.Val.getFloat(); 1830 bool LoseInfo = false; 1831 Probability.convert(llvm::APFloat::IEEEdouble(), 1832 llvm::RoundingMode::Dynamic, &LoseInfo); 1833 if (!(Probability >= llvm::APFloat(0.0) && 1834 Probability <= llvm::APFloat(1.0))) { 1835 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1836 << ProbArg->getSourceRange(); 1837 return ExprError(); 1838 } 1839 break; 1840 } 1841 case Builtin::BI__builtin_preserve_access_index: 1842 if (SemaBuiltinPreserveAI(*this, TheCall)) 1843 return ExprError(); 1844 break; 1845 case Builtin::BI__builtin_call_with_static_chain: 1846 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1847 return ExprError(); 1848 break; 1849 case Builtin::BI__exception_code: 1850 case Builtin::BI_exception_code: 1851 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1852 diag::err_seh___except_block)) 1853 return ExprError(); 1854 break; 1855 case Builtin::BI__exception_info: 1856 case Builtin::BI_exception_info: 1857 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1858 diag::err_seh___except_filter)) 1859 return ExprError(); 1860 break; 1861 case Builtin::BI__GetExceptionInfo: 1862 if (checkArgCount(*this, TheCall, 1)) 1863 return ExprError(); 1864 1865 if (CheckCXXThrowOperand( 1866 TheCall->getBeginLoc(), 1867 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1868 TheCall)) 1869 return ExprError(); 1870 1871 TheCall->setType(Context.VoidPtrTy); 1872 break; 1873 // OpenCL v2.0, s6.13.16 - Pipe functions 1874 case Builtin::BIread_pipe: 1875 case Builtin::BIwrite_pipe: 1876 // Since those two functions are declared with var args, we need a semantic 1877 // check for the argument. 1878 if (SemaBuiltinRWPipe(*this, TheCall)) 1879 return ExprError(); 1880 break; 1881 case Builtin::BIreserve_read_pipe: 1882 case Builtin::BIreserve_write_pipe: 1883 case Builtin::BIwork_group_reserve_read_pipe: 1884 case Builtin::BIwork_group_reserve_write_pipe: 1885 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1886 return ExprError(); 1887 break; 1888 case Builtin::BIsub_group_reserve_read_pipe: 1889 case Builtin::BIsub_group_reserve_write_pipe: 1890 if (checkOpenCLSubgroupExt(*this, TheCall) || 1891 SemaBuiltinReserveRWPipe(*this, TheCall)) 1892 return ExprError(); 1893 break; 1894 case Builtin::BIcommit_read_pipe: 1895 case Builtin::BIcommit_write_pipe: 1896 case Builtin::BIwork_group_commit_read_pipe: 1897 case Builtin::BIwork_group_commit_write_pipe: 1898 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1899 return ExprError(); 1900 break; 1901 case Builtin::BIsub_group_commit_read_pipe: 1902 case Builtin::BIsub_group_commit_write_pipe: 1903 if (checkOpenCLSubgroupExt(*this, TheCall) || 1904 SemaBuiltinCommitRWPipe(*this, TheCall)) 1905 return ExprError(); 1906 break; 1907 case Builtin::BIget_pipe_num_packets: 1908 case Builtin::BIget_pipe_max_packets: 1909 if (SemaBuiltinPipePackets(*this, TheCall)) 1910 return ExprError(); 1911 break; 1912 case Builtin::BIto_global: 1913 case Builtin::BIto_local: 1914 case Builtin::BIto_private: 1915 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1916 return ExprError(); 1917 break; 1918 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1919 case Builtin::BIenqueue_kernel: 1920 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1921 return ExprError(); 1922 break; 1923 case Builtin::BIget_kernel_work_group_size: 1924 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1925 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1926 return ExprError(); 1927 break; 1928 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1929 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1930 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1931 return ExprError(); 1932 break; 1933 case Builtin::BI__builtin_os_log_format: 1934 Cleanup.setExprNeedsCleanups(true); 1935 LLVM_FALLTHROUGH; 1936 case Builtin::BI__builtin_os_log_format_buffer_size: 1937 if (SemaBuiltinOSLogFormat(TheCall)) 1938 return ExprError(); 1939 break; 1940 case Builtin::BI__builtin_frame_address: 1941 case Builtin::BI__builtin_return_address: { 1942 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1943 return ExprError(); 1944 1945 // -Wframe-address warning if non-zero passed to builtin 1946 // return/frame address. 1947 Expr::EvalResult Result; 1948 if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1949 Result.Val.getInt() != 0) 1950 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1951 << ((BuiltinID == Builtin::BI__builtin_return_address) 1952 ? "__builtin_return_address" 1953 : "__builtin_frame_address") 1954 << TheCall->getSourceRange(); 1955 break; 1956 } 1957 1958 case Builtin::BI__builtin_matrix_transpose: 1959 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1960 1961 case Builtin::BI__builtin_matrix_column_major_load: 1962 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1963 1964 case Builtin::BI__builtin_matrix_column_major_store: 1965 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1966 } 1967 1968 // Since the target specific builtins for each arch overlap, only check those 1969 // of the arch we are compiling for. 1970 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1971 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1972 assert(Context.getAuxTargetInfo() && 1973 "Aux Target Builtin, but not an aux target?"); 1974 1975 if (CheckTSBuiltinFunctionCall( 1976 *Context.getAuxTargetInfo(), 1977 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 1978 return ExprError(); 1979 } else { 1980 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 1981 TheCall)) 1982 return ExprError(); 1983 } 1984 } 1985 1986 return TheCallResult; 1987 } 1988 1989 // Get the valid immediate range for the specified NEON type code. 1990 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1991 NeonTypeFlags Type(t); 1992 int IsQuad = ForceQuad ? true : Type.isQuad(); 1993 switch (Type.getEltType()) { 1994 case NeonTypeFlags::Int8: 1995 case NeonTypeFlags::Poly8: 1996 return shift ? 7 : (8 << IsQuad) - 1; 1997 case NeonTypeFlags::Int16: 1998 case NeonTypeFlags::Poly16: 1999 return shift ? 15 : (4 << IsQuad) - 1; 2000 case NeonTypeFlags::Int32: 2001 return shift ? 31 : (2 << IsQuad) - 1; 2002 case NeonTypeFlags::Int64: 2003 case NeonTypeFlags::Poly64: 2004 return shift ? 63 : (1 << IsQuad) - 1; 2005 case NeonTypeFlags::Poly128: 2006 return shift ? 127 : (1 << IsQuad) - 1; 2007 case NeonTypeFlags::Float16: 2008 assert(!shift && "cannot shift float types!"); 2009 return (4 << IsQuad) - 1; 2010 case NeonTypeFlags::Float32: 2011 assert(!shift && "cannot shift float types!"); 2012 return (2 << IsQuad) - 1; 2013 case NeonTypeFlags::Float64: 2014 assert(!shift && "cannot shift float types!"); 2015 return (1 << IsQuad) - 1; 2016 case NeonTypeFlags::BFloat16: 2017 assert(!shift && "cannot shift float types!"); 2018 return (4 << IsQuad) - 1; 2019 } 2020 llvm_unreachable("Invalid NeonTypeFlag!"); 2021 } 2022 2023 /// getNeonEltType - Return the QualType corresponding to the elements of 2024 /// the vector type specified by the NeonTypeFlags. This is used to check 2025 /// the pointer arguments for Neon load/store intrinsics. 2026 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2027 bool IsPolyUnsigned, bool IsInt64Long) { 2028 switch (Flags.getEltType()) { 2029 case NeonTypeFlags::Int8: 2030 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2031 case NeonTypeFlags::Int16: 2032 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2033 case NeonTypeFlags::Int32: 2034 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2035 case NeonTypeFlags::Int64: 2036 if (IsInt64Long) 2037 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2038 else 2039 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2040 : Context.LongLongTy; 2041 case NeonTypeFlags::Poly8: 2042 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2043 case NeonTypeFlags::Poly16: 2044 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2045 case NeonTypeFlags::Poly64: 2046 if (IsInt64Long) 2047 return Context.UnsignedLongTy; 2048 else 2049 return Context.UnsignedLongLongTy; 2050 case NeonTypeFlags::Poly128: 2051 break; 2052 case NeonTypeFlags::Float16: 2053 return Context.HalfTy; 2054 case NeonTypeFlags::Float32: 2055 return Context.FloatTy; 2056 case NeonTypeFlags::Float64: 2057 return Context.DoubleTy; 2058 case NeonTypeFlags::BFloat16: 2059 return Context.BFloat16Ty; 2060 } 2061 llvm_unreachable("Invalid NeonTypeFlag!"); 2062 } 2063 2064 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2065 // Range check SVE intrinsics that take immediate values. 2066 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2067 2068 switch (BuiltinID) { 2069 default: 2070 return false; 2071 #define GET_SVE_IMMEDIATE_CHECK 2072 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2073 #undef GET_SVE_IMMEDIATE_CHECK 2074 } 2075 2076 // Perform all the immediate checks for this builtin call. 2077 bool HasError = false; 2078 for (auto &I : ImmChecks) { 2079 int ArgNum, CheckTy, ElementSizeInBits; 2080 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2081 2082 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2083 2084 // Function that checks whether the operand (ArgNum) is an immediate 2085 // that is one of the predefined values. 2086 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2087 int ErrDiag) -> bool { 2088 // We can't check the value of a dependent argument. 2089 Expr *Arg = TheCall->getArg(ArgNum); 2090 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2091 return false; 2092 2093 // Check constant-ness first. 2094 llvm::APSInt Imm; 2095 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2096 return true; 2097 2098 if (!CheckImm(Imm.getSExtValue())) 2099 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2100 return false; 2101 }; 2102 2103 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2104 case SVETypeFlags::ImmCheck0_31: 2105 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2106 HasError = true; 2107 break; 2108 case SVETypeFlags::ImmCheck0_13: 2109 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2110 HasError = true; 2111 break; 2112 case SVETypeFlags::ImmCheck1_16: 2113 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2114 HasError = true; 2115 break; 2116 case SVETypeFlags::ImmCheck0_7: 2117 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2118 HasError = true; 2119 break; 2120 case SVETypeFlags::ImmCheckExtract: 2121 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2122 (2048 / ElementSizeInBits) - 1)) 2123 HasError = true; 2124 break; 2125 case SVETypeFlags::ImmCheckShiftRight: 2126 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2127 HasError = true; 2128 break; 2129 case SVETypeFlags::ImmCheckShiftRightNarrow: 2130 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2131 ElementSizeInBits / 2)) 2132 HasError = true; 2133 break; 2134 case SVETypeFlags::ImmCheckShiftLeft: 2135 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2136 ElementSizeInBits - 1)) 2137 HasError = true; 2138 break; 2139 case SVETypeFlags::ImmCheckLaneIndex: 2140 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2141 (128 / (1 * ElementSizeInBits)) - 1)) 2142 HasError = true; 2143 break; 2144 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2145 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2146 (128 / (2 * ElementSizeInBits)) - 1)) 2147 HasError = true; 2148 break; 2149 case SVETypeFlags::ImmCheckLaneIndexDot: 2150 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2151 (128 / (4 * ElementSizeInBits)) - 1)) 2152 HasError = true; 2153 break; 2154 case SVETypeFlags::ImmCheckComplexRot90_270: 2155 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2156 diag::err_rotation_argument_to_cadd)) 2157 HasError = true; 2158 break; 2159 case SVETypeFlags::ImmCheckComplexRotAll90: 2160 if (CheckImmediateInSet( 2161 [](int64_t V) { 2162 return V == 0 || V == 90 || V == 180 || V == 270; 2163 }, 2164 diag::err_rotation_argument_to_cmla)) 2165 HasError = true; 2166 break; 2167 case SVETypeFlags::ImmCheck0_1: 2168 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2169 HasError = true; 2170 break; 2171 case SVETypeFlags::ImmCheck0_2: 2172 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2173 HasError = true; 2174 break; 2175 case SVETypeFlags::ImmCheck0_3: 2176 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2177 HasError = true; 2178 break; 2179 } 2180 } 2181 2182 return HasError; 2183 } 2184 2185 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2186 unsigned BuiltinID, CallExpr *TheCall) { 2187 llvm::APSInt Result; 2188 uint64_t mask = 0; 2189 unsigned TV = 0; 2190 int PtrArgNum = -1; 2191 bool HasConstPtr = false; 2192 switch (BuiltinID) { 2193 #define GET_NEON_OVERLOAD_CHECK 2194 #include "clang/Basic/arm_neon.inc" 2195 #include "clang/Basic/arm_fp16.inc" 2196 #undef GET_NEON_OVERLOAD_CHECK 2197 } 2198 2199 // For NEON intrinsics which are overloaded on vector element type, validate 2200 // the immediate which specifies which variant to emit. 2201 unsigned ImmArg = TheCall->getNumArgs()-1; 2202 if (mask) { 2203 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2204 return true; 2205 2206 TV = Result.getLimitedValue(64); 2207 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2208 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2209 << TheCall->getArg(ImmArg)->getSourceRange(); 2210 } 2211 2212 if (PtrArgNum >= 0) { 2213 // Check that pointer arguments have the specified type. 2214 Expr *Arg = TheCall->getArg(PtrArgNum); 2215 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2216 Arg = ICE->getSubExpr(); 2217 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2218 QualType RHSTy = RHS.get()->getType(); 2219 2220 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2221 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2222 Arch == llvm::Triple::aarch64_32 || 2223 Arch == llvm::Triple::aarch64_be; 2224 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2225 QualType EltTy = 2226 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2227 if (HasConstPtr) 2228 EltTy = EltTy.withConst(); 2229 QualType LHSTy = Context.getPointerType(EltTy); 2230 AssignConvertType ConvTy; 2231 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2232 if (RHS.isInvalid()) 2233 return true; 2234 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2235 RHS.get(), AA_Assigning)) 2236 return true; 2237 } 2238 2239 // For NEON intrinsics which take an immediate value as part of the 2240 // instruction, range check them here. 2241 unsigned i = 0, l = 0, u = 0; 2242 switch (BuiltinID) { 2243 default: 2244 return false; 2245 #define GET_NEON_IMMEDIATE_CHECK 2246 #include "clang/Basic/arm_neon.inc" 2247 #include "clang/Basic/arm_fp16.inc" 2248 #undef GET_NEON_IMMEDIATE_CHECK 2249 } 2250 2251 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2252 } 2253 2254 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2255 switch (BuiltinID) { 2256 default: 2257 return false; 2258 #include "clang/Basic/arm_mve_builtin_sema.inc" 2259 } 2260 } 2261 2262 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2263 CallExpr *TheCall) { 2264 bool Err = false; 2265 switch (BuiltinID) { 2266 default: 2267 return false; 2268 #include "clang/Basic/arm_cde_builtin_sema.inc" 2269 } 2270 2271 if (Err) 2272 return true; 2273 2274 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2275 } 2276 2277 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2278 const Expr *CoprocArg, bool WantCDE) { 2279 if (isConstantEvaluated()) 2280 return false; 2281 2282 // We can't check the value of a dependent argument. 2283 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2284 return false; 2285 2286 llvm::APSInt CoprocNoAP; 2287 bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context); 2288 (void)IsICE; 2289 assert(IsICE && "Coprocossor immediate is not a constant expression"); 2290 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2291 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2292 2293 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2294 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2295 2296 if (IsCDECoproc != WantCDE) 2297 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2298 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2299 2300 return false; 2301 } 2302 2303 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2304 unsigned MaxWidth) { 2305 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2306 BuiltinID == ARM::BI__builtin_arm_ldaex || 2307 BuiltinID == ARM::BI__builtin_arm_strex || 2308 BuiltinID == ARM::BI__builtin_arm_stlex || 2309 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2310 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2311 BuiltinID == AArch64::BI__builtin_arm_strex || 2312 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2313 "unexpected ARM builtin"); 2314 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2315 BuiltinID == ARM::BI__builtin_arm_ldaex || 2316 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2317 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2318 2319 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2320 2321 // Ensure that we have the proper number of arguments. 2322 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2323 return true; 2324 2325 // Inspect the pointer argument of the atomic builtin. This should always be 2326 // a pointer type, whose element is an integral scalar or pointer type. 2327 // Because it is a pointer type, we don't have to worry about any implicit 2328 // casts here. 2329 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2330 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2331 if (PointerArgRes.isInvalid()) 2332 return true; 2333 PointerArg = PointerArgRes.get(); 2334 2335 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2336 if (!pointerType) { 2337 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2338 << PointerArg->getType() << PointerArg->getSourceRange(); 2339 return true; 2340 } 2341 2342 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2343 // task is to insert the appropriate casts into the AST. First work out just 2344 // what the appropriate type is. 2345 QualType ValType = pointerType->getPointeeType(); 2346 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2347 if (IsLdrex) 2348 AddrType.addConst(); 2349 2350 // Issue a warning if the cast is dodgy. 2351 CastKind CastNeeded = CK_NoOp; 2352 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2353 CastNeeded = CK_BitCast; 2354 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2355 << PointerArg->getType() << Context.getPointerType(AddrType) 2356 << AA_Passing << PointerArg->getSourceRange(); 2357 } 2358 2359 // Finally, do the cast and replace the argument with the corrected version. 2360 AddrType = Context.getPointerType(AddrType); 2361 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2362 if (PointerArgRes.isInvalid()) 2363 return true; 2364 PointerArg = PointerArgRes.get(); 2365 2366 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2367 2368 // In general, we allow ints, floats and pointers to be loaded and stored. 2369 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2370 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2371 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2372 << PointerArg->getType() << PointerArg->getSourceRange(); 2373 return true; 2374 } 2375 2376 // But ARM doesn't have instructions to deal with 128-bit versions. 2377 if (Context.getTypeSize(ValType) > MaxWidth) { 2378 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2379 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2380 << PointerArg->getType() << PointerArg->getSourceRange(); 2381 return true; 2382 } 2383 2384 switch (ValType.getObjCLifetime()) { 2385 case Qualifiers::OCL_None: 2386 case Qualifiers::OCL_ExplicitNone: 2387 // okay 2388 break; 2389 2390 case Qualifiers::OCL_Weak: 2391 case Qualifiers::OCL_Strong: 2392 case Qualifiers::OCL_Autoreleasing: 2393 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2394 << ValType << PointerArg->getSourceRange(); 2395 return true; 2396 } 2397 2398 if (IsLdrex) { 2399 TheCall->setType(ValType); 2400 return false; 2401 } 2402 2403 // Initialize the argument to be stored. 2404 ExprResult ValArg = TheCall->getArg(0); 2405 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2406 Context, ValType, /*consume*/ false); 2407 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2408 if (ValArg.isInvalid()) 2409 return true; 2410 TheCall->setArg(0, ValArg.get()); 2411 2412 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2413 // but the custom checker bypasses all default analysis. 2414 TheCall->setType(Context.IntTy); 2415 return false; 2416 } 2417 2418 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2419 CallExpr *TheCall) { 2420 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2421 BuiltinID == ARM::BI__builtin_arm_ldaex || 2422 BuiltinID == ARM::BI__builtin_arm_strex || 2423 BuiltinID == ARM::BI__builtin_arm_stlex) { 2424 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2425 } 2426 2427 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2428 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2429 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2430 } 2431 2432 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2433 BuiltinID == ARM::BI__builtin_arm_wsr64) 2434 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2435 2436 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2437 BuiltinID == ARM::BI__builtin_arm_rsrp || 2438 BuiltinID == ARM::BI__builtin_arm_wsr || 2439 BuiltinID == ARM::BI__builtin_arm_wsrp) 2440 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2441 2442 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2443 return true; 2444 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2445 return true; 2446 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2447 return true; 2448 2449 // For intrinsics which take an immediate value as part of the instruction, 2450 // range check them here. 2451 // FIXME: VFP Intrinsics should error if VFP not present. 2452 switch (BuiltinID) { 2453 default: return false; 2454 case ARM::BI__builtin_arm_ssat: 2455 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2456 case ARM::BI__builtin_arm_usat: 2457 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2458 case ARM::BI__builtin_arm_ssat16: 2459 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2460 case ARM::BI__builtin_arm_usat16: 2461 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2462 case ARM::BI__builtin_arm_vcvtr_f: 2463 case ARM::BI__builtin_arm_vcvtr_d: 2464 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2465 case ARM::BI__builtin_arm_dmb: 2466 case ARM::BI__builtin_arm_dsb: 2467 case ARM::BI__builtin_arm_isb: 2468 case ARM::BI__builtin_arm_dbg: 2469 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2470 case ARM::BI__builtin_arm_cdp: 2471 case ARM::BI__builtin_arm_cdp2: 2472 case ARM::BI__builtin_arm_mcr: 2473 case ARM::BI__builtin_arm_mcr2: 2474 case ARM::BI__builtin_arm_mrc: 2475 case ARM::BI__builtin_arm_mrc2: 2476 case ARM::BI__builtin_arm_mcrr: 2477 case ARM::BI__builtin_arm_mcrr2: 2478 case ARM::BI__builtin_arm_mrrc: 2479 case ARM::BI__builtin_arm_mrrc2: 2480 case ARM::BI__builtin_arm_ldc: 2481 case ARM::BI__builtin_arm_ldcl: 2482 case ARM::BI__builtin_arm_ldc2: 2483 case ARM::BI__builtin_arm_ldc2l: 2484 case ARM::BI__builtin_arm_stc: 2485 case ARM::BI__builtin_arm_stcl: 2486 case ARM::BI__builtin_arm_stc2: 2487 case ARM::BI__builtin_arm_stc2l: 2488 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2489 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2490 /*WantCDE*/ false); 2491 } 2492 } 2493 2494 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2495 unsigned BuiltinID, 2496 CallExpr *TheCall) { 2497 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2498 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2499 BuiltinID == AArch64::BI__builtin_arm_strex || 2500 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2501 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2502 } 2503 2504 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2505 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2506 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2507 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2508 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2509 } 2510 2511 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2512 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2513 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2514 2515 // Memory Tagging Extensions (MTE) Intrinsics 2516 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2517 BuiltinID == AArch64::BI__builtin_arm_addg || 2518 BuiltinID == AArch64::BI__builtin_arm_gmi || 2519 BuiltinID == AArch64::BI__builtin_arm_ldg || 2520 BuiltinID == AArch64::BI__builtin_arm_stg || 2521 BuiltinID == AArch64::BI__builtin_arm_subp) { 2522 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2523 } 2524 2525 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2526 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2527 BuiltinID == AArch64::BI__builtin_arm_wsr || 2528 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2529 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2530 2531 // Only check the valid encoding range. Any constant in this range would be 2532 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2533 // an exception for incorrect registers. This matches MSVC behavior. 2534 if (BuiltinID == AArch64::BI_ReadStatusReg || 2535 BuiltinID == AArch64::BI_WriteStatusReg) 2536 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2537 2538 if (BuiltinID == AArch64::BI__getReg) 2539 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2540 2541 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2542 return true; 2543 2544 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2545 return true; 2546 2547 // For intrinsics which take an immediate value as part of the instruction, 2548 // range check them here. 2549 unsigned i = 0, l = 0, u = 0; 2550 switch (BuiltinID) { 2551 default: return false; 2552 case AArch64::BI__builtin_arm_dmb: 2553 case AArch64::BI__builtin_arm_dsb: 2554 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2555 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2556 } 2557 2558 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2559 } 2560 2561 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2562 CallExpr *TheCall) { 2563 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2564 BuiltinID == BPF::BI__builtin_btf_type_id) && 2565 "unexpected ARM builtin"); 2566 2567 if (checkArgCount(*this, TheCall, 2)) 2568 return true; 2569 2570 Expr *Arg; 2571 if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2572 // The second argument needs to be a constant int 2573 llvm::APSInt Value; 2574 Arg = TheCall->getArg(1); 2575 if (!Arg->isIntegerConstantExpr(Value, Context)) { 2576 Diag(Arg->getBeginLoc(), diag::err_btf_type_id_not_const) 2577 << 2 << Arg->getSourceRange(); 2578 return true; 2579 } 2580 2581 TheCall->setType(Context.UnsignedIntTy); 2582 return false; 2583 } 2584 2585 // The first argument needs to be a record field access. 2586 // If it is an array element access, we delay decision 2587 // to BPF backend to check whether the access is a 2588 // field access or not. 2589 Arg = TheCall->getArg(0); 2590 if (Arg->getType()->getAsPlaceholderType() || 2591 (Arg->IgnoreParens()->getObjectKind() != OK_BitField && 2592 !dyn_cast<MemberExpr>(Arg->IgnoreParens()) && 2593 !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) { 2594 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field) 2595 << 1 << Arg->getSourceRange(); 2596 return true; 2597 } 2598 2599 // The second argument needs to be a constant int 2600 Arg = TheCall->getArg(1); 2601 llvm::APSInt Value; 2602 if (!Arg->isIntegerConstantExpr(Value, Context)) { 2603 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const) 2604 << 2 << Arg->getSourceRange(); 2605 return true; 2606 } 2607 2608 TheCall->setType(Context.UnsignedIntTy); 2609 return false; 2610 } 2611 2612 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2613 struct ArgInfo { 2614 uint8_t OpNum; 2615 bool IsSigned; 2616 uint8_t BitWidth; 2617 uint8_t Align; 2618 }; 2619 struct BuiltinInfo { 2620 unsigned BuiltinID; 2621 ArgInfo Infos[2]; 2622 }; 2623 2624 static BuiltinInfo Infos[] = { 2625 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2626 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2627 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2628 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2629 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2630 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2631 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2632 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2633 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2634 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2635 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2636 2637 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2638 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2639 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2640 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2641 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2642 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2643 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2644 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2645 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2646 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2647 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2648 2649 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2650 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2651 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2652 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2653 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2654 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2655 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2656 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2657 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2658 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2659 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2660 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2661 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2662 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2663 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2664 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2665 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2666 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2667 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2668 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2669 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2670 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2671 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2672 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2673 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2674 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2675 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2676 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2677 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2678 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2679 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2680 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2681 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2682 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2683 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2684 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2685 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2686 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2687 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2688 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2689 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2690 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2691 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2692 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2693 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2694 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2695 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2696 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2697 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2698 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2699 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2700 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2701 {{ 1, false, 6, 0 }} }, 2702 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2703 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2704 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2705 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2706 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2707 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2708 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2709 {{ 1, false, 5, 0 }} }, 2710 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2711 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2712 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2713 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2714 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2715 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2716 { 2, false, 5, 0 }} }, 2717 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2718 { 2, false, 6, 0 }} }, 2719 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2720 { 3, false, 5, 0 }} }, 2721 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2722 { 3, false, 6, 0 }} }, 2723 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2724 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2725 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2726 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2727 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2728 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2729 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2730 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2731 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2732 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2733 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2734 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2735 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2736 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2737 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2738 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2739 {{ 2, false, 4, 0 }, 2740 { 3, false, 5, 0 }} }, 2741 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2742 {{ 2, false, 4, 0 }, 2743 { 3, false, 5, 0 }} }, 2744 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2745 {{ 2, false, 4, 0 }, 2746 { 3, false, 5, 0 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2748 {{ 2, false, 4, 0 }, 2749 { 3, false, 5, 0 }} }, 2750 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2758 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2760 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2761 { 2, false, 5, 0 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2763 { 2, false, 6, 0 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2767 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2768 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2773 {{ 1, false, 4, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2776 {{ 1, false, 4, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2797 {{ 3, false, 1, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2802 {{ 3, false, 1, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2807 {{ 3, false, 1, 0 }} }, 2808 }; 2809 2810 // Use a dynamically initialized static to sort the table exactly once on 2811 // first run. 2812 static const bool SortOnce = 2813 (llvm::sort(Infos, 2814 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2815 return LHS.BuiltinID < RHS.BuiltinID; 2816 }), 2817 true); 2818 (void)SortOnce; 2819 2820 const BuiltinInfo *F = llvm::partition_point( 2821 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2822 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2823 return false; 2824 2825 bool Error = false; 2826 2827 for (const ArgInfo &A : F->Infos) { 2828 // Ignore empty ArgInfo elements. 2829 if (A.BitWidth == 0) 2830 continue; 2831 2832 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2833 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2834 if (!A.Align) { 2835 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2836 } else { 2837 unsigned M = 1 << A.Align; 2838 Min *= M; 2839 Max *= M; 2840 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2841 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2842 } 2843 } 2844 return Error; 2845 } 2846 2847 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2848 CallExpr *TheCall) { 2849 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2850 } 2851 2852 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2853 unsigned BuiltinID, CallExpr *TheCall) { 2854 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2855 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2856 } 2857 2858 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2859 CallExpr *TheCall) { 2860 2861 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2862 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2863 if (!TI.hasFeature("dsp")) 2864 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2865 } 2866 2867 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2868 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2869 if (!TI.hasFeature("dspr2")) 2870 return Diag(TheCall->getBeginLoc(), 2871 diag::err_mips_builtin_requires_dspr2); 2872 } 2873 2874 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2875 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2876 if (!TI.hasFeature("msa")) 2877 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2878 } 2879 2880 return false; 2881 } 2882 2883 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2884 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2885 // ordering for DSP is unspecified. MSA is ordered by the data format used 2886 // by the underlying instruction i.e., df/m, df/n and then by size. 2887 // 2888 // FIXME: The size tests here should instead be tablegen'd along with the 2889 // definitions from include/clang/Basic/BuiltinsMips.def. 2890 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2891 // be too. 2892 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2893 unsigned i = 0, l = 0, u = 0, m = 0; 2894 switch (BuiltinID) { 2895 default: return false; 2896 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2897 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2898 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2899 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2900 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2901 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2902 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2903 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 2904 // df/m field. 2905 // These intrinsics take an unsigned 3 bit immediate. 2906 case Mips::BI__builtin_msa_bclri_b: 2907 case Mips::BI__builtin_msa_bnegi_b: 2908 case Mips::BI__builtin_msa_bseti_b: 2909 case Mips::BI__builtin_msa_sat_s_b: 2910 case Mips::BI__builtin_msa_sat_u_b: 2911 case Mips::BI__builtin_msa_slli_b: 2912 case Mips::BI__builtin_msa_srai_b: 2913 case Mips::BI__builtin_msa_srari_b: 2914 case Mips::BI__builtin_msa_srli_b: 2915 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2916 case Mips::BI__builtin_msa_binsli_b: 2917 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2918 // These intrinsics take an unsigned 4 bit immediate. 2919 case Mips::BI__builtin_msa_bclri_h: 2920 case Mips::BI__builtin_msa_bnegi_h: 2921 case Mips::BI__builtin_msa_bseti_h: 2922 case Mips::BI__builtin_msa_sat_s_h: 2923 case Mips::BI__builtin_msa_sat_u_h: 2924 case Mips::BI__builtin_msa_slli_h: 2925 case Mips::BI__builtin_msa_srai_h: 2926 case Mips::BI__builtin_msa_srari_h: 2927 case Mips::BI__builtin_msa_srli_h: 2928 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2929 case Mips::BI__builtin_msa_binsli_h: 2930 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2931 // These intrinsics take an unsigned 5 bit immediate. 2932 // The first block of intrinsics actually have an unsigned 5 bit field, 2933 // not a df/n field. 2934 case Mips::BI__builtin_msa_cfcmsa: 2935 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 2936 case Mips::BI__builtin_msa_clei_u_b: 2937 case Mips::BI__builtin_msa_clei_u_h: 2938 case Mips::BI__builtin_msa_clei_u_w: 2939 case Mips::BI__builtin_msa_clei_u_d: 2940 case Mips::BI__builtin_msa_clti_u_b: 2941 case Mips::BI__builtin_msa_clti_u_h: 2942 case Mips::BI__builtin_msa_clti_u_w: 2943 case Mips::BI__builtin_msa_clti_u_d: 2944 case Mips::BI__builtin_msa_maxi_u_b: 2945 case Mips::BI__builtin_msa_maxi_u_h: 2946 case Mips::BI__builtin_msa_maxi_u_w: 2947 case Mips::BI__builtin_msa_maxi_u_d: 2948 case Mips::BI__builtin_msa_mini_u_b: 2949 case Mips::BI__builtin_msa_mini_u_h: 2950 case Mips::BI__builtin_msa_mini_u_w: 2951 case Mips::BI__builtin_msa_mini_u_d: 2952 case Mips::BI__builtin_msa_addvi_b: 2953 case Mips::BI__builtin_msa_addvi_h: 2954 case Mips::BI__builtin_msa_addvi_w: 2955 case Mips::BI__builtin_msa_addvi_d: 2956 case Mips::BI__builtin_msa_bclri_w: 2957 case Mips::BI__builtin_msa_bnegi_w: 2958 case Mips::BI__builtin_msa_bseti_w: 2959 case Mips::BI__builtin_msa_sat_s_w: 2960 case Mips::BI__builtin_msa_sat_u_w: 2961 case Mips::BI__builtin_msa_slli_w: 2962 case Mips::BI__builtin_msa_srai_w: 2963 case Mips::BI__builtin_msa_srari_w: 2964 case Mips::BI__builtin_msa_srli_w: 2965 case Mips::BI__builtin_msa_srlri_w: 2966 case Mips::BI__builtin_msa_subvi_b: 2967 case Mips::BI__builtin_msa_subvi_h: 2968 case Mips::BI__builtin_msa_subvi_w: 2969 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2970 case Mips::BI__builtin_msa_binsli_w: 2971 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2972 // These intrinsics take an unsigned 6 bit immediate. 2973 case Mips::BI__builtin_msa_bclri_d: 2974 case Mips::BI__builtin_msa_bnegi_d: 2975 case Mips::BI__builtin_msa_bseti_d: 2976 case Mips::BI__builtin_msa_sat_s_d: 2977 case Mips::BI__builtin_msa_sat_u_d: 2978 case Mips::BI__builtin_msa_slli_d: 2979 case Mips::BI__builtin_msa_srai_d: 2980 case Mips::BI__builtin_msa_srari_d: 2981 case Mips::BI__builtin_msa_srli_d: 2982 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2983 case Mips::BI__builtin_msa_binsli_d: 2984 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2985 // These intrinsics take a signed 5 bit immediate. 2986 case Mips::BI__builtin_msa_ceqi_b: 2987 case Mips::BI__builtin_msa_ceqi_h: 2988 case Mips::BI__builtin_msa_ceqi_w: 2989 case Mips::BI__builtin_msa_ceqi_d: 2990 case Mips::BI__builtin_msa_clti_s_b: 2991 case Mips::BI__builtin_msa_clti_s_h: 2992 case Mips::BI__builtin_msa_clti_s_w: 2993 case Mips::BI__builtin_msa_clti_s_d: 2994 case Mips::BI__builtin_msa_clei_s_b: 2995 case Mips::BI__builtin_msa_clei_s_h: 2996 case Mips::BI__builtin_msa_clei_s_w: 2997 case Mips::BI__builtin_msa_clei_s_d: 2998 case Mips::BI__builtin_msa_maxi_s_b: 2999 case Mips::BI__builtin_msa_maxi_s_h: 3000 case Mips::BI__builtin_msa_maxi_s_w: 3001 case Mips::BI__builtin_msa_maxi_s_d: 3002 case Mips::BI__builtin_msa_mini_s_b: 3003 case Mips::BI__builtin_msa_mini_s_h: 3004 case Mips::BI__builtin_msa_mini_s_w: 3005 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3006 // These intrinsics take an unsigned 8 bit immediate. 3007 case Mips::BI__builtin_msa_andi_b: 3008 case Mips::BI__builtin_msa_nori_b: 3009 case Mips::BI__builtin_msa_ori_b: 3010 case Mips::BI__builtin_msa_shf_b: 3011 case Mips::BI__builtin_msa_shf_h: 3012 case Mips::BI__builtin_msa_shf_w: 3013 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3014 case Mips::BI__builtin_msa_bseli_b: 3015 case Mips::BI__builtin_msa_bmnzi_b: 3016 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3017 // df/n format 3018 // These intrinsics take an unsigned 4 bit immediate. 3019 case Mips::BI__builtin_msa_copy_s_b: 3020 case Mips::BI__builtin_msa_copy_u_b: 3021 case Mips::BI__builtin_msa_insve_b: 3022 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3023 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3024 // These intrinsics take an unsigned 3 bit immediate. 3025 case Mips::BI__builtin_msa_copy_s_h: 3026 case Mips::BI__builtin_msa_copy_u_h: 3027 case Mips::BI__builtin_msa_insve_h: 3028 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3029 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3030 // These intrinsics take an unsigned 2 bit immediate. 3031 case Mips::BI__builtin_msa_copy_s_w: 3032 case Mips::BI__builtin_msa_copy_u_w: 3033 case Mips::BI__builtin_msa_insve_w: 3034 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3035 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3036 // These intrinsics take an unsigned 1 bit immediate. 3037 case Mips::BI__builtin_msa_copy_s_d: 3038 case Mips::BI__builtin_msa_copy_u_d: 3039 case Mips::BI__builtin_msa_insve_d: 3040 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3041 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3042 // Memory offsets and immediate loads. 3043 // These intrinsics take a signed 10 bit immediate. 3044 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3045 case Mips::BI__builtin_msa_ldi_h: 3046 case Mips::BI__builtin_msa_ldi_w: 3047 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3048 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3049 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3050 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3051 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3052 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3053 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3054 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3055 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3056 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3057 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3058 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3059 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3060 } 3061 3062 if (!m) 3063 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3064 3065 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3066 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3067 } 3068 3069 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3070 CallExpr *TheCall) { 3071 unsigned i = 0, l = 0, u = 0; 3072 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3073 BuiltinID == PPC::BI__builtin_divdeu || 3074 BuiltinID == PPC::BI__builtin_bpermd; 3075 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3076 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3077 BuiltinID == PPC::BI__builtin_divweu || 3078 BuiltinID == PPC::BI__builtin_divde || 3079 BuiltinID == PPC::BI__builtin_divdeu; 3080 3081 if (Is64BitBltin && !IsTarget64Bit) 3082 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3083 << TheCall->getSourceRange(); 3084 3085 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3086 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3087 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3088 << TheCall->getSourceRange(); 3089 3090 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3091 if (!TI.hasFeature("vsx")) 3092 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3093 << TheCall->getSourceRange(); 3094 return false; 3095 }; 3096 3097 switch (BuiltinID) { 3098 default: return false; 3099 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3100 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3101 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3102 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3103 case PPC::BI__builtin_altivec_dss: 3104 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3105 case PPC::BI__builtin_tbegin: 3106 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3107 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3108 case PPC::BI__builtin_tabortwc: 3109 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3110 case PPC::BI__builtin_tabortwci: 3111 case PPC::BI__builtin_tabortdci: 3112 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3113 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3114 case PPC::BI__builtin_altivec_dst: 3115 case PPC::BI__builtin_altivec_dstt: 3116 case PPC::BI__builtin_altivec_dstst: 3117 case PPC::BI__builtin_altivec_dststt: 3118 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3119 case PPC::BI__builtin_vsx_xxpermdi: 3120 case PPC::BI__builtin_vsx_xxsldwi: 3121 return SemaBuiltinVSX(TheCall); 3122 case PPC::BI__builtin_unpack_vector_int128: 3123 return SemaVSXCheck(TheCall) || 3124 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3125 case PPC::BI__builtin_pack_vector_int128: 3126 return SemaVSXCheck(TheCall); 3127 case PPC::BI__builtin_altivec_vgnb: 3128 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3129 case PPC::BI__builtin_vsx_xxeval: 3130 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3131 } 3132 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3133 } 3134 3135 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3136 CallExpr *TheCall) { 3137 // position of memory order and scope arguments in the builtin 3138 unsigned OrderIndex, ScopeIndex; 3139 switch (BuiltinID) { 3140 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3141 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3142 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3143 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3144 OrderIndex = 2; 3145 ScopeIndex = 3; 3146 break; 3147 case AMDGPU::BI__builtin_amdgcn_fence: 3148 OrderIndex = 0; 3149 ScopeIndex = 1; 3150 break; 3151 default: 3152 return false; 3153 } 3154 3155 ExprResult Arg = TheCall->getArg(OrderIndex); 3156 auto ArgExpr = Arg.get(); 3157 Expr::EvalResult ArgResult; 3158 3159 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3160 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3161 << ArgExpr->getType(); 3162 int ord = ArgResult.Val.getInt().getZExtValue(); 3163 3164 // Check valididty of memory ordering as per C11 / C++11's memody model. 3165 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3166 case llvm::AtomicOrderingCABI::acquire: 3167 case llvm::AtomicOrderingCABI::release: 3168 case llvm::AtomicOrderingCABI::acq_rel: 3169 case llvm::AtomicOrderingCABI::seq_cst: 3170 break; 3171 default: { 3172 return Diag(ArgExpr->getBeginLoc(), 3173 diag::warn_atomic_op_has_invalid_memory_order) 3174 << ArgExpr->getSourceRange(); 3175 } 3176 } 3177 3178 Arg = TheCall->getArg(ScopeIndex); 3179 ArgExpr = Arg.get(); 3180 Expr::EvalResult ArgResult1; 3181 // Check that sync scope is a constant literal 3182 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen, 3183 Context)) 3184 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3185 << ArgExpr->getType(); 3186 3187 return false; 3188 } 3189 3190 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3191 CallExpr *TheCall) { 3192 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3193 Expr *Arg = TheCall->getArg(0); 3194 llvm::APSInt AbortCode(32); 3195 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3196 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3197 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3198 << Arg->getSourceRange(); 3199 } 3200 3201 // For intrinsics which take an immediate value as part of the instruction, 3202 // range check them here. 3203 unsigned i = 0, l = 0, u = 0; 3204 switch (BuiltinID) { 3205 default: return false; 3206 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3207 case SystemZ::BI__builtin_s390_verimb: 3208 case SystemZ::BI__builtin_s390_verimh: 3209 case SystemZ::BI__builtin_s390_verimf: 3210 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3211 case SystemZ::BI__builtin_s390_vfaeb: 3212 case SystemZ::BI__builtin_s390_vfaeh: 3213 case SystemZ::BI__builtin_s390_vfaef: 3214 case SystemZ::BI__builtin_s390_vfaebs: 3215 case SystemZ::BI__builtin_s390_vfaehs: 3216 case SystemZ::BI__builtin_s390_vfaefs: 3217 case SystemZ::BI__builtin_s390_vfaezb: 3218 case SystemZ::BI__builtin_s390_vfaezh: 3219 case SystemZ::BI__builtin_s390_vfaezf: 3220 case SystemZ::BI__builtin_s390_vfaezbs: 3221 case SystemZ::BI__builtin_s390_vfaezhs: 3222 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3223 case SystemZ::BI__builtin_s390_vfisb: 3224 case SystemZ::BI__builtin_s390_vfidb: 3225 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3226 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3227 case SystemZ::BI__builtin_s390_vftcisb: 3228 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3229 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3230 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3231 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3232 case SystemZ::BI__builtin_s390_vstrcb: 3233 case SystemZ::BI__builtin_s390_vstrch: 3234 case SystemZ::BI__builtin_s390_vstrcf: 3235 case SystemZ::BI__builtin_s390_vstrczb: 3236 case SystemZ::BI__builtin_s390_vstrczh: 3237 case SystemZ::BI__builtin_s390_vstrczf: 3238 case SystemZ::BI__builtin_s390_vstrcbs: 3239 case SystemZ::BI__builtin_s390_vstrchs: 3240 case SystemZ::BI__builtin_s390_vstrcfs: 3241 case SystemZ::BI__builtin_s390_vstrczbs: 3242 case SystemZ::BI__builtin_s390_vstrczhs: 3243 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3244 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3245 case SystemZ::BI__builtin_s390_vfminsb: 3246 case SystemZ::BI__builtin_s390_vfmaxsb: 3247 case SystemZ::BI__builtin_s390_vfmindb: 3248 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3249 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3250 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3251 } 3252 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3253 } 3254 3255 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3256 /// This checks that the target supports __builtin_cpu_supports and 3257 /// that the string argument is constant and valid. 3258 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3259 CallExpr *TheCall) { 3260 Expr *Arg = TheCall->getArg(0); 3261 3262 // Check if the argument is a string literal. 3263 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3264 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3265 << Arg->getSourceRange(); 3266 3267 // Check the contents of the string. 3268 StringRef Feature = 3269 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3270 if (!TI.validateCpuSupports(Feature)) 3271 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3272 << Arg->getSourceRange(); 3273 return false; 3274 } 3275 3276 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3277 /// This checks that the target supports __builtin_cpu_is and 3278 /// that the string argument is constant and valid. 3279 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3280 Expr *Arg = TheCall->getArg(0); 3281 3282 // Check if the argument is a string literal. 3283 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3284 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3285 << Arg->getSourceRange(); 3286 3287 // Check the contents of the string. 3288 StringRef Feature = 3289 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3290 if (!TI.validateCpuIs(Feature)) 3291 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3292 << Arg->getSourceRange(); 3293 return false; 3294 } 3295 3296 // Check if the rounding mode is legal. 3297 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3298 // Indicates if this instruction has rounding control or just SAE. 3299 bool HasRC = false; 3300 3301 unsigned ArgNum = 0; 3302 switch (BuiltinID) { 3303 default: 3304 return false; 3305 case X86::BI__builtin_ia32_vcvttsd2si32: 3306 case X86::BI__builtin_ia32_vcvttsd2si64: 3307 case X86::BI__builtin_ia32_vcvttsd2usi32: 3308 case X86::BI__builtin_ia32_vcvttsd2usi64: 3309 case X86::BI__builtin_ia32_vcvttss2si32: 3310 case X86::BI__builtin_ia32_vcvttss2si64: 3311 case X86::BI__builtin_ia32_vcvttss2usi32: 3312 case X86::BI__builtin_ia32_vcvttss2usi64: 3313 ArgNum = 1; 3314 break; 3315 case X86::BI__builtin_ia32_maxpd512: 3316 case X86::BI__builtin_ia32_maxps512: 3317 case X86::BI__builtin_ia32_minpd512: 3318 case X86::BI__builtin_ia32_minps512: 3319 ArgNum = 2; 3320 break; 3321 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3322 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3323 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3324 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3325 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3326 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3327 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3328 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3329 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3330 case X86::BI__builtin_ia32_exp2pd_mask: 3331 case X86::BI__builtin_ia32_exp2ps_mask: 3332 case X86::BI__builtin_ia32_getexppd512_mask: 3333 case X86::BI__builtin_ia32_getexpps512_mask: 3334 case X86::BI__builtin_ia32_rcp28pd_mask: 3335 case X86::BI__builtin_ia32_rcp28ps_mask: 3336 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3337 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3338 case X86::BI__builtin_ia32_vcomisd: 3339 case X86::BI__builtin_ia32_vcomiss: 3340 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3341 ArgNum = 3; 3342 break; 3343 case X86::BI__builtin_ia32_cmppd512_mask: 3344 case X86::BI__builtin_ia32_cmpps512_mask: 3345 case X86::BI__builtin_ia32_cmpsd_mask: 3346 case X86::BI__builtin_ia32_cmpss_mask: 3347 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3348 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3349 case X86::BI__builtin_ia32_getexpss128_round_mask: 3350 case X86::BI__builtin_ia32_getmantpd512_mask: 3351 case X86::BI__builtin_ia32_getmantps512_mask: 3352 case X86::BI__builtin_ia32_maxsd_round_mask: 3353 case X86::BI__builtin_ia32_maxss_round_mask: 3354 case X86::BI__builtin_ia32_minsd_round_mask: 3355 case X86::BI__builtin_ia32_minss_round_mask: 3356 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3357 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3358 case X86::BI__builtin_ia32_reducepd512_mask: 3359 case X86::BI__builtin_ia32_reduceps512_mask: 3360 case X86::BI__builtin_ia32_rndscalepd_mask: 3361 case X86::BI__builtin_ia32_rndscaleps_mask: 3362 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3363 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3364 ArgNum = 4; 3365 break; 3366 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3367 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3368 case X86::BI__builtin_ia32_fixupimmps512_mask: 3369 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3370 case X86::BI__builtin_ia32_fixupimmsd_mask: 3371 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3372 case X86::BI__builtin_ia32_fixupimmss_mask: 3373 case X86::BI__builtin_ia32_fixupimmss_maskz: 3374 case X86::BI__builtin_ia32_getmantsd_round_mask: 3375 case X86::BI__builtin_ia32_getmantss_round_mask: 3376 case X86::BI__builtin_ia32_rangepd512_mask: 3377 case X86::BI__builtin_ia32_rangeps512_mask: 3378 case X86::BI__builtin_ia32_rangesd128_round_mask: 3379 case X86::BI__builtin_ia32_rangess128_round_mask: 3380 case X86::BI__builtin_ia32_reducesd_mask: 3381 case X86::BI__builtin_ia32_reducess_mask: 3382 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3383 case X86::BI__builtin_ia32_rndscaless_round_mask: 3384 ArgNum = 5; 3385 break; 3386 case X86::BI__builtin_ia32_vcvtsd2si64: 3387 case X86::BI__builtin_ia32_vcvtsd2si32: 3388 case X86::BI__builtin_ia32_vcvtsd2usi32: 3389 case X86::BI__builtin_ia32_vcvtsd2usi64: 3390 case X86::BI__builtin_ia32_vcvtss2si32: 3391 case X86::BI__builtin_ia32_vcvtss2si64: 3392 case X86::BI__builtin_ia32_vcvtss2usi32: 3393 case X86::BI__builtin_ia32_vcvtss2usi64: 3394 case X86::BI__builtin_ia32_sqrtpd512: 3395 case X86::BI__builtin_ia32_sqrtps512: 3396 ArgNum = 1; 3397 HasRC = true; 3398 break; 3399 case X86::BI__builtin_ia32_addpd512: 3400 case X86::BI__builtin_ia32_addps512: 3401 case X86::BI__builtin_ia32_divpd512: 3402 case X86::BI__builtin_ia32_divps512: 3403 case X86::BI__builtin_ia32_mulpd512: 3404 case X86::BI__builtin_ia32_mulps512: 3405 case X86::BI__builtin_ia32_subpd512: 3406 case X86::BI__builtin_ia32_subps512: 3407 case X86::BI__builtin_ia32_cvtsi2sd64: 3408 case X86::BI__builtin_ia32_cvtsi2ss32: 3409 case X86::BI__builtin_ia32_cvtsi2ss64: 3410 case X86::BI__builtin_ia32_cvtusi2sd64: 3411 case X86::BI__builtin_ia32_cvtusi2ss32: 3412 case X86::BI__builtin_ia32_cvtusi2ss64: 3413 ArgNum = 2; 3414 HasRC = true; 3415 break; 3416 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3417 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3418 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3419 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3420 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3421 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3422 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3423 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3424 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3425 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3426 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3427 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3428 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3429 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3430 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3431 ArgNum = 3; 3432 HasRC = true; 3433 break; 3434 case X86::BI__builtin_ia32_addss_round_mask: 3435 case X86::BI__builtin_ia32_addsd_round_mask: 3436 case X86::BI__builtin_ia32_divss_round_mask: 3437 case X86::BI__builtin_ia32_divsd_round_mask: 3438 case X86::BI__builtin_ia32_mulss_round_mask: 3439 case X86::BI__builtin_ia32_mulsd_round_mask: 3440 case X86::BI__builtin_ia32_subss_round_mask: 3441 case X86::BI__builtin_ia32_subsd_round_mask: 3442 case X86::BI__builtin_ia32_scalefpd512_mask: 3443 case X86::BI__builtin_ia32_scalefps512_mask: 3444 case X86::BI__builtin_ia32_scalefsd_round_mask: 3445 case X86::BI__builtin_ia32_scalefss_round_mask: 3446 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3447 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3448 case X86::BI__builtin_ia32_sqrtss_round_mask: 3449 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3450 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3451 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3452 case X86::BI__builtin_ia32_vfmaddss3_mask: 3453 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3454 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3455 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3456 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3457 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3458 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3459 case X86::BI__builtin_ia32_vfmaddps512_mask: 3460 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3461 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3462 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3463 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3464 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3465 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3466 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3467 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3468 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3469 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3470 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3471 ArgNum = 4; 3472 HasRC = true; 3473 break; 3474 } 3475 3476 llvm::APSInt Result; 3477 3478 // We can't check the value of a dependent argument. 3479 Expr *Arg = TheCall->getArg(ArgNum); 3480 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3481 return false; 3482 3483 // Check constant-ness first. 3484 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3485 return true; 3486 3487 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3488 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3489 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3490 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3491 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3492 Result == 8/*ROUND_NO_EXC*/ || 3493 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3494 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3495 return false; 3496 3497 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3498 << Arg->getSourceRange(); 3499 } 3500 3501 // Check if the gather/scatter scale is legal. 3502 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3503 CallExpr *TheCall) { 3504 unsigned ArgNum = 0; 3505 switch (BuiltinID) { 3506 default: 3507 return false; 3508 case X86::BI__builtin_ia32_gatherpfdpd: 3509 case X86::BI__builtin_ia32_gatherpfdps: 3510 case X86::BI__builtin_ia32_gatherpfqpd: 3511 case X86::BI__builtin_ia32_gatherpfqps: 3512 case X86::BI__builtin_ia32_scatterpfdpd: 3513 case X86::BI__builtin_ia32_scatterpfdps: 3514 case X86::BI__builtin_ia32_scatterpfqpd: 3515 case X86::BI__builtin_ia32_scatterpfqps: 3516 ArgNum = 3; 3517 break; 3518 case X86::BI__builtin_ia32_gatherd_pd: 3519 case X86::BI__builtin_ia32_gatherd_pd256: 3520 case X86::BI__builtin_ia32_gatherq_pd: 3521 case X86::BI__builtin_ia32_gatherq_pd256: 3522 case X86::BI__builtin_ia32_gatherd_ps: 3523 case X86::BI__builtin_ia32_gatherd_ps256: 3524 case X86::BI__builtin_ia32_gatherq_ps: 3525 case X86::BI__builtin_ia32_gatherq_ps256: 3526 case X86::BI__builtin_ia32_gatherd_q: 3527 case X86::BI__builtin_ia32_gatherd_q256: 3528 case X86::BI__builtin_ia32_gatherq_q: 3529 case X86::BI__builtin_ia32_gatherq_q256: 3530 case X86::BI__builtin_ia32_gatherd_d: 3531 case X86::BI__builtin_ia32_gatherd_d256: 3532 case X86::BI__builtin_ia32_gatherq_d: 3533 case X86::BI__builtin_ia32_gatherq_d256: 3534 case X86::BI__builtin_ia32_gather3div2df: 3535 case X86::BI__builtin_ia32_gather3div2di: 3536 case X86::BI__builtin_ia32_gather3div4df: 3537 case X86::BI__builtin_ia32_gather3div4di: 3538 case X86::BI__builtin_ia32_gather3div4sf: 3539 case X86::BI__builtin_ia32_gather3div4si: 3540 case X86::BI__builtin_ia32_gather3div8sf: 3541 case X86::BI__builtin_ia32_gather3div8si: 3542 case X86::BI__builtin_ia32_gather3siv2df: 3543 case X86::BI__builtin_ia32_gather3siv2di: 3544 case X86::BI__builtin_ia32_gather3siv4df: 3545 case X86::BI__builtin_ia32_gather3siv4di: 3546 case X86::BI__builtin_ia32_gather3siv4sf: 3547 case X86::BI__builtin_ia32_gather3siv4si: 3548 case X86::BI__builtin_ia32_gather3siv8sf: 3549 case X86::BI__builtin_ia32_gather3siv8si: 3550 case X86::BI__builtin_ia32_gathersiv8df: 3551 case X86::BI__builtin_ia32_gathersiv16sf: 3552 case X86::BI__builtin_ia32_gatherdiv8df: 3553 case X86::BI__builtin_ia32_gatherdiv16sf: 3554 case X86::BI__builtin_ia32_gathersiv8di: 3555 case X86::BI__builtin_ia32_gathersiv16si: 3556 case X86::BI__builtin_ia32_gatherdiv8di: 3557 case X86::BI__builtin_ia32_gatherdiv16si: 3558 case X86::BI__builtin_ia32_scatterdiv2df: 3559 case X86::BI__builtin_ia32_scatterdiv2di: 3560 case X86::BI__builtin_ia32_scatterdiv4df: 3561 case X86::BI__builtin_ia32_scatterdiv4di: 3562 case X86::BI__builtin_ia32_scatterdiv4sf: 3563 case X86::BI__builtin_ia32_scatterdiv4si: 3564 case X86::BI__builtin_ia32_scatterdiv8sf: 3565 case X86::BI__builtin_ia32_scatterdiv8si: 3566 case X86::BI__builtin_ia32_scattersiv2df: 3567 case X86::BI__builtin_ia32_scattersiv2di: 3568 case X86::BI__builtin_ia32_scattersiv4df: 3569 case X86::BI__builtin_ia32_scattersiv4di: 3570 case X86::BI__builtin_ia32_scattersiv4sf: 3571 case X86::BI__builtin_ia32_scattersiv4si: 3572 case X86::BI__builtin_ia32_scattersiv8sf: 3573 case X86::BI__builtin_ia32_scattersiv8si: 3574 case X86::BI__builtin_ia32_scattersiv8df: 3575 case X86::BI__builtin_ia32_scattersiv16sf: 3576 case X86::BI__builtin_ia32_scatterdiv8df: 3577 case X86::BI__builtin_ia32_scatterdiv16sf: 3578 case X86::BI__builtin_ia32_scattersiv8di: 3579 case X86::BI__builtin_ia32_scattersiv16si: 3580 case X86::BI__builtin_ia32_scatterdiv8di: 3581 case X86::BI__builtin_ia32_scatterdiv16si: 3582 ArgNum = 4; 3583 break; 3584 } 3585 3586 llvm::APSInt Result; 3587 3588 // We can't check the value of a dependent argument. 3589 Expr *Arg = TheCall->getArg(ArgNum); 3590 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3591 return false; 3592 3593 // Check constant-ness first. 3594 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3595 return true; 3596 3597 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3598 return false; 3599 3600 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3601 << Arg->getSourceRange(); 3602 } 3603 3604 static bool isX86_32Builtin(unsigned BuiltinID) { 3605 // These builtins only work on x86-32 targets. 3606 switch (BuiltinID) { 3607 case X86::BI__builtin_ia32_readeflags_u32: 3608 case X86::BI__builtin_ia32_writeeflags_u32: 3609 return true; 3610 } 3611 3612 return false; 3613 } 3614 3615 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3616 CallExpr *TheCall) { 3617 if (BuiltinID == X86::BI__builtin_cpu_supports) 3618 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3619 3620 if (BuiltinID == X86::BI__builtin_cpu_is) 3621 return SemaBuiltinCpuIs(*this, TI, TheCall); 3622 3623 // Check for 32-bit only builtins on a 64-bit target. 3624 const llvm::Triple &TT = TI.getTriple(); 3625 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3626 return Diag(TheCall->getCallee()->getBeginLoc(), 3627 diag::err_32_bit_builtin_64_bit_tgt); 3628 3629 // If the intrinsic has rounding or SAE make sure its valid. 3630 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3631 return true; 3632 3633 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3634 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3635 return true; 3636 3637 // For intrinsics which take an immediate value as part of the instruction, 3638 // range check them here. 3639 int i = 0, l = 0, u = 0; 3640 switch (BuiltinID) { 3641 default: 3642 return false; 3643 case X86::BI__builtin_ia32_vec_ext_v2si: 3644 case X86::BI__builtin_ia32_vec_ext_v2di: 3645 case X86::BI__builtin_ia32_vextractf128_pd256: 3646 case X86::BI__builtin_ia32_vextractf128_ps256: 3647 case X86::BI__builtin_ia32_vextractf128_si256: 3648 case X86::BI__builtin_ia32_extract128i256: 3649 case X86::BI__builtin_ia32_extractf64x4_mask: 3650 case X86::BI__builtin_ia32_extracti64x4_mask: 3651 case X86::BI__builtin_ia32_extractf32x8_mask: 3652 case X86::BI__builtin_ia32_extracti32x8_mask: 3653 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3654 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3655 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3656 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3657 i = 1; l = 0; u = 1; 3658 break; 3659 case X86::BI__builtin_ia32_vec_set_v2di: 3660 case X86::BI__builtin_ia32_vinsertf128_pd256: 3661 case X86::BI__builtin_ia32_vinsertf128_ps256: 3662 case X86::BI__builtin_ia32_vinsertf128_si256: 3663 case X86::BI__builtin_ia32_insert128i256: 3664 case X86::BI__builtin_ia32_insertf32x8: 3665 case X86::BI__builtin_ia32_inserti32x8: 3666 case X86::BI__builtin_ia32_insertf64x4: 3667 case X86::BI__builtin_ia32_inserti64x4: 3668 case X86::BI__builtin_ia32_insertf64x2_256: 3669 case X86::BI__builtin_ia32_inserti64x2_256: 3670 case X86::BI__builtin_ia32_insertf32x4_256: 3671 case X86::BI__builtin_ia32_inserti32x4_256: 3672 i = 2; l = 0; u = 1; 3673 break; 3674 case X86::BI__builtin_ia32_vpermilpd: 3675 case X86::BI__builtin_ia32_vec_ext_v4hi: 3676 case X86::BI__builtin_ia32_vec_ext_v4si: 3677 case X86::BI__builtin_ia32_vec_ext_v4sf: 3678 case X86::BI__builtin_ia32_vec_ext_v4di: 3679 case X86::BI__builtin_ia32_extractf32x4_mask: 3680 case X86::BI__builtin_ia32_extracti32x4_mask: 3681 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3682 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3683 i = 1; l = 0; u = 3; 3684 break; 3685 case X86::BI_mm_prefetch: 3686 case X86::BI__builtin_ia32_vec_ext_v8hi: 3687 case X86::BI__builtin_ia32_vec_ext_v8si: 3688 i = 1; l = 0; u = 7; 3689 break; 3690 case X86::BI__builtin_ia32_sha1rnds4: 3691 case X86::BI__builtin_ia32_blendpd: 3692 case X86::BI__builtin_ia32_shufpd: 3693 case X86::BI__builtin_ia32_vec_set_v4hi: 3694 case X86::BI__builtin_ia32_vec_set_v4si: 3695 case X86::BI__builtin_ia32_vec_set_v4di: 3696 case X86::BI__builtin_ia32_shuf_f32x4_256: 3697 case X86::BI__builtin_ia32_shuf_f64x2_256: 3698 case X86::BI__builtin_ia32_shuf_i32x4_256: 3699 case X86::BI__builtin_ia32_shuf_i64x2_256: 3700 case X86::BI__builtin_ia32_insertf64x2_512: 3701 case X86::BI__builtin_ia32_inserti64x2_512: 3702 case X86::BI__builtin_ia32_insertf32x4: 3703 case X86::BI__builtin_ia32_inserti32x4: 3704 i = 2; l = 0; u = 3; 3705 break; 3706 case X86::BI__builtin_ia32_vpermil2pd: 3707 case X86::BI__builtin_ia32_vpermil2pd256: 3708 case X86::BI__builtin_ia32_vpermil2ps: 3709 case X86::BI__builtin_ia32_vpermil2ps256: 3710 i = 3; l = 0; u = 3; 3711 break; 3712 case X86::BI__builtin_ia32_cmpb128_mask: 3713 case X86::BI__builtin_ia32_cmpw128_mask: 3714 case X86::BI__builtin_ia32_cmpd128_mask: 3715 case X86::BI__builtin_ia32_cmpq128_mask: 3716 case X86::BI__builtin_ia32_cmpb256_mask: 3717 case X86::BI__builtin_ia32_cmpw256_mask: 3718 case X86::BI__builtin_ia32_cmpd256_mask: 3719 case X86::BI__builtin_ia32_cmpq256_mask: 3720 case X86::BI__builtin_ia32_cmpb512_mask: 3721 case X86::BI__builtin_ia32_cmpw512_mask: 3722 case X86::BI__builtin_ia32_cmpd512_mask: 3723 case X86::BI__builtin_ia32_cmpq512_mask: 3724 case X86::BI__builtin_ia32_ucmpb128_mask: 3725 case X86::BI__builtin_ia32_ucmpw128_mask: 3726 case X86::BI__builtin_ia32_ucmpd128_mask: 3727 case X86::BI__builtin_ia32_ucmpq128_mask: 3728 case X86::BI__builtin_ia32_ucmpb256_mask: 3729 case X86::BI__builtin_ia32_ucmpw256_mask: 3730 case X86::BI__builtin_ia32_ucmpd256_mask: 3731 case X86::BI__builtin_ia32_ucmpq256_mask: 3732 case X86::BI__builtin_ia32_ucmpb512_mask: 3733 case X86::BI__builtin_ia32_ucmpw512_mask: 3734 case X86::BI__builtin_ia32_ucmpd512_mask: 3735 case X86::BI__builtin_ia32_ucmpq512_mask: 3736 case X86::BI__builtin_ia32_vpcomub: 3737 case X86::BI__builtin_ia32_vpcomuw: 3738 case X86::BI__builtin_ia32_vpcomud: 3739 case X86::BI__builtin_ia32_vpcomuq: 3740 case X86::BI__builtin_ia32_vpcomb: 3741 case X86::BI__builtin_ia32_vpcomw: 3742 case X86::BI__builtin_ia32_vpcomd: 3743 case X86::BI__builtin_ia32_vpcomq: 3744 case X86::BI__builtin_ia32_vec_set_v8hi: 3745 case X86::BI__builtin_ia32_vec_set_v8si: 3746 i = 2; l = 0; u = 7; 3747 break; 3748 case X86::BI__builtin_ia32_vpermilpd256: 3749 case X86::BI__builtin_ia32_roundps: 3750 case X86::BI__builtin_ia32_roundpd: 3751 case X86::BI__builtin_ia32_roundps256: 3752 case X86::BI__builtin_ia32_roundpd256: 3753 case X86::BI__builtin_ia32_getmantpd128_mask: 3754 case X86::BI__builtin_ia32_getmantpd256_mask: 3755 case X86::BI__builtin_ia32_getmantps128_mask: 3756 case X86::BI__builtin_ia32_getmantps256_mask: 3757 case X86::BI__builtin_ia32_getmantpd512_mask: 3758 case X86::BI__builtin_ia32_getmantps512_mask: 3759 case X86::BI__builtin_ia32_vec_ext_v16qi: 3760 case X86::BI__builtin_ia32_vec_ext_v16hi: 3761 i = 1; l = 0; u = 15; 3762 break; 3763 case X86::BI__builtin_ia32_pblendd128: 3764 case X86::BI__builtin_ia32_blendps: 3765 case X86::BI__builtin_ia32_blendpd256: 3766 case X86::BI__builtin_ia32_shufpd256: 3767 case X86::BI__builtin_ia32_roundss: 3768 case X86::BI__builtin_ia32_roundsd: 3769 case X86::BI__builtin_ia32_rangepd128_mask: 3770 case X86::BI__builtin_ia32_rangepd256_mask: 3771 case X86::BI__builtin_ia32_rangepd512_mask: 3772 case X86::BI__builtin_ia32_rangeps128_mask: 3773 case X86::BI__builtin_ia32_rangeps256_mask: 3774 case X86::BI__builtin_ia32_rangeps512_mask: 3775 case X86::BI__builtin_ia32_getmantsd_round_mask: 3776 case X86::BI__builtin_ia32_getmantss_round_mask: 3777 case X86::BI__builtin_ia32_vec_set_v16qi: 3778 case X86::BI__builtin_ia32_vec_set_v16hi: 3779 i = 2; l = 0; u = 15; 3780 break; 3781 case X86::BI__builtin_ia32_vec_ext_v32qi: 3782 i = 1; l = 0; u = 31; 3783 break; 3784 case X86::BI__builtin_ia32_cmpps: 3785 case X86::BI__builtin_ia32_cmpss: 3786 case X86::BI__builtin_ia32_cmppd: 3787 case X86::BI__builtin_ia32_cmpsd: 3788 case X86::BI__builtin_ia32_cmpps256: 3789 case X86::BI__builtin_ia32_cmppd256: 3790 case X86::BI__builtin_ia32_cmpps128_mask: 3791 case X86::BI__builtin_ia32_cmppd128_mask: 3792 case X86::BI__builtin_ia32_cmpps256_mask: 3793 case X86::BI__builtin_ia32_cmppd256_mask: 3794 case X86::BI__builtin_ia32_cmpps512_mask: 3795 case X86::BI__builtin_ia32_cmppd512_mask: 3796 case X86::BI__builtin_ia32_cmpsd_mask: 3797 case X86::BI__builtin_ia32_cmpss_mask: 3798 case X86::BI__builtin_ia32_vec_set_v32qi: 3799 i = 2; l = 0; u = 31; 3800 break; 3801 case X86::BI__builtin_ia32_permdf256: 3802 case X86::BI__builtin_ia32_permdi256: 3803 case X86::BI__builtin_ia32_permdf512: 3804 case X86::BI__builtin_ia32_permdi512: 3805 case X86::BI__builtin_ia32_vpermilps: 3806 case X86::BI__builtin_ia32_vpermilps256: 3807 case X86::BI__builtin_ia32_vpermilpd512: 3808 case X86::BI__builtin_ia32_vpermilps512: 3809 case X86::BI__builtin_ia32_pshufd: 3810 case X86::BI__builtin_ia32_pshufd256: 3811 case X86::BI__builtin_ia32_pshufd512: 3812 case X86::BI__builtin_ia32_pshufhw: 3813 case X86::BI__builtin_ia32_pshufhw256: 3814 case X86::BI__builtin_ia32_pshufhw512: 3815 case X86::BI__builtin_ia32_pshuflw: 3816 case X86::BI__builtin_ia32_pshuflw256: 3817 case X86::BI__builtin_ia32_pshuflw512: 3818 case X86::BI__builtin_ia32_vcvtps2ph: 3819 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3820 case X86::BI__builtin_ia32_vcvtps2ph256: 3821 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3822 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3823 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3824 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3825 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3826 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3827 case X86::BI__builtin_ia32_rndscaleps_mask: 3828 case X86::BI__builtin_ia32_rndscalepd_mask: 3829 case X86::BI__builtin_ia32_reducepd128_mask: 3830 case X86::BI__builtin_ia32_reducepd256_mask: 3831 case X86::BI__builtin_ia32_reducepd512_mask: 3832 case X86::BI__builtin_ia32_reduceps128_mask: 3833 case X86::BI__builtin_ia32_reduceps256_mask: 3834 case X86::BI__builtin_ia32_reduceps512_mask: 3835 case X86::BI__builtin_ia32_prold512: 3836 case X86::BI__builtin_ia32_prolq512: 3837 case X86::BI__builtin_ia32_prold128: 3838 case X86::BI__builtin_ia32_prold256: 3839 case X86::BI__builtin_ia32_prolq128: 3840 case X86::BI__builtin_ia32_prolq256: 3841 case X86::BI__builtin_ia32_prord512: 3842 case X86::BI__builtin_ia32_prorq512: 3843 case X86::BI__builtin_ia32_prord128: 3844 case X86::BI__builtin_ia32_prord256: 3845 case X86::BI__builtin_ia32_prorq128: 3846 case X86::BI__builtin_ia32_prorq256: 3847 case X86::BI__builtin_ia32_fpclasspd128_mask: 3848 case X86::BI__builtin_ia32_fpclasspd256_mask: 3849 case X86::BI__builtin_ia32_fpclassps128_mask: 3850 case X86::BI__builtin_ia32_fpclassps256_mask: 3851 case X86::BI__builtin_ia32_fpclassps512_mask: 3852 case X86::BI__builtin_ia32_fpclasspd512_mask: 3853 case X86::BI__builtin_ia32_fpclasssd_mask: 3854 case X86::BI__builtin_ia32_fpclassss_mask: 3855 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3856 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3857 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3858 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3859 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3860 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3861 case X86::BI__builtin_ia32_kshiftliqi: 3862 case X86::BI__builtin_ia32_kshiftlihi: 3863 case X86::BI__builtin_ia32_kshiftlisi: 3864 case X86::BI__builtin_ia32_kshiftlidi: 3865 case X86::BI__builtin_ia32_kshiftriqi: 3866 case X86::BI__builtin_ia32_kshiftrihi: 3867 case X86::BI__builtin_ia32_kshiftrisi: 3868 case X86::BI__builtin_ia32_kshiftridi: 3869 i = 1; l = 0; u = 255; 3870 break; 3871 case X86::BI__builtin_ia32_vperm2f128_pd256: 3872 case X86::BI__builtin_ia32_vperm2f128_ps256: 3873 case X86::BI__builtin_ia32_vperm2f128_si256: 3874 case X86::BI__builtin_ia32_permti256: 3875 case X86::BI__builtin_ia32_pblendw128: 3876 case X86::BI__builtin_ia32_pblendw256: 3877 case X86::BI__builtin_ia32_blendps256: 3878 case X86::BI__builtin_ia32_pblendd256: 3879 case X86::BI__builtin_ia32_palignr128: 3880 case X86::BI__builtin_ia32_palignr256: 3881 case X86::BI__builtin_ia32_palignr512: 3882 case X86::BI__builtin_ia32_alignq512: 3883 case X86::BI__builtin_ia32_alignd512: 3884 case X86::BI__builtin_ia32_alignd128: 3885 case X86::BI__builtin_ia32_alignd256: 3886 case X86::BI__builtin_ia32_alignq128: 3887 case X86::BI__builtin_ia32_alignq256: 3888 case X86::BI__builtin_ia32_vcomisd: 3889 case X86::BI__builtin_ia32_vcomiss: 3890 case X86::BI__builtin_ia32_shuf_f32x4: 3891 case X86::BI__builtin_ia32_shuf_f64x2: 3892 case X86::BI__builtin_ia32_shuf_i32x4: 3893 case X86::BI__builtin_ia32_shuf_i64x2: 3894 case X86::BI__builtin_ia32_shufpd512: 3895 case X86::BI__builtin_ia32_shufps: 3896 case X86::BI__builtin_ia32_shufps256: 3897 case X86::BI__builtin_ia32_shufps512: 3898 case X86::BI__builtin_ia32_dbpsadbw128: 3899 case X86::BI__builtin_ia32_dbpsadbw256: 3900 case X86::BI__builtin_ia32_dbpsadbw512: 3901 case X86::BI__builtin_ia32_vpshldd128: 3902 case X86::BI__builtin_ia32_vpshldd256: 3903 case X86::BI__builtin_ia32_vpshldd512: 3904 case X86::BI__builtin_ia32_vpshldq128: 3905 case X86::BI__builtin_ia32_vpshldq256: 3906 case X86::BI__builtin_ia32_vpshldq512: 3907 case X86::BI__builtin_ia32_vpshldw128: 3908 case X86::BI__builtin_ia32_vpshldw256: 3909 case X86::BI__builtin_ia32_vpshldw512: 3910 case X86::BI__builtin_ia32_vpshrdd128: 3911 case X86::BI__builtin_ia32_vpshrdd256: 3912 case X86::BI__builtin_ia32_vpshrdd512: 3913 case X86::BI__builtin_ia32_vpshrdq128: 3914 case X86::BI__builtin_ia32_vpshrdq256: 3915 case X86::BI__builtin_ia32_vpshrdq512: 3916 case X86::BI__builtin_ia32_vpshrdw128: 3917 case X86::BI__builtin_ia32_vpshrdw256: 3918 case X86::BI__builtin_ia32_vpshrdw512: 3919 i = 2; l = 0; u = 255; 3920 break; 3921 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3922 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3923 case X86::BI__builtin_ia32_fixupimmps512_mask: 3924 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3925 case X86::BI__builtin_ia32_fixupimmsd_mask: 3926 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3927 case X86::BI__builtin_ia32_fixupimmss_mask: 3928 case X86::BI__builtin_ia32_fixupimmss_maskz: 3929 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3930 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3931 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3932 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3933 case X86::BI__builtin_ia32_fixupimmps128_mask: 3934 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3935 case X86::BI__builtin_ia32_fixupimmps256_mask: 3936 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3937 case X86::BI__builtin_ia32_pternlogd512_mask: 3938 case X86::BI__builtin_ia32_pternlogd512_maskz: 3939 case X86::BI__builtin_ia32_pternlogq512_mask: 3940 case X86::BI__builtin_ia32_pternlogq512_maskz: 3941 case X86::BI__builtin_ia32_pternlogd128_mask: 3942 case X86::BI__builtin_ia32_pternlogd128_maskz: 3943 case X86::BI__builtin_ia32_pternlogd256_mask: 3944 case X86::BI__builtin_ia32_pternlogd256_maskz: 3945 case X86::BI__builtin_ia32_pternlogq128_mask: 3946 case X86::BI__builtin_ia32_pternlogq128_maskz: 3947 case X86::BI__builtin_ia32_pternlogq256_mask: 3948 case X86::BI__builtin_ia32_pternlogq256_maskz: 3949 i = 3; l = 0; u = 255; 3950 break; 3951 case X86::BI__builtin_ia32_gatherpfdpd: 3952 case X86::BI__builtin_ia32_gatherpfdps: 3953 case X86::BI__builtin_ia32_gatherpfqpd: 3954 case X86::BI__builtin_ia32_gatherpfqps: 3955 case X86::BI__builtin_ia32_scatterpfdpd: 3956 case X86::BI__builtin_ia32_scatterpfdps: 3957 case X86::BI__builtin_ia32_scatterpfqpd: 3958 case X86::BI__builtin_ia32_scatterpfqps: 3959 i = 4; l = 2; u = 3; 3960 break; 3961 case X86::BI__builtin_ia32_reducesd_mask: 3962 case X86::BI__builtin_ia32_reducess_mask: 3963 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3964 case X86::BI__builtin_ia32_rndscaless_round_mask: 3965 i = 4; l = 0; u = 255; 3966 break; 3967 } 3968 3969 // Note that we don't force a hard error on the range check here, allowing 3970 // template-generated or macro-generated dead code to potentially have out-of- 3971 // range values. These need to code generate, but don't need to necessarily 3972 // make any sense. We use a warning that defaults to an error. 3973 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3974 } 3975 3976 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3977 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3978 /// Returns true when the format fits the function and the FormatStringInfo has 3979 /// been populated. 3980 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3981 FormatStringInfo *FSI) { 3982 FSI->HasVAListArg = Format->getFirstArg() == 0; 3983 FSI->FormatIdx = Format->getFormatIdx() - 1; 3984 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3985 3986 // The way the format attribute works in GCC, the implicit this argument 3987 // of member functions is counted. However, it doesn't appear in our own 3988 // lists, so decrement format_idx in that case. 3989 if (IsCXXMember) { 3990 if(FSI->FormatIdx == 0) 3991 return false; 3992 --FSI->FormatIdx; 3993 if (FSI->FirstDataArg != 0) 3994 --FSI->FirstDataArg; 3995 } 3996 return true; 3997 } 3998 3999 /// Checks if a the given expression evaluates to null. 4000 /// 4001 /// Returns true if the value evaluates to null. 4002 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4003 // If the expression has non-null type, it doesn't evaluate to null. 4004 if (auto nullability 4005 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4006 if (*nullability == NullabilityKind::NonNull) 4007 return false; 4008 } 4009 4010 // As a special case, transparent unions initialized with zero are 4011 // considered null for the purposes of the nonnull attribute. 4012 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4013 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4014 if (const CompoundLiteralExpr *CLE = 4015 dyn_cast<CompoundLiteralExpr>(Expr)) 4016 if (const InitListExpr *ILE = 4017 dyn_cast<InitListExpr>(CLE->getInitializer())) 4018 Expr = ILE->getInit(0); 4019 } 4020 4021 bool Result; 4022 return (!Expr->isValueDependent() && 4023 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4024 !Result); 4025 } 4026 4027 static void CheckNonNullArgument(Sema &S, 4028 const Expr *ArgExpr, 4029 SourceLocation CallSiteLoc) { 4030 if (CheckNonNullExpr(S, ArgExpr)) 4031 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4032 S.PDiag(diag::warn_null_arg) 4033 << ArgExpr->getSourceRange()); 4034 } 4035 4036 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4037 FormatStringInfo FSI; 4038 if ((GetFormatStringType(Format) == FST_NSString) && 4039 getFormatStringInfo(Format, false, &FSI)) { 4040 Idx = FSI.FormatIdx; 4041 return true; 4042 } 4043 return false; 4044 } 4045 4046 /// Diagnose use of %s directive in an NSString which is being passed 4047 /// as formatting string to formatting method. 4048 static void 4049 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4050 const NamedDecl *FDecl, 4051 Expr **Args, 4052 unsigned NumArgs) { 4053 unsigned Idx = 0; 4054 bool Format = false; 4055 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4056 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4057 Idx = 2; 4058 Format = true; 4059 } 4060 else 4061 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4062 if (S.GetFormatNSStringIdx(I, Idx)) { 4063 Format = true; 4064 break; 4065 } 4066 } 4067 if (!Format || NumArgs <= Idx) 4068 return; 4069 const Expr *FormatExpr = Args[Idx]; 4070 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4071 FormatExpr = CSCE->getSubExpr(); 4072 const StringLiteral *FormatString; 4073 if (const ObjCStringLiteral *OSL = 4074 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4075 FormatString = OSL->getString(); 4076 else 4077 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4078 if (!FormatString) 4079 return; 4080 if (S.FormatStringHasSArg(FormatString)) { 4081 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4082 << "%s" << 1 << 1; 4083 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4084 << FDecl->getDeclName(); 4085 } 4086 } 4087 4088 /// Determine whether the given type has a non-null nullability annotation. 4089 static bool isNonNullType(ASTContext &ctx, QualType type) { 4090 if (auto nullability = type->getNullability(ctx)) 4091 return *nullability == NullabilityKind::NonNull; 4092 4093 return false; 4094 } 4095 4096 static void CheckNonNullArguments(Sema &S, 4097 const NamedDecl *FDecl, 4098 const FunctionProtoType *Proto, 4099 ArrayRef<const Expr *> Args, 4100 SourceLocation CallSiteLoc) { 4101 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4102 4103 // Already checked by by constant evaluator. 4104 if (S.isConstantEvaluated()) 4105 return; 4106 // Check the attributes attached to the method/function itself. 4107 llvm::SmallBitVector NonNullArgs; 4108 if (FDecl) { 4109 // Handle the nonnull attribute on the function/method declaration itself. 4110 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4111 if (!NonNull->args_size()) { 4112 // Easy case: all pointer arguments are nonnull. 4113 for (const auto *Arg : Args) 4114 if (S.isValidPointerAttrType(Arg->getType())) 4115 CheckNonNullArgument(S, Arg, CallSiteLoc); 4116 return; 4117 } 4118 4119 for (const ParamIdx &Idx : NonNull->args()) { 4120 unsigned IdxAST = Idx.getASTIndex(); 4121 if (IdxAST >= Args.size()) 4122 continue; 4123 if (NonNullArgs.empty()) 4124 NonNullArgs.resize(Args.size()); 4125 NonNullArgs.set(IdxAST); 4126 } 4127 } 4128 } 4129 4130 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4131 // Handle the nonnull attribute on the parameters of the 4132 // function/method. 4133 ArrayRef<ParmVarDecl*> parms; 4134 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4135 parms = FD->parameters(); 4136 else 4137 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4138 4139 unsigned ParamIndex = 0; 4140 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4141 I != E; ++I, ++ParamIndex) { 4142 const ParmVarDecl *PVD = *I; 4143 if (PVD->hasAttr<NonNullAttr>() || 4144 isNonNullType(S.Context, PVD->getType())) { 4145 if (NonNullArgs.empty()) 4146 NonNullArgs.resize(Args.size()); 4147 4148 NonNullArgs.set(ParamIndex); 4149 } 4150 } 4151 } else { 4152 // If we have a non-function, non-method declaration but no 4153 // function prototype, try to dig out the function prototype. 4154 if (!Proto) { 4155 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4156 QualType type = VD->getType().getNonReferenceType(); 4157 if (auto pointerType = type->getAs<PointerType>()) 4158 type = pointerType->getPointeeType(); 4159 else if (auto blockType = type->getAs<BlockPointerType>()) 4160 type = blockType->getPointeeType(); 4161 // FIXME: data member pointers? 4162 4163 // Dig out the function prototype, if there is one. 4164 Proto = type->getAs<FunctionProtoType>(); 4165 } 4166 } 4167 4168 // Fill in non-null argument information from the nullability 4169 // information on the parameter types (if we have them). 4170 if (Proto) { 4171 unsigned Index = 0; 4172 for (auto paramType : Proto->getParamTypes()) { 4173 if (isNonNullType(S.Context, paramType)) { 4174 if (NonNullArgs.empty()) 4175 NonNullArgs.resize(Args.size()); 4176 4177 NonNullArgs.set(Index); 4178 } 4179 4180 ++Index; 4181 } 4182 } 4183 } 4184 4185 // Check for non-null arguments. 4186 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4187 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4188 if (NonNullArgs[ArgIndex]) 4189 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4190 } 4191 } 4192 4193 /// Handles the checks for format strings, non-POD arguments to vararg 4194 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4195 /// attributes. 4196 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4197 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4198 bool IsMemberFunction, SourceLocation Loc, 4199 SourceRange Range, VariadicCallType CallType) { 4200 // FIXME: We should check as much as we can in the template definition. 4201 if (CurContext->isDependentContext()) 4202 return; 4203 4204 // Printf and scanf checking. 4205 llvm::SmallBitVector CheckedVarArgs; 4206 if (FDecl) { 4207 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4208 // Only create vector if there are format attributes. 4209 CheckedVarArgs.resize(Args.size()); 4210 4211 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4212 CheckedVarArgs); 4213 } 4214 } 4215 4216 // Refuse POD arguments that weren't caught by the format string 4217 // checks above. 4218 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4219 if (CallType != VariadicDoesNotApply && 4220 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4221 unsigned NumParams = Proto ? Proto->getNumParams() 4222 : FDecl && isa<FunctionDecl>(FDecl) 4223 ? cast<FunctionDecl>(FDecl)->getNumParams() 4224 : FDecl && isa<ObjCMethodDecl>(FDecl) 4225 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4226 : 0; 4227 4228 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4229 // Args[ArgIdx] can be null in malformed code. 4230 if (const Expr *Arg = Args[ArgIdx]) { 4231 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4232 checkVariadicArgument(Arg, CallType); 4233 } 4234 } 4235 } 4236 4237 if (FDecl || Proto) { 4238 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4239 4240 // Type safety checking. 4241 if (FDecl) { 4242 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4243 CheckArgumentWithTypeTag(I, Args, Loc); 4244 } 4245 } 4246 4247 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4248 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4249 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4250 if (!Arg->isValueDependent()) { 4251 Expr::EvalResult Align; 4252 if (Arg->EvaluateAsInt(Align, Context)) { 4253 const llvm::APSInt &I = Align.Val.getInt(); 4254 if (!I.isPowerOf2()) 4255 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4256 << Arg->getSourceRange(); 4257 4258 if (I > Sema::MaximumAlignment) 4259 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4260 << Arg->getSourceRange() << Sema::MaximumAlignment; 4261 } 4262 } 4263 } 4264 4265 if (FD) 4266 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4267 } 4268 4269 /// CheckConstructorCall - Check a constructor call for correctness and safety 4270 /// properties not enforced by the C type system. 4271 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4272 ArrayRef<const Expr *> Args, 4273 const FunctionProtoType *Proto, 4274 SourceLocation Loc) { 4275 VariadicCallType CallType = 4276 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4277 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4278 Loc, SourceRange(), CallType); 4279 } 4280 4281 /// CheckFunctionCall - Check a direct function call for various correctness 4282 /// and safety properties not strictly enforced by the C type system. 4283 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4284 const FunctionProtoType *Proto) { 4285 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4286 isa<CXXMethodDecl>(FDecl); 4287 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4288 IsMemberOperatorCall; 4289 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4290 TheCall->getCallee()); 4291 Expr** Args = TheCall->getArgs(); 4292 unsigned NumArgs = TheCall->getNumArgs(); 4293 4294 Expr *ImplicitThis = nullptr; 4295 if (IsMemberOperatorCall) { 4296 // If this is a call to a member operator, hide the first argument 4297 // from checkCall. 4298 // FIXME: Our choice of AST representation here is less than ideal. 4299 ImplicitThis = Args[0]; 4300 ++Args; 4301 --NumArgs; 4302 } else if (IsMemberFunction) 4303 ImplicitThis = 4304 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4305 4306 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4307 IsMemberFunction, TheCall->getRParenLoc(), 4308 TheCall->getCallee()->getSourceRange(), CallType); 4309 4310 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4311 // None of the checks below are needed for functions that don't have 4312 // simple names (e.g., C++ conversion functions). 4313 if (!FnInfo) 4314 return false; 4315 4316 CheckAbsoluteValueFunction(TheCall, FDecl); 4317 CheckMaxUnsignedZero(TheCall, FDecl); 4318 4319 if (getLangOpts().ObjC) 4320 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4321 4322 unsigned CMId = FDecl->getMemoryFunctionKind(); 4323 if (CMId == 0) 4324 return false; 4325 4326 // Handle memory setting and copying functions. 4327 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4328 CheckStrlcpycatArguments(TheCall, FnInfo); 4329 else if (CMId == Builtin::BIstrncat) 4330 CheckStrncatArguments(TheCall, FnInfo); 4331 else 4332 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4333 4334 return false; 4335 } 4336 4337 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4338 ArrayRef<const Expr *> Args) { 4339 VariadicCallType CallType = 4340 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4341 4342 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4343 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4344 CallType); 4345 4346 return false; 4347 } 4348 4349 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4350 const FunctionProtoType *Proto) { 4351 QualType Ty; 4352 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4353 Ty = V->getType().getNonReferenceType(); 4354 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4355 Ty = F->getType().getNonReferenceType(); 4356 else 4357 return false; 4358 4359 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4360 !Ty->isFunctionProtoType()) 4361 return false; 4362 4363 VariadicCallType CallType; 4364 if (!Proto || !Proto->isVariadic()) { 4365 CallType = VariadicDoesNotApply; 4366 } else if (Ty->isBlockPointerType()) { 4367 CallType = VariadicBlock; 4368 } else { // Ty->isFunctionPointerType() 4369 CallType = VariadicFunction; 4370 } 4371 4372 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4373 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4374 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4375 TheCall->getCallee()->getSourceRange(), CallType); 4376 4377 return false; 4378 } 4379 4380 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4381 /// such as function pointers returned from functions. 4382 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4383 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4384 TheCall->getCallee()); 4385 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4386 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4387 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4388 TheCall->getCallee()->getSourceRange(), CallType); 4389 4390 return false; 4391 } 4392 4393 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4394 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4395 return false; 4396 4397 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4398 switch (Op) { 4399 case AtomicExpr::AO__c11_atomic_init: 4400 case AtomicExpr::AO__opencl_atomic_init: 4401 llvm_unreachable("There is no ordering argument for an init"); 4402 4403 case AtomicExpr::AO__c11_atomic_load: 4404 case AtomicExpr::AO__opencl_atomic_load: 4405 case AtomicExpr::AO__atomic_load_n: 4406 case AtomicExpr::AO__atomic_load: 4407 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4408 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4409 4410 case AtomicExpr::AO__c11_atomic_store: 4411 case AtomicExpr::AO__opencl_atomic_store: 4412 case AtomicExpr::AO__atomic_store: 4413 case AtomicExpr::AO__atomic_store_n: 4414 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4415 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4416 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4417 4418 default: 4419 return true; 4420 } 4421 } 4422 4423 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4424 AtomicExpr::AtomicOp Op) { 4425 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4426 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4427 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4428 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4429 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4430 Op); 4431 } 4432 4433 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4434 SourceLocation RParenLoc, MultiExprArg Args, 4435 AtomicExpr::AtomicOp Op, 4436 AtomicArgumentOrder ArgOrder) { 4437 // All the non-OpenCL operations take one of the following forms. 4438 // The OpenCL operations take the __c11 forms with one extra argument for 4439 // synchronization scope. 4440 enum { 4441 // C __c11_atomic_init(A *, C) 4442 Init, 4443 4444 // C __c11_atomic_load(A *, int) 4445 Load, 4446 4447 // void __atomic_load(A *, CP, int) 4448 LoadCopy, 4449 4450 // void __atomic_store(A *, CP, int) 4451 Copy, 4452 4453 // C __c11_atomic_add(A *, M, int) 4454 Arithmetic, 4455 4456 // C __atomic_exchange_n(A *, CP, int) 4457 Xchg, 4458 4459 // void __atomic_exchange(A *, C *, CP, int) 4460 GNUXchg, 4461 4462 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4463 C11CmpXchg, 4464 4465 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4466 GNUCmpXchg 4467 } Form = Init; 4468 4469 const unsigned NumForm = GNUCmpXchg + 1; 4470 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4471 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4472 // where: 4473 // C is an appropriate type, 4474 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4475 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4476 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4477 // the int parameters are for orderings. 4478 4479 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4480 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4481 "need to update code for modified forms"); 4482 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4483 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4484 AtomicExpr::AO__atomic_load, 4485 "need to update code for modified C11 atomics"); 4486 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4487 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4488 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4489 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4490 IsOpenCL; 4491 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4492 Op == AtomicExpr::AO__atomic_store_n || 4493 Op == AtomicExpr::AO__atomic_exchange_n || 4494 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4495 bool IsAddSub = false; 4496 4497 switch (Op) { 4498 case AtomicExpr::AO__c11_atomic_init: 4499 case AtomicExpr::AO__opencl_atomic_init: 4500 Form = Init; 4501 break; 4502 4503 case AtomicExpr::AO__c11_atomic_load: 4504 case AtomicExpr::AO__opencl_atomic_load: 4505 case AtomicExpr::AO__atomic_load_n: 4506 Form = Load; 4507 break; 4508 4509 case AtomicExpr::AO__atomic_load: 4510 Form = LoadCopy; 4511 break; 4512 4513 case AtomicExpr::AO__c11_atomic_store: 4514 case AtomicExpr::AO__opencl_atomic_store: 4515 case AtomicExpr::AO__atomic_store: 4516 case AtomicExpr::AO__atomic_store_n: 4517 Form = Copy; 4518 break; 4519 4520 case AtomicExpr::AO__c11_atomic_fetch_add: 4521 case AtomicExpr::AO__c11_atomic_fetch_sub: 4522 case AtomicExpr::AO__opencl_atomic_fetch_add: 4523 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4524 case AtomicExpr::AO__atomic_fetch_add: 4525 case AtomicExpr::AO__atomic_fetch_sub: 4526 case AtomicExpr::AO__atomic_add_fetch: 4527 case AtomicExpr::AO__atomic_sub_fetch: 4528 IsAddSub = true; 4529 LLVM_FALLTHROUGH; 4530 case AtomicExpr::AO__c11_atomic_fetch_and: 4531 case AtomicExpr::AO__c11_atomic_fetch_or: 4532 case AtomicExpr::AO__c11_atomic_fetch_xor: 4533 case AtomicExpr::AO__opencl_atomic_fetch_and: 4534 case AtomicExpr::AO__opencl_atomic_fetch_or: 4535 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4536 case AtomicExpr::AO__atomic_fetch_and: 4537 case AtomicExpr::AO__atomic_fetch_or: 4538 case AtomicExpr::AO__atomic_fetch_xor: 4539 case AtomicExpr::AO__atomic_fetch_nand: 4540 case AtomicExpr::AO__atomic_and_fetch: 4541 case AtomicExpr::AO__atomic_or_fetch: 4542 case AtomicExpr::AO__atomic_xor_fetch: 4543 case AtomicExpr::AO__atomic_nand_fetch: 4544 case AtomicExpr::AO__c11_atomic_fetch_min: 4545 case AtomicExpr::AO__c11_atomic_fetch_max: 4546 case AtomicExpr::AO__opencl_atomic_fetch_min: 4547 case AtomicExpr::AO__opencl_atomic_fetch_max: 4548 case AtomicExpr::AO__atomic_min_fetch: 4549 case AtomicExpr::AO__atomic_max_fetch: 4550 case AtomicExpr::AO__atomic_fetch_min: 4551 case AtomicExpr::AO__atomic_fetch_max: 4552 Form = Arithmetic; 4553 break; 4554 4555 case AtomicExpr::AO__c11_atomic_exchange: 4556 case AtomicExpr::AO__opencl_atomic_exchange: 4557 case AtomicExpr::AO__atomic_exchange_n: 4558 Form = Xchg; 4559 break; 4560 4561 case AtomicExpr::AO__atomic_exchange: 4562 Form = GNUXchg; 4563 break; 4564 4565 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4566 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4567 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4568 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4569 Form = C11CmpXchg; 4570 break; 4571 4572 case AtomicExpr::AO__atomic_compare_exchange: 4573 case AtomicExpr::AO__atomic_compare_exchange_n: 4574 Form = GNUCmpXchg; 4575 break; 4576 } 4577 4578 unsigned AdjustedNumArgs = NumArgs[Form]; 4579 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4580 ++AdjustedNumArgs; 4581 // Check we have the right number of arguments. 4582 if (Args.size() < AdjustedNumArgs) { 4583 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4584 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4585 << ExprRange; 4586 return ExprError(); 4587 } else if (Args.size() > AdjustedNumArgs) { 4588 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4589 diag::err_typecheck_call_too_many_args) 4590 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4591 << ExprRange; 4592 return ExprError(); 4593 } 4594 4595 // Inspect the first argument of the atomic operation. 4596 Expr *Ptr = Args[0]; 4597 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4598 if (ConvertedPtr.isInvalid()) 4599 return ExprError(); 4600 4601 Ptr = ConvertedPtr.get(); 4602 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4603 if (!pointerType) { 4604 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4605 << Ptr->getType() << Ptr->getSourceRange(); 4606 return ExprError(); 4607 } 4608 4609 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4610 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4611 QualType ValType = AtomTy; // 'C' 4612 if (IsC11) { 4613 if (!AtomTy->isAtomicType()) { 4614 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4615 << Ptr->getType() << Ptr->getSourceRange(); 4616 return ExprError(); 4617 } 4618 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4619 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4620 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4621 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4622 << Ptr->getSourceRange(); 4623 return ExprError(); 4624 } 4625 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4626 } else if (Form != Load && Form != LoadCopy) { 4627 if (ValType.isConstQualified()) { 4628 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4629 << Ptr->getType() << Ptr->getSourceRange(); 4630 return ExprError(); 4631 } 4632 } 4633 4634 // For an arithmetic operation, the implied arithmetic must be well-formed. 4635 if (Form == Arithmetic) { 4636 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4637 if (IsAddSub && !ValType->isIntegerType() 4638 && !ValType->isPointerType()) { 4639 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4640 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4641 return ExprError(); 4642 } 4643 if (!IsAddSub && !ValType->isIntegerType()) { 4644 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4645 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4646 return ExprError(); 4647 } 4648 if (IsC11 && ValType->isPointerType() && 4649 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4650 diag::err_incomplete_type)) { 4651 return ExprError(); 4652 } 4653 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4654 // For __atomic_*_n operations, the value type must be a scalar integral or 4655 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4656 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4657 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4658 return ExprError(); 4659 } 4660 4661 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4662 !AtomTy->isScalarType()) { 4663 // For GNU atomics, require a trivially-copyable type. This is not part of 4664 // the GNU atomics specification, but we enforce it for sanity. 4665 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4666 << Ptr->getType() << Ptr->getSourceRange(); 4667 return ExprError(); 4668 } 4669 4670 switch (ValType.getObjCLifetime()) { 4671 case Qualifiers::OCL_None: 4672 case Qualifiers::OCL_ExplicitNone: 4673 // okay 4674 break; 4675 4676 case Qualifiers::OCL_Weak: 4677 case Qualifiers::OCL_Strong: 4678 case Qualifiers::OCL_Autoreleasing: 4679 // FIXME: Can this happen? By this point, ValType should be known 4680 // to be trivially copyable. 4681 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4682 << ValType << Ptr->getSourceRange(); 4683 return ExprError(); 4684 } 4685 4686 // All atomic operations have an overload which takes a pointer to a volatile 4687 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4688 // into the result or the other operands. Similarly atomic_load takes a 4689 // pointer to a const 'A'. 4690 ValType.removeLocalVolatile(); 4691 ValType.removeLocalConst(); 4692 QualType ResultType = ValType; 4693 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4694 Form == Init) 4695 ResultType = Context.VoidTy; 4696 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4697 ResultType = Context.BoolTy; 4698 4699 // The type of a parameter passed 'by value'. In the GNU atomics, such 4700 // arguments are actually passed as pointers. 4701 QualType ByValType = ValType; // 'CP' 4702 bool IsPassedByAddress = false; 4703 if (!IsC11 && !IsN) { 4704 ByValType = Ptr->getType(); 4705 IsPassedByAddress = true; 4706 } 4707 4708 SmallVector<Expr *, 5> APIOrderedArgs; 4709 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4710 APIOrderedArgs.push_back(Args[0]); 4711 switch (Form) { 4712 case Init: 4713 case Load: 4714 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4715 break; 4716 case LoadCopy: 4717 case Copy: 4718 case Arithmetic: 4719 case Xchg: 4720 APIOrderedArgs.push_back(Args[2]); // Val1 4721 APIOrderedArgs.push_back(Args[1]); // Order 4722 break; 4723 case GNUXchg: 4724 APIOrderedArgs.push_back(Args[2]); // Val1 4725 APIOrderedArgs.push_back(Args[3]); // Val2 4726 APIOrderedArgs.push_back(Args[1]); // Order 4727 break; 4728 case C11CmpXchg: 4729 APIOrderedArgs.push_back(Args[2]); // Val1 4730 APIOrderedArgs.push_back(Args[4]); // Val2 4731 APIOrderedArgs.push_back(Args[1]); // Order 4732 APIOrderedArgs.push_back(Args[3]); // OrderFail 4733 break; 4734 case GNUCmpXchg: 4735 APIOrderedArgs.push_back(Args[2]); // Val1 4736 APIOrderedArgs.push_back(Args[4]); // Val2 4737 APIOrderedArgs.push_back(Args[5]); // Weak 4738 APIOrderedArgs.push_back(Args[1]); // Order 4739 APIOrderedArgs.push_back(Args[3]); // OrderFail 4740 break; 4741 } 4742 } else 4743 APIOrderedArgs.append(Args.begin(), Args.end()); 4744 4745 // The first argument's non-CV pointer type is used to deduce the type of 4746 // subsequent arguments, except for: 4747 // - weak flag (always converted to bool) 4748 // - memory order (always converted to int) 4749 // - scope (always converted to int) 4750 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4751 QualType Ty; 4752 if (i < NumVals[Form] + 1) { 4753 switch (i) { 4754 case 0: 4755 // The first argument is always a pointer. It has a fixed type. 4756 // It is always dereferenced, a nullptr is undefined. 4757 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4758 // Nothing else to do: we already know all we want about this pointer. 4759 continue; 4760 case 1: 4761 // The second argument is the non-atomic operand. For arithmetic, this 4762 // is always passed by value, and for a compare_exchange it is always 4763 // passed by address. For the rest, GNU uses by-address and C11 uses 4764 // by-value. 4765 assert(Form != Load); 4766 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4767 Ty = ValType; 4768 else if (Form == Copy || Form == Xchg) { 4769 if (IsPassedByAddress) { 4770 // The value pointer is always dereferenced, a nullptr is undefined. 4771 CheckNonNullArgument(*this, APIOrderedArgs[i], 4772 ExprRange.getBegin()); 4773 } 4774 Ty = ByValType; 4775 } else if (Form == Arithmetic) 4776 Ty = Context.getPointerDiffType(); 4777 else { 4778 Expr *ValArg = APIOrderedArgs[i]; 4779 // The value pointer is always dereferenced, a nullptr is undefined. 4780 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4781 LangAS AS = LangAS::Default; 4782 // Keep address space of non-atomic pointer type. 4783 if (const PointerType *PtrTy = 4784 ValArg->getType()->getAs<PointerType>()) { 4785 AS = PtrTy->getPointeeType().getAddressSpace(); 4786 } 4787 Ty = Context.getPointerType( 4788 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4789 } 4790 break; 4791 case 2: 4792 // The third argument to compare_exchange / GNU exchange is the desired 4793 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4794 if (IsPassedByAddress) 4795 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4796 Ty = ByValType; 4797 break; 4798 case 3: 4799 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4800 Ty = Context.BoolTy; 4801 break; 4802 } 4803 } else { 4804 // The order(s) and scope are always converted to int. 4805 Ty = Context.IntTy; 4806 } 4807 4808 InitializedEntity Entity = 4809 InitializedEntity::InitializeParameter(Context, Ty, false); 4810 ExprResult Arg = APIOrderedArgs[i]; 4811 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4812 if (Arg.isInvalid()) 4813 return true; 4814 APIOrderedArgs[i] = Arg.get(); 4815 } 4816 4817 // Permute the arguments into a 'consistent' order. 4818 SmallVector<Expr*, 5> SubExprs; 4819 SubExprs.push_back(Ptr); 4820 switch (Form) { 4821 case Init: 4822 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4823 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4824 break; 4825 case Load: 4826 SubExprs.push_back(APIOrderedArgs[1]); // Order 4827 break; 4828 case LoadCopy: 4829 case Copy: 4830 case Arithmetic: 4831 case Xchg: 4832 SubExprs.push_back(APIOrderedArgs[2]); // Order 4833 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4834 break; 4835 case GNUXchg: 4836 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4837 SubExprs.push_back(APIOrderedArgs[3]); // Order 4838 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4839 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4840 break; 4841 case C11CmpXchg: 4842 SubExprs.push_back(APIOrderedArgs[3]); // Order 4843 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4844 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 4845 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4846 break; 4847 case GNUCmpXchg: 4848 SubExprs.push_back(APIOrderedArgs[4]); // Order 4849 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4850 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 4851 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4852 SubExprs.push_back(APIOrderedArgs[3]); // Weak 4853 break; 4854 } 4855 4856 if (SubExprs.size() >= 2 && Form != Init) { 4857 llvm::APSInt Result(32); 4858 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4859 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4860 Diag(SubExprs[1]->getBeginLoc(), 4861 diag::warn_atomic_op_has_invalid_memory_order) 4862 << SubExprs[1]->getSourceRange(); 4863 } 4864 4865 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4866 auto *Scope = Args[Args.size() - 1]; 4867 llvm::APSInt Result(32); 4868 if (Scope->isIntegerConstantExpr(Result, Context) && 4869 !ScopeModel->isValid(Result.getZExtValue())) { 4870 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4871 << Scope->getSourceRange(); 4872 } 4873 SubExprs.push_back(Scope); 4874 } 4875 4876 AtomicExpr *AE = new (Context) 4877 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 4878 4879 if ((Op == AtomicExpr::AO__c11_atomic_load || 4880 Op == AtomicExpr::AO__c11_atomic_store || 4881 Op == AtomicExpr::AO__opencl_atomic_load || 4882 Op == AtomicExpr::AO__opencl_atomic_store ) && 4883 Context.AtomicUsesUnsupportedLibcall(AE)) 4884 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4885 << ((Op == AtomicExpr::AO__c11_atomic_load || 4886 Op == AtomicExpr::AO__opencl_atomic_load) 4887 ? 0 4888 : 1); 4889 4890 return AE; 4891 } 4892 4893 /// checkBuiltinArgument - Given a call to a builtin function, perform 4894 /// normal type-checking on the given argument, updating the call in 4895 /// place. This is useful when a builtin function requires custom 4896 /// type-checking for some of its arguments but not necessarily all of 4897 /// them. 4898 /// 4899 /// Returns true on error. 4900 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4901 FunctionDecl *Fn = E->getDirectCallee(); 4902 assert(Fn && "builtin call without direct callee!"); 4903 4904 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4905 InitializedEntity Entity = 4906 InitializedEntity::InitializeParameter(S.Context, Param); 4907 4908 ExprResult Arg = E->getArg(0); 4909 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4910 if (Arg.isInvalid()) 4911 return true; 4912 4913 E->setArg(ArgIndex, Arg.get()); 4914 return false; 4915 } 4916 4917 /// We have a call to a function like __sync_fetch_and_add, which is an 4918 /// overloaded function based on the pointer type of its first argument. 4919 /// The main BuildCallExpr routines have already promoted the types of 4920 /// arguments because all of these calls are prototyped as void(...). 4921 /// 4922 /// This function goes through and does final semantic checking for these 4923 /// builtins, as well as generating any warnings. 4924 ExprResult 4925 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4926 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4927 Expr *Callee = TheCall->getCallee(); 4928 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4929 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4930 4931 // Ensure that we have at least one argument to do type inference from. 4932 if (TheCall->getNumArgs() < 1) { 4933 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4934 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4935 return ExprError(); 4936 } 4937 4938 // Inspect the first argument of the atomic builtin. This should always be 4939 // a pointer type, whose element is an integral scalar or pointer type. 4940 // Because it is a pointer type, we don't have to worry about any implicit 4941 // casts here. 4942 // FIXME: We don't allow floating point scalars as input. 4943 Expr *FirstArg = TheCall->getArg(0); 4944 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4945 if (FirstArgResult.isInvalid()) 4946 return ExprError(); 4947 FirstArg = FirstArgResult.get(); 4948 TheCall->setArg(0, FirstArg); 4949 4950 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4951 if (!pointerType) { 4952 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4953 << FirstArg->getType() << FirstArg->getSourceRange(); 4954 return ExprError(); 4955 } 4956 4957 QualType ValType = pointerType->getPointeeType(); 4958 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4959 !ValType->isBlockPointerType()) { 4960 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4961 << FirstArg->getType() << FirstArg->getSourceRange(); 4962 return ExprError(); 4963 } 4964 4965 if (ValType.isConstQualified()) { 4966 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4967 << FirstArg->getType() << FirstArg->getSourceRange(); 4968 return ExprError(); 4969 } 4970 4971 switch (ValType.getObjCLifetime()) { 4972 case Qualifiers::OCL_None: 4973 case Qualifiers::OCL_ExplicitNone: 4974 // okay 4975 break; 4976 4977 case Qualifiers::OCL_Weak: 4978 case Qualifiers::OCL_Strong: 4979 case Qualifiers::OCL_Autoreleasing: 4980 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4981 << ValType << FirstArg->getSourceRange(); 4982 return ExprError(); 4983 } 4984 4985 // Strip any qualifiers off ValType. 4986 ValType = ValType.getUnqualifiedType(); 4987 4988 // The majority of builtins return a value, but a few have special return 4989 // types, so allow them to override appropriately below. 4990 QualType ResultType = ValType; 4991 4992 // We need to figure out which concrete builtin this maps onto. For example, 4993 // __sync_fetch_and_add with a 2 byte object turns into 4994 // __sync_fetch_and_add_2. 4995 #define BUILTIN_ROW(x) \ 4996 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4997 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4998 4999 static const unsigned BuiltinIndices[][5] = { 5000 BUILTIN_ROW(__sync_fetch_and_add), 5001 BUILTIN_ROW(__sync_fetch_and_sub), 5002 BUILTIN_ROW(__sync_fetch_and_or), 5003 BUILTIN_ROW(__sync_fetch_and_and), 5004 BUILTIN_ROW(__sync_fetch_and_xor), 5005 BUILTIN_ROW(__sync_fetch_and_nand), 5006 5007 BUILTIN_ROW(__sync_add_and_fetch), 5008 BUILTIN_ROW(__sync_sub_and_fetch), 5009 BUILTIN_ROW(__sync_and_and_fetch), 5010 BUILTIN_ROW(__sync_or_and_fetch), 5011 BUILTIN_ROW(__sync_xor_and_fetch), 5012 BUILTIN_ROW(__sync_nand_and_fetch), 5013 5014 BUILTIN_ROW(__sync_val_compare_and_swap), 5015 BUILTIN_ROW(__sync_bool_compare_and_swap), 5016 BUILTIN_ROW(__sync_lock_test_and_set), 5017 BUILTIN_ROW(__sync_lock_release), 5018 BUILTIN_ROW(__sync_swap) 5019 }; 5020 #undef BUILTIN_ROW 5021 5022 // Determine the index of the size. 5023 unsigned SizeIndex; 5024 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5025 case 1: SizeIndex = 0; break; 5026 case 2: SizeIndex = 1; break; 5027 case 4: SizeIndex = 2; break; 5028 case 8: SizeIndex = 3; break; 5029 case 16: SizeIndex = 4; break; 5030 default: 5031 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5032 << FirstArg->getType() << FirstArg->getSourceRange(); 5033 return ExprError(); 5034 } 5035 5036 // Each of these builtins has one pointer argument, followed by some number of 5037 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5038 // that we ignore. Find out which row of BuiltinIndices to read from as well 5039 // as the number of fixed args. 5040 unsigned BuiltinID = FDecl->getBuiltinID(); 5041 unsigned BuiltinIndex, NumFixed = 1; 5042 bool WarnAboutSemanticsChange = false; 5043 switch (BuiltinID) { 5044 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5045 case Builtin::BI__sync_fetch_and_add: 5046 case Builtin::BI__sync_fetch_and_add_1: 5047 case Builtin::BI__sync_fetch_and_add_2: 5048 case Builtin::BI__sync_fetch_and_add_4: 5049 case Builtin::BI__sync_fetch_and_add_8: 5050 case Builtin::BI__sync_fetch_and_add_16: 5051 BuiltinIndex = 0; 5052 break; 5053 5054 case Builtin::BI__sync_fetch_and_sub: 5055 case Builtin::BI__sync_fetch_and_sub_1: 5056 case Builtin::BI__sync_fetch_and_sub_2: 5057 case Builtin::BI__sync_fetch_and_sub_4: 5058 case Builtin::BI__sync_fetch_and_sub_8: 5059 case Builtin::BI__sync_fetch_and_sub_16: 5060 BuiltinIndex = 1; 5061 break; 5062 5063 case Builtin::BI__sync_fetch_and_or: 5064 case Builtin::BI__sync_fetch_and_or_1: 5065 case Builtin::BI__sync_fetch_and_or_2: 5066 case Builtin::BI__sync_fetch_and_or_4: 5067 case Builtin::BI__sync_fetch_and_or_8: 5068 case Builtin::BI__sync_fetch_and_or_16: 5069 BuiltinIndex = 2; 5070 break; 5071 5072 case Builtin::BI__sync_fetch_and_and: 5073 case Builtin::BI__sync_fetch_and_and_1: 5074 case Builtin::BI__sync_fetch_and_and_2: 5075 case Builtin::BI__sync_fetch_and_and_4: 5076 case Builtin::BI__sync_fetch_and_and_8: 5077 case Builtin::BI__sync_fetch_and_and_16: 5078 BuiltinIndex = 3; 5079 break; 5080 5081 case Builtin::BI__sync_fetch_and_xor: 5082 case Builtin::BI__sync_fetch_and_xor_1: 5083 case Builtin::BI__sync_fetch_and_xor_2: 5084 case Builtin::BI__sync_fetch_and_xor_4: 5085 case Builtin::BI__sync_fetch_and_xor_8: 5086 case Builtin::BI__sync_fetch_and_xor_16: 5087 BuiltinIndex = 4; 5088 break; 5089 5090 case Builtin::BI__sync_fetch_and_nand: 5091 case Builtin::BI__sync_fetch_and_nand_1: 5092 case Builtin::BI__sync_fetch_and_nand_2: 5093 case Builtin::BI__sync_fetch_and_nand_4: 5094 case Builtin::BI__sync_fetch_and_nand_8: 5095 case Builtin::BI__sync_fetch_and_nand_16: 5096 BuiltinIndex = 5; 5097 WarnAboutSemanticsChange = true; 5098 break; 5099 5100 case Builtin::BI__sync_add_and_fetch: 5101 case Builtin::BI__sync_add_and_fetch_1: 5102 case Builtin::BI__sync_add_and_fetch_2: 5103 case Builtin::BI__sync_add_and_fetch_4: 5104 case Builtin::BI__sync_add_and_fetch_8: 5105 case Builtin::BI__sync_add_and_fetch_16: 5106 BuiltinIndex = 6; 5107 break; 5108 5109 case Builtin::BI__sync_sub_and_fetch: 5110 case Builtin::BI__sync_sub_and_fetch_1: 5111 case Builtin::BI__sync_sub_and_fetch_2: 5112 case Builtin::BI__sync_sub_and_fetch_4: 5113 case Builtin::BI__sync_sub_and_fetch_8: 5114 case Builtin::BI__sync_sub_and_fetch_16: 5115 BuiltinIndex = 7; 5116 break; 5117 5118 case Builtin::BI__sync_and_and_fetch: 5119 case Builtin::BI__sync_and_and_fetch_1: 5120 case Builtin::BI__sync_and_and_fetch_2: 5121 case Builtin::BI__sync_and_and_fetch_4: 5122 case Builtin::BI__sync_and_and_fetch_8: 5123 case Builtin::BI__sync_and_and_fetch_16: 5124 BuiltinIndex = 8; 5125 break; 5126 5127 case Builtin::BI__sync_or_and_fetch: 5128 case Builtin::BI__sync_or_and_fetch_1: 5129 case Builtin::BI__sync_or_and_fetch_2: 5130 case Builtin::BI__sync_or_and_fetch_4: 5131 case Builtin::BI__sync_or_and_fetch_8: 5132 case Builtin::BI__sync_or_and_fetch_16: 5133 BuiltinIndex = 9; 5134 break; 5135 5136 case Builtin::BI__sync_xor_and_fetch: 5137 case Builtin::BI__sync_xor_and_fetch_1: 5138 case Builtin::BI__sync_xor_and_fetch_2: 5139 case Builtin::BI__sync_xor_and_fetch_4: 5140 case Builtin::BI__sync_xor_and_fetch_8: 5141 case Builtin::BI__sync_xor_and_fetch_16: 5142 BuiltinIndex = 10; 5143 break; 5144 5145 case Builtin::BI__sync_nand_and_fetch: 5146 case Builtin::BI__sync_nand_and_fetch_1: 5147 case Builtin::BI__sync_nand_and_fetch_2: 5148 case Builtin::BI__sync_nand_and_fetch_4: 5149 case Builtin::BI__sync_nand_and_fetch_8: 5150 case Builtin::BI__sync_nand_and_fetch_16: 5151 BuiltinIndex = 11; 5152 WarnAboutSemanticsChange = true; 5153 break; 5154 5155 case Builtin::BI__sync_val_compare_and_swap: 5156 case Builtin::BI__sync_val_compare_and_swap_1: 5157 case Builtin::BI__sync_val_compare_and_swap_2: 5158 case Builtin::BI__sync_val_compare_and_swap_4: 5159 case Builtin::BI__sync_val_compare_and_swap_8: 5160 case Builtin::BI__sync_val_compare_and_swap_16: 5161 BuiltinIndex = 12; 5162 NumFixed = 2; 5163 break; 5164 5165 case Builtin::BI__sync_bool_compare_and_swap: 5166 case Builtin::BI__sync_bool_compare_and_swap_1: 5167 case Builtin::BI__sync_bool_compare_and_swap_2: 5168 case Builtin::BI__sync_bool_compare_and_swap_4: 5169 case Builtin::BI__sync_bool_compare_and_swap_8: 5170 case Builtin::BI__sync_bool_compare_and_swap_16: 5171 BuiltinIndex = 13; 5172 NumFixed = 2; 5173 ResultType = Context.BoolTy; 5174 break; 5175 5176 case Builtin::BI__sync_lock_test_and_set: 5177 case Builtin::BI__sync_lock_test_and_set_1: 5178 case Builtin::BI__sync_lock_test_and_set_2: 5179 case Builtin::BI__sync_lock_test_and_set_4: 5180 case Builtin::BI__sync_lock_test_and_set_8: 5181 case Builtin::BI__sync_lock_test_and_set_16: 5182 BuiltinIndex = 14; 5183 break; 5184 5185 case Builtin::BI__sync_lock_release: 5186 case Builtin::BI__sync_lock_release_1: 5187 case Builtin::BI__sync_lock_release_2: 5188 case Builtin::BI__sync_lock_release_4: 5189 case Builtin::BI__sync_lock_release_8: 5190 case Builtin::BI__sync_lock_release_16: 5191 BuiltinIndex = 15; 5192 NumFixed = 0; 5193 ResultType = Context.VoidTy; 5194 break; 5195 5196 case Builtin::BI__sync_swap: 5197 case Builtin::BI__sync_swap_1: 5198 case Builtin::BI__sync_swap_2: 5199 case Builtin::BI__sync_swap_4: 5200 case Builtin::BI__sync_swap_8: 5201 case Builtin::BI__sync_swap_16: 5202 BuiltinIndex = 16; 5203 break; 5204 } 5205 5206 // Now that we know how many fixed arguments we expect, first check that we 5207 // have at least that many. 5208 if (TheCall->getNumArgs() < 1+NumFixed) { 5209 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5210 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5211 << Callee->getSourceRange(); 5212 return ExprError(); 5213 } 5214 5215 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5216 << Callee->getSourceRange(); 5217 5218 if (WarnAboutSemanticsChange) { 5219 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5220 << Callee->getSourceRange(); 5221 } 5222 5223 // Get the decl for the concrete builtin from this, we can tell what the 5224 // concrete integer type we should convert to is. 5225 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5226 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5227 FunctionDecl *NewBuiltinDecl; 5228 if (NewBuiltinID == BuiltinID) 5229 NewBuiltinDecl = FDecl; 5230 else { 5231 // Perform builtin lookup to avoid redeclaring it. 5232 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5233 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5234 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5235 assert(Res.getFoundDecl()); 5236 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5237 if (!NewBuiltinDecl) 5238 return ExprError(); 5239 } 5240 5241 // The first argument --- the pointer --- has a fixed type; we 5242 // deduce the types of the rest of the arguments accordingly. Walk 5243 // the remaining arguments, converting them to the deduced value type. 5244 for (unsigned i = 0; i != NumFixed; ++i) { 5245 ExprResult Arg = TheCall->getArg(i+1); 5246 5247 // GCC does an implicit conversion to the pointer or integer ValType. This 5248 // can fail in some cases (1i -> int**), check for this error case now. 5249 // Initialize the argument. 5250 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5251 ValType, /*consume*/ false); 5252 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5253 if (Arg.isInvalid()) 5254 return ExprError(); 5255 5256 // Okay, we have something that *can* be converted to the right type. Check 5257 // to see if there is a potentially weird extension going on here. This can 5258 // happen when you do an atomic operation on something like an char* and 5259 // pass in 42. The 42 gets converted to char. This is even more strange 5260 // for things like 45.123 -> char, etc. 5261 // FIXME: Do this check. 5262 TheCall->setArg(i+1, Arg.get()); 5263 } 5264 5265 // Create a new DeclRefExpr to refer to the new decl. 5266 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5267 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5268 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5269 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5270 5271 // Set the callee in the CallExpr. 5272 // FIXME: This loses syntactic information. 5273 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5274 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5275 CK_BuiltinFnToFnPtr); 5276 TheCall->setCallee(PromotedCall.get()); 5277 5278 // Change the result type of the call to match the original value type. This 5279 // is arbitrary, but the codegen for these builtins ins design to handle it 5280 // gracefully. 5281 TheCall->setType(ResultType); 5282 5283 return TheCallResult; 5284 } 5285 5286 /// SemaBuiltinNontemporalOverloaded - We have a call to 5287 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5288 /// overloaded function based on the pointer type of its last argument. 5289 /// 5290 /// This function goes through and does final semantic checking for these 5291 /// builtins. 5292 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5293 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5294 DeclRefExpr *DRE = 5295 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5296 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5297 unsigned BuiltinID = FDecl->getBuiltinID(); 5298 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5299 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5300 "Unexpected nontemporal load/store builtin!"); 5301 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5302 unsigned numArgs = isStore ? 2 : 1; 5303 5304 // Ensure that we have the proper number of arguments. 5305 if (checkArgCount(*this, TheCall, numArgs)) 5306 return ExprError(); 5307 5308 // Inspect the last argument of the nontemporal builtin. This should always 5309 // be a pointer type, from which we imply the type of the memory access. 5310 // Because it is a pointer type, we don't have to worry about any implicit 5311 // casts here. 5312 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5313 ExprResult PointerArgResult = 5314 DefaultFunctionArrayLvalueConversion(PointerArg); 5315 5316 if (PointerArgResult.isInvalid()) 5317 return ExprError(); 5318 PointerArg = PointerArgResult.get(); 5319 TheCall->setArg(numArgs - 1, PointerArg); 5320 5321 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5322 if (!pointerType) { 5323 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5324 << PointerArg->getType() << PointerArg->getSourceRange(); 5325 return ExprError(); 5326 } 5327 5328 QualType ValType = pointerType->getPointeeType(); 5329 5330 // Strip any qualifiers off ValType. 5331 ValType = ValType.getUnqualifiedType(); 5332 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5333 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5334 !ValType->isVectorType()) { 5335 Diag(DRE->getBeginLoc(), 5336 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5337 << PointerArg->getType() << PointerArg->getSourceRange(); 5338 return ExprError(); 5339 } 5340 5341 if (!isStore) { 5342 TheCall->setType(ValType); 5343 return TheCallResult; 5344 } 5345 5346 ExprResult ValArg = TheCall->getArg(0); 5347 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5348 Context, ValType, /*consume*/ false); 5349 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5350 if (ValArg.isInvalid()) 5351 return ExprError(); 5352 5353 TheCall->setArg(0, ValArg.get()); 5354 TheCall->setType(Context.VoidTy); 5355 return TheCallResult; 5356 } 5357 5358 /// CheckObjCString - Checks that the argument to the builtin 5359 /// CFString constructor is correct 5360 /// Note: It might also make sense to do the UTF-16 conversion here (would 5361 /// simplify the backend). 5362 bool Sema::CheckObjCString(Expr *Arg) { 5363 Arg = Arg->IgnoreParenCasts(); 5364 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5365 5366 if (!Literal || !Literal->isAscii()) { 5367 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5368 << Arg->getSourceRange(); 5369 return true; 5370 } 5371 5372 if (Literal->containsNonAsciiOrNull()) { 5373 StringRef String = Literal->getString(); 5374 unsigned NumBytes = String.size(); 5375 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5376 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5377 llvm::UTF16 *ToPtr = &ToBuf[0]; 5378 5379 llvm::ConversionResult Result = 5380 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5381 ToPtr + NumBytes, llvm::strictConversion); 5382 // Check for conversion failure. 5383 if (Result != llvm::conversionOK) 5384 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5385 << Arg->getSourceRange(); 5386 } 5387 return false; 5388 } 5389 5390 /// CheckObjCString - Checks that the format string argument to the os_log() 5391 /// and os_trace() functions is correct, and converts it to const char *. 5392 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5393 Arg = Arg->IgnoreParenCasts(); 5394 auto *Literal = dyn_cast<StringLiteral>(Arg); 5395 if (!Literal) { 5396 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5397 Literal = ObjcLiteral->getString(); 5398 } 5399 } 5400 5401 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5402 return ExprError( 5403 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5404 << Arg->getSourceRange()); 5405 } 5406 5407 ExprResult Result(Literal); 5408 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5409 InitializedEntity Entity = 5410 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5411 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5412 return Result; 5413 } 5414 5415 /// Check that the user is calling the appropriate va_start builtin for the 5416 /// target and calling convention. 5417 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5418 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5419 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5420 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5421 TT.getArch() == llvm::Triple::aarch64_32); 5422 bool IsWindows = TT.isOSWindows(); 5423 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5424 if (IsX64 || IsAArch64) { 5425 CallingConv CC = CC_C; 5426 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5427 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5428 if (IsMSVAStart) { 5429 // Don't allow this in System V ABI functions. 5430 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5431 return S.Diag(Fn->getBeginLoc(), 5432 diag::err_ms_va_start_used_in_sysv_function); 5433 } else { 5434 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5435 // On x64 Windows, don't allow this in System V ABI functions. 5436 // (Yes, that means there's no corresponding way to support variadic 5437 // System V ABI functions on Windows.) 5438 if ((IsWindows && CC == CC_X86_64SysV) || 5439 (!IsWindows && CC == CC_Win64)) 5440 return S.Diag(Fn->getBeginLoc(), 5441 diag::err_va_start_used_in_wrong_abi_function) 5442 << !IsWindows; 5443 } 5444 return false; 5445 } 5446 5447 if (IsMSVAStart) 5448 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5449 return false; 5450 } 5451 5452 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5453 ParmVarDecl **LastParam = nullptr) { 5454 // Determine whether the current function, block, or obj-c method is variadic 5455 // and get its parameter list. 5456 bool IsVariadic = false; 5457 ArrayRef<ParmVarDecl *> Params; 5458 DeclContext *Caller = S.CurContext; 5459 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5460 IsVariadic = Block->isVariadic(); 5461 Params = Block->parameters(); 5462 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5463 IsVariadic = FD->isVariadic(); 5464 Params = FD->parameters(); 5465 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5466 IsVariadic = MD->isVariadic(); 5467 // FIXME: This isn't correct for methods (results in bogus warning). 5468 Params = MD->parameters(); 5469 } else if (isa<CapturedDecl>(Caller)) { 5470 // We don't support va_start in a CapturedDecl. 5471 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5472 return true; 5473 } else { 5474 // This must be some other declcontext that parses exprs. 5475 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5476 return true; 5477 } 5478 5479 if (!IsVariadic) { 5480 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5481 return true; 5482 } 5483 5484 if (LastParam) 5485 *LastParam = Params.empty() ? nullptr : Params.back(); 5486 5487 return false; 5488 } 5489 5490 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5491 /// for validity. Emit an error and return true on failure; return false 5492 /// on success. 5493 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5494 Expr *Fn = TheCall->getCallee(); 5495 5496 if (checkVAStartABI(*this, BuiltinID, Fn)) 5497 return true; 5498 5499 if (TheCall->getNumArgs() > 2) { 5500 Diag(TheCall->getArg(2)->getBeginLoc(), 5501 diag::err_typecheck_call_too_many_args) 5502 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5503 << Fn->getSourceRange() 5504 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5505 (*(TheCall->arg_end() - 1))->getEndLoc()); 5506 return true; 5507 } 5508 5509 if (TheCall->getNumArgs() < 2) { 5510 return Diag(TheCall->getEndLoc(), 5511 diag::err_typecheck_call_too_few_args_at_least) 5512 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5513 } 5514 5515 // Type-check the first argument normally. 5516 if (checkBuiltinArgument(*this, TheCall, 0)) 5517 return true; 5518 5519 // Check that the current function is variadic, and get its last parameter. 5520 ParmVarDecl *LastParam; 5521 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5522 return true; 5523 5524 // Verify that the second argument to the builtin is the last argument of the 5525 // current function or method. 5526 bool SecondArgIsLastNamedArgument = false; 5527 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5528 5529 // These are valid if SecondArgIsLastNamedArgument is false after the next 5530 // block. 5531 QualType Type; 5532 SourceLocation ParamLoc; 5533 bool IsCRegister = false; 5534 5535 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5536 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5537 SecondArgIsLastNamedArgument = PV == LastParam; 5538 5539 Type = PV->getType(); 5540 ParamLoc = PV->getLocation(); 5541 IsCRegister = 5542 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5543 } 5544 } 5545 5546 if (!SecondArgIsLastNamedArgument) 5547 Diag(TheCall->getArg(1)->getBeginLoc(), 5548 diag::warn_second_arg_of_va_start_not_last_named_param); 5549 else if (IsCRegister || Type->isReferenceType() || 5550 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5551 // Promotable integers are UB, but enumerations need a bit of 5552 // extra checking to see what their promotable type actually is. 5553 if (!Type->isPromotableIntegerType()) 5554 return false; 5555 if (!Type->isEnumeralType()) 5556 return true; 5557 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5558 return !(ED && 5559 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5560 }()) { 5561 unsigned Reason = 0; 5562 if (Type->isReferenceType()) Reason = 1; 5563 else if (IsCRegister) Reason = 2; 5564 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5565 Diag(ParamLoc, diag::note_parameter_type) << Type; 5566 } 5567 5568 TheCall->setType(Context.VoidTy); 5569 return false; 5570 } 5571 5572 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5573 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5574 // const char *named_addr); 5575 5576 Expr *Func = Call->getCallee(); 5577 5578 if (Call->getNumArgs() < 3) 5579 return Diag(Call->getEndLoc(), 5580 diag::err_typecheck_call_too_few_args_at_least) 5581 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5582 5583 // Type-check the first argument normally. 5584 if (checkBuiltinArgument(*this, Call, 0)) 5585 return true; 5586 5587 // Check that the current function is variadic. 5588 if (checkVAStartIsInVariadicFunction(*this, Func)) 5589 return true; 5590 5591 // __va_start on Windows does not validate the parameter qualifiers 5592 5593 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5594 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5595 5596 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5597 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5598 5599 const QualType &ConstCharPtrTy = 5600 Context.getPointerType(Context.CharTy.withConst()); 5601 if (!Arg1Ty->isPointerType() || 5602 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5603 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5604 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5605 << 0 /* qualifier difference */ 5606 << 3 /* parameter mismatch */ 5607 << 2 << Arg1->getType() << ConstCharPtrTy; 5608 5609 const QualType SizeTy = Context.getSizeType(); 5610 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5611 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5612 << Arg2->getType() << SizeTy << 1 /* different class */ 5613 << 0 /* qualifier difference */ 5614 << 3 /* parameter mismatch */ 5615 << 3 << Arg2->getType() << SizeTy; 5616 5617 return false; 5618 } 5619 5620 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5621 /// friends. This is declared to take (...), so we have to check everything. 5622 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5623 if (TheCall->getNumArgs() < 2) 5624 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5625 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5626 if (TheCall->getNumArgs() > 2) 5627 return Diag(TheCall->getArg(2)->getBeginLoc(), 5628 diag::err_typecheck_call_too_many_args) 5629 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5630 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5631 (*(TheCall->arg_end() - 1))->getEndLoc()); 5632 5633 ExprResult OrigArg0 = TheCall->getArg(0); 5634 ExprResult OrigArg1 = TheCall->getArg(1); 5635 5636 // Do standard promotions between the two arguments, returning their common 5637 // type. 5638 QualType Res = UsualArithmeticConversions( 5639 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5640 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5641 return true; 5642 5643 // Make sure any conversions are pushed back into the call; this is 5644 // type safe since unordered compare builtins are declared as "_Bool 5645 // foo(...)". 5646 TheCall->setArg(0, OrigArg0.get()); 5647 TheCall->setArg(1, OrigArg1.get()); 5648 5649 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5650 return false; 5651 5652 // If the common type isn't a real floating type, then the arguments were 5653 // invalid for this operation. 5654 if (Res.isNull() || !Res->isRealFloatingType()) 5655 return Diag(OrigArg0.get()->getBeginLoc(), 5656 diag::err_typecheck_call_invalid_ordered_compare) 5657 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5658 << SourceRange(OrigArg0.get()->getBeginLoc(), 5659 OrigArg1.get()->getEndLoc()); 5660 5661 return false; 5662 } 5663 5664 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5665 /// __builtin_isnan and friends. This is declared to take (...), so we have 5666 /// to check everything. We expect the last argument to be a floating point 5667 /// value. 5668 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5669 if (TheCall->getNumArgs() < NumArgs) 5670 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5671 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5672 if (TheCall->getNumArgs() > NumArgs) 5673 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5674 diag::err_typecheck_call_too_many_args) 5675 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5676 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5677 (*(TheCall->arg_end() - 1))->getEndLoc()); 5678 5679 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5680 // on all preceding parameters just being int. Try all of those. 5681 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5682 Expr *Arg = TheCall->getArg(i); 5683 5684 if (Arg->isTypeDependent()) 5685 return false; 5686 5687 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5688 5689 if (Res.isInvalid()) 5690 return true; 5691 TheCall->setArg(i, Res.get()); 5692 } 5693 5694 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5695 5696 if (OrigArg->isTypeDependent()) 5697 return false; 5698 5699 // Usual Unary Conversions will convert half to float, which we want for 5700 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5701 // type how it is, but do normal L->Rvalue conversions. 5702 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5703 OrigArg = UsualUnaryConversions(OrigArg).get(); 5704 else 5705 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5706 TheCall->setArg(NumArgs - 1, OrigArg); 5707 5708 // This operation requires a non-_Complex floating-point number. 5709 if (!OrigArg->getType()->isRealFloatingType()) 5710 return Diag(OrigArg->getBeginLoc(), 5711 diag::err_typecheck_call_invalid_unary_fp) 5712 << OrigArg->getType() << OrigArg->getSourceRange(); 5713 5714 return false; 5715 } 5716 5717 // Customized Sema Checking for VSX builtins that have the following signature: 5718 // vector [...] builtinName(vector [...], vector [...], const int); 5719 // Which takes the same type of vectors (any legal vector type) for the first 5720 // two arguments and takes compile time constant for the third argument. 5721 // Example builtins are : 5722 // vector double vec_xxpermdi(vector double, vector double, int); 5723 // vector short vec_xxsldwi(vector short, vector short, int); 5724 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5725 unsigned ExpectedNumArgs = 3; 5726 if (TheCall->getNumArgs() < ExpectedNumArgs) 5727 return Diag(TheCall->getEndLoc(), 5728 diag::err_typecheck_call_too_few_args_at_least) 5729 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5730 << TheCall->getSourceRange(); 5731 5732 if (TheCall->getNumArgs() > ExpectedNumArgs) 5733 return Diag(TheCall->getEndLoc(), 5734 diag::err_typecheck_call_too_many_args_at_most) 5735 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5736 << TheCall->getSourceRange(); 5737 5738 // Check the third argument is a compile time constant 5739 llvm::APSInt Value; 5740 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5741 return Diag(TheCall->getBeginLoc(), 5742 diag::err_vsx_builtin_nonconstant_argument) 5743 << 3 /* argument index */ << TheCall->getDirectCallee() 5744 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5745 TheCall->getArg(2)->getEndLoc()); 5746 5747 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5748 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5749 5750 // Check the type of argument 1 and argument 2 are vectors. 5751 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5752 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5753 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5754 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5755 << TheCall->getDirectCallee() 5756 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5757 TheCall->getArg(1)->getEndLoc()); 5758 } 5759 5760 // Check the first two arguments are the same type. 5761 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5762 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5763 << TheCall->getDirectCallee() 5764 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5765 TheCall->getArg(1)->getEndLoc()); 5766 } 5767 5768 // When default clang type checking is turned off and the customized type 5769 // checking is used, the returning type of the function must be explicitly 5770 // set. Otherwise it is _Bool by default. 5771 TheCall->setType(Arg1Ty); 5772 5773 return false; 5774 } 5775 5776 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5777 // This is declared to take (...), so we have to check everything. 5778 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5779 if (TheCall->getNumArgs() < 2) 5780 return ExprError(Diag(TheCall->getEndLoc(), 5781 diag::err_typecheck_call_too_few_args_at_least) 5782 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5783 << TheCall->getSourceRange()); 5784 5785 // Determine which of the following types of shufflevector we're checking: 5786 // 1) unary, vector mask: (lhs, mask) 5787 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5788 QualType resType = TheCall->getArg(0)->getType(); 5789 unsigned numElements = 0; 5790 5791 if (!TheCall->getArg(0)->isTypeDependent() && 5792 !TheCall->getArg(1)->isTypeDependent()) { 5793 QualType LHSType = TheCall->getArg(0)->getType(); 5794 QualType RHSType = TheCall->getArg(1)->getType(); 5795 5796 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5797 return ExprError( 5798 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5799 << TheCall->getDirectCallee() 5800 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5801 TheCall->getArg(1)->getEndLoc())); 5802 5803 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5804 unsigned numResElements = TheCall->getNumArgs() - 2; 5805 5806 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5807 // with mask. If so, verify that RHS is an integer vector type with the 5808 // same number of elts as lhs. 5809 if (TheCall->getNumArgs() == 2) { 5810 if (!RHSType->hasIntegerRepresentation() || 5811 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5812 return ExprError(Diag(TheCall->getBeginLoc(), 5813 diag::err_vec_builtin_incompatible_vector) 5814 << TheCall->getDirectCallee() 5815 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5816 TheCall->getArg(1)->getEndLoc())); 5817 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5818 return ExprError(Diag(TheCall->getBeginLoc(), 5819 diag::err_vec_builtin_incompatible_vector) 5820 << TheCall->getDirectCallee() 5821 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5822 TheCall->getArg(1)->getEndLoc())); 5823 } else if (numElements != numResElements) { 5824 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5825 resType = Context.getVectorType(eltType, numResElements, 5826 VectorType::GenericVector); 5827 } 5828 } 5829 5830 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5831 if (TheCall->getArg(i)->isTypeDependent() || 5832 TheCall->getArg(i)->isValueDependent()) 5833 continue; 5834 5835 llvm::APSInt Result(32); 5836 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5837 return ExprError(Diag(TheCall->getBeginLoc(), 5838 diag::err_shufflevector_nonconstant_argument) 5839 << TheCall->getArg(i)->getSourceRange()); 5840 5841 // Allow -1 which will be translated to undef in the IR. 5842 if (Result.isSigned() && Result.isAllOnesValue()) 5843 continue; 5844 5845 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5846 return ExprError(Diag(TheCall->getBeginLoc(), 5847 diag::err_shufflevector_argument_too_large) 5848 << TheCall->getArg(i)->getSourceRange()); 5849 } 5850 5851 SmallVector<Expr*, 32> exprs; 5852 5853 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5854 exprs.push_back(TheCall->getArg(i)); 5855 TheCall->setArg(i, nullptr); 5856 } 5857 5858 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5859 TheCall->getCallee()->getBeginLoc(), 5860 TheCall->getRParenLoc()); 5861 } 5862 5863 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5864 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5865 SourceLocation BuiltinLoc, 5866 SourceLocation RParenLoc) { 5867 ExprValueKind VK = VK_RValue; 5868 ExprObjectKind OK = OK_Ordinary; 5869 QualType DstTy = TInfo->getType(); 5870 QualType SrcTy = E->getType(); 5871 5872 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5873 return ExprError(Diag(BuiltinLoc, 5874 diag::err_convertvector_non_vector) 5875 << E->getSourceRange()); 5876 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5877 return ExprError(Diag(BuiltinLoc, 5878 diag::err_convertvector_non_vector_type)); 5879 5880 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5881 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 5882 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 5883 if (SrcElts != DstElts) 5884 return ExprError(Diag(BuiltinLoc, 5885 diag::err_convertvector_incompatible_vector) 5886 << E->getSourceRange()); 5887 } 5888 5889 return new (Context) 5890 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5891 } 5892 5893 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5894 // This is declared to take (const void*, ...) and can take two 5895 // optional constant int args. 5896 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5897 unsigned NumArgs = TheCall->getNumArgs(); 5898 5899 if (NumArgs > 3) 5900 return Diag(TheCall->getEndLoc(), 5901 diag::err_typecheck_call_too_many_args_at_most) 5902 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5903 5904 // Argument 0 is checked for us and the remaining arguments must be 5905 // constant integers. 5906 for (unsigned i = 1; i != NumArgs; ++i) 5907 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5908 return true; 5909 5910 return false; 5911 } 5912 5913 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5914 // __assume does not evaluate its arguments, and should warn if its argument 5915 // has side effects. 5916 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5917 Expr *Arg = TheCall->getArg(0); 5918 if (Arg->isInstantiationDependent()) return false; 5919 5920 if (Arg->HasSideEffects(Context)) 5921 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5922 << Arg->getSourceRange() 5923 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5924 5925 return false; 5926 } 5927 5928 /// Handle __builtin_alloca_with_align. This is declared 5929 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5930 /// than 8. 5931 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5932 // The alignment must be a constant integer. 5933 Expr *Arg = TheCall->getArg(1); 5934 5935 // We can't check the value of a dependent argument. 5936 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5937 if (const auto *UE = 5938 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5939 if (UE->getKind() == UETT_AlignOf || 5940 UE->getKind() == UETT_PreferredAlignOf) 5941 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5942 << Arg->getSourceRange(); 5943 5944 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5945 5946 if (!Result.isPowerOf2()) 5947 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5948 << Arg->getSourceRange(); 5949 5950 if (Result < Context.getCharWidth()) 5951 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5952 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5953 5954 if (Result > std::numeric_limits<int32_t>::max()) 5955 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5956 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5957 } 5958 5959 return false; 5960 } 5961 5962 /// Handle __builtin_assume_aligned. This is declared 5963 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5964 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5965 unsigned NumArgs = TheCall->getNumArgs(); 5966 5967 if (NumArgs > 3) 5968 return Diag(TheCall->getEndLoc(), 5969 diag::err_typecheck_call_too_many_args_at_most) 5970 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5971 5972 // The alignment must be a constant integer. 5973 Expr *Arg = TheCall->getArg(1); 5974 5975 // We can't check the value of a dependent argument. 5976 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5977 llvm::APSInt Result; 5978 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5979 return true; 5980 5981 if (!Result.isPowerOf2()) 5982 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5983 << Arg->getSourceRange(); 5984 5985 if (Result > Sema::MaximumAlignment) 5986 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 5987 << Arg->getSourceRange() << Sema::MaximumAlignment; 5988 } 5989 5990 if (NumArgs > 2) { 5991 ExprResult Arg(TheCall->getArg(2)); 5992 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5993 Context.getSizeType(), false); 5994 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5995 if (Arg.isInvalid()) return true; 5996 TheCall->setArg(2, Arg.get()); 5997 } 5998 5999 return false; 6000 } 6001 6002 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6003 unsigned BuiltinID = 6004 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6005 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6006 6007 unsigned NumArgs = TheCall->getNumArgs(); 6008 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6009 if (NumArgs < NumRequiredArgs) { 6010 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6011 << 0 /* function call */ << NumRequiredArgs << NumArgs 6012 << TheCall->getSourceRange(); 6013 } 6014 if (NumArgs >= NumRequiredArgs + 0x100) { 6015 return Diag(TheCall->getEndLoc(), 6016 diag::err_typecheck_call_too_many_args_at_most) 6017 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6018 << TheCall->getSourceRange(); 6019 } 6020 unsigned i = 0; 6021 6022 // For formatting call, check buffer arg. 6023 if (!IsSizeCall) { 6024 ExprResult Arg(TheCall->getArg(i)); 6025 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6026 Context, Context.VoidPtrTy, false); 6027 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6028 if (Arg.isInvalid()) 6029 return true; 6030 TheCall->setArg(i, Arg.get()); 6031 i++; 6032 } 6033 6034 // Check string literal arg. 6035 unsigned FormatIdx = i; 6036 { 6037 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6038 if (Arg.isInvalid()) 6039 return true; 6040 TheCall->setArg(i, Arg.get()); 6041 i++; 6042 } 6043 6044 // Make sure variadic args are scalar. 6045 unsigned FirstDataArg = i; 6046 while (i < NumArgs) { 6047 ExprResult Arg = DefaultVariadicArgumentPromotion( 6048 TheCall->getArg(i), VariadicFunction, nullptr); 6049 if (Arg.isInvalid()) 6050 return true; 6051 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6052 if (ArgSize.getQuantity() >= 0x100) { 6053 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6054 << i << (int)ArgSize.getQuantity() << 0xff 6055 << TheCall->getSourceRange(); 6056 } 6057 TheCall->setArg(i, Arg.get()); 6058 i++; 6059 } 6060 6061 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6062 // call to avoid duplicate diagnostics. 6063 if (!IsSizeCall) { 6064 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6065 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6066 bool Success = CheckFormatArguments( 6067 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6068 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6069 CheckedVarArgs); 6070 if (!Success) 6071 return true; 6072 } 6073 6074 if (IsSizeCall) { 6075 TheCall->setType(Context.getSizeType()); 6076 } else { 6077 TheCall->setType(Context.VoidPtrTy); 6078 } 6079 return false; 6080 } 6081 6082 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6083 /// TheCall is a constant expression. 6084 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6085 llvm::APSInt &Result) { 6086 Expr *Arg = TheCall->getArg(ArgNum); 6087 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6088 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6089 6090 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6091 6092 if (!Arg->isIntegerConstantExpr(Result, Context)) 6093 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6094 << FDecl->getDeclName() << Arg->getSourceRange(); 6095 6096 return false; 6097 } 6098 6099 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6100 /// TheCall is a constant expression in the range [Low, High]. 6101 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6102 int Low, int High, bool RangeIsError) { 6103 if (isConstantEvaluated()) 6104 return false; 6105 llvm::APSInt Result; 6106 6107 // We can't check the value of a dependent argument. 6108 Expr *Arg = TheCall->getArg(ArgNum); 6109 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6110 return false; 6111 6112 // Check constant-ness first. 6113 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6114 return true; 6115 6116 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6117 if (RangeIsError) 6118 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6119 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6120 else 6121 // Defer the warning until we know if the code will be emitted so that 6122 // dead code can ignore this. 6123 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6124 PDiag(diag::warn_argument_invalid_range) 6125 << Result.toString(10) << Low << High 6126 << Arg->getSourceRange()); 6127 } 6128 6129 return false; 6130 } 6131 6132 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6133 /// TheCall is a constant expression is a multiple of Num.. 6134 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6135 unsigned Num) { 6136 llvm::APSInt Result; 6137 6138 // We can't check the value of a dependent argument. 6139 Expr *Arg = TheCall->getArg(ArgNum); 6140 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6141 return false; 6142 6143 // Check constant-ness first. 6144 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6145 return true; 6146 6147 if (Result.getSExtValue() % Num != 0) 6148 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6149 << Num << Arg->getSourceRange(); 6150 6151 return false; 6152 } 6153 6154 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6155 /// constant expression representing a power of 2. 6156 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6157 llvm::APSInt Result; 6158 6159 // We can't check the value of a dependent argument. 6160 Expr *Arg = TheCall->getArg(ArgNum); 6161 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6162 return false; 6163 6164 // Check constant-ness first. 6165 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6166 return true; 6167 6168 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6169 // and only if x is a power of 2. 6170 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6171 return false; 6172 6173 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6174 << Arg->getSourceRange(); 6175 } 6176 6177 static bool IsShiftedByte(llvm::APSInt Value) { 6178 if (Value.isNegative()) 6179 return false; 6180 6181 // Check if it's a shifted byte, by shifting it down 6182 while (true) { 6183 // If the value fits in the bottom byte, the check passes. 6184 if (Value < 0x100) 6185 return true; 6186 6187 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6188 // fails. 6189 if ((Value & 0xFF) != 0) 6190 return false; 6191 6192 // If the bottom 8 bits are all 0, but something above that is nonzero, 6193 // then shifting the value right by 8 bits won't affect whether it's a 6194 // shifted byte or not. So do that, and go round again. 6195 Value >>= 8; 6196 } 6197 } 6198 6199 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6200 /// a constant expression representing an arbitrary byte value shifted left by 6201 /// a multiple of 8 bits. 6202 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6203 unsigned ArgBits) { 6204 llvm::APSInt Result; 6205 6206 // We can't check the value of a dependent argument. 6207 Expr *Arg = TheCall->getArg(ArgNum); 6208 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6209 return false; 6210 6211 // Check constant-ness first. 6212 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6213 return true; 6214 6215 // Truncate to the given size. 6216 Result = Result.getLoBits(ArgBits); 6217 Result.setIsUnsigned(true); 6218 6219 if (IsShiftedByte(Result)) 6220 return false; 6221 6222 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6223 << Arg->getSourceRange(); 6224 } 6225 6226 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6227 /// TheCall is a constant expression representing either a shifted byte value, 6228 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6229 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6230 /// Arm MVE intrinsics. 6231 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6232 int ArgNum, 6233 unsigned ArgBits) { 6234 llvm::APSInt Result; 6235 6236 // We can't check the value of a dependent argument. 6237 Expr *Arg = TheCall->getArg(ArgNum); 6238 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6239 return false; 6240 6241 // Check constant-ness first. 6242 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6243 return true; 6244 6245 // Truncate to the given size. 6246 Result = Result.getLoBits(ArgBits); 6247 Result.setIsUnsigned(true); 6248 6249 // Check to see if it's in either of the required forms. 6250 if (IsShiftedByte(Result) || 6251 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6252 return false; 6253 6254 return Diag(TheCall->getBeginLoc(), 6255 diag::err_argument_not_shifted_byte_or_xxff) 6256 << Arg->getSourceRange(); 6257 } 6258 6259 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6260 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6261 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6262 if (checkArgCount(*this, TheCall, 2)) 6263 return true; 6264 Expr *Arg0 = TheCall->getArg(0); 6265 Expr *Arg1 = TheCall->getArg(1); 6266 6267 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6268 if (FirstArg.isInvalid()) 6269 return true; 6270 QualType FirstArgType = FirstArg.get()->getType(); 6271 if (!FirstArgType->isAnyPointerType()) 6272 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6273 << "first" << FirstArgType << Arg0->getSourceRange(); 6274 TheCall->setArg(0, FirstArg.get()); 6275 6276 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6277 if (SecArg.isInvalid()) 6278 return true; 6279 QualType SecArgType = SecArg.get()->getType(); 6280 if (!SecArgType->isIntegerType()) 6281 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6282 << "second" << SecArgType << Arg1->getSourceRange(); 6283 6284 // Derive the return type from the pointer argument. 6285 TheCall->setType(FirstArgType); 6286 return false; 6287 } 6288 6289 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6290 if (checkArgCount(*this, TheCall, 2)) 6291 return true; 6292 6293 Expr *Arg0 = TheCall->getArg(0); 6294 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6295 if (FirstArg.isInvalid()) 6296 return true; 6297 QualType FirstArgType = FirstArg.get()->getType(); 6298 if (!FirstArgType->isAnyPointerType()) 6299 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6300 << "first" << FirstArgType << Arg0->getSourceRange(); 6301 TheCall->setArg(0, FirstArg.get()); 6302 6303 // Derive the return type from the pointer argument. 6304 TheCall->setType(FirstArgType); 6305 6306 // Second arg must be an constant in range [0,15] 6307 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6308 } 6309 6310 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6311 if (checkArgCount(*this, TheCall, 2)) 6312 return true; 6313 Expr *Arg0 = TheCall->getArg(0); 6314 Expr *Arg1 = TheCall->getArg(1); 6315 6316 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6317 if (FirstArg.isInvalid()) 6318 return true; 6319 QualType FirstArgType = FirstArg.get()->getType(); 6320 if (!FirstArgType->isAnyPointerType()) 6321 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6322 << "first" << FirstArgType << Arg0->getSourceRange(); 6323 6324 QualType SecArgType = Arg1->getType(); 6325 if (!SecArgType->isIntegerType()) 6326 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6327 << "second" << SecArgType << Arg1->getSourceRange(); 6328 TheCall->setType(Context.IntTy); 6329 return false; 6330 } 6331 6332 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6333 BuiltinID == AArch64::BI__builtin_arm_stg) { 6334 if (checkArgCount(*this, TheCall, 1)) 6335 return true; 6336 Expr *Arg0 = TheCall->getArg(0); 6337 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6338 if (FirstArg.isInvalid()) 6339 return true; 6340 6341 QualType FirstArgType = FirstArg.get()->getType(); 6342 if (!FirstArgType->isAnyPointerType()) 6343 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6344 << "first" << FirstArgType << Arg0->getSourceRange(); 6345 TheCall->setArg(0, FirstArg.get()); 6346 6347 // Derive the return type from the pointer argument. 6348 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6349 TheCall->setType(FirstArgType); 6350 return false; 6351 } 6352 6353 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6354 Expr *ArgA = TheCall->getArg(0); 6355 Expr *ArgB = TheCall->getArg(1); 6356 6357 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6358 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6359 6360 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6361 return true; 6362 6363 QualType ArgTypeA = ArgExprA.get()->getType(); 6364 QualType ArgTypeB = ArgExprB.get()->getType(); 6365 6366 auto isNull = [&] (Expr *E) -> bool { 6367 return E->isNullPointerConstant( 6368 Context, Expr::NPC_ValueDependentIsNotNull); }; 6369 6370 // argument should be either a pointer or null 6371 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6372 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6373 << "first" << ArgTypeA << ArgA->getSourceRange(); 6374 6375 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6376 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6377 << "second" << ArgTypeB << ArgB->getSourceRange(); 6378 6379 // Ensure Pointee types are compatible 6380 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6381 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6382 QualType pointeeA = ArgTypeA->getPointeeType(); 6383 QualType pointeeB = ArgTypeB->getPointeeType(); 6384 if (!Context.typesAreCompatible( 6385 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6386 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6387 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6388 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6389 << ArgB->getSourceRange(); 6390 } 6391 } 6392 6393 // at least one argument should be pointer type 6394 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6395 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6396 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6397 6398 if (isNull(ArgA)) // adopt type of the other pointer 6399 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6400 6401 if (isNull(ArgB)) 6402 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6403 6404 TheCall->setArg(0, ArgExprA.get()); 6405 TheCall->setArg(1, ArgExprB.get()); 6406 TheCall->setType(Context.LongLongTy); 6407 return false; 6408 } 6409 assert(false && "Unhandled ARM MTE intrinsic"); 6410 return true; 6411 } 6412 6413 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6414 /// TheCall is an ARM/AArch64 special register string literal. 6415 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6416 int ArgNum, unsigned ExpectedFieldNum, 6417 bool AllowName) { 6418 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6419 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6420 BuiltinID == ARM::BI__builtin_arm_rsr || 6421 BuiltinID == ARM::BI__builtin_arm_rsrp || 6422 BuiltinID == ARM::BI__builtin_arm_wsr || 6423 BuiltinID == ARM::BI__builtin_arm_wsrp; 6424 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6425 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6426 BuiltinID == AArch64::BI__builtin_arm_rsr || 6427 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6428 BuiltinID == AArch64::BI__builtin_arm_wsr || 6429 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6430 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6431 6432 // We can't check the value of a dependent argument. 6433 Expr *Arg = TheCall->getArg(ArgNum); 6434 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6435 return false; 6436 6437 // Check if the argument is a string literal. 6438 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6439 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6440 << Arg->getSourceRange(); 6441 6442 // Check the type of special register given. 6443 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6444 SmallVector<StringRef, 6> Fields; 6445 Reg.split(Fields, ":"); 6446 6447 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6448 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6449 << Arg->getSourceRange(); 6450 6451 // If the string is the name of a register then we cannot check that it is 6452 // valid here but if the string is of one the forms described in ACLE then we 6453 // can check that the supplied fields are integers and within the valid 6454 // ranges. 6455 if (Fields.size() > 1) { 6456 bool FiveFields = Fields.size() == 5; 6457 6458 bool ValidString = true; 6459 if (IsARMBuiltin) { 6460 ValidString &= Fields[0].startswith_lower("cp") || 6461 Fields[0].startswith_lower("p"); 6462 if (ValidString) 6463 Fields[0] = 6464 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6465 6466 ValidString &= Fields[2].startswith_lower("c"); 6467 if (ValidString) 6468 Fields[2] = Fields[2].drop_front(1); 6469 6470 if (FiveFields) { 6471 ValidString &= Fields[3].startswith_lower("c"); 6472 if (ValidString) 6473 Fields[3] = Fields[3].drop_front(1); 6474 } 6475 } 6476 6477 SmallVector<int, 5> Ranges; 6478 if (FiveFields) 6479 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6480 else 6481 Ranges.append({15, 7, 15}); 6482 6483 for (unsigned i=0; i<Fields.size(); ++i) { 6484 int IntField; 6485 ValidString &= !Fields[i].getAsInteger(10, IntField); 6486 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6487 } 6488 6489 if (!ValidString) 6490 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6491 << Arg->getSourceRange(); 6492 } else if (IsAArch64Builtin && Fields.size() == 1) { 6493 // If the register name is one of those that appear in the condition below 6494 // and the special register builtin being used is one of the write builtins, 6495 // then we require that the argument provided for writing to the register 6496 // is an integer constant expression. This is because it will be lowered to 6497 // an MSR (immediate) instruction, so we need to know the immediate at 6498 // compile time. 6499 if (TheCall->getNumArgs() != 2) 6500 return false; 6501 6502 std::string RegLower = Reg.lower(); 6503 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6504 RegLower != "pan" && RegLower != "uao") 6505 return false; 6506 6507 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6508 } 6509 6510 return false; 6511 } 6512 6513 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6514 /// This checks that the target supports __builtin_longjmp and 6515 /// that val is a constant 1. 6516 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6517 if (!Context.getTargetInfo().hasSjLjLowering()) 6518 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6519 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6520 6521 Expr *Arg = TheCall->getArg(1); 6522 llvm::APSInt Result; 6523 6524 // TODO: This is less than ideal. Overload this to take a value. 6525 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6526 return true; 6527 6528 if (Result != 1) 6529 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6530 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6531 6532 return false; 6533 } 6534 6535 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6536 /// This checks that the target supports __builtin_setjmp. 6537 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6538 if (!Context.getTargetInfo().hasSjLjLowering()) 6539 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6540 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6541 return false; 6542 } 6543 6544 namespace { 6545 6546 class UncoveredArgHandler { 6547 enum { Unknown = -1, AllCovered = -2 }; 6548 6549 signed FirstUncoveredArg = Unknown; 6550 SmallVector<const Expr *, 4> DiagnosticExprs; 6551 6552 public: 6553 UncoveredArgHandler() = default; 6554 6555 bool hasUncoveredArg() const { 6556 return (FirstUncoveredArg >= 0); 6557 } 6558 6559 unsigned getUncoveredArg() const { 6560 assert(hasUncoveredArg() && "no uncovered argument"); 6561 return FirstUncoveredArg; 6562 } 6563 6564 void setAllCovered() { 6565 // A string has been found with all arguments covered, so clear out 6566 // the diagnostics. 6567 DiagnosticExprs.clear(); 6568 FirstUncoveredArg = AllCovered; 6569 } 6570 6571 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6572 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6573 6574 // Don't update if a previous string covers all arguments. 6575 if (FirstUncoveredArg == AllCovered) 6576 return; 6577 6578 // UncoveredArgHandler tracks the highest uncovered argument index 6579 // and with it all the strings that match this index. 6580 if (NewFirstUncoveredArg == FirstUncoveredArg) 6581 DiagnosticExprs.push_back(StrExpr); 6582 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6583 DiagnosticExprs.clear(); 6584 DiagnosticExprs.push_back(StrExpr); 6585 FirstUncoveredArg = NewFirstUncoveredArg; 6586 } 6587 } 6588 6589 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6590 }; 6591 6592 enum StringLiteralCheckType { 6593 SLCT_NotALiteral, 6594 SLCT_UncheckedLiteral, 6595 SLCT_CheckedLiteral 6596 }; 6597 6598 } // namespace 6599 6600 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6601 BinaryOperatorKind BinOpKind, 6602 bool AddendIsRight) { 6603 unsigned BitWidth = Offset.getBitWidth(); 6604 unsigned AddendBitWidth = Addend.getBitWidth(); 6605 // There might be negative interim results. 6606 if (Addend.isUnsigned()) { 6607 Addend = Addend.zext(++AddendBitWidth); 6608 Addend.setIsSigned(true); 6609 } 6610 // Adjust the bit width of the APSInts. 6611 if (AddendBitWidth > BitWidth) { 6612 Offset = Offset.sext(AddendBitWidth); 6613 BitWidth = AddendBitWidth; 6614 } else if (BitWidth > AddendBitWidth) { 6615 Addend = Addend.sext(BitWidth); 6616 } 6617 6618 bool Ov = false; 6619 llvm::APSInt ResOffset = Offset; 6620 if (BinOpKind == BO_Add) 6621 ResOffset = Offset.sadd_ov(Addend, Ov); 6622 else { 6623 assert(AddendIsRight && BinOpKind == BO_Sub && 6624 "operator must be add or sub with addend on the right"); 6625 ResOffset = Offset.ssub_ov(Addend, Ov); 6626 } 6627 6628 // We add an offset to a pointer here so we should support an offset as big as 6629 // possible. 6630 if (Ov) { 6631 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6632 "index (intermediate) result too big"); 6633 Offset = Offset.sext(2 * BitWidth); 6634 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6635 return; 6636 } 6637 6638 Offset = ResOffset; 6639 } 6640 6641 namespace { 6642 6643 // This is a wrapper class around StringLiteral to support offsetted string 6644 // literals as format strings. It takes the offset into account when returning 6645 // the string and its length or the source locations to display notes correctly. 6646 class FormatStringLiteral { 6647 const StringLiteral *FExpr; 6648 int64_t Offset; 6649 6650 public: 6651 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6652 : FExpr(fexpr), Offset(Offset) {} 6653 6654 StringRef getString() const { 6655 return FExpr->getString().drop_front(Offset); 6656 } 6657 6658 unsigned getByteLength() const { 6659 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6660 } 6661 6662 unsigned getLength() const { return FExpr->getLength() - Offset; } 6663 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6664 6665 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6666 6667 QualType getType() const { return FExpr->getType(); } 6668 6669 bool isAscii() const { return FExpr->isAscii(); } 6670 bool isWide() const { return FExpr->isWide(); } 6671 bool isUTF8() const { return FExpr->isUTF8(); } 6672 bool isUTF16() const { return FExpr->isUTF16(); } 6673 bool isUTF32() const { return FExpr->isUTF32(); } 6674 bool isPascal() const { return FExpr->isPascal(); } 6675 6676 SourceLocation getLocationOfByte( 6677 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6678 const TargetInfo &Target, unsigned *StartToken = nullptr, 6679 unsigned *StartTokenByteOffset = nullptr) const { 6680 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6681 StartToken, StartTokenByteOffset); 6682 } 6683 6684 SourceLocation getBeginLoc() const LLVM_READONLY { 6685 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6686 } 6687 6688 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6689 }; 6690 6691 } // namespace 6692 6693 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6694 const Expr *OrigFormatExpr, 6695 ArrayRef<const Expr *> Args, 6696 bool HasVAListArg, unsigned format_idx, 6697 unsigned firstDataArg, 6698 Sema::FormatStringType Type, 6699 bool inFunctionCall, 6700 Sema::VariadicCallType CallType, 6701 llvm::SmallBitVector &CheckedVarArgs, 6702 UncoveredArgHandler &UncoveredArg, 6703 bool IgnoreStringsWithoutSpecifiers); 6704 6705 // Determine if an expression is a string literal or constant string. 6706 // If this function returns false on the arguments to a function expecting a 6707 // format string, we will usually need to emit a warning. 6708 // True string literals are then checked by CheckFormatString. 6709 static StringLiteralCheckType 6710 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6711 bool HasVAListArg, unsigned format_idx, 6712 unsigned firstDataArg, Sema::FormatStringType Type, 6713 Sema::VariadicCallType CallType, bool InFunctionCall, 6714 llvm::SmallBitVector &CheckedVarArgs, 6715 UncoveredArgHandler &UncoveredArg, 6716 llvm::APSInt Offset, 6717 bool IgnoreStringsWithoutSpecifiers = false) { 6718 if (S.isConstantEvaluated()) 6719 return SLCT_NotALiteral; 6720 tryAgain: 6721 assert(Offset.isSigned() && "invalid offset"); 6722 6723 if (E->isTypeDependent() || E->isValueDependent()) 6724 return SLCT_NotALiteral; 6725 6726 E = E->IgnoreParenCasts(); 6727 6728 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6729 // Technically -Wformat-nonliteral does not warn about this case. 6730 // The behavior of printf and friends in this case is implementation 6731 // dependent. Ideally if the format string cannot be null then 6732 // it should have a 'nonnull' attribute in the function prototype. 6733 return SLCT_UncheckedLiteral; 6734 6735 switch (E->getStmtClass()) { 6736 case Stmt::BinaryConditionalOperatorClass: 6737 case Stmt::ConditionalOperatorClass: { 6738 // The expression is a literal if both sub-expressions were, and it was 6739 // completely checked only if both sub-expressions were checked. 6740 const AbstractConditionalOperator *C = 6741 cast<AbstractConditionalOperator>(E); 6742 6743 // Determine whether it is necessary to check both sub-expressions, for 6744 // example, because the condition expression is a constant that can be 6745 // evaluated at compile time. 6746 bool CheckLeft = true, CheckRight = true; 6747 6748 bool Cond; 6749 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6750 S.isConstantEvaluated())) { 6751 if (Cond) 6752 CheckRight = false; 6753 else 6754 CheckLeft = false; 6755 } 6756 6757 // We need to maintain the offsets for the right and the left hand side 6758 // separately to check if every possible indexed expression is a valid 6759 // string literal. They might have different offsets for different string 6760 // literals in the end. 6761 StringLiteralCheckType Left; 6762 if (!CheckLeft) 6763 Left = SLCT_UncheckedLiteral; 6764 else { 6765 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6766 HasVAListArg, format_idx, firstDataArg, 6767 Type, CallType, InFunctionCall, 6768 CheckedVarArgs, UncoveredArg, Offset, 6769 IgnoreStringsWithoutSpecifiers); 6770 if (Left == SLCT_NotALiteral || !CheckRight) { 6771 return Left; 6772 } 6773 } 6774 6775 StringLiteralCheckType Right = checkFormatStringExpr( 6776 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6777 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6778 IgnoreStringsWithoutSpecifiers); 6779 6780 return (CheckLeft && Left < Right) ? Left : Right; 6781 } 6782 6783 case Stmt::ImplicitCastExprClass: 6784 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6785 goto tryAgain; 6786 6787 case Stmt::OpaqueValueExprClass: 6788 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6789 E = src; 6790 goto tryAgain; 6791 } 6792 return SLCT_NotALiteral; 6793 6794 case Stmt::PredefinedExprClass: 6795 // While __func__, etc., are technically not string literals, they 6796 // cannot contain format specifiers and thus are not a security 6797 // liability. 6798 return SLCT_UncheckedLiteral; 6799 6800 case Stmt::DeclRefExprClass: { 6801 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6802 6803 // As an exception, do not flag errors for variables binding to 6804 // const string literals. 6805 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6806 bool isConstant = false; 6807 QualType T = DR->getType(); 6808 6809 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6810 isConstant = AT->getElementType().isConstant(S.Context); 6811 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6812 isConstant = T.isConstant(S.Context) && 6813 PT->getPointeeType().isConstant(S.Context); 6814 } else if (T->isObjCObjectPointerType()) { 6815 // In ObjC, there is usually no "const ObjectPointer" type, 6816 // so don't check if the pointee type is constant. 6817 isConstant = T.isConstant(S.Context); 6818 } 6819 6820 if (isConstant) { 6821 if (const Expr *Init = VD->getAnyInitializer()) { 6822 // Look through initializers like const char c[] = { "foo" } 6823 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6824 if (InitList->isStringLiteralInit()) 6825 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6826 } 6827 return checkFormatStringExpr(S, Init, Args, 6828 HasVAListArg, format_idx, 6829 firstDataArg, Type, CallType, 6830 /*InFunctionCall*/ false, CheckedVarArgs, 6831 UncoveredArg, Offset); 6832 } 6833 } 6834 6835 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6836 // special check to see if the format string is a function parameter 6837 // of the function calling the printf function. If the function 6838 // has an attribute indicating it is a printf-like function, then we 6839 // should suppress warnings concerning non-literals being used in a call 6840 // to a vprintf function. For example: 6841 // 6842 // void 6843 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6844 // va_list ap; 6845 // va_start(ap, fmt); 6846 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6847 // ... 6848 // } 6849 if (HasVAListArg) { 6850 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6851 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6852 int PVIndex = PV->getFunctionScopeIndex() + 1; 6853 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6854 // adjust for implicit parameter 6855 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6856 if (MD->isInstance()) 6857 ++PVIndex; 6858 // We also check if the formats are compatible. 6859 // We can't pass a 'scanf' string to a 'printf' function. 6860 if (PVIndex == PVFormat->getFormatIdx() && 6861 Type == S.GetFormatStringType(PVFormat)) 6862 return SLCT_UncheckedLiteral; 6863 } 6864 } 6865 } 6866 } 6867 } 6868 6869 return SLCT_NotALiteral; 6870 } 6871 6872 case Stmt::CallExprClass: 6873 case Stmt::CXXMemberCallExprClass: { 6874 const CallExpr *CE = cast<CallExpr>(E); 6875 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6876 bool IsFirst = true; 6877 StringLiteralCheckType CommonResult; 6878 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6879 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6880 StringLiteralCheckType Result = checkFormatStringExpr( 6881 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6882 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6883 IgnoreStringsWithoutSpecifiers); 6884 if (IsFirst) { 6885 CommonResult = Result; 6886 IsFirst = false; 6887 } 6888 } 6889 if (!IsFirst) 6890 return CommonResult; 6891 6892 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6893 unsigned BuiltinID = FD->getBuiltinID(); 6894 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6895 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6896 const Expr *Arg = CE->getArg(0); 6897 return checkFormatStringExpr(S, Arg, Args, 6898 HasVAListArg, format_idx, 6899 firstDataArg, Type, CallType, 6900 InFunctionCall, CheckedVarArgs, 6901 UncoveredArg, Offset, 6902 IgnoreStringsWithoutSpecifiers); 6903 } 6904 } 6905 } 6906 6907 return SLCT_NotALiteral; 6908 } 6909 case Stmt::ObjCMessageExprClass: { 6910 const auto *ME = cast<ObjCMessageExpr>(E); 6911 if (const auto *MD = ME->getMethodDecl()) { 6912 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 6913 // As a special case heuristic, if we're using the method -[NSBundle 6914 // localizedStringForKey:value:table:], ignore any key strings that lack 6915 // format specifiers. The idea is that if the key doesn't have any 6916 // format specifiers then its probably just a key to map to the 6917 // localized strings. If it does have format specifiers though, then its 6918 // likely that the text of the key is the format string in the 6919 // programmer's language, and should be checked. 6920 const ObjCInterfaceDecl *IFace; 6921 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 6922 IFace->getIdentifier()->isStr("NSBundle") && 6923 MD->getSelector().isKeywordSelector( 6924 {"localizedStringForKey", "value", "table"})) { 6925 IgnoreStringsWithoutSpecifiers = true; 6926 } 6927 6928 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6929 return checkFormatStringExpr( 6930 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6931 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6932 IgnoreStringsWithoutSpecifiers); 6933 } 6934 } 6935 6936 return SLCT_NotALiteral; 6937 } 6938 case Stmt::ObjCStringLiteralClass: 6939 case Stmt::StringLiteralClass: { 6940 const StringLiteral *StrE = nullptr; 6941 6942 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6943 StrE = ObjCFExpr->getString(); 6944 else 6945 StrE = cast<StringLiteral>(E); 6946 6947 if (StrE) { 6948 if (Offset.isNegative() || Offset > StrE->getLength()) { 6949 // TODO: It would be better to have an explicit warning for out of 6950 // bounds literals. 6951 return SLCT_NotALiteral; 6952 } 6953 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6954 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6955 firstDataArg, Type, InFunctionCall, CallType, 6956 CheckedVarArgs, UncoveredArg, 6957 IgnoreStringsWithoutSpecifiers); 6958 return SLCT_CheckedLiteral; 6959 } 6960 6961 return SLCT_NotALiteral; 6962 } 6963 case Stmt::BinaryOperatorClass: { 6964 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6965 6966 // A string literal + an int offset is still a string literal. 6967 if (BinOp->isAdditiveOp()) { 6968 Expr::EvalResult LResult, RResult; 6969 6970 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 6971 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6972 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 6973 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6974 6975 if (LIsInt != RIsInt) { 6976 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6977 6978 if (LIsInt) { 6979 if (BinOpKind == BO_Add) { 6980 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6981 E = BinOp->getRHS(); 6982 goto tryAgain; 6983 } 6984 } else { 6985 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6986 E = BinOp->getLHS(); 6987 goto tryAgain; 6988 } 6989 } 6990 } 6991 6992 return SLCT_NotALiteral; 6993 } 6994 case Stmt::UnaryOperatorClass: { 6995 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6996 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6997 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6998 Expr::EvalResult IndexResult; 6999 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7000 Expr::SE_NoSideEffects, 7001 S.isConstantEvaluated())) { 7002 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7003 /*RHS is int*/ true); 7004 E = ASE->getBase(); 7005 goto tryAgain; 7006 } 7007 } 7008 7009 return SLCT_NotALiteral; 7010 } 7011 7012 default: 7013 return SLCT_NotALiteral; 7014 } 7015 } 7016 7017 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7018 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7019 .Case("scanf", FST_Scanf) 7020 .Cases("printf", "printf0", FST_Printf) 7021 .Cases("NSString", "CFString", FST_NSString) 7022 .Case("strftime", FST_Strftime) 7023 .Case("strfmon", FST_Strfmon) 7024 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7025 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7026 .Case("os_trace", FST_OSLog) 7027 .Case("os_log", FST_OSLog) 7028 .Default(FST_Unknown); 7029 } 7030 7031 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7032 /// functions) for correct use of format strings. 7033 /// Returns true if a format string has been fully checked. 7034 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7035 ArrayRef<const Expr *> Args, 7036 bool IsCXXMember, 7037 VariadicCallType CallType, 7038 SourceLocation Loc, SourceRange Range, 7039 llvm::SmallBitVector &CheckedVarArgs) { 7040 FormatStringInfo FSI; 7041 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7042 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7043 FSI.FirstDataArg, GetFormatStringType(Format), 7044 CallType, Loc, Range, CheckedVarArgs); 7045 return false; 7046 } 7047 7048 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7049 bool HasVAListArg, unsigned format_idx, 7050 unsigned firstDataArg, FormatStringType Type, 7051 VariadicCallType CallType, 7052 SourceLocation Loc, SourceRange Range, 7053 llvm::SmallBitVector &CheckedVarArgs) { 7054 // CHECK: printf/scanf-like function is called with no format string. 7055 if (format_idx >= Args.size()) { 7056 Diag(Loc, diag::warn_missing_format_string) << Range; 7057 return false; 7058 } 7059 7060 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7061 7062 // CHECK: format string is not a string literal. 7063 // 7064 // Dynamically generated format strings are difficult to 7065 // automatically vet at compile time. Requiring that format strings 7066 // are string literals: (1) permits the checking of format strings by 7067 // the compiler and thereby (2) can practically remove the source of 7068 // many format string exploits. 7069 7070 // Format string can be either ObjC string (e.g. @"%d") or 7071 // C string (e.g. "%d") 7072 // ObjC string uses the same format specifiers as C string, so we can use 7073 // the same format string checking logic for both ObjC and C strings. 7074 UncoveredArgHandler UncoveredArg; 7075 StringLiteralCheckType CT = 7076 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7077 format_idx, firstDataArg, Type, CallType, 7078 /*IsFunctionCall*/ true, CheckedVarArgs, 7079 UncoveredArg, 7080 /*no string offset*/ llvm::APSInt(64, false) = 0); 7081 7082 // Generate a diagnostic where an uncovered argument is detected. 7083 if (UncoveredArg.hasUncoveredArg()) { 7084 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7085 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7086 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7087 } 7088 7089 if (CT != SLCT_NotALiteral) 7090 // Literal format string found, check done! 7091 return CT == SLCT_CheckedLiteral; 7092 7093 // Strftime is particular as it always uses a single 'time' argument, 7094 // so it is safe to pass a non-literal string. 7095 if (Type == FST_Strftime) 7096 return false; 7097 7098 // Do not emit diag when the string param is a macro expansion and the 7099 // format is either NSString or CFString. This is a hack to prevent 7100 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7101 // which are usually used in place of NS and CF string literals. 7102 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7103 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7104 return false; 7105 7106 // If there are no arguments specified, warn with -Wformat-security, otherwise 7107 // warn only with -Wformat-nonliteral. 7108 if (Args.size() == firstDataArg) { 7109 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7110 << OrigFormatExpr->getSourceRange(); 7111 switch (Type) { 7112 default: 7113 break; 7114 case FST_Kprintf: 7115 case FST_FreeBSDKPrintf: 7116 case FST_Printf: 7117 Diag(FormatLoc, diag::note_format_security_fixit) 7118 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7119 break; 7120 case FST_NSString: 7121 Diag(FormatLoc, diag::note_format_security_fixit) 7122 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7123 break; 7124 } 7125 } else { 7126 Diag(FormatLoc, diag::warn_format_nonliteral) 7127 << OrigFormatExpr->getSourceRange(); 7128 } 7129 return false; 7130 } 7131 7132 namespace { 7133 7134 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7135 protected: 7136 Sema &S; 7137 const FormatStringLiteral *FExpr; 7138 const Expr *OrigFormatExpr; 7139 const Sema::FormatStringType FSType; 7140 const unsigned FirstDataArg; 7141 const unsigned NumDataArgs; 7142 const char *Beg; // Start of format string. 7143 const bool HasVAListArg; 7144 ArrayRef<const Expr *> Args; 7145 unsigned FormatIdx; 7146 llvm::SmallBitVector CoveredArgs; 7147 bool usesPositionalArgs = false; 7148 bool atFirstArg = true; 7149 bool inFunctionCall; 7150 Sema::VariadicCallType CallType; 7151 llvm::SmallBitVector &CheckedVarArgs; 7152 UncoveredArgHandler &UncoveredArg; 7153 7154 public: 7155 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7156 const Expr *origFormatExpr, 7157 const Sema::FormatStringType type, unsigned firstDataArg, 7158 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7159 ArrayRef<const Expr *> Args, unsigned formatIdx, 7160 bool inFunctionCall, Sema::VariadicCallType callType, 7161 llvm::SmallBitVector &CheckedVarArgs, 7162 UncoveredArgHandler &UncoveredArg) 7163 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7164 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7165 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7166 inFunctionCall(inFunctionCall), CallType(callType), 7167 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7168 CoveredArgs.resize(numDataArgs); 7169 CoveredArgs.reset(); 7170 } 7171 7172 void DoneProcessing(); 7173 7174 void HandleIncompleteSpecifier(const char *startSpecifier, 7175 unsigned specifierLen) override; 7176 7177 void HandleInvalidLengthModifier( 7178 const analyze_format_string::FormatSpecifier &FS, 7179 const analyze_format_string::ConversionSpecifier &CS, 7180 const char *startSpecifier, unsigned specifierLen, 7181 unsigned DiagID); 7182 7183 void HandleNonStandardLengthModifier( 7184 const analyze_format_string::FormatSpecifier &FS, 7185 const char *startSpecifier, unsigned specifierLen); 7186 7187 void HandleNonStandardConversionSpecifier( 7188 const analyze_format_string::ConversionSpecifier &CS, 7189 const char *startSpecifier, unsigned specifierLen); 7190 7191 void HandlePosition(const char *startPos, unsigned posLen) override; 7192 7193 void HandleInvalidPosition(const char *startSpecifier, 7194 unsigned specifierLen, 7195 analyze_format_string::PositionContext p) override; 7196 7197 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7198 7199 void HandleNullChar(const char *nullCharacter) override; 7200 7201 template <typename Range> 7202 static void 7203 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7204 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7205 bool IsStringLocation, Range StringRange, 7206 ArrayRef<FixItHint> Fixit = None); 7207 7208 protected: 7209 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7210 const char *startSpec, 7211 unsigned specifierLen, 7212 const char *csStart, unsigned csLen); 7213 7214 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7215 const char *startSpec, 7216 unsigned specifierLen); 7217 7218 SourceRange getFormatStringRange(); 7219 CharSourceRange getSpecifierRange(const char *startSpecifier, 7220 unsigned specifierLen); 7221 SourceLocation getLocationOfByte(const char *x); 7222 7223 const Expr *getDataArg(unsigned i) const; 7224 7225 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7226 const analyze_format_string::ConversionSpecifier &CS, 7227 const char *startSpecifier, unsigned specifierLen, 7228 unsigned argIndex); 7229 7230 template <typename Range> 7231 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7232 bool IsStringLocation, Range StringRange, 7233 ArrayRef<FixItHint> Fixit = None); 7234 }; 7235 7236 } // namespace 7237 7238 SourceRange CheckFormatHandler::getFormatStringRange() { 7239 return OrigFormatExpr->getSourceRange(); 7240 } 7241 7242 CharSourceRange CheckFormatHandler:: 7243 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7244 SourceLocation Start = getLocationOfByte(startSpecifier); 7245 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7246 7247 // Advance the end SourceLocation by one due to half-open ranges. 7248 End = End.getLocWithOffset(1); 7249 7250 return CharSourceRange::getCharRange(Start, End); 7251 } 7252 7253 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7254 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7255 S.getLangOpts(), S.Context.getTargetInfo()); 7256 } 7257 7258 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7259 unsigned specifierLen){ 7260 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7261 getLocationOfByte(startSpecifier), 7262 /*IsStringLocation*/true, 7263 getSpecifierRange(startSpecifier, specifierLen)); 7264 } 7265 7266 void CheckFormatHandler::HandleInvalidLengthModifier( 7267 const analyze_format_string::FormatSpecifier &FS, 7268 const analyze_format_string::ConversionSpecifier &CS, 7269 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7270 using namespace analyze_format_string; 7271 7272 const LengthModifier &LM = FS.getLengthModifier(); 7273 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7274 7275 // See if we know how to fix this length modifier. 7276 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7277 if (FixedLM) { 7278 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7279 getLocationOfByte(LM.getStart()), 7280 /*IsStringLocation*/true, 7281 getSpecifierRange(startSpecifier, specifierLen)); 7282 7283 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7284 << FixedLM->toString() 7285 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7286 7287 } else { 7288 FixItHint Hint; 7289 if (DiagID == diag::warn_format_nonsensical_length) 7290 Hint = FixItHint::CreateRemoval(LMRange); 7291 7292 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7293 getLocationOfByte(LM.getStart()), 7294 /*IsStringLocation*/true, 7295 getSpecifierRange(startSpecifier, specifierLen), 7296 Hint); 7297 } 7298 } 7299 7300 void CheckFormatHandler::HandleNonStandardLengthModifier( 7301 const analyze_format_string::FormatSpecifier &FS, 7302 const char *startSpecifier, unsigned specifierLen) { 7303 using namespace analyze_format_string; 7304 7305 const LengthModifier &LM = FS.getLengthModifier(); 7306 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7307 7308 // See if we know how to fix this length modifier. 7309 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7310 if (FixedLM) { 7311 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7312 << LM.toString() << 0, 7313 getLocationOfByte(LM.getStart()), 7314 /*IsStringLocation*/true, 7315 getSpecifierRange(startSpecifier, specifierLen)); 7316 7317 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7318 << FixedLM->toString() 7319 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7320 7321 } else { 7322 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7323 << LM.toString() << 0, 7324 getLocationOfByte(LM.getStart()), 7325 /*IsStringLocation*/true, 7326 getSpecifierRange(startSpecifier, specifierLen)); 7327 } 7328 } 7329 7330 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7331 const analyze_format_string::ConversionSpecifier &CS, 7332 const char *startSpecifier, unsigned specifierLen) { 7333 using namespace analyze_format_string; 7334 7335 // See if we know how to fix this conversion specifier. 7336 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7337 if (FixedCS) { 7338 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7339 << CS.toString() << /*conversion specifier*/1, 7340 getLocationOfByte(CS.getStart()), 7341 /*IsStringLocation*/true, 7342 getSpecifierRange(startSpecifier, specifierLen)); 7343 7344 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7345 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7346 << FixedCS->toString() 7347 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7348 } else { 7349 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7350 << CS.toString() << /*conversion specifier*/1, 7351 getLocationOfByte(CS.getStart()), 7352 /*IsStringLocation*/true, 7353 getSpecifierRange(startSpecifier, specifierLen)); 7354 } 7355 } 7356 7357 void CheckFormatHandler::HandlePosition(const char *startPos, 7358 unsigned posLen) { 7359 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7360 getLocationOfByte(startPos), 7361 /*IsStringLocation*/true, 7362 getSpecifierRange(startPos, posLen)); 7363 } 7364 7365 void 7366 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7367 analyze_format_string::PositionContext p) { 7368 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7369 << (unsigned) p, 7370 getLocationOfByte(startPos), /*IsStringLocation*/true, 7371 getSpecifierRange(startPos, posLen)); 7372 } 7373 7374 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7375 unsigned posLen) { 7376 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7377 getLocationOfByte(startPos), 7378 /*IsStringLocation*/true, 7379 getSpecifierRange(startPos, posLen)); 7380 } 7381 7382 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7383 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7384 // The presence of a null character is likely an error. 7385 EmitFormatDiagnostic( 7386 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7387 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7388 getFormatStringRange()); 7389 } 7390 } 7391 7392 // Note that this may return NULL if there was an error parsing or building 7393 // one of the argument expressions. 7394 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7395 return Args[FirstDataArg + i]; 7396 } 7397 7398 void CheckFormatHandler::DoneProcessing() { 7399 // Does the number of data arguments exceed the number of 7400 // format conversions in the format string? 7401 if (!HasVAListArg) { 7402 // Find any arguments that weren't covered. 7403 CoveredArgs.flip(); 7404 signed notCoveredArg = CoveredArgs.find_first(); 7405 if (notCoveredArg >= 0) { 7406 assert((unsigned)notCoveredArg < NumDataArgs); 7407 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7408 } else { 7409 UncoveredArg.setAllCovered(); 7410 } 7411 } 7412 } 7413 7414 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7415 const Expr *ArgExpr) { 7416 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7417 "Invalid state"); 7418 7419 if (!ArgExpr) 7420 return; 7421 7422 SourceLocation Loc = ArgExpr->getBeginLoc(); 7423 7424 if (S.getSourceManager().isInSystemMacro(Loc)) 7425 return; 7426 7427 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7428 for (auto E : DiagnosticExprs) 7429 PDiag << E->getSourceRange(); 7430 7431 CheckFormatHandler::EmitFormatDiagnostic( 7432 S, IsFunctionCall, DiagnosticExprs[0], 7433 PDiag, Loc, /*IsStringLocation*/false, 7434 DiagnosticExprs[0]->getSourceRange()); 7435 } 7436 7437 bool 7438 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7439 SourceLocation Loc, 7440 const char *startSpec, 7441 unsigned specifierLen, 7442 const char *csStart, 7443 unsigned csLen) { 7444 bool keepGoing = true; 7445 if (argIndex < NumDataArgs) { 7446 // Consider the argument coverered, even though the specifier doesn't 7447 // make sense. 7448 CoveredArgs.set(argIndex); 7449 } 7450 else { 7451 // If argIndex exceeds the number of data arguments we 7452 // don't issue a warning because that is just a cascade of warnings (and 7453 // they may have intended '%%' anyway). We don't want to continue processing 7454 // the format string after this point, however, as we will like just get 7455 // gibberish when trying to match arguments. 7456 keepGoing = false; 7457 } 7458 7459 StringRef Specifier(csStart, csLen); 7460 7461 // If the specifier in non-printable, it could be the first byte of a UTF-8 7462 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7463 // hex value. 7464 std::string CodePointStr; 7465 if (!llvm::sys::locale::isPrint(*csStart)) { 7466 llvm::UTF32 CodePoint; 7467 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7468 const llvm::UTF8 *E = 7469 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7470 llvm::ConversionResult Result = 7471 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7472 7473 if (Result != llvm::conversionOK) { 7474 unsigned char FirstChar = *csStart; 7475 CodePoint = (llvm::UTF32)FirstChar; 7476 } 7477 7478 llvm::raw_string_ostream OS(CodePointStr); 7479 if (CodePoint < 256) 7480 OS << "\\x" << llvm::format("%02x", CodePoint); 7481 else if (CodePoint <= 0xFFFF) 7482 OS << "\\u" << llvm::format("%04x", CodePoint); 7483 else 7484 OS << "\\U" << llvm::format("%08x", CodePoint); 7485 OS.flush(); 7486 Specifier = CodePointStr; 7487 } 7488 7489 EmitFormatDiagnostic( 7490 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7491 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7492 7493 return keepGoing; 7494 } 7495 7496 void 7497 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7498 const char *startSpec, 7499 unsigned specifierLen) { 7500 EmitFormatDiagnostic( 7501 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7502 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7503 } 7504 7505 bool 7506 CheckFormatHandler::CheckNumArgs( 7507 const analyze_format_string::FormatSpecifier &FS, 7508 const analyze_format_string::ConversionSpecifier &CS, 7509 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7510 7511 if (argIndex >= NumDataArgs) { 7512 PartialDiagnostic PDiag = FS.usesPositionalArg() 7513 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7514 << (argIndex+1) << NumDataArgs) 7515 : S.PDiag(diag::warn_printf_insufficient_data_args); 7516 EmitFormatDiagnostic( 7517 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7518 getSpecifierRange(startSpecifier, specifierLen)); 7519 7520 // Since more arguments than conversion tokens are given, by extension 7521 // all arguments are covered, so mark this as so. 7522 UncoveredArg.setAllCovered(); 7523 return false; 7524 } 7525 return true; 7526 } 7527 7528 template<typename Range> 7529 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7530 SourceLocation Loc, 7531 bool IsStringLocation, 7532 Range StringRange, 7533 ArrayRef<FixItHint> FixIt) { 7534 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7535 Loc, IsStringLocation, StringRange, FixIt); 7536 } 7537 7538 /// If the format string is not within the function call, emit a note 7539 /// so that the function call and string are in diagnostic messages. 7540 /// 7541 /// \param InFunctionCall if true, the format string is within the function 7542 /// call and only one diagnostic message will be produced. Otherwise, an 7543 /// extra note will be emitted pointing to location of the format string. 7544 /// 7545 /// \param ArgumentExpr the expression that is passed as the format string 7546 /// argument in the function call. Used for getting locations when two 7547 /// diagnostics are emitted. 7548 /// 7549 /// \param PDiag the callee should already have provided any strings for the 7550 /// diagnostic message. This function only adds locations and fixits 7551 /// to diagnostics. 7552 /// 7553 /// \param Loc primary location for diagnostic. If two diagnostics are 7554 /// required, one will be at Loc and a new SourceLocation will be created for 7555 /// the other one. 7556 /// 7557 /// \param IsStringLocation if true, Loc points to the format string should be 7558 /// used for the note. Otherwise, Loc points to the argument list and will 7559 /// be used with PDiag. 7560 /// 7561 /// \param StringRange some or all of the string to highlight. This is 7562 /// templated so it can accept either a CharSourceRange or a SourceRange. 7563 /// 7564 /// \param FixIt optional fix it hint for the format string. 7565 template <typename Range> 7566 void CheckFormatHandler::EmitFormatDiagnostic( 7567 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7568 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7569 Range StringRange, ArrayRef<FixItHint> FixIt) { 7570 if (InFunctionCall) { 7571 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7572 D << StringRange; 7573 D << FixIt; 7574 } else { 7575 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7576 << ArgumentExpr->getSourceRange(); 7577 7578 const Sema::SemaDiagnosticBuilder &Note = 7579 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7580 diag::note_format_string_defined); 7581 7582 Note << StringRange; 7583 Note << FixIt; 7584 } 7585 } 7586 7587 //===--- CHECK: Printf format string checking ------------------------------===// 7588 7589 namespace { 7590 7591 class CheckPrintfHandler : public CheckFormatHandler { 7592 public: 7593 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7594 const Expr *origFormatExpr, 7595 const Sema::FormatStringType type, unsigned firstDataArg, 7596 unsigned numDataArgs, bool isObjC, const char *beg, 7597 bool hasVAListArg, ArrayRef<const Expr *> Args, 7598 unsigned formatIdx, bool inFunctionCall, 7599 Sema::VariadicCallType CallType, 7600 llvm::SmallBitVector &CheckedVarArgs, 7601 UncoveredArgHandler &UncoveredArg) 7602 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7603 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7604 inFunctionCall, CallType, CheckedVarArgs, 7605 UncoveredArg) {} 7606 7607 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7608 7609 /// Returns true if '%@' specifiers are allowed in the format string. 7610 bool allowsObjCArg() const { 7611 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7612 FSType == Sema::FST_OSTrace; 7613 } 7614 7615 bool HandleInvalidPrintfConversionSpecifier( 7616 const analyze_printf::PrintfSpecifier &FS, 7617 const char *startSpecifier, 7618 unsigned specifierLen) override; 7619 7620 void handleInvalidMaskType(StringRef MaskType) override; 7621 7622 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7623 const char *startSpecifier, 7624 unsigned specifierLen) override; 7625 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7626 const char *StartSpecifier, 7627 unsigned SpecifierLen, 7628 const Expr *E); 7629 7630 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7631 const char *startSpecifier, unsigned specifierLen); 7632 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7633 const analyze_printf::OptionalAmount &Amt, 7634 unsigned type, 7635 const char *startSpecifier, unsigned specifierLen); 7636 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7637 const analyze_printf::OptionalFlag &flag, 7638 const char *startSpecifier, unsigned specifierLen); 7639 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7640 const analyze_printf::OptionalFlag &ignoredFlag, 7641 const analyze_printf::OptionalFlag &flag, 7642 const char *startSpecifier, unsigned specifierLen); 7643 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7644 const Expr *E); 7645 7646 void HandleEmptyObjCModifierFlag(const char *startFlag, 7647 unsigned flagLen) override; 7648 7649 void HandleInvalidObjCModifierFlag(const char *startFlag, 7650 unsigned flagLen) override; 7651 7652 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7653 const char *flagsEnd, 7654 const char *conversionPosition) 7655 override; 7656 }; 7657 7658 } // namespace 7659 7660 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7661 const analyze_printf::PrintfSpecifier &FS, 7662 const char *startSpecifier, 7663 unsigned specifierLen) { 7664 const analyze_printf::PrintfConversionSpecifier &CS = 7665 FS.getConversionSpecifier(); 7666 7667 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7668 getLocationOfByte(CS.getStart()), 7669 startSpecifier, specifierLen, 7670 CS.getStart(), CS.getLength()); 7671 } 7672 7673 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7674 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7675 } 7676 7677 bool CheckPrintfHandler::HandleAmount( 7678 const analyze_format_string::OptionalAmount &Amt, 7679 unsigned k, const char *startSpecifier, 7680 unsigned specifierLen) { 7681 if (Amt.hasDataArgument()) { 7682 if (!HasVAListArg) { 7683 unsigned argIndex = Amt.getArgIndex(); 7684 if (argIndex >= NumDataArgs) { 7685 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7686 << k, 7687 getLocationOfByte(Amt.getStart()), 7688 /*IsStringLocation*/true, 7689 getSpecifierRange(startSpecifier, specifierLen)); 7690 // Don't do any more checking. We will just emit 7691 // spurious errors. 7692 return false; 7693 } 7694 7695 // Type check the data argument. It should be an 'int'. 7696 // Although not in conformance with C99, we also allow the argument to be 7697 // an 'unsigned int' as that is a reasonably safe case. GCC also 7698 // doesn't emit a warning for that case. 7699 CoveredArgs.set(argIndex); 7700 const Expr *Arg = getDataArg(argIndex); 7701 if (!Arg) 7702 return false; 7703 7704 QualType T = Arg->getType(); 7705 7706 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7707 assert(AT.isValid()); 7708 7709 if (!AT.matchesType(S.Context, T)) { 7710 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7711 << k << AT.getRepresentativeTypeName(S.Context) 7712 << T << Arg->getSourceRange(), 7713 getLocationOfByte(Amt.getStart()), 7714 /*IsStringLocation*/true, 7715 getSpecifierRange(startSpecifier, specifierLen)); 7716 // Don't do any more checking. We will just emit 7717 // spurious errors. 7718 return false; 7719 } 7720 } 7721 } 7722 return true; 7723 } 7724 7725 void CheckPrintfHandler::HandleInvalidAmount( 7726 const analyze_printf::PrintfSpecifier &FS, 7727 const analyze_printf::OptionalAmount &Amt, 7728 unsigned type, 7729 const char *startSpecifier, 7730 unsigned specifierLen) { 7731 const analyze_printf::PrintfConversionSpecifier &CS = 7732 FS.getConversionSpecifier(); 7733 7734 FixItHint fixit = 7735 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7736 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7737 Amt.getConstantLength())) 7738 : FixItHint(); 7739 7740 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7741 << type << CS.toString(), 7742 getLocationOfByte(Amt.getStart()), 7743 /*IsStringLocation*/true, 7744 getSpecifierRange(startSpecifier, specifierLen), 7745 fixit); 7746 } 7747 7748 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7749 const analyze_printf::OptionalFlag &flag, 7750 const char *startSpecifier, 7751 unsigned specifierLen) { 7752 // Warn about pointless flag with a fixit removal. 7753 const analyze_printf::PrintfConversionSpecifier &CS = 7754 FS.getConversionSpecifier(); 7755 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7756 << flag.toString() << CS.toString(), 7757 getLocationOfByte(flag.getPosition()), 7758 /*IsStringLocation*/true, 7759 getSpecifierRange(startSpecifier, specifierLen), 7760 FixItHint::CreateRemoval( 7761 getSpecifierRange(flag.getPosition(), 1))); 7762 } 7763 7764 void CheckPrintfHandler::HandleIgnoredFlag( 7765 const analyze_printf::PrintfSpecifier &FS, 7766 const analyze_printf::OptionalFlag &ignoredFlag, 7767 const analyze_printf::OptionalFlag &flag, 7768 const char *startSpecifier, 7769 unsigned specifierLen) { 7770 // Warn about ignored flag with a fixit removal. 7771 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7772 << ignoredFlag.toString() << flag.toString(), 7773 getLocationOfByte(ignoredFlag.getPosition()), 7774 /*IsStringLocation*/true, 7775 getSpecifierRange(startSpecifier, specifierLen), 7776 FixItHint::CreateRemoval( 7777 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7778 } 7779 7780 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7781 unsigned flagLen) { 7782 // Warn about an empty flag. 7783 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7784 getLocationOfByte(startFlag), 7785 /*IsStringLocation*/true, 7786 getSpecifierRange(startFlag, flagLen)); 7787 } 7788 7789 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7790 unsigned flagLen) { 7791 // Warn about an invalid flag. 7792 auto Range = getSpecifierRange(startFlag, flagLen); 7793 StringRef flag(startFlag, flagLen); 7794 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7795 getLocationOfByte(startFlag), 7796 /*IsStringLocation*/true, 7797 Range, FixItHint::CreateRemoval(Range)); 7798 } 7799 7800 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7801 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7802 // Warn about using '[...]' without a '@' conversion. 7803 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7804 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7805 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7806 getLocationOfByte(conversionPosition), 7807 /*IsStringLocation*/true, 7808 Range, FixItHint::CreateRemoval(Range)); 7809 } 7810 7811 // Determines if the specified is a C++ class or struct containing 7812 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7813 // "c_str()"). 7814 template<typename MemberKind> 7815 static llvm::SmallPtrSet<MemberKind*, 1> 7816 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7817 const RecordType *RT = Ty->getAs<RecordType>(); 7818 llvm::SmallPtrSet<MemberKind*, 1> Results; 7819 7820 if (!RT) 7821 return Results; 7822 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7823 if (!RD || !RD->getDefinition()) 7824 return Results; 7825 7826 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7827 Sema::LookupMemberName); 7828 R.suppressDiagnostics(); 7829 7830 // We just need to include all members of the right kind turned up by the 7831 // filter, at this point. 7832 if (S.LookupQualifiedName(R, RT->getDecl())) 7833 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7834 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7835 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7836 Results.insert(FK); 7837 } 7838 return Results; 7839 } 7840 7841 /// Check if we could call '.c_str()' on an object. 7842 /// 7843 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7844 /// allow the call, or if it would be ambiguous). 7845 bool Sema::hasCStrMethod(const Expr *E) { 7846 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7847 7848 MethodSet Results = 7849 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7850 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7851 MI != ME; ++MI) 7852 if ((*MI)->getMinRequiredArguments() == 0) 7853 return true; 7854 return false; 7855 } 7856 7857 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7858 // better diagnostic if so. AT is assumed to be valid. 7859 // Returns true when a c_str() conversion method is found. 7860 bool CheckPrintfHandler::checkForCStrMembers( 7861 const analyze_printf::ArgType &AT, const Expr *E) { 7862 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7863 7864 MethodSet Results = 7865 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7866 7867 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7868 MI != ME; ++MI) { 7869 const CXXMethodDecl *Method = *MI; 7870 if (Method->getMinRequiredArguments() == 0 && 7871 AT.matchesType(S.Context, Method->getReturnType())) { 7872 // FIXME: Suggest parens if the expression needs them. 7873 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7874 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7875 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7876 return true; 7877 } 7878 } 7879 7880 return false; 7881 } 7882 7883 bool 7884 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7885 &FS, 7886 const char *startSpecifier, 7887 unsigned specifierLen) { 7888 using namespace analyze_format_string; 7889 using namespace analyze_printf; 7890 7891 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7892 7893 if (FS.consumesDataArgument()) { 7894 if (atFirstArg) { 7895 atFirstArg = false; 7896 usesPositionalArgs = FS.usesPositionalArg(); 7897 } 7898 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7899 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7900 startSpecifier, specifierLen); 7901 return false; 7902 } 7903 } 7904 7905 // First check if the field width, precision, and conversion specifier 7906 // have matching data arguments. 7907 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7908 startSpecifier, specifierLen)) { 7909 return false; 7910 } 7911 7912 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7913 startSpecifier, specifierLen)) { 7914 return false; 7915 } 7916 7917 if (!CS.consumesDataArgument()) { 7918 // FIXME: Technically specifying a precision or field width here 7919 // makes no sense. Worth issuing a warning at some point. 7920 return true; 7921 } 7922 7923 // Consume the argument. 7924 unsigned argIndex = FS.getArgIndex(); 7925 if (argIndex < NumDataArgs) { 7926 // The check to see if the argIndex is valid will come later. 7927 // We set the bit here because we may exit early from this 7928 // function if we encounter some other error. 7929 CoveredArgs.set(argIndex); 7930 } 7931 7932 // FreeBSD kernel extensions. 7933 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7934 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7935 // We need at least two arguments. 7936 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7937 return false; 7938 7939 // Claim the second argument. 7940 CoveredArgs.set(argIndex + 1); 7941 7942 // Type check the first argument (int for %b, pointer for %D) 7943 const Expr *Ex = getDataArg(argIndex); 7944 const analyze_printf::ArgType &AT = 7945 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7946 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7947 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7948 EmitFormatDiagnostic( 7949 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7950 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7951 << false << Ex->getSourceRange(), 7952 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7953 getSpecifierRange(startSpecifier, specifierLen)); 7954 7955 // Type check the second argument (char * for both %b and %D) 7956 Ex = getDataArg(argIndex + 1); 7957 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7958 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7959 EmitFormatDiagnostic( 7960 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7961 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7962 << false << Ex->getSourceRange(), 7963 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7964 getSpecifierRange(startSpecifier, specifierLen)); 7965 7966 return true; 7967 } 7968 7969 // Check for using an Objective-C specific conversion specifier 7970 // in a non-ObjC literal. 7971 if (!allowsObjCArg() && CS.isObjCArg()) { 7972 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7973 specifierLen); 7974 } 7975 7976 // %P can only be used with os_log. 7977 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7978 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7979 specifierLen); 7980 } 7981 7982 // %n is not allowed with os_log. 7983 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7984 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7985 getLocationOfByte(CS.getStart()), 7986 /*IsStringLocation*/ false, 7987 getSpecifierRange(startSpecifier, specifierLen)); 7988 7989 return true; 7990 } 7991 7992 // Only scalars are allowed for os_trace. 7993 if (FSType == Sema::FST_OSTrace && 7994 (CS.getKind() == ConversionSpecifier::PArg || 7995 CS.getKind() == ConversionSpecifier::sArg || 7996 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7997 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7998 specifierLen); 7999 } 8000 8001 // Check for use of public/private annotation outside of os_log(). 8002 if (FSType != Sema::FST_OSLog) { 8003 if (FS.isPublic().isSet()) { 8004 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8005 << "public", 8006 getLocationOfByte(FS.isPublic().getPosition()), 8007 /*IsStringLocation*/ false, 8008 getSpecifierRange(startSpecifier, specifierLen)); 8009 } 8010 if (FS.isPrivate().isSet()) { 8011 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8012 << "private", 8013 getLocationOfByte(FS.isPrivate().getPosition()), 8014 /*IsStringLocation*/ false, 8015 getSpecifierRange(startSpecifier, specifierLen)); 8016 } 8017 } 8018 8019 // Check for invalid use of field width 8020 if (!FS.hasValidFieldWidth()) { 8021 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8022 startSpecifier, specifierLen); 8023 } 8024 8025 // Check for invalid use of precision 8026 if (!FS.hasValidPrecision()) { 8027 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8028 startSpecifier, specifierLen); 8029 } 8030 8031 // Precision is mandatory for %P specifier. 8032 if (CS.getKind() == ConversionSpecifier::PArg && 8033 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8034 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8035 getLocationOfByte(startSpecifier), 8036 /*IsStringLocation*/ false, 8037 getSpecifierRange(startSpecifier, specifierLen)); 8038 } 8039 8040 // Check each flag does not conflict with any other component. 8041 if (!FS.hasValidThousandsGroupingPrefix()) 8042 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8043 if (!FS.hasValidLeadingZeros()) 8044 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8045 if (!FS.hasValidPlusPrefix()) 8046 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8047 if (!FS.hasValidSpacePrefix()) 8048 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8049 if (!FS.hasValidAlternativeForm()) 8050 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8051 if (!FS.hasValidLeftJustified()) 8052 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8053 8054 // Check that flags are not ignored by another flag 8055 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8056 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8057 startSpecifier, specifierLen); 8058 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8059 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8060 startSpecifier, specifierLen); 8061 8062 // Check the length modifier is valid with the given conversion specifier. 8063 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8064 S.getLangOpts())) 8065 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8066 diag::warn_format_nonsensical_length); 8067 else if (!FS.hasStandardLengthModifier()) 8068 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8069 else if (!FS.hasStandardLengthConversionCombination()) 8070 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8071 diag::warn_format_non_standard_conversion_spec); 8072 8073 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8074 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8075 8076 // The remaining checks depend on the data arguments. 8077 if (HasVAListArg) 8078 return true; 8079 8080 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8081 return false; 8082 8083 const Expr *Arg = getDataArg(argIndex); 8084 if (!Arg) 8085 return true; 8086 8087 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8088 } 8089 8090 static bool requiresParensToAddCast(const Expr *E) { 8091 // FIXME: We should have a general way to reason about operator 8092 // precedence and whether parens are actually needed here. 8093 // Take care of a few common cases where they aren't. 8094 const Expr *Inside = E->IgnoreImpCasts(); 8095 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8096 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8097 8098 switch (Inside->getStmtClass()) { 8099 case Stmt::ArraySubscriptExprClass: 8100 case Stmt::CallExprClass: 8101 case Stmt::CharacterLiteralClass: 8102 case Stmt::CXXBoolLiteralExprClass: 8103 case Stmt::DeclRefExprClass: 8104 case Stmt::FloatingLiteralClass: 8105 case Stmt::IntegerLiteralClass: 8106 case Stmt::MemberExprClass: 8107 case Stmt::ObjCArrayLiteralClass: 8108 case Stmt::ObjCBoolLiteralExprClass: 8109 case Stmt::ObjCBoxedExprClass: 8110 case Stmt::ObjCDictionaryLiteralClass: 8111 case Stmt::ObjCEncodeExprClass: 8112 case Stmt::ObjCIvarRefExprClass: 8113 case Stmt::ObjCMessageExprClass: 8114 case Stmt::ObjCPropertyRefExprClass: 8115 case Stmt::ObjCStringLiteralClass: 8116 case Stmt::ObjCSubscriptRefExprClass: 8117 case Stmt::ParenExprClass: 8118 case Stmt::StringLiteralClass: 8119 case Stmt::UnaryOperatorClass: 8120 return false; 8121 default: 8122 return true; 8123 } 8124 } 8125 8126 static std::pair<QualType, StringRef> 8127 shouldNotPrintDirectly(const ASTContext &Context, 8128 QualType IntendedTy, 8129 const Expr *E) { 8130 // Use a 'while' to peel off layers of typedefs. 8131 QualType TyTy = IntendedTy; 8132 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8133 StringRef Name = UserTy->getDecl()->getName(); 8134 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8135 .Case("CFIndex", Context.getNSIntegerType()) 8136 .Case("NSInteger", Context.getNSIntegerType()) 8137 .Case("NSUInteger", Context.getNSUIntegerType()) 8138 .Case("SInt32", Context.IntTy) 8139 .Case("UInt32", Context.UnsignedIntTy) 8140 .Default(QualType()); 8141 8142 if (!CastTy.isNull()) 8143 return std::make_pair(CastTy, Name); 8144 8145 TyTy = UserTy->desugar(); 8146 } 8147 8148 // Strip parens if necessary. 8149 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8150 return shouldNotPrintDirectly(Context, 8151 PE->getSubExpr()->getType(), 8152 PE->getSubExpr()); 8153 8154 // If this is a conditional expression, then its result type is constructed 8155 // via usual arithmetic conversions and thus there might be no necessary 8156 // typedef sugar there. Recurse to operands to check for NSInteger & 8157 // Co. usage condition. 8158 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8159 QualType TrueTy, FalseTy; 8160 StringRef TrueName, FalseName; 8161 8162 std::tie(TrueTy, TrueName) = 8163 shouldNotPrintDirectly(Context, 8164 CO->getTrueExpr()->getType(), 8165 CO->getTrueExpr()); 8166 std::tie(FalseTy, FalseName) = 8167 shouldNotPrintDirectly(Context, 8168 CO->getFalseExpr()->getType(), 8169 CO->getFalseExpr()); 8170 8171 if (TrueTy == FalseTy) 8172 return std::make_pair(TrueTy, TrueName); 8173 else if (TrueTy.isNull()) 8174 return std::make_pair(FalseTy, FalseName); 8175 else if (FalseTy.isNull()) 8176 return std::make_pair(TrueTy, TrueName); 8177 } 8178 8179 return std::make_pair(QualType(), StringRef()); 8180 } 8181 8182 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8183 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8184 /// type do not count. 8185 static bool 8186 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8187 QualType From = ICE->getSubExpr()->getType(); 8188 QualType To = ICE->getType(); 8189 // It's an integer promotion if the destination type is the promoted 8190 // source type. 8191 if (ICE->getCastKind() == CK_IntegralCast && 8192 From->isPromotableIntegerType() && 8193 S.Context.getPromotedIntegerType(From) == To) 8194 return true; 8195 // Look through vector types, since we do default argument promotion for 8196 // those in OpenCL. 8197 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8198 From = VecTy->getElementType(); 8199 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8200 To = VecTy->getElementType(); 8201 // It's a floating promotion if the source type is a lower rank. 8202 return ICE->getCastKind() == CK_FloatingCast && 8203 S.Context.getFloatingTypeOrder(From, To) < 0; 8204 } 8205 8206 bool 8207 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8208 const char *StartSpecifier, 8209 unsigned SpecifierLen, 8210 const Expr *E) { 8211 using namespace analyze_format_string; 8212 using namespace analyze_printf; 8213 8214 // Now type check the data expression that matches the 8215 // format specifier. 8216 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8217 if (!AT.isValid()) 8218 return true; 8219 8220 QualType ExprTy = E->getType(); 8221 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8222 ExprTy = TET->getUnderlyingExpr()->getType(); 8223 } 8224 8225 // Diagnose attempts to print a boolean value as a character. Unlike other 8226 // -Wformat diagnostics, this is fine from a type perspective, but it still 8227 // doesn't make sense. 8228 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8229 E->isKnownToHaveBooleanValue()) { 8230 const CharSourceRange &CSR = 8231 getSpecifierRange(StartSpecifier, SpecifierLen); 8232 SmallString<4> FSString; 8233 llvm::raw_svector_ostream os(FSString); 8234 FS.toString(os); 8235 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8236 << FSString, 8237 E->getExprLoc(), false, CSR); 8238 return true; 8239 } 8240 8241 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8242 if (Match == analyze_printf::ArgType::Match) 8243 return true; 8244 8245 // Look through argument promotions for our error message's reported type. 8246 // This includes the integral and floating promotions, but excludes array 8247 // and function pointer decay (seeing that an argument intended to be a 8248 // string has type 'char [6]' is probably more confusing than 'char *') and 8249 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8250 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8251 if (isArithmeticArgumentPromotion(S, ICE)) { 8252 E = ICE->getSubExpr(); 8253 ExprTy = E->getType(); 8254 8255 // Check if we didn't match because of an implicit cast from a 'char' 8256 // or 'short' to an 'int'. This is done because printf is a varargs 8257 // function. 8258 if (ICE->getType() == S.Context.IntTy || 8259 ICE->getType() == S.Context.UnsignedIntTy) { 8260 // All further checking is done on the subexpression 8261 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8262 AT.matchesType(S.Context, ExprTy); 8263 if (ImplicitMatch == analyze_printf::ArgType::Match) 8264 return true; 8265 if (ImplicitMatch == ArgType::NoMatchPedantic || 8266 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8267 Match = ImplicitMatch; 8268 } 8269 } 8270 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8271 // Special case for 'a', which has type 'int' in C. 8272 // Note, however, that we do /not/ want to treat multibyte constants like 8273 // 'MooV' as characters! This form is deprecated but still exists. 8274 if (ExprTy == S.Context.IntTy) 8275 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8276 ExprTy = S.Context.CharTy; 8277 } 8278 8279 // Look through enums to their underlying type. 8280 bool IsEnum = false; 8281 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8282 ExprTy = EnumTy->getDecl()->getIntegerType(); 8283 IsEnum = true; 8284 } 8285 8286 // %C in an Objective-C context prints a unichar, not a wchar_t. 8287 // If the argument is an integer of some kind, believe the %C and suggest 8288 // a cast instead of changing the conversion specifier. 8289 QualType IntendedTy = ExprTy; 8290 if (isObjCContext() && 8291 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8292 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8293 !ExprTy->isCharType()) { 8294 // 'unichar' is defined as a typedef of unsigned short, but we should 8295 // prefer using the typedef if it is visible. 8296 IntendedTy = S.Context.UnsignedShortTy; 8297 8298 // While we are here, check if the value is an IntegerLiteral that happens 8299 // to be within the valid range. 8300 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8301 const llvm::APInt &V = IL->getValue(); 8302 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8303 return true; 8304 } 8305 8306 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8307 Sema::LookupOrdinaryName); 8308 if (S.LookupName(Result, S.getCurScope())) { 8309 NamedDecl *ND = Result.getFoundDecl(); 8310 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8311 if (TD->getUnderlyingType() == IntendedTy) 8312 IntendedTy = S.Context.getTypedefType(TD); 8313 } 8314 } 8315 } 8316 8317 // Special-case some of Darwin's platform-independence types by suggesting 8318 // casts to primitive types that are known to be large enough. 8319 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8320 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8321 QualType CastTy; 8322 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8323 if (!CastTy.isNull()) { 8324 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8325 // (long in ASTContext). Only complain to pedants. 8326 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8327 (AT.isSizeT() || AT.isPtrdiffT()) && 8328 AT.matchesType(S.Context, CastTy)) 8329 Match = ArgType::NoMatchPedantic; 8330 IntendedTy = CastTy; 8331 ShouldNotPrintDirectly = true; 8332 } 8333 } 8334 8335 // We may be able to offer a FixItHint if it is a supported type. 8336 PrintfSpecifier fixedFS = FS; 8337 bool Success = 8338 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8339 8340 if (Success) { 8341 // Get the fix string from the fixed format specifier 8342 SmallString<16> buf; 8343 llvm::raw_svector_ostream os(buf); 8344 fixedFS.toString(os); 8345 8346 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8347 8348 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8349 unsigned Diag; 8350 switch (Match) { 8351 case ArgType::Match: llvm_unreachable("expected non-matching"); 8352 case ArgType::NoMatchPedantic: 8353 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8354 break; 8355 case ArgType::NoMatchTypeConfusion: 8356 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8357 break; 8358 case ArgType::NoMatch: 8359 Diag = diag::warn_format_conversion_argument_type_mismatch; 8360 break; 8361 } 8362 8363 // In this case, the specifier is wrong and should be changed to match 8364 // the argument. 8365 EmitFormatDiagnostic(S.PDiag(Diag) 8366 << AT.getRepresentativeTypeName(S.Context) 8367 << IntendedTy << IsEnum << E->getSourceRange(), 8368 E->getBeginLoc(), 8369 /*IsStringLocation*/ false, SpecRange, 8370 FixItHint::CreateReplacement(SpecRange, os.str())); 8371 } else { 8372 // The canonical type for formatting this value is different from the 8373 // actual type of the expression. (This occurs, for example, with Darwin's 8374 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8375 // should be printed as 'long' for 64-bit compatibility.) 8376 // Rather than emitting a normal format/argument mismatch, we want to 8377 // add a cast to the recommended type (and correct the format string 8378 // if necessary). 8379 SmallString<16> CastBuf; 8380 llvm::raw_svector_ostream CastFix(CastBuf); 8381 CastFix << "("; 8382 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8383 CastFix << ")"; 8384 8385 SmallVector<FixItHint,4> Hints; 8386 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8387 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8388 8389 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8390 // If there's already a cast present, just replace it. 8391 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8392 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8393 8394 } else if (!requiresParensToAddCast(E)) { 8395 // If the expression has high enough precedence, 8396 // just write the C-style cast. 8397 Hints.push_back( 8398 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8399 } else { 8400 // Otherwise, add parens around the expression as well as the cast. 8401 CastFix << "("; 8402 Hints.push_back( 8403 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8404 8405 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8406 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8407 } 8408 8409 if (ShouldNotPrintDirectly) { 8410 // The expression has a type that should not be printed directly. 8411 // We extract the name from the typedef because we don't want to show 8412 // the underlying type in the diagnostic. 8413 StringRef Name; 8414 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8415 Name = TypedefTy->getDecl()->getName(); 8416 else 8417 Name = CastTyName; 8418 unsigned Diag = Match == ArgType::NoMatchPedantic 8419 ? diag::warn_format_argument_needs_cast_pedantic 8420 : diag::warn_format_argument_needs_cast; 8421 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8422 << E->getSourceRange(), 8423 E->getBeginLoc(), /*IsStringLocation=*/false, 8424 SpecRange, Hints); 8425 } else { 8426 // In this case, the expression could be printed using a different 8427 // specifier, but we've decided that the specifier is probably correct 8428 // and we should cast instead. Just use the normal warning message. 8429 EmitFormatDiagnostic( 8430 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8431 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8432 << E->getSourceRange(), 8433 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8434 } 8435 } 8436 } else { 8437 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8438 SpecifierLen); 8439 // Since the warning for passing non-POD types to variadic functions 8440 // was deferred until now, we emit a warning for non-POD 8441 // arguments here. 8442 switch (S.isValidVarArgType(ExprTy)) { 8443 case Sema::VAK_Valid: 8444 case Sema::VAK_ValidInCXX11: { 8445 unsigned Diag; 8446 switch (Match) { 8447 case ArgType::Match: llvm_unreachable("expected non-matching"); 8448 case ArgType::NoMatchPedantic: 8449 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8450 break; 8451 case ArgType::NoMatchTypeConfusion: 8452 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8453 break; 8454 case ArgType::NoMatch: 8455 Diag = diag::warn_format_conversion_argument_type_mismatch; 8456 break; 8457 } 8458 8459 EmitFormatDiagnostic( 8460 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8461 << IsEnum << CSR << E->getSourceRange(), 8462 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8463 break; 8464 } 8465 case Sema::VAK_Undefined: 8466 case Sema::VAK_MSVCUndefined: 8467 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8468 << S.getLangOpts().CPlusPlus11 << ExprTy 8469 << CallType 8470 << AT.getRepresentativeTypeName(S.Context) << CSR 8471 << E->getSourceRange(), 8472 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8473 checkForCStrMembers(AT, E); 8474 break; 8475 8476 case Sema::VAK_Invalid: 8477 if (ExprTy->isObjCObjectType()) 8478 EmitFormatDiagnostic( 8479 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8480 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8481 << AT.getRepresentativeTypeName(S.Context) << CSR 8482 << E->getSourceRange(), 8483 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8484 else 8485 // FIXME: If this is an initializer list, suggest removing the braces 8486 // or inserting a cast to the target type. 8487 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8488 << isa<InitListExpr>(E) << ExprTy << CallType 8489 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8490 break; 8491 } 8492 8493 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8494 "format string specifier index out of range"); 8495 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8496 } 8497 8498 return true; 8499 } 8500 8501 //===--- CHECK: Scanf format string checking ------------------------------===// 8502 8503 namespace { 8504 8505 class CheckScanfHandler : public CheckFormatHandler { 8506 public: 8507 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8508 const Expr *origFormatExpr, Sema::FormatStringType type, 8509 unsigned firstDataArg, unsigned numDataArgs, 8510 const char *beg, bool hasVAListArg, 8511 ArrayRef<const Expr *> Args, unsigned formatIdx, 8512 bool inFunctionCall, Sema::VariadicCallType CallType, 8513 llvm::SmallBitVector &CheckedVarArgs, 8514 UncoveredArgHandler &UncoveredArg) 8515 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8516 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8517 inFunctionCall, CallType, CheckedVarArgs, 8518 UncoveredArg) {} 8519 8520 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8521 const char *startSpecifier, 8522 unsigned specifierLen) override; 8523 8524 bool HandleInvalidScanfConversionSpecifier( 8525 const analyze_scanf::ScanfSpecifier &FS, 8526 const char *startSpecifier, 8527 unsigned specifierLen) override; 8528 8529 void HandleIncompleteScanList(const char *start, const char *end) override; 8530 }; 8531 8532 } // namespace 8533 8534 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8535 const char *end) { 8536 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8537 getLocationOfByte(end), /*IsStringLocation*/true, 8538 getSpecifierRange(start, end - start)); 8539 } 8540 8541 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8542 const analyze_scanf::ScanfSpecifier &FS, 8543 const char *startSpecifier, 8544 unsigned specifierLen) { 8545 const analyze_scanf::ScanfConversionSpecifier &CS = 8546 FS.getConversionSpecifier(); 8547 8548 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8549 getLocationOfByte(CS.getStart()), 8550 startSpecifier, specifierLen, 8551 CS.getStart(), CS.getLength()); 8552 } 8553 8554 bool CheckScanfHandler::HandleScanfSpecifier( 8555 const analyze_scanf::ScanfSpecifier &FS, 8556 const char *startSpecifier, 8557 unsigned specifierLen) { 8558 using namespace analyze_scanf; 8559 using namespace analyze_format_string; 8560 8561 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8562 8563 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8564 // be used to decide if we are using positional arguments consistently. 8565 if (FS.consumesDataArgument()) { 8566 if (atFirstArg) { 8567 atFirstArg = false; 8568 usesPositionalArgs = FS.usesPositionalArg(); 8569 } 8570 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8571 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8572 startSpecifier, specifierLen); 8573 return false; 8574 } 8575 } 8576 8577 // Check if the field with is non-zero. 8578 const OptionalAmount &Amt = FS.getFieldWidth(); 8579 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8580 if (Amt.getConstantAmount() == 0) { 8581 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8582 Amt.getConstantLength()); 8583 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8584 getLocationOfByte(Amt.getStart()), 8585 /*IsStringLocation*/true, R, 8586 FixItHint::CreateRemoval(R)); 8587 } 8588 } 8589 8590 if (!FS.consumesDataArgument()) { 8591 // FIXME: Technically specifying a precision or field width here 8592 // makes no sense. Worth issuing a warning at some point. 8593 return true; 8594 } 8595 8596 // Consume the argument. 8597 unsigned argIndex = FS.getArgIndex(); 8598 if (argIndex < NumDataArgs) { 8599 // The check to see if the argIndex is valid will come later. 8600 // We set the bit here because we may exit early from this 8601 // function if we encounter some other error. 8602 CoveredArgs.set(argIndex); 8603 } 8604 8605 // Check the length modifier is valid with the given conversion specifier. 8606 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8607 S.getLangOpts())) 8608 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8609 diag::warn_format_nonsensical_length); 8610 else if (!FS.hasStandardLengthModifier()) 8611 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8612 else if (!FS.hasStandardLengthConversionCombination()) 8613 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8614 diag::warn_format_non_standard_conversion_spec); 8615 8616 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8617 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8618 8619 // The remaining checks depend on the data arguments. 8620 if (HasVAListArg) 8621 return true; 8622 8623 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8624 return false; 8625 8626 // Check that the argument type matches the format specifier. 8627 const Expr *Ex = getDataArg(argIndex); 8628 if (!Ex) 8629 return true; 8630 8631 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8632 8633 if (!AT.isValid()) { 8634 return true; 8635 } 8636 8637 analyze_format_string::ArgType::MatchKind Match = 8638 AT.matchesType(S.Context, Ex->getType()); 8639 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8640 if (Match == analyze_format_string::ArgType::Match) 8641 return true; 8642 8643 ScanfSpecifier fixedFS = FS; 8644 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8645 S.getLangOpts(), S.Context); 8646 8647 unsigned Diag = 8648 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8649 : diag::warn_format_conversion_argument_type_mismatch; 8650 8651 if (Success) { 8652 // Get the fix string from the fixed format specifier. 8653 SmallString<128> buf; 8654 llvm::raw_svector_ostream os(buf); 8655 fixedFS.toString(os); 8656 8657 EmitFormatDiagnostic( 8658 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8659 << Ex->getType() << false << Ex->getSourceRange(), 8660 Ex->getBeginLoc(), 8661 /*IsStringLocation*/ false, 8662 getSpecifierRange(startSpecifier, specifierLen), 8663 FixItHint::CreateReplacement( 8664 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8665 } else { 8666 EmitFormatDiagnostic(S.PDiag(Diag) 8667 << AT.getRepresentativeTypeName(S.Context) 8668 << Ex->getType() << false << Ex->getSourceRange(), 8669 Ex->getBeginLoc(), 8670 /*IsStringLocation*/ false, 8671 getSpecifierRange(startSpecifier, specifierLen)); 8672 } 8673 8674 return true; 8675 } 8676 8677 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8678 const Expr *OrigFormatExpr, 8679 ArrayRef<const Expr *> Args, 8680 bool HasVAListArg, unsigned format_idx, 8681 unsigned firstDataArg, 8682 Sema::FormatStringType Type, 8683 bool inFunctionCall, 8684 Sema::VariadicCallType CallType, 8685 llvm::SmallBitVector &CheckedVarArgs, 8686 UncoveredArgHandler &UncoveredArg, 8687 bool IgnoreStringsWithoutSpecifiers) { 8688 // CHECK: is the format string a wide literal? 8689 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8690 CheckFormatHandler::EmitFormatDiagnostic( 8691 S, inFunctionCall, Args[format_idx], 8692 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8693 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8694 return; 8695 } 8696 8697 // Str - The format string. NOTE: this is NOT null-terminated! 8698 StringRef StrRef = FExpr->getString(); 8699 const char *Str = StrRef.data(); 8700 // Account for cases where the string literal is truncated in a declaration. 8701 const ConstantArrayType *T = 8702 S.Context.getAsConstantArrayType(FExpr->getType()); 8703 assert(T && "String literal not of constant array type!"); 8704 size_t TypeSize = T->getSize().getZExtValue(); 8705 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8706 const unsigned numDataArgs = Args.size() - firstDataArg; 8707 8708 if (IgnoreStringsWithoutSpecifiers && 8709 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8710 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8711 return; 8712 8713 // Emit a warning if the string literal is truncated and does not contain an 8714 // embedded null character. 8715 if (TypeSize <= StrRef.size() && 8716 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8717 CheckFormatHandler::EmitFormatDiagnostic( 8718 S, inFunctionCall, Args[format_idx], 8719 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8720 FExpr->getBeginLoc(), 8721 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8722 return; 8723 } 8724 8725 // CHECK: empty format string? 8726 if (StrLen == 0 && numDataArgs > 0) { 8727 CheckFormatHandler::EmitFormatDiagnostic( 8728 S, inFunctionCall, Args[format_idx], 8729 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8730 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8731 return; 8732 } 8733 8734 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8735 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8736 Type == Sema::FST_OSTrace) { 8737 CheckPrintfHandler H( 8738 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8739 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8740 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8741 CheckedVarArgs, UncoveredArg); 8742 8743 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8744 S.getLangOpts(), 8745 S.Context.getTargetInfo(), 8746 Type == Sema::FST_FreeBSDKPrintf)) 8747 H.DoneProcessing(); 8748 } else if (Type == Sema::FST_Scanf) { 8749 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8750 numDataArgs, Str, HasVAListArg, Args, format_idx, 8751 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8752 8753 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8754 S.getLangOpts(), 8755 S.Context.getTargetInfo())) 8756 H.DoneProcessing(); 8757 } // TODO: handle other formats 8758 } 8759 8760 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8761 // Str - The format string. NOTE: this is NOT null-terminated! 8762 StringRef StrRef = FExpr->getString(); 8763 const char *Str = StrRef.data(); 8764 // Account for cases where the string literal is truncated in a declaration. 8765 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8766 assert(T && "String literal not of constant array type!"); 8767 size_t TypeSize = T->getSize().getZExtValue(); 8768 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8769 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8770 getLangOpts(), 8771 Context.getTargetInfo()); 8772 } 8773 8774 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8775 8776 // Returns the related absolute value function that is larger, of 0 if one 8777 // does not exist. 8778 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8779 switch (AbsFunction) { 8780 default: 8781 return 0; 8782 8783 case Builtin::BI__builtin_abs: 8784 return Builtin::BI__builtin_labs; 8785 case Builtin::BI__builtin_labs: 8786 return Builtin::BI__builtin_llabs; 8787 case Builtin::BI__builtin_llabs: 8788 return 0; 8789 8790 case Builtin::BI__builtin_fabsf: 8791 return Builtin::BI__builtin_fabs; 8792 case Builtin::BI__builtin_fabs: 8793 return Builtin::BI__builtin_fabsl; 8794 case Builtin::BI__builtin_fabsl: 8795 return 0; 8796 8797 case Builtin::BI__builtin_cabsf: 8798 return Builtin::BI__builtin_cabs; 8799 case Builtin::BI__builtin_cabs: 8800 return Builtin::BI__builtin_cabsl; 8801 case Builtin::BI__builtin_cabsl: 8802 return 0; 8803 8804 case Builtin::BIabs: 8805 return Builtin::BIlabs; 8806 case Builtin::BIlabs: 8807 return Builtin::BIllabs; 8808 case Builtin::BIllabs: 8809 return 0; 8810 8811 case Builtin::BIfabsf: 8812 return Builtin::BIfabs; 8813 case Builtin::BIfabs: 8814 return Builtin::BIfabsl; 8815 case Builtin::BIfabsl: 8816 return 0; 8817 8818 case Builtin::BIcabsf: 8819 return Builtin::BIcabs; 8820 case Builtin::BIcabs: 8821 return Builtin::BIcabsl; 8822 case Builtin::BIcabsl: 8823 return 0; 8824 } 8825 } 8826 8827 // Returns the argument type of the absolute value function. 8828 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8829 unsigned AbsType) { 8830 if (AbsType == 0) 8831 return QualType(); 8832 8833 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8834 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8835 if (Error != ASTContext::GE_None) 8836 return QualType(); 8837 8838 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8839 if (!FT) 8840 return QualType(); 8841 8842 if (FT->getNumParams() != 1) 8843 return QualType(); 8844 8845 return FT->getParamType(0); 8846 } 8847 8848 // Returns the best absolute value function, or zero, based on type and 8849 // current absolute value function. 8850 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8851 unsigned AbsFunctionKind) { 8852 unsigned BestKind = 0; 8853 uint64_t ArgSize = Context.getTypeSize(ArgType); 8854 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8855 Kind = getLargerAbsoluteValueFunction(Kind)) { 8856 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8857 if (Context.getTypeSize(ParamType) >= ArgSize) { 8858 if (BestKind == 0) 8859 BestKind = Kind; 8860 else if (Context.hasSameType(ParamType, ArgType)) { 8861 BestKind = Kind; 8862 break; 8863 } 8864 } 8865 } 8866 return BestKind; 8867 } 8868 8869 enum AbsoluteValueKind { 8870 AVK_Integer, 8871 AVK_Floating, 8872 AVK_Complex 8873 }; 8874 8875 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8876 if (T->isIntegralOrEnumerationType()) 8877 return AVK_Integer; 8878 if (T->isRealFloatingType()) 8879 return AVK_Floating; 8880 if (T->isAnyComplexType()) 8881 return AVK_Complex; 8882 8883 llvm_unreachable("Type not integer, floating, or complex"); 8884 } 8885 8886 // Changes the absolute value function to a different type. Preserves whether 8887 // the function is a builtin. 8888 static unsigned changeAbsFunction(unsigned AbsKind, 8889 AbsoluteValueKind ValueKind) { 8890 switch (ValueKind) { 8891 case AVK_Integer: 8892 switch (AbsKind) { 8893 default: 8894 return 0; 8895 case Builtin::BI__builtin_fabsf: 8896 case Builtin::BI__builtin_fabs: 8897 case Builtin::BI__builtin_fabsl: 8898 case Builtin::BI__builtin_cabsf: 8899 case Builtin::BI__builtin_cabs: 8900 case Builtin::BI__builtin_cabsl: 8901 return Builtin::BI__builtin_abs; 8902 case Builtin::BIfabsf: 8903 case Builtin::BIfabs: 8904 case Builtin::BIfabsl: 8905 case Builtin::BIcabsf: 8906 case Builtin::BIcabs: 8907 case Builtin::BIcabsl: 8908 return Builtin::BIabs; 8909 } 8910 case AVK_Floating: 8911 switch (AbsKind) { 8912 default: 8913 return 0; 8914 case Builtin::BI__builtin_abs: 8915 case Builtin::BI__builtin_labs: 8916 case Builtin::BI__builtin_llabs: 8917 case Builtin::BI__builtin_cabsf: 8918 case Builtin::BI__builtin_cabs: 8919 case Builtin::BI__builtin_cabsl: 8920 return Builtin::BI__builtin_fabsf; 8921 case Builtin::BIabs: 8922 case Builtin::BIlabs: 8923 case Builtin::BIllabs: 8924 case Builtin::BIcabsf: 8925 case Builtin::BIcabs: 8926 case Builtin::BIcabsl: 8927 return Builtin::BIfabsf; 8928 } 8929 case AVK_Complex: 8930 switch (AbsKind) { 8931 default: 8932 return 0; 8933 case Builtin::BI__builtin_abs: 8934 case Builtin::BI__builtin_labs: 8935 case Builtin::BI__builtin_llabs: 8936 case Builtin::BI__builtin_fabsf: 8937 case Builtin::BI__builtin_fabs: 8938 case Builtin::BI__builtin_fabsl: 8939 return Builtin::BI__builtin_cabsf; 8940 case Builtin::BIabs: 8941 case Builtin::BIlabs: 8942 case Builtin::BIllabs: 8943 case Builtin::BIfabsf: 8944 case Builtin::BIfabs: 8945 case Builtin::BIfabsl: 8946 return Builtin::BIcabsf; 8947 } 8948 } 8949 llvm_unreachable("Unable to convert function"); 8950 } 8951 8952 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8953 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8954 if (!FnInfo) 8955 return 0; 8956 8957 switch (FDecl->getBuiltinID()) { 8958 default: 8959 return 0; 8960 case Builtin::BI__builtin_abs: 8961 case Builtin::BI__builtin_fabs: 8962 case Builtin::BI__builtin_fabsf: 8963 case Builtin::BI__builtin_fabsl: 8964 case Builtin::BI__builtin_labs: 8965 case Builtin::BI__builtin_llabs: 8966 case Builtin::BI__builtin_cabs: 8967 case Builtin::BI__builtin_cabsf: 8968 case Builtin::BI__builtin_cabsl: 8969 case Builtin::BIabs: 8970 case Builtin::BIlabs: 8971 case Builtin::BIllabs: 8972 case Builtin::BIfabs: 8973 case Builtin::BIfabsf: 8974 case Builtin::BIfabsl: 8975 case Builtin::BIcabs: 8976 case Builtin::BIcabsf: 8977 case Builtin::BIcabsl: 8978 return FDecl->getBuiltinID(); 8979 } 8980 llvm_unreachable("Unknown Builtin type"); 8981 } 8982 8983 // If the replacement is valid, emit a note with replacement function. 8984 // Additionally, suggest including the proper header if not already included. 8985 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8986 unsigned AbsKind, QualType ArgType) { 8987 bool EmitHeaderHint = true; 8988 const char *HeaderName = nullptr; 8989 const char *FunctionName = nullptr; 8990 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8991 FunctionName = "std::abs"; 8992 if (ArgType->isIntegralOrEnumerationType()) { 8993 HeaderName = "cstdlib"; 8994 } else if (ArgType->isRealFloatingType()) { 8995 HeaderName = "cmath"; 8996 } else { 8997 llvm_unreachable("Invalid Type"); 8998 } 8999 9000 // Lookup all std::abs 9001 if (NamespaceDecl *Std = S.getStdNamespace()) { 9002 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9003 R.suppressDiagnostics(); 9004 S.LookupQualifiedName(R, Std); 9005 9006 for (const auto *I : R) { 9007 const FunctionDecl *FDecl = nullptr; 9008 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9009 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9010 } else { 9011 FDecl = dyn_cast<FunctionDecl>(I); 9012 } 9013 if (!FDecl) 9014 continue; 9015 9016 // Found std::abs(), check that they are the right ones. 9017 if (FDecl->getNumParams() != 1) 9018 continue; 9019 9020 // Check that the parameter type can handle the argument. 9021 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9022 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9023 S.Context.getTypeSize(ArgType) <= 9024 S.Context.getTypeSize(ParamType)) { 9025 // Found a function, don't need the header hint. 9026 EmitHeaderHint = false; 9027 break; 9028 } 9029 } 9030 } 9031 } else { 9032 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9033 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9034 9035 if (HeaderName) { 9036 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9037 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9038 R.suppressDiagnostics(); 9039 S.LookupName(R, S.getCurScope()); 9040 9041 if (R.isSingleResult()) { 9042 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9043 if (FD && FD->getBuiltinID() == AbsKind) { 9044 EmitHeaderHint = false; 9045 } else { 9046 return; 9047 } 9048 } else if (!R.empty()) { 9049 return; 9050 } 9051 } 9052 } 9053 9054 S.Diag(Loc, diag::note_replace_abs_function) 9055 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9056 9057 if (!HeaderName) 9058 return; 9059 9060 if (!EmitHeaderHint) 9061 return; 9062 9063 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9064 << FunctionName; 9065 } 9066 9067 template <std::size_t StrLen> 9068 static bool IsStdFunction(const FunctionDecl *FDecl, 9069 const char (&Str)[StrLen]) { 9070 if (!FDecl) 9071 return false; 9072 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9073 return false; 9074 if (!FDecl->isInStdNamespace()) 9075 return false; 9076 9077 return true; 9078 } 9079 9080 // Warn when using the wrong abs() function. 9081 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9082 const FunctionDecl *FDecl) { 9083 if (Call->getNumArgs() != 1) 9084 return; 9085 9086 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9087 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9088 if (AbsKind == 0 && !IsStdAbs) 9089 return; 9090 9091 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9092 QualType ParamType = Call->getArg(0)->getType(); 9093 9094 // Unsigned types cannot be negative. Suggest removing the absolute value 9095 // function call. 9096 if (ArgType->isUnsignedIntegerType()) { 9097 const char *FunctionName = 9098 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9099 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9100 Diag(Call->getExprLoc(), diag::note_remove_abs) 9101 << FunctionName 9102 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9103 return; 9104 } 9105 9106 // Taking the absolute value of a pointer is very suspicious, they probably 9107 // wanted to index into an array, dereference a pointer, call a function, etc. 9108 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9109 unsigned DiagType = 0; 9110 if (ArgType->isFunctionType()) 9111 DiagType = 1; 9112 else if (ArgType->isArrayType()) 9113 DiagType = 2; 9114 9115 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9116 return; 9117 } 9118 9119 // std::abs has overloads which prevent most of the absolute value problems 9120 // from occurring. 9121 if (IsStdAbs) 9122 return; 9123 9124 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9125 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9126 9127 // The argument and parameter are the same kind. Check if they are the right 9128 // size. 9129 if (ArgValueKind == ParamValueKind) { 9130 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9131 return; 9132 9133 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9134 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9135 << FDecl << ArgType << ParamType; 9136 9137 if (NewAbsKind == 0) 9138 return; 9139 9140 emitReplacement(*this, Call->getExprLoc(), 9141 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9142 return; 9143 } 9144 9145 // ArgValueKind != ParamValueKind 9146 // The wrong type of absolute value function was used. Attempt to find the 9147 // proper one. 9148 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9149 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9150 if (NewAbsKind == 0) 9151 return; 9152 9153 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9154 << FDecl << ParamValueKind << ArgValueKind; 9155 9156 emitReplacement(*this, Call->getExprLoc(), 9157 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9158 } 9159 9160 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9161 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9162 const FunctionDecl *FDecl) { 9163 if (!Call || !FDecl) return; 9164 9165 // Ignore template specializations and macros. 9166 if (inTemplateInstantiation()) return; 9167 if (Call->getExprLoc().isMacroID()) return; 9168 9169 // Only care about the one template argument, two function parameter std::max 9170 if (Call->getNumArgs() != 2) return; 9171 if (!IsStdFunction(FDecl, "max")) return; 9172 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9173 if (!ArgList) return; 9174 if (ArgList->size() != 1) return; 9175 9176 // Check that template type argument is unsigned integer. 9177 const auto& TA = ArgList->get(0); 9178 if (TA.getKind() != TemplateArgument::Type) return; 9179 QualType ArgType = TA.getAsType(); 9180 if (!ArgType->isUnsignedIntegerType()) return; 9181 9182 // See if either argument is a literal zero. 9183 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9184 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9185 if (!MTE) return false; 9186 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9187 if (!Num) return false; 9188 if (Num->getValue() != 0) return false; 9189 return true; 9190 }; 9191 9192 const Expr *FirstArg = Call->getArg(0); 9193 const Expr *SecondArg = Call->getArg(1); 9194 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9195 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9196 9197 // Only warn when exactly one argument is zero. 9198 if (IsFirstArgZero == IsSecondArgZero) return; 9199 9200 SourceRange FirstRange = FirstArg->getSourceRange(); 9201 SourceRange SecondRange = SecondArg->getSourceRange(); 9202 9203 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9204 9205 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9206 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9207 9208 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9209 SourceRange RemovalRange; 9210 if (IsFirstArgZero) { 9211 RemovalRange = SourceRange(FirstRange.getBegin(), 9212 SecondRange.getBegin().getLocWithOffset(-1)); 9213 } else { 9214 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9215 SecondRange.getEnd()); 9216 } 9217 9218 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9219 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9220 << FixItHint::CreateRemoval(RemovalRange); 9221 } 9222 9223 //===--- CHECK: Standard memory functions ---------------------------------===// 9224 9225 /// Takes the expression passed to the size_t parameter of functions 9226 /// such as memcmp, strncat, etc and warns if it's a comparison. 9227 /// 9228 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9229 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9230 IdentifierInfo *FnName, 9231 SourceLocation FnLoc, 9232 SourceLocation RParenLoc) { 9233 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9234 if (!Size) 9235 return false; 9236 9237 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9238 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9239 return false; 9240 9241 SourceRange SizeRange = Size->getSourceRange(); 9242 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9243 << SizeRange << FnName; 9244 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9245 << FnName 9246 << FixItHint::CreateInsertion( 9247 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9248 << FixItHint::CreateRemoval(RParenLoc); 9249 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9250 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9251 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9252 ")"); 9253 9254 return true; 9255 } 9256 9257 /// Determine whether the given type is or contains a dynamic class type 9258 /// (e.g., whether it has a vtable). 9259 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9260 bool &IsContained) { 9261 // Look through array types while ignoring qualifiers. 9262 const Type *Ty = T->getBaseElementTypeUnsafe(); 9263 IsContained = false; 9264 9265 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9266 RD = RD ? RD->getDefinition() : nullptr; 9267 if (!RD || RD->isInvalidDecl()) 9268 return nullptr; 9269 9270 if (RD->isDynamicClass()) 9271 return RD; 9272 9273 // Check all the fields. If any bases were dynamic, the class is dynamic. 9274 // It's impossible for a class to transitively contain itself by value, so 9275 // infinite recursion is impossible. 9276 for (auto *FD : RD->fields()) { 9277 bool SubContained; 9278 if (const CXXRecordDecl *ContainedRD = 9279 getContainedDynamicClass(FD->getType(), SubContained)) { 9280 IsContained = true; 9281 return ContainedRD; 9282 } 9283 } 9284 9285 return nullptr; 9286 } 9287 9288 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9289 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9290 if (Unary->getKind() == UETT_SizeOf) 9291 return Unary; 9292 return nullptr; 9293 } 9294 9295 /// If E is a sizeof expression, returns its argument expression, 9296 /// otherwise returns NULL. 9297 static const Expr *getSizeOfExprArg(const Expr *E) { 9298 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9299 if (!SizeOf->isArgumentType()) 9300 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9301 return nullptr; 9302 } 9303 9304 /// If E is a sizeof expression, returns its argument type. 9305 static QualType getSizeOfArgType(const Expr *E) { 9306 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9307 return SizeOf->getTypeOfArgument(); 9308 return QualType(); 9309 } 9310 9311 namespace { 9312 9313 struct SearchNonTrivialToInitializeField 9314 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9315 using Super = 9316 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9317 9318 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9319 9320 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9321 SourceLocation SL) { 9322 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9323 asDerived().visitArray(PDIK, AT, SL); 9324 return; 9325 } 9326 9327 Super::visitWithKind(PDIK, FT, SL); 9328 } 9329 9330 void visitARCStrong(QualType FT, SourceLocation SL) { 9331 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9332 } 9333 void visitARCWeak(QualType FT, SourceLocation SL) { 9334 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9335 } 9336 void visitStruct(QualType FT, SourceLocation SL) { 9337 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9338 visit(FD->getType(), FD->getLocation()); 9339 } 9340 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9341 const ArrayType *AT, SourceLocation SL) { 9342 visit(getContext().getBaseElementType(AT), SL); 9343 } 9344 void visitTrivial(QualType FT, SourceLocation SL) {} 9345 9346 static void diag(QualType RT, const Expr *E, Sema &S) { 9347 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9348 } 9349 9350 ASTContext &getContext() { return S.getASTContext(); } 9351 9352 const Expr *E; 9353 Sema &S; 9354 }; 9355 9356 struct SearchNonTrivialToCopyField 9357 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9358 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9359 9360 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9361 9362 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9363 SourceLocation SL) { 9364 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9365 asDerived().visitArray(PCK, AT, SL); 9366 return; 9367 } 9368 9369 Super::visitWithKind(PCK, FT, SL); 9370 } 9371 9372 void visitARCStrong(QualType FT, SourceLocation SL) { 9373 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9374 } 9375 void visitARCWeak(QualType FT, SourceLocation SL) { 9376 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9377 } 9378 void visitStruct(QualType FT, SourceLocation SL) { 9379 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9380 visit(FD->getType(), FD->getLocation()); 9381 } 9382 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9383 SourceLocation SL) { 9384 visit(getContext().getBaseElementType(AT), SL); 9385 } 9386 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9387 SourceLocation SL) {} 9388 void visitTrivial(QualType FT, SourceLocation SL) {} 9389 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9390 9391 static void diag(QualType RT, const Expr *E, Sema &S) { 9392 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9393 } 9394 9395 ASTContext &getContext() { return S.getASTContext(); } 9396 9397 const Expr *E; 9398 Sema &S; 9399 }; 9400 9401 } 9402 9403 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9404 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9405 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9406 9407 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9408 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9409 return false; 9410 9411 return doesExprLikelyComputeSize(BO->getLHS()) || 9412 doesExprLikelyComputeSize(BO->getRHS()); 9413 } 9414 9415 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9416 } 9417 9418 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9419 /// 9420 /// \code 9421 /// #define MACRO 0 9422 /// foo(MACRO); 9423 /// foo(0); 9424 /// \endcode 9425 /// 9426 /// This should return true for the first call to foo, but not for the second 9427 /// (regardless of whether foo is a macro or function). 9428 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9429 SourceLocation CallLoc, 9430 SourceLocation ArgLoc) { 9431 if (!CallLoc.isMacroID()) 9432 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9433 9434 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9435 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9436 } 9437 9438 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9439 /// last two arguments transposed. 9440 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9441 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9442 return; 9443 9444 const Expr *SizeArg = 9445 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9446 9447 auto isLiteralZero = [](const Expr *E) { 9448 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9449 }; 9450 9451 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9452 SourceLocation CallLoc = Call->getRParenLoc(); 9453 SourceManager &SM = S.getSourceManager(); 9454 if (isLiteralZero(SizeArg) && 9455 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9456 9457 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9458 9459 // Some platforms #define bzero to __builtin_memset. See if this is the 9460 // case, and if so, emit a better diagnostic. 9461 if (BId == Builtin::BIbzero || 9462 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9463 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9464 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9465 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9466 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9467 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9468 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9469 } 9470 return; 9471 } 9472 9473 // If the second argument to a memset is a sizeof expression and the third 9474 // isn't, this is also likely an error. This should catch 9475 // 'memset(buf, sizeof(buf), 0xff)'. 9476 if (BId == Builtin::BImemset && 9477 doesExprLikelyComputeSize(Call->getArg(1)) && 9478 !doesExprLikelyComputeSize(Call->getArg(2))) { 9479 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9480 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9481 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9482 return; 9483 } 9484 } 9485 9486 /// Check for dangerous or invalid arguments to memset(). 9487 /// 9488 /// This issues warnings on known problematic, dangerous or unspecified 9489 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9490 /// function calls. 9491 /// 9492 /// \param Call The call expression to diagnose. 9493 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9494 unsigned BId, 9495 IdentifierInfo *FnName) { 9496 assert(BId != 0); 9497 9498 // It is possible to have a non-standard definition of memset. Validate 9499 // we have enough arguments, and if not, abort further checking. 9500 unsigned ExpectedNumArgs = 9501 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9502 if (Call->getNumArgs() < ExpectedNumArgs) 9503 return; 9504 9505 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9506 BId == Builtin::BIstrndup ? 1 : 2); 9507 unsigned LenArg = 9508 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9509 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9510 9511 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9512 Call->getBeginLoc(), Call->getRParenLoc())) 9513 return; 9514 9515 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9516 CheckMemaccessSize(*this, BId, Call); 9517 9518 // We have special checking when the length is a sizeof expression. 9519 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9520 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9521 llvm::FoldingSetNodeID SizeOfArgID; 9522 9523 // Although widely used, 'bzero' is not a standard function. Be more strict 9524 // with the argument types before allowing diagnostics and only allow the 9525 // form bzero(ptr, sizeof(...)). 9526 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9527 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9528 return; 9529 9530 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9531 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9532 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9533 9534 QualType DestTy = Dest->getType(); 9535 QualType PointeeTy; 9536 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9537 PointeeTy = DestPtrTy->getPointeeType(); 9538 9539 // Never warn about void type pointers. This can be used to suppress 9540 // false positives. 9541 if (PointeeTy->isVoidType()) 9542 continue; 9543 9544 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9545 // actually comparing the expressions for equality. Because computing the 9546 // expression IDs can be expensive, we only do this if the diagnostic is 9547 // enabled. 9548 if (SizeOfArg && 9549 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9550 SizeOfArg->getExprLoc())) { 9551 // We only compute IDs for expressions if the warning is enabled, and 9552 // cache the sizeof arg's ID. 9553 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9554 SizeOfArg->Profile(SizeOfArgID, Context, true); 9555 llvm::FoldingSetNodeID DestID; 9556 Dest->Profile(DestID, Context, true); 9557 if (DestID == SizeOfArgID) { 9558 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9559 // over sizeof(src) as well. 9560 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9561 StringRef ReadableName = FnName->getName(); 9562 9563 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9564 if (UnaryOp->getOpcode() == UO_AddrOf) 9565 ActionIdx = 1; // If its an address-of operator, just remove it. 9566 if (!PointeeTy->isIncompleteType() && 9567 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9568 ActionIdx = 2; // If the pointee's size is sizeof(char), 9569 // suggest an explicit length. 9570 9571 // If the function is defined as a builtin macro, do not show macro 9572 // expansion. 9573 SourceLocation SL = SizeOfArg->getExprLoc(); 9574 SourceRange DSR = Dest->getSourceRange(); 9575 SourceRange SSR = SizeOfArg->getSourceRange(); 9576 SourceManager &SM = getSourceManager(); 9577 9578 if (SM.isMacroArgExpansion(SL)) { 9579 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9580 SL = SM.getSpellingLoc(SL); 9581 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9582 SM.getSpellingLoc(DSR.getEnd())); 9583 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9584 SM.getSpellingLoc(SSR.getEnd())); 9585 } 9586 9587 DiagRuntimeBehavior(SL, SizeOfArg, 9588 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9589 << ReadableName 9590 << PointeeTy 9591 << DestTy 9592 << DSR 9593 << SSR); 9594 DiagRuntimeBehavior(SL, SizeOfArg, 9595 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9596 << ActionIdx 9597 << SSR); 9598 9599 break; 9600 } 9601 } 9602 9603 // Also check for cases where the sizeof argument is the exact same 9604 // type as the memory argument, and where it points to a user-defined 9605 // record type. 9606 if (SizeOfArgTy != QualType()) { 9607 if (PointeeTy->isRecordType() && 9608 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9609 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9610 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9611 << FnName << SizeOfArgTy << ArgIdx 9612 << PointeeTy << Dest->getSourceRange() 9613 << LenExpr->getSourceRange()); 9614 break; 9615 } 9616 } 9617 } else if (DestTy->isArrayType()) { 9618 PointeeTy = DestTy; 9619 } 9620 9621 if (PointeeTy == QualType()) 9622 continue; 9623 9624 // Always complain about dynamic classes. 9625 bool IsContained; 9626 if (const CXXRecordDecl *ContainedRD = 9627 getContainedDynamicClass(PointeeTy, IsContained)) { 9628 9629 unsigned OperationType = 0; 9630 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9631 // "overwritten" if we're warning about the destination for any call 9632 // but memcmp; otherwise a verb appropriate to the call. 9633 if (ArgIdx != 0 || IsCmp) { 9634 if (BId == Builtin::BImemcpy) 9635 OperationType = 1; 9636 else if(BId == Builtin::BImemmove) 9637 OperationType = 2; 9638 else if (IsCmp) 9639 OperationType = 3; 9640 } 9641 9642 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9643 PDiag(diag::warn_dyn_class_memaccess) 9644 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9645 << IsContained << ContainedRD << OperationType 9646 << Call->getCallee()->getSourceRange()); 9647 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9648 BId != Builtin::BImemset) 9649 DiagRuntimeBehavior( 9650 Dest->getExprLoc(), Dest, 9651 PDiag(diag::warn_arc_object_memaccess) 9652 << ArgIdx << FnName << PointeeTy 9653 << Call->getCallee()->getSourceRange()); 9654 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9655 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9656 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9657 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9658 PDiag(diag::warn_cstruct_memaccess) 9659 << ArgIdx << FnName << PointeeTy << 0); 9660 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9661 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9662 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9663 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9664 PDiag(diag::warn_cstruct_memaccess) 9665 << ArgIdx << FnName << PointeeTy << 1); 9666 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9667 } else { 9668 continue; 9669 } 9670 } else 9671 continue; 9672 9673 DiagRuntimeBehavior( 9674 Dest->getExprLoc(), Dest, 9675 PDiag(diag::note_bad_memaccess_silence) 9676 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9677 break; 9678 } 9679 } 9680 9681 // A little helper routine: ignore addition and subtraction of integer literals. 9682 // This intentionally does not ignore all integer constant expressions because 9683 // we don't want to remove sizeof(). 9684 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9685 Ex = Ex->IgnoreParenCasts(); 9686 9687 while (true) { 9688 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9689 if (!BO || !BO->isAdditiveOp()) 9690 break; 9691 9692 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9693 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9694 9695 if (isa<IntegerLiteral>(RHS)) 9696 Ex = LHS; 9697 else if (isa<IntegerLiteral>(LHS)) 9698 Ex = RHS; 9699 else 9700 break; 9701 } 9702 9703 return Ex; 9704 } 9705 9706 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9707 ASTContext &Context) { 9708 // Only handle constant-sized or VLAs, but not flexible members. 9709 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9710 // Only issue the FIXIT for arrays of size > 1. 9711 if (CAT->getSize().getSExtValue() <= 1) 9712 return false; 9713 } else if (!Ty->isVariableArrayType()) { 9714 return false; 9715 } 9716 return true; 9717 } 9718 9719 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9720 // be the size of the source, instead of the destination. 9721 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9722 IdentifierInfo *FnName) { 9723 9724 // Don't crash if the user has the wrong number of arguments 9725 unsigned NumArgs = Call->getNumArgs(); 9726 if ((NumArgs != 3) && (NumArgs != 4)) 9727 return; 9728 9729 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9730 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9731 const Expr *CompareWithSrc = nullptr; 9732 9733 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9734 Call->getBeginLoc(), Call->getRParenLoc())) 9735 return; 9736 9737 // Look for 'strlcpy(dst, x, sizeof(x))' 9738 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9739 CompareWithSrc = Ex; 9740 else { 9741 // Look for 'strlcpy(dst, x, strlen(x))' 9742 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9743 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9744 SizeCall->getNumArgs() == 1) 9745 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9746 } 9747 } 9748 9749 if (!CompareWithSrc) 9750 return; 9751 9752 // Determine if the argument to sizeof/strlen is equal to the source 9753 // argument. In principle there's all kinds of things you could do 9754 // here, for instance creating an == expression and evaluating it with 9755 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9756 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9757 if (!SrcArgDRE) 9758 return; 9759 9760 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9761 if (!CompareWithSrcDRE || 9762 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9763 return; 9764 9765 const Expr *OriginalSizeArg = Call->getArg(2); 9766 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9767 << OriginalSizeArg->getSourceRange() << FnName; 9768 9769 // Output a FIXIT hint if the destination is an array (rather than a 9770 // pointer to an array). This could be enhanced to handle some 9771 // pointers if we know the actual size, like if DstArg is 'array+2' 9772 // we could say 'sizeof(array)-2'. 9773 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9774 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9775 return; 9776 9777 SmallString<128> sizeString; 9778 llvm::raw_svector_ostream OS(sizeString); 9779 OS << "sizeof("; 9780 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9781 OS << ")"; 9782 9783 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9784 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9785 OS.str()); 9786 } 9787 9788 /// Check if two expressions refer to the same declaration. 9789 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9790 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9791 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9792 return D1->getDecl() == D2->getDecl(); 9793 return false; 9794 } 9795 9796 static const Expr *getStrlenExprArg(const Expr *E) { 9797 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9798 const FunctionDecl *FD = CE->getDirectCallee(); 9799 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9800 return nullptr; 9801 return CE->getArg(0)->IgnoreParenCasts(); 9802 } 9803 return nullptr; 9804 } 9805 9806 // Warn on anti-patterns as the 'size' argument to strncat. 9807 // The correct size argument should look like following: 9808 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9809 void Sema::CheckStrncatArguments(const CallExpr *CE, 9810 IdentifierInfo *FnName) { 9811 // Don't crash if the user has the wrong number of arguments. 9812 if (CE->getNumArgs() < 3) 9813 return; 9814 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9815 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9816 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9817 9818 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9819 CE->getRParenLoc())) 9820 return; 9821 9822 // Identify common expressions, which are wrongly used as the size argument 9823 // to strncat and may lead to buffer overflows. 9824 unsigned PatternType = 0; 9825 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9826 // - sizeof(dst) 9827 if (referToTheSameDecl(SizeOfArg, DstArg)) 9828 PatternType = 1; 9829 // - sizeof(src) 9830 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9831 PatternType = 2; 9832 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9833 if (BE->getOpcode() == BO_Sub) { 9834 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9835 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9836 // - sizeof(dst) - strlen(dst) 9837 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9838 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9839 PatternType = 1; 9840 // - sizeof(src) - (anything) 9841 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9842 PatternType = 2; 9843 } 9844 } 9845 9846 if (PatternType == 0) 9847 return; 9848 9849 // Generate the diagnostic. 9850 SourceLocation SL = LenArg->getBeginLoc(); 9851 SourceRange SR = LenArg->getSourceRange(); 9852 SourceManager &SM = getSourceManager(); 9853 9854 // If the function is defined as a builtin macro, do not show macro expansion. 9855 if (SM.isMacroArgExpansion(SL)) { 9856 SL = SM.getSpellingLoc(SL); 9857 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9858 SM.getSpellingLoc(SR.getEnd())); 9859 } 9860 9861 // Check if the destination is an array (rather than a pointer to an array). 9862 QualType DstTy = DstArg->getType(); 9863 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9864 Context); 9865 if (!isKnownSizeArray) { 9866 if (PatternType == 1) 9867 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9868 else 9869 Diag(SL, diag::warn_strncat_src_size) << SR; 9870 return; 9871 } 9872 9873 if (PatternType == 1) 9874 Diag(SL, diag::warn_strncat_large_size) << SR; 9875 else 9876 Diag(SL, diag::warn_strncat_src_size) << SR; 9877 9878 SmallString<128> sizeString; 9879 llvm::raw_svector_ostream OS(sizeString); 9880 OS << "sizeof("; 9881 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9882 OS << ") - "; 9883 OS << "strlen("; 9884 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9885 OS << ") - 1"; 9886 9887 Diag(SL, diag::note_strncat_wrong_size) 9888 << FixItHint::CreateReplacement(SR, OS.str()); 9889 } 9890 9891 void 9892 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9893 SourceLocation ReturnLoc, 9894 bool isObjCMethod, 9895 const AttrVec *Attrs, 9896 const FunctionDecl *FD) { 9897 // Check if the return value is null but should not be. 9898 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9899 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9900 CheckNonNullExpr(*this, RetValExp)) 9901 Diag(ReturnLoc, diag::warn_null_ret) 9902 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9903 9904 // C++11 [basic.stc.dynamic.allocation]p4: 9905 // If an allocation function declared with a non-throwing 9906 // exception-specification fails to allocate storage, it shall return 9907 // a null pointer. Any other allocation function that fails to allocate 9908 // storage shall indicate failure only by throwing an exception [...] 9909 if (FD) { 9910 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9911 if (Op == OO_New || Op == OO_Array_New) { 9912 const FunctionProtoType *Proto 9913 = FD->getType()->castAs<FunctionProtoType>(); 9914 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9915 CheckNonNullExpr(*this, RetValExp)) 9916 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9917 << FD << getLangOpts().CPlusPlus11; 9918 } 9919 } 9920 } 9921 9922 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9923 9924 /// Check for comparisons of floating point operands using != and ==. 9925 /// Issue a warning if these are no self-comparisons, as they are not likely 9926 /// to do what the programmer intended. 9927 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9928 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9929 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9930 9931 // Special case: check for x == x (which is OK). 9932 // Do not emit warnings for such cases. 9933 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9934 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9935 if (DRL->getDecl() == DRR->getDecl()) 9936 return; 9937 9938 // Special case: check for comparisons against literals that can be exactly 9939 // represented by APFloat. In such cases, do not emit a warning. This 9940 // is a heuristic: often comparison against such literals are used to 9941 // detect if a value in a variable has not changed. This clearly can 9942 // lead to false negatives. 9943 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9944 if (FLL->isExact()) 9945 return; 9946 } else 9947 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9948 if (FLR->isExact()) 9949 return; 9950 9951 // Check for comparisons with builtin types. 9952 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9953 if (CL->getBuiltinCallee()) 9954 return; 9955 9956 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9957 if (CR->getBuiltinCallee()) 9958 return; 9959 9960 // Emit the diagnostic. 9961 Diag(Loc, diag::warn_floatingpoint_eq) 9962 << LHS->getSourceRange() << RHS->getSourceRange(); 9963 } 9964 9965 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9966 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9967 9968 namespace { 9969 9970 /// Structure recording the 'active' range of an integer-valued 9971 /// expression. 9972 struct IntRange { 9973 /// The number of bits active in the int. 9974 unsigned Width; 9975 9976 /// True if the int is known not to have negative values. 9977 bool NonNegative; 9978 9979 IntRange(unsigned Width, bool NonNegative) 9980 : Width(Width), NonNegative(NonNegative) {} 9981 9982 /// Returns the range of the bool type. 9983 static IntRange forBoolType() { 9984 return IntRange(1, true); 9985 } 9986 9987 /// Returns the range of an opaque value of the given integral type. 9988 static IntRange forValueOfType(ASTContext &C, QualType T) { 9989 return forValueOfCanonicalType(C, 9990 T->getCanonicalTypeInternal().getTypePtr()); 9991 } 9992 9993 /// Returns the range of an opaque value of a canonical integral type. 9994 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9995 assert(T->isCanonicalUnqualified()); 9996 9997 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9998 T = VT->getElementType().getTypePtr(); 9999 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10000 T = CT->getElementType().getTypePtr(); 10001 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10002 T = AT->getValueType().getTypePtr(); 10003 10004 if (!C.getLangOpts().CPlusPlus) { 10005 // For enum types in C code, use the underlying datatype. 10006 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10007 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10008 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10009 // For enum types in C++, use the known bit width of the enumerators. 10010 EnumDecl *Enum = ET->getDecl(); 10011 // In C++11, enums can have a fixed underlying type. Use this type to 10012 // compute the range. 10013 if (Enum->isFixed()) { 10014 return IntRange(C.getIntWidth(QualType(T, 0)), 10015 !ET->isSignedIntegerOrEnumerationType()); 10016 } 10017 10018 unsigned NumPositive = Enum->getNumPositiveBits(); 10019 unsigned NumNegative = Enum->getNumNegativeBits(); 10020 10021 if (NumNegative == 0) 10022 return IntRange(NumPositive, true/*NonNegative*/); 10023 else 10024 return IntRange(std::max(NumPositive + 1, NumNegative), 10025 false/*NonNegative*/); 10026 } 10027 10028 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10029 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10030 10031 const BuiltinType *BT = cast<BuiltinType>(T); 10032 assert(BT->isInteger()); 10033 10034 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10035 } 10036 10037 /// Returns the "target" range of a canonical integral type, i.e. 10038 /// the range of values expressible in the type. 10039 /// 10040 /// This matches forValueOfCanonicalType except that enums have the 10041 /// full range of their type, not the range of their enumerators. 10042 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10043 assert(T->isCanonicalUnqualified()); 10044 10045 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10046 T = VT->getElementType().getTypePtr(); 10047 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10048 T = CT->getElementType().getTypePtr(); 10049 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10050 T = AT->getValueType().getTypePtr(); 10051 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10052 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10053 10054 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10055 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10056 10057 const BuiltinType *BT = cast<BuiltinType>(T); 10058 assert(BT->isInteger()); 10059 10060 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10061 } 10062 10063 /// Returns the supremum of two ranges: i.e. their conservative merge. 10064 static IntRange join(IntRange L, IntRange R) { 10065 return IntRange(std::max(L.Width, R.Width), 10066 L.NonNegative && R.NonNegative); 10067 } 10068 10069 /// Returns the infinum of two ranges: i.e. their aggressive merge. 10070 static IntRange meet(IntRange L, IntRange R) { 10071 return IntRange(std::min(L.Width, R.Width), 10072 L.NonNegative || R.NonNegative); 10073 } 10074 }; 10075 10076 } // namespace 10077 10078 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10079 unsigned MaxWidth) { 10080 if (value.isSigned() && value.isNegative()) 10081 return IntRange(value.getMinSignedBits(), false); 10082 10083 if (value.getBitWidth() > MaxWidth) 10084 value = value.trunc(MaxWidth); 10085 10086 // isNonNegative() just checks the sign bit without considering 10087 // signedness. 10088 return IntRange(value.getActiveBits(), true); 10089 } 10090 10091 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10092 unsigned MaxWidth) { 10093 if (result.isInt()) 10094 return GetValueRange(C, result.getInt(), MaxWidth); 10095 10096 if (result.isVector()) { 10097 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10098 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10099 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10100 R = IntRange::join(R, El); 10101 } 10102 return R; 10103 } 10104 10105 if (result.isComplexInt()) { 10106 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10107 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10108 return IntRange::join(R, I); 10109 } 10110 10111 // This can happen with lossless casts to intptr_t of "based" lvalues. 10112 // Assume it might use arbitrary bits. 10113 // FIXME: The only reason we need to pass the type in here is to get 10114 // the sign right on this one case. It would be nice if APValue 10115 // preserved this. 10116 assert(result.isLValue() || result.isAddrLabelDiff()); 10117 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10118 } 10119 10120 static QualType GetExprType(const Expr *E) { 10121 QualType Ty = E->getType(); 10122 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10123 Ty = AtomicRHS->getValueType(); 10124 return Ty; 10125 } 10126 10127 /// Pseudo-evaluate the given integer expression, estimating the 10128 /// range of values it might take. 10129 /// 10130 /// \param MaxWidth - the width to which the value will be truncated 10131 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10132 bool InConstantContext) { 10133 E = E->IgnoreParens(); 10134 10135 // Try a full evaluation first. 10136 Expr::EvalResult result; 10137 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10138 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10139 10140 // I think we only want to look through implicit casts here; if the 10141 // user has an explicit widening cast, we should treat the value as 10142 // being of the new, wider type. 10143 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10144 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10145 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 10146 10147 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10148 10149 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10150 CE->getCastKind() == CK_BooleanToSignedIntegral; 10151 10152 // Assume that non-integer casts can span the full range of the type. 10153 if (!isIntegerCast) 10154 return OutputTypeRange; 10155 10156 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10157 std::min(MaxWidth, OutputTypeRange.Width), 10158 InConstantContext); 10159 10160 // Bail out if the subexpr's range is as wide as the cast type. 10161 if (SubRange.Width >= OutputTypeRange.Width) 10162 return OutputTypeRange; 10163 10164 // Otherwise, we take the smaller width, and we're non-negative if 10165 // either the output type or the subexpr is. 10166 return IntRange(SubRange.Width, 10167 SubRange.NonNegative || OutputTypeRange.NonNegative); 10168 } 10169 10170 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10171 // If we can fold the condition, just take that operand. 10172 bool CondResult; 10173 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10174 return GetExprRange(C, 10175 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10176 MaxWidth, InConstantContext); 10177 10178 // Otherwise, conservatively merge. 10179 IntRange L = 10180 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 10181 IntRange R = 10182 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 10183 return IntRange::join(L, R); 10184 } 10185 10186 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10187 switch (BO->getOpcode()) { 10188 case BO_Cmp: 10189 llvm_unreachable("builtin <=> should have class type"); 10190 10191 // Boolean-valued operations are single-bit and positive. 10192 case BO_LAnd: 10193 case BO_LOr: 10194 case BO_LT: 10195 case BO_GT: 10196 case BO_LE: 10197 case BO_GE: 10198 case BO_EQ: 10199 case BO_NE: 10200 return IntRange::forBoolType(); 10201 10202 // The type of the assignments is the type of the LHS, so the RHS 10203 // is not necessarily the same type. 10204 case BO_MulAssign: 10205 case BO_DivAssign: 10206 case BO_RemAssign: 10207 case BO_AddAssign: 10208 case BO_SubAssign: 10209 case BO_XorAssign: 10210 case BO_OrAssign: 10211 // TODO: bitfields? 10212 return IntRange::forValueOfType(C, GetExprType(E)); 10213 10214 // Simple assignments just pass through the RHS, which will have 10215 // been coerced to the LHS type. 10216 case BO_Assign: 10217 // TODO: bitfields? 10218 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10219 10220 // Operations with opaque sources are black-listed. 10221 case BO_PtrMemD: 10222 case BO_PtrMemI: 10223 return IntRange::forValueOfType(C, GetExprType(E)); 10224 10225 // Bitwise-and uses the *infinum* of the two source ranges. 10226 case BO_And: 10227 case BO_AndAssign: 10228 return IntRange::meet( 10229 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10230 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10231 10232 // Left shift gets black-listed based on a judgement call. 10233 case BO_Shl: 10234 // ...except that we want to treat '1 << (blah)' as logically 10235 // positive. It's an important idiom. 10236 if (IntegerLiteral *I 10237 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10238 if (I->getValue() == 1) { 10239 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10240 return IntRange(R.Width, /*NonNegative*/ true); 10241 } 10242 } 10243 LLVM_FALLTHROUGH; 10244 10245 case BO_ShlAssign: 10246 return IntRange::forValueOfType(C, GetExprType(E)); 10247 10248 // Right shift by a constant can narrow its left argument. 10249 case BO_Shr: 10250 case BO_ShrAssign: { 10251 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10252 10253 // If the shift amount is a positive constant, drop the width by 10254 // that much. 10255 llvm::APSInt shift; 10256 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 10257 shift.isNonNegative()) { 10258 unsigned zext = shift.getZExtValue(); 10259 if (zext >= L.Width) 10260 L.Width = (L.NonNegative ? 0 : 1); 10261 else 10262 L.Width -= zext; 10263 } 10264 10265 return L; 10266 } 10267 10268 // Comma acts as its right operand. 10269 case BO_Comma: 10270 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10271 10272 // Black-list pointer subtractions. 10273 case BO_Sub: 10274 if (BO->getLHS()->getType()->isPointerType()) 10275 return IntRange::forValueOfType(C, GetExprType(E)); 10276 break; 10277 10278 // The width of a division result is mostly determined by the size 10279 // of the LHS. 10280 case BO_Div: { 10281 // Don't 'pre-truncate' the operands. 10282 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10283 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10284 10285 // If the divisor is constant, use that. 10286 llvm::APSInt divisor; 10287 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 10288 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 10289 if (log2 >= L.Width) 10290 L.Width = (L.NonNegative ? 0 : 1); 10291 else 10292 L.Width = std::min(L.Width - log2, MaxWidth); 10293 return L; 10294 } 10295 10296 // Otherwise, just use the LHS's width. 10297 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10298 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10299 } 10300 10301 // The result of a remainder can't be larger than the result of 10302 // either side. 10303 case BO_Rem: { 10304 // Don't 'pre-truncate' the operands. 10305 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10306 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10307 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10308 10309 IntRange meet = IntRange::meet(L, R); 10310 meet.Width = std::min(meet.Width, MaxWidth); 10311 return meet; 10312 } 10313 10314 // The default behavior is okay for these. 10315 case BO_Mul: 10316 case BO_Add: 10317 case BO_Xor: 10318 case BO_Or: 10319 break; 10320 } 10321 10322 // The default case is to treat the operation as if it were closed 10323 // on the narrowest type that encompasses both operands. 10324 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10325 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10326 return IntRange::join(L, R); 10327 } 10328 10329 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10330 switch (UO->getOpcode()) { 10331 // Boolean-valued operations are white-listed. 10332 case UO_LNot: 10333 return IntRange::forBoolType(); 10334 10335 // Operations with opaque sources are black-listed. 10336 case UO_Deref: 10337 case UO_AddrOf: // should be impossible 10338 return IntRange::forValueOfType(C, GetExprType(E)); 10339 10340 default: 10341 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10342 } 10343 } 10344 10345 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10346 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10347 10348 if (const auto *BitField = E->getSourceBitField()) 10349 return IntRange(BitField->getBitWidthValue(C), 10350 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10351 10352 return IntRange::forValueOfType(C, GetExprType(E)); 10353 } 10354 10355 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10356 bool InConstantContext) { 10357 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10358 } 10359 10360 /// Checks whether the given value, which currently has the given 10361 /// source semantics, has the same value when coerced through the 10362 /// target semantics. 10363 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10364 const llvm::fltSemantics &Src, 10365 const llvm::fltSemantics &Tgt) { 10366 llvm::APFloat truncated = value; 10367 10368 bool ignored; 10369 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10370 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10371 10372 return truncated.bitwiseIsEqual(value); 10373 } 10374 10375 /// Checks whether the given value, which currently has the given 10376 /// source semantics, has the same value when coerced through the 10377 /// target semantics. 10378 /// 10379 /// The value might be a vector of floats (or a complex number). 10380 static bool IsSameFloatAfterCast(const APValue &value, 10381 const llvm::fltSemantics &Src, 10382 const llvm::fltSemantics &Tgt) { 10383 if (value.isFloat()) 10384 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10385 10386 if (value.isVector()) { 10387 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10388 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10389 return false; 10390 return true; 10391 } 10392 10393 assert(value.isComplexFloat()); 10394 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10395 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10396 } 10397 10398 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10399 bool IsListInit = false); 10400 10401 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10402 // Suppress cases where we are comparing against an enum constant. 10403 if (const DeclRefExpr *DR = 10404 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10405 if (isa<EnumConstantDecl>(DR->getDecl())) 10406 return true; 10407 10408 // Suppress cases where the value is expanded from a macro, unless that macro 10409 // is how a language represents a boolean literal. This is the case in both C 10410 // and Objective-C. 10411 SourceLocation BeginLoc = E->getBeginLoc(); 10412 if (BeginLoc.isMacroID()) { 10413 StringRef MacroName = Lexer::getImmediateMacroName( 10414 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10415 return MacroName != "YES" && MacroName != "NO" && 10416 MacroName != "true" && MacroName != "false"; 10417 } 10418 10419 return false; 10420 } 10421 10422 static bool isKnownToHaveUnsignedValue(Expr *E) { 10423 return E->getType()->isIntegerType() && 10424 (!E->getType()->isSignedIntegerType() || 10425 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10426 } 10427 10428 namespace { 10429 /// The promoted range of values of a type. In general this has the 10430 /// following structure: 10431 /// 10432 /// |-----------| . . . |-----------| 10433 /// ^ ^ ^ ^ 10434 /// Min HoleMin HoleMax Max 10435 /// 10436 /// ... where there is only a hole if a signed type is promoted to unsigned 10437 /// (in which case Min and Max are the smallest and largest representable 10438 /// values). 10439 struct PromotedRange { 10440 // Min, or HoleMax if there is a hole. 10441 llvm::APSInt PromotedMin; 10442 // Max, or HoleMin if there is a hole. 10443 llvm::APSInt PromotedMax; 10444 10445 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10446 if (R.Width == 0) 10447 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10448 else if (R.Width >= BitWidth && !Unsigned) { 10449 // Promotion made the type *narrower*. This happens when promoting 10450 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10451 // Treat all values of 'signed int' as being in range for now. 10452 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10453 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10454 } else { 10455 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10456 .extOrTrunc(BitWidth); 10457 PromotedMin.setIsUnsigned(Unsigned); 10458 10459 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10460 .extOrTrunc(BitWidth); 10461 PromotedMax.setIsUnsigned(Unsigned); 10462 } 10463 } 10464 10465 // Determine whether this range is contiguous (has no hole). 10466 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10467 10468 // Where a constant value is within the range. 10469 enum ComparisonResult { 10470 LT = 0x1, 10471 LE = 0x2, 10472 GT = 0x4, 10473 GE = 0x8, 10474 EQ = 0x10, 10475 NE = 0x20, 10476 InRangeFlag = 0x40, 10477 10478 Less = LE | LT | NE, 10479 Min = LE | InRangeFlag, 10480 InRange = InRangeFlag, 10481 Max = GE | InRangeFlag, 10482 Greater = GE | GT | NE, 10483 10484 OnlyValue = LE | GE | EQ | InRangeFlag, 10485 InHole = NE 10486 }; 10487 10488 ComparisonResult compare(const llvm::APSInt &Value) const { 10489 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10490 Value.isUnsigned() == PromotedMin.isUnsigned()); 10491 if (!isContiguous()) { 10492 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10493 if (Value.isMinValue()) return Min; 10494 if (Value.isMaxValue()) return Max; 10495 if (Value >= PromotedMin) return InRange; 10496 if (Value <= PromotedMax) return InRange; 10497 return InHole; 10498 } 10499 10500 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10501 case -1: return Less; 10502 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10503 case 1: 10504 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10505 case -1: return InRange; 10506 case 0: return Max; 10507 case 1: return Greater; 10508 } 10509 } 10510 10511 llvm_unreachable("impossible compare result"); 10512 } 10513 10514 static llvm::Optional<StringRef> 10515 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10516 if (Op == BO_Cmp) { 10517 ComparisonResult LTFlag = LT, GTFlag = GT; 10518 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10519 10520 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10521 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10522 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10523 return llvm::None; 10524 } 10525 10526 ComparisonResult TrueFlag, FalseFlag; 10527 if (Op == BO_EQ) { 10528 TrueFlag = EQ; 10529 FalseFlag = NE; 10530 } else if (Op == BO_NE) { 10531 TrueFlag = NE; 10532 FalseFlag = EQ; 10533 } else { 10534 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10535 TrueFlag = LT; 10536 FalseFlag = GE; 10537 } else { 10538 TrueFlag = GT; 10539 FalseFlag = LE; 10540 } 10541 if (Op == BO_GE || Op == BO_LE) 10542 std::swap(TrueFlag, FalseFlag); 10543 } 10544 if (R & TrueFlag) 10545 return StringRef("true"); 10546 if (R & FalseFlag) 10547 return StringRef("false"); 10548 return llvm::None; 10549 } 10550 }; 10551 } 10552 10553 static bool HasEnumType(Expr *E) { 10554 // Strip off implicit integral promotions. 10555 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10556 if (ICE->getCastKind() != CK_IntegralCast && 10557 ICE->getCastKind() != CK_NoOp) 10558 break; 10559 E = ICE->getSubExpr(); 10560 } 10561 10562 return E->getType()->isEnumeralType(); 10563 } 10564 10565 static int classifyConstantValue(Expr *Constant) { 10566 // The values of this enumeration are used in the diagnostics 10567 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10568 enum ConstantValueKind { 10569 Miscellaneous = 0, 10570 LiteralTrue, 10571 LiteralFalse 10572 }; 10573 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10574 return BL->getValue() ? ConstantValueKind::LiteralTrue 10575 : ConstantValueKind::LiteralFalse; 10576 return ConstantValueKind::Miscellaneous; 10577 } 10578 10579 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10580 Expr *Constant, Expr *Other, 10581 const llvm::APSInt &Value, 10582 bool RhsConstant) { 10583 if (S.inTemplateInstantiation()) 10584 return false; 10585 10586 Expr *OriginalOther = Other; 10587 10588 Constant = Constant->IgnoreParenImpCasts(); 10589 Other = Other->IgnoreParenImpCasts(); 10590 10591 // Suppress warnings on tautological comparisons between values of the same 10592 // enumeration type. There are only two ways we could warn on this: 10593 // - If the constant is outside the range of representable values of 10594 // the enumeration. In such a case, we should warn about the cast 10595 // to enumeration type, not about the comparison. 10596 // - If the constant is the maximum / minimum in-range value. For an 10597 // enumeratin type, such comparisons can be meaningful and useful. 10598 if (Constant->getType()->isEnumeralType() && 10599 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10600 return false; 10601 10602 // TODO: Investigate using GetExprRange() to get tighter bounds 10603 // on the bit ranges. 10604 QualType OtherT = Other->getType(); 10605 if (const auto *AT = OtherT->getAs<AtomicType>()) 10606 OtherT = AT->getValueType(); 10607 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10608 10609 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10610 // (Namely, macOS). 10611 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10612 S.NSAPIObj->isObjCBOOLType(OtherT) && 10613 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10614 10615 // Whether we're treating Other as being a bool because of the form of 10616 // expression despite it having another type (typically 'int' in C). 10617 bool OtherIsBooleanDespiteType = 10618 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10619 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10620 OtherRange = IntRange::forBoolType(); 10621 10622 // Determine the promoted range of the other type and see if a comparison of 10623 // the constant against that range is tautological. 10624 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10625 Value.isUnsigned()); 10626 auto Cmp = OtherPromotedRange.compare(Value); 10627 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10628 if (!Result) 10629 return false; 10630 10631 // Suppress the diagnostic for an in-range comparison if the constant comes 10632 // from a macro or enumerator. We don't want to diagnose 10633 // 10634 // some_long_value <= INT_MAX 10635 // 10636 // when sizeof(int) == sizeof(long). 10637 bool InRange = Cmp & PromotedRange::InRangeFlag; 10638 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10639 return false; 10640 10641 // If this is a comparison to an enum constant, include that 10642 // constant in the diagnostic. 10643 const EnumConstantDecl *ED = nullptr; 10644 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10645 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10646 10647 // Should be enough for uint128 (39 decimal digits) 10648 SmallString<64> PrettySourceValue; 10649 llvm::raw_svector_ostream OS(PrettySourceValue); 10650 if (ED) { 10651 OS << '\'' << *ED << "' (" << Value << ")"; 10652 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10653 Constant->IgnoreParenImpCasts())) { 10654 OS << (BL->getValue() ? "YES" : "NO"); 10655 } else { 10656 OS << Value; 10657 } 10658 10659 if (IsObjCSignedCharBool) { 10660 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10661 S.PDiag(diag::warn_tautological_compare_objc_bool) 10662 << OS.str() << *Result); 10663 return true; 10664 } 10665 10666 // FIXME: We use a somewhat different formatting for the in-range cases and 10667 // cases involving boolean values for historical reasons. We should pick a 10668 // consistent way of presenting these diagnostics. 10669 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10670 10671 S.DiagRuntimeBehavior( 10672 E->getOperatorLoc(), E, 10673 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10674 : diag::warn_tautological_bool_compare) 10675 << OS.str() << classifyConstantValue(Constant) << OtherT 10676 << OtherIsBooleanDespiteType << *Result 10677 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10678 } else { 10679 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10680 ? (HasEnumType(OriginalOther) 10681 ? diag::warn_unsigned_enum_always_true_comparison 10682 : diag::warn_unsigned_always_true_comparison) 10683 : diag::warn_tautological_constant_compare; 10684 10685 S.Diag(E->getOperatorLoc(), Diag) 10686 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10687 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10688 } 10689 10690 return true; 10691 } 10692 10693 /// Analyze the operands of the given comparison. Implements the 10694 /// fallback case from AnalyzeComparison. 10695 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10696 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10697 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10698 } 10699 10700 /// Implements -Wsign-compare. 10701 /// 10702 /// \param E the binary operator to check for warnings 10703 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10704 // The type the comparison is being performed in. 10705 QualType T = E->getLHS()->getType(); 10706 10707 // Only analyze comparison operators where both sides have been converted to 10708 // the same type. 10709 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10710 return AnalyzeImpConvsInComparison(S, E); 10711 10712 // Don't analyze value-dependent comparisons directly. 10713 if (E->isValueDependent()) 10714 return AnalyzeImpConvsInComparison(S, E); 10715 10716 Expr *LHS = E->getLHS(); 10717 Expr *RHS = E->getRHS(); 10718 10719 if (T->isIntegralType(S.Context)) { 10720 llvm::APSInt RHSValue; 10721 llvm::APSInt LHSValue; 10722 10723 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10724 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10725 10726 // We don't care about expressions whose result is a constant. 10727 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10728 return AnalyzeImpConvsInComparison(S, E); 10729 10730 // We only care about expressions where just one side is literal 10731 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10732 // Is the constant on the RHS or LHS? 10733 const bool RhsConstant = IsRHSIntegralLiteral; 10734 Expr *Const = RhsConstant ? RHS : LHS; 10735 Expr *Other = RhsConstant ? LHS : RHS; 10736 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10737 10738 // Check whether an integer constant comparison results in a value 10739 // of 'true' or 'false'. 10740 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10741 return AnalyzeImpConvsInComparison(S, E); 10742 } 10743 } 10744 10745 if (!T->hasUnsignedIntegerRepresentation()) { 10746 // We don't do anything special if this isn't an unsigned integral 10747 // comparison: we're only interested in integral comparisons, and 10748 // signed comparisons only happen in cases we don't care to warn about. 10749 return AnalyzeImpConvsInComparison(S, E); 10750 } 10751 10752 LHS = LHS->IgnoreParenImpCasts(); 10753 RHS = RHS->IgnoreParenImpCasts(); 10754 10755 if (!S.getLangOpts().CPlusPlus) { 10756 // Avoid warning about comparison of integers with different signs when 10757 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10758 // the type of `E`. 10759 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10760 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10761 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10762 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10763 } 10764 10765 // Check to see if one of the (unmodified) operands is of different 10766 // signedness. 10767 Expr *signedOperand, *unsignedOperand; 10768 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10769 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10770 "unsigned comparison between two signed integer expressions?"); 10771 signedOperand = LHS; 10772 unsignedOperand = RHS; 10773 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10774 signedOperand = RHS; 10775 unsignedOperand = LHS; 10776 } else { 10777 return AnalyzeImpConvsInComparison(S, E); 10778 } 10779 10780 // Otherwise, calculate the effective range of the signed operand. 10781 IntRange signedRange = 10782 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10783 10784 // Go ahead and analyze implicit conversions in the operands. Note 10785 // that we skip the implicit conversions on both sides. 10786 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10787 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10788 10789 // If the signed range is non-negative, -Wsign-compare won't fire. 10790 if (signedRange.NonNegative) 10791 return; 10792 10793 // For (in)equality comparisons, if the unsigned operand is a 10794 // constant which cannot collide with a overflowed signed operand, 10795 // then reinterpreting the signed operand as unsigned will not 10796 // change the result of the comparison. 10797 if (E->isEqualityOp()) { 10798 unsigned comparisonWidth = S.Context.getIntWidth(T); 10799 IntRange unsignedRange = 10800 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10801 10802 // We should never be unable to prove that the unsigned operand is 10803 // non-negative. 10804 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10805 10806 if (unsignedRange.Width < comparisonWidth) 10807 return; 10808 } 10809 10810 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10811 S.PDiag(diag::warn_mixed_sign_comparison) 10812 << LHS->getType() << RHS->getType() 10813 << LHS->getSourceRange() << RHS->getSourceRange()); 10814 } 10815 10816 /// Analyzes an attempt to assign the given value to a bitfield. 10817 /// 10818 /// Returns true if there was something fishy about the attempt. 10819 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10820 SourceLocation InitLoc) { 10821 assert(Bitfield->isBitField()); 10822 if (Bitfield->isInvalidDecl()) 10823 return false; 10824 10825 // White-list bool bitfields. 10826 QualType BitfieldType = Bitfield->getType(); 10827 if (BitfieldType->isBooleanType()) 10828 return false; 10829 10830 if (BitfieldType->isEnumeralType()) { 10831 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10832 // If the underlying enum type was not explicitly specified as an unsigned 10833 // type and the enum contain only positive values, MSVC++ will cause an 10834 // inconsistency by storing this as a signed type. 10835 if (S.getLangOpts().CPlusPlus11 && 10836 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10837 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10838 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10839 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10840 << BitfieldEnumDecl->getNameAsString(); 10841 } 10842 } 10843 10844 if (Bitfield->getType()->isBooleanType()) 10845 return false; 10846 10847 // Ignore value- or type-dependent expressions. 10848 if (Bitfield->getBitWidth()->isValueDependent() || 10849 Bitfield->getBitWidth()->isTypeDependent() || 10850 Init->isValueDependent() || 10851 Init->isTypeDependent()) 10852 return false; 10853 10854 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10855 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10856 10857 Expr::EvalResult Result; 10858 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10859 Expr::SE_AllowSideEffects)) { 10860 // The RHS is not constant. If the RHS has an enum type, make sure the 10861 // bitfield is wide enough to hold all the values of the enum without 10862 // truncation. 10863 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10864 EnumDecl *ED = EnumTy->getDecl(); 10865 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10866 10867 // Enum types are implicitly signed on Windows, so check if there are any 10868 // negative enumerators to see if the enum was intended to be signed or 10869 // not. 10870 bool SignedEnum = ED->getNumNegativeBits() > 0; 10871 10872 // Check for surprising sign changes when assigning enum values to a 10873 // bitfield of different signedness. If the bitfield is signed and we 10874 // have exactly the right number of bits to store this unsigned enum, 10875 // suggest changing the enum to an unsigned type. This typically happens 10876 // on Windows where unfixed enums always use an underlying type of 'int'. 10877 unsigned DiagID = 0; 10878 if (SignedEnum && !SignedBitfield) { 10879 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10880 } else if (SignedBitfield && !SignedEnum && 10881 ED->getNumPositiveBits() == FieldWidth) { 10882 DiagID = diag::warn_signed_bitfield_enum_conversion; 10883 } 10884 10885 if (DiagID) { 10886 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10887 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10888 SourceRange TypeRange = 10889 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10890 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10891 << SignedEnum << TypeRange; 10892 } 10893 10894 // Compute the required bitwidth. If the enum has negative values, we need 10895 // one more bit than the normal number of positive bits to represent the 10896 // sign bit. 10897 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10898 ED->getNumNegativeBits()) 10899 : ED->getNumPositiveBits(); 10900 10901 // Check the bitwidth. 10902 if (BitsNeeded > FieldWidth) { 10903 Expr *WidthExpr = Bitfield->getBitWidth(); 10904 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10905 << Bitfield << ED; 10906 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10907 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10908 } 10909 } 10910 10911 return false; 10912 } 10913 10914 llvm::APSInt Value = Result.Val.getInt(); 10915 10916 unsigned OriginalWidth = Value.getBitWidth(); 10917 10918 if (!Value.isSigned() || Value.isNegative()) 10919 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10920 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10921 OriginalWidth = Value.getMinSignedBits(); 10922 10923 if (OriginalWidth <= FieldWidth) 10924 return false; 10925 10926 // Compute the value which the bitfield will contain. 10927 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10928 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10929 10930 // Check whether the stored value is equal to the original value. 10931 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10932 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10933 return false; 10934 10935 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10936 // therefore don't strictly fit into a signed bitfield of width 1. 10937 if (FieldWidth == 1 && Value == 1) 10938 return false; 10939 10940 std::string PrettyValue = Value.toString(10); 10941 std::string PrettyTrunc = TruncatedValue.toString(10); 10942 10943 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10944 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10945 << Init->getSourceRange(); 10946 10947 return true; 10948 } 10949 10950 /// Analyze the given simple or compound assignment for warning-worthy 10951 /// operations. 10952 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10953 // Just recurse on the LHS. 10954 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10955 10956 // We want to recurse on the RHS as normal unless we're assigning to 10957 // a bitfield. 10958 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10959 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10960 E->getOperatorLoc())) { 10961 // Recurse, ignoring any implicit conversions on the RHS. 10962 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10963 E->getOperatorLoc()); 10964 } 10965 } 10966 10967 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10968 10969 // Diagnose implicitly sequentially-consistent atomic assignment. 10970 if (E->getLHS()->getType()->isAtomicType()) 10971 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10972 } 10973 10974 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10975 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10976 SourceLocation CContext, unsigned diag, 10977 bool pruneControlFlow = false) { 10978 if (pruneControlFlow) { 10979 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10980 S.PDiag(diag) 10981 << SourceType << T << E->getSourceRange() 10982 << SourceRange(CContext)); 10983 return; 10984 } 10985 S.Diag(E->getExprLoc(), diag) 10986 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10987 } 10988 10989 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10990 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10991 SourceLocation CContext, 10992 unsigned diag, bool pruneControlFlow = false) { 10993 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10994 } 10995 10996 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 10997 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 10998 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 10999 } 11000 11001 static void adornObjCBoolConversionDiagWithTernaryFixit( 11002 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11003 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11004 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11005 Ignored = OVE->getSourceExpr(); 11006 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11007 isa<BinaryOperator>(Ignored) || 11008 isa<CXXOperatorCallExpr>(Ignored); 11009 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11010 if (NeedsParens) 11011 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11012 << FixItHint::CreateInsertion(EndLoc, ")"); 11013 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11014 } 11015 11016 /// Diagnose an implicit cast from a floating point value to an integer value. 11017 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11018 SourceLocation CContext) { 11019 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11020 const bool PruneWarnings = S.inTemplateInstantiation(); 11021 11022 Expr *InnerE = E->IgnoreParenImpCasts(); 11023 // We also want to warn on, e.g., "int i = -1.234" 11024 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11025 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11026 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11027 11028 const bool IsLiteral = 11029 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11030 11031 llvm::APFloat Value(0.0); 11032 bool IsConstant = 11033 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11034 if (!IsConstant) { 11035 if (isObjCSignedCharBool(S, T)) { 11036 return adornObjCBoolConversionDiagWithTernaryFixit( 11037 S, E, 11038 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11039 << E->getType()); 11040 } 11041 11042 return DiagnoseImpCast(S, E, T, CContext, 11043 diag::warn_impcast_float_integer, PruneWarnings); 11044 } 11045 11046 bool isExact = false; 11047 11048 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11049 T->hasUnsignedIntegerRepresentation()); 11050 llvm::APFloat::opStatus Result = Value.convertToInteger( 11051 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11052 11053 // FIXME: Force the precision of the source value down so we don't print 11054 // digits which are usually useless (we don't really care here if we 11055 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11056 // would automatically print the shortest representation, but it's a bit 11057 // tricky to implement. 11058 SmallString<16> PrettySourceValue; 11059 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11060 precision = (precision * 59 + 195) / 196; 11061 Value.toString(PrettySourceValue, precision); 11062 11063 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11064 return adornObjCBoolConversionDiagWithTernaryFixit( 11065 S, E, 11066 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11067 << PrettySourceValue); 11068 } 11069 11070 if (Result == llvm::APFloat::opOK && isExact) { 11071 if (IsLiteral) return; 11072 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11073 PruneWarnings); 11074 } 11075 11076 // Conversion of a floating-point value to a non-bool integer where the 11077 // integral part cannot be represented by the integer type is undefined. 11078 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11079 return DiagnoseImpCast( 11080 S, E, T, CContext, 11081 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11082 : diag::warn_impcast_float_to_integer_out_of_range, 11083 PruneWarnings); 11084 11085 unsigned DiagID = 0; 11086 if (IsLiteral) { 11087 // Warn on floating point literal to integer. 11088 DiagID = diag::warn_impcast_literal_float_to_integer; 11089 } else if (IntegerValue == 0) { 11090 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11091 return DiagnoseImpCast(S, E, T, CContext, 11092 diag::warn_impcast_float_integer, PruneWarnings); 11093 } 11094 // Warn on non-zero to zero conversion. 11095 DiagID = diag::warn_impcast_float_to_integer_zero; 11096 } else { 11097 if (IntegerValue.isUnsigned()) { 11098 if (!IntegerValue.isMaxValue()) { 11099 return DiagnoseImpCast(S, E, T, CContext, 11100 diag::warn_impcast_float_integer, PruneWarnings); 11101 } 11102 } else { // IntegerValue.isSigned() 11103 if (!IntegerValue.isMaxSignedValue() && 11104 !IntegerValue.isMinSignedValue()) { 11105 return DiagnoseImpCast(S, E, T, CContext, 11106 diag::warn_impcast_float_integer, PruneWarnings); 11107 } 11108 } 11109 // Warn on evaluatable floating point expression to integer conversion. 11110 DiagID = diag::warn_impcast_float_to_integer; 11111 } 11112 11113 SmallString<16> PrettyTargetValue; 11114 if (IsBool) 11115 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11116 else 11117 IntegerValue.toString(PrettyTargetValue); 11118 11119 if (PruneWarnings) { 11120 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11121 S.PDiag(DiagID) 11122 << E->getType() << T.getUnqualifiedType() 11123 << PrettySourceValue << PrettyTargetValue 11124 << E->getSourceRange() << SourceRange(CContext)); 11125 } else { 11126 S.Diag(E->getExprLoc(), DiagID) 11127 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11128 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11129 } 11130 } 11131 11132 /// Analyze the given compound assignment for the possible losing of 11133 /// floating-point precision. 11134 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11135 assert(isa<CompoundAssignOperator>(E) && 11136 "Must be compound assignment operation"); 11137 // Recurse on the LHS and RHS in here 11138 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11139 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11140 11141 if (E->getLHS()->getType()->isAtomicType()) 11142 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11143 11144 // Now check the outermost expression 11145 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11146 const auto *RBT = cast<CompoundAssignOperator>(E) 11147 ->getComputationResultType() 11148 ->getAs<BuiltinType>(); 11149 11150 // The below checks assume source is floating point. 11151 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11152 11153 // If source is floating point but target is an integer. 11154 if (ResultBT->isInteger()) 11155 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11156 E->getExprLoc(), diag::warn_impcast_float_integer); 11157 11158 if (!ResultBT->isFloatingPoint()) 11159 return; 11160 11161 // If both source and target are floating points, warn about losing precision. 11162 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11163 QualType(ResultBT, 0), QualType(RBT, 0)); 11164 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11165 // warn about dropping FP rank. 11166 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11167 diag::warn_impcast_float_result_precision); 11168 } 11169 11170 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11171 IntRange Range) { 11172 if (!Range.Width) return "0"; 11173 11174 llvm::APSInt ValueInRange = Value; 11175 ValueInRange.setIsSigned(!Range.NonNegative); 11176 ValueInRange = ValueInRange.trunc(Range.Width); 11177 return ValueInRange.toString(10); 11178 } 11179 11180 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11181 if (!isa<ImplicitCastExpr>(Ex)) 11182 return false; 11183 11184 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11185 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11186 const Type *Source = 11187 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11188 if (Target->isDependentType()) 11189 return false; 11190 11191 const BuiltinType *FloatCandidateBT = 11192 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11193 const Type *BoolCandidateType = ToBool ? Target : Source; 11194 11195 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11196 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11197 } 11198 11199 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11200 SourceLocation CC) { 11201 unsigned NumArgs = TheCall->getNumArgs(); 11202 for (unsigned i = 0; i < NumArgs; ++i) { 11203 Expr *CurrA = TheCall->getArg(i); 11204 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11205 continue; 11206 11207 bool IsSwapped = ((i > 0) && 11208 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11209 IsSwapped |= ((i < (NumArgs - 1)) && 11210 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11211 if (IsSwapped) { 11212 // Warn on this floating-point to bool conversion. 11213 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11214 CurrA->getType(), CC, 11215 diag::warn_impcast_floating_point_to_bool); 11216 } 11217 } 11218 } 11219 11220 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11221 SourceLocation CC) { 11222 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11223 E->getExprLoc())) 11224 return; 11225 11226 // Don't warn on functions which have return type nullptr_t. 11227 if (isa<CallExpr>(E)) 11228 return; 11229 11230 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11231 const Expr::NullPointerConstantKind NullKind = 11232 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11233 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11234 return; 11235 11236 // Return if target type is a safe conversion. 11237 if (T->isAnyPointerType() || T->isBlockPointerType() || 11238 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11239 return; 11240 11241 SourceLocation Loc = E->getSourceRange().getBegin(); 11242 11243 // Venture through the macro stacks to get to the source of macro arguments. 11244 // The new location is a better location than the complete location that was 11245 // passed in. 11246 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11247 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11248 11249 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11250 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11251 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11252 Loc, S.SourceMgr, S.getLangOpts()); 11253 if (MacroName == "NULL") 11254 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11255 } 11256 11257 // Only warn if the null and context location are in the same macro expansion. 11258 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11259 return; 11260 11261 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11262 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11263 << FixItHint::CreateReplacement(Loc, 11264 S.getFixItZeroLiteralForType(T, Loc)); 11265 } 11266 11267 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11268 ObjCArrayLiteral *ArrayLiteral); 11269 11270 static void 11271 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11272 ObjCDictionaryLiteral *DictionaryLiteral); 11273 11274 /// Check a single element within a collection literal against the 11275 /// target element type. 11276 static void checkObjCCollectionLiteralElement(Sema &S, 11277 QualType TargetElementType, 11278 Expr *Element, 11279 unsigned ElementKind) { 11280 // Skip a bitcast to 'id' or qualified 'id'. 11281 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11282 if (ICE->getCastKind() == CK_BitCast && 11283 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11284 Element = ICE->getSubExpr(); 11285 } 11286 11287 QualType ElementType = Element->getType(); 11288 ExprResult ElementResult(Element); 11289 if (ElementType->getAs<ObjCObjectPointerType>() && 11290 S.CheckSingleAssignmentConstraints(TargetElementType, 11291 ElementResult, 11292 false, false) 11293 != Sema::Compatible) { 11294 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11295 << ElementType << ElementKind << TargetElementType 11296 << Element->getSourceRange(); 11297 } 11298 11299 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11300 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11301 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11302 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11303 } 11304 11305 /// Check an Objective-C array literal being converted to the given 11306 /// target type. 11307 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11308 ObjCArrayLiteral *ArrayLiteral) { 11309 if (!S.NSArrayDecl) 11310 return; 11311 11312 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11313 if (!TargetObjCPtr) 11314 return; 11315 11316 if (TargetObjCPtr->isUnspecialized() || 11317 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11318 != S.NSArrayDecl->getCanonicalDecl()) 11319 return; 11320 11321 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11322 if (TypeArgs.size() != 1) 11323 return; 11324 11325 QualType TargetElementType = TypeArgs[0]; 11326 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11327 checkObjCCollectionLiteralElement(S, TargetElementType, 11328 ArrayLiteral->getElement(I), 11329 0); 11330 } 11331 } 11332 11333 /// Check an Objective-C dictionary literal being converted to the given 11334 /// target type. 11335 static void 11336 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11337 ObjCDictionaryLiteral *DictionaryLiteral) { 11338 if (!S.NSDictionaryDecl) 11339 return; 11340 11341 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11342 if (!TargetObjCPtr) 11343 return; 11344 11345 if (TargetObjCPtr->isUnspecialized() || 11346 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11347 != S.NSDictionaryDecl->getCanonicalDecl()) 11348 return; 11349 11350 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11351 if (TypeArgs.size() != 2) 11352 return; 11353 11354 QualType TargetKeyType = TypeArgs[0]; 11355 QualType TargetObjectType = TypeArgs[1]; 11356 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11357 auto Element = DictionaryLiteral->getKeyValueElement(I); 11358 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11359 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11360 } 11361 } 11362 11363 // Helper function to filter out cases for constant width constant conversion. 11364 // Don't warn on char array initialization or for non-decimal values. 11365 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11366 SourceLocation CC) { 11367 // If initializing from a constant, and the constant starts with '0', 11368 // then it is a binary, octal, or hexadecimal. Allow these constants 11369 // to fill all the bits, even if there is a sign change. 11370 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11371 const char FirstLiteralCharacter = 11372 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11373 if (FirstLiteralCharacter == '0') 11374 return false; 11375 } 11376 11377 // If the CC location points to a '{', and the type is char, then assume 11378 // assume it is an array initialization. 11379 if (CC.isValid() && T->isCharType()) { 11380 const char FirstContextCharacter = 11381 S.getSourceManager().getCharacterData(CC)[0]; 11382 if (FirstContextCharacter == '{') 11383 return false; 11384 } 11385 11386 return true; 11387 } 11388 11389 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11390 const auto *IL = dyn_cast<IntegerLiteral>(E); 11391 if (!IL) { 11392 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11393 if (UO->getOpcode() == UO_Minus) 11394 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11395 } 11396 } 11397 11398 return IL; 11399 } 11400 11401 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11402 E = E->IgnoreParenImpCasts(); 11403 SourceLocation ExprLoc = E->getExprLoc(); 11404 11405 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11406 BinaryOperator::Opcode Opc = BO->getOpcode(); 11407 Expr::EvalResult Result; 11408 // Do not diagnose unsigned shifts. 11409 if (Opc == BO_Shl) { 11410 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11411 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11412 if (LHS && LHS->getValue() == 0) 11413 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11414 else if (!E->isValueDependent() && LHS && RHS && 11415 RHS->getValue().isNonNegative() && 11416 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11417 S.Diag(ExprLoc, diag::warn_left_shift_always) 11418 << (Result.Val.getInt() != 0); 11419 else if (E->getType()->isSignedIntegerType()) 11420 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11421 } 11422 } 11423 11424 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11425 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11426 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11427 if (!LHS || !RHS) 11428 return; 11429 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11430 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11431 // Do not diagnose common idioms. 11432 return; 11433 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11434 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11435 } 11436 } 11437 11438 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11439 SourceLocation CC, 11440 bool *ICContext = nullptr, 11441 bool IsListInit = false) { 11442 if (E->isTypeDependent() || E->isValueDependent()) return; 11443 11444 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11445 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11446 if (Source == Target) return; 11447 if (Target->isDependentType()) return; 11448 11449 // If the conversion context location is invalid don't complain. We also 11450 // don't want to emit a warning if the issue occurs from the expansion of 11451 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11452 // delay this check as long as possible. Once we detect we are in that 11453 // scenario, we just return. 11454 if (CC.isInvalid()) 11455 return; 11456 11457 if (Source->isAtomicType()) 11458 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11459 11460 // Diagnose implicit casts to bool. 11461 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11462 if (isa<StringLiteral>(E)) 11463 // Warn on string literal to bool. Checks for string literals in logical 11464 // and expressions, for instance, assert(0 && "error here"), are 11465 // prevented by a check in AnalyzeImplicitConversions(). 11466 return DiagnoseImpCast(S, E, T, CC, 11467 diag::warn_impcast_string_literal_to_bool); 11468 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11469 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11470 // This covers the literal expressions that evaluate to Objective-C 11471 // objects. 11472 return DiagnoseImpCast(S, E, T, CC, 11473 diag::warn_impcast_objective_c_literal_to_bool); 11474 } 11475 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11476 // Warn on pointer to bool conversion that is always true. 11477 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11478 SourceRange(CC)); 11479 } 11480 } 11481 11482 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11483 // is a typedef for signed char (macOS), then that constant value has to be 1 11484 // or 0. 11485 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11486 Expr::EvalResult Result; 11487 if (E->EvaluateAsInt(Result, S.getASTContext(), 11488 Expr::SE_AllowSideEffects)) { 11489 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11490 adornObjCBoolConversionDiagWithTernaryFixit( 11491 S, E, 11492 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11493 << Result.Val.getInt().toString(10)); 11494 } 11495 return; 11496 } 11497 } 11498 11499 // Check implicit casts from Objective-C collection literals to specialized 11500 // collection types, e.g., NSArray<NSString *> *. 11501 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11502 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11503 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11504 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11505 11506 // Strip vector types. 11507 if (isa<VectorType>(Source)) { 11508 if (!isa<VectorType>(Target)) { 11509 if (S.SourceMgr.isInSystemMacro(CC)) 11510 return; 11511 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11512 } 11513 11514 // If the vector cast is cast between two vectors of the same size, it is 11515 // a bitcast, not a conversion. 11516 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11517 return; 11518 11519 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11520 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11521 } 11522 if (auto VecTy = dyn_cast<VectorType>(Target)) 11523 Target = VecTy->getElementType().getTypePtr(); 11524 11525 // Strip complex types. 11526 if (isa<ComplexType>(Source)) { 11527 if (!isa<ComplexType>(Target)) { 11528 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11529 return; 11530 11531 return DiagnoseImpCast(S, E, T, CC, 11532 S.getLangOpts().CPlusPlus 11533 ? diag::err_impcast_complex_scalar 11534 : diag::warn_impcast_complex_scalar); 11535 } 11536 11537 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11538 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11539 } 11540 11541 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11542 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11543 11544 // If the source is floating point... 11545 if (SourceBT && SourceBT->isFloatingPoint()) { 11546 // ...and the target is floating point... 11547 if (TargetBT && TargetBT->isFloatingPoint()) { 11548 // ...then warn if we're dropping FP rank. 11549 11550 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11551 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11552 if (Order > 0) { 11553 // Don't warn about float constants that are precisely 11554 // representable in the target type. 11555 Expr::EvalResult result; 11556 if (E->EvaluateAsRValue(result, S.Context)) { 11557 // Value might be a float, a float vector, or a float complex. 11558 if (IsSameFloatAfterCast(result.Val, 11559 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11560 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11561 return; 11562 } 11563 11564 if (S.SourceMgr.isInSystemMacro(CC)) 11565 return; 11566 11567 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11568 } 11569 // ... or possibly if we're increasing rank, too 11570 else if (Order < 0) { 11571 if (S.SourceMgr.isInSystemMacro(CC)) 11572 return; 11573 11574 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11575 } 11576 return; 11577 } 11578 11579 // If the target is integral, always warn. 11580 if (TargetBT && TargetBT->isInteger()) { 11581 if (S.SourceMgr.isInSystemMacro(CC)) 11582 return; 11583 11584 DiagnoseFloatingImpCast(S, E, T, CC); 11585 } 11586 11587 // Detect the case where a call result is converted from floating-point to 11588 // to bool, and the final argument to the call is converted from bool, to 11589 // discover this typo: 11590 // 11591 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11592 // 11593 // FIXME: This is an incredibly special case; is there some more general 11594 // way to detect this class of misplaced-parentheses bug? 11595 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11596 // Check last argument of function call to see if it is an 11597 // implicit cast from a type matching the type the result 11598 // is being cast to. 11599 CallExpr *CEx = cast<CallExpr>(E); 11600 if (unsigned NumArgs = CEx->getNumArgs()) { 11601 Expr *LastA = CEx->getArg(NumArgs - 1); 11602 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11603 if (isa<ImplicitCastExpr>(LastA) && 11604 InnerE->getType()->isBooleanType()) { 11605 // Warn on this floating-point to bool conversion 11606 DiagnoseImpCast(S, E, T, CC, 11607 diag::warn_impcast_floating_point_to_bool); 11608 } 11609 } 11610 } 11611 return; 11612 } 11613 11614 // Valid casts involving fixed point types should be accounted for here. 11615 if (Source->isFixedPointType()) { 11616 if (Target->isUnsaturatedFixedPointType()) { 11617 Expr::EvalResult Result; 11618 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11619 S.isConstantEvaluated())) { 11620 APFixedPoint Value = Result.Val.getFixedPoint(); 11621 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11622 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11623 if (Value > MaxVal || Value < MinVal) { 11624 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11625 S.PDiag(diag::warn_impcast_fixed_point_range) 11626 << Value.toString() << T 11627 << E->getSourceRange() 11628 << clang::SourceRange(CC)); 11629 return; 11630 } 11631 } 11632 } else if (Target->isIntegerType()) { 11633 Expr::EvalResult Result; 11634 if (!S.isConstantEvaluated() && 11635 E->EvaluateAsFixedPoint(Result, S.Context, 11636 Expr::SE_AllowSideEffects)) { 11637 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11638 11639 bool Overflowed; 11640 llvm::APSInt IntResult = FXResult.convertToInt( 11641 S.Context.getIntWidth(T), 11642 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11643 11644 if (Overflowed) { 11645 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11646 S.PDiag(diag::warn_impcast_fixed_point_range) 11647 << FXResult.toString() << T 11648 << E->getSourceRange() 11649 << clang::SourceRange(CC)); 11650 return; 11651 } 11652 } 11653 } 11654 } else if (Target->isUnsaturatedFixedPointType()) { 11655 if (Source->isIntegerType()) { 11656 Expr::EvalResult Result; 11657 if (!S.isConstantEvaluated() && 11658 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11659 llvm::APSInt Value = Result.Val.getInt(); 11660 11661 bool Overflowed; 11662 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11663 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11664 11665 if (Overflowed) { 11666 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11667 S.PDiag(diag::warn_impcast_fixed_point_range) 11668 << Value.toString(/*Radix=*/10) << T 11669 << E->getSourceRange() 11670 << clang::SourceRange(CC)); 11671 return; 11672 } 11673 } 11674 } 11675 } 11676 11677 // If we are casting an integer type to a floating point type without 11678 // initialization-list syntax, we might lose accuracy if the floating 11679 // point type has a narrower significand than the integer type. 11680 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11681 TargetBT->isFloatingType() && !IsListInit) { 11682 // Determine the number of precision bits in the source integer type. 11683 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11684 unsigned int SourcePrecision = SourceRange.Width; 11685 11686 // Determine the number of precision bits in the 11687 // target floating point type. 11688 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11689 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11690 11691 if (SourcePrecision > 0 && TargetPrecision > 0 && 11692 SourcePrecision > TargetPrecision) { 11693 11694 llvm::APSInt SourceInt; 11695 if (E->isIntegerConstantExpr(SourceInt, S.Context)) { 11696 // If the source integer is a constant, convert it to the target 11697 // floating point type. Issue a warning if the value changes 11698 // during the whole conversion. 11699 llvm::APFloat TargetFloatValue( 11700 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11701 llvm::APFloat::opStatus ConversionStatus = 11702 TargetFloatValue.convertFromAPInt( 11703 SourceInt, SourceBT->isSignedInteger(), 11704 llvm::APFloat::rmNearestTiesToEven); 11705 11706 if (ConversionStatus != llvm::APFloat::opOK) { 11707 std::string PrettySourceValue = SourceInt.toString(10); 11708 SmallString<32> PrettyTargetValue; 11709 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11710 11711 S.DiagRuntimeBehavior( 11712 E->getExprLoc(), E, 11713 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11714 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11715 << E->getSourceRange() << clang::SourceRange(CC)); 11716 } 11717 } else { 11718 // Otherwise, the implicit conversion may lose precision. 11719 DiagnoseImpCast(S, E, T, CC, 11720 diag::warn_impcast_integer_float_precision); 11721 } 11722 } 11723 } 11724 11725 DiagnoseNullConversion(S, E, T, CC); 11726 11727 S.DiscardMisalignedMemberAddress(Target, E); 11728 11729 if (Target->isBooleanType()) 11730 DiagnoseIntInBoolContext(S, E); 11731 11732 if (!Source->isIntegerType() || !Target->isIntegerType()) 11733 return; 11734 11735 // TODO: remove this early return once the false positives for constant->bool 11736 // in templates, macros, etc, are reduced or removed. 11737 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11738 return; 11739 11740 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11741 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11742 return adornObjCBoolConversionDiagWithTernaryFixit( 11743 S, E, 11744 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11745 << E->getType()); 11746 } 11747 11748 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11749 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11750 11751 if (SourceRange.Width > TargetRange.Width) { 11752 // If the source is a constant, use a default-on diagnostic. 11753 // TODO: this should happen for bitfield stores, too. 11754 Expr::EvalResult Result; 11755 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11756 S.isConstantEvaluated())) { 11757 llvm::APSInt Value(32); 11758 Value = Result.Val.getInt(); 11759 11760 if (S.SourceMgr.isInSystemMacro(CC)) 11761 return; 11762 11763 std::string PrettySourceValue = Value.toString(10); 11764 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11765 11766 S.DiagRuntimeBehavior( 11767 E->getExprLoc(), E, 11768 S.PDiag(diag::warn_impcast_integer_precision_constant) 11769 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11770 << E->getSourceRange() << clang::SourceRange(CC)); 11771 return; 11772 } 11773 11774 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11775 if (S.SourceMgr.isInSystemMacro(CC)) 11776 return; 11777 11778 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11779 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11780 /* pruneControlFlow */ true); 11781 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11782 } 11783 11784 if (TargetRange.Width > SourceRange.Width) { 11785 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11786 if (UO->getOpcode() == UO_Minus) 11787 if (Source->isUnsignedIntegerType()) { 11788 if (Target->isUnsignedIntegerType()) 11789 return DiagnoseImpCast(S, E, T, CC, 11790 diag::warn_impcast_high_order_zero_bits); 11791 if (Target->isSignedIntegerType()) 11792 return DiagnoseImpCast(S, E, T, CC, 11793 diag::warn_impcast_nonnegative_result); 11794 } 11795 } 11796 11797 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11798 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11799 // Warn when doing a signed to signed conversion, warn if the positive 11800 // source value is exactly the width of the target type, which will 11801 // cause a negative value to be stored. 11802 11803 Expr::EvalResult Result; 11804 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11805 !S.SourceMgr.isInSystemMacro(CC)) { 11806 llvm::APSInt Value = Result.Val.getInt(); 11807 if (isSameWidthConstantConversion(S, E, T, CC)) { 11808 std::string PrettySourceValue = Value.toString(10); 11809 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11810 11811 S.DiagRuntimeBehavior( 11812 E->getExprLoc(), E, 11813 S.PDiag(diag::warn_impcast_integer_precision_constant) 11814 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11815 << E->getSourceRange() << clang::SourceRange(CC)); 11816 return; 11817 } 11818 } 11819 11820 // Fall through for non-constants to give a sign conversion warning. 11821 } 11822 11823 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11824 (!TargetRange.NonNegative && SourceRange.NonNegative && 11825 SourceRange.Width == TargetRange.Width)) { 11826 if (S.SourceMgr.isInSystemMacro(CC)) 11827 return; 11828 11829 unsigned DiagID = diag::warn_impcast_integer_sign; 11830 11831 // Traditionally, gcc has warned about this under -Wsign-compare. 11832 // We also want to warn about it in -Wconversion. 11833 // So if -Wconversion is off, use a completely identical diagnostic 11834 // in the sign-compare group. 11835 // The conditional-checking code will 11836 if (ICContext) { 11837 DiagID = diag::warn_impcast_integer_sign_conditional; 11838 *ICContext = true; 11839 } 11840 11841 return DiagnoseImpCast(S, E, T, CC, DiagID); 11842 } 11843 11844 // Diagnose conversions between different enumeration types. 11845 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11846 // type, to give us better diagnostics. 11847 QualType SourceType = E->getType(); 11848 if (!S.getLangOpts().CPlusPlus) { 11849 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11850 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11851 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11852 SourceType = S.Context.getTypeDeclType(Enum); 11853 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11854 } 11855 } 11856 11857 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11858 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11859 if (SourceEnum->getDecl()->hasNameForLinkage() && 11860 TargetEnum->getDecl()->hasNameForLinkage() && 11861 SourceEnum != TargetEnum) { 11862 if (S.SourceMgr.isInSystemMacro(CC)) 11863 return; 11864 11865 return DiagnoseImpCast(S, E, SourceType, T, CC, 11866 diag::warn_impcast_different_enum_types); 11867 } 11868 } 11869 11870 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11871 SourceLocation CC, QualType T); 11872 11873 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11874 SourceLocation CC, bool &ICContext) { 11875 E = E->IgnoreParenImpCasts(); 11876 11877 if (isa<ConditionalOperator>(E)) 11878 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11879 11880 AnalyzeImplicitConversions(S, E, CC); 11881 if (E->getType() != T) 11882 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11883 } 11884 11885 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11886 SourceLocation CC, QualType T) { 11887 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11888 11889 bool Suspicious = false; 11890 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11891 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11892 11893 if (T->isBooleanType()) 11894 DiagnoseIntInBoolContext(S, E); 11895 11896 // If -Wconversion would have warned about either of the candidates 11897 // for a signedness conversion to the context type... 11898 if (!Suspicious) return; 11899 11900 // ...but it's currently ignored... 11901 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11902 return; 11903 11904 // ...then check whether it would have warned about either of the 11905 // candidates for a signedness conversion to the condition type. 11906 if (E->getType() == T) return; 11907 11908 Suspicious = false; 11909 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11910 E->getType(), CC, &Suspicious); 11911 if (!Suspicious) 11912 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11913 E->getType(), CC, &Suspicious); 11914 } 11915 11916 /// Check conversion of given expression to boolean. 11917 /// Input argument E is a logical expression. 11918 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11919 if (S.getLangOpts().Bool) 11920 return; 11921 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11922 return; 11923 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11924 } 11925 11926 namespace { 11927 struct AnalyzeImplicitConversionsWorkItem { 11928 Expr *E; 11929 SourceLocation CC; 11930 bool IsListInit; 11931 }; 11932 } 11933 11934 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 11935 /// that should be visited are added to WorkList. 11936 static void AnalyzeImplicitConversions( 11937 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 11938 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 11939 Expr *OrigE = Item.E; 11940 SourceLocation CC = Item.CC; 11941 11942 QualType T = OrigE->getType(); 11943 Expr *E = OrigE->IgnoreParenImpCasts(); 11944 11945 // Propagate whether we are in a C++ list initialization expression. 11946 // If so, we do not issue warnings for implicit int-float conversion 11947 // precision loss, because C++11 narrowing already handles it. 11948 bool IsListInit = Item.IsListInit || 11949 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 11950 11951 if (E->isTypeDependent() || E->isValueDependent()) 11952 return; 11953 11954 Expr *SourceExpr = E; 11955 // Examine, but don't traverse into the source expression of an 11956 // OpaqueValueExpr, since it may have multiple parents and we don't want to 11957 // emit duplicate diagnostics. Its fine to examine the form or attempt to 11958 // evaluate it in the context of checking the specific conversion to T though. 11959 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11960 if (auto *Src = OVE->getSourceExpr()) 11961 SourceExpr = Src; 11962 11963 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 11964 if (UO->getOpcode() == UO_Not && 11965 UO->getSubExpr()->isKnownToHaveBooleanValue()) 11966 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 11967 << OrigE->getSourceRange() << T->isBooleanType() 11968 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 11969 11970 // For conditional operators, we analyze the arguments as if they 11971 // were being fed directly into the output. 11972 if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) { 11973 CheckConditionalOperator(S, CO, CC, T); 11974 return; 11975 } 11976 11977 // Check implicit argument conversions for function calls. 11978 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 11979 CheckImplicitArgumentConversions(S, Call, CC); 11980 11981 // Go ahead and check any implicit conversions we might have skipped. 11982 // The non-canonical typecheck is just an optimization; 11983 // CheckImplicitConversion will filter out dead implicit conversions. 11984 if (SourceExpr->getType() != T) 11985 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 11986 11987 // Now continue drilling into this expression. 11988 11989 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11990 // The bound subexpressions in a PseudoObjectExpr are not reachable 11991 // as transitive children. 11992 // FIXME: Use a more uniform representation for this. 11993 for (auto *SE : POE->semantics()) 11994 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11995 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 11996 } 11997 11998 // Skip past explicit casts. 11999 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12000 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12001 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12002 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12003 WorkList.push_back({E, CC, IsListInit}); 12004 return; 12005 } 12006 12007 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12008 // Do a somewhat different check with comparison operators. 12009 if (BO->isComparisonOp()) 12010 return AnalyzeComparison(S, BO); 12011 12012 // And with simple assignments. 12013 if (BO->getOpcode() == BO_Assign) 12014 return AnalyzeAssignment(S, BO); 12015 // And with compound assignments. 12016 if (BO->isAssignmentOp()) 12017 return AnalyzeCompoundAssignment(S, BO); 12018 } 12019 12020 // These break the otherwise-useful invariant below. Fortunately, 12021 // we don't really need to recurse into them, because any internal 12022 // expressions should have been analyzed already when they were 12023 // built into statements. 12024 if (isa<StmtExpr>(E)) return; 12025 12026 // Don't descend into unevaluated contexts. 12027 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12028 12029 // Now just recurse over the expression's children. 12030 CC = E->getExprLoc(); 12031 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12032 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12033 for (Stmt *SubStmt : E->children()) { 12034 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12035 if (!ChildExpr) 12036 continue; 12037 12038 if (IsLogicalAndOperator && 12039 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12040 // Ignore checking string literals that are in logical and operators. 12041 // This is a common pattern for asserts. 12042 continue; 12043 WorkList.push_back({ChildExpr, CC, IsListInit}); 12044 } 12045 12046 if (BO && BO->isLogicalOp()) { 12047 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12048 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12049 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12050 12051 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12052 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12053 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12054 } 12055 12056 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12057 if (U->getOpcode() == UO_LNot) { 12058 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12059 } else if (U->getOpcode() != UO_AddrOf) { 12060 if (U->getSubExpr()->getType()->isAtomicType()) 12061 S.Diag(U->getSubExpr()->getBeginLoc(), 12062 diag::warn_atomic_implicit_seq_cst); 12063 } 12064 } 12065 } 12066 12067 /// AnalyzeImplicitConversions - Find and report any interesting 12068 /// implicit conversions in the given expression. There are a couple 12069 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12070 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12071 bool IsListInit/*= false*/) { 12072 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12073 WorkList.push_back({OrigE, CC, IsListInit}); 12074 while (!WorkList.empty()) 12075 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12076 } 12077 12078 /// Diagnose integer type and any valid implicit conversion to it. 12079 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12080 // Taking into account implicit conversions, 12081 // allow any integer. 12082 if (!E->getType()->isIntegerType()) { 12083 S.Diag(E->getBeginLoc(), 12084 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12085 return true; 12086 } 12087 // Potentially emit standard warnings for implicit conversions if enabled 12088 // using -Wconversion. 12089 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12090 return false; 12091 } 12092 12093 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12094 // Returns true when emitting a warning about taking the address of a reference. 12095 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12096 const PartialDiagnostic &PD) { 12097 E = E->IgnoreParenImpCasts(); 12098 12099 const FunctionDecl *FD = nullptr; 12100 12101 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12102 if (!DRE->getDecl()->getType()->isReferenceType()) 12103 return false; 12104 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12105 if (!M->getMemberDecl()->getType()->isReferenceType()) 12106 return false; 12107 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12108 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12109 return false; 12110 FD = Call->getDirectCallee(); 12111 } else { 12112 return false; 12113 } 12114 12115 SemaRef.Diag(E->getExprLoc(), PD); 12116 12117 // If possible, point to location of function. 12118 if (FD) { 12119 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12120 } 12121 12122 return true; 12123 } 12124 12125 // Returns true if the SourceLocation is expanded from any macro body. 12126 // Returns false if the SourceLocation is invalid, is from not in a macro 12127 // expansion, or is from expanded from a top-level macro argument. 12128 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12129 if (Loc.isInvalid()) 12130 return false; 12131 12132 while (Loc.isMacroID()) { 12133 if (SM.isMacroBodyExpansion(Loc)) 12134 return true; 12135 Loc = SM.getImmediateMacroCallerLoc(Loc); 12136 } 12137 12138 return false; 12139 } 12140 12141 /// Diagnose pointers that are always non-null. 12142 /// \param E the expression containing the pointer 12143 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12144 /// compared to a null pointer 12145 /// \param IsEqual True when the comparison is equal to a null pointer 12146 /// \param Range Extra SourceRange to highlight in the diagnostic 12147 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12148 Expr::NullPointerConstantKind NullKind, 12149 bool IsEqual, SourceRange Range) { 12150 if (!E) 12151 return; 12152 12153 // Don't warn inside macros. 12154 if (E->getExprLoc().isMacroID()) { 12155 const SourceManager &SM = getSourceManager(); 12156 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12157 IsInAnyMacroBody(SM, Range.getBegin())) 12158 return; 12159 } 12160 E = E->IgnoreImpCasts(); 12161 12162 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12163 12164 if (isa<CXXThisExpr>(E)) { 12165 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12166 : diag::warn_this_bool_conversion; 12167 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12168 return; 12169 } 12170 12171 bool IsAddressOf = false; 12172 12173 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12174 if (UO->getOpcode() != UO_AddrOf) 12175 return; 12176 IsAddressOf = true; 12177 E = UO->getSubExpr(); 12178 } 12179 12180 if (IsAddressOf) { 12181 unsigned DiagID = IsCompare 12182 ? diag::warn_address_of_reference_null_compare 12183 : diag::warn_address_of_reference_bool_conversion; 12184 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12185 << IsEqual; 12186 if (CheckForReference(*this, E, PD)) { 12187 return; 12188 } 12189 } 12190 12191 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12192 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12193 std::string Str; 12194 llvm::raw_string_ostream S(Str); 12195 E->printPretty(S, nullptr, getPrintingPolicy()); 12196 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12197 : diag::warn_cast_nonnull_to_bool; 12198 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12199 << E->getSourceRange() << Range << IsEqual; 12200 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12201 }; 12202 12203 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12204 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12205 if (auto *Callee = Call->getDirectCallee()) { 12206 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12207 ComplainAboutNonnullParamOrCall(A); 12208 return; 12209 } 12210 } 12211 } 12212 12213 // Expect to find a single Decl. Skip anything more complicated. 12214 ValueDecl *D = nullptr; 12215 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12216 D = R->getDecl(); 12217 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12218 D = M->getMemberDecl(); 12219 } 12220 12221 // Weak Decls can be null. 12222 if (!D || D->isWeak()) 12223 return; 12224 12225 // Check for parameter decl with nonnull attribute 12226 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12227 if (getCurFunction() && 12228 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12229 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12230 ComplainAboutNonnullParamOrCall(A); 12231 return; 12232 } 12233 12234 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12235 // Skip function template not specialized yet. 12236 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12237 return; 12238 auto ParamIter = llvm::find(FD->parameters(), PV); 12239 assert(ParamIter != FD->param_end()); 12240 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12241 12242 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12243 if (!NonNull->args_size()) { 12244 ComplainAboutNonnullParamOrCall(NonNull); 12245 return; 12246 } 12247 12248 for (const ParamIdx &ArgNo : NonNull->args()) { 12249 if (ArgNo.getASTIndex() == ParamNo) { 12250 ComplainAboutNonnullParamOrCall(NonNull); 12251 return; 12252 } 12253 } 12254 } 12255 } 12256 } 12257 } 12258 12259 QualType T = D->getType(); 12260 const bool IsArray = T->isArrayType(); 12261 const bool IsFunction = T->isFunctionType(); 12262 12263 // Address of function is used to silence the function warning. 12264 if (IsAddressOf && IsFunction) { 12265 return; 12266 } 12267 12268 // Found nothing. 12269 if (!IsAddressOf && !IsFunction && !IsArray) 12270 return; 12271 12272 // Pretty print the expression for the diagnostic. 12273 std::string Str; 12274 llvm::raw_string_ostream S(Str); 12275 E->printPretty(S, nullptr, getPrintingPolicy()); 12276 12277 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12278 : diag::warn_impcast_pointer_to_bool; 12279 enum { 12280 AddressOf, 12281 FunctionPointer, 12282 ArrayPointer 12283 } DiagType; 12284 if (IsAddressOf) 12285 DiagType = AddressOf; 12286 else if (IsFunction) 12287 DiagType = FunctionPointer; 12288 else if (IsArray) 12289 DiagType = ArrayPointer; 12290 else 12291 llvm_unreachable("Could not determine diagnostic."); 12292 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12293 << Range << IsEqual; 12294 12295 if (!IsFunction) 12296 return; 12297 12298 // Suggest '&' to silence the function warning. 12299 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12300 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12301 12302 // Check to see if '()' fixit should be emitted. 12303 QualType ReturnType; 12304 UnresolvedSet<4> NonTemplateOverloads; 12305 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12306 if (ReturnType.isNull()) 12307 return; 12308 12309 if (IsCompare) { 12310 // There are two cases here. If there is null constant, the only suggest 12311 // for a pointer return type. If the null is 0, then suggest if the return 12312 // type is a pointer or an integer type. 12313 if (!ReturnType->isPointerType()) { 12314 if (NullKind == Expr::NPCK_ZeroExpression || 12315 NullKind == Expr::NPCK_ZeroLiteral) { 12316 if (!ReturnType->isIntegerType()) 12317 return; 12318 } else { 12319 return; 12320 } 12321 } 12322 } else { // !IsCompare 12323 // For function to bool, only suggest if the function pointer has bool 12324 // return type. 12325 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12326 return; 12327 } 12328 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12329 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12330 } 12331 12332 /// Diagnoses "dangerous" implicit conversions within the given 12333 /// expression (which is a full expression). Implements -Wconversion 12334 /// and -Wsign-compare. 12335 /// 12336 /// \param CC the "context" location of the implicit conversion, i.e. 12337 /// the most location of the syntactic entity requiring the implicit 12338 /// conversion 12339 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12340 // Don't diagnose in unevaluated contexts. 12341 if (isUnevaluatedContext()) 12342 return; 12343 12344 // Don't diagnose for value- or type-dependent expressions. 12345 if (E->isTypeDependent() || E->isValueDependent()) 12346 return; 12347 12348 // Check for array bounds violations in cases where the check isn't triggered 12349 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12350 // ArraySubscriptExpr is on the RHS of a variable initialization. 12351 CheckArrayAccess(E); 12352 12353 // This is not the right CC for (e.g.) a variable initialization. 12354 AnalyzeImplicitConversions(*this, E, CC); 12355 } 12356 12357 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12358 /// Input argument E is a logical expression. 12359 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12360 ::CheckBoolLikeConversion(*this, E, CC); 12361 } 12362 12363 /// Diagnose when expression is an integer constant expression and its evaluation 12364 /// results in integer overflow 12365 void Sema::CheckForIntOverflow (Expr *E) { 12366 // Use a work list to deal with nested struct initializers. 12367 SmallVector<Expr *, 2> Exprs(1, E); 12368 12369 do { 12370 Expr *OriginalE = Exprs.pop_back_val(); 12371 Expr *E = OriginalE->IgnoreParenCasts(); 12372 12373 if (isa<BinaryOperator>(E)) { 12374 E->EvaluateForOverflow(Context); 12375 continue; 12376 } 12377 12378 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12379 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12380 else if (isa<ObjCBoxedExpr>(OriginalE)) 12381 E->EvaluateForOverflow(Context); 12382 else if (auto Call = dyn_cast<CallExpr>(E)) 12383 Exprs.append(Call->arg_begin(), Call->arg_end()); 12384 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12385 Exprs.append(Message->arg_begin(), Message->arg_end()); 12386 } while (!Exprs.empty()); 12387 } 12388 12389 namespace { 12390 12391 /// Visitor for expressions which looks for unsequenced operations on the 12392 /// same object. 12393 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12394 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12395 12396 /// A tree of sequenced regions within an expression. Two regions are 12397 /// unsequenced if one is an ancestor or a descendent of the other. When we 12398 /// finish processing an expression with sequencing, such as a comma 12399 /// expression, we fold its tree nodes into its parent, since they are 12400 /// unsequenced with respect to nodes we will visit later. 12401 class SequenceTree { 12402 struct Value { 12403 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12404 unsigned Parent : 31; 12405 unsigned Merged : 1; 12406 }; 12407 SmallVector<Value, 8> Values; 12408 12409 public: 12410 /// A region within an expression which may be sequenced with respect 12411 /// to some other region. 12412 class Seq { 12413 friend class SequenceTree; 12414 12415 unsigned Index; 12416 12417 explicit Seq(unsigned N) : Index(N) {} 12418 12419 public: 12420 Seq() : Index(0) {} 12421 }; 12422 12423 SequenceTree() { Values.push_back(Value(0)); } 12424 Seq root() const { return Seq(0); } 12425 12426 /// Create a new sequence of operations, which is an unsequenced 12427 /// subset of \p Parent. This sequence of operations is sequenced with 12428 /// respect to other children of \p Parent. 12429 Seq allocate(Seq Parent) { 12430 Values.push_back(Value(Parent.Index)); 12431 return Seq(Values.size() - 1); 12432 } 12433 12434 /// Merge a sequence of operations into its parent. 12435 void merge(Seq S) { 12436 Values[S.Index].Merged = true; 12437 } 12438 12439 /// Determine whether two operations are unsequenced. This operation 12440 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12441 /// should have been merged into its parent as appropriate. 12442 bool isUnsequenced(Seq Cur, Seq Old) { 12443 unsigned C = representative(Cur.Index); 12444 unsigned Target = representative(Old.Index); 12445 while (C >= Target) { 12446 if (C == Target) 12447 return true; 12448 C = Values[C].Parent; 12449 } 12450 return false; 12451 } 12452 12453 private: 12454 /// Pick a representative for a sequence. 12455 unsigned representative(unsigned K) { 12456 if (Values[K].Merged) 12457 // Perform path compression as we go. 12458 return Values[K].Parent = representative(Values[K].Parent); 12459 return K; 12460 } 12461 }; 12462 12463 /// An object for which we can track unsequenced uses. 12464 using Object = const NamedDecl *; 12465 12466 /// Different flavors of object usage which we track. We only track the 12467 /// least-sequenced usage of each kind. 12468 enum UsageKind { 12469 /// A read of an object. Multiple unsequenced reads are OK. 12470 UK_Use, 12471 12472 /// A modification of an object which is sequenced before the value 12473 /// computation of the expression, such as ++n in C++. 12474 UK_ModAsValue, 12475 12476 /// A modification of an object which is not sequenced before the value 12477 /// computation of the expression, such as n++. 12478 UK_ModAsSideEffect, 12479 12480 UK_Count = UK_ModAsSideEffect + 1 12481 }; 12482 12483 /// Bundle together a sequencing region and the expression corresponding 12484 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12485 struct Usage { 12486 const Expr *UsageExpr; 12487 SequenceTree::Seq Seq; 12488 12489 Usage() : UsageExpr(nullptr), Seq() {} 12490 }; 12491 12492 struct UsageInfo { 12493 Usage Uses[UK_Count]; 12494 12495 /// Have we issued a diagnostic for this object already? 12496 bool Diagnosed; 12497 12498 UsageInfo() : Uses(), Diagnosed(false) {} 12499 }; 12500 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12501 12502 Sema &SemaRef; 12503 12504 /// Sequenced regions within the expression. 12505 SequenceTree Tree; 12506 12507 /// Declaration modifications and references which we have seen. 12508 UsageInfoMap UsageMap; 12509 12510 /// The region we are currently within. 12511 SequenceTree::Seq Region; 12512 12513 /// Filled in with declarations which were modified as a side-effect 12514 /// (that is, post-increment operations). 12515 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12516 12517 /// Expressions to check later. We defer checking these to reduce 12518 /// stack usage. 12519 SmallVectorImpl<const Expr *> &WorkList; 12520 12521 /// RAII object wrapping the visitation of a sequenced subexpression of an 12522 /// expression. At the end of this process, the side-effects of the evaluation 12523 /// become sequenced with respect to the value computation of the result, so 12524 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12525 /// UK_ModAsValue. 12526 struct SequencedSubexpression { 12527 SequencedSubexpression(SequenceChecker &Self) 12528 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12529 Self.ModAsSideEffect = &ModAsSideEffect; 12530 } 12531 12532 ~SequencedSubexpression() { 12533 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12534 // Add a new usage with usage kind UK_ModAsValue, and then restore 12535 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12536 // the previous one was empty). 12537 UsageInfo &UI = Self.UsageMap[M.first]; 12538 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12539 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12540 SideEffectUsage = M.second; 12541 } 12542 Self.ModAsSideEffect = OldModAsSideEffect; 12543 } 12544 12545 SequenceChecker &Self; 12546 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12547 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12548 }; 12549 12550 /// RAII object wrapping the visitation of a subexpression which we might 12551 /// choose to evaluate as a constant. If any subexpression is evaluated and 12552 /// found to be non-constant, this allows us to suppress the evaluation of 12553 /// the outer expression. 12554 class EvaluationTracker { 12555 public: 12556 EvaluationTracker(SequenceChecker &Self) 12557 : Self(Self), Prev(Self.EvalTracker) { 12558 Self.EvalTracker = this; 12559 } 12560 12561 ~EvaluationTracker() { 12562 Self.EvalTracker = Prev; 12563 if (Prev) 12564 Prev->EvalOK &= EvalOK; 12565 } 12566 12567 bool evaluate(const Expr *E, bool &Result) { 12568 if (!EvalOK || E->isValueDependent()) 12569 return false; 12570 EvalOK = E->EvaluateAsBooleanCondition( 12571 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12572 return EvalOK; 12573 } 12574 12575 private: 12576 SequenceChecker &Self; 12577 EvaluationTracker *Prev; 12578 bool EvalOK = true; 12579 } *EvalTracker = nullptr; 12580 12581 /// Find the object which is produced by the specified expression, 12582 /// if any. 12583 Object getObject(const Expr *E, bool Mod) const { 12584 E = E->IgnoreParenCasts(); 12585 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12586 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12587 return getObject(UO->getSubExpr(), Mod); 12588 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12589 if (BO->getOpcode() == BO_Comma) 12590 return getObject(BO->getRHS(), Mod); 12591 if (Mod && BO->isAssignmentOp()) 12592 return getObject(BO->getLHS(), Mod); 12593 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12594 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12595 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12596 return ME->getMemberDecl(); 12597 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12598 // FIXME: If this is a reference, map through to its value. 12599 return DRE->getDecl(); 12600 return nullptr; 12601 } 12602 12603 /// Note that an object \p O was modified or used by an expression 12604 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12605 /// the object \p O as obtained via the \p UsageMap. 12606 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12607 // Get the old usage for the given object and usage kind. 12608 Usage &U = UI.Uses[UK]; 12609 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12610 // If we have a modification as side effect and are in a sequenced 12611 // subexpression, save the old Usage so that we can restore it later 12612 // in SequencedSubexpression::~SequencedSubexpression. 12613 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12614 ModAsSideEffect->push_back(std::make_pair(O, U)); 12615 // Then record the new usage with the current sequencing region. 12616 U.UsageExpr = UsageExpr; 12617 U.Seq = Region; 12618 } 12619 } 12620 12621 /// Check whether a modification or use of an object \p O in an expression 12622 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12623 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12624 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12625 /// usage and false we are checking for a mod-use unsequenced usage. 12626 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12627 UsageKind OtherKind, bool IsModMod) { 12628 if (UI.Diagnosed) 12629 return; 12630 12631 const Usage &U = UI.Uses[OtherKind]; 12632 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12633 return; 12634 12635 const Expr *Mod = U.UsageExpr; 12636 const Expr *ModOrUse = UsageExpr; 12637 if (OtherKind == UK_Use) 12638 std::swap(Mod, ModOrUse); 12639 12640 SemaRef.DiagRuntimeBehavior( 12641 Mod->getExprLoc(), {Mod, ModOrUse}, 12642 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12643 : diag::warn_unsequenced_mod_use) 12644 << O << SourceRange(ModOrUse->getExprLoc())); 12645 UI.Diagnosed = true; 12646 } 12647 12648 // A note on note{Pre, Post}{Use, Mod}: 12649 // 12650 // (It helps to follow the algorithm with an expression such as 12651 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12652 // operations before C++17 and both are well-defined in C++17). 12653 // 12654 // When visiting a node which uses/modify an object we first call notePreUse 12655 // or notePreMod before visiting its sub-expression(s). At this point the 12656 // children of the current node have not yet been visited and so the eventual 12657 // uses/modifications resulting from the children of the current node have not 12658 // been recorded yet. 12659 // 12660 // We then visit the children of the current node. After that notePostUse or 12661 // notePostMod is called. These will 1) detect an unsequenced modification 12662 // as side effect (as in "k++ + k") and 2) add a new usage with the 12663 // appropriate usage kind. 12664 // 12665 // We also have to be careful that some operation sequences modification as 12666 // side effect as well (for example: || or ,). To account for this we wrap 12667 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12668 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12669 // which record usages which are modifications as side effect, and then 12670 // downgrade them (or more accurately restore the previous usage which was a 12671 // modification as side effect) when exiting the scope of the sequenced 12672 // subexpression. 12673 12674 void notePreUse(Object O, const Expr *UseExpr) { 12675 UsageInfo &UI = UsageMap[O]; 12676 // Uses conflict with other modifications. 12677 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12678 } 12679 12680 void notePostUse(Object O, const Expr *UseExpr) { 12681 UsageInfo &UI = UsageMap[O]; 12682 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12683 /*IsModMod=*/false); 12684 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12685 } 12686 12687 void notePreMod(Object O, const Expr *ModExpr) { 12688 UsageInfo &UI = UsageMap[O]; 12689 // Modifications conflict with other modifications and with uses. 12690 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12691 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12692 } 12693 12694 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12695 UsageInfo &UI = UsageMap[O]; 12696 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12697 /*IsModMod=*/true); 12698 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12699 } 12700 12701 public: 12702 SequenceChecker(Sema &S, const Expr *E, 12703 SmallVectorImpl<const Expr *> &WorkList) 12704 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12705 Visit(E); 12706 // Silence a -Wunused-private-field since WorkList is now unused. 12707 // TODO: Evaluate if it can be used, and if not remove it. 12708 (void)this->WorkList; 12709 } 12710 12711 void VisitStmt(const Stmt *S) { 12712 // Skip all statements which aren't expressions for now. 12713 } 12714 12715 void VisitExpr(const Expr *E) { 12716 // By default, just recurse to evaluated subexpressions. 12717 Base::VisitStmt(E); 12718 } 12719 12720 void VisitCastExpr(const CastExpr *E) { 12721 Object O = Object(); 12722 if (E->getCastKind() == CK_LValueToRValue) 12723 O = getObject(E->getSubExpr(), false); 12724 12725 if (O) 12726 notePreUse(O, E); 12727 VisitExpr(E); 12728 if (O) 12729 notePostUse(O, E); 12730 } 12731 12732 void VisitSequencedExpressions(const Expr *SequencedBefore, 12733 const Expr *SequencedAfter) { 12734 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12735 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12736 SequenceTree::Seq OldRegion = Region; 12737 12738 { 12739 SequencedSubexpression SeqBefore(*this); 12740 Region = BeforeRegion; 12741 Visit(SequencedBefore); 12742 } 12743 12744 Region = AfterRegion; 12745 Visit(SequencedAfter); 12746 12747 Region = OldRegion; 12748 12749 Tree.merge(BeforeRegion); 12750 Tree.merge(AfterRegion); 12751 } 12752 12753 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12754 // C++17 [expr.sub]p1: 12755 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12756 // expression E1 is sequenced before the expression E2. 12757 if (SemaRef.getLangOpts().CPlusPlus17) 12758 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12759 else { 12760 Visit(ASE->getLHS()); 12761 Visit(ASE->getRHS()); 12762 } 12763 } 12764 12765 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12766 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12767 void VisitBinPtrMem(const BinaryOperator *BO) { 12768 // C++17 [expr.mptr.oper]p4: 12769 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12770 // the expression E1 is sequenced before the expression E2. 12771 if (SemaRef.getLangOpts().CPlusPlus17) 12772 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12773 else { 12774 Visit(BO->getLHS()); 12775 Visit(BO->getRHS()); 12776 } 12777 } 12778 12779 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12780 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12781 void VisitBinShlShr(const BinaryOperator *BO) { 12782 // C++17 [expr.shift]p4: 12783 // The expression E1 is sequenced before the expression E2. 12784 if (SemaRef.getLangOpts().CPlusPlus17) 12785 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12786 else { 12787 Visit(BO->getLHS()); 12788 Visit(BO->getRHS()); 12789 } 12790 } 12791 12792 void VisitBinComma(const BinaryOperator *BO) { 12793 // C++11 [expr.comma]p1: 12794 // Every value computation and side effect associated with the left 12795 // expression is sequenced before every value computation and side 12796 // effect associated with the right expression. 12797 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12798 } 12799 12800 void VisitBinAssign(const BinaryOperator *BO) { 12801 SequenceTree::Seq RHSRegion; 12802 SequenceTree::Seq LHSRegion; 12803 if (SemaRef.getLangOpts().CPlusPlus17) { 12804 RHSRegion = Tree.allocate(Region); 12805 LHSRegion = Tree.allocate(Region); 12806 } else { 12807 RHSRegion = Region; 12808 LHSRegion = Region; 12809 } 12810 SequenceTree::Seq OldRegion = Region; 12811 12812 // C++11 [expr.ass]p1: 12813 // [...] the assignment is sequenced after the value computation 12814 // of the right and left operands, [...] 12815 // 12816 // so check it before inspecting the operands and update the 12817 // map afterwards. 12818 Object O = getObject(BO->getLHS(), /*Mod=*/true); 12819 if (O) 12820 notePreMod(O, BO); 12821 12822 if (SemaRef.getLangOpts().CPlusPlus17) { 12823 // C++17 [expr.ass]p1: 12824 // [...] The right operand is sequenced before the left operand. [...] 12825 { 12826 SequencedSubexpression SeqBefore(*this); 12827 Region = RHSRegion; 12828 Visit(BO->getRHS()); 12829 } 12830 12831 Region = LHSRegion; 12832 Visit(BO->getLHS()); 12833 12834 if (O && isa<CompoundAssignOperator>(BO)) 12835 notePostUse(O, BO); 12836 12837 } else { 12838 // C++11 does not specify any sequencing between the LHS and RHS. 12839 Region = LHSRegion; 12840 Visit(BO->getLHS()); 12841 12842 if (O && isa<CompoundAssignOperator>(BO)) 12843 notePostUse(O, BO); 12844 12845 Region = RHSRegion; 12846 Visit(BO->getRHS()); 12847 } 12848 12849 // C++11 [expr.ass]p1: 12850 // the assignment is sequenced [...] before the value computation of the 12851 // assignment expression. 12852 // C11 6.5.16/3 has no such rule. 12853 Region = OldRegion; 12854 if (O) 12855 notePostMod(O, BO, 12856 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12857 : UK_ModAsSideEffect); 12858 if (SemaRef.getLangOpts().CPlusPlus17) { 12859 Tree.merge(RHSRegion); 12860 Tree.merge(LHSRegion); 12861 } 12862 } 12863 12864 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 12865 VisitBinAssign(CAO); 12866 } 12867 12868 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12869 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12870 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 12871 Object O = getObject(UO->getSubExpr(), true); 12872 if (!O) 12873 return VisitExpr(UO); 12874 12875 notePreMod(O, UO); 12876 Visit(UO->getSubExpr()); 12877 // C++11 [expr.pre.incr]p1: 12878 // the expression ++x is equivalent to x+=1 12879 notePostMod(O, UO, 12880 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12881 : UK_ModAsSideEffect); 12882 } 12883 12884 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12885 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12886 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 12887 Object O = getObject(UO->getSubExpr(), true); 12888 if (!O) 12889 return VisitExpr(UO); 12890 12891 notePreMod(O, UO); 12892 Visit(UO->getSubExpr()); 12893 notePostMod(O, UO, UK_ModAsSideEffect); 12894 } 12895 12896 void VisitBinLOr(const BinaryOperator *BO) { 12897 // C++11 [expr.log.or]p2: 12898 // If the second expression is evaluated, every value computation and 12899 // side effect associated with the first expression is sequenced before 12900 // every value computation and side effect associated with the 12901 // second expression. 12902 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12903 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12904 SequenceTree::Seq OldRegion = Region; 12905 12906 EvaluationTracker Eval(*this); 12907 { 12908 SequencedSubexpression Sequenced(*this); 12909 Region = LHSRegion; 12910 Visit(BO->getLHS()); 12911 } 12912 12913 // C++11 [expr.log.or]p1: 12914 // [...] the second operand is not evaluated if the first operand 12915 // evaluates to true. 12916 bool EvalResult = false; 12917 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12918 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 12919 if (ShouldVisitRHS) { 12920 Region = RHSRegion; 12921 Visit(BO->getRHS()); 12922 } 12923 12924 Region = OldRegion; 12925 Tree.merge(LHSRegion); 12926 Tree.merge(RHSRegion); 12927 } 12928 12929 void VisitBinLAnd(const BinaryOperator *BO) { 12930 // C++11 [expr.log.and]p2: 12931 // If the second expression is evaluated, every value computation and 12932 // side effect associated with the first expression is sequenced before 12933 // every value computation and side effect associated with the 12934 // second expression. 12935 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12936 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12937 SequenceTree::Seq OldRegion = Region; 12938 12939 EvaluationTracker Eval(*this); 12940 { 12941 SequencedSubexpression Sequenced(*this); 12942 Region = LHSRegion; 12943 Visit(BO->getLHS()); 12944 } 12945 12946 // C++11 [expr.log.and]p1: 12947 // [...] the second operand is not evaluated if the first operand is false. 12948 bool EvalResult = false; 12949 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12950 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 12951 if (ShouldVisitRHS) { 12952 Region = RHSRegion; 12953 Visit(BO->getRHS()); 12954 } 12955 12956 Region = OldRegion; 12957 Tree.merge(LHSRegion); 12958 Tree.merge(RHSRegion); 12959 } 12960 12961 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 12962 // C++11 [expr.cond]p1: 12963 // [...] Every value computation and side effect associated with the first 12964 // expression is sequenced before every value computation and side effect 12965 // associated with the second or third expression. 12966 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 12967 12968 // No sequencing is specified between the true and false expression. 12969 // However since exactly one of both is going to be evaluated we can 12970 // consider them to be sequenced. This is needed to avoid warning on 12971 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 12972 // both the true and false expressions because we can't evaluate x. 12973 // This will still allow us to detect an expression like (pre C++17) 12974 // "(x ? y += 1 : y += 2) = y". 12975 // 12976 // We don't wrap the visitation of the true and false expression with 12977 // SequencedSubexpression because we don't want to downgrade modifications 12978 // as side effect in the true and false expressions after the visition 12979 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 12980 // not warn between the two "y++", but we should warn between the "y++" 12981 // and the "y". 12982 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 12983 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 12984 SequenceTree::Seq OldRegion = Region; 12985 12986 EvaluationTracker Eval(*this); 12987 { 12988 SequencedSubexpression Sequenced(*this); 12989 Region = ConditionRegion; 12990 Visit(CO->getCond()); 12991 } 12992 12993 // C++11 [expr.cond]p1: 12994 // [...] The first expression is contextually converted to bool (Clause 4). 12995 // It is evaluated and if it is true, the result of the conditional 12996 // expression is the value of the second expression, otherwise that of the 12997 // third expression. Only one of the second and third expressions is 12998 // evaluated. [...] 12999 bool EvalResult = false; 13000 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13001 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13002 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13003 if (ShouldVisitTrueExpr) { 13004 Region = TrueRegion; 13005 Visit(CO->getTrueExpr()); 13006 } 13007 if (ShouldVisitFalseExpr) { 13008 Region = FalseRegion; 13009 Visit(CO->getFalseExpr()); 13010 } 13011 13012 Region = OldRegion; 13013 Tree.merge(ConditionRegion); 13014 Tree.merge(TrueRegion); 13015 Tree.merge(FalseRegion); 13016 } 13017 13018 void VisitCallExpr(const CallExpr *CE) { 13019 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13020 13021 if (CE->isUnevaluatedBuiltinCall(Context)) 13022 return; 13023 13024 // C++11 [intro.execution]p15: 13025 // When calling a function [...], every value computation and side effect 13026 // associated with any argument expression, or with the postfix expression 13027 // designating the called function, is sequenced before execution of every 13028 // expression or statement in the body of the function [and thus before 13029 // the value computation of its result]. 13030 SequencedSubexpression Sequenced(*this); 13031 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13032 // C++17 [expr.call]p5 13033 // The postfix-expression is sequenced before each expression in the 13034 // expression-list and any default argument. [...] 13035 SequenceTree::Seq CalleeRegion; 13036 SequenceTree::Seq OtherRegion; 13037 if (SemaRef.getLangOpts().CPlusPlus17) { 13038 CalleeRegion = Tree.allocate(Region); 13039 OtherRegion = Tree.allocate(Region); 13040 } else { 13041 CalleeRegion = Region; 13042 OtherRegion = Region; 13043 } 13044 SequenceTree::Seq OldRegion = Region; 13045 13046 // Visit the callee expression first. 13047 Region = CalleeRegion; 13048 if (SemaRef.getLangOpts().CPlusPlus17) { 13049 SequencedSubexpression Sequenced(*this); 13050 Visit(CE->getCallee()); 13051 } else { 13052 Visit(CE->getCallee()); 13053 } 13054 13055 // Then visit the argument expressions. 13056 Region = OtherRegion; 13057 for (const Expr *Argument : CE->arguments()) 13058 Visit(Argument); 13059 13060 Region = OldRegion; 13061 if (SemaRef.getLangOpts().CPlusPlus17) { 13062 Tree.merge(CalleeRegion); 13063 Tree.merge(OtherRegion); 13064 } 13065 }); 13066 } 13067 13068 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13069 // C++17 [over.match.oper]p2: 13070 // [...] the operator notation is first transformed to the equivalent 13071 // function-call notation as summarized in Table 12 (where @ denotes one 13072 // of the operators covered in the specified subclause). However, the 13073 // operands are sequenced in the order prescribed for the built-in 13074 // operator (Clause 8). 13075 // 13076 // From the above only overloaded binary operators and overloaded call 13077 // operators have sequencing rules in C++17 that we need to handle 13078 // separately. 13079 if (!SemaRef.getLangOpts().CPlusPlus17 || 13080 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13081 return VisitCallExpr(CXXOCE); 13082 13083 enum { 13084 NoSequencing, 13085 LHSBeforeRHS, 13086 RHSBeforeLHS, 13087 LHSBeforeRest 13088 } SequencingKind; 13089 switch (CXXOCE->getOperator()) { 13090 case OO_Equal: 13091 case OO_PlusEqual: 13092 case OO_MinusEqual: 13093 case OO_StarEqual: 13094 case OO_SlashEqual: 13095 case OO_PercentEqual: 13096 case OO_CaretEqual: 13097 case OO_AmpEqual: 13098 case OO_PipeEqual: 13099 case OO_LessLessEqual: 13100 case OO_GreaterGreaterEqual: 13101 SequencingKind = RHSBeforeLHS; 13102 break; 13103 13104 case OO_LessLess: 13105 case OO_GreaterGreater: 13106 case OO_AmpAmp: 13107 case OO_PipePipe: 13108 case OO_Comma: 13109 case OO_ArrowStar: 13110 case OO_Subscript: 13111 SequencingKind = LHSBeforeRHS; 13112 break; 13113 13114 case OO_Call: 13115 SequencingKind = LHSBeforeRest; 13116 break; 13117 13118 default: 13119 SequencingKind = NoSequencing; 13120 break; 13121 } 13122 13123 if (SequencingKind == NoSequencing) 13124 return VisitCallExpr(CXXOCE); 13125 13126 // This is a call, so all subexpressions are sequenced before the result. 13127 SequencedSubexpression Sequenced(*this); 13128 13129 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13130 assert(SemaRef.getLangOpts().CPlusPlus17 && 13131 "Should only get there with C++17 and above!"); 13132 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13133 "Should only get there with an overloaded binary operator" 13134 " or an overloaded call operator!"); 13135 13136 if (SequencingKind == LHSBeforeRest) { 13137 assert(CXXOCE->getOperator() == OO_Call && 13138 "We should only have an overloaded call operator here!"); 13139 13140 // This is very similar to VisitCallExpr, except that we only have the 13141 // C++17 case. The postfix-expression is the first argument of the 13142 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13143 // are in the following arguments. 13144 // 13145 // Note that we intentionally do not visit the callee expression since 13146 // it is just a decayed reference to a function. 13147 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13148 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13149 SequenceTree::Seq OldRegion = Region; 13150 13151 assert(CXXOCE->getNumArgs() >= 1 && 13152 "An overloaded call operator must have at least one argument" 13153 " for the postfix-expression!"); 13154 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13155 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13156 CXXOCE->getNumArgs() - 1); 13157 13158 // Visit the postfix-expression first. 13159 { 13160 Region = PostfixExprRegion; 13161 SequencedSubexpression Sequenced(*this); 13162 Visit(PostfixExpr); 13163 } 13164 13165 // Then visit the argument expressions. 13166 Region = ArgsRegion; 13167 for (const Expr *Arg : Args) 13168 Visit(Arg); 13169 13170 Region = OldRegion; 13171 Tree.merge(PostfixExprRegion); 13172 Tree.merge(ArgsRegion); 13173 } else { 13174 assert(CXXOCE->getNumArgs() == 2 && 13175 "Should only have two arguments here!"); 13176 assert((SequencingKind == LHSBeforeRHS || 13177 SequencingKind == RHSBeforeLHS) && 13178 "Unexpected sequencing kind!"); 13179 13180 // We do not visit the callee expression since it is just a decayed 13181 // reference to a function. 13182 const Expr *E1 = CXXOCE->getArg(0); 13183 const Expr *E2 = CXXOCE->getArg(1); 13184 if (SequencingKind == RHSBeforeLHS) 13185 std::swap(E1, E2); 13186 13187 return VisitSequencedExpressions(E1, E2); 13188 } 13189 }); 13190 } 13191 13192 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13193 // This is a call, so all subexpressions are sequenced before the result. 13194 SequencedSubexpression Sequenced(*this); 13195 13196 if (!CCE->isListInitialization()) 13197 return VisitExpr(CCE); 13198 13199 // In C++11, list initializations are sequenced. 13200 SmallVector<SequenceTree::Seq, 32> Elts; 13201 SequenceTree::Seq Parent = Region; 13202 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13203 E = CCE->arg_end(); 13204 I != E; ++I) { 13205 Region = Tree.allocate(Parent); 13206 Elts.push_back(Region); 13207 Visit(*I); 13208 } 13209 13210 // Forget that the initializers are sequenced. 13211 Region = Parent; 13212 for (unsigned I = 0; I < Elts.size(); ++I) 13213 Tree.merge(Elts[I]); 13214 } 13215 13216 void VisitInitListExpr(const InitListExpr *ILE) { 13217 if (!SemaRef.getLangOpts().CPlusPlus11) 13218 return VisitExpr(ILE); 13219 13220 // In C++11, list initializations are sequenced. 13221 SmallVector<SequenceTree::Seq, 32> Elts; 13222 SequenceTree::Seq Parent = Region; 13223 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13224 const Expr *E = ILE->getInit(I); 13225 if (!E) 13226 continue; 13227 Region = Tree.allocate(Parent); 13228 Elts.push_back(Region); 13229 Visit(E); 13230 } 13231 13232 // Forget that the initializers are sequenced. 13233 Region = Parent; 13234 for (unsigned I = 0; I < Elts.size(); ++I) 13235 Tree.merge(Elts[I]); 13236 } 13237 }; 13238 13239 } // namespace 13240 13241 void Sema::CheckUnsequencedOperations(const Expr *E) { 13242 SmallVector<const Expr *, 8> WorkList; 13243 WorkList.push_back(E); 13244 while (!WorkList.empty()) { 13245 const Expr *Item = WorkList.pop_back_val(); 13246 SequenceChecker(*this, Item, WorkList); 13247 } 13248 } 13249 13250 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13251 bool IsConstexpr) { 13252 llvm::SaveAndRestore<bool> ConstantContext( 13253 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13254 CheckImplicitConversions(E, CheckLoc); 13255 if (!E->isInstantiationDependent()) 13256 CheckUnsequencedOperations(E); 13257 if (!IsConstexpr && !E->isValueDependent()) 13258 CheckForIntOverflow(E); 13259 DiagnoseMisalignedMembers(); 13260 } 13261 13262 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13263 FieldDecl *BitField, 13264 Expr *Init) { 13265 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13266 } 13267 13268 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13269 SourceLocation Loc) { 13270 if (!PType->isVariablyModifiedType()) 13271 return; 13272 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13273 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13274 return; 13275 } 13276 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13277 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13278 return; 13279 } 13280 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13281 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13282 return; 13283 } 13284 13285 const ArrayType *AT = S.Context.getAsArrayType(PType); 13286 if (!AT) 13287 return; 13288 13289 if (AT->getSizeModifier() != ArrayType::Star) { 13290 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13291 return; 13292 } 13293 13294 S.Diag(Loc, diag::err_array_star_in_function_definition); 13295 } 13296 13297 /// CheckParmsForFunctionDef - Check that the parameters of the given 13298 /// function are appropriate for the definition of a function. This 13299 /// takes care of any checks that cannot be performed on the 13300 /// declaration itself, e.g., that the types of each of the function 13301 /// parameters are complete. 13302 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13303 bool CheckParameterNames) { 13304 bool HasInvalidParm = false; 13305 for (ParmVarDecl *Param : Parameters) { 13306 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13307 // function declarator that is part of a function definition of 13308 // that function shall not have incomplete type. 13309 // 13310 // This is also C++ [dcl.fct]p6. 13311 if (!Param->isInvalidDecl() && 13312 RequireCompleteType(Param->getLocation(), Param->getType(), 13313 diag::err_typecheck_decl_incomplete_type)) { 13314 Param->setInvalidDecl(); 13315 HasInvalidParm = true; 13316 } 13317 13318 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13319 // declaration of each parameter shall include an identifier. 13320 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13321 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13322 // Diagnose this as an extension in C17 and earlier. 13323 if (!getLangOpts().C2x) 13324 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 13325 } 13326 13327 // C99 6.7.5.3p12: 13328 // If the function declarator is not part of a definition of that 13329 // function, parameters may have incomplete type and may use the [*] 13330 // notation in their sequences of declarator specifiers to specify 13331 // variable length array types. 13332 QualType PType = Param->getOriginalType(); 13333 // FIXME: This diagnostic should point the '[*]' if source-location 13334 // information is added for it. 13335 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13336 13337 // If the parameter is a c++ class type and it has to be destructed in the 13338 // callee function, declare the destructor so that it can be called by the 13339 // callee function. Do not perform any direct access check on the dtor here. 13340 if (!Param->isInvalidDecl()) { 13341 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13342 if (!ClassDecl->isInvalidDecl() && 13343 !ClassDecl->hasIrrelevantDestructor() && 13344 !ClassDecl->isDependentContext() && 13345 ClassDecl->isParamDestroyedInCallee()) { 13346 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13347 MarkFunctionReferenced(Param->getLocation(), Destructor); 13348 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13349 } 13350 } 13351 } 13352 13353 // Parameters with the pass_object_size attribute only need to be marked 13354 // constant at function definitions. Because we lack information about 13355 // whether we're on a declaration or definition when we're instantiating the 13356 // attribute, we need to check for constness here. 13357 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13358 if (!Param->getType().isConstQualified()) 13359 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13360 << Attr->getSpelling() << 1; 13361 13362 // Check for parameter names shadowing fields from the class. 13363 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13364 // The owning context for the parameter should be the function, but we 13365 // want to see if this function's declaration context is a record. 13366 DeclContext *DC = Param->getDeclContext(); 13367 if (DC && DC->isFunctionOrMethod()) { 13368 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13369 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13370 RD, /*DeclIsField*/ false); 13371 } 13372 } 13373 } 13374 13375 return HasInvalidParm; 13376 } 13377 13378 Optional<std::pair<CharUnits, CharUnits>> 13379 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 13380 13381 /// Compute the alignment and offset of the base class object given the 13382 /// derived-to-base cast expression and the alignment and offset of the derived 13383 /// class object. 13384 static std::pair<CharUnits, CharUnits> 13385 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 13386 CharUnits BaseAlignment, CharUnits Offset, 13387 ASTContext &Ctx) { 13388 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 13389 ++PathI) { 13390 const CXXBaseSpecifier *Base = *PathI; 13391 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 13392 if (Base->isVirtual()) { 13393 // The complete object may have a lower alignment than the non-virtual 13394 // alignment of the base, in which case the base may be misaligned. Choose 13395 // the smaller of the non-virtual alignment and BaseAlignment, which is a 13396 // conservative lower bound of the complete object alignment. 13397 CharUnits NonVirtualAlignment = 13398 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 13399 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 13400 Offset = CharUnits::Zero(); 13401 } else { 13402 const ASTRecordLayout &RL = 13403 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 13404 Offset += RL.getBaseClassOffset(BaseDecl); 13405 } 13406 DerivedType = Base->getType(); 13407 } 13408 13409 return std::make_pair(BaseAlignment, Offset); 13410 } 13411 13412 /// Compute the alignment and offset of a binary additive operator. 13413 static Optional<std::pair<CharUnits, CharUnits>> 13414 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 13415 bool IsSub, ASTContext &Ctx) { 13416 QualType PointeeType = PtrE->getType()->getPointeeType(); 13417 13418 if (!PointeeType->isConstantSizeType()) 13419 return llvm::None; 13420 13421 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 13422 13423 if (!P) 13424 return llvm::None; 13425 13426 llvm::APSInt IdxRes; 13427 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 13428 if (IntE->isIntegerConstantExpr(IdxRes, Ctx)) { 13429 CharUnits Offset = EltSize * IdxRes.getExtValue(); 13430 if (IsSub) 13431 Offset = -Offset; 13432 return std::make_pair(P->first, P->second + Offset); 13433 } 13434 13435 // If the integer expression isn't a constant expression, compute the lower 13436 // bound of the alignment using the alignment and offset of the pointer 13437 // expression and the element size. 13438 return std::make_pair( 13439 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 13440 CharUnits::Zero()); 13441 } 13442 13443 /// This helper function takes an lvalue expression and returns the alignment of 13444 /// a VarDecl and a constant offset from the VarDecl. 13445 Optional<std::pair<CharUnits, CharUnits>> 13446 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 13447 E = E->IgnoreParens(); 13448 switch (E->getStmtClass()) { 13449 default: 13450 break; 13451 case Stmt::CStyleCastExprClass: 13452 case Stmt::CXXStaticCastExprClass: 13453 case Stmt::ImplicitCastExprClass: { 13454 auto *CE = cast<CastExpr>(E); 13455 const Expr *From = CE->getSubExpr(); 13456 switch (CE->getCastKind()) { 13457 default: 13458 break; 13459 case CK_NoOp: 13460 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13461 case CK_UncheckedDerivedToBase: 13462 case CK_DerivedToBase: { 13463 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13464 if (!P) 13465 break; 13466 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 13467 P->second, Ctx); 13468 } 13469 } 13470 break; 13471 } 13472 case Stmt::ArraySubscriptExprClass: { 13473 auto *ASE = cast<ArraySubscriptExpr>(E); 13474 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 13475 false, Ctx); 13476 } 13477 case Stmt::DeclRefExprClass: { 13478 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 13479 // FIXME: If VD is captured by copy or is an escaping __block variable, 13480 // use the alignment of VD's type. 13481 if (!VD->getType()->isReferenceType()) 13482 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 13483 if (VD->hasInit()) 13484 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 13485 } 13486 break; 13487 } 13488 case Stmt::MemberExprClass: { 13489 auto *ME = cast<MemberExpr>(E); 13490 if (ME->isArrow()) 13491 break; 13492 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 13493 if (!FD || FD->getType()->isReferenceType()) 13494 break; 13495 auto P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 13496 if (!P) 13497 break; 13498 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 13499 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 13500 return std::make_pair(P->first, 13501 P->second + CharUnits::fromQuantity(Offset)); 13502 } 13503 case Stmt::UnaryOperatorClass: { 13504 auto *UO = cast<UnaryOperator>(E); 13505 switch (UO->getOpcode()) { 13506 default: 13507 break; 13508 case UO_Deref: 13509 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 13510 } 13511 break; 13512 } 13513 case Stmt::BinaryOperatorClass: { 13514 auto *BO = cast<BinaryOperator>(E); 13515 auto Opcode = BO->getOpcode(); 13516 switch (Opcode) { 13517 default: 13518 break; 13519 case BO_Comma: 13520 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 13521 } 13522 break; 13523 } 13524 } 13525 return llvm::None; 13526 } 13527 13528 /// This helper function takes a pointer expression and returns the alignment of 13529 /// a VarDecl and a constant offset from the VarDecl. 13530 Optional<std::pair<CharUnits, CharUnits>> 13531 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 13532 E = E->IgnoreParens(); 13533 switch (E->getStmtClass()) { 13534 default: 13535 break; 13536 case Stmt::CStyleCastExprClass: 13537 case Stmt::CXXStaticCastExprClass: 13538 case Stmt::ImplicitCastExprClass: { 13539 auto *CE = cast<CastExpr>(E); 13540 const Expr *From = CE->getSubExpr(); 13541 switch (CE->getCastKind()) { 13542 default: 13543 break; 13544 case CK_NoOp: 13545 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13546 case CK_ArrayToPointerDecay: 13547 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13548 case CK_UncheckedDerivedToBase: 13549 case CK_DerivedToBase: { 13550 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13551 if (!P) 13552 break; 13553 return getDerivedToBaseAlignmentAndOffset( 13554 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 13555 } 13556 } 13557 break; 13558 } 13559 case Stmt::UnaryOperatorClass: { 13560 auto *UO = cast<UnaryOperator>(E); 13561 if (UO->getOpcode() == UO_AddrOf) 13562 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 13563 break; 13564 } 13565 case Stmt::BinaryOperatorClass: { 13566 auto *BO = cast<BinaryOperator>(E); 13567 auto Opcode = BO->getOpcode(); 13568 switch (Opcode) { 13569 default: 13570 break; 13571 case BO_Add: 13572 case BO_Sub: { 13573 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 13574 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 13575 std::swap(LHS, RHS); 13576 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 13577 Ctx); 13578 } 13579 case BO_Comma: 13580 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 13581 } 13582 break; 13583 } 13584 } 13585 return llvm::None; 13586 } 13587 13588 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 13589 // See if we can compute the alignment of a VarDecl and an offset from it. 13590 Optional<std::pair<CharUnits, CharUnits>> P = 13591 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 13592 13593 if (P) 13594 return P->first.alignmentAtOffset(P->second); 13595 13596 // If that failed, return the type's alignment. 13597 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 13598 } 13599 13600 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13601 /// pointer cast increases the alignment requirements. 13602 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13603 // This is actually a lot of work to potentially be doing on every 13604 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13605 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13606 return; 13607 13608 // Ignore dependent types. 13609 if (T->isDependentType() || Op->getType()->isDependentType()) 13610 return; 13611 13612 // Require that the destination be a pointer type. 13613 const PointerType *DestPtr = T->getAs<PointerType>(); 13614 if (!DestPtr) return; 13615 13616 // If the destination has alignment 1, we're done. 13617 QualType DestPointee = DestPtr->getPointeeType(); 13618 if (DestPointee->isIncompleteType()) return; 13619 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13620 if (DestAlign.isOne()) return; 13621 13622 // Require that the source be a pointer type. 13623 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13624 if (!SrcPtr) return; 13625 QualType SrcPointee = SrcPtr->getPointeeType(); 13626 13627 // Explicitly allow casts from cv void*. We already implicitly 13628 // allowed casts to cv void*, since they have alignment 1. 13629 // Also allow casts involving incomplete types, which implicitly 13630 // includes 'void'. 13631 if (SrcPointee->isIncompleteType()) return; 13632 13633 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 13634 13635 if (SrcAlign >= DestAlign) return; 13636 13637 Diag(TRange.getBegin(), diag::warn_cast_align) 13638 << Op->getType() << T 13639 << static_cast<unsigned>(SrcAlign.getQuantity()) 13640 << static_cast<unsigned>(DestAlign.getQuantity()) 13641 << TRange << Op->getSourceRange(); 13642 } 13643 13644 /// Check whether this array fits the idiom of a size-one tail padded 13645 /// array member of a struct. 13646 /// 13647 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 13648 /// commonly used to emulate flexible arrays in C89 code. 13649 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 13650 const NamedDecl *ND) { 13651 if (Size != 1 || !ND) return false; 13652 13653 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 13654 if (!FD) return false; 13655 13656 // Don't consider sizes resulting from macro expansions or template argument 13657 // substitution to form C89 tail-padded arrays. 13658 13659 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 13660 while (TInfo) { 13661 TypeLoc TL = TInfo->getTypeLoc(); 13662 // Look through typedefs. 13663 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13664 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13665 TInfo = TDL->getTypeSourceInfo(); 13666 continue; 13667 } 13668 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13669 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13670 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13671 return false; 13672 } 13673 break; 13674 } 13675 13676 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13677 if (!RD) return false; 13678 if (RD->isUnion()) return false; 13679 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13680 if (!CRD->isStandardLayout()) return false; 13681 } 13682 13683 // See if this is the last field decl in the record. 13684 const Decl *D = FD; 13685 while ((D = D->getNextDeclInContext())) 13686 if (isa<FieldDecl>(D)) 13687 return false; 13688 return true; 13689 } 13690 13691 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13692 const ArraySubscriptExpr *ASE, 13693 bool AllowOnePastEnd, bool IndexNegated) { 13694 // Already diagnosed by the constant evaluator. 13695 if (isConstantEvaluated()) 13696 return; 13697 13698 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13699 if (IndexExpr->isValueDependent()) 13700 return; 13701 13702 const Type *EffectiveType = 13703 BaseExpr->getType()->getPointeeOrArrayElementType(); 13704 BaseExpr = BaseExpr->IgnoreParenCasts(); 13705 const ConstantArrayType *ArrayTy = 13706 Context.getAsConstantArrayType(BaseExpr->getType()); 13707 13708 if (!ArrayTy) 13709 return; 13710 13711 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13712 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13713 return; 13714 13715 Expr::EvalResult Result; 13716 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13717 return; 13718 13719 llvm::APSInt index = Result.Val.getInt(); 13720 if (IndexNegated) 13721 index = -index; 13722 13723 const NamedDecl *ND = nullptr; 13724 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13725 ND = DRE->getDecl(); 13726 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13727 ND = ME->getMemberDecl(); 13728 13729 if (index.isUnsigned() || !index.isNegative()) { 13730 // It is possible that the type of the base expression after 13731 // IgnoreParenCasts is incomplete, even though the type of the base 13732 // expression before IgnoreParenCasts is complete (see PR39746 for an 13733 // example). In this case we have no information about whether the array 13734 // access exceeds the array bounds. However we can still diagnose an array 13735 // access which precedes the array bounds. 13736 if (BaseType->isIncompleteType()) 13737 return; 13738 13739 llvm::APInt size = ArrayTy->getSize(); 13740 if (!size.isStrictlyPositive()) 13741 return; 13742 13743 if (BaseType != EffectiveType) { 13744 // Make sure we're comparing apples to apples when comparing index to size 13745 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13746 uint64_t array_typesize = Context.getTypeSize(BaseType); 13747 // Handle ptrarith_typesize being zero, such as when casting to void* 13748 if (!ptrarith_typesize) ptrarith_typesize = 1; 13749 if (ptrarith_typesize != array_typesize) { 13750 // There's a cast to a different size type involved 13751 uint64_t ratio = array_typesize / ptrarith_typesize; 13752 // TODO: Be smarter about handling cases where array_typesize is not a 13753 // multiple of ptrarith_typesize 13754 if (ptrarith_typesize * ratio == array_typesize) 13755 size *= llvm::APInt(size.getBitWidth(), ratio); 13756 } 13757 } 13758 13759 if (size.getBitWidth() > index.getBitWidth()) 13760 index = index.zext(size.getBitWidth()); 13761 else if (size.getBitWidth() < index.getBitWidth()) 13762 size = size.zext(index.getBitWidth()); 13763 13764 // For array subscripting the index must be less than size, but for pointer 13765 // arithmetic also allow the index (offset) to be equal to size since 13766 // computing the next address after the end of the array is legal and 13767 // commonly done e.g. in C++ iterators and range-based for loops. 13768 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13769 return; 13770 13771 // Also don't warn for arrays of size 1 which are members of some 13772 // structure. These are often used to approximate flexible arrays in C89 13773 // code. 13774 if (IsTailPaddedMemberArray(*this, size, ND)) 13775 return; 13776 13777 // Suppress the warning if the subscript expression (as identified by the 13778 // ']' location) and the index expression are both from macro expansions 13779 // within a system header. 13780 if (ASE) { 13781 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13782 ASE->getRBracketLoc()); 13783 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13784 SourceLocation IndexLoc = 13785 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13786 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13787 return; 13788 } 13789 } 13790 13791 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13792 if (ASE) 13793 DiagID = diag::warn_array_index_exceeds_bounds; 13794 13795 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13796 PDiag(DiagID) << index.toString(10, true) 13797 << size.toString(10, true) 13798 << (unsigned)size.getLimitedValue(~0U) 13799 << IndexExpr->getSourceRange()); 13800 } else { 13801 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13802 if (!ASE) { 13803 DiagID = diag::warn_ptr_arith_precedes_bounds; 13804 if (index.isNegative()) index = -index; 13805 } 13806 13807 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13808 PDiag(DiagID) << index.toString(10, true) 13809 << IndexExpr->getSourceRange()); 13810 } 13811 13812 if (!ND) { 13813 // Try harder to find a NamedDecl to point at in the note. 13814 while (const ArraySubscriptExpr *ASE = 13815 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13816 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13817 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13818 ND = DRE->getDecl(); 13819 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13820 ND = ME->getMemberDecl(); 13821 } 13822 13823 if (ND) 13824 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13825 PDiag(diag::note_array_declared_here) 13826 << ND->getDeclName()); 13827 } 13828 13829 void Sema::CheckArrayAccess(const Expr *expr) { 13830 int AllowOnePastEnd = 0; 13831 while (expr) { 13832 expr = expr->IgnoreParenImpCasts(); 13833 switch (expr->getStmtClass()) { 13834 case Stmt::ArraySubscriptExprClass: { 13835 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13836 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13837 AllowOnePastEnd > 0); 13838 expr = ASE->getBase(); 13839 break; 13840 } 13841 case Stmt::MemberExprClass: { 13842 expr = cast<MemberExpr>(expr)->getBase(); 13843 break; 13844 } 13845 case Stmt::OMPArraySectionExprClass: { 13846 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13847 if (ASE->getLowerBound()) 13848 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13849 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13850 return; 13851 } 13852 case Stmt::UnaryOperatorClass: { 13853 // Only unwrap the * and & unary operators 13854 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13855 expr = UO->getSubExpr(); 13856 switch (UO->getOpcode()) { 13857 case UO_AddrOf: 13858 AllowOnePastEnd++; 13859 break; 13860 case UO_Deref: 13861 AllowOnePastEnd--; 13862 break; 13863 default: 13864 return; 13865 } 13866 break; 13867 } 13868 case Stmt::ConditionalOperatorClass: { 13869 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13870 if (const Expr *lhs = cond->getLHS()) 13871 CheckArrayAccess(lhs); 13872 if (const Expr *rhs = cond->getRHS()) 13873 CheckArrayAccess(rhs); 13874 return; 13875 } 13876 case Stmt::CXXOperatorCallExprClass: { 13877 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13878 for (const auto *Arg : OCE->arguments()) 13879 CheckArrayAccess(Arg); 13880 return; 13881 } 13882 default: 13883 return; 13884 } 13885 } 13886 } 13887 13888 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13889 13890 namespace { 13891 13892 struct RetainCycleOwner { 13893 VarDecl *Variable = nullptr; 13894 SourceRange Range; 13895 SourceLocation Loc; 13896 bool Indirect = false; 13897 13898 RetainCycleOwner() = default; 13899 13900 void setLocsFrom(Expr *e) { 13901 Loc = e->getExprLoc(); 13902 Range = e->getSourceRange(); 13903 } 13904 }; 13905 13906 } // namespace 13907 13908 /// Consider whether capturing the given variable can possibly lead to 13909 /// a retain cycle. 13910 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 13911 // In ARC, it's captured strongly iff the variable has __strong 13912 // lifetime. In MRR, it's captured strongly if the variable is 13913 // __block and has an appropriate type. 13914 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13915 return false; 13916 13917 owner.Variable = var; 13918 if (ref) 13919 owner.setLocsFrom(ref); 13920 return true; 13921 } 13922 13923 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13924 while (true) { 13925 e = e->IgnoreParens(); 13926 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13927 switch (cast->getCastKind()) { 13928 case CK_BitCast: 13929 case CK_LValueBitCast: 13930 case CK_LValueToRValue: 13931 case CK_ARCReclaimReturnedObject: 13932 e = cast->getSubExpr(); 13933 continue; 13934 13935 default: 13936 return false; 13937 } 13938 } 13939 13940 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13941 ObjCIvarDecl *ivar = ref->getDecl(); 13942 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13943 return false; 13944 13945 // Try to find a retain cycle in the base. 13946 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13947 return false; 13948 13949 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13950 owner.Indirect = true; 13951 return true; 13952 } 13953 13954 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13955 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13956 if (!var) return false; 13957 return considerVariable(var, ref, owner); 13958 } 13959 13960 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13961 if (member->isArrow()) return false; 13962 13963 // Don't count this as an indirect ownership. 13964 e = member->getBase(); 13965 continue; 13966 } 13967 13968 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13969 // Only pay attention to pseudo-objects on property references. 13970 ObjCPropertyRefExpr *pre 13971 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13972 ->IgnoreParens()); 13973 if (!pre) return false; 13974 if (pre->isImplicitProperty()) return false; 13975 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13976 if (!property->isRetaining() && 13977 !(property->getPropertyIvarDecl() && 13978 property->getPropertyIvarDecl()->getType() 13979 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13980 return false; 13981 13982 owner.Indirect = true; 13983 if (pre->isSuperReceiver()) { 13984 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13985 if (!owner.Variable) 13986 return false; 13987 owner.Loc = pre->getLocation(); 13988 owner.Range = pre->getSourceRange(); 13989 return true; 13990 } 13991 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13992 ->getSourceExpr()); 13993 continue; 13994 } 13995 13996 // Array ivars? 13997 13998 return false; 13999 } 14000 } 14001 14002 namespace { 14003 14004 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14005 ASTContext &Context; 14006 VarDecl *Variable; 14007 Expr *Capturer = nullptr; 14008 bool VarWillBeReased = false; 14009 14010 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14011 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14012 Context(Context), Variable(variable) {} 14013 14014 void VisitDeclRefExpr(DeclRefExpr *ref) { 14015 if (ref->getDecl() == Variable && !Capturer) 14016 Capturer = ref; 14017 } 14018 14019 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14020 if (Capturer) return; 14021 Visit(ref->getBase()); 14022 if (Capturer && ref->isFreeIvar()) 14023 Capturer = ref; 14024 } 14025 14026 void VisitBlockExpr(BlockExpr *block) { 14027 // Look inside nested blocks 14028 if (block->getBlockDecl()->capturesVariable(Variable)) 14029 Visit(block->getBlockDecl()->getBody()); 14030 } 14031 14032 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14033 if (Capturer) return; 14034 if (OVE->getSourceExpr()) 14035 Visit(OVE->getSourceExpr()); 14036 } 14037 14038 void VisitBinaryOperator(BinaryOperator *BinOp) { 14039 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14040 return; 14041 Expr *LHS = BinOp->getLHS(); 14042 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14043 if (DRE->getDecl() != Variable) 14044 return; 14045 if (Expr *RHS = BinOp->getRHS()) { 14046 RHS = RHS->IgnoreParenCasts(); 14047 llvm::APSInt Value; 14048 VarWillBeReased = 14049 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 14050 } 14051 } 14052 } 14053 }; 14054 14055 } // namespace 14056 14057 /// Check whether the given argument is a block which captures a 14058 /// variable. 14059 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14060 assert(owner.Variable && owner.Loc.isValid()); 14061 14062 e = e->IgnoreParenCasts(); 14063 14064 // Look through [^{...} copy] and Block_copy(^{...}). 14065 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14066 Selector Cmd = ME->getSelector(); 14067 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14068 e = ME->getInstanceReceiver(); 14069 if (!e) 14070 return nullptr; 14071 e = e->IgnoreParenCasts(); 14072 } 14073 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14074 if (CE->getNumArgs() == 1) { 14075 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14076 if (Fn) { 14077 const IdentifierInfo *FnI = Fn->getIdentifier(); 14078 if (FnI && FnI->isStr("_Block_copy")) { 14079 e = CE->getArg(0)->IgnoreParenCasts(); 14080 } 14081 } 14082 } 14083 } 14084 14085 BlockExpr *block = dyn_cast<BlockExpr>(e); 14086 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14087 return nullptr; 14088 14089 FindCaptureVisitor visitor(S.Context, owner.Variable); 14090 visitor.Visit(block->getBlockDecl()->getBody()); 14091 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14092 } 14093 14094 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14095 RetainCycleOwner &owner) { 14096 assert(capturer); 14097 assert(owner.Variable && owner.Loc.isValid()); 14098 14099 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14100 << owner.Variable << capturer->getSourceRange(); 14101 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14102 << owner.Indirect << owner.Range; 14103 } 14104 14105 /// Check for a keyword selector that starts with the word 'add' or 14106 /// 'set'. 14107 static bool isSetterLikeSelector(Selector sel) { 14108 if (sel.isUnarySelector()) return false; 14109 14110 StringRef str = sel.getNameForSlot(0); 14111 while (!str.empty() && str.front() == '_') str = str.substr(1); 14112 if (str.startswith("set")) 14113 str = str.substr(3); 14114 else if (str.startswith("add")) { 14115 // Specially allow 'addOperationWithBlock:'. 14116 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14117 return false; 14118 str = str.substr(3); 14119 } 14120 else 14121 return false; 14122 14123 if (str.empty()) return true; 14124 return !isLowercase(str.front()); 14125 } 14126 14127 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14128 ObjCMessageExpr *Message) { 14129 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14130 Message->getReceiverInterface(), 14131 NSAPI::ClassId_NSMutableArray); 14132 if (!IsMutableArray) { 14133 return None; 14134 } 14135 14136 Selector Sel = Message->getSelector(); 14137 14138 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14139 S.NSAPIObj->getNSArrayMethodKind(Sel); 14140 if (!MKOpt) { 14141 return None; 14142 } 14143 14144 NSAPI::NSArrayMethodKind MK = *MKOpt; 14145 14146 switch (MK) { 14147 case NSAPI::NSMutableArr_addObject: 14148 case NSAPI::NSMutableArr_insertObjectAtIndex: 14149 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14150 return 0; 14151 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14152 return 1; 14153 14154 default: 14155 return None; 14156 } 14157 14158 return None; 14159 } 14160 14161 static 14162 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14163 ObjCMessageExpr *Message) { 14164 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14165 Message->getReceiverInterface(), 14166 NSAPI::ClassId_NSMutableDictionary); 14167 if (!IsMutableDictionary) { 14168 return None; 14169 } 14170 14171 Selector Sel = Message->getSelector(); 14172 14173 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14174 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14175 if (!MKOpt) { 14176 return None; 14177 } 14178 14179 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14180 14181 switch (MK) { 14182 case NSAPI::NSMutableDict_setObjectForKey: 14183 case NSAPI::NSMutableDict_setValueForKey: 14184 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14185 return 0; 14186 14187 default: 14188 return None; 14189 } 14190 14191 return None; 14192 } 14193 14194 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14195 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14196 Message->getReceiverInterface(), 14197 NSAPI::ClassId_NSMutableSet); 14198 14199 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14200 Message->getReceiverInterface(), 14201 NSAPI::ClassId_NSMutableOrderedSet); 14202 if (!IsMutableSet && !IsMutableOrderedSet) { 14203 return None; 14204 } 14205 14206 Selector Sel = Message->getSelector(); 14207 14208 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14209 if (!MKOpt) { 14210 return None; 14211 } 14212 14213 NSAPI::NSSetMethodKind MK = *MKOpt; 14214 14215 switch (MK) { 14216 case NSAPI::NSMutableSet_addObject: 14217 case NSAPI::NSOrderedSet_setObjectAtIndex: 14218 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14219 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14220 return 0; 14221 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14222 return 1; 14223 } 14224 14225 return None; 14226 } 14227 14228 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14229 if (!Message->isInstanceMessage()) { 14230 return; 14231 } 14232 14233 Optional<int> ArgOpt; 14234 14235 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14236 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14237 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14238 return; 14239 } 14240 14241 int ArgIndex = *ArgOpt; 14242 14243 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14244 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14245 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14246 } 14247 14248 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14249 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14250 if (ArgRE->isObjCSelfExpr()) { 14251 Diag(Message->getSourceRange().getBegin(), 14252 diag::warn_objc_circular_container) 14253 << ArgRE->getDecl() << StringRef("'super'"); 14254 } 14255 } 14256 } else { 14257 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14258 14259 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14260 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14261 } 14262 14263 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14264 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14265 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14266 ValueDecl *Decl = ReceiverRE->getDecl(); 14267 Diag(Message->getSourceRange().getBegin(), 14268 diag::warn_objc_circular_container) 14269 << Decl << Decl; 14270 if (!ArgRE->isObjCSelfExpr()) { 14271 Diag(Decl->getLocation(), 14272 diag::note_objc_circular_container_declared_here) 14273 << Decl; 14274 } 14275 } 14276 } 14277 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 14278 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 14279 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 14280 ObjCIvarDecl *Decl = IvarRE->getDecl(); 14281 Diag(Message->getSourceRange().getBegin(), 14282 diag::warn_objc_circular_container) 14283 << Decl << Decl; 14284 Diag(Decl->getLocation(), 14285 diag::note_objc_circular_container_declared_here) 14286 << Decl; 14287 } 14288 } 14289 } 14290 } 14291 } 14292 14293 /// Check a message send to see if it's likely to cause a retain cycle. 14294 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14295 // Only check instance methods whose selector looks like a setter. 14296 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14297 return; 14298 14299 // Try to find a variable that the receiver is strongly owned by. 14300 RetainCycleOwner owner; 14301 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14302 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14303 return; 14304 } else { 14305 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14306 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14307 owner.Loc = msg->getSuperLoc(); 14308 owner.Range = msg->getSuperLoc(); 14309 } 14310 14311 // Check whether the receiver is captured by any of the arguments. 14312 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14313 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14314 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14315 // noescape blocks should not be retained by the method. 14316 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14317 continue; 14318 return diagnoseRetainCycle(*this, capturer, owner); 14319 } 14320 } 14321 } 14322 14323 /// Check a property assign to see if it's likely to cause a retain cycle. 14324 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14325 RetainCycleOwner owner; 14326 if (!findRetainCycleOwner(*this, receiver, owner)) 14327 return; 14328 14329 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14330 diagnoseRetainCycle(*this, capturer, owner); 14331 } 14332 14333 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14334 RetainCycleOwner Owner; 14335 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14336 return; 14337 14338 // Because we don't have an expression for the variable, we have to set the 14339 // location explicitly here. 14340 Owner.Loc = Var->getLocation(); 14341 Owner.Range = Var->getSourceRange(); 14342 14343 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14344 diagnoseRetainCycle(*this, Capturer, Owner); 14345 } 14346 14347 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14348 Expr *RHS, bool isProperty) { 14349 // Check if RHS is an Objective-C object literal, which also can get 14350 // immediately zapped in a weak reference. Note that we explicitly 14351 // allow ObjCStringLiterals, since those are designed to never really die. 14352 RHS = RHS->IgnoreParenImpCasts(); 14353 14354 // This enum needs to match with the 'select' in 14355 // warn_objc_arc_literal_assign (off-by-1). 14356 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14357 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14358 return false; 14359 14360 S.Diag(Loc, diag::warn_arc_literal_assign) 14361 << (unsigned) Kind 14362 << (isProperty ? 0 : 1) 14363 << RHS->getSourceRange(); 14364 14365 return true; 14366 } 14367 14368 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 14369 Qualifiers::ObjCLifetime LT, 14370 Expr *RHS, bool isProperty) { 14371 // Strip off any implicit cast added to get to the one ARC-specific. 14372 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14373 if (cast->getCastKind() == CK_ARCConsumeObject) { 14374 S.Diag(Loc, diag::warn_arc_retained_assign) 14375 << (LT == Qualifiers::OCL_ExplicitNone) 14376 << (isProperty ? 0 : 1) 14377 << RHS->getSourceRange(); 14378 return true; 14379 } 14380 RHS = cast->getSubExpr(); 14381 } 14382 14383 if (LT == Qualifiers::OCL_Weak && 14384 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 14385 return true; 14386 14387 return false; 14388 } 14389 14390 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 14391 QualType LHS, Expr *RHS) { 14392 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 14393 14394 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 14395 return false; 14396 14397 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 14398 return true; 14399 14400 return false; 14401 } 14402 14403 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 14404 Expr *LHS, Expr *RHS) { 14405 QualType LHSType; 14406 // PropertyRef on LHS type need be directly obtained from 14407 // its declaration as it has a PseudoType. 14408 ObjCPropertyRefExpr *PRE 14409 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 14410 if (PRE && !PRE->isImplicitProperty()) { 14411 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14412 if (PD) 14413 LHSType = PD->getType(); 14414 } 14415 14416 if (LHSType.isNull()) 14417 LHSType = LHS->getType(); 14418 14419 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 14420 14421 if (LT == Qualifiers::OCL_Weak) { 14422 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14423 getCurFunction()->markSafeWeakUse(LHS); 14424 } 14425 14426 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14427 return; 14428 14429 // FIXME. Check for other life times. 14430 if (LT != Qualifiers::OCL_None) 14431 return; 14432 14433 if (PRE) { 14434 if (PRE->isImplicitProperty()) 14435 return; 14436 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14437 if (!PD) 14438 return; 14439 14440 unsigned Attributes = PD->getPropertyAttributes(); 14441 if (Attributes & ObjCPropertyAttribute::kind_assign) { 14442 // when 'assign' attribute was not explicitly specified 14443 // by user, ignore it and rely on property type itself 14444 // for lifetime info. 14445 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 14446 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 14447 LHSType->isObjCRetainableType()) 14448 return; 14449 14450 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14451 if (cast->getCastKind() == CK_ARCConsumeObject) { 14452 Diag(Loc, diag::warn_arc_retained_property_assign) 14453 << RHS->getSourceRange(); 14454 return; 14455 } 14456 RHS = cast->getSubExpr(); 14457 } 14458 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 14459 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 14460 return; 14461 } 14462 } 14463 } 14464 14465 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 14466 14467 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 14468 SourceLocation StmtLoc, 14469 const NullStmt *Body) { 14470 // Do not warn if the body is a macro that expands to nothing, e.g: 14471 // 14472 // #define CALL(x) 14473 // if (condition) 14474 // CALL(0); 14475 if (Body->hasLeadingEmptyMacro()) 14476 return false; 14477 14478 // Get line numbers of statement and body. 14479 bool StmtLineInvalid; 14480 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 14481 &StmtLineInvalid); 14482 if (StmtLineInvalid) 14483 return false; 14484 14485 bool BodyLineInvalid; 14486 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 14487 &BodyLineInvalid); 14488 if (BodyLineInvalid) 14489 return false; 14490 14491 // Warn if null statement and body are on the same line. 14492 if (StmtLine != BodyLine) 14493 return false; 14494 14495 return true; 14496 } 14497 14498 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 14499 const Stmt *Body, 14500 unsigned DiagID) { 14501 // Since this is a syntactic check, don't emit diagnostic for template 14502 // instantiations, this just adds noise. 14503 if (CurrentInstantiationScope) 14504 return; 14505 14506 // The body should be a null statement. 14507 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14508 if (!NBody) 14509 return; 14510 14511 // Do the usual checks. 14512 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14513 return; 14514 14515 Diag(NBody->getSemiLoc(), DiagID); 14516 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14517 } 14518 14519 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14520 const Stmt *PossibleBody) { 14521 assert(!CurrentInstantiationScope); // Ensured by caller 14522 14523 SourceLocation StmtLoc; 14524 const Stmt *Body; 14525 unsigned DiagID; 14526 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14527 StmtLoc = FS->getRParenLoc(); 14528 Body = FS->getBody(); 14529 DiagID = diag::warn_empty_for_body; 14530 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14531 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14532 Body = WS->getBody(); 14533 DiagID = diag::warn_empty_while_body; 14534 } else 14535 return; // Neither `for' nor `while'. 14536 14537 // The body should be a null statement. 14538 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14539 if (!NBody) 14540 return; 14541 14542 // Skip expensive checks if diagnostic is disabled. 14543 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14544 return; 14545 14546 // Do the usual checks. 14547 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14548 return; 14549 14550 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14551 // noise level low, emit diagnostics only if for/while is followed by a 14552 // CompoundStmt, e.g.: 14553 // for (int i = 0; i < n; i++); 14554 // { 14555 // a(i); 14556 // } 14557 // or if for/while is followed by a statement with more indentation 14558 // than for/while itself: 14559 // for (int i = 0; i < n; i++); 14560 // a(i); 14561 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14562 if (!ProbableTypo) { 14563 bool BodyColInvalid; 14564 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14565 PossibleBody->getBeginLoc(), &BodyColInvalid); 14566 if (BodyColInvalid) 14567 return; 14568 14569 bool StmtColInvalid; 14570 unsigned StmtCol = 14571 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14572 if (StmtColInvalid) 14573 return; 14574 14575 if (BodyCol > StmtCol) 14576 ProbableTypo = true; 14577 } 14578 14579 if (ProbableTypo) { 14580 Diag(NBody->getSemiLoc(), DiagID); 14581 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14582 } 14583 } 14584 14585 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14586 14587 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14588 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14589 SourceLocation OpLoc) { 14590 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14591 return; 14592 14593 if (inTemplateInstantiation()) 14594 return; 14595 14596 // Strip parens and casts away. 14597 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14598 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14599 14600 // Check for a call expression 14601 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14602 if (!CE || CE->getNumArgs() != 1) 14603 return; 14604 14605 // Check for a call to std::move 14606 if (!CE->isCallToStdMove()) 14607 return; 14608 14609 // Get argument from std::move 14610 RHSExpr = CE->getArg(0); 14611 14612 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14613 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14614 14615 // Two DeclRefExpr's, check that the decls are the same. 14616 if (LHSDeclRef && RHSDeclRef) { 14617 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14618 return; 14619 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14620 RHSDeclRef->getDecl()->getCanonicalDecl()) 14621 return; 14622 14623 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14624 << LHSExpr->getSourceRange() 14625 << RHSExpr->getSourceRange(); 14626 return; 14627 } 14628 14629 // Member variables require a different approach to check for self moves. 14630 // MemberExpr's are the same if every nested MemberExpr refers to the same 14631 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14632 // the base Expr's are CXXThisExpr's. 14633 const Expr *LHSBase = LHSExpr; 14634 const Expr *RHSBase = RHSExpr; 14635 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14636 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14637 if (!LHSME || !RHSME) 14638 return; 14639 14640 while (LHSME && RHSME) { 14641 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14642 RHSME->getMemberDecl()->getCanonicalDecl()) 14643 return; 14644 14645 LHSBase = LHSME->getBase(); 14646 RHSBase = RHSME->getBase(); 14647 LHSME = dyn_cast<MemberExpr>(LHSBase); 14648 RHSME = dyn_cast<MemberExpr>(RHSBase); 14649 } 14650 14651 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14652 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14653 if (LHSDeclRef && RHSDeclRef) { 14654 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14655 return; 14656 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14657 RHSDeclRef->getDecl()->getCanonicalDecl()) 14658 return; 14659 14660 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14661 << LHSExpr->getSourceRange() 14662 << RHSExpr->getSourceRange(); 14663 return; 14664 } 14665 14666 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14667 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14668 << LHSExpr->getSourceRange() 14669 << RHSExpr->getSourceRange(); 14670 } 14671 14672 //===--- Layout compatibility ----------------------------------------------// 14673 14674 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14675 14676 /// Check if two enumeration types are layout-compatible. 14677 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14678 // C++11 [dcl.enum] p8: 14679 // Two enumeration types are layout-compatible if they have the same 14680 // underlying type. 14681 return ED1->isComplete() && ED2->isComplete() && 14682 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14683 } 14684 14685 /// Check if two fields are layout-compatible. 14686 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14687 FieldDecl *Field2) { 14688 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14689 return false; 14690 14691 if (Field1->isBitField() != Field2->isBitField()) 14692 return false; 14693 14694 if (Field1->isBitField()) { 14695 // Make sure that the bit-fields are the same length. 14696 unsigned Bits1 = Field1->getBitWidthValue(C); 14697 unsigned Bits2 = Field2->getBitWidthValue(C); 14698 14699 if (Bits1 != Bits2) 14700 return false; 14701 } 14702 14703 return true; 14704 } 14705 14706 /// Check if two standard-layout structs are layout-compatible. 14707 /// (C++11 [class.mem] p17) 14708 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14709 RecordDecl *RD2) { 14710 // If both records are C++ classes, check that base classes match. 14711 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14712 // If one of records is a CXXRecordDecl we are in C++ mode, 14713 // thus the other one is a CXXRecordDecl, too. 14714 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14715 // Check number of base classes. 14716 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14717 return false; 14718 14719 // Check the base classes. 14720 for (CXXRecordDecl::base_class_const_iterator 14721 Base1 = D1CXX->bases_begin(), 14722 BaseEnd1 = D1CXX->bases_end(), 14723 Base2 = D2CXX->bases_begin(); 14724 Base1 != BaseEnd1; 14725 ++Base1, ++Base2) { 14726 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14727 return false; 14728 } 14729 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14730 // If only RD2 is a C++ class, it should have zero base classes. 14731 if (D2CXX->getNumBases() > 0) 14732 return false; 14733 } 14734 14735 // Check the fields. 14736 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14737 Field2End = RD2->field_end(), 14738 Field1 = RD1->field_begin(), 14739 Field1End = RD1->field_end(); 14740 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14741 if (!isLayoutCompatible(C, *Field1, *Field2)) 14742 return false; 14743 } 14744 if (Field1 != Field1End || Field2 != Field2End) 14745 return false; 14746 14747 return true; 14748 } 14749 14750 /// Check if two standard-layout unions are layout-compatible. 14751 /// (C++11 [class.mem] p18) 14752 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14753 RecordDecl *RD2) { 14754 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14755 for (auto *Field2 : RD2->fields()) 14756 UnmatchedFields.insert(Field2); 14757 14758 for (auto *Field1 : RD1->fields()) { 14759 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14760 I = UnmatchedFields.begin(), 14761 E = UnmatchedFields.end(); 14762 14763 for ( ; I != E; ++I) { 14764 if (isLayoutCompatible(C, Field1, *I)) { 14765 bool Result = UnmatchedFields.erase(*I); 14766 (void) Result; 14767 assert(Result); 14768 break; 14769 } 14770 } 14771 if (I == E) 14772 return false; 14773 } 14774 14775 return UnmatchedFields.empty(); 14776 } 14777 14778 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14779 RecordDecl *RD2) { 14780 if (RD1->isUnion() != RD2->isUnion()) 14781 return false; 14782 14783 if (RD1->isUnion()) 14784 return isLayoutCompatibleUnion(C, RD1, RD2); 14785 else 14786 return isLayoutCompatibleStruct(C, RD1, RD2); 14787 } 14788 14789 /// Check if two types are layout-compatible in C++11 sense. 14790 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14791 if (T1.isNull() || T2.isNull()) 14792 return false; 14793 14794 // C++11 [basic.types] p11: 14795 // If two types T1 and T2 are the same type, then T1 and T2 are 14796 // layout-compatible types. 14797 if (C.hasSameType(T1, T2)) 14798 return true; 14799 14800 T1 = T1.getCanonicalType().getUnqualifiedType(); 14801 T2 = T2.getCanonicalType().getUnqualifiedType(); 14802 14803 const Type::TypeClass TC1 = T1->getTypeClass(); 14804 const Type::TypeClass TC2 = T2->getTypeClass(); 14805 14806 if (TC1 != TC2) 14807 return false; 14808 14809 if (TC1 == Type::Enum) { 14810 return isLayoutCompatible(C, 14811 cast<EnumType>(T1)->getDecl(), 14812 cast<EnumType>(T2)->getDecl()); 14813 } else if (TC1 == Type::Record) { 14814 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14815 return false; 14816 14817 return isLayoutCompatible(C, 14818 cast<RecordType>(T1)->getDecl(), 14819 cast<RecordType>(T2)->getDecl()); 14820 } 14821 14822 return false; 14823 } 14824 14825 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14826 14827 /// Given a type tag expression find the type tag itself. 14828 /// 14829 /// \param TypeExpr Type tag expression, as it appears in user's code. 14830 /// 14831 /// \param VD Declaration of an identifier that appears in a type tag. 14832 /// 14833 /// \param MagicValue Type tag magic value. 14834 /// 14835 /// \param isConstantEvaluated wether the evalaution should be performed in 14836 14837 /// constant context. 14838 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14839 const ValueDecl **VD, uint64_t *MagicValue, 14840 bool isConstantEvaluated) { 14841 while(true) { 14842 if (!TypeExpr) 14843 return false; 14844 14845 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14846 14847 switch (TypeExpr->getStmtClass()) { 14848 case Stmt::UnaryOperatorClass: { 14849 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14850 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14851 TypeExpr = UO->getSubExpr(); 14852 continue; 14853 } 14854 return false; 14855 } 14856 14857 case Stmt::DeclRefExprClass: { 14858 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14859 *VD = DRE->getDecl(); 14860 return true; 14861 } 14862 14863 case Stmt::IntegerLiteralClass: { 14864 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14865 llvm::APInt MagicValueAPInt = IL->getValue(); 14866 if (MagicValueAPInt.getActiveBits() <= 64) { 14867 *MagicValue = MagicValueAPInt.getZExtValue(); 14868 return true; 14869 } else 14870 return false; 14871 } 14872 14873 case Stmt::BinaryConditionalOperatorClass: 14874 case Stmt::ConditionalOperatorClass: { 14875 const AbstractConditionalOperator *ACO = 14876 cast<AbstractConditionalOperator>(TypeExpr); 14877 bool Result; 14878 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14879 isConstantEvaluated)) { 14880 if (Result) 14881 TypeExpr = ACO->getTrueExpr(); 14882 else 14883 TypeExpr = ACO->getFalseExpr(); 14884 continue; 14885 } 14886 return false; 14887 } 14888 14889 case Stmt::BinaryOperatorClass: { 14890 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14891 if (BO->getOpcode() == BO_Comma) { 14892 TypeExpr = BO->getRHS(); 14893 continue; 14894 } 14895 return false; 14896 } 14897 14898 default: 14899 return false; 14900 } 14901 } 14902 } 14903 14904 /// Retrieve the C type corresponding to type tag TypeExpr. 14905 /// 14906 /// \param TypeExpr Expression that specifies a type tag. 14907 /// 14908 /// \param MagicValues Registered magic values. 14909 /// 14910 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14911 /// kind. 14912 /// 14913 /// \param TypeInfo Information about the corresponding C type. 14914 /// 14915 /// \param isConstantEvaluated wether the evalaution should be performed in 14916 /// constant context. 14917 /// 14918 /// \returns true if the corresponding C type was found. 14919 static bool GetMatchingCType( 14920 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14921 const ASTContext &Ctx, 14922 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14923 *MagicValues, 14924 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14925 bool isConstantEvaluated) { 14926 FoundWrongKind = false; 14927 14928 // Variable declaration that has type_tag_for_datatype attribute. 14929 const ValueDecl *VD = nullptr; 14930 14931 uint64_t MagicValue; 14932 14933 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14934 return false; 14935 14936 if (VD) { 14937 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14938 if (I->getArgumentKind() != ArgumentKind) { 14939 FoundWrongKind = true; 14940 return false; 14941 } 14942 TypeInfo.Type = I->getMatchingCType(); 14943 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14944 TypeInfo.MustBeNull = I->getMustBeNull(); 14945 return true; 14946 } 14947 return false; 14948 } 14949 14950 if (!MagicValues) 14951 return false; 14952 14953 llvm::DenseMap<Sema::TypeTagMagicValue, 14954 Sema::TypeTagData>::const_iterator I = 14955 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14956 if (I == MagicValues->end()) 14957 return false; 14958 14959 TypeInfo = I->second; 14960 return true; 14961 } 14962 14963 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14964 uint64_t MagicValue, QualType Type, 14965 bool LayoutCompatible, 14966 bool MustBeNull) { 14967 if (!TypeTagForDatatypeMagicValues) 14968 TypeTagForDatatypeMagicValues.reset( 14969 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14970 14971 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14972 (*TypeTagForDatatypeMagicValues)[Magic] = 14973 TypeTagData(Type, LayoutCompatible, MustBeNull); 14974 } 14975 14976 static bool IsSameCharType(QualType T1, QualType T2) { 14977 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14978 if (!BT1) 14979 return false; 14980 14981 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14982 if (!BT2) 14983 return false; 14984 14985 BuiltinType::Kind T1Kind = BT1->getKind(); 14986 BuiltinType::Kind T2Kind = BT2->getKind(); 14987 14988 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14989 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14990 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14991 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14992 } 14993 14994 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14995 const ArrayRef<const Expr *> ExprArgs, 14996 SourceLocation CallSiteLoc) { 14997 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14998 bool IsPointerAttr = Attr->getIsPointer(); 14999 15000 // Retrieve the argument representing the 'type_tag'. 15001 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15002 if (TypeTagIdxAST >= ExprArgs.size()) { 15003 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15004 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15005 return; 15006 } 15007 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15008 bool FoundWrongKind; 15009 TypeTagData TypeInfo; 15010 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15011 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15012 TypeInfo, isConstantEvaluated())) { 15013 if (FoundWrongKind) 15014 Diag(TypeTagExpr->getExprLoc(), 15015 diag::warn_type_tag_for_datatype_wrong_kind) 15016 << TypeTagExpr->getSourceRange(); 15017 return; 15018 } 15019 15020 // Retrieve the argument representing the 'arg_idx'. 15021 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15022 if (ArgumentIdxAST >= ExprArgs.size()) { 15023 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15024 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15025 return; 15026 } 15027 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15028 if (IsPointerAttr) { 15029 // Skip implicit cast of pointer to `void *' (as a function argument). 15030 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15031 if (ICE->getType()->isVoidPointerType() && 15032 ICE->getCastKind() == CK_BitCast) 15033 ArgumentExpr = ICE->getSubExpr(); 15034 } 15035 QualType ArgumentType = ArgumentExpr->getType(); 15036 15037 // Passing a `void*' pointer shouldn't trigger a warning. 15038 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15039 return; 15040 15041 if (TypeInfo.MustBeNull) { 15042 // Type tag with matching void type requires a null pointer. 15043 if (!ArgumentExpr->isNullPointerConstant(Context, 15044 Expr::NPC_ValueDependentIsNotNull)) { 15045 Diag(ArgumentExpr->getExprLoc(), 15046 diag::warn_type_safety_null_pointer_required) 15047 << ArgumentKind->getName() 15048 << ArgumentExpr->getSourceRange() 15049 << TypeTagExpr->getSourceRange(); 15050 } 15051 return; 15052 } 15053 15054 QualType RequiredType = TypeInfo.Type; 15055 if (IsPointerAttr) 15056 RequiredType = Context.getPointerType(RequiredType); 15057 15058 bool mismatch = false; 15059 if (!TypeInfo.LayoutCompatible) { 15060 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15061 15062 // C++11 [basic.fundamental] p1: 15063 // Plain char, signed char, and unsigned char are three distinct types. 15064 // 15065 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15066 // char' depending on the current char signedness mode. 15067 if (mismatch) 15068 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15069 RequiredType->getPointeeType())) || 15070 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15071 mismatch = false; 15072 } else 15073 if (IsPointerAttr) 15074 mismatch = !isLayoutCompatible(Context, 15075 ArgumentType->getPointeeType(), 15076 RequiredType->getPointeeType()); 15077 else 15078 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15079 15080 if (mismatch) 15081 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15082 << ArgumentType << ArgumentKind 15083 << TypeInfo.LayoutCompatible << RequiredType 15084 << ArgumentExpr->getSourceRange() 15085 << TypeTagExpr->getSourceRange(); 15086 } 15087 15088 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15089 CharUnits Alignment) { 15090 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15091 } 15092 15093 void Sema::DiagnoseMisalignedMembers() { 15094 for (MisalignedMember &m : MisalignedMembers) { 15095 const NamedDecl *ND = m.RD; 15096 if (ND->getName().empty()) { 15097 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15098 ND = TD; 15099 } 15100 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15101 << m.MD << ND << m.E->getSourceRange(); 15102 } 15103 MisalignedMembers.clear(); 15104 } 15105 15106 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15107 E = E->IgnoreParens(); 15108 if (!T->isPointerType() && !T->isIntegerType()) 15109 return; 15110 if (isa<UnaryOperator>(E) && 15111 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15112 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15113 if (isa<MemberExpr>(Op)) { 15114 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15115 if (MA != MisalignedMembers.end() && 15116 (T->isIntegerType() || 15117 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15118 Context.getTypeAlignInChars( 15119 T->getPointeeType()) <= MA->Alignment)))) 15120 MisalignedMembers.erase(MA); 15121 } 15122 } 15123 } 15124 15125 void Sema::RefersToMemberWithReducedAlignment( 15126 Expr *E, 15127 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15128 Action) { 15129 const auto *ME = dyn_cast<MemberExpr>(E); 15130 if (!ME) 15131 return; 15132 15133 // No need to check expressions with an __unaligned-qualified type. 15134 if (E->getType().getQualifiers().hasUnaligned()) 15135 return; 15136 15137 // For a chain of MemberExpr like "a.b.c.d" this list 15138 // will keep FieldDecl's like [d, c, b]. 15139 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15140 const MemberExpr *TopME = nullptr; 15141 bool AnyIsPacked = false; 15142 do { 15143 QualType BaseType = ME->getBase()->getType(); 15144 if (BaseType->isDependentType()) 15145 return; 15146 if (ME->isArrow()) 15147 BaseType = BaseType->getPointeeType(); 15148 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15149 if (RD->isInvalidDecl()) 15150 return; 15151 15152 ValueDecl *MD = ME->getMemberDecl(); 15153 auto *FD = dyn_cast<FieldDecl>(MD); 15154 // We do not care about non-data members. 15155 if (!FD || FD->isInvalidDecl()) 15156 return; 15157 15158 AnyIsPacked = 15159 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15160 ReverseMemberChain.push_back(FD); 15161 15162 TopME = ME; 15163 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15164 } while (ME); 15165 assert(TopME && "We did not compute a topmost MemberExpr!"); 15166 15167 // Not the scope of this diagnostic. 15168 if (!AnyIsPacked) 15169 return; 15170 15171 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15172 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15173 // TODO: The innermost base of the member expression may be too complicated. 15174 // For now, just disregard these cases. This is left for future 15175 // improvement. 15176 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15177 return; 15178 15179 // Alignment expected by the whole expression. 15180 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15181 15182 // No need to do anything else with this case. 15183 if (ExpectedAlignment.isOne()) 15184 return; 15185 15186 // Synthesize offset of the whole access. 15187 CharUnits Offset; 15188 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15189 I++) { 15190 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15191 } 15192 15193 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15194 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15195 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15196 15197 // The base expression of the innermost MemberExpr may give 15198 // stronger guarantees than the class containing the member. 15199 if (DRE && !TopME->isArrow()) { 15200 const ValueDecl *VD = DRE->getDecl(); 15201 if (!VD->getType()->isReferenceType()) 15202 CompleteObjectAlignment = 15203 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15204 } 15205 15206 // Check if the synthesized offset fulfills the alignment. 15207 if (Offset % ExpectedAlignment != 0 || 15208 // It may fulfill the offset it but the effective alignment may still be 15209 // lower than the expected expression alignment. 15210 CompleteObjectAlignment < ExpectedAlignment) { 15211 // If this happens, we want to determine a sensible culprit of this. 15212 // Intuitively, watching the chain of member expressions from right to 15213 // left, we start with the required alignment (as required by the field 15214 // type) but some packed attribute in that chain has reduced the alignment. 15215 // It may happen that another packed structure increases it again. But if 15216 // we are here such increase has not been enough. So pointing the first 15217 // FieldDecl that either is packed or else its RecordDecl is, 15218 // seems reasonable. 15219 FieldDecl *FD = nullptr; 15220 CharUnits Alignment; 15221 for (FieldDecl *FDI : ReverseMemberChain) { 15222 if (FDI->hasAttr<PackedAttr>() || 15223 FDI->getParent()->hasAttr<PackedAttr>()) { 15224 FD = FDI; 15225 Alignment = std::min( 15226 Context.getTypeAlignInChars(FD->getType()), 15227 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15228 break; 15229 } 15230 } 15231 assert(FD && "We did not find a packed FieldDecl!"); 15232 Action(E, FD->getParent(), FD, Alignment); 15233 } 15234 } 15235 15236 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15237 using namespace std::placeholders; 15238 15239 RefersToMemberWithReducedAlignment( 15240 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15241 _2, _3, _4)); 15242 } 15243 15244 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15245 ExprResult CallResult) { 15246 if (checkArgCount(*this, TheCall, 1)) 15247 return ExprError(); 15248 15249 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15250 if (MatrixArg.isInvalid()) 15251 return MatrixArg; 15252 Expr *Matrix = MatrixArg.get(); 15253 15254 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15255 if (!MType) { 15256 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 15257 return ExprError(); 15258 } 15259 15260 // Create returned matrix type by swapping rows and columns of the argument 15261 // matrix type. 15262 QualType ResultType = Context.getConstantMatrixType( 15263 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15264 15265 // Change the return type to the type of the returned matrix. 15266 TheCall->setType(ResultType); 15267 15268 // Update call argument to use the possibly converted matrix argument. 15269 TheCall->setArg(0, Matrix); 15270 return CallResult; 15271 } 15272 15273 // Get and verify the matrix dimensions. 15274 static llvm::Optional<unsigned> 15275 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 15276 llvm::APSInt Value(64); 15277 SourceLocation ErrorPos; 15278 if (!Expr->isIntegerConstantExpr(Value, S.Context, &ErrorPos)) { 15279 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 15280 << Name; 15281 return {}; 15282 } 15283 uint64_t Dim = Value.getZExtValue(); 15284 if (!ConstantMatrixType::isDimensionValid(Dim)) { 15285 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 15286 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 15287 return {}; 15288 } 15289 return Dim; 15290 } 15291 15292 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 15293 ExprResult CallResult) { 15294 if (!getLangOpts().MatrixTypes) { 15295 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 15296 return ExprError(); 15297 } 15298 15299 if (checkArgCount(*this, TheCall, 4)) 15300 return ExprError(); 15301 15302 unsigned PtrArgIdx = 0; 15303 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15304 Expr *RowsExpr = TheCall->getArg(1); 15305 Expr *ColumnsExpr = TheCall->getArg(2); 15306 Expr *StrideExpr = TheCall->getArg(3); 15307 15308 bool ArgError = false; 15309 15310 // Check pointer argument. 15311 { 15312 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15313 if (PtrConv.isInvalid()) 15314 return PtrConv; 15315 PtrExpr = PtrConv.get(); 15316 TheCall->setArg(0, PtrExpr); 15317 if (PtrExpr->isTypeDependent()) { 15318 TheCall->setType(Context.DependentTy); 15319 return TheCall; 15320 } 15321 } 15322 15323 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15324 QualType ElementTy; 15325 if (!PtrTy) { 15326 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15327 << PtrArgIdx + 1; 15328 ArgError = true; 15329 } else { 15330 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 15331 15332 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 15333 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15334 << PtrArgIdx + 1; 15335 ArgError = true; 15336 } 15337 } 15338 15339 // Apply default Lvalue conversions and convert the expression to size_t. 15340 auto ApplyArgumentConversions = [this](Expr *E) { 15341 ExprResult Conv = DefaultLvalueConversion(E); 15342 if (Conv.isInvalid()) 15343 return Conv; 15344 15345 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 15346 }; 15347 15348 // Apply conversion to row and column expressions. 15349 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 15350 if (!RowsConv.isInvalid()) { 15351 RowsExpr = RowsConv.get(); 15352 TheCall->setArg(1, RowsExpr); 15353 } else 15354 RowsExpr = nullptr; 15355 15356 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 15357 if (!ColumnsConv.isInvalid()) { 15358 ColumnsExpr = ColumnsConv.get(); 15359 TheCall->setArg(2, ColumnsExpr); 15360 } else 15361 ColumnsExpr = nullptr; 15362 15363 // If any any part of the result matrix type is still pending, just use 15364 // Context.DependentTy, until all parts are resolved. 15365 if ((RowsExpr && RowsExpr->isTypeDependent()) || 15366 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 15367 TheCall->setType(Context.DependentTy); 15368 return CallResult; 15369 } 15370 15371 // Check row and column dimenions. 15372 llvm::Optional<unsigned> MaybeRows; 15373 if (RowsExpr) 15374 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 15375 15376 llvm::Optional<unsigned> MaybeColumns; 15377 if (ColumnsExpr) 15378 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 15379 15380 // Check stride argument. 15381 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 15382 if (StrideConv.isInvalid()) 15383 return ExprError(); 15384 StrideExpr = StrideConv.get(); 15385 TheCall->setArg(3, StrideExpr); 15386 15387 llvm::APSInt Value(64); 15388 if (MaybeRows && StrideExpr->isIntegerConstantExpr(Value, Context)) { 15389 uint64_t Stride = Value.getZExtValue(); 15390 if (Stride < *MaybeRows) { 15391 Diag(StrideExpr->getBeginLoc(), 15392 diag::err_builtin_matrix_stride_too_small); 15393 ArgError = true; 15394 } 15395 } 15396 15397 if (ArgError || !MaybeRows || !MaybeColumns) 15398 return ExprError(); 15399 15400 TheCall->setType( 15401 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 15402 return CallResult; 15403 } 15404 15405 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 15406 ExprResult CallResult) { 15407 if (checkArgCount(*this, TheCall, 3)) 15408 return ExprError(); 15409 15410 unsigned PtrArgIdx = 1; 15411 Expr *MatrixExpr = TheCall->getArg(0); 15412 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15413 Expr *StrideExpr = TheCall->getArg(2); 15414 15415 bool ArgError = false; 15416 15417 { 15418 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 15419 if (MatrixConv.isInvalid()) 15420 return MatrixConv; 15421 MatrixExpr = MatrixConv.get(); 15422 TheCall->setArg(0, MatrixExpr); 15423 } 15424 if (MatrixExpr->isTypeDependent()) { 15425 TheCall->setType(Context.DependentTy); 15426 return TheCall; 15427 } 15428 15429 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 15430 if (!MatrixTy) { 15431 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 15432 ArgError = true; 15433 } 15434 15435 { 15436 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15437 if (PtrConv.isInvalid()) 15438 return PtrConv; 15439 PtrExpr = PtrConv.get(); 15440 TheCall->setArg(1, PtrExpr); 15441 if (PtrExpr->isTypeDependent()) { 15442 TheCall->setType(Context.DependentTy); 15443 return TheCall; 15444 } 15445 } 15446 15447 // Check pointer argument. 15448 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15449 if (!PtrTy) { 15450 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15451 << PtrArgIdx + 1; 15452 ArgError = true; 15453 } else { 15454 QualType ElementTy = PtrTy->getPointeeType(); 15455 if (ElementTy.isConstQualified()) { 15456 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 15457 ArgError = true; 15458 } 15459 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 15460 if (MatrixTy && 15461 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 15462 Diag(PtrExpr->getBeginLoc(), 15463 diag::err_builtin_matrix_pointer_arg_mismatch) 15464 << ElementTy << MatrixTy->getElementType(); 15465 ArgError = true; 15466 } 15467 } 15468 15469 // Apply default Lvalue conversions and convert the stride expression to 15470 // size_t. 15471 { 15472 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 15473 if (StrideConv.isInvalid()) 15474 return StrideConv; 15475 15476 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 15477 if (StrideConv.isInvalid()) 15478 return StrideConv; 15479 StrideExpr = StrideConv.get(); 15480 TheCall->setArg(2, StrideExpr); 15481 } 15482 15483 // Check stride argument. 15484 llvm::APSInt Value(64); 15485 if (MatrixTy && StrideExpr->isIntegerConstantExpr(Value, Context)) { 15486 uint64_t Stride = Value.getZExtValue(); 15487 if (Stride < MatrixTy->getNumRows()) { 15488 Diag(StrideExpr->getBeginLoc(), 15489 diag::err_builtin_matrix_stride_too_small); 15490 ArgError = true; 15491 } 15492 } 15493 15494 if (ArgError) 15495 return ExprError(); 15496 15497 return CallResult; 15498 } 15499