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 value dependent. 241 if (!AlignOp->isValueDependent() && 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 case PPC::BI__builtin_altivec_vsldbi: 3132 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3133 case PPC::BI__builtin_altivec_vsrdbi: 3134 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3135 case PPC::BI__builtin_vsx_xxpermx: 3136 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3137 } 3138 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3139 } 3140 3141 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3142 CallExpr *TheCall) { 3143 // position of memory order and scope arguments in the builtin 3144 unsigned OrderIndex, ScopeIndex; 3145 switch (BuiltinID) { 3146 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3147 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3148 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3149 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3150 OrderIndex = 2; 3151 ScopeIndex = 3; 3152 break; 3153 case AMDGPU::BI__builtin_amdgcn_fence: 3154 OrderIndex = 0; 3155 ScopeIndex = 1; 3156 break; 3157 default: 3158 return false; 3159 } 3160 3161 ExprResult Arg = TheCall->getArg(OrderIndex); 3162 auto ArgExpr = Arg.get(); 3163 Expr::EvalResult ArgResult; 3164 3165 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3166 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3167 << ArgExpr->getType(); 3168 int ord = ArgResult.Val.getInt().getZExtValue(); 3169 3170 // Check valididty of memory ordering as per C11 / C++11's memody model. 3171 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3172 case llvm::AtomicOrderingCABI::acquire: 3173 case llvm::AtomicOrderingCABI::release: 3174 case llvm::AtomicOrderingCABI::acq_rel: 3175 case llvm::AtomicOrderingCABI::seq_cst: 3176 break; 3177 default: { 3178 return Diag(ArgExpr->getBeginLoc(), 3179 diag::warn_atomic_op_has_invalid_memory_order) 3180 << ArgExpr->getSourceRange(); 3181 } 3182 } 3183 3184 Arg = TheCall->getArg(ScopeIndex); 3185 ArgExpr = Arg.get(); 3186 Expr::EvalResult ArgResult1; 3187 // Check that sync scope is a constant literal 3188 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen, 3189 Context)) 3190 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3191 << ArgExpr->getType(); 3192 3193 return false; 3194 } 3195 3196 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3197 CallExpr *TheCall) { 3198 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3199 Expr *Arg = TheCall->getArg(0); 3200 llvm::APSInt AbortCode(32); 3201 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3202 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3203 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3204 << Arg->getSourceRange(); 3205 } 3206 3207 // For intrinsics which take an immediate value as part of the instruction, 3208 // range check them here. 3209 unsigned i = 0, l = 0, u = 0; 3210 switch (BuiltinID) { 3211 default: return false; 3212 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3213 case SystemZ::BI__builtin_s390_verimb: 3214 case SystemZ::BI__builtin_s390_verimh: 3215 case SystemZ::BI__builtin_s390_verimf: 3216 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3217 case SystemZ::BI__builtin_s390_vfaeb: 3218 case SystemZ::BI__builtin_s390_vfaeh: 3219 case SystemZ::BI__builtin_s390_vfaef: 3220 case SystemZ::BI__builtin_s390_vfaebs: 3221 case SystemZ::BI__builtin_s390_vfaehs: 3222 case SystemZ::BI__builtin_s390_vfaefs: 3223 case SystemZ::BI__builtin_s390_vfaezb: 3224 case SystemZ::BI__builtin_s390_vfaezh: 3225 case SystemZ::BI__builtin_s390_vfaezf: 3226 case SystemZ::BI__builtin_s390_vfaezbs: 3227 case SystemZ::BI__builtin_s390_vfaezhs: 3228 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3229 case SystemZ::BI__builtin_s390_vfisb: 3230 case SystemZ::BI__builtin_s390_vfidb: 3231 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3232 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3233 case SystemZ::BI__builtin_s390_vftcisb: 3234 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3235 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3236 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3237 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3238 case SystemZ::BI__builtin_s390_vstrcb: 3239 case SystemZ::BI__builtin_s390_vstrch: 3240 case SystemZ::BI__builtin_s390_vstrcf: 3241 case SystemZ::BI__builtin_s390_vstrczb: 3242 case SystemZ::BI__builtin_s390_vstrczh: 3243 case SystemZ::BI__builtin_s390_vstrczf: 3244 case SystemZ::BI__builtin_s390_vstrcbs: 3245 case SystemZ::BI__builtin_s390_vstrchs: 3246 case SystemZ::BI__builtin_s390_vstrcfs: 3247 case SystemZ::BI__builtin_s390_vstrczbs: 3248 case SystemZ::BI__builtin_s390_vstrczhs: 3249 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3250 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3251 case SystemZ::BI__builtin_s390_vfminsb: 3252 case SystemZ::BI__builtin_s390_vfmaxsb: 3253 case SystemZ::BI__builtin_s390_vfmindb: 3254 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3255 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3256 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3257 } 3258 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3259 } 3260 3261 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3262 /// This checks that the target supports __builtin_cpu_supports and 3263 /// that the string argument is constant and valid. 3264 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3265 CallExpr *TheCall) { 3266 Expr *Arg = TheCall->getArg(0); 3267 3268 // Check if the argument is a string literal. 3269 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3270 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3271 << Arg->getSourceRange(); 3272 3273 // Check the contents of the string. 3274 StringRef Feature = 3275 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3276 if (!TI.validateCpuSupports(Feature)) 3277 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3278 << Arg->getSourceRange(); 3279 return false; 3280 } 3281 3282 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3283 /// This checks that the target supports __builtin_cpu_is and 3284 /// that the string argument is constant and valid. 3285 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3286 Expr *Arg = TheCall->getArg(0); 3287 3288 // Check if the argument is a string literal. 3289 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3290 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3291 << Arg->getSourceRange(); 3292 3293 // Check the contents of the string. 3294 StringRef Feature = 3295 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3296 if (!TI.validateCpuIs(Feature)) 3297 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3298 << Arg->getSourceRange(); 3299 return false; 3300 } 3301 3302 // Check if the rounding mode is legal. 3303 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3304 // Indicates if this instruction has rounding control or just SAE. 3305 bool HasRC = false; 3306 3307 unsigned ArgNum = 0; 3308 switch (BuiltinID) { 3309 default: 3310 return false; 3311 case X86::BI__builtin_ia32_vcvttsd2si32: 3312 case X86::BI__builtin_ia32_vcvttsd2si64: 3313 case X86::BI__builtin_ia32_vcvttsd2usi32: 3314 case X86::BI__builtin_ia32_vcvttsd2usi64: 3315 case X86::BI__builtin_ia32_vcvttss2si32: 3316 case X86::BI__builtin_ia32_vcvttss2si64: 3317 case X86::BI__builtin_ia32_vcvttss2usi32: 3318 case X86::BI__builtin_ia32_vcvttss2usi64: 3319 ArgNum = 1; 3320 break; 3321 case X86::BI__builtin_ia32_maxpd512: 3322 case X86::BI__builtin_ia32_maxps512: 3323 case X86::BI__builtin_ia32_minpd512: 3324 case X86::BI__builtin_ia32_minps512: 3325 ArgNum = 2; 3326 break; 3327 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3328 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3329 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3330 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3331 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3332 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3333 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3334 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3335 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3336 case X86::BI__builtin_ia32_exp2pd_mask: 3337 case X86::BI__builtin_ia32_exp2ps_mask: 3338 case X86::BI__builtin_ia32_getexppd512_mask: 3339 case X86::BI__builtin_ia32_getexpps512_mask: 3340 case X86::BI__builtin_ia32_rcp28pd_mask: 3341 case X86::BI__builtin_ia32_rcp28ps_mask: 3342 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3343 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3344 case X86::BI__builtin_ia32_vcomisd: 3345 case X86::BI__builtin_ia32_vcomiss: 3346 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3347 ArgNum = 3; 3348 break; 3349 case X86::BI__builtin_ia32_cmppd512_mask: 3350 case X86::BI__builtin_ia32_cmpps512_mask: 3351 case X86::BI__builtin_ia32_cmpsd_mask: 3352 case X86::BI__builtin_ia32_cmpss_mask: 3353 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3354 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3355 case X86::BI__builtin_ia32_getexpss128_round_mask: 3356 case X86::BI__builtin_ia32_getmantpd512_mask: 3357 case X86::BI__builtin_ia32_getmantps512_mask: 3358 case X86::BI__builtin_ia32_maxsd_round_mask: 3359 case X86::BI__builtin_ia32_maxss_round_mask: 3360 case X86::BI__builtin_ia32_minsd_round_mask: 3361 case X86::BI__builtin_ia32_minss_round_mask: 3362 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3363 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3364 case X86::BI__builtin_ia32_reducepd512_mask: 3365 case X86::BI__builtin_ia32_reduceps512_mask: 3366 case X86::BI__builtin_ia32_rndscalepd_mask: 3367 case X86::BI__builtin_ia32_rndscaleps_mask: 3368 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3369 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3370 ArgNum = 4; 3371 break; 3372 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3373 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3374 case X86::BI__builtin_ia32_fixupimmps512_mask: 3375 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3376 case X86::BI__builtin_ia32_fixupimmsd_mask: 3377 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3378 case X86::BI__builtin_ia32_fixupimmss_mask: 3379 case X86::BI__builtin_ia32_fixupimmss_maskz: 3380 case X86::BI__builtin_ia32_getmantsd_round_mask: 3381 case X86::BI__builtin_ia32_getmantss_round_mask: 3382 case X86::BI__builtin_ia32_rangepd512_mask: 3383 case X86::BI__builtin_ia32_rangeps512_mask: 3384 case X86::BI__builtin_ia32_rangesd128_round_mask: 3385 case X86::BI__builtin_ia32_rangess128_round_mask: 3386 case X86::BI__builtin_ia32_reducesd_mask: 3387 case X86::BI__builtin_ia32_reducess_mask: 3388 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3389 case X86::BI__builtin_ia32_rndscaless_round_mask: 3390 ArgNum = 5; 3391 break; 3392 case X86::BI__builtin_ia32_vcvtsd2si64: 3393 case X86::BI__builtin_ia32_vcvtsd2si32: 3394 case X86::BI__builtin_ia32_vcvtsd2usi32: 3395 case X86::BI__builtin_ia32_vcvtsd2usi64: 3396 case X86::BI__builtin_ia32_vcvtss2si32: 3397 case X86::BI__builtin_ia32_vcvtss2si64: 3398 case X86::BI__builtin_ia32_vcvtss2usi32: 3399 case X86::BI__builtin_ia32_vcvtss2usi64: 3400 case X86::BI__builtin_ia32_sqrtpd512: 3401 case X86::BI__builtin_ia32_sqrtps512: 3402 ArgNum = 1; 3403 HasRC = true; 3404 break; 3405 case X86::BI__builtin_ia32_addpd512: 3406 case X86::BI__builtin_ia32_addps512: 3407 case X86::BI__builtin_ia32_divpd512: 3408 case X86::BI__builtin_ia32_divps512: 3409 case X86::BI__builtin_ia32_mulpd512: 3410 case X86::BI__builtin_ia32_mulps512: 3411 case X86::BI__builtin_ia32_subpd512: 3412 case X86::BI__builtin_ia32_subps512: 3413 case X86::BI__builtin_ia32_cvtsi2sd64: 3414 case X86::BI__builtin_ia32_cvtsi2ss32: 3415 case X86::BI__builtin_ia32_cvtsi2ss64: 3416 case X86::BI__builtin_ia32_cvtusi2sd64: 3417 case X86::BI__builtin_ia32_cvtusi2ss32: 3418 case X86::BI__builtin_ia32_cvtusi2ss64: 3419 ArgNum = 2; 3420 HasRC = true; 3421 break; 3422 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3423 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3424 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3425 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3426 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3427 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3428 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3429 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3430 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3431 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3432 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3433 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3434 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3435 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3436 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3437 ArgNum = 3; 3438 HasRC = true; 3439 break; 3440 case X86::BI__builtin_ia32_addss_round_mask: 3441 case X86::BI__builtin_ia32_addsd_round_mask: 3442 case X86::BI__builtin_ia32_divss_round_mask: 3443 case X86::BI__builtin_ia32_divsd_round_mask: 3444 case X86::BI__builtin_ia32_mulss_round_mask: 3445 case X86::BI__builtin_ia32_mulsd_round_mask: 3446 case X86::BI__builtin_ia32_subss_round_mask: 3447 case X86::BI__builtin_ia32_subsd_round_mask: 3448 case X86::BI__builtin_ia32_scalefpd512_mask: 3449 case X86::BI__builtin_ia32_scalefps512_mask: 3450 case X86::BI__builtin_ia32_scalefsd_round_mask: 3451 case X86::BI__builtin_ia32_scalefss_round_mask: 3452 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3453 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3454 case X86::BI__builtin_ia32_sqrtss_round_mask: 3455 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3456 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3457 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3458 case X86::BI__builtin_ia32_vfmaddss3_mask: 3459 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3460 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3461 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3462 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3463 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3464 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3465 case X86::BI__builtin_ia32_vfmaddps512_mask: 3466 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3467 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3468 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3469 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3470 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3471 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3472 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3473 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3474 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3475 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3476 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3477 ArgNum = 4; 3478 HasRC = true; 3479 break; 3480 } 3481 3482 llvm::APSInt Result; 3483 3484 // We can't check the value of a dependent argument. 3485 Expr *Arg = TheCall->getArg(ArgNum); 3486 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3487 return false; 3488 3489 // Check constant-ness first. 3490 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3491 return true; 3492 3493 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3494 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3495 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3496 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3497 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3498 Result == 8/*ROUND_NO_EXC*/ || 3499 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3500 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3501 return false; 3502 3503 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3504 << Arg->getSourceRange(); 3505 } 3506 3507 // Check if the gather/scatter scale is legal. 3508 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3509 CallExpr *TheCall) { 3510 unsigned ArgNum = 0; 3511 switch (BuiltinID) { 3512 default: 3513 return false; 3514 case X86::BI__builtin_ia32_gatherpfdpd: 3515 case X86::BI__builtin_ia32_gatherpfdps: 3516 case X86::BI__builtin_ia32_gatherpfqpd: 3517 case X86::BI__builtin_ia32_gatherpfqps: 3518 case X86::BI__builtin_ia32_scatterpfdpd: 3519 case X86::BI__builtin_ia32_scatterpfdps: 3520 case X86::BI__builtin_ia32_scatterpfqpd: 3521 case X86::BI__builtin_ia32_scatterpfqps: 3522 ArgNum = 3; 3523 break; 3524 case X86::BI__builtin_ia32_gatherd_pd: 3525 case X86::BI__builtin_ia32_gatherd_pd256: 3526 case X86::BI__builtin_ia32_gatherq_pd: 3527 case X86::BI__builtin_ia32_gatherq_pd256: 3528 case X86::BI__builtin_ia32_gatherd_ps: 3529 case X86::BI__builtin_ia32_gatherd_ps256: 3530 case X86::BI__builtin_ia32_gatherq_ps: 3531 case X86::BI__builtin_ia32_gatherq_ps256: 3532 case X86::BI__builtin_ia32_gatherd_q: 3533 case X86::BI__builtin_ia32_gatherd_q256: 3534 case X86::BI__builtin_ia32_gatherq_q: 3535 case X86::BI__builtin_ia32_gatherq_q256: 3536 case X86::BI__builtin_ia32_gatherd_d: 3537 case X86::BI__builtin_ia32_gatherd_d256: 3538 case X86::BI__builtin_ia32_gatherq_d: 3539 case X86::BI__builtin_ia32_gatherq_d256: 3540 case X86::BI__builtin_ia32_gather3div2df: 3541 case X86::BI__builtin_ia32_gather3div2di: 3542 case X86::BI__builtin_ia32_gather3div4df: 3543 case X86::BI__builtin_ia32_gather3div4di: 3544 case X86::BI__builtin_ia32_gather3div4sf: 3545 case X86::BI__builtin_ia32_gather3div4si: 3546 case X86::BI__builtin_ia32_gather3div8sf: 3547 case X86::BI__builtin_ia32_gather3div8si: 3548 case X86::BI__builtin_ia32_gather3siv2df: 3549 case X86::BI__builtin_ia32_gather3siv2di: 3550 case X86::BI__builtin_ia32_gather3siv4df: 3551 case X86::BI__builtin_ia32_gather3siv4di: 3552 case X86::BI__builtin_ia32_gather3siv4sf: 3553 case X86::BI__builtin_ia32_gather3siv4si: 3554 case X86::BI__builtin_ia32_gather3siv8sf: 3555 case X86::BI__builtin_ia32_gather3siv8si: 3556 case X86::BI__builtin_ia32_gathersiv8df: 3557 case X86::BI__builtin_ia32_gathersiv16sf: 3558 case X86::BI__builtin_ia32_gatherdiv8df: 3559 case X86::BI__builtin_ia32_gatherdiv16sf: 3560 case X86::BI__builtin_ia32_gathersiv8di: 3561 case X86::BI__builtin_ia32_gathersiv16si: 3562 case X86::BI__builtin_ia32_gatherdiv8di: 3563 case X86::BI__builtin_ia32_gatherdiv16si: 3564 case X86::BI__builtin_ia32_scatterdiv2df: 3565 case X86::BI__builtin_ia32_scatterdiv2di: 3566 case X86::BI__builtin_ia32_scatterdiv4df: 3567 case X86::BI__builtin_ia32_scatterdiv4di: 3568 case X86::BI__builtin_ia32_scatterdiv4sf: 3569 case X86::BI__builtin_ia32_scatterdiv4si: 3570 case X86::BI__builtin_ia32_scatterdiv8sf: 3571 case X86::BI__builtin_ia32_scatterdiv8si: 3572 case X86::BI__builtin_ia32_scattersiv2df: 3573 case X86::BI__builtin_ia32_scattersiv2di: 3574 case X86::BI__builtin_ia32_scattersiv4df: 3575 case X86::BI__builtin_ia32_scattersiv4di: 3576 case X86::BI__builtin_ia32_scattersiv4sf: 3577 case X86::BI__builtin_ia32_scattersiv4si: 3578 case X86::BI__builtin_ia32_scattersiv8sf: 3579 case X86::BI__builtin_ia32_scattersiv8si: 3580 case X86::BI__builtin_ia32_scattersiv8df: 3581 case X86::BI__builtin_ia32_scattersiv16sf: 3582 case X86::BI__builtin_ia32_scatterdiv8df: 3583 case X86::BI__builtin_ia32_scatterdiv16sf: 3584 case X86::BI__builtin_ia32_scattersiv8di: 3585 case X86::BI__builtin_ia32_scattersiv16si: 3586 case X86::BI__builtin_ia32_scatterdiv8di: 3587 case X86::BI__builtin_ia32_scatterdiv16si: 3588 ArgNum = 4; 3589 break; 3590 } 3591 3592 llvm::APSInt Result; 3593 3594 // We can't check the value of a dependent argument. 3595 Expr *Arg = TheCall->getArg(ArgNum); 3596 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3597 return false; 3598 3599 // Check constant-ness first. 3600 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3601 return true; 3602 3603 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3604 return false; 3605 3606 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3607 << Arg->getSourceRange(); 3608 } 3609 3610 static bool isX86_32Builtin(unsigned BuiltinID) { 3611 // These builtins only work on x86-32 targets. 3612 switch (BuiltinID) { 3613 case X86::BI__builtin_ia32_readeflags_u32: 3614 case X86::BI__builtin_ia32_writeeflags_u32: 3615 return true; 3616 } 3617 3618 return false; 3619 } 3620 3621 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3622 CallExpr *TheCall) { 3623 if (BuiltinID == X86::BI__builtin_cpu_supports) 3624 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3625 3626 if (BuiltinID == X86::BI__builtin_cpu_is) 3627 return SemaBuiltinCpuIs(*this, TI, TheCall); 3628 3629 // Check for 32-bit only builtins on a 64-bit target. 3630 const llvm::Triple &TT = TI.getTriple(); 3631 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3632 return Diag(TheCall->getCallee()->getBeginLoc(), 3633 diag::err_32_bit_builtin_64_bit_tgt); 3634 3635 // If the intrinsic has rounding or SAE make sure its valid. 3636 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3637 return true; 3638 3639 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3640 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3641 return true; 3642 3643 // For intrinsics which take an immediate value as part of the instruction, 3644 // range check them here. 3645 int i = 0, l = 0, u = 0; 3646 switch (BuiltinID) { 3647 default: 3648 return false; 3649 case X86::BI__builtin_ia32_vec_ext_v2si: 3650 case X86::BI__builtin_ia32_vec_ext_v2di: 3651 case X86::BI__builtin_ia32_vextractf128_pd256: 3652 case X86::BI__builtin_ia32_vextractf128_ps256: 3653 case X86::BI__builtin_ia32_vextractf128_si256: 3654 case X86::BI__builtin_ia32_extract128i256: 3655 case X86::BI__builtin_ia32_extractf64x4_mask: 3656 case X86::BI__builtin_ia32_extracti64x4_mask: 3657 case X86::BI__builtin_ia32_extractf32x8_mask: 3658 case X86::BI__builtin_ia32_extracti32x8_mask: 3659 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3660 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3661 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3662 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3663 i = 1; l = 0; u = 1; 3664 break; 3665 case X86::BI__builtin_ia32_vec_set_v2di: 3666 case X86::BI__builtin_ia32_vinsertf128_pd256: 3667 case X86::BI__builtin_ia32_vinsertf128_ps256: 3668 case X86::BI__builtin_ia32_vinsertf128_si256: 3669 case X86::BI__builtin_ia32_insert128i256: 3670 case X86::BI__builtin_ia32_insertf32x8: 3671 case X86::BI__builtin_ia32_inserti32x8: 3672 case X86::BI__builtin_ia32_insertf64x4: 3673 case X86::BI__builtin_ia32_inserti64x4: 3674 case X86::BI__builtin_ia32_insertf64x2_256: 3675 case X86::BI__builtin_ia32_inserti64x2_256: 3676 case X86::BI__builtin_ia32_insertf32x4_256: 3677 case X86::BI__builtin_ia32_inserti32x4_256: 3678 i = 2; l = 0; u = 1; 3679 break; 3680 case X86::BI__builtin_ia32_vpermilpd: 3681 case X86::BI__builtin_ia32_vec_ext_v4hi: 3682 case X86::BI__builtin_ia32_vec_ext_v4si: 3683 case X86::BI__builtin_ia32_vec_ext_v4sf: 3684 case X86::BI__builtin_ia32_vec_ext_v4di: 3685 case X86::BI__builtin_ia32_extractf32x4_mask: 3686 case X86::BI__builtin_ia32_extracti32x4_mask: 3687 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3688 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3689 i = 1; l = 0; u = 3; 3690 break; 3691 case X86::BI_mm_prefetch: 3692 case X86::BI__builtin_ia32_vec_ext_v8hi: 3693 case X86::BI__builtin_ia32_vec_ext_v8si: 3694 i = 1; l = 0; u = 7; 3695 break; 3696 case X86::BI__builtin_ia32_sha1rnds4: 3697 case X86::BI__builtin_ia32_blendpd: 3698 case X86::BI__builtin_ia32_shufpd: 3699 case X86::BI__builtin_ia32_vec_set_v4hi: 3700 case X86::BI__builtin_ia32_vec_set_v4si: 3701 case X86::BI__builtin_ia32_vec_set_v4di: 3702 case X86::BI__builtin_ia32_shuf_f32x4_256: 3703 case X86::BI__builtin_ia32_shuf_f64x2_256: 3704 case X86::BI__builtin_ia32_shuf_i32x4_256: 3705 case X86::BI__builtin_ia32_shuf_i64x2_256: 3706 case X86::BI__builtin_ia32_insertf64x2_512: 3707 case X86::BI__builtin_ia32_inserti64x2_512: 3708 case X86::BI__builtin_ia32_insertf32x4: 3709 case X86::BI__builtin_ia32_inserti32x4: 3710 i = 2; l = 0; u = 3; 3711 break; 3712 case X86::BI__builtin_ia32_vpermil2pd: 3713 case X86::BI__builtin_ia32_vpermil2pd256: 3714 case X86::BI__builtin_ia32_vpermil2ps: 3715 case X86::BI__builtin_ia32_vpermil2ps256: 3716 i = 3; l = 0; u = 3; 3717 break; 3718 case X86::BI__builtin_ia32_cmpb128_mask: 3719 case X86::BI__builtin_ia32_cmpw128_mask: 3720 case X86::BI__builtin_ia32_cmpd128_mask: 3721 case X86::BI__builtin_ia32_cmpq128_mask: 3722 case X86::BI__builtin_ia32_cmpb256_mask: 3723 case X86::BI__builtin_ia32_cmpw256_mask: 3724 case X86::BI__builtin_ia32_cmpd256_mask: 3725 case X86::BI__builtin_ia32_cmpq256_mask: 3726 case X86::BI__builtin_ia32_cmpb512_mask: 3727 case X86::BI__builtin_ia32_cmpw512_mask: 3728 case X86::BI__builtin_ia32_cmpd512_mask: 3729 case X86::BI__builtin_ia32_cmpq512_mask: 3730 case X86::BI__builtin_ia32_ucmpb128_mask: 3731 case X86::BI__builtin_ia32_ucmpw128_mask: 3732 case X86::BI__builtin_ia32_ucmpd128_mask: 3733 case X86::BI__builtin_ia32_ucmpq128_mask: 3734 case X86::BI__builtin_ia32_ucmpb256_mask: 3735 case X86::BI__builtin_ia32_ucmpw256_mask: 3736 case X86::BI__builtin_ia32_ucmpd256_mask: 3737 case X86::BI__builtin_ia32_ucmpq256_mask: 3738 case X86::BI__builtin_ia32_ucmpb512_mask: 3739 case X86::BI__builtin_ia32_ucmpw512_mask: 3740 case X86::BI__builtin_ia32_ucmpd512_mask: 3741 case X86::BI__builtin_ia32_ucmpq512_mask: 3742 case X86::BI__builtin_ia32_vpcomub: 3743 case X86::BI__builtin_ia32_vpcomuw: 3744 case X86::BI__builtin_ia32_vpcomud: 3745 case X86::BI__builtin_ia32_vpcomuq: 3746 case X86::BI__builtin_ia32_vpcomb: 3747 case X86::BI__builtin_ia32_vpcomw: 3748 case X86::BI__builtin_ia32_vpcomd: 3749 case X86::BI__builtin_ia32_vpcomq: 3750 case X86::BI__builtin_ia32_vec_set_v8hi: 3751 case X86::BI__builtin_ia32_vec_set_v8si: 3752 i = 2; l = 0; u = 7; 3753 break; 3754 case X86::BI__builtin_ia32_vpermilpd256: 3755 case X86::BI__builtin_ia32_roundps: 3756 case X86::BI__builtin_ia32_roundpd: 3757 case X86::BI__builtin_ia32_roundps256: 3758 case X86::BI__builtin_ia32_roundpd256: 3759 case X86::BI__builtin_ia32_getmantpd128_mask: 3760 case X86::BI__builtin_ia32_getmantpd256_mask: 3761 case X86::BI__builtin_ia32_getmantps128_mask: 3762 case X86::BI__builtin_ia32_getmantps256_mask: 3763 case X86::BI__builtin_ia32_getmantpd512_mask: 3764 case X86::BI__builtin_ia32_getmantps512_mask: 3765 case X86::BI__builtin_ia32_vec_ext_v16qi: 3766 case X86::BI__builtin_ia32_vec_ext_v16hi: 3767 i = 1; l = 0; u = 15; 3768 break; 3769 case X86::BI__builtin_ia32_pblendd128: 3770 case X86::BI__builtin_ia32_blendps: 3771 case X86::BI__builtin_ia32_blendpd256: 3772 case X86::BI__builtin_ia32_shufpd256: 3773 case X86::BI__builtin_ia32_roundss: 3774 case X86::BI__builtin_ia32_roundsd: 3775 case X86::BI__builtin_ia32_rangepd128_mask: 3776 case X86::BI__builtin_ia32_rangepd256_mask: 3777 case X86::BI__builtin_ia32_rangepd512_mask: 3778 case X86::BI__builtin_ia32_rangeps128_mask: 3779 case X86::BI__builtin_ia32_rangeps256_mask: 3780 case X86::BI__builtin_ia32_rangeps512_mask: 3781 case X86::BI__builtin_ia32_getmantsd_round_mask: 3782 case X86::BI__builtin_ia32_getmantss_round_mask: 3783 case X86::BI__builtin_ia32_vec_set_v16qi: 3784 case X86::BI__builtin_ia32_vec_set_v16hi: 3785 i = 2; l = 0; u = 15; 3786 break; 3787 case X86::BI__builtin_ia32_vec_ext_v32qi: 3788 i = 1; l = 0; u = 31; 3789 break; 3790 case X86::BI__builtin_ia32_cmpps: 3791 case X86::BI__builtin_ia32_cmpss: 3792 case X86::BI__builtin_ia32_cmppd: 3793 case X86::BI__builtin_ia32_cmpsd: 3794 case X86::BI__builtin_ia32_cmpps256: 3795 case X86::BI__builtin_ia32_cmppd256: 3796 case X86::BI__builtin_ia32_cmpps128_mask: 3797 case X86::BI__builtin_ia32_cmppd128_mask: 3798 case X86::BI__builtin_ia32_cmpps256_mask: 3799 case X86::BI__builtin_ia32_cmppd256_mask: 3800 case X86::BI__builtin_ia32_cmpps512_mask: 3801 case X86::BI__builtin_ia32_cmppd512_mask: 3802 case X86::BI__builtin_ia32_cmpsd_mask: 3803 case X86::BI__builtin_ia32_cmpss_mask: 3804 case X86::BI__builtin_ia32_vec_set_v32qi: 3805 i = 2; l = 0; u = 31; 3806 break; 3807 case X86::BI__builtin_ia32_permdf256: 3808 case X86::BI__builtin_ia32_permdi256: 3809 case X86::BI__builtin_ia32_permdf512: 3810 case X86::BI__builtin_ia32_permdi512: 3811 case X86::BI__builtin_ia32_vpermilps: 3812 case X86::BI__builtin_ia32_vpermilps256: 3813 case X86::BI__builtin_ia32_vpermilpd512: 3814 case X86::BI__builtin_ia32_vpermilps512: 3815 case X86::BI__builtin_ia32_pshufd: 3816 case X86::BI__builtin_ia32_pshufd256: 3817 case X86::BI__builtin_ia32_pshufd512: 3818 case X86::BI__builtin_ia32_pshufhw: 3819 case X86::BI__builtin_ia32_pshufhw256: 3820 case X86::BI__builtin_ia32_pshufhw512: 3821 case X86::BI__builtin_ia32_pshuflw: 3822 case X86::BI__builtin_ia32_pshuflw256: 3823 case X86::BI__builtin_ia32_pshuflw512: 3824 case X86::BI__builtin_ia32_vcvtps2ph: 3825 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3826 case X86::BI__builtin_ia32_vcvtps2ph256: 3827 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3828 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3829 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3830 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3831 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3832 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3833 case X86::BI__builtin_ia32_rndscaleps_mask: 3834 case X86::BI__builtin_ia32_rndscalepd_mask: 3835 case X86::BI__builtin_ia32_reducepd128_mask: 3836 case X86::BI__builtin_ia32_reducepd256_mask: 3837 case X86::BI__builtin_ia32_reducepd512_mask: 3838 case X86::BI__builtin_ia32_reduceps128_mask: 3839 case X86::BI__builtin_ia32_reduceps256_mask: 3840 case X86::BI__builtin_ia32_reduceps512_mask: 3841 case X86::BI__builtin_ia32_prold512: 3842 case X86::BI__builtin_ia32_prolq512: 3843 case X86::BI__builtin_ia32_prold128: 3844 case X86::BI__builtin_ia32_prold256: 3845 case X86::BI__builtin_ia32_prolq128: 3846 case X86::BI__builtin_ia32_prolq256: 3847 case X86::BI__builtin_ia32_prord512: 3848 case X86::BI__builtin_ia32_prorq512: 3849 case X86::BI__builtin_ia32_prord128: 3850 case X86::BI__builtin_ia32_prord256: 3851 case X86::BI__builtin_ia32_prorq128: 3852 case X86::BI__builtin_ia32_prorq256: 3853 case X86::BI__builtin_ia32_fpclasspd128_mask: 3854 case X86::BI__builtin_ia32_fpclasspd256_mask: 3855 case X86::BI__builtin_ia32_fpclassps128_mask: 3856 case X86::BI__builtin_ia32_fpclassps256_mask: 3857 case X86::BI__builtin_ia32_fpclassps512_mask: 3858 case X86::BI__builtin_ia32_fpclasspd512_mask: 3859 case X86::BI__builtin_ia32_fpclasssd_mask: 3860 case X86::BI__builtin_ia32_fpclassss_mask: 3861 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3862 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3863 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3864 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3865 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3866 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3867 case X86::BI__builtin_ia32_kshiftliqi: 3868 case X86::BI__builtin_ia32_kshiftlihi: 3869 case X86::BI__builtin_ia32_kshiftlisi: 3870 case X86::BI__builtin_ia32_kshiftlidi: 3871 case X86::BI__builtin_ia32_kshiftriqi: 3872 case X86::BI__builtin_ia32_kshiftrihi: 3873 case X86::BI__builtin_ia32_kshiftrisi: 3874 case X86::BI__builtin_ia32_kshiftridi: 3875 i = 1; l = 0; u = 255; 3876 break; 3877 case X86::BI__builtin_ia32_vperm2f128_pd256: 3878 case X86::BI__builtin_ia32_vperm2f128_ps256: 3879 case X86::BI__builtin_ia32_vperm2f128_si256: 3880 case X86::BI__builtin_ia32_permti256: 3881 case X86::BI__builtin_ia32_pblendw128: 3882 case X86::BI__builtin_ia32_pblendw256: 3883 case X86::BI__builtin_ia32_blendps256: 3884 case X86::BI__builtin_ia32_pblendd256: 3885 case X86::BI__builtin_ia32_palignr128: 3886 case X86::BI__builtin_ia32_palignr256: 3887 case X86::BI__builtin_ia32_palignr512: 3888 case X86::BI__builtin_ia32_alignq512: 3889 case X86::BI__builtin_ia32_alignd512: 3890 case X86::BI__builtin_ia32_alignd128: 3891 case X86::BI__builtin_ia32_alignd256: 3892 case X86::BI__builtin_ia32_alignq128: 3893 case X86::BI__builtin_ia32_alignq256: 3894 case X86::BI__builtin_ia32_vcomisd: 3895 case X86::BI__builtin_ia32_vcomiss: 3896 case X86::BI__builtin_ia32_shuf_f32x4: 3897 case X86::BI__builtin_ia32_shuf_f64x2: 3898 case X86::BI__builtin_ia32_shuf_i32x4: 3899 case X86::BI__builtin_ia32_shuf_i64x2: 3900 case X86::BI__builtin_ia32_shufpd512: 3901 case X86::BI__builtin_ia32_shufps: 3902 case X86::BI__builtin_ia32_shufps256: 3903 case X86::BI__builtin_ia32_shufps512: 3904 case X86::BI__builtin_ia32_dbpsadbw128: 3905 case X86::BI__builtin_ia32_dbpsadbw256: 3906 case X86::BI__builtin_ia32_dbpsadbw512: 3907 case X86::BI__builtin_ia32_vpshldd128: 3908 case X86::BI__builtin_ia32_vpshldd256: 3909 case X86::BI__builtin_ia32_vpshldd512: 3910 case X86::BI__builtin_ia32_vpshldq128: 3911 case X86::BI__builtin_ia32_vpshldq256: 3912 case X86::BI__builtin_ia32_vpshldq512: 3913 case X86::BI__builtin_ia32_vpshldw128: 3914 case X86::BI__builtin_ia32_vpshldw256: 3915 case X86::BI__builtin_ia32_vpshldw512: 3916 case X86::BI__builtin_ia32_vpshrdd128: 3917 case X86::BI__builtin_ia32_vpshrdd256: 3918 case X86::BI__builtin_ia32_vpshrdd512: 3919 case X86::BI__builtin_ia32_vpshrdq128: 3920 case X86::BI__builtin_ia32_vpshrdq256: 3921 case X86::BI__builtin_ia32_vpshrdq512: 3922 case X86::BI__builtin_ia32_vpshrdw128: 3923 case X86::BI__builtin_ia32_vpshrdw256: 3924 case X86::BI__builtin_ia32_vpshrdw512: 3925 i = 2; l = 0; u = 255; 3926 break; 3927 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3928 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3929 case X86::BI__builtin_ia32_fixupimmps512_mask: 3930 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3931 case X86::BI__builtin_ia32_fixupimmsd_mask: 3932 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3933 case X86::BI__builtin_ia32_fixupimmss_mask: 3934 case X86::BI__builtin_ia32_fixupimmss_maskz: 3935 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3936 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3937 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3938 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3939 case X86::BI__builtin_ia32_fixupimmps128_mask: 3940 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3941 case X86::BI__builtin_ia32_fixupimmps256_mask: 3942 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3943 case X86::BI__builtin_ia32_pternlogd512_mask: 3944 case X86::BI__builtin_ia32_pternlogd512_maskz: 3945 case X86::BI__builtin_ia32_pternlogq512_mask: 3946 case X86::BI__builtin_ia32_pternlogq512_maskz: 3947 case X86::BI__builtin_ia32_pternlogd128_mask: 3948 case X86::BI__builtin_ia32_pternlogd128_maskz: 3949 case X86::BI__builtin_ia32_pternlogd256_mask: 3950 case X86::BI__builtin_ia32_pternlogd256_maskz: 3951 case X86::BI__builtin_ia32_pternlogq128_mask: 3952 case X86::BI__builtin_ia32_pternlogq128_maskz: 3953 case X86::BI__builtin_ia32_pternlogq256_mask: 3954 case X86::BI__builtin_ia32_pternlogq256_maskz: 3955 i = 3; l = 0; u = 255; 3956 break; 3957 case X86::BI__builtin_ia32_gatherpfdpd: 3958 case X86::BI__builtin_ia32_gatherpfdps: 3959 case X86::BI__builtin_ia32_gatherpfqpd: 3960 case X86::BI__builtin_ia32_gatherpfqps: 3961 case X86::BI__builtin_ia32_scatterpfdpd: 3962 case X86::BI__builtin_ia32_scatterpfdps: 3963 case X86::BI__builtin_ia32_scatterpfqpd: 3964 case X86::BI__builtin_ia32_scatterpfqps: 3965 i = 4; l = 2; u = 3; 3966 break; 3967 case X86::BI__builtin_ia32_reducesd_mask: 3968 case X86::BI__builtin_ia32_reducess_mask: 3969 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3970 case X86::BI__builtin_ia32_rndscaless_round_mask: 3971 i = 4; l = 0; u = 255; 3972 break; 3973 } 3974 3975 // Note that we don't force a hard error on the range check here, allowing 3976 // template-generated or macro-generated dead code to potentially have out-of- 3977 // range values. These need to code generate, but don't need to necessarily 3978 // make any sense. We use a warning that defaults to an error. 3979 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3980 } 3981 3982 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3983 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3984 /// Returns true when the format fits the function and the FormatStringInfo has 3985 /// been populated. 3986 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3987 FormatStringInfo *FSI) { 3988 FSI->HasVAListArg = Format->getFirstArg() == 0; 3989 FSI->FormatIdx = Format->getFormatIdx() - 1; 3990 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3991 3992 // The way the format attribute works in GCC, the implicit this argument 3993 // of member functions is counted. However, it doesn't appear in our own 3994 // lists, so decrement format_idx in that case. 3995 if (IsCXXMember) { 3996 if(FSI->FormatIdx == 0) 3997 return false; 3998 --FSI->FormatIdx; 3999 if (FSI->FirstDataArg != 0) 4000 --FSI->FirstDataArg; 4001 } 4002 return true; 4003 } 4004 4005 /// Checks if a the given expression evaluates to null. 4006 /// 4007 /// Returns true if the value evaluates to null. 4008 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4009 // If the expression has non-null type, it doesn't evaluate to null. 4010 if (auto nullability 4011 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4012 if (*nullability == NullabilityKind::NonNull) 4013 return false; 4014 } 4015 4016 // As a special case, transparent unions initialized with zero are 4017 // considered null for the purposes of the nonnull attribute. 4018 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4019 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4020 if (const CompoundLiteralExpr *CLE = 4021 dyn_cast<CompoundLiteralExpr>(Expr)) 4022 if (const InitListExpr *ILE = 4023 dyn_cast<InitListExpr>(CLE->getInitializer())) 4024 Expr = ILE->getInit(0); 4025 } 4026 4027 bool Result; 4028 return (!Expr->isValueDependent() && 4029 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4030 !Result); 4031 } 4032 4033 static void CheckNonNullArgument(Sema &S, 4034 const Expr *ArgExpr, 4035 SourceLocation CallSiteLoc) { 4036 if (CheckNonNullExpr(S, ArgExpr)) 4037 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4038 S.PDiag(diag::warn_null_arg) 4039 << ArgExpr->getSourceRange()); 4040 } 4041 4042 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4043 FormatStringInfo FSI; 4044 if ((GetFormatStringType(Format) == FST_NSString) && 4045 getFormatStringInfo(Format, false, &FSI)) { 4046 Idx = FSI.FormatIdx; 4047 return true; 4048 } 4049 return false; 4050 } 4051 4052 /// Diagnose use of %s directive in an NSString which is being passed 4053 /// as formatting string to formatting method. 4054 static void 4055 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4056 const NamedDecl *FDecl, 4057 Expr **Args, 4058 unsigned NumArgs) { 4059 unsigned Idx = 0; 4060 bool Format = false; 4061 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4062 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4063 Idx = 2; 4064 Format = true; 4065 } 4066 else 4067 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4068 if (S.GetFormatNSStringIdx(I, Idx)) { 4069 Format = true; 4070 break; 4071 } 4072 } 4073 if (!Format || NumArgs <= Idx) 4074 return; 4075 const Expr *FormatExpr = Args[Idx]; 4076 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4077 FormatExpr = CSCE->getSubExpr(); 4078 const StringLiteral *FormatString; 4079 if (const ObjCStringLiteral *OSL = 4080 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4081 FormatString = OSL->getString(); 4082 else 4083 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4084 if (!FormatString) 4085 return; 4086 if (S.FormatStringHasSArg(FormatString)) { 4087 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4088 << "%s" << 1 << 1; 4089 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4090 << FDecl->getDeclName(); 4091 } 4092 } 4093 4094 /// Determine whether the given type has a non-null nullability annotation. 4095 static bool isNonNullType(ASTContext &ctx, QualType type) { 4096 if (auto nullability = type->getNullability(ctx)) 4097 return *nullability == NullabilityKind::NonNull; 4098 4099 return false; 4100 } 4101 4102 static void CheckNonNullArguments(Sema &S, 4103 const NamedDecl *FDecl, 4104 const FunctionProtoType *Proto, 4105 ArrayRef<const Expr *> Args, 4106 SourceLocation CallSiteLoc) { 4107 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4108 4109 // Already checked by by constant evaluator. 4110 if (S.isConstantEvaluated()) 4111 return; 4112 // Check the attributes attached to the method/function itself. 4113 llvm::SmallBitVector NonNullArgs; 4114 if (FDecl) { 4115 // Handle the nonnull attribute on the function/method declaration itself. 4116 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4117 if (!NonNull->args_size()) { 4118 // Easy case: all pointer arguments are nonnull. 4119 for (const auto *Arg : Args) 4120 if (S.isValidPointerAttrType(Arg->getType())) 4121 CheckNonNullArgument(S, Arg, CallSiteLoc); 4122 return; 4123 } 4124 4125 for (const ParamIdx &Idx : NonNull->args()) { 4126 unsigned IdxAST = Idx.getASTIndex(); 4127 if (IdxAST >= Args.size()) 4128 continue; 4129 if (NonNullArgs.empty()) 4130 NonNullArgs.resize(Args.size()); 4131 NonNullArgs.set(IdxAST); 4132 } 4133 } 4134 } 4135 4136 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4137 // Handle the nonnull attribute on the parameters of the 4138 // function/method. 4139 ArrayRef<ParmVarDecl*> parms; 4140 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4141 parms = FD->parameters(); 4142 else 4143 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4144 4145 unsigned ParamIndex = 0; 4146 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4147 I != E; ++I, ++ParamIndex) { 4148 const ParmVarDecl *PVD = *I; 4149 if (PVD->hasAttr<NonNullAttr>() || 4150 isNonNullType(S.Context, PVD->getType())) { 4151 if (NonNullArgs.empty()) 4152 NonNullArgs.resize(Args.size()); 4153 4154 NonNullArgs.set(ParamIndex); 4155 } 4156 } 4157 } else { 4158 // If we have a non-function, non-method declaration but no 4159 // function prototype, try to dig out the function prototype. 4160 if (!Proto) { 4161 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4162 QualType type = VD->getType().getNonReferenceType(); 4163 if (auto pointerType = type->getAs<PointerType>()) 4164 type = pointerType->getPointeeType(); 4165 else if (auto blockType = type->getAs<BlockPointerType>()) 4166 type = blockType->getPointeeType(); 4167 // FIXME: data member pointers? 4168 4169 // Dig out the function prototype, if there is one. 4170 Proto = type->getAs<FunctionProtoType>(); 4171 } 4172 } 4173 4174 // Fill in non-null argument information from the nullability 4175 // information on the parameter types (if we have them). 4176 if (Proto) { 4177 unsigned Index = 0; 4178 for (auto paramType : Proto->getParamTypes()) { 4179 if (isNonNullType(S.Context, paramType)) { 4180 if (NonNullArgs.empty()) 4181 NonNullArgs.resize(Args.size()); 4182 4183 NonNullArgs.set(Index); 4184 } 4185 4186 ++Index; 4187 } 4188 } 4189 } 4190 4191 // Check for non-null arguments. 4192 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4193 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4194 if (NonNullArgs[ArgIndex]) 4195 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4196 } 4197 } 4198 4199 /// Handles the checks for format strings, non-POD arguments to vararg 4200 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4201 /// attributes. 4202 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4203 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4204 bool IsMemberFunction, SourceLocation Loc, 4205 SourceRange Range, VariadicCallType CallType) { 4206 // FIXME: We should check as much as we can in the template definition. 4207 if (CurContext->isDependentContext()) 4208 return; 4209 4210 // Printf and scanf checking. 4211 llvm::SmallBitVector CheckedVarArgs; 4212 if (FDecl) { 4213 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4214 // Only create vector if there are format attributes. 4215 CheckedVarArgs.resize(Args.size()); 4216 4217 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4218 CheckedVarArgs); 4219 } 4220 } 4221 4222 // Refuse POD arguments that weren't caught by the format string 4223 // checks above. 4224 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4225 if (CallType != VariadicDoesNotApply && 4226 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4227 unsigned NumParams = Proto ? Proto->getNumParams() 4228 : FDecl && isa<FunctionDecl>(FDecl) 4229 ? cast<FunctionDecl>(FDecl)->getNumParams() 4230 : FDecl && isa<ObjCMethodDecl>(FDecl) 4231 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4232 : 0; 4233 4234 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4235 // Args[ArgIdx] can be null in malformed code. 4236 if (const Expr *Arg = Args[ArgIdx]) { 4237 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4238 checkVariadicArgument(Arg, CallType); 4239 } 4240 } 4241 } 4242 4243 if (FDecl || Proto) { 4244 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4245 4246 // Type safety checking. 4247 if (FDecl) { 4248 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4249 CheckArgumentWithTypeTag(I, Args, Loc); 4250 } 4251 } 4252 4253 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4254 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4255 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4256 if (!Arg->isValueDependent()) { 4257 Expr::EvalResult Align; 4258 if (Arg->EvaluateAsInt(Align, Context)) { 4259 const llvm::APSInt &I = Align.Val.getInt(); 4260 if (!I.isPowerOf2()) 4261 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4262 << Arg->getSourceRange(); 4263 4264 if (I > Sema::MaximumAlignment) 4265 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4266 << Arg->getSourceRange() << Sema::MaximumAlignment; 4267 } 4268 } 4269 } 4270 4271 if (FD) 4272 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4273 } 4274 4275 /// CheckConstructorCall - Check a constructor call for correctness and safety 4276 /// properties not enforced by the C type system. 4277 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4278 ArrayRef<const Expr *> Args, 4279 const FunctionProtoType *Proto, 4280 SourceLocation Loc) { 4281 VariadicCallType CallType = 4282 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4283 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4284 Loc, SourceRange(), CallType); 4285 } 4286 4287 /// CheckFunctionCall - Check a direct function call for various correctness 4288 /// and safety properties not strictly enforced by the C type system. 4289 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4290 const FunctionProtoType *Proto) { 4291 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4292 isa<CXXMethodDecl>(FDecl); 4293 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4294 IsMemberOperatorCall; 4295 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4296 TheCall->getCallee()); 4297 Expr** Args = TheCall->getArgs(); 4298 unsigned NumArgs = TheCall->getNumArgs(); 4299 4300 Expr *ImplicitThis = nullptr; 4301 if (IsMemberOperatorCall) { 4302 // If this is a call to a member operator, hide the first argument 4303 // from checkCall. 4304 // FIXME: Our choice of AST representation here is less than ideal. 4305 ImplicitThis = Args[0]; 4306 ++Args; 4307 --NumArgs; 4308 } else if (IsMemberFunction) 4309 ImplicitThis = 4310 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4311 4312 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4313 IsMemberFunction, TheCall->getRParenLoc(), 4314 TheCall->getCallee()->getSourceRange(), CallType); 4315 4316 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4317 // None of the checks below are needed for functions that don't have 4318 // simple names (e.g., C++ conversion functions). 4319 if (!FnInfo) 4320 return false; 4321 4322 CheckAbsoluteValueFunction(TheCall, FDecl); 4323 CheckMaxUnsignedZero(TheCall, FDecl); 4324 4325 if (getLangOpts().ObjC) 4326 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4327 4328 unsigned CMId = FDecl->getMemoryFunctionKind(); 4329 if (CMId == 0) 4330 return false; 4331 4332 // Handle memory setting and copying functions. 4333 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4334 CheckStrlcpycatArguments(TheCall, FnInfo); 4335 else if (CMId == Builtin::BIstrncat) 4336 CheckStrncatArguments(TheCall, FnInfo); 4337 else 4338 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4339 4340 return false; 4341 } 4342 4343 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4344 ArrayRef<const Expr *> Args) { 4345 VariadicCallType CallType = 4346 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4347 4348 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4349 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4350 CallType); 4351 4352 return false; 4353 } 4354 4355 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4356 const FunctionProtoType *Proto) { 4357 QualType Ty; 4358 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4359 Ty = V->getType().getNonReferenceType(); 4360 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4361 Ty = F->getType().getNonReferenceType(); 4362 else 4363 return false; 4364 4365 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4366 !Ty->isFunctionProtoType()) 4367 return false; 4368 4369 VariadicCallType CallType; 4370 if (!Proto || !Proto->isVariadic()) { 4371 CallType = VariadicDoesNotApply; 4372 } else if (Ty->isBlockPointerType()) { 4373 CallType = VariadicBlock; 4374 } else { // Ty->isFunctionPointerType() 4375 CallType = VariadicFunction; 4376 } 4377 4378 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4379 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4380 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4381 TheCall->getCallee()->getSourceRange(), CallType); 4382 4383 return false; 4384 } 4385 4386 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4387 /// such as function pointers returned from functions. 4388 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4389 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4390 TheCall->getCallee()); 4391 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4392 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4393 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4394 TheCall->getCallee()->getSourceRange(), CallType); 4395 4396 return false; 4397 } 4398 4399 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4400 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4401 return false; 4402 4403 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4404 switch (Op) { 4405 case AtomicExpr::AO__c11_atomic_init: 4406 case AtomicExpr::AO__opencl_atomic_init: 4407 llvm_unreachable("There is no ordering argument for an init"); 4408 4409 case AtomicExpr::AO__c11_atomic_load: 4410 case AtomicExpr::AO__opencl_atomic_load: 4411 case AtomicExpr::AO__atomic_load_n: 4412 case AtomicExpr::AO__atomic_load: 4413 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4414 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4415 4416 case AtomicExpr::AO__c11_atomic_store: 4417 case AtomicExpr::AO__opencl_atomic_store: 4418 case AtomicExpr::AO__atomic_store: 4419 case AtomicExpr::AO__atomic_store_n: 4420 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4421 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4422 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4423 4424 default: 4425 return true; 4426 } 4427 } 4428 4429 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4430 AtomicExpr::AtomicOp Op) { 4431 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4432 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4433 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4434 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4435 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4436 Op); 4437 } 4438 4439 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4440 SourceLocation RParenLoc, MultiExprArg Args, 4441 AtomicExpr::AtomicOp Op, 4442 AtomicArgumentOrder ArgOrder) { 4443 // All the non-OpenCL operations take one of the following forms. 4444 // The OpenCL operations take the __c11 forms with one extra argument for 4445 // synchronization scope. 4446 enum { 4447 // C __c11_atomic_init(A *, C) 4448 Init, 4449 4450 // C __c11_atomic_load(A *, int) 4451 Load, 4452 4453 // void __atomic_load(A *, CP, int) 4454 LoadCopy, 4455 4456 // void __atomic_store(A *, CP, int) 4457 Copy, 4458 4459 // C __c11_atomic_add(A *, M, int) 4460 Arithmetic, 4461 4462 // C __atomic_exchange_n(A *, CP, int) 4463 Xchg, 4464 4465 // void __atomic_exchange(A *, C *, CP, int) 4466 GNUXchg, 4467 4468 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4469 C11CmpXchg, 4470 4471 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4472 GNUCmpXchg 4473 } Form = Init; 4474 4475 const unsigned NumForm = GNUCmpXchg + 1; 4476 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4477 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4478 // where: 4479 // C is an appropriate type, 4480 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4481 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4482 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4483 // the int parameters are for orderings. 4484 4485 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4486 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4487 "need to update code for modified forms"); 4488 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4489 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4490 AtomicExpr::AO__atomic_load, 4491 "need to update code for modified C11 atomics"); 4492 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4493 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4494 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4495 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4496 IsOpenCL; 4497 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4498 Op == AtomicExpr::AO__atomic_store_n || 4499 Op == AtomicExpr::AO__atomic_exchange_n || 4500 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4501 bool IsAddSub = false; 4502 4503 switch (Op) { 4504 case AtomicExpr::AO__c11_atomic_init: 4505 case AtomicExpr::AO__opencl_atomic_init: 4506 Form = Init; 4507 break; 4508 4509 case AtomicExpr::AO__c11_atomic_load: 4510 case AtomicExpr::AO__opencl_atomic_load: 4511 case AtomicExpr::AO__atomic_load_n: 4512 Form = Load; 4513 break; 4514 4515 case AtomicExpr::AO__atomic_load: 4516 Form = LoadCopy; 4517 break; 4518 4519 case AtomicExpr::AO__c11_atomic_store: 4520 case AtomicExpr::AO__opencl_atomic_store: 4521 case AtomicExpr::AO__atomic_store: 4522 case AtomicExpr::AO__atomic_store_n: 4523 Form = Copy; 4524 break; 4525 4526 case AtomicExpr::AO__c11_atomic_fetch_add: 4527 case AtomicExpr::AO__c11_atomic_fetch_sub: 4528 case AtomicExpr::AO__opencl_atomic_fetch_add: 4529 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4530 case AtomicExpr::AO__atomic_fetch_add: 4531 case AtomicExpr::AO__atomic_fetch_sub: 4532 case AtomicExpr::AO__atomic_add_fetch: 4533 case AtomicExpr::AO__atomic_sub_fetch: 4534 IsAddSub = true; 4535 LLVM_FALLTHROUGH; 4536 case AtomicExpr::AO__c11_atomic_fetch_and: 4537 case AtomicExpr::AO__c11_atomic_fetch_or: 4538 case AtomicExpr::AO__c11_atomic_fetch_xor: 4539 case AtomicExpr::AO__opencl_atomic_fetch_and: 4540 case AtomicExpr::AO__opencl_atomic_fetch_or: 4541 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4542 case AtomicExpr::AO__atomic_fetch_and: 4543 case AtomicExpr::AO__atomic_fetch_or: 4544 case AtomicExpr::AO__atomic_fetch_xor: 4545 case AtomicExpr::AO__atomic_fetch_nand: 4546 case AtomicExpr::AO__atomic_and_fetch: 4547 case AtomicExpr::AO__atomic_or_fetch: 4548 case AtomicExpr::AO__atomic_xor_fetch: 4549 case AtomicExpr::AO__atomic_nand_fetch: 4550 case AtomicExpr::AO__c11_atomic_fetch_min: 4551 case AtomicExpr::AO__c11_atomic_fetch_max: 4552 case AtomicExpr::AO__opencl_atomic_fetch_min: 4553 case AtomicExpr::AO__opencl_atomic_fetch_max: 4554 case AtomicExpr::AO__atomic_min_fetch: 4555 case AtomicExpr::AO__atomic_max_fetch: 4556 case AtomicExpr::AO__atomic_fetch_min: 4557 case AtomicExpr::AO__atomic_fetch_max: 4558 Form = Arithmetic; 4559 break; 4560 4561 case AtomicExpr::AO__c11_atomic_exchange: 4562 case AtomicExpr::AO__opencl_atomic_exchange: 4563 case AtomicExpr::AO__atomic_exchange_n: 4564 Form = Xchg; 4565 break; 4566 4567 case AtomicExpr::AO__atomic_exchange: 4568 Form = GNUXchg; 4569 break; 4570 4571 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4572 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4573 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4574 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4575 Form = C11CmpXchg; 4576 break; 4577 4578 case AtomicExpr::AO__atomic_compare_exchange: 4579 case AtomicExpr::AO__atomic_compare_exchange_n: 4580 Form = GNUCmpXchg; 4581 break; 4582 } 4583 4584 unsigned AdjustedNumArgs = NumArgs[Form]; 4585 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4586 ++AdjustedNumArgs; 4587 // Check we have the right number of arguments. 4588 if (Args.size() < AdjustedNumArgs) { 4589 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4590 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4591 << ExprRange; 4592 return ExprError(); 4593 } else if (Args.size() > AdjustedNumArgs) { 4594 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4595 diag::err_typecheck_call_too_many_args) 4596 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4597 << ExprRange; 4598 return ExprError(); 4599 } 4600 4601 // Inspect the first argument of the atomic operation. 4602 Expr *Ptr = Args[0]; 4603 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4604 if (ConvertedPtr.isInvalid()) 4605 return ExprError(); 4606 4607 Ptr = ConvertedPtr.get(); 4608 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4609 if (!pointerType) { 4610 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4611 << Ptr->getType() << Ptr->getSourceRange(); 4612 return ExprError(); 4613 } 4614 4615 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4616 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4617 QualType ValType = AtomTy; // 'C' 4618 if (IsC11) { 4619 if (!AtomTy->isAtomicType()) { 4620 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4621 << Ptr->getType() << Ptr->getSourceRange(); 4622 return ExprError(); 4623 } 4624 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4625 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4626 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4627 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4628 << Ptr->getSourceRange(); 4629 return ExprError(); 4630 } 4631 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4632 } else if (Form != Load && Form != LoadCopy) { 4633 if (ValType.isConstQualified()) { 4634 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4635 << Ptr->getType() << Ptr->getSourceRange(); 4636 return ExprError(); 4637 } 4638 } 4639 4640 // For an arithmetic operation, the implied arithmetic must be well-formed. 4641 if (Form == Arithmetic) { 4642 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4643 if (IsAddSub && !ValType->isIntegerType() 4644 && !ValType->isPointerType()) { 4645 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4646 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4647 return ExprError(); 4648 } 4649 if (!IsAddSub && !ValType->isIntegerType()) { 4650 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4651 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4652 return ExprError(); 4653 } 4654 if (IsC11 && ValType->isPointerType() && 4655 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4656 diag::err_incomplete_type)) { 4657 return ExprError(); 4658 } 4659 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4660 // For __atomic_*_n operations, the value type must be a scalar integral or 4661 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4662 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4663 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4664 return ExprError(); 4665 } 4666 4667 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4668 !AtomTy->isScalarType()) { 4669 // For GNU atomics, require a trivially-copyable type. This is not part of 4670 // the GNU atomics specification, but we enforce it for sanity. 4671 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4672 << Ptr->getType() << Ptr->getSourceRange(); 4673 return ExprError(); 4674 } 4675 4676 switch (ValType.getObjCLifetime()) { 4677 case Qualifiers::OCL_None: 4678 case Qualifiers::OCL_ExplicitNone: 4679 // okay 4680 break; 4681 4682 case Qualifiers::OCL_Weak: 4683 case Qualifiers::OCL_Strong: 4684 case Qualifiers::OCL_Autoreleasing: 4685 // FIXME: Can this happen? By this point, ValType should be known 4686 // to be trivially copyable. 4687 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4688 << ValType << Ptr->getSourceRange(); 4689 return ExprError(); 4690 } 4691 4692 // All atomic operations have an overload which takes a pointer to a volatile 4693 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4694 // into the result or the other operands. Similarly atomic_load takes a 4695 // pointer to a const 'A'. 4696 ValType.removeLocalVolatile(); 4697 ValType.removeLocalConst(); 4698 QualType ResultType = ValType; 4699 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4700 Form == Init) 4701 ResultType = Context.VoidTy; 4702 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4703 ResultType = Context.BoolTy; 4704 4705 // The type of a parameter passed 'by value'. In the GNU atomics, such 4706 // arguments are actually passed as pointers. 4707 QualType ByValType = ValType; // 'CP' 4708 bool IsPassedByAddress = false; 4709 if (!IsC11 && !IsN) { 4710 ByValType = Ptr->getType(); 4711 IsPassedByAddress = true; 4712 } 4713 4714 SmallVector<Expr *, 5> APIOrderedArgs; 4715 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4716 APIOrderedArgs.push_back(Args[0]); 4717 switch (Form) { 4718 case Init: 4719 case Load: 4720 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4721 break; 4722 case LoadCopy: 4723 case Copy: 4724 case Arithmetic: 4725 case Xchg: 4726 APIOrderedArgs.push_back(Args[2]); // Val1 4727 APIOrderedArgs.push_back(Args[1]); // Order 4728 break; 4729 case GNUXchg: 4730 APIOrderedArgs.push_back(Args[2]); // Val1 4731 APIOrderedArgs.push_back(Args[3]); // Val2 4732 APIOrderedArgs.push_back(Args[1]); // Order 4733 break; 4734 case C11CmpXchg: 4735 APIOrderedArgs.push_back(Args[2]); // Val1 4736 APIOrderedArgs.push_back(Args[4]); // Val2 4737 APIOrderedArgs.push_back(Args[1]); // Order 4738 APIOrderedArgs.push_back(Args[3]); // OrderFail 4739 break; 4740 case GNUCmpXchg: 4741 APIOrderedArgs.push_back(Args[2]); // Val1 4742 APIOrderedArgs.push_back(Args[4]); // Val2 4743 APIOrderedArgs.push_back(Args[5]); // Weak 4744 APIOrderedArgs.push_back(Args[1]); // Order 4745 APIOrderedArgs.push_back(Args[3]); // OrderFail 4746 break; 4747 } 4748 } else 4749 APIOrderedArgs.append(Args.begin(), Args.end()); 4750 4751 // The first argument's non-CV pointer type is used to deduce the type of 4752 // subsequent arguments, except for: 4753 // - weak flag (always converted to bool) 4754 // - memory order (always converted to int) 4755 // - scope (always converted to int) 4756 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4757 QualType Ty; 4758 if (i < NumVals[Form] + 1) { 4759 switch (i) { 4760 case 0: 4761 // The first argument is always a pointer. It has a fixed type. 4762 // It is always dereferenced, a nullptr is undefined. 4763 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4764 // Nothing else to do: we already know all we want about this pointer. 4765 continue; 4766 case 1: 4767 // The second argument is the non-atomic operand. For arithmetic, this 4768 // is always passed by value, and for a compare_exchange it is always 4769 // passed by address. For the rest, GNU uses by-address and C11 uses 4770 // by-value. 4771 assert(Form != Load); 4772 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4773 Ty = ValType; 4774 else if (Form == Copy || Form == Xchg) { 4775 if (IsPassedByAddress) { 4776 // The value pointer is always dereferenced, a nullptr is undefined. 4777 CheckNonNullArgument(*this, APIOrderedArgs[i], 4778 ExprRange.getBegin()); 4779 } 4780 Ty = ByValType; 4781 } else if (Form == Arithmetic) 4782 Ty = Context.getPointerDiffType(); 4783 else { 4784 Expr *ValArg = APIOrderedArgs[i]; 4785 // The value pointer is always dereferenced, a nullptr is undefined. 4786 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4787 LangAS AS = LangAS::Default; 4788 // Keep address space of non-atomic pointer type. 4789 if (const PointerType *PtrTy = 4790 ValArg->getType()->getAs<PointerType>()) { 4791 AS = PtrTy->getPointeeType().getAddressSpace(); 4792 } 4793 Ty = Context.getPointerType( 4794 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4795 } 4796 break; 4797 case 2: 4798 // The third argument to compare_exchange / GNU exchange is the desired 4799 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4800 if (IsPassedByAddress) 4801 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4802 Ty = ByValType; 4803 break; 4804 case 3: 4805 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4806 Ty = Context.BoolTy; 4807 break; 4808 } 4809 } else { 4810 // The order(s) and scope are always converted to int. 4811 Ty = Context.IntTy; 4812 } 4813 4814 InitializedEntity Entity = 4815 InitializedEntity::InitializeParameter(Context, Ty, false); 4816 ExprResult Arg = APIOrderedArgs[i]; 4817 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4818 if (Arg.isInvalid()) 4819 return true; 4820 APIOrderedArgs[i] = Arg.get(); 4821 } 4822 4823 // Permute the arguments into a 'consistent' order. 4824 SmallVector<Expr*, 5> SubExprs; 4825 SubExprs.push_back(Ptr); 4826 switch (Form) { 4827 case Init: 4828 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4829 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4830 break; 4831 case Load: 4832 SubExprs.push_back(APIOrderedArgs[1]); // Order 4833 break; 4834 case LoadCopy: 4835 case Copy: 4836 case Arithmetic: 4837 case Xchg: 4838 SubExprs.push_back(APIOrderedArgs[2]); // Order 4839 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4840 break; 4841 case GNUXchg: 4842 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4843 SubExprs.push_back(APIOrderedArgs[3]); // Order 4844 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4845 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4846 break; 4847 case C11CmpXchg: 4848 SubExprs.push_back(APIOrderedArgs[3]); // Order 4849 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4850 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 4851 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4852 break; 4853 case GNUCmpXchg: 4854 SubExprs.push_back(APIOrderedArgs[4]); // Order 4855 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4856 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 4857 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4858 SubExprs.push_back(APIOrderedArgs[3]); // Weak 4859 break; 4860 } 4861 4862 if (SubExprs.size() >= 2 && Form != Init) { 4863 llvm::APSInt Result(32); 4864 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4865 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4866 Diag(SubExprs[1]->getBeginLoc(), 4867 diag::warn_atomic_op_has_invalid_memory_order) 4868 << SubExprs[1]->getSourceRange(); 4869 } 4870 4871 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4872 auto *Scope = Args[Args.size() - 1]; 4873 llvm::APSInt Result(32); 4874 if (Scope->isIntegerConstantExpr(Result, Context) && 4875 !ScopeModel->isValid(Result.getZExtValue())) { 4876 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4877 << Scope->getSourceRange(); 4878 } 4879 SubExprs.push_back(Scope); 4880 } 4881 4882 AtomicExpr *AE = new (Context) 4883 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 4884 4885 if ((Op == AtomicExpr::AO__c11_atomic_load || 4886 Op == AtomicExpr::AO__c11_atomic_store || 4887 Op == AtomicExpr::AO__opencl_atomic_load || 4888 Op == AtomicExpr::AO__opencl_atomic_store ) && 4889 Context.AtomicUsesUnsupportedLibcall(AE)) 4890 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4891 << ((Op == AtomicExpr::AO__c11_atomic_load || 4892 Op == AtomicExpr::AO__opencl_atomic_load) 4893 ? 0 4894 : 1); 4895 4896 return AE; 4897 } 4898 4899 /// checkBuiltinArgument - Given a call to a builtin function, perform 4900 /// normal type-checking on the given argument, updating the call in 4901 /// place. This is useful when a builtin function requires custom 4902 /// type-checking for some of its arguments but not necessarily all of 4903 /// them. 4904 /// 4905 /// Returns true on error. 4906 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4907 FunctionDecl *Fn = E->getDirectCallee(); 4908 assert(Fn && "builtin call without direct callee!"); 4909 4910 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4911 InitializedEntity Entity = 4912 InitializedEntity::InitializeParameter(S.Context, Param); 4913 4914 ExprResult Arg = E->getArg(0); 4915 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4916 if (Arg.isInvalid()) 4917 return true; 4918 4919 E->setArg(ArgIndex, Arg.get()); 4920 return false; 4921 } 4922 4923 /// We have a call to a function like __sync_fetch_and_add, which is an 4924 /// overloaded function based on the pointer type of its first argument. 4925 /// The main BuildCallExpr routines have already promoted the types of 4926 /// arguments because all of these calls are prototyped as void(...). 4927 /// 4928 /// This function goes through and does final semantic checking for these 4929 /// builtins, as well as generating any warnings. 4930 ExprResult 4931 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4932 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4933 Expr *Callee = TheCall->getCallee(); 4934 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4935 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4936 4937 // Ensure that we have at least one argument to do type inference from. 4938 if (TheCall->getNumArgs() < 1) { 4939 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4940 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4941 return ExprError(); 4942 } 4943 4944 // Inspect the first argument of the atomic builtin. This should always be 4945 // a pointer type, whose element is an integral scalar or pointer type. 4946 // Because it is a pointer type, we don't have to worry about any implicit 4947 // casts here. 4948 // FIXME: We don't allow floating point scalars as input. 4949 Expr *FirstArg = TheCall->getArg(0); 4950 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4951 if (FirstArgResult.isInvalid()) 4952 return ExprError(); 4953 FirstArg = FirstArgResult.get(); 4954 TheCall->setArg(0, FirstArg); 4955 4956 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4957 if (!pointerType) { 4958 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4959 << FirstArg->getType() << FirstArg->getSourceRange(); 4960 return ExprError(); 4961 } 4962 4963 QualType ValType = pointerType->getPointeeType(); 4964 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4965 !ValType->isBlockPointerType()) { 4966 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4967 << FirstArg->getType() << FirstArg->getSourceRange(); 4968 return ExprError(); 4969 } 4970 4971 if (ValType.isConstQualified()) { 4972 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4973 << FirstArg->getType() << FirstArg->getSourceRange(); 4974 return ExprError(); 4975 } 4976 4977 switch (ValType.getObjCLifetime()) { 4978 case Qualifiers::OCL_None: 4979 case Qualifiers::OCL_ExplicitNone: 4980 // okay 4981 break; 4982 4983 case Qualifiers::OCL_Weak: 4984 case Qualifiers::OCL_Strong: 4985 case Qualifiers::OCL_Autoreleasing: 4986 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4987 << ValType << FirstArg->getSourceRange(); 4988 return ExprError(); 4989 } 4990 4991 // Strip any qualifiers off ValType. 4992 ValType = ValType.getUnqualifiedType(); 4993 4994 // The majority of builtins return a value, but a few have special return 4995 // types, so allow them to override appropriately below. 4996 QualType ResultType = ValType; 4997 4998 // We need to figure out which concrete builtin this maps onto. For example, 4999 // __sync_fetch_and_add with a 2 byte object turns into 5000 // __sync_fetch_and_add_2. 5001 #define BUILTIN_ROW(x) \ 5002 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5003 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5004 5005 static const unsigned BuiltinIndices[][5] = { 5006 BUILTIN_ROW(__sync_fetch_and_add), 5007 BUILTIN_ROW(__sync_fetch_and_sub), 5008 BUILTIN_ROW(__sync_fetch_and_or), 5009 BUILTIN_ROW(__sync_fetch_and_and), 5010 BUILTIN_ROW(__sync_fetch_and_xor), 5011 BUILTIN_ROW(__sync_fetch_and_nand), 5012 5013 BUILTIN_ROW(__sync_add_and_fetch), 5014 BUILTIN_ROW(__sync_sub_and_fetch), 5015 BUILTIN_ROW(__sync_and_and_fetch), 5016 BUILTIN_ROW(__sync_or_and_fetch), 5017 BUILTIN_ROW(__sync_xor_and_fetch), 5018 BUILTIN_ROW(__sync_nand_and_fetch), 5019 5020 BUILTIN_ROW(__sync_val_compare_and_swap), 5021 BUILTIN_ROW(__sync_bool_compare_and_swap), 5022 BUILTIN_ROW(__sync_lock_test_and_set), 5023 BUILTIN_ROW(__sync_lock_release), 5024 BUILTIN_ROW(__sync_swap) 5025 }; 5026 #undef BUILTIN_ROW 5027 5028 // Determine the index of the size. 5029 unsigned SizeIndex; 5030 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5031 case 1: SizeIndex = 0; break; 5032 case 2: SizeIndex = 1; break; 5033 case 4: SizeIndex = 2; break; 5034 case 8: SizeIndex = 3; break; 5035 case 16: SizeIndex = 4; break; 5036 default: 5037 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5038 << FirstArg->getType() << FirstArg->getSourceRange(); 5039 return ExprError(); 5040 } 5041 5042 // Each of these builtins has one pointer argument, followed by some number of 5043 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5044 // that we ignore. Find out which row of BuiltinIndices to read from as well 5045 // as the number of fixed args. 5046 unsigned BuiltinID = FDecl->getBuiltinID(); 5047 unsigned BuiltinIndex, NumFixed = 1; 5048 bool WarnAboutSemanticsChange = false; 5049 switch (BuiltinID) { 5050 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5051 case Builtin::BI__sync_fetch_and_add: 5052 case Builtin::BI__sync_fetch_and_add_1: 5053 case Builtin::BI__sync_fetch_and_add_2: 5054 case Builtin::BI__sync_fetch_and_add_4: 5055 case Builtin::BI__sync_fetch_and_add_8: 5056 case Builtin::BI__sync_fetch_and_add_16: 5057 BuiltinIndex = 0; 5058 break; 5059 5060 case Builtin::BI__sync_fetch_and_sub: 5061 case Builtin::BI__sync_fetch_and_sub_1: 5062 case Builtin::BI__sync_fetch_and_sub_2: 5063 case Builtin::BI__sync_fetch_and_sub_4: 5064 case Builtin::BI__sync_fetch_and_sub_8: 5065 case Builtin::BI__sync_fetch_and_sub_16: 5066 BuiltinIndex = 1; 5067 break; 5068 5069 case Builtin::BI__sync_fetch_and_or: 5070 case Builtin::BI__sync_fetch_and_or_1: 5071 case Builtin::BI__sync_fetch_and_or_2: 5072 case Builtin::BI__sync_fetch_and_or_4: 5073 case Builtin::BI__sync_fetch_and_or_8: 5074 case Builtin::BI__sync_fetch_and_or_16: 5075 BuiltinIndex = 2; 5076 break; 5077 5078 case Builtin::BI__sync_fetch_and_and: 5079 case Builtin::BI__sync_fetch_and_and_1: 5080 case Builtin::BI__sync_fetch_and_and_2: 5081 case Builtin::BI__sync_fetch_and_and_4: 5082 case Builtin::BI__sync_fetch_and_and_8: 5083 case Builtin::BI__sync_fetch_and_and_16: 5084 BuiltinIndex = 3; 5085 break; 5086 5087 case Builtin::BI__sync_fetch_and_xor: 5088 case Builtin::BI__sync_fetch_and_xor_1: 5089 case Builtin::BI__sync_fetch_and_xor_2: 5090 case Builtin::BI__sync_fetch_and_xor_4: 5091 case Builtin::BI__sync_fetch_and_xor_8: 5092 case Builtin::BI__sync_fetch_and_xor_16: 5093 BuiltinIndex = 4; 5094 break; 5095 5096 case Builtin::BI__sync_fetch_and_nand: 5097 case Builtin::BI__sync_fetch_and_nand_1: 5098 case Builtin::BI__sync_fetch_and_nand_2: 5099 case Builtin::BI__sync_fetch_and_nand_4: 5100 case Builtin::BI__sync_fetch_and_nand_8: 5101 case Builtin::BI__sync_fetch_and_nand_16: 5102 BuiltinIndex = 5; 5103 WarnAboutSemanticsChange = true; 5104 break; 5105 5106 case Builtin::BI__sync_add_and_fetch: 5107 case Builtin::BI__sync_add_and_fetch_1: 5108 case Builtin::BI__sync_add_and_fetch_2: 5109 case Builtin::BI__sync_add_and_fetch_4: 5110 case Builtin::BI__sync_add_and_fetch_8: 5111 case Builtin::BI__sync_add_and_fetch_16: 5112 BuiltinIndex = 6; 5113 break; 5114 5115 case Builtin::BI__sync_sub_and_fetch: 5116 case Builtin::BI__sync_sub_and_fetch_1: 5117 case Builtin::BI__sync_sub_and_fetch_2: 5118 case Builtin::BI__sync_sub_and_fetch_4: 5119 case Builtin::BI__sync_sub_and_fetch_8: 5120 case Builtin::BI__sync_sub_and_fetch_16: 5121 BuiltinIndex = 7; 5122 break; 5123 5124 case Builtin::BI__sync_and_and_fetch: 5125 case Builtin::BI__sync_and_and_fetch_1: 5126 case Builtin::BI__sync_and_and_fetch_2: 5127 case Builtin::BI__sync_and_and_fetch_4: 5128 case Builtin::BI__sync_and_and_fetch_8: 5129 case Builtin::BI__sync_and_and_fetch_16: 5130 BuiltinIndex = 8; 5131 break; 5132 5133 case Builtin::BI__sync_or_and_fetch: 5134 case Builtin::BI__sync_or_and_fetch_1: 5135 case Builtin::BI__sync_or_and_fetch_2: 5136 case Builtin::BI__sync_or_and_fetch_4: 5137 case Builtin::BI__sync_or_and_fetch_8: 5138 case Builtin::BI__sync_or_and_fetch_16: 5139 BuiltinIndex = 9; 5140 break; 5141 5142 case Builtin::BI__sync_xor_and_fetch: 5143 case Builtin::BI__sync_xor_and_fetch_1: 5144 case Builtin::BI__sync_xor_and_fetch_2: 5145 case Builtin::BI__sync_xor_and_fetch_4: 5146 case Builtin::BI__sync_xor_and_fetch_8: 5147 case Builtin::BI__sync_xor_and_fetch_16: 5148 BuiltinIndex = 10; 5149 break; 5150 5151 case Builtin::BI__sync_nand_and_fetch: 5152 case Builtin::BI__sync_nand_and_fetch_1: 5153 case Builtin::BI__sync_nand_and_fetch_2: 5154 case Builtin::BI__sync_nand_and_fetch_4: 5155 case Builtin::BI__sync_nand_and_fetch_8: 5156 case Builtin::BI__sync_nand_and_fetch_16: 5157 BuiltinIndex = 11; 5158 WarnAboutSemanticsChange = true; 5159 break; 5160 5161 case Builtin::BI__sync_val_compare_and_swap: 5162 case Builtin::BI__sync_val_compare_and_swap_1: 5163 case Builtin::BI__sync_val_compare_and_swap_2: 5164 case Builtin::BI__sync_val_compare_and_swap_4: 5165 case Builtin::BI__sync_val_compare_and_swap_8: 5166 case Builtin::BI__sync_val_compare_and_swap_16: 5167 BuiltinIndex = 12; 5168 NumFixed = 2; 5169 break; 5170 5171 case Builtin::BI__sync_bool_compare_and_swap: 5172 case Builtin::BI__sync_bool_compare_and_swap_1: 5173 case Builtin::BI__sync_bool_compare_and_swap_2: 5174 case Builtin::BI__sync_bool_compare_and_swap_4: 5175 case Builtin::BI__sync_bool_compare_and_swap_8: 5176 case Builtin::BI__sync_bool_compare_and_swap_16: 5177 BuiltinIndex = 13; 5178 NumFixed = 2; 5179 ResultType = Context.BoolTy; 5180 break; 5181 5182 case Builtin::BI__sync_lock_test_and_set: 5183 case Builtin::BI__sync_lock_test_and_set_1: 5184 case Builtin::BI__sync_lock_test_and_set_2: 5185 case Builtin::BI__sync_lock_test_and_set_4: 5186 case Builtin::BI__sync_lock_test_and_set_8: 5187 case Builtin::BI__sync_lock_test_and_set_16: 5188 BuiltinIndex = 14; 5189 break; 5190 5191 case Builtin::BI__sync_lock_release: 5192 case Builtin::BI__sync_lock_release_1: 5193 case Builtin::BI__sync_lock_release_2: 5194 case Builtin::BI__sync_lock_release_4: 5195 case Builtin::BI__sync_lock_release_8: 5196 case Builtin::BI__sync_lock_release_16: 5197 BuiltinIndex = 15; 5198 NumFixed = 0; 5199 ResultType = Context.VoidTy; 5200 break; 5201 5202 case Builtin::BI__sync_swap: 5203 case Builtin::BI__sync_swap_1: 5204 case Builtin::BI__sync_swap_2: 5205 case Builtin::BI__sync_swap_4: 5206 case Builtin::BI__sync_swap_8: 5207 case Builtin::BI__sync_swap_16: 5208 BuiltinIndex = 16; 5209 break; 5210 } 5211 5212 // Now that we know how many fixed arguments we expect, first check that we 5213 // have at least that many. 5214 if (TheCall->getNumArgs() < 1+NumFixed) { 5215 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5216 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5217 << Callee->getSourceRange(); 5218 return ExprError(); 5219 } 5220 5221 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5222 << Callee->getSourceRange(); 5223 5224 if (WarnAboutSemanticsChange) { 5225 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5226 << Callee->getSourceRange(); 5227 } 5228 5229 // Get the decl for the concrete builtin from this, we can tell what the 5230 // concrete integer type we should convert to is. 5231 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5232 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5233 FunctionDecl *NewBuiltinDecl; 5234 if (NewBuiltinID == BuiltinID) 5235 NewBuiltinDecl = FDecl; 5236 else { 5237 // Perform builtin lookup to avoid redeclaring it. 5238 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5239 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5240 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5241 assert(Res.getFoundDecl()); 5242 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5243 if (!NewBuiltinDecl) 5244 return ExprError(); 5245 } 5246 5247 // The first argument --- the pointer --- has a fixed type; we 5248 // deduce the types of the rest of the arguments accordingly. Walk 5249 // the remaining arguments, converting them to the deduced value type. 5250 for (unsigned i = 0; i != NumFixed; ++i) { 5251 ExprResult Arg = TheCall->getArg(i+1); 5252 5253 // GCC does an implicit conversion to the pointer or integer ValType. This 5254 // can fail in some cases (1i -> int**), check for this error case now. 5255 // Initialize the argument. 5256 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5257 ValType, /*consume*/ false); 5258 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5259 if (Arg.isInvalid()) 5260 return ExprError(); 5261 5262 // Okay, we have something that *can* be converted to the right type. Check 5263 // to see if there is a potentially weird extension going on here. This can 5264 // happen when you do an atomic operation on something like an char* and 5265 // pass in 42. The 42 gets converted to char. This is even more strange 5266 // for things like 45.123 -> char, etc. 5267 // FIXME: Do this check. 5268 TheCall->setArg(i+1, Arg.get()); 5269 } 5270 5271 // Create a new DeclRefExpr to refer to the new decl. 5272 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5273 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5274 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5275 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5276 5277 // Set the callee in the CallExpr. 5278 // FIXME: This loses syntactic information. 5279 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5280 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5281 CK_BuiltinFnToFnPtr); 5282 TheCall->setCallee(PromotedCall.get()); 5283 5284 // Change the result type of the call to match the original value type. This 5285 // is arbitrary, but the codegen for these builtins ins design to handle it 5286 // gracefully. 5287 TheCall->setType(ResultType); 5288 5289 return TheCallResult; 5290 } 5291 5292 /// SemaBuiltinNontemporalOverloaded - We have a call to 5293 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5294 /// overloaded function based on the pointer type of its last argument. 5295 /// 5296 /// This function goes through and does final semantic checking for these 5297 /// builtins. 5298 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5299 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5300 DeclRefExpr *DRE = 5301 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5302 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5303 unsigned BuiltinID = FDecl->getBuiltinID(); 5304 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5305 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5306 "Unexpected nontemporal load/store builtin!"); 5307 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5308 unsigned numArgs = isStore ? 2 : 1; 5309 5310 // Ensure that we have the proper number of arguments. 5311 if (checkArgCount(*this, TheCall, numArgs)) 5312 return ExprError(); 5313 5314 // Inspect the last argument of the nontemporal builtin. This should always 5315 // be a pointer type, from which we imply the type of the memory access. 5316 // Because it is a pointer type, we don't have to worry about any implicit 5317 // casts here. 5318 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5319 ExprResult PointerArgResult = 5320 DefaultFunctionArrayLvalueConversion(PointerArg); 5321 5322 if (PointerArgResult.isInvalid()) 5323 return ExprError(); 5324 PointerArg = PointerArgResult.get(); 5325 TheCall->setArg(numArgs - 1, PointerArg); 5326 5327 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5328 if (!pointerType) { 5329 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5330 << PointerArg->getType() << PointerArg->getSourceRange(); 5331 return ExprError(); 5332 } 5333 5334 QualType ValType = pointerType->getPointeeType(); 5335 5336 // Strip any qualifiers off ValType. 5337 ValType = ValType.getUnqualifiedType(); 5338 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5339 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5340 !ValType->isVectorType()) { 5341 Diag(DRE->getBeginLoc(), 5342 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5343 << PointerArg->getType() << PointerArg->getSourceRange(); 5344 return ExprError(); 5345 } 5346 5347 if (!isStore) { 5348 TheCall->setType(ValType); 5349 return TheCallResult; 5350 } 5351 5352 ExprResult ValArg = TheCall->getArg(0); 5353 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5354 Context, ValType, /*consume*/ false); 5355 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5356 if (ValArg.isInvalid()) 5357 return ExprError(); 5358 5359 TheCall->setArg(0, ValArg.get()); 5360 TheCall->setType(Context.VoidTy); 5361 return TheCallResult; 5362 } 5363 5364 /// CheckObjCString - Checks that the argument to the builtin 5365 /// CFString constructor is correct 5366 /// Note: It might also make sense to do the UTF-16 conversion here (would 5367 /// simplify the backend). 5368 bool Sema::CheckObjCString(Expr *Arg) { 5369 Arg = Arg->IgnoreParenCasts(); 5370 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5371 5372 if (!Literal || !Literal->isAscii()) { 5373 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5374 << Arg->getSourceRange(); 5375 return true; 5376 } 5377 5378 if (Literal->containsNonAsciiOrNull()) { 5379 StringRef String = Literal->getString(); 5380 unsigned NumBytes = String.size(); 5381 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5382 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5383 llvm::UTF16 *ToPtr = &ToBuf[0]; 5384 5385 llvm::ConversionResult Result = 5386 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5387 ToPtr + NumBytes, llvm::strictConversion); 5388 // Check for conversion failure. 5389 if (Result != llvm::conversionOK) 5390 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5391 << Arg->getSourceRange(); 5392 } 5393 return false; 5394 } 5395 5396 /// CheckObjCString - Checks that the format string argument to the os_log() 5397 /// and os_trace() functions is correct, and converts it to const char *. 5398 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5399 Arg = Arg->IgnoreParenCasts(); 5400 auto *Literal = dyn_cast<StringLiteral>(Arg); 5401 if (!Literal) { 5402 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5403 Literal = ObjcLiteral->getString(); 5404 } 5405 } 5406 5407 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5408 return ExprError( 5409 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5410 << Arg->getSourceRange()); 5411 } 5412 5413 ExprResult Result(Literal); 5414 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5415 InitializedEntity Entity = 5416 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5417 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5418 return Result; 5419 } 5420 5421 /// Check that the user is calling the appropriate va_start builtin for the 5422 /// target and calling convention. 5423 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5424 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5425 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5426 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5427 TT.getArch() == llvm::Triple::aarch64_32); 5428 bool IsWindows = TT.isOSWindows(); 5429 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5430 if (IsX64 || IsAArch64) { 5431 CallingConv CC = CC_C; 5432 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5433 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5434 if (IsMSVAStart) { 5435 // Don't allow this in System V ABI functions. 5436 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5437 return S.Diag(Fn->getBeginLoc(), 5438 diag::err_ms_va_start_used_in_sysv_function); 5439 } else { 5440 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5441 // On x64 Windows, don't allow this in System V ABI functions. 5442 // (Yes, that means there's no corresponding way to support variadic 5443 // System V ABI functions on Windows.) 5444 if ((IsWindows && CC == CC_X86_64SysV) || 5445 (!IsWindows && CC == CC_Win64)) 5446 return S.Diag(Fn->getBeginLoc(), 5447 diag::err_va_start_used_in_wrong_abi_function) 5448 << !IsWindows; 5449 } 5450 return false; 5451 } 5452 5453 if (IsMSVAStart) 5454 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5455 return false; 5456 } 5457 5458 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5459 ParmVarDecl **LastParam = nullptr) { 5460 // Determine whether the current function, block, or obj-c method is variadic 5461 // and get its parameter list. 5462 bool IsVariadic = false; 5463 ArrayRef<ParmVarDecl *> Params; 5464 DeclContext *Caller = S.CurContext; 5465 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5466 IsVariadic = Block->isVariadic(); 5467 Params = Block->parameters(); 5468 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5469 IsVariadic = FD->isVariadic(); 5470 Params = FD->parameters(); 5471 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5472 IsVariadic = MD->isVariadic(); 5473 // FIXME: This isn't correct for methods (results in bogus warning). 5474 Params = MD->parameters(); 5475 } else if (isa<CapturedDecl>(Caller)) { 5476 // We don't support va_start in a CapturedDecl. 5477 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5478 return true; 5479 } else { 5480 // This must be some other declcontext that parses exprs. 5481 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5482 return true; 5483 } 5484 5485 if (!IsVariadic) { 5486 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5487 return true; 5488 } 5489 5490 if (LastParam) 5491 *LastParam = Params.empty() ? nullptr : Params.back(); 5492 5493 return false; 5494 } 5495 5496 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5497 /// for validity. Emit an error and return true on failure; return false 5498 /// on success. 5499 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5500 Expr *Fn = TheCall->getCallee(); 5501 5502 if (checkVAStartABI(*this, BuiltinID, Fn)) 5503 return true; 5504 5505 if (TheCall->getNumArgs() > 2) { 5506 Diag(TheCall->getArg(2)->getBeginLoc(), 5507 diag::err_typecheck_call_too_many_args) 5508 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5509 << Fn->getSourceRange() 5510 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5511 (*(TheCall->arg_end() - 1))->getEndLoc()); 5512 return true; 5513 } 5514 5515 if (TheCall->getNumArgs() < 2) { 5516 return Diag(TheCall->getEndLoc(), 5517 diag::err_typecheck_call_too_few_args_at_least) 5518 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5519 } 5520 5521 // Type-check the first argument normally. 5522 if (checkBuiltinArgument(*this, TheCall, 0)) 5523 return true; 5524 5525 // Check that the current function is variadic, and get its last parameter. 5526 ParmVarDecl *LastParam; 5527 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5528 return true; 5529 5530 // Verify that the second argument to the builtin is the last argument of the 5531 // current function or method. 5532 bool SecondArgIsLastNamedArgument = false; 5533 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5534 5535 // These are valid if SecondArgIsLastNamedArgument is false after the next 5536 // block. 5537 QualType Type; 5538 SourceLocation ParamLoc; 5539 bool IsCRegister = false; 5540 5541 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5542 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5543 SecondArgIsLastNamedArgument = PV == LastParam; 5544 5545 Type = PV->getType(); 5546 ParamLoc = PV->getLocation(); 5547 IsCRegister = 5548 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5549 } 5550 } 5551 5552 if (!SecondArgIsLastNamedArgument) 5553 Diag(TheCall->getArg(1)->getBeginLoc(), 5554 diag::warn_second_arg_of_va_start_not_last_named_param); 5555 else if (IsCRegister || Type->isReferenceType() || 5556 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5557 // Promotable integers are UB, but enumerations need a bit of 5558 // extra checking to see what their promotable type actually is. 5559 if (!Type->isPromotableIntegerType()) 5560 return false; 5561 if (!Type->isEnumeralType()) 5562 return true; 5563 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5564 return !(ED && 5565 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5566 }()) { 5567 unsigned Reason = 0; 5568 if (Type->isReferenceType()) Reason = 1; 5569 else if (IsCRegister) Reason = 2; 5570 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5571 Diag(ParamLoc, diag::note_parameter_type) << Type; 5572 } 5573 5574 TheCall->setType(Context.VoidTy); 5575 return false; 5576 } 5577 5578 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5579 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5580 // const char *named_addr); 5581 5582 Expr *Func = Call->getCallee(); 5583 5584 if (Call->getNumArgs() < 3) 5585 return Diag(Call->getEndLoc(), 5586 diag::err_typecheck_call_too_few_args_at_least) 5587 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5588 5589 // Type-check the first argument normally. 5590 if (checkBuiltinArgument(*this, Call, 0)) 5591 return true; 5592 5593 // Check that the current function is variadic. 5594 if (checkVAStartIsInVariadicFunction(*this, Func)) 5595 return true; 5596 5597 // __va_start on Windows does not validate the parameter qualifiers 5598 5599 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5600 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5601 5602 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5603 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5604 5605 const QualType &ConstCharPtrTy = 5606 Context.getPointerType(Context.CharTy.withConst()); 5607 if (!Arg1Ty->isPointerType() || 5608 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5609 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5610 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5611 << 0 /* qualifier difference */ 5612 << 3 /* parameter mismatch */ 5613 << 2 << Arg1->getType() << ConstCharPtrTy; 5614 5615 const QualType SizeTy = Context.getSizeType(); 5616 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5617 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5618 << Arg2->getType() << SizeTy << 1 /* different class */ 5619 << 0 /* qualifier difference */ 5620 << 3 /* parameter mismatch */ 5621 << 3 << Arg2->getType() << SizeTy; 5622 5623 return false; 5624 } 5625 5626 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5627 /// friends. This is declared to take (...), so we have to check everything. 5628 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5629 if (TheCall->getNumArgs() < 2) 5630 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5631 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5632 if (TheCall->getNumArgs() > 2) 5633 return Diag(TheCall->getArg(2)->getBeginLoc(), 5634 diag::err_typecheck_call_too_many_args) 5635 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5636 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5637 (*(TheCall->arg_end() - 1))->getEndLoc()); 5638 5639 ExprResult OrigArg0 = TheCall->getArg(0); 5640 ExprResult OrigArg1 = TheCall->getArg(1); 5641 5642 // Do standard promotions between the two arguments, returning their common 5643 // type. 5644 QualType Res = UsualArithmeticConversions( 5645 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5646 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5647 return true; 5648 5649 // Make sure any conversions are pushed back into the call; this is 5650 // type safe since unordered compare builtins are declared as "_Bool 5651 // foo(...)". 5652 TheCall->setArg(0, OrigArg0.get()); 5653 TheCall->setArg(1, OrigArg1.get()); 5654 5655 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5656 return false; 5657 5658 // If the common type isn't a real floating type, then the arguments were 5659 // invalid for this operation. 5660 if (Res.isNull() || !Res->isRealFloatingType()) 5661 return Diag(OrigArg0.get()->getBeginLoc(), 5662 diag::err_typecheck_call_invalid_ordered_compare) 5663 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5664 << SourceRange(OrigArg0.get()->getBeginLoc(), 5665 OrigArg1.get()->getEndLoc()); 5666 5667 return false; 5668 } 5669 5670 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5671 /// __builtin_isnan and friends. This is declared to take (...), so we have 5672 /// to check everything. We expect the last argument to be a floating point 5673 /// value. 5674 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5675 if (TheCall->getNumArgs() < NumArgs) 5676 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5677 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5678 if (TheCall->getNumArgs() > NumArgs) 5679 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5680 diag::err_typecheck_call_too_many_args) 5681 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5682 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5683 (*(TheCall->arg_end() - 1))->getEndLoc()); 5684 5685 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5686 // on all preceding parameters just being int. Try all of those. 5687 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5688 Expr *Arg = TheCall->getArg(i); 5689 5690 if (Arg->isTypeDependent()) 5691 return false; 5692 5693 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5694 5695 if (Res.isInvalid()) 5696 return true; 5697 TheCall->setArg(i, Res.get()); 5698 } 5699 5700 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5701 5702 if (OrigArg->isTypeDependent()) 5703 return false; 5704 5705 // Usual Unary Conversions will convert half to float, which we want for 5706 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5707 // type how it is, but do normal L->Rvalue conversions. 5708 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5709 OrigArg = UsualUnaryConversions(OrigArg).get(); 5710 else 5711 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5712 TheCall->setArg(NumArgs - 1, OrigArg); 5713 5714 // This operation requires a non-_Complex floating-point number. 5715 if (!OrigArg->getType()->isRealFloatingType()) 5716 return Diag(OrigArg->getBeginLoc(), 5717 diag::err_typecheck_call_invalid_unary_fp) 5718 << OrigArg->getType() << OrigArg->getSourceRange(); 5719 5720 return false; 5721 } 5722 5723 // Customized Sema Checking for VSX builtins that have the following signature: 5724 // vector [...] builtinName(vector [...], vector [...], const int); 5725 // Which takes the same type of vectors (any legal vector type) for the first 5726 // two arguments and takes compile time constant for the third argument. 5727 // Example builtins are : 5728 // vector double vec_xxpermdi(vector double, vector double, int); 5729 // vector short vec_xxsldwi(vector short, vector short, int); 5730 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5731 unsigned ExpectedNumArgs = 3; 5732 if (TheCall->getNumArgs() < ExpectedNumArgs) 5733 return Diag(TheCall->getEndLoc(), 5734 diag::err_typecheck_call_too_few_args_at_least) 5735 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5736 << TheCall->getSourceRange(); 5737 5738 if (TheCall->getNumArgs() > ExpectedNumArgs) 5739 return Diag(TheCall->getEndLoc(), 5740 diag::err_typecheck_call_too_many_args_at_most) 5741 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5742 << TheCall->getSourceRange(); 5743 5744 // Check the third argument is a compile time constant 5745 llvm::APSInt Value; 5746 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5747 return Diag(TheCall->getBeginLoc(), 5748 diag::err_vsx_builtin_nonconstant_argument) 5749 << 3 /* argument index */ << TheCall->getDirectCallee() 5750 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5751 TheCall->getArg(2)->getEndLoc()); 5752 5753 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5754 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5755 5756 // Check the type of argument 1 and argument 2 are vectors. 5757 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5758 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5759 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5760 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5761 << TheCall->getDirectCallee() 5762 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5763 TheCall->getArg(1)->getEndLoc()); 5764 } 5765 5766 // Check the first two arguments are the same type. 5767 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5768 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5769 << TheCall->getDirectCallee() 5770 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5771 TheCall->getArg(1)->getEndLoc()); 5772 } 5773 5774 // When default clang type checking is turned off and the customized type 5775 // checking is used, the returning type of the function must be explicitly 5776 // set. Otherwise it is _Bool by default. 5777 TheCall->setType(Arg1Ty); 5778 5779 return false; 5780 } 5781 5782 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5783 // This is declared to take (...), so we have to check everything. 5784 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5785 if (TheCall->getNumArgs() < 2) 5786 return ExprError(Diag(TheCall->getEndLoc(), 5787 diag::err_typecheck_call_too_few_args_at_least) 5788 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5789 << TheCall->getSourceRange()); 5790 5791 // Determine which of the following types of shufflevector we're checking: 5792 // 1) unary, vector mask: (lhs, mask) 5793 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5794 QualType resType = TheCall->getArg(0)->getType(); 5795 unsigned numElements = 0; 5796 5797 if (!TheCall->getArg(0)->isTypeDependent() && 5798 !TheCall->getArg(1)->isTypeDependent()) { 5799 QualType LHSType = TheCall->getArg(0)->getType(); 5800 QualType RHSType = TheCall->getArg(1)->getType(); 5801 5802 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5803 return ExprError( 5804 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5805 << TheCall->getDirectCallee() 5806 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5807 TheCall->getArg(1)->getEndLoc())); 5808 5809 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5810 unsigned numResElements = TheCall->getNumArgs() - 2; 5811 5812 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5813 // with mask. If so, verify that RHS is an integer vector type with the 5814 // same number of elts as lhs. 5815 if (TheCall->getNumArgs() == 2) { 5816 if (!RHSType->hasIntegerRepresentation() || 5817 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5818 return ExprError(Diag(TheCall->getBeginLoc(), 5819 diag::err_vec_builtin_incompatible_vector) 5820 << TheCall->getDirectCallee() 5821 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5822 TheCall->getArg(1)->getEndLoc())); 5823 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5824 return ExprError(Diag(TheCall->getBeginLoc(), 5825 diag::err_vec_builtin_incompatible_vector) 5826 << TheCall->getDirectCallee() 5827 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5828 TheCall->getArg(1)->getEndLoc())); 5829 } else if (numElements != numResElements) { 5830 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5831 resType = Context.getVectorType(eltType, numResElements, 5832 VectorType::GenericVector); 5833 } 5834 } 5835 5836 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5837 if (TheCall->getArg(i)->isTypeDependent() || 5838 TheCall->getArg(i)->isValueDependent()) 5839 continue; 5840 5841 llvm::APSInt Result(32); 5842 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5843 return ExprError(Diag(TheCall->getBeginLoc(), 5844 diag::err_shufflevector_nonconstant_argument) 5845 << TheCall->getArg(i)->getSourceRange()); 5846 5847 // Allow -1 which will be translated to undef in the IR. 5848 if (Result.isSigned() && Result.isAllOnesValue()) 5849 continue; 5850 5851 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5852 return ExprError(Diag(TheCall->getBeginLoc(), 5853 diag::err_shufflevector_argument_too_large) 5854 << TheCall->getArg(i)->getSourceRange()); 5855 } 5856 5857 SmallVector<Expr*, 32> exprs; 5858 5859 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5860 exprs.push_back(TheCall->getArg(i)); 5861 TheCall->setArg(i, nullptr); 5862 } 5863 5864 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5865 TheCall->getCallee()->getBeginLoc(), 5866 TheCall->getRParenLoc()); 5867 } 5868 5869 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5870 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5871 SourceLocation BuiltinLoc, 5872 SourceLocation RParenLoc) { 5873 ExprValueKind VK = VK_RValue; 5874 ExprObjectKind OK = OK_Ordinary; 5875 QualType DstTy = TInfo->getType(); 5876 QualType SrcTy = E->getType(); 5877 5878 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5879 return ExprError(Diag(BuiltinLoc, 5880 diag::err_convertvector_non_vector) 5881 << E->getSourceRange()); 5882 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5883 return ExprError(Diag(BuiltinLoc, 5884 diag::err_convertvector_non_vector_type)); 5885 5886 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5887 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 5888 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 5889 if (SrcElts != DstElts) 5890 return ExprError(Diag(BuiltinLoc, 5891 diag::err_convertvector_incompatible_vector) 5892 << E->getSourceRange()); 5893 } 5894 5895 return new (Context) 5896 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5897 } 5898 5899 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5900 // This is declared to take (const void*, ...) and can take two 5901 // optional constant int args. 5902 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5903 unsigned NumArgs = TheCall->getNumArgs(); 5904 5905 if (NumArgs > 3) 5906 return Diag(TheCall->getEndLoc(), 5907 diag::err_typecheck_call_too_many_args_at_most) 5908 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5909 5910 // Argument 0 is checked for us and the remaining arguments must be 5911 // constant integers. 5912 for (unsigned i = 1; i != NumArgs; ++i) 5913 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5914 return true; 5915 5916 return false; 5917 } 5918 5919 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5920 // __assume does not evaluate its arguments, and should warn if its argument 5921 // has side effects. 5922 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5923 Expr *Arg = TheCall->getArg(0); 5924 if (Arg->isInstantiationDependent()) return false; 5925 5926 if (Arg->HasSideEffects(Context)) 5927 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5928 << Arg->getSourceRange() 5929 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5930 5931 return false; 5932 } 5933 5934 /// Handle __builtin_alloca_with_align. This is declared 5935 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5936 /// than 8. 5937 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5938 // The alignment must be a constant integer. 5939 Expr *Arg = TheCall->getArg(1); 5940 5941 // We can't check the value of a dependent argument. 5942 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5943 if (const auto *UE = 5944 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5945 if (UE->getKind() == UETT_AlignOf || 5946 UE->getKind() == UETT_PreferredAlignOf) 5947 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5948 << Arg->getSourceRange(); 5949 5950 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5951 5952 if (!Result.isPowerOf2()) 5953 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5954 << Arg->getSourceRange(); 5955 5956 if (Result < Context.getCharWidth()) 5957 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5958 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5959 5960 if (Result > std::numeric_limits<int32_t>::max()) 5961 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5962 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5963 } 5964 5965 return false; 5966 } 5967 5968 /// Handle __builtin_assume_aligned. This is declared 5969 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5970 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5971 unsigned NumArgs = TheCall->getNumArgs(); 5972 5973 if (NumArgs > 3) 5974 return Diag(TheCall->getEndLoc(), 5975 diag::err_typecheck_call_too_many_args_at_most) 5976 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5977 5978 // The alignment must be a constant integer. 5979 Expr *Arg = TheCall->getArg(1); 5980 5981 // We can't check the value of a dependent argument. 5982 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5983 llvm::APSInt Result; 5984 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5985 return true; 5986 5987 if (!Result.isPowerOf2()) 5988 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5989 << Arg->getSourceRange(); 5990 5991 if (Result > Sema::MaximumAlignment) 5992 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 5993 << Arg->getSourceRange() << Sema::MaximumAlignment; 5994 } 5995 5996 if (NumArgs > 2) { 5997 ExprResult Arg(TheCall->getArg(2)); 5998 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5999 Context.getSizeType(), false); 6000 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6001 if (Arg.isInvalid()) return true; 6002 TheCall->setArg(2, Arg.get()); 6003 } 6004 6005 return false; 6006 } 6007 6008 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6009 unsigned BuiltinID = 6010 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6011 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6012 6013 unsigned NumArgs = TheCall->getNumArgs(); 6014 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6015 if (NumArgs < NumRequiredArgs) { 6016 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6017 << 0 /* function call */ << NumRequiredArgs << NumArgs 6018 << TheCall->getSourceRange(); 6019 } 6020 if (NumArgs >= NumRequiredArgs + 0x100) { 6021 return Diag(TheCall->getEndLoc(), 6022 diag::err_typecheck_call_too_many_args_at_most) 6023 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6024 << TheCall->getSourceRange(); 6025 } 6026 unsigned i = 0; 6027 6028 // For formatting call, check buffer arg. 6029 if (!IsSizeCall) { 6030 ExprResult Arg(TheCall->getArg(i)); 6031 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6032 Context, Context.VoidPtrTy, false); 6033 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6034 if (Arg.isInvalid()) 6035 return true; 6036 TheCall->setArg(i, Arg.get()); 6037 i++; 6038 } 6039 6040 // Check string literal arg. 6041 unsigned FormatIdx = i; 6042 { 6043 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6044 if (Arg.isInvalid()) 6045 return true; 6046 TheCall->setArg(i, Arg.get()); 6047 i++; 6048 } 6049 6050 // Make sure variadic args are scalar. 6051 unsigned FirstDataArg = i; 6052 while (i < NumArgs) { 6053 ExprResult Arg = DefaultVariadicArgumentPromotion( 6054 TheCall->getArg(i), VariadicFunction, nullptr); 6055 if (Arg.isInvalid()) 6056 return true; 6057 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6058 if (ArgSize.getQuantity() >= 0x100) { 6059 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6060 << i << (int)ArgSize.getQuantity() << 0xff 6061 << TheCall->getSourceRange(); 6062 } 6063 TheCall->setArg(i, Arg.get()); 6064 i++; 6065 } 6066 6067 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6068 // call to avoid duplicate diagnostics. 6069 if (!IsSizeCall) { 6070 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6071 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6072 bool Success = CheckFormatArguments( 6073 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6074 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6075 CheckedVarArgs); 6076 if (!Success) 6077 return true; 6078 } 6079 6080 if (IsSizeCall) { 6081 TheCall->setType(Context.getSizeType()); 6082 } else { 6083 TheCall->setType(Context.VoidPtrTy); 6084 } 6085 return false; 6086 } 6087 6088 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6089 /// TheCall is a constant expression. 6090 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6091 llvm::APSInt &Result) { 6092 Expr *Arg = TheCall->getArg(ArgNum); 6093 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6094 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6095 6096 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6097 6098 if (!Arg->isIntegerConstantExpr(Result, Context)) 6099 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6100 << FDecl->getDeclName() << Arg->getSourceRange(); 6101 6102 return false; 6103 } 6104 6105 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6106 /// TheCall is a constant expression in the range [Low, High]. 6107 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6108 int Low, int High, bool RangeIsError) { 6109 if (isConstantEvaluated()) 6110 return false; 6111 llvm::APSInt Result; 6112 6113 // We can't check the value of a dependent argument. 6114 Expr *Arg = TheCall->getArg(ArgNum); 6115 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6116 return false; 6117 6118 // Check constant-ness first. 6119 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6120 return true; 6121 6122 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6123 if (RangeIsError) 6124 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6125 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6126 else 6127 // Defer the warning until we know if the code will be emitted so that 6128 // dead code can ignore this. 6129 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6130 PDiag(diag::warn_argument_invalid_range) 6131 << Result.toString(10) << Low << High 6132 << Arg->getSourceRange()); 6133 } 6134 6135 return false; 6136 } 6137 6138 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6139 /// TheCall is a constant expression is a multiple of Num.. 6140 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6141 unsigned Num) { 6142 llvm::APSInt Result; 6143 6144 // We can't check the value of a dependent argument. 6145 Expr *Arg = TheCall->getArg(ArgNum); 6146 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6147 return false; 6148 6149 // Check constant-ness first. 6150 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6151 return true; 6152 6153 if (Result.getSExtValue() % Num != 0) 6154 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6155 << Num << Arg->getSourceRange(); 6156 6157 return false; 6158 } 6159 6160 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6161 /// constant expression representing a power of 2. 6162 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6163 llvm::APSInt Result; 6164 6165 // We can't check the value of a dependent argument. 6166 Expr *Arg = TheCall->getArg(ArgNum); 6167 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6168 return false; 6169 6170 // Check constant-ness first. 6171 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6172 return true; 6173 6174 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6175 // and only if x is a power of 2. 6176 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6177 return false; 6178 6179 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6180 << Arg->getSourceRange(); 6181 } 6182 6183 static bool IsShiftedByte(llvm::APSInt Value) { 6184 if (Value.isNegative()) 6185 return false; 6186 6187 // Check if it's a shifted byte, by shifting it down 6188 while (true) { 6189 // If the value fits in the bottom byte, the check passes. 6190 if (Value < 0x100) 6191 return true; 6192 6193 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6194 // fails. 6195 if ((Value & 0xFF) != 0) 6196 return false; 6197 6198 // If the bottom 8 bits are all 0, but something above that is nonzero, 6199 // then shifting the value right by 8 bits won't affect whether it's a 6200 // shifted byte or not. So do that, and go round again. 6201 Value >>= 8; 6202 } 6203 } 6204 6205 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6206 /// a constant expression representing an arbitrary byte value shifted left by 6207 /// a multiple of 8 bits. 6208 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6209 unsigned ArgBits) { 6210 llvm::APSInt Result; 6211 6212 // We can't check the value of a dependent argument. 6213 Expr *Arg = TheCall->getArg(ArgNum); 6214 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6215 return false; 6216 6217 // Check constant-ness first. 6218 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6219 return true; 6220 6221 // Truncate to the given size. 6222 Result = Result.getLoBits(ArgBits); 6223 Result.setIsUnsigned(true); 6224 6225 if (IsShiftedByte(Result)) 6226 return false; 6227 6228 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6229 << Arg->getSourceRange(); 6230 } 6231 6232 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6233 /// TheCall is a constant expression representing either a shifted byte value, 6234 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6235 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6236 /// Arm MVE intrinsics. 6237 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6238 int ArgNum, 6239 unsigned ArgBits) { 6240 llvm::APSInt Result; 6241 6242 // We can't check the value of a dependent argument. 6243 Expr *Arg = TheCall->getArg(ArgNum); 6244 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6245 return false; 6246 6247 // Check constant-ness first. 6248 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6249 return true; 6250 6251 // Truncate to the given size. 6252 Result = Result.getLoBits(ArgBits); 6253 Result.setIsUnsigned(true); 6254 6255 // Check to see if it's in either of the required forms. 6256 if (IsShiftedByte(Result) || 6257 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6258 return false; 6259 6260 return Diag(TheCall->getBeginLoc(), 6261 diag::err_argument_not_shifted_byte_or_xxff) 6262 << Arg->getSourceRange(); 6263 } 6264 6265 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6266 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6267 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6268 if (checkArgCount(*this, TheCall, 2)) 6269 return true; 6270 Expr *Arg0 = TheCall->getArg(0); 6271 Expr *Arg1 = TheCall->getArg(1); 6272 6273 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6274 if (FirstArg.isInvalid()) 6275 return true; 6276 QualType FirstArgType = FirstArg.get()->getType(); 6277 if (!FirstArgType->isAnyPointerType()) 6278 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6279 << "first" << FirstArgType << Arg0->getSourceRange(); 6280 TheCall->setArg(0, FirstArg.get()); 6281 6282 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6283 if (SecArg.isInvalid()) 6284 return true; 6285 QualType SecArgType = SecArg.get()->getType(); 6286 if (!SecArgType->isIntegerType()) 6287 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6288 << "second" << SecArgType << Arg1->getSourceRange(); 6289 6290 // Derive the return type from the pointer argument. 6291 TheCall->setType(FirstArgType); 6292 return false; 6293 } 6294 6295 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6296 if (checkArgCount(*this, TheCall, 2)) 6297 return true; 6298 6299 Expr *Arg0 = TheCall->getArg(0); 6300 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6301 if (FirstArg.isInvalid()) 6302 return true; 6303 QualType FirstArgType = FirstArg.get()->getType(); 6304 if (!FirstArgType->isAnyPointerType()) 6305 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6306 << "first" << FirstArgType << Arg0->getSourceRange(); 6307 TheCall->setArg(0, FirstArg.get()); 6308 6309 // Derive the return type from the pointer argument. 6310 TheCall->setType(FirstArgType); 6311 6312 // Second arg must be an constant in range [0,15] 6313 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6314 } 6315 6316 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6317 if (checkArgCount(*this, TheCall, 2)) 6318 return true; 6319 Expr *Arg0 = TheCall->getArg(0); 6320 Expr *Arg1 = TheCall->getArg(1); 6321 6322 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6323 if (FirstArg.isInvalid()) 6324 return true; 6325 QualType FirstArgType = FirstArg.get()->getType(); 6326 if (!FirstArgType->isAnyPointerType()) 6327 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6328 << "first" << FirstArgType << Arg0->getSourceRange(); 6329 6330 QualType SecArgType = Arg1->getType(); 6331 if (!SecArgType->isIntegerType()) 6332 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6333 << "second" << SecArgType << Arg1->getSourceRange(); 6334 TheCall->setType(Context.IntTy); 6335 return false; 6336 } 6337 6338 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6339 BuiltinID == AArch64::BI__builtin_arm_stg) { 6340 if (checkArgCount(*this, TheCall, 1)) 6341 return true; 6342 Expr *Arg0 = TheCall->getArg(0); 6343 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6344 if (FirstArg.isInvalid()) 6345 return true; 6346 6347 QualType FirstArgType = FirstArg.get()->getType(); 6348 if (!FirstArgType->isAnyPointerType()) 6349 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6350 << "first" << FirstArgType << Arg0->getSourceRange(); 6351 TheCall->setArg(0, FirstArg.get()); 6352 6353 // Derive the return type from the pointer argument. 6354 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6355 TheCall->setType(FirstArgType); 6356 return false; 6357 } 6358 6359 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6360 Expr *ArgA = TheCall->getArg(0); 6361 Expr *ArgB = TheCall->getArg(1); 6362 6363 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6364 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6365 6366 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6367 return true; 6368 6369 QualType ArgTypeA = ArgExprA.get()->getType(); 6370 QualType ArgTypeB = ArgExprB.get()->getType(); 6371 6372 auto isNull = [&] (Expr *E) -> bool { 6373 return E->isNullPointerConstant( 6374 Context, Expr::NPC_ValueDependentIsNotNull); }; 6375 6376 // argument should be either a pointer or null 6377 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6378 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6379 << "first" << ArgTypeA << ArgA->getSourceRange(); 6380 6381 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6382 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6383 << "second" << ArgTypeB << ArgB->getSourceRange(); 6384 6385 // Ensure Pointee types are compatible 6386 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6387 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6388 QualType pointeeA = ArgTypeA->getPointeeType(); 6389 QualType pointeeB = ArgTypeB->getPointeeType(); 6390 if (!Context.typesAreCompatible( 6391 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6392 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6393 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6394 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6395 << ArgB->getSourceRange(); 6396 } 6397 } 6398 6399 // at least one argument should be pointer type 6400 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6401 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6402 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6403 6404 if (isNull(ArgA)) // adopt type of the other pointer 6405 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6406 6407 if (isNull(ArgB)) 6408 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6409 6410 TheCall->setArg(0, ArgExprA.get()); 6411 TheCall->setArg(1, ArgExprB.get()); 6412 TheCall->setType(Context.LongLongTy); 6413 return false; 6414 } 6415 assert(false && "Unhandled ARM MTE intrinsic"); 6416 return true; 6417 } 6418 6419 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6420 /// TheCall is an ARM/AArch64 special register string literal. 6421 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6422 int ArgNum, unsigned ExpectedFieldNum, 6423 bool AllowName) { 6424 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6425 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6426 BuiltinID == ARM::BI__builtin_arm_rsr || 6427 BuiltinID == ARM::BI__builtin_arm_rsrp || 6428 BuiltinID == ARM::BI__builtin_arm_wsr || 6429 BuiltinID == ARM::BI__builtin_arm_wsrp; 6430 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6431 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6432 BuiltinID == AArch64::BI__builtin_arm_rsr || 6433 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6434 BuiltinID == AArch64::BI__builtin_arm_wsr || 6435 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6436 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6437 6438 // We can't check the value of a dependent argument. 6439 Expr *Arg = TheCall->getArg(ArgNum); 6440 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6441 return false; 6442 6443 // Check if the argument is a string literal. 6444 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6445 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6446 << Arg->getSourceRange(); 6447 6448 // Check the type of special register given. 6449 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6450 SmallVector<StringRef, 6> Fields; 6451 Reg.split(Fields, ":"); 6452 6453 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6454 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6455 << Arg->getSourceRange(); 6456 6457 // If the string is the name of a register then we cannot check that it is 6458 // valid here but if the string is of one the forms described in ACLE then we 6459 // can check that the supplied fields are integers and within the valid 6460 // ranges. 6461 if (Fields.size() > 1) { 6462 bool FiveFields = Fields.size() == 5; 6463 6464 bool ValidString = true; 6465 if (IsARMBuiltin) { 6466 ValidString &= Fields[0].startswith_lower("cp") || 6467 Fields[0].startswith_lower("p"); 6468 if (ValidString) 6469 Fields[0] = 6470 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6471 6472 ValidString &= Fields[2].startswith_lower("c"); 6473 if (ValidString) 6474 Fields[2] = Fields[2].drop_front(1); 6475 6476 if (FiveFields) { 6477 ValidString &= Fields[3].startswith_lower("c"); 6478 if (ValidString) 6479 Fields[3] = Fields[3].drop_front(1); 6480 } 6481 } 6482 6483 SmallVector<int, 5> Ranges; 6484 if (FiveFields) 6485 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6486 else 6487 Ranges.append({15, 7, 15}); 6488 6489 for (unsigned i=0; i<Fields.size(); ++i) { 6490 int IntField; 6491 ValidString &= !Fields[i].getAsInteger(10, IntField); 6492 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6493 } 6494 6495 if (!ValidString) 6496 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6497 << Arg->getSourceRange(); 6498 } else if (IsAArch64Builtin && Fields.size() == 1) { 6499 // If the register name is one of those that appear in the condition below 6500 // and the special register builtin being used is one of the write builtins, 6501 // then we require that the argument provided for writing to the register 6502 // is an integer constant expression. This is because it will be lowered to 6503 // an MSR (immediate) instruction, so we need to know the immediate at 6504 // compile time. 6505 if (TheCall->getNumArgs() != 2) 6506 return false; 6507 6508 std::string RegLower = Reg.lower(); 6509 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6510 RegLower != "pan" && RegLower != "uao") 6511 return false; 6512 6513 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6514 } 6515 6516 return false; 6517 } 6518 6519 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6520 /// This checks that the target supports __builtin_longjmp and 6521 /// that val is a constant 1. 6522 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6523 if (!Context.getTargetInfo().hasSjLjLowering()) 6524 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6525 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6526 6527 Expr *Arg = TheCall->getArg(1); 6528 llvm::APSInt Result; 6529 6530 // TODO: This is less than ideal. Overload this to take a value. 6531 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6532 return true; 6533 6534 if (Result != 1) 6535 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6536 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6537 6538 return false; 6539 } 6540 6541 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6542 /// This checks that the target supports __builtin_setjmp. 6543 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6544 if (!Context.getTargetInfo().hasSjLjLowering()) 6545 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6546 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6547 return false; 6548 } 6549 6550 namespace { 6551 6552 class UncoveredArgHandler { 6553 enum { Unknown = -1, AllCovered = -2 }; 6554 6555 signed FirstUncoveredArg = Unknown; 6556 SmallVector<const Expr *, 4> DiagnosticExprs; 6557 6558 public: 6559 UncoveredArgHandler() = default; 6560 6561 bool hasUncoveredArg() const { 6562 return (FirstUncoveredArg >= 0); 6563 } 6564 6565 unsigned getUncoveredArg() const { 6566 assert(hasUncoveredArg() && "no uncovered argument"); 6567 return FirstUncoveredArg; 6568 } 6569 6570 void setAllCovered() { 6571 // A string has been found with all arguments covered, so clear out 6572 // the diagnostics. 6573 DiagnosticExprs.clear(); 6574 FirstUncoveredArg = AllCovered; 6575 } 6576 6577 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6578 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6579 6580 // Don't update if a previous string covers all arguments. 6581 if (FirstUncoveredArg == AllCovered) 6582 return; 6583 6584 // UncoveredArgHandler tracks the highest uncovered argument index 6585 // and with it all the strings that match this index. 6586 if (NewFirstUncoveredArg == FirstUncoveredArg) 6587 DiagnosticExprs.push_back(StrExpr); 6588 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6589 DiagnosticExprs.clear(); 6590 DiagnosticExprs.push_back(StrExpr); 6591 FirstUncoveredArg = NewFirstUncoveredArg; 6592 } 6593 } 6594 6595 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6596 }; 6597 6598 enum StringLiteralCheckType { 6599 SLCT_NotALiteral, 6600 SLCT_UncheckedLiteral, 6601 SLCT_CheckedLiteral 6602 }; 6603 6604 } // namespace 6605 6606 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6607 BinaryOperatorKind BinOpKind, 6608 bool AddendIsRight) { 6609 unsigned BitWidth = Offset.getBitWidth(); 6610 unsigned AddendBitWidth = Addend.getBitWidth(); 6611 // There might be negative interim results. 6612 if (Addend.isUnsigned()) { 6613 Addend = Addend.zext(++AddendBitWidth); 6614 Addend.setIsSigned(true); 6615 } 6616 // Adjust the bit width of the APSInts. 6617 if (AddendBitWidth > BitWidth) { 6618 Offset = Offset.sext(AddendBitWidth); 6619 BitWidth = AddendBitWidth; 6620 } else if (BitWidth > AddendBitWidth) { 6621 Addend = Addend.sext(BitWidth); 6622 } 6623 6624 bool Ov = false; 6625 llvm::APSInt ResOffset = Offset; 6626 if (BinOpKind == BO_Add) 6627 ResOffset = Offset.sadd_ov(Addend, Ov); 6628 else { 6629 assert(AddendIsRight && BinOpKind == BO_Sub && 6630 "operator must be add or sub with addend on the right"); 6631 ResOffset = Offset.ssub_ov(Addend, Ov); 6632 } 6633 6634 // We add an offset to a pointer here so we should support an offset as big as 6635 // possible. 6636 if (Ov) { 6637 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6638 "index (intermediate) result too big"); 6639 Offset = Offset.sext(2 * BitWidth); 6640 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6641 return; 6642 } 6643 6644 Offset = ResOffset; 6645 } 6646 6647 namespace { 6648 6649 // This is a wrapper class around StringLiteral to support offsetted string 6650 // literals as format strings. It takes the offset into account when returning 6651 // the string and its length or the source locations to display notes correctly. 6652 class FormatStringLiteral { 6653 const StringLiteral *FExpr; 6654 int64_t Offset; 6655 6656 public: 6657 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6658 : FExpr(fexpr), Offset(Offset) {} 6659 6660 StringRef getString() const { 6661 return FExpr->getString().drop_front(Offset); 6662 } 6663 6664 unsigned getByteLength() const { 6665 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6666 } 6667 6668 unsigned getLength() const { return FExpr->getLength() - Offset; } 6669 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6670 6671 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6672 6673 QualType getType() const { return FExpr->getType(); } 6674 6675 bool isAscii() const { return FExpr->isAscii(); } 6676 bool isWide() const { return FExpr->isWide(); } 6677 bool isUTF8() const { return FExpr->isUTF8(); } 6678 bool isUTF16() const { return FExpr->isUTF16(); } 6679 bool isUTF32() const { return FExpr->isUTF32(); } 6680 bool isPascal() const { return FExpr->isPascal(); } 6681 6682 SourceLocation getLocationOfByte( 6683 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6684 const TargetInfo &Target, unsigned *StartToken = nullptr, 6685 unsigned *StartTokenByteOffset = nullptr) const { 6686 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6687 StartToken, StartTokenByteOffset); 6688 } 6689 6690 SourceLocation getBeginLoc() const LLVM_READONLY { 6691 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6692 } 6693 6694 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6695 }; 6696 6697 } // namespace 6698 6699 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6700 const Expr *OrigFormatExpr, 6701 ArrayRef<const Expr *> Args, 6702 bool HasVAListArg, unsigned format_idx, 6703 unsigned firstDataArg, 6704 Sema::FormatStringType Type, 6705 bool inFunctionCall, 6706 Sema::VariadicCallType CallType, 6707 llvm::SmallBitVector &CheckedVarArgs, 6708 UncoveredArgHandler &UncoveredArg, 6709 bool IgnoreStringsWithoutSpecifiers); 6710 6711 // Determine if an expression is a string literal or constant string. 6712 // If this function returns false on the arguments to a function expecting a 6713 // format string, we will usually need to emit a warning. 6714 // True string literals are then checked by CheckFormatString. 6715 static StringLiteralCheckType 6716 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6717 bool HasVAListArg, unsigned format_idx, 6718 unsigned firstDataArg, Sema::FormatStringType Type, 6719 Sema::VariadicCallType CallType, bool InFunctionCall, 6720 llvm::SmallBitVector &CheckedVarArgs, 6721 UncoveredArgHandler &UncoveredArg, 6722 llvm::APSInt Offset, 6723 bool IgnoreStringsWithoutSpecifiers = false) { 6724 if (S.isConstantEvaluated()) 6725 return SLCT_NotALiteral; 6726 tryAgain: 6727 assert(Offset.isSigned() && "invalid offset"); 6728 6729 if (E->isTypeDependent() || E->isValueDependent()) 6730 return SLCT_NotALiteral; 6731 6732 E = E->IgnoreParenCasts(); 6733 6734 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6735 // Technically -Wformat-nonliteral does not warn about this case. 6736 // The behavior of printf and friends in this case is implementation 6737 // dependent. Ideally if the format string cannot be null then 6738 // it should have a 'nonnull' attribute in the function prototype. 6739 return SLCT_UncheckedLiteral; 6740 6741 switch (E->getStmtClass()) { 6742 case Stmt::BinaryConditionalOperatorClass: 6743 case Stmt::ConditionalOperatorClass: { 6744 // The expression is a literal if both sub-expressions were, and it was 6745 // completely checked only if both sub-expressions were checked. 6746 const AbstractConditionalOperator *C = 6747 cast<AbstractConditionalOperator>(E); 6748 6749 // Determine whether it is necessary to check both sub-expressions, for 6750 // example, because the condition expression is a constant that can be 6751 // evaluated at compile time. 6752 bool CheckLeft = true, CheckRight = true; 6753 6754 bool Cond; 6755 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6756 S.isConstantEvaluated())) { 6757 if (Cond) 6758 CheckRight = false; 6759 else 6760 CheckLeft = false; 6761 } 6762 6763 // We need to maintain the offsets for the right and the left hand side 6764 // separately to check if every possible indexed expression is a valid 6765 // string literal. They might have different offsets for different string 6766 // literals in the end. 6767 StringLiteralCheckType Left; 6768 if (!CheckLeft) 6769 Left = SLCT_UncheckedLiteral; 6770 else { 6771 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6772 HasVAListArg, format_idx, firstDataArg, 6773 Type, CallType, InFunctionCall, 6774 CheckedVarArgs, UncoveredArg, Offset, 6775 IgnoreStringsWithoutSpecifiers); 6776 if (Left == SLCT_NotALiteral || !CheckRight) { 6777 return Left; 6778 } 6779 } 6780 6781 StringLiteralCheckType Right = checkFormatStringExpr( 6782 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6783 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6784 IgnoreStringsWithoutSpecifiers); 6785 6786 return (CheckLeft && Left < Right) ? Left : Right; 6787 } 6788 6789 case Stmt::ImplicitCastExprClass: 6790 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6791 goto tryAgain; 6792 6793 case Stmt::OpaqueValueExprClass: 6794 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6795 E = src; 6796 goto tryAgain; 6797 } 6798 return SLCT_NotALiteral; 6799 6800 case Stmt::PredefinedExprClass: 6801 // While __func__, etc., are technically not string literals, they 6802 // cannot contain format specifiers and thus are not a security 6803 // liability. 6804 return SLCT_UncheckedLiteral; 6805 6806 case Stmt::DeclRefExprClass: { 6807 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6808 6809 // As an exception, do not flag errors for variables binding to 6810 // const string literals. 6811 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6812 bool isConstant = false; 6813 QualType T = DR->getType(); 6814 6815 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6816 isConstant = AT->getElementType().isConstant(S.Context); 6817 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6818 isConstant = T.isConstant(S.Context) && 6819 PT->getPointeeType().isConstant(S.Context); 6820 } else if (T->isObjCObjectPointerType()) { 6821 // In ObjC, there is usually no "const ObjectPointer" type, 6822 // so don't check if the pointee type is constant. 6823 isConstant = T.isConstant(S.Context); 6824 } 6825 6826 if (isConstant) { 6827 if (const Expr *Init = VD->getAnyInitializer()) { 6828 // Look through initializers like const char c[] = { "foo" } 6829 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6830 if (InitList->isStringLiteralInit()) 6831 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6832 } 6833 return checkFormatStringExpr(S, Init, Args, 6834 HasVAListArg, format_idx, 6835 firstDataArg, Type, CallType, 6836 /*InFunctionCall*/ false, CheckedVarArgs, 6837 UncoveredArg, Offset); 6838 } 6839 } 6840 6841 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6842 // special check to see if the format string is a function parameter 6843 // of the function calling the printf function. If the function 6844 // has an attribute indicating it is a printf-like function, then we 6845 // should suppress warnings concerning non-literals being used in a call 6846 // to a vprintf function. For example: 6847 // 6848 // void 6849 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6850 // va_list ap; 6851 // va_start(ap, fmt); 6852 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6853 // ... 6854 // } 6855 if (HasVAListArg) { 6856 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6857 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6858 int PVIndex = PV->getFunctionScopeIndex() + 1; 6859 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6860 // adjust for implicit parameter 6861 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6862 if (MD->isInstance()) 6863 ++PVIndex; 6864 // We also check if the formats are compatible. 6865 // We can't pass a 'scanf' string to a 'printf' function. 6866 if (PVIndex == PVFormat->getFormatIdx() && 6867 Type == S.GetFormatStringType(PVFormat)) 6868 return SLCT_UncheckedLiteral; 6869 } 6870 } 6871 } 6872 } 6873 } 6874 6875 return SLCT_NotALiteral; 6876 } 6877 6878 case Stmt::CallExprClass: 6879 case Stmt::CXXMemberCallExprClass: { 6880 const CallExpr *CE = cast<CallExpr>(E); 6881 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6882 bool IsFirst = true; 6883 StringLiteralCheckType CommonResult; 6884 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6885 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6886 StringLiteralCheckType Result = checkFormatStringExpr( 6887 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6888 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6889 IgnoreStringsWithoutSpecifiers); 6890 if (IsFirst) { 6891 CommonResult = Result; 6892 IsFirst = false; 6893 } 6894 } 6895 if (!IsFirst) 6896 return CommonResult; 6897 6898 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6899 unsigned BuiltinID = FD->getBuiltinID(); 6900 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6901 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6902 const Expr *Arg = CE->getArg(0); 6903 return checkFormatStringExpr(S, Arg, Args, 6904 HasVAListArg, format_idx, 6905 firstDataArg, Type, CallType, 6906 InFunctionCall, CheckedVarArgs, 6907 UncoveredArg, Offset, 6908 IgnoreStringsWithoutSpecifiers); 6909 } 6910 } 6911 } 6912 6913 return SLCT_NotALiteral; 6914 } 6915 case Stmt::ObjCMessageExprClass: { 6916 const auto *ME = cast<ObjCMessageExpr>(E); 6917 if (const auto *MD = ME->getMethodDecl()) { 6918 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 6919 // As a special case heuristic, if we're using the method -[NSBundle 6920 // localizedStringForKey:value:table:], ignore any key strings that lack 6921 // format specifiers. The idea is that if the key doesn't have any 6922 // format specifiers then its probably just a key to map to the 6923 // localized strings. If it does have format specifiers though, then its 6924 // likely that the text of the key is the format string in the 6925 // programmer's language, and should be checked. 6926 const ObjCInterfaceDecl *IFace; 6927 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 6928 IFace->getIdentifier()->isStr("NSBundle") && 6929 MD->getSelector().isKeywordSelector( 6930 {"localizedStringForKey", "value", "table"})) { 6931 IgnoreStringsWithoutSpecifiers = true; 6932 } 6933 6934 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6935 return checkFormatStringExpr( 6936 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6937 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6938 IgnoreStringsWithoutSpecifiers); 6939 } 6940 } 6941 6942 return SLCT_NotALiteral; 6943 } 6944 case Stmt::ObjCStringLiteralClass: 6945 case Stmt::StringLiteralClass: { 6946 const StringLiteral *StrE = nullptr; 6947 6948 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6949 StrE = ObjCFExpr->getString(); 6950 else 6951 StrE = cast<StringLiteral>(E); 6952 6953 if (StrE) { 6954 if (Offset.isNegative() || Offset > StrE->getLength()) { 6955 // TODO: It would be better to have an explicit warning for out of 6956 // bounds literals. 6957 return SLCT_NotALiteral; 6958 } 6959 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6960 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6961 firstDataArg, Type, InFunctionCall, CallType, 6962 CheckedVarArgs, UncoveredArg, 6963 IgnoreStringsWithoutSpecifiers); 6964 return SLCT_CheckedLiteral; 6965 } 6966 6967 return SLCT_NotALiteral; 6968 } 6969 case Stmt::BinaryOperatorClass: { 6970 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6971 6972 // A string literal + an int offset is still a string literal. 6973 if (BinOp->isAdditiveOp()) { 6974 Expr::EvalResult LResult, RResult; 6975 6976 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 6977 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6978 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 6979 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6980 6981 if (LIsInt != RIsInt) { 6982 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6983 6984 if (LIsInt) { 6985 if (BinOpKind == BO_Add) { 6986 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6987 E = BinOp->getRHS(); 6988 goto tryAgain; 6989 } 6990 } else { 6991 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6992 E = BinOp->getLHS(); 6993 goto tryAgain; 6994 } 6995 } 6996 } 6997 6998 return SLCT_NotALiteral; 6999 } 7000 case Stmt::UnaryOperatorClass: { 7001 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7002 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7003 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7004 Expr::EvalResult IndexResult; 7005 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7006 Expr::SE_NoSideEffects, 7007 S.isConstantEvaluated())) { 7008 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7009 /*RHS is int*/ true); 7010 E = ASE->getBase(); 7011 goto tryAgain; 7012 } 7013 } 7014 7015 return SLCT_NotALiteral; 7016 } 7017 7018 default: 7019 return SLCT_NotALiteral; 7020 } 7021 } 7022 7023 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7024 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7025 .Case("scanf", FST_Scanf) 7026 .Cases("printf", "printf0", FST_Printf) 7027 .Cases("NSString", "CFString", FST_NSString) 7028 .Case("strftime", FST_Strftime) 7029 .Case("strfmon", FST_Strfmon) 7030 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7031 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7032 .Case("os_trace", FST_OSLog) 7033 .Case("os_log", FST_OSLog) 7034 .Default(FST_Unknown); 7035 } 7036 7037 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7038 /// functions) for correct use of format strings. 7039 /// Returns true if a format string has been fully checked. 7040 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7041 ArrayRef<const Expr *> Args, 7042 bool IsCXXMember, 7043 VariadicCallType CallType, 7044 SourceLocation Loc, SourceRange Range, 7045 llvm::SmallBitVector &CheckedVarArgs) { 7046 FormatStringInfo FSI; 7047 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7048 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7049 FSI.FirstDataArg, GetFormatStringType(Format), 7050 CallType, Loc, Range, CheckedVarArgs); 7051 return false; 7052 } 7053 7054 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7055 bool HasVAListArg, unsigned format_idx, 7056 unsigned firstDataArg, FormatStringType Type, 7057 VariadicCallType CallType, 7058 SourceLocation Loc, SourceRange Range, 7059 llvm::SmallBitVector &CheckedVarArgs) { 7060 // CHECK: printf/scanf-like function is called with no format string. 7061 if (format_idx >= Args.size()) { 7062 Diag(Loc, diag::warn_missing_format_string) << Range; 7063 return false; 7064 } 7065 7066 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7067 7068 // CHECK: format string is not a string literal. 7069 // 7070 // Dynamically generated format strings are difficult to 7071 // automatically vet at compile time. Requiring that format strings 7072 // are string literals: (1) permits the checking of format strings by 7073 // the compiler and thereby (2) can practically remove the source of 7074 // many format string exploits. 7075 7076 // Format string can be either ObjC string (e.g. @"%d") or 7077 // C string (e.g. "%d") 7078 // ObjC string uses the same format specifiers as C string, so we can use 7079 // the same format string checking logic for both ObjC and C strings. 7080 UncoveredArgHandler UncoveredArg; 7081 StringLiteralCheckType CT = 7082 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7083 format_idx, firstDataArg, Type, CallType, 7084 /*IsFunctionCall*/ true, CheckedVarArgs, 7085 UncoveredArg, 7086 /*no string offset*/ llvm::APSInt(64, false) = 0); 7087 7088 // Generate a diagnostic where an uncovered argument is detected. 7089 if (UncoveredArg.hasUncoveredArg()) { 7090 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7091 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7092 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7093 } 7094 7095 if (CT != SLCT_NotALiteral) 7096 // Literal format string found, check done! 7097 return CT == SLCT_CheckedLiteral; 7098 7099 // Strftime is particular as it always uses a single 'time' argument, 7100 // so it is safe to pass a non-literal string. 7101 if (Type == FST_Strftime) 7102 return false; 7103 7104 // Do not emit diag when the string param is a macro expansion and the 7105 // format is either NSString or CFString. This is a hack to prevent 7106 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7107 // which are usually used in place of NS and CF string literals. 7108 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7109 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7110 return false; 7111 7112 // If there are no arguments specified, warn with -Wformat-security, otherwise 7113 // warn only with -Wformat-nonliteral. 7114 if (Args.size() == firstDataArg) { 7115 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7116 << OrigFormatExpr->getSourceRange(); 7117 switch (Type) { 7118 default: 7119 break; 7120 case FST_Kprintf: 7121 case FST_FreeBSDKPrintf: 7122 case FST_Printf: 7123 Diag(FormatLoc, diag::note_format_security_fixit) 7124 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7125 break; 7126 case FST_NSString: 7127 Diag(FormatLoc, diag::note_format_security_fixit) 7128 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7129 break; 7130 } 7131 } else { 7132 Diag(FormatLoc, diag::warn_format_nonliteral) 7133 << OrigFormatExpr->getSourceRange(); 7134 } 7135 return false; 7136 } 7137 7138 namespace { 7139 7140 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7141 protected: 7142 Sema &S; 7143 const FormatStringLiteral *FExpr; 7144 const Expr *OrigFormatExpr; 7145 const Sema::FormatStringType FSType; 7146 const unsigned FirstDataArg; 7147 const unsigned NumDataArgs; 7148 const char *Beg; // Start of format string. 7149 const bool HasVAListArg; 7150 ArrayRef<const Expr *> Args; 7151 unsigned FormatIdx; 7152 llvm::SmallBitVector CoveredArgs; 7153 bool usesPositionalArgs = false; 7154 bool atFirstArg = true; 7155 bool inFunctionCall; 7156 Sema::VariadicCallType CallType; 7157 llvm::SmallBitVector &CheckedVarArgs; 7158 UncoveredArgHandler &UncoveredArg; 7159 7160 public: 7161 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7162 const Expr *origFormatExpr, 7163 const Sema::FormatStringType type, unsigned firstDataArg, 7164 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7165 ArrayRef<const Expr *> Args, unsigned formatIdx, 7166 bool inFunctionCall, Sema::VariadicCallType callType, 7167 llvm::SmallBitVector &CheckedVarArgs, 7168 UncoveredArgHandler &UncoveredArg) 7169 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7170 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7171 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7172 inFunctionCall(inFunctionCall), CallType(callType), 7173 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7174 CoveredArgs.resize(numDataArgs); 7175 CoveredArgs.reset(); 7176 } 7177 7178 void DoneProcessing(); 7179 7180 void HandleIncompleteSpecifier(const char *startSpecifier, 7181 unsigned specifierLen) override; 7182 7183 void HandleInvalidLengthModifier( 7184 const analyze_format_string::FormatSpecifier &FS, 7185 const analyze_format_string::ConversionSpecifier &CS, 7186 const char *startSpecifier, unsigned specifierLen, 7187 unsigned DiagID); 7188 7189 void HandleNonStandardLengthModifier( 7190 const analyze_format_string::FormatSpecifier &FS, 7191 const char *startSpecifier, unsigned specifierLen); 7192 7193 void HandleNonStandardConversionSpecifier( 7194 const analyze_format_string::ConversionSpecifier &CS, 7195 const char *startSpecifier, unsigned specifierLen); 7196 7197 void HandlePosition(const char *startPos, unsigned posLen) override; 7198 7199 void HandleInvalidPosition(const char *startSpecifier, 7200 unsigned specifierLen, 7201 analyze_format_string::PositionContext p) override; 7202 7203 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7204 7205 void HandleNullChar(const char *nullCharacter) override; 7206 7207 template <typename Range> 7208 static void 7209 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7210 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7211 bool IsStringLocation, Range StringRange, 7212 ArrayRef<FixItHint> Fixit = None); 7213 7214 protected: 7215 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7216 const char *startSpec, 7217 unsigned specifierLen, 7218 const char *csStart, unsigned csLen); 7219 7220 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7221 const char *startSpec, 7222 unsigned specifierLen); 7223 7224 SourceRange getFormatStringRange(); 7225 CharSourceRange getSpecifierRange(const char *startSpecifier, 7226 unsigned specifierLen); 7227 SourceLocation getLocationOfByte(const char *x); 7228 7229 const Expr *getDataArg(unsigned i) const; 7230 7231 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7232 const analyze_format_string::ConversionSpecifier &CS, 7233 const char *startSpecifier, unsigned specifierLen, 7234 unsigned argIndex); 7235 7236 template <typename Range> 7237 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7238 bool IsStringLocation, Range StringRange, 7239 ArrayRef<FixItHint> Fixit = None); 7240 }; 7241 7242 } // namespace 7243 7244 SourceRange CheckFormatHandler::getFormatStringRange() { 7245 return OrigFormatExpr->getSourceRange(); 7246 } 7247 7248 CharSourceRange CheckFormatHandler:: 7249 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7250 SourceLocation Start = getLocationOfByte(startSpecifier); 7251 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7252 7253 // Advance the end SourceLocation by one due to half-open ranges. 7254 End = End.getLocWithOffset(1); 7255 7256 return CharSourceRange::getCharRange(Start, End); 7257 } 7258 7259 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7260 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7261 S.getLangOpts(), S.Context.getTargetInfo()); 7262 } 7263 7264 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7265 unsigned specifierLen){ 7266 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7267 getLocationOfByte(startSpecifier), 7268 /*IsStringLocation*/true, 7269 getSpecifierRange(startSpecifier, specifierLen)); 7270 } 7271 7272 void CheckFormatHandler::HandleInvalidLengthModifier( 7273 const analyze_format_string::FormatSpecifier &FS, 7274 const analyze_format_string::ConversionSpecifier &CS, 7275 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7276 using namespace analyze_format_string; 7277 7278 const LengthModifier &LM = FS.getLengthModifier(); 7279 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7280 7281 // See if we know how to fix this length modifier. 7282 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7283 if (FixedLM) { 7284 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7285 getLocationOfByte(LM.getStart()), 7286 /*IsStringLocation*/true, 7287 getSpecifierRange(startSpecifier, specifierLen)); 7288 7289 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7290 << FixedLM->toString() 7291 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7292 7293 } else { 7294 FixItHint Hint; 7295 if (DiagID == diag::warn_format_nonsensical_length) 7296 Hint = FixItHint::CreateRemoval(LMRange); 7297 7298 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7299 getLocationOfByte(LM.getStart()), 7300 /*IsStringLocation*/true, 7301 getSpecifierRange(startSpecifier, specifierLen), 7302 Hint); 7303 } 7304 } 7305 7306 void CheckFormatHandler::HandleNonStandardLengthModifier( 7307 const analyze_format_string::FormatSpecifier &FS, 7308 const char *startSpecifier, unsigned specifierLen) { 7309 using namespace analyze_format_string; 7310 7311 const LengthModifier &LM = FS.getLengthModifier(); 7312 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7313 7314 // See if we know how to fix this length modifier. 7315 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7316 if (FixedLM) { 7317 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7318 << LM.toString() << 0, 7319 getLocationOfByte(LM.getStart()), 7320 /*IsStringLocation*/true, 7321 getSpecifierRange(startSpecifier, specifierLen)); 7322 7323 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7324 << FixedLM->toString() 7325 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7326 7327 } else { 7328 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7329 << LM.toString() << 0, 7330 getLocationOfByte(LM.getStart()), 7331 /*IsStringLocation*/true, 7332 getSpecifierRange(startSpecifier, specifierLen)); 7333 } 7334 } 7335 7336 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7337 const analyze_format_string::ConversionSpecifier &CS, 7338 const char *startSpecifier, unsigned specifierLen) { 7339 using namespace analyze_format_string; 7340 7341 // See if we know how to fix this conversion specifier. 7342 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7343 if (FixedCS) { 7344 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7345 << CS.toString() << /*conversion specifier*/1, 7346 getLocationOfByte(CS.getStart()), 7347 /*IsStringLocation*/true, 7348 getSpecifierRange(startSpecifier, specifierLen)); 7349 7350 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7351 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7352 << FixedCS->toString() 7353 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7354 } else { 7355 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7356 << CS.toString() << /*conversion specifier*/1, 7357 getLocationOfByte(CS.getStart()), 7358 /*IsStringLocation*/true, 7359 getSpecifierRange(startSpecifier, specifierLen)); 7360 } 7361 } 7362 7363 void CheckFormatHandler::HandlePosition(const char *startPos, 7364 unsigned posLen) { 7365 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7366 getLocationOfByte(startPos), 7367 /*IsStringLocation*/true, 7368 getSpecifierRange(startPos, posLen)); 7369 } 7370 7371 void 7372 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7373 analyze_format_string::PositionContext p) { 7374 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7375 << (unsigned) p, 7376 getLocationOfByte(startPos), /*IsStringLocation*/true, 7377 getSpecifierRange(startPos, posLen)); 7378 } 7379 7380 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7381 unsigned posLen) { 7382 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7383 getLocationOfByte(startPos), 7384 /*IsStringLocation*/true, 7385 getSpecifierRange(startPos, posLen)); 7386 } 7387 7388 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7389 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7390 // The presence of a null character is likely an error. 7391 EmitFormatDiagnostic( 7392 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7393 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7394 getFormatStringRange()); 7395 } 7396 } 7397 7398 // Note that this may return NULL if there was an error parsing or building 7399 // one of the argument expressions. 7400 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7401 return Args[FirstDataArg + i]; 7402 } 7403 7404 void CheckFormatHandler::DoneProcessing() { 7405 // Does the number of data arguments exceed the number of 7406 // format conversions in the format string? 7407 if (!HasVAListArg) { 7408 // Find any arguments that weren't covered. 7409 CoveredArgs.flip(); 7410 signed notCoveredArg = CoveredArgs.find_first(); 7411 if (notCoveredArg >= 0) { 7412 assert((unsigned)notCoveredArg < NumDataArgs); 7413 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7414 } else { 7415 UncoveredArg.setAllCovered(); 7416 } 7417 } 7418 } 7419 7420 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7421 const Expr *ArgExpr) { 7422 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7423 "Invalid state"); 7424 7425 if (!ArgExpr) 7426 return; 7427 7428 SourceLocation Loc = ArgExpr->getBeginLoc(); 7429 7430 if (S.getSourceManager().isInSystemMacro(Loc)) 7431 return; 7432 7433 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7434 for (auto E : DiagnosticExprs) 7435 PDiag << E->getSourceRange(); 7436 7437 CheckFormatHandler::EmitFormatDiagnostic( 7438 S, IsFunctionCall, DiagnosticExprs[0], 7439 PDiag, Loc, /*IsStringLocation*/false, 7440 DiagnosticExprs[0]->getSourceRange()); 7441 } 7442 7443 bool 7444 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7445 SourceLocation Loc, 7446 const char *startSpec, 7447 unsigned specifierLen, 7448 const char *csStart, 7449 unsigned csLen) { 7450 bool keepGoing = true; 7451 if (argIndex < NumDataArgs) { 7452 // Consider the argument coverered, even though the specifier doesn't 7453 // make sense. 7454 CoveredArgs.set(argIndex); 7455 } 7456 else { 7457 // If argIndex exceeds the number of data arguments we 7458 // don't issue a warning because that is just a cascade of warnings (and 7459 // they may have intended '%%' anyway). We don't want to continue processing 7460 // the format string after this point, however, as we will like just get 7461 // gibberish when trying to match arguments. 7462 keepGoing = false; 7463 } 7464 7465 StringRef Specifier(csStart, csLen); 7466 7467 // If the specifier in non-printable, it could be the first byte of a UTF-8 7468 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7469 // hex value. 7470 std::string CodePointStr; 7471 if (!llvm::sys::locale::isPrint(*csStart)) { 7472 llvm::UTF32 CodePoint; 7473 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7474 const llvm::UTF8 *E = 7475 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7476 llvm::ConversionResult Result = 7477 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7478 7479 if (Result != llvm::conversionOK) { 7480 unsigned char FirstChar = *csStart; 7481 CodePoint = (llvm::UTF32)FirstChar; 7482 } 7483 7484 llvm::raw_string_ostream OS(CodePointStr); 7485 if (CodePoint < 256) 7486 OS << "\\x" << llvm::format("%02x", CodePoint); 7487 else if (CodePoint <= 0xFFFF) 7488 OS << "\\u" << llvm::format("%04x", CodePoint); 7489 else 7490 OS << "\\U" << llvm::format("%08x", CodePoint); 7491 OS.flush(); 7492 Specifier = CodePointStr; 7493 } 7494 7495 EmitFormatDiagnostic( 7496 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7497 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7498 7499 return keepGoing; 7500 } 7501 7502 void 7503 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7504 const char *startSpec, 7505 unsigned specifierLen) { 7506 EmitFormatDiagnostic( 7507 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7508 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7509 } 7510 7511 bool 7512 CheckFormatHandler::CheckNumArgs( 7513 const analyze_format_string::FormatSpecifier &FS, 7514 const analyze_format_string::ConversionSpecifier &CS, 7515 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7516 7517 if (argIndex >= NumDataArgs) { 7518 PartialDiagnostic PDiag = FS.usesPositionalArg() 7519 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7520 << (argIndex+1) << NumDataArgs) 7521 : S.PDiag(diag::warn_printf_insufficient_data_args); 7522 EmitFormatDiagnostic( 7523 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7524 getSpecifierRange(startSpecifier, specifierLen)); 7525 7526 // Since more arguments than conversion tokens are given, by extension 7527 // all arguments are covered, so mark this as so. 7528 UncoveredArg.setAllCovered(); 7529 return false; 7530 } 7531 return true; 7532 } 7533 7534 template<typename Range> 7535 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7536 SourceLocation Loc, 7537 bool IsStringLocation, 7538 Range StringRange, 7539 ArrayRef<FixItHint> FixIt) { 7540 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7541 Loc, IsStringLocation, StringRange, FixIt); 7542 } 7543 7544 /// If the format string is not within the function call, emit a note 7545 /// so that the function call and string are in diagnostic messages. 7546 /// 7547 /// \param InFunctionCall if true, the format string is within the function 7548 /// call and only one diagnostic message will be produced. Otherwise, an 7549 /// extra note will be emitted pointing to location of the format string. 7550 /// 7551 /// \param ArgumentExpr the expression that is passed as the format string 7552 /// argument in the function call. Used for getting locations when two 7553 /// diagnostics are emitted. 7554 /// 7555 /// \param PDiag the callee should already have provided any strings for the 7556 /// diagnostic message. This function only adds locations and fixits 7557 /// to diagnostics. 7558 /// 7559 /// \param Loc primary location for diagnostic. If two diagnostics are 7560 /// required, one will be at Loc and a new SourceLocation will be created for 7561 /// the other one. 7562 /// 7563 /// \param IsStringLocation if true, Loc points to the format string should be 7564 /// used for the note. Otherwise, Loc points to the argument list and will 7565 /// be used with PDiag. 7566 /// 7567 /// \param StringRange some or all of the string to highlight. This is 7568 /// templated so it can accept either a CharSourceRange or a SourceRange. 7569 /// 7570 /// \param FixIt optional fix it hint for the format string. 7571 template <typename Range> 7572 void CheckFormatHandler::EmitFormatDiagnostic( 7573 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7574 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7575 Range StringRange, ArrayRef<FixItHint> FixIt) { 7576 if (InFunctionCall) { 7577 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7578 D << StringRange; 7579 D << FixIt; 7580 } else { 7581 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7582 << ArgumentExpr->getSourceRange(); 7583 7584 const Sema::SemaDiagnosticBuilder &Note = 7585 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7586 diag::note_format_string_defined); 7587 7588 Note << StringRange; 7589 Note << FixIt; 7590 } 7591 } 7592 7593 //===--- CHECK: Printf format string checking ------------------------------===// 7594 7595 namespace { 7596 7597 class CheckPrintfHandler : public CheckFormatHandler { 7598 public: 7599 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7600 const Expr *origFormatExpr, 7601 const Sema::FormatStringType type, unsigned firstDataArg, 7602 unsigned numDataArgs, bool isObjC, const char *beg, 7603 bool hasVAListArg, ArrayRef<const Expr *> Args, 7604 unsigned formatIdx, bool inFunctionCall, 7605 Sema::VariadicCallType CallType, 7606 llvm::SmallBitVector &CheckedVarArgs, 7607 UncoveredArgHandler &UncoveredArg) 7608 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7609 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7610 inFunctionCall, CallType, CheckedVarArgs, 7611 UncoveredArg) {} 7612 7613 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7614 7615 /// Returns true if '%@' specifiers are allowed in the format string. 7616 bool allowsObjCArg() const { 7617 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7618 FSType == Sema::FST_OSTrace; 7619 } 7620 7621 bool HandleInvalidPrintfConversionSpecifier( 7622 const analyze_printf::PrintfSpecifier &FS, 7623 const char *startSpecifier, 7624 unsigned specifierLen) override; 7625 7626 void handleInvalidMaskType(StringRef MaskType) override; 7627 7628 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7629 const char *startSpecifier, 7630 unsigned specifierLen) override; 7631 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7632 const char *StartSpecifier, 7633 unsigned SpecifierLen, 7634 const Expr *E); 7635 7636 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7637 const char *startSpecifier, unsigned specifierLen); 7638 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7639 const analyze_printf::OptionalAmount &Amt, 7640 unsigned type, 7641 const char *startSpecifier, unsigned specifierLen); 7642 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7643 const analyze_printf::OptionalFlag &flag, 7644 const char *startSpecifier, unsigned specifierLen); 7645 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7646 const analyze_printf::OptionalFlag &ignoredFlag, 7647 const analyze_printf::OptionalFlag &flag, 7648 const char *startSpecifier, unsigned specifierLen); 7649 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7650 const Expr *E); 7651 7652 void HandleEmptyObjCModifierFlag(const char *startFlag, 7653 unsigned flagLen) override; 7654 7655 void HandleInvalidObjCModifierFlag(const char *startFlag, 7656 unsigned flagLen) override; 7657 7658 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7659 const char *flagsEnd, 7660 const char *conversionPosition) 7661 override; 7662 }; 7663 7664 } // namespace 7665 7666 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7667 const analyze_printf::PrintfSpecifier &FS, 7668 const char *startSpecifier, 7669 unsigned specifierLen) { 7670 const analyze_printf::PrintfConversionSpecifier &CS = 7671 FS.getConversionSpecifier(); 7672 7673 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7674 getLocationOfByte(CS.getStart()), 7675 startSpecifier, specifierLen, 7676 CS.getStart(), CS.getLength()); 7677 } 7678 7679 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7680 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7681 } 7682 7683 bool CheckPrintfHandler::HandleAmount( 7684 const analyze_format_string::OptionalAmount &Amt, 7685 unsigned k, const char *startSpecifier, 7686 unsigned specifierLen) { 7687 if (Amt.hasDataArgument()) { 7688 if (!HasVAListArg) { 7689 unsigned argIndex = Amt.getArgIndex(); 7690 if (argIndex >= NumDataArgs) { 7691 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7692 << k, 7693 getLocationOfByte(Amt.getStart()), 7694 /*IsStringLocation*/true, 7695 getSpecifierRange(startSpecifier, specifierLen)); 7696 // Don't do any more checking. We will just emit 7697 // spurious errors. 7698 return false; 7699 } 7700 7701 // Type check the data argument. It should be an 'int'. 7702 // Although not in conformance with C99, we also allow the argument to be 7703 // an 'unsigned int' as that is a reasonably safe case. GCC also 7704 // doesn't emit a warning for that case. 7705 CoveredArgs.set(argIndex); 7706 const Expr *Arg = getDataArg(argIndex); 7707 if (!Arg) 7708 return false; 7709 7710 QualType T = Arg->getType(); 7711 7712 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7713 assert(AT.isValid()); 7714 7715 if (!AT.matchesType(S.Context, T)) { 7716 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7717 << k << AT.getRepresentativeTypeName(S.Context) 7718 << T << Arg->getSourceRange(), 7719 getLocationOfByte(Amt.getStart()), 7720 /*IsStringLocation*/true, 7721 getSpecifierRange(startSpecifier, specifierLen)); 7722 // Don't do any more checking. We will just emit 7723 // spurious errors. 7724 return false; 7725 } 7726 } 7727 } 7728 return true; 7729 } 7730 7731 void CheckPrintfHandler::HandleInvalidAmount( 7732 const analyze_printf::PrintfSpecifier &FS, 7733 const analyze_printf::OptionalAmount &Amt, 7734 unsigned type, 7735 const char *startSpecifier, 7736 unsigned specifierLen) { 7737 const analyze_printf::PrintfConversionSpecifier &CS = 7738 FS.getConversionSpecifier(); 7739 7740 FixItHint fixit = 7741 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7742 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7743 Amt.getConstantLength())) 7744 : FixItHint(); 7745 7746 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7747 << type << CS.toString(), 7748 getLocationOfByte(Amt.getStart()), 7749 /*IsStringLocation*/true, 7750 getSpecifierRange(startSpecifier, specifierLen), 7751 fixit); 7752 } 7753 7754 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7755 const analyze_printf::OptionalFlag &flag, 7756 const char *startSpecifier, 7757 unsigned specifierLen) { 7758 // Warn about pointless flag with a fixit removal. 7759 const analyze_printf::PrintfConversionSpecifier &CS = 7760 FS.getConversionSpecifier(); 7761 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7762 << flag.toString() << CS.toString(), 7763 getLocationOfByte(flag.getPosition()), 7764 /*IsStringLocation*/true, 7765 getSpecifierRange(startSpecifier, specifierLen), 7766 FixItHint::CreateRemoval( 7767 getSpecifierRange(flag.getPosition(), 1))); 7768 } 7769 7770 void CheckPrintfHandler::HandleIgnoredFlag( 7771 const analyze_printf::PrintfSpecifier &FS, 7772 const analyze_printf::OptionalFlag &ignoredFlag, 7773 const analyze_printf::OptionalFlag &flag, 7774 const char *startSpecifier, 7775 unsigned specifierLen) { 7776 // Warn about ignored flag with a fixit removal. 7777 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7778 << ignoredFlag.toString() << flag.toString(), 7779 getLocationOfByte(ignoredFlag.getPosition()), 7780 /*IsStringLocation*/true, 7781 getSpecifierRange(startSpecifier, specifierLen), 7782 FixItHint::CreateRemoval( 7783 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7784 } 7785 7786 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7787 unsigned flagLen) { 7788 // Warn about an empty flag. 7789 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7790 getLocationOfByte(startFlag), 7791 /*IsStringLocation*/true, 7792 getSpecifierRange(startFlag, flagLen)); 7793 } 7794 7795 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7796 unsigned flagLen) { 7797 // Warn about an invalid flag. 7798 auto Range = getSpecifierRange(startFlag, flagLen); 7799 StringRef flag(startFlag, flagLen); 7800 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7801 getLocationOfByte(startFlag), 7802 /*IsStringLocation*/true, 7803 Range, FixItHint::CreateRemoval(Range)); 7804 } 7805 7806 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7807 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7808 // Warn about using '[...]' without a '@' conversion. 7809 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7810 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7811 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7812 getLocationOfByte(conversionPosition), 7813 /*IsStringLocation*/true, 7814 Range, FixItHint::CreateRemoval(Range)); 7815 } 7816 7817 // Determines if the specified is a C++ class or struct containing 7818 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7819 // "c_str()"). 7820 template<typename MemberKind> 7821 static llvm::SmallPtrSet<MemberKind*, 1> 7822 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7823 const RecordType *RT = Ty->getAs<RecordType>(); 7824 llvm::SmallPtrSet<MemberKind*, 1> Results; 7825 7826 if (!RT) 7827 return Results; 7828 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7829 if (!RD || !RD->getDefinition()) 7830 return Results; 7831 7832 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7833 Sema::LookupMemberName); 7834 R.suppressDiagnostics(); 7835 7836 // We just need to include all members of the right kind turned up by the 7837 // filter, at this point. 7838 if (S.LookupQualifiedName(R, RT->getDecl())) 7839 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7840 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7841 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7842 Results.insert(FK); 7843 } 7844 return Results; 7845 } 7846 7847 /// Check if we could call '.c_str()' on an object. 7848 /// 7849 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7850 /// allow the call, or if it would be ambiguous). 7851 bool Sema::hasCStrMethod(const Expr *E) { 7852 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7853 7854 MethodSet Results = 7855 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7856 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7857 MI != ME; ++MI) 7858 if ((*MI)->getMinRequiredArguments() == 0) 7859 return true; 7860 return false; 7861 } 7862 7863 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7864 // better diagnostic if so. AT is assumed to be valid. 7865 // Returns true when a c_str() conversion method is found. 7866 bool CheckPrintfHandler::checkForCStrMembers( 7867 const analyze_printf::ArgType &AT, const Expr *E) { 7868 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7869 7870 MethodSet Results = 7871 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7872 7873 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7874 MI != ME; ++MI) { 7875 const CXXMethodDecl *Method = *MI; 7876 if (Method->getMinRequiredArguments() == 0 && 7877 AT.matchesType(S.Context, Method->getReturnType())) { 7878 // FIXME: Suggest parens if the expression needs them. 7879 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7880 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7881 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7882 return true; 7883 } 7884 } 7885 7886 return false; 7887 } 7888 7889 bool 7890 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7891 &FS, 7892 const char *startSpecifier, 7893 unsigned specifierLen) { 7894 using namespace analyze_format_string; 7895 using namespace analyze_printf; 7896 7897 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7898 7899 if (FS.consumesDataArgument()) { 7900 if (atFirstArg) { 7901 atFirstArg = false; 7902 usesPositionalArgs = FS.usesPositionalArg(); 7903 } 7904 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7905 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7906 startSpecifier, specifierLen); 7907 return false; 7908 } 7909 } 7910 7911 // First check if the field width, precision, and conversion specifier 7912 // have matching data arguments. 7913 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7914 startSpecifier, specifierLen)) { 7915 return false; 7916 } 7917 7918 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7919 startSpecifier, specifierLen)) { 7920 return false; 7921 } 7922 7923 if (!CS.consumesDataArgument()) { 7924 // FIXME: Technically specifying a precision or field width here 7925 // makes no sense. Worth issuing a warning at some point. 7926 return true; 7927 } 7928 7929 // Consume the argument. 7930 unsigned argIndex = FS.getArgIndex(); 7931 if (argIndex < NumDataArgs) { 7932 // The check to see if the argIndex is valid will come later. 7933 // We set the bit here because we may exit early from this 7934 // function if we encounter some other error. 7935 CoveredArgs.set(argIndex); 7936 } 7937 7938 // FreeBSD kernel extensions. 7939 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7940 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7941 // We need at least two arguments. 7942 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7943 return false; 7944 7945 // Claim the second argument. 7946 CoveredArgs.set(argIndex + 1); 7947 7948 // Type check the first argument (int for %b, pointer for %D) 7949 const Expr *Ex = getDataArg(argIndex); 7950 const analyze_printf::ArgType &AT = 7951 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7952 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7953 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7954 EmitFormatDiagnostic( 7955 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7956 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7957 << false << Ex->getSourceRange(), 7958 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7959 getSpecifierRange(startSpecifier, specifierLen)); 7960 7961 // Type check the second argument (char * for both %b and %D) 7962 Ex = getDataArg(argIndex + 1); 7963 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7964 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7965 EmitFormatDiagnostic( 7966 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7967 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7968 << false << Ex->getSourceRange(), 7969 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7970 getSpecifierRange(startSpecifier, specifierLen)); 7971 7972 return true; 7973 } 7974 7975 // Check for using an Objective-C specific conversion specifier 7976 // in a non-ObjC literal. 7977 if (!allowsObjCArg() && CS.isObjCArg()) { 7978 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7979 specifierLen); 7980 } 7981 7982 // %P can only be used with os_log. 7983 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7984 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7985 specifierLen); 7986 } 7987 7988 // %n is not allowed with os_log. 7989 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7990 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7991 getLocationOfByte(CS.getStart()), 7992 /*IsStringLocation*/ false, 7993 getSpecifierRange(startSpecifier, specifierLen)); 7994 7995 return true; 7996 } 7997 7998 // Only scalars are allowed for os_trace. 7999 if (FSType == Sema::FST_OSTrace && 8000 (CS.getKind() == ConversionSpecifier::PArg || 8001 CS.getKind() == ConversionSpecifier::sArg || 8002 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8003 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8004 specifierLen); 8005 } 8006 8007 // Check for use of public/private annotation outside of os_log(). 8008 if (FSType != Sema::FST_OSLog) { 8009 if (FS.isPublic().isSet()) { 8010 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8011 << "public", 8012 getLocationOfByte(FS.isPublic().getPosition()), 8013 /*IsStringLocation*/ false, 8014 getSpecifierRange(startSpecifier, specifierLen)); 8015 } 8016 if (FS.isPrivate().isSet()) { 8017 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8018 << "private", 8019 getLocationOfByte(FS.isPrivate().getPosition()), 8020 /*IsStringLocation*/ false, 8021 getSpecifierRange(startSpecifier, specifierLen)); 8022 } 8023 } 8024 8025 // Check for invalid use of field width 8026 if (!FS.hasValidFieldWidth()) { 8027 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8028 startSpecifier, specifierLen); 8029 } 8030 8031 // Check for invalid use of precision 8032 if (!FS.hasValidPrecision()) { 8033 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8034 startSpecifier, specifierLen); 8035 } 8036 8037 // Precision is mandatory for %P specifier. 8038 if (CS.getKind() == ConversionSpecifier::PArg && 8039 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8040 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8041 getLocationOfByte(startSpecifier), 8042 /*IsStringLocation*/ false, 8043 getSpecifierRange(startSpecifier, specifierLen)); 8044 } 8045 8046 // Check each flag does not conflict with any other component. 8047 if (!FS.hasValidThousandsGroupingPrefix()) 8048 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8049 if (!FS.hasValidLeadingZeros()) 8050 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8051 if (!FS.hasValidPlusPrefix()) 8052 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8053 if (!FS.hasValidSpacePrefix()) 8054 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8055 if (!FS.hasValidAlternativeForm()) 8056 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8057 if (!FS.hasValidLeftJustified()) 8058 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8059 8060 // Check that flags are not ignored by another flag 8061 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8062 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8063 startSpecifier, specifierLen); 8064 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8065 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8066 startSpecifier, specifierLen); 8067 8068 // Check the length modifier is valid with the given conversion specifier. 8069 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8070 S.getLangOpts())) 8071 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8072 diag::warn_format_nonsensical_length); 8073 else if (!FS.hasStandardLengthModifier()) 8074 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8075 else if (!FS.hasStandardLengthConversionCombination()) 8076 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8077 diag::warn_format_non_standard_conversion_spec); 8078 8079 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8080 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8081 8082 // The remaining checks depend on the data arguments. 8083 if (HasVAListArg) 8084 return true; 8085 8086 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8087 return false; 8088 8089 const Expr *Arg = getDataArg(argIndex); 8090 if (!Arg) 8091 return true; 8092 8093 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8094 } 8095 8096 static bool requiresParensToAddCast(const Expr *E) { 8097 // FIXME: We should have a general way to reason about operator 8098 // precedence and whether parens are actually needed here. 8099 // Take care of a few common cases where they aren't. 8100 const Expr *Inside = E->IgnoreImpCasts(); 8101 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8102 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8103 8104 switch (Inside->getStmtClass()) { 8105 case Stmt::ArraySubscriptExprClass: 8106 case Stmt::CallExprClass: 8107 case Stmt::CharacterLiteralClass: 8108 case Stmt::CXXBoolLiteralExprClass: 8109 case Stmt::DeclRefExprClass: 8110 case Stmt::FloatingLiteralClass: 8111 case Stmt::IntegerLiteralClass: 8112 case Stmt::MemberExprClass: 8113 case Stmt::ObjCArrayLiteralClass: 8114 case Stmt::ObjCBoolLiteralExprClass: 8115 case Stmt::ObjCBoxedExprClass: 8116 case Stmt::ObjCDictionaryLiteralClass: 8117 case Stmt::ObjCEncodeExprClass: 8118 case Stmt::ObjCIvarRefExprClass: 8119 case Stmt::ObjCMessageExprClass: 8120 case Stmt::ObjCPropertyRefExprClass: 8121 case Stmt::ObjCStringLiteralClass: 8122 case Stmt::ObjCSubscriptRefExprClass: 8123 case Stmt::ParenExprClass: 8124 case Stmt::StringLiteralClass: 8125 case Stmt::UnaryOperatorClass: 8126 return false; 8127 default: 8128 return true; 8129 } 8130 } 8131 8132 static std::pair<QualType, StringRef> 8133 shouldNotPrintDirectly(const ASTContext &Context, 8134 QualType IntendedTy, 8135 const Expr *E) { 8136 // Use a 'while' to peel off layers of typedefs. 8137 QualType TyTy = IntendedTy; 8138 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8139 StringRef Name = UserTy->getDecl()->getName(); 8140 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8141 .Case("CFIndex", Context.getNSIntegerType()) 8142 .Case("NSInteger", Context.getNSIntegerType()) 8143 .Case("NSUInteger", Context.getNSUIntegerType()) 8144 .Case("SInt32", Context.IntTy) 8145 .Case("UInt32", Context.UnsignedIntTy) 8146 .Default(QualType()); 8147 8148 if (!CastTy.isNull()) 8149 return std::make_pair(CastTy, Name); 8150 8151 TyTy = UserTy->desugar(); 8152 } 8153 8154 // Strip parens if necessary. 8155 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8156 return shouldNotPrintDirectly(Context, 8157 PE->getSubExpr()->getType(), 8158 PE->getSubExpr()); 8159 8160 // If this is a conditional expression, then its result type is constructed 8161 // via usual arithmetic conversions and thus there might be no necessary 8162 // typedef sugar there. Recurse to operands to check for NSInteger & 8163 // Co. usage condition. 8164 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8165 QualType TrueTy, FalseTy; 8166 StringRef TrueName, FalseName; 8167 8168 std::tie(TrueTy, TrueName) = 8169 shouldNotPrintDirectly(Context, 8170 CO->getTrueExpr()->getType(), 8171 CO->getTrueExpr()); 8172 std::tie(FalseTy, FalseName) = 8173 shouldNotPrintDirectly(Context, 8174 CO->getFalseExpr()->getType(), 8175 CO->getFalseExpr()); 8176 8177 if (TrueTy == FalseTy) 8178 return std::make_pair(TrueTy, TrueName); 8179 else if (TrueTy.isNull()) 8180 return std::make_pair(FalseTy, FalseName); 8181 else if (FalseTy.isNull()) 8182 return std::make_pair(TrueTy, TrueName); 8183 } 8184 8185 return std::make_pair(QualType(), StringRef()); 8186 } 8187 8188 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8189 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8190 /// type do not count. 8191 static bool 8192 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8193 QualType From = ICE->getSubExpr()->getType(); 8194 QualType To = ICE->getType(); 8195 // It's an integer promotion if the destination type is the promoted 8196 // source type. 8197 if (ICE->getCastKind() == CK_IntegralCast && 8198 From->isPromotableIntegerType() && 8199 S.Context.getPromotedIntegerType(From) == To) 8200 return true; 8201 // Look through vector types, since we do default argument promotion for 8202 // those in OpenCL. 8203 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8204 From = VecTy->getElementType(); 8205 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8206 To = VecTy->getElementType(); 8207 // It's a floating promotion if the source type is a lower rank. 8208 return ICE->getCastKind() == CK_FloatingCast && 8209 S.Context.getFloatingTypeOrder(From, To) < 0; 8210 } 8211 8212 bool 8213 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8214 const char *StartSpecifier, 8215 unsigned SpecifierLen, 8216 const Expr *E) { 8217 using namespace analyze_format_string; 8218 using namespace analyze_printf; 8219 8220 // Now type check the data expression that matches the 8221 // format specifier. 8222 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8223 if (!AT.isValid()) 8224 return true; 8225 8226 QualType ExprTy = E->getType(); 8227 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8228 ExprTy = TET->getUnderlyingExpr()->getType(); 8229 } 8230 8231 // Diagnose attempts to print a boolean value as a character. Unlike other 8232 // -Wformat diagnostics, this is fine from a type perspective, but it still 8233 // doesn't make sense. 8234 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8235 E->isKnownToHaveBooleanValue()) { 8236 const CharSourceRange &CSR = 8237 getSpecifierRange(StartSpecifier, SpecifierLen); 8238 SmallString<4> FSString; 8239 llvm::raw_svector_ostream os(FSString); 8240 FS.toString(os); 8241 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8242 << FSString, 8243 E->getExprLoc(), false, CSR); 8244 return true; 8245 } 8246 8247 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8248 if (Match == analyze_printf::ArgType::Match) 8249 return true; 8250 8251 // Look through argument promotions for our error message's reported type. 8252 // This includes the integral and floating promotions, but excludes array 8253 // and function pointer decay (seeing that an argument intended to be a 8254 // string has type 'char [6]' is probably more confusing than 'char *') and 8255 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8256 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8257 if (isArithmeticArgumentPromotion(S, ICE)) { 8258 E = ICE->getSubExpr(); 8259 ExprTy = E->getType(); 8260 8261 // Check if we didn't match because of an implicit cast from a 'char' 8262 // or 'short' to an 'int'. This is done because printf is a varargs 8263 // function. 8264 if (ICE->getType() == S.Context.IntTy || 8265 ICE->getType() == S.Context.UnsignedIntTy) { 8266 // All further checking is done on the subexpression 8267 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8268 AT.matchesType(S.Context, ExprTy); 8269 if (ImplicitMatch == analyze_printf::ArgType::Match) 8270 return true; 8271 if (ImplicitMatch == ArgType::NoMatchPedantic || 8272 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8273 Match = ImplicitMatch; 8274 } 8275 } 8276 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8277 // Special case for 'a', which has type 'int' in C. 8278 // Note, however, that we do /not/ want to treat multibyte constants like 8279 // 'MooV' as characters! This form is deprecated but still exists. 8280 if (ExprTy == S.Context.IntTy) 8281 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8282 ExprTy = S.Context.CharTy; 8283 } 8284 8285 // Look through enums to their underlying type. 8286 bool IsEnum = false; 8287 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8288 ExprTy = EnumTy->getDecl()->getIntegerType(); 8289 IsEnum = true; 8290 } 8291 8292 // %C in an Objective-C context prints a unichar, not a wchar_t. 8293 // If the argument is an integer of some kind, believe the %C and suggest 8294 // a cast instead of changing the conversion specifier. 8295 QualType IntendedTy = ExprTy; 8296 if (isObjCContext() && 8297 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8298 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8299 !ExprTy->isCharType()) { 8300 // 'unichar' is defined as a typedef of unsigned short, but we should 8301 // prefer using the typedef if it is visible. 8302 IntendedTy = S.Context.UnsignedShortTy; 8303 8304 // While we are here, check if the value is an IntegerLiteral that happens 8305 // to be within the valid range. 8306 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8307 const llvm::APInt &V = IL->getValue(); 8308 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8309 return true; 8310 } 8311 8312 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8313 Sema::LookupOrdinaryName); 8314 if (S.LookupName(Result, S.getCurScope())) { 8315 NamedDecl *ND = Result.getFoundDecl(); 8316 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8317 if (TD->getUnderlyingType() == IntendedTy) 8318 IntendedTy = S.Context.getTypedefType(TD); 8319 } 8320 } 8321 } 8322 8323 // Special-case some of Darwin's platform-independence types by suggesting 8324 // casts to primitive types that are known to be large enough. 8325 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8326 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8327 QualType CastTy; 8328 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8329 if (!CastTy.isNull()) { 8330 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8331 // (long in ASTContext). Only complain to pedants. 8332 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8333 (AT.isSizeT() || AT.isPtrdiffT()) && 8334 AT.matchesType(S.Context, CastTy)) 8335 Match = ArgType::NoMatchPedantic; 8336 IntendedTy = CastTy; 8337 ShouldNotPrintDirectly = true; 8338 } 8339 } 8340 8341 // We may be able to offer a FixItHint if it is a supported type. 8342 PrintfSpecifier fixedFS = FS; 8343 bool Success = 8344 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8345 8346 if (Success) { 8347 // Get the fix string from the fixed format specifier 8348 SmallString<16> buf; 8349 llvm::raw_svector_ostream os(buf); 8350 fixedFS.toString(os); 8351 8352 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8353 8354 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8355 unsigned Diag; 8356 switch (Match) { 8357 case ArgType::Match: llvm_unreachable("expected non-matching"); 8358 case ArgType::NoMatchPedantic: 8359 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8360 break; 8361 case ArgType::NoMatchTypeConfusion: 8362 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8363 break; 8364 case ArgType::NoMatch: 8365 Diag = diag::warn_format_conversion_argument_type_mismatch; 8366 break; 8367 } 8368 8369 // In this case, the specifier is wrong and should be changed to match 8370 // the argument. 8371 EmitFormatDiagnostic(S.PDiag(Diag) 8372 << AT.getRepresentativeTypeName(S.Context) 8373 << IntendedTy << IsEnum << E->getSourceRange(), 8374 E->getBeginLoc(), 8375 /*IsStringLocation*/ false, SpecRange, 8376 FixItHint::CreateReplacement(SpecRange, os.str())); 8377 } else { 8378 // The canonical type for formatting this value is different from the 8379 // actual type of the expression. (This occurs, for example, with Darwin's 8380 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8381 // should be printed as 'long' for 64-bit compatibility.) 8382 // Rather than emitting a normal format/argument mismatch, we want to 8383 // add a cast to the recommended type (and correct the format string 8384 // if necessary). 8385 SmallString<16> CastBuf; 8386 llvm::raw_svector_ostream CastFix(CastBuf); 8387 CastFix << "("; 8388 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8389 CastFix << ")"; 8390 8391 SmallVector<FixItHint,4> Hints; 8392 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8393 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8394 8395 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8396 // If there's already a cast present, just replace it. 8397 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8398 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8399 8400 } else if (!requiresParensToAddCast(E)) { 8401 // If the expression has high enough precedence, 8402 // just write the C-style cast. 8403 Hints.push_back( 8404 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8405 } else { 8406 // Otherwise, add parens around the expression as well as the cast. 8407 CastFix << "("; 8408 Hints.push_back( 8409 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8410 8411 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8412 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8413 } 8414 8415 if (ShouldNotPrintDirectly) { 8416 // The expression has a type that should not be printed directly. 8417 // We extract the name from the typedef because we don't want to show 8418 // the underlying type in the diagnostic. 8419 StringRef Name; 8420 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8421 Name = TypedefTy->getDecl()->getName(); 8422 else 8423 Name = CastTyName; 8424 unsigned Diag = Match == ArgType::NoMatchPedantic 8425 ? diag::warn_format_argument_needs_cast_pedantic 8426 : diag::warn_format_argument_needs_cast; 8427 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8428 << E->getSourceRange(), 8429 E->getBeginLoc(), /*IsStringLocation=*/false, 8430 SpecRange, Hints); 8431 } else { 8432 // In this case, the expression could be printed using a different 8433 // specifier, but we've decided that the specifier is probably correct 8434 // and we should cast instead. Just use the normal warning message. 8435 EmitFormatDiagnostic( 8436 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8437 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8438 << E->getSourceRange(), 8439 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8440 } 8441 } 8442 } else { 8443 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8444 SpecifierLen); 8445 // Since the warning for passing non-POD types to variadic functions 8446 // was deferred until now, we emit a warning for non-POD 8447 // arguments here. 8448 switch (S.isValidVarArgType(ExprTy)) { 8449 case Sema::VAK_Valid: 8450 case Sema::VAK_ValidInCXX11: { 8451 unsigned Diag; 8452 switch (Match) { 8453 case ArgType::Match: llvm_unreachable("expected non-matching"); 8454 case ArgType::NoMatchPedantic: 8455 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8456 break; 8457 case ArgType::NoMatchTypeConfusion: 8458 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8459 break; 8460 case ArgType::NoMatch: 8461 Diag = diag::warn_format_conversion_argument_type_mismatch; 8462 break; 8463 } 8464 8465 EmitFormatDiagnostic( 8466 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8467 << IsEnum << CSR << E->getSourceRange(), 8468 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8469 break; 8470 } 8471 case Sema::VAK_Undefined: 8472 case Sema::VAK_MSVCUndefined: 8473 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8474 << S.getLangOpts().CPlusPlus11 << ExprTy 8475 << CallType 8476 << AT.getRepresentativeTypeName(S.Context) << CSR 8477 << E->getSourceRange(), 8478 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8479 checkForCStrMembers(AT, E); 8480 break; 8481 8482 case Sema::VAK_Invalid: 8483 if (ExprTy->isObjCObjectType()) 8484 EmitFormatDiagnostic( 8485 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8486 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8487 << AT.getRepresentativeTypeName(S.Context) << CSR 8488 << E->getSourceRange(), 8489 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8490 else 8491 // FIXME: If this is an initializer list, suggest removing the braces 8492 // or inserting a cast to the target type. 8493 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8494 << isa<InitListExpr>(E) << ExprTy << CallType 8495 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8496 break; 8497 } 8498 8499 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8500 "format string specifier index out of range"); 8501 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8502 } 8503 8504 return true; 8505 } 8506 8507 //===--- CHECK: Scanf format string checking ------------------------------===// 8508 8509 namespace { 8510 8511 class CheckScanfHandler : public CheckFormatHandler { 8512 public: 8513 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8514 const Expr *origFormatExpr, Sema::FormatStringType type, 8515 unsigned firstDataArg, unsigned numDataArgs, 8516 const char *beg, bool hasVAListArg, 8517 ArrayRef<const Expr *> Args, unsigned formatIdx, 8518 bool inFunctionCall, Sema::VariadicCallType CallType, 8519 llvm::SmallBitVector &CheckedVarArgs, 8520 UncoveredArgHandler &UncoveredArg) 8521 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8522 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8523 inFunctionCall, CallType, CheckedVarArgs, 8524 UncoveredArg) {} 8525 8526 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8527 const char *startSpecifier, 8528 unsigned specifierLen) override; 8529 8530 bool HandleInvalidScanfConversionSpecifier( 8531 const analyze_scanf::ScanfSpecifier &FS, 8532 const char *startSpecifier, 8533 unsigned specifierLen) override; 8534 8535 void HandleIncompleteScanList(const char *start, const char *end) override; 8536 }; 8537 8538 } // namespace 8539 8540 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8541 const char *end) { 8542 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8543 getLocationOfByte(end), /*IsStringLocation*/true, 8544 getSpecifierRange(start, end - start)); 8545 } 8546 8547 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8548 const analyze_scanf::ScanfSpecifier &FS, 8549 const char *startSpecifier, 8550 unsigned specifierLen) { 8551 const analyze_scanf::ScanfConversionSpecifier &CS = 8552 FS.getConversionSpecifier(); 8553 8554 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8555 getLocationOfByte(CS.getStart()), 8556 startSpecifier, specifierLen, 8557 CS.getStart(), CS.getLength()); 8558 } 8559 8560 bool CheckScanfHandler::HandleScanfSpecifier( 8561 const analyze_scanf::ScanfSpecifier &FS, 8562 const char *startSpecifier, 8563 unsigned specifierLen) { 8564 using namespace analyze_scanf; 8565 using namespace analyze_format_string; 8566 8567 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8568 8569 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8570 // be used to decide if we are using positional arguments consistently. 8571 if (FS.consumesDataArgument()) { 8572 if (atFirstArg) { 8573 atFirstArg = false; 8574 usesPositionalArgs = FS.usesPositionalArg(); 8575 } 8576 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8577 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8578 startSpecifier, specifierLen); 8579 return false; 8580 } 8581 } 8582 8583 // Check if the field with is non-zero. 8584 const OptionalAmount &Amt = FS.getFieldWidth(); 8585 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8586 if (Amt.getConstantAmount() == 0) { 8587 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8588 Amt.getConstantLength()); 8589 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8590 getLocationOfByte(Amt.getStart()), 8591 /*IsStringLocation*/true, R, 8592 FixItHint::CreateRemoval(R)); 8593 } 8594 } 8595 8596 if (!FS.consumesDataArgument()) { 8597 // FIXME: Technically specifying a precision or field width here 8598 // makes no sense. Worth issuing a warning at some point. 8599 return true; 8600 } 8601 8602 // Consume the argument. 8603 unsigned argIndex = FS.getArgIndex(); 8604 if (argIndex < NumDataArgs) { 8605 // The check to see if the argIndex is valid will come later. 8606 // We set the bit here because we may exit early from this 8607 // function if we encounter some other error. 8608 CoveredArgs.set(argIndex); 8609 } 8610 8611 // Check the length modifier is valid with the given conversion specifier. 8612 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8613 S.getLangOpts())) 8614 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8615 diag::warn_format_nonsensical_length); 8616 else if (!FS.hasStandardLengthModifier()) 8617 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8618 else if (!FS.hasStandardLengthConversionCombination()) 8619 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8620 diag::warn_format_non_standard_conversion_spec); 8621 8622 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8623 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8624 8625 // The remaining checks depend on the data arguments. 8626 if (HasVAListArg) 8627 return true; 8628 8629 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8630 return false; 8631 8632 // Check that the argument type matches the format specifier. 8633 const Expr *Ex = getDataArg(argIndex); 8634 if (!Ex) 8635 return true; 8636 8637 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8638 8639 if (!AT.isValid()) { 8640 return true; 8641 } 8642 8643 analyze_format_string::ArgType::MatchKind Match = 8644 AT.matchesType(S.Context, Ex->getType()); 8645 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8646 if (Match == analyze_format_string::ArgType::Match) 8647 return true; 8648 8649 ScanfSpecifier fixedFS = FS; 8650 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8651 S.getLangOpts(), S.Context); 8652 8653 unsigned Diag = 8654 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8655 : diag::warn_format_conversion_argument_type_mismatch; 8656 8657 if (Success) { 8658 // Get the fix string from the fixed format specifier. 8659 SmallString<128> buf; 8660 llvm::raw_svector_ostream os(buf); 8661 fixedFS.toString(os); 8662 8663 EmitFormatDiagnostic( 8664 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8665 << Ex->getType() << false << Ex->getSourceRange(), 8666 Ex->getBeginLoc(), 8667 /*IsStringLocation*/ false, 8668 getSpecifierRange(startSpecifier, specifierLen), 8669 FixItHint::CreateReplacement( 8670 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8671 } else { 8672 EmitFormatDiagnostic(S.PDiag(Diag) 8673 << AT.getRepresentativeTypeName(S.Context) 8674 << Ex->getType() << false << Ex->getSourceRange(), 8675 Ex->getBeginLoc(), 8676 /*IsStringLocation*/ false, 8677 getSpecifierRange(startSpecifier, specifierLen)); 8678 } 8679 8680 return true; 8681 } 8682 8683 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8684 const Expr *OrigFormatExpr, 8685 ArrayRef<const Expr *> Args, 8686 bool HasVAListArg, unsigned format_idx, 8687 unsigned firstDataArg, 8688 Sema::FormatStringType Type, 8689 bool inFunctionCall, 8690 Sema::VariadicCallType CallType, 8691 llvm::SmallBitVector &CheckedVarArgs, 8692 UncoveredArgHandler &UncoveredArg, 8693 bool IgnoreStringsWithoutSpecifiers) { 8694 // CHECK: is the format string a wide literal? 8695 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8696 CheckFormatHandler::EmitFormatDiagnostic( 8697 S, inFunctionCall, Args[format_idx], 8698 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8699 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8700 return; 8701 } 8702 8703 // Str - The format string. NOTE: this is NOT null-terminated! 8704 StringRef StrRef = FExpr->getString(); 8705 const char *Str = StrRef.data(); 8706 // Account for cases where the string literal is truncated in a declaration. 8707 const ConstantArrayType *T = 8708 S.Context.getAsConstantArrayType(FExpr->getType()); 8709 assert(T && "String literal not of constant array type!"); 8710 size_t TypeSize = T->getSize().getZExtValue(); 8711 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8712 const unsigned numDataArgs = Args.size() - firstDataArg; 8713 8714 if (IgnoreStringsWithoutSpecifiers && 8715 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8716 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8717 return; 8718 8719 // Emit a warning if the string literal is truncated and does not contain an 8720 // embedded null character. 8721 if (TypeSize <= StrRef.size() && 8722 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8723 CheckFormatHandler::EmitFormatDiagnostic( 8724 S, inFunctionCall, Args[format_idx], 8725 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8726 FExpr->getBeginLoc(), 8727 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8728 return; 8729 } 8730 8731 // CHECK: empty format string? 8732 if (StrLen == 0 && numDataArgs > 0) { 8733 CheckFormatHandler::EmitFormatDiagnostic( 8734 S, inFunctionCall, Args[format_idx], 8735 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8736 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8737 return; 8738 } 8739 8740 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8741 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8742 Type == Sema::FST_OSTrace) { 8743 CheckPrintfHandler H( 8744 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8745 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8746 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8747 CheckedVarArgs, UncoveredArg); 8748 8749 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8750 S.getLangOpts(), 8751 S.Context.getTargetInfo(), 8752 Type == Sema::FST_FreeBSDKPrintf)) 8753 H.DoneProcessing(); 8754 } else if (Type == Sema::FST_Scanf) { 8755 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8756 numDataArgs, Str, HasVAListArg, Args, format_idx, 8757 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8758 8759 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8760 S.getLangOpts(), 8761 S.Context.getTargetInfo())) 8762 H.DoneProcessing(); 8763 } // TODO: handle other formats 8764 } 8765 8766 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8767 // Str - The format string. NOTE: this is NOT null-terminated! 8768 StringRef StrRef = FExpr->getString(); 8769 const char *Str = StrRef.data(); 8770 // Account for cases where the string literal is truncated in a declaration. 8771 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8772 assert(T && "String literal not of constant array type!"); 8773 size_t TypeSize = T->getSize().getZExtValue(); 8774 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8775 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8776 getLangOpts(), 8777 Context.getTargetInfo()); 8778 } 8779 8780 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8781 8782 // Returns the related absolute value function that is larger, of 0 if one 8783 // does not exist. 8784 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8785 switch (AbsFunction) { 8786 default: 8787 return 0; 8788 8789 case Builtin::BI__builtin_abs: 8790 return Builtin::BI__builtin_labs; 8791 case Builtin::BI__builtin_labs: 8792 return Builtin::BI__builtin_llabs; 8793 case Builtin::BI__builtin_llabs: 8794 return 0; 8795 8796 case Builtin::BI__builtin_fabsf: 8797 return Builtin::BI__builtin_fabs; 8798 case Builtin::BI__builtin_fabs: 8799 return Builtin::BI__builtin_fabsl; 8800 case Builtin::BI__builtin_fabsl: 8801 return 0; 8802 8803 case Builtin::BI__builtin_cabsf: 8804 return Builtin::BI__builtin_cabs; 8805 case Builtin::BI__builtin_cabs: 8806 return Builtin::BI__builtin_cabsl; 8807 case Builtin::BI__builtin_cabsl: 8808 return 0; 8809 8810 case Builtin::BIabs: 8811 return Builtin::BIlabs; 8812 case Builtin::BIlabs: 8813 return Builtin::BIllabs; 8814 case Builtin::BIllabs: 8815 return 0; 8816 8817 case Builtin::BIfabsf: 8818 return Builtin::BIfabs; 8819 case Builtin::BIfabs: 8820 return Builtin::BIfabsl; 8821 case Builtin::BIfabsl: 8822 return 0; 8823 8824 case Builtin::BIcabsf: 8825 return Builtin::BIcabs; 8826 case Builtin::BIcabs: 8827 return Builtin::BIcabsl; 8828 case Builtin::BIcabsl: 8829 return 0; 8830 } 8831 } 8832 8833 // Returns the argument type of the absolute value function. 8834 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8835 unsigned AbsType) { 8836 if (AbsType == 0) 8837 return QualType(); 8838 8839 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8840 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8841 if (Error != ASTContext::GE_None) 8842 return QualType(); 8843 8844 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8845 if (!FT) 8846 return QualType(); 8847 8848 if (FT->getNumParams() != 1) 8849 return QualType(); 8850 8851 return FT->getParamType(0); 8852 } 8853 8854 // Returns the best absolute value function, or zero, based on type and 8855 // current absolute value function. 8856 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8857 unsigned AbsFunctionKind) { 8858 unsigned BestKind = 0; 8859 uint64_t ArgSize = Context.getTypeSize(ArgType); 8860 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8861 Kind = getLargerAbsoluteValueFunction(Kind)) { 8862 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8863 if (Context.getTypeSize(ParamType) >= ArgSize) { 8864 if (BestKind == 0) 8865 BestKind = Kind; 8866 else if (Context.hasSameType(ParamType, ArgType)) { 8867 BestKind = Kind; 8868 break; 8869 } 8870 } 8871 } 8872 return BestKind; 8873 } 8874 8875 enum AbsoluteValueKind { 8876 AVK_Integer, 8877 AVK_Floating, 8878 AVK_Complex 8879 }; 8880 8881 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8882 if (T->isIntegralOrEnumerationType()) 8883 return AVK_Integer; 8884 if (T->isRealFloatingType()) 8885 return AVK_Floating; 8886 if (T->isAnyComplexType()) 8887 return AVK_Complex; 8888 8889 llvm_unreachable("Type not integer, floating, or complex"); 8890 } 8891 8892 // Changes the absolute value function to a different type. Preserves whether 8893 // the function is a builtin. 8894 static unsigned changeAbsFunction(unsigned AbsKind, 8895 AbsoluteValueKind ValueKind) { 8896 switch (ValueKind) { 8897 case AVK_Integer: 8898 switch (AbsKind) { 8899 default: 8900 return 0; 8901 case Builtin::BI__builtin_fabsf: 8902 case Builtin::BI__builtin_fabs: 8903 case Builtin::BI__builtin_fabsl: 8904 case Builtin::BI__builtin_cabsf: 8905 case Builtin::BI__builtin_cabs: 8906 case Builtin::BI__builtin_cabsl: 8907 return Builtin::BI__builtin_abs; 8908 case Builtin::BIfabsf: 8909 case Builtin::BIfabs: 8910 case Builtin::BIfabsl: 8911 case Builtin::BIcabsf: 8912 case Builtin::BIcabs: 8913 case Builtin::BIcabsl: 8914 return Builtin::BIabs; 8915 } 8916 case AVK_Floating: 8917 switch (AbsKind) { 8918 default: 8919 return 0; 8920 case Builtin::BI__builtin_abs: 8921 case Builtin::BI__builtin_labs: 8922 case Builtin::BI__builtin_llabs: 8923 case Builtin::BI__builtin_cabsf: 8924 case Builtin::BI__builtin_cabs: 8925 case Builtin::BI__builtin_cabsl: 8926 return Builtin::BI__builtin_fabsf; 8927 case Builtin::BIabs: 8928 case Builtin::BIlabs: 8929 case Builtin::BIllabs: 8930 case Builtin::BIcabsf: 8931 case Builtin::BIcabs: 8932 case Builtin::BIcabsl: 8933 return Builtin::BIfabsf; 8934 } 8935 case AVK_Complex: 8936 switch (AbsKind) { 8937 default: 8938 return 0; 8939 case Builtin::BI__builtin_abs: 8940 case Builtin::BI__builtin_labs: 8941 case Builtin::BI__builtin_llabs: 8942 case Builtin::BI__builtin_fabsf: 8943 case Builtin::BI__builtin_fabs: 8944 case Builtin::BI__builtin_fabsl: 8945 return Builtin::BI__builtin_cabsf; 8946 case Builtin::BIabs: 8947 case Builtin::BIlabs: 8948 case Builtin::BIllabs: 8949 case Builtin::BIfabsf: 8950 case Builtin::BIfabs: 8951 case Builtin::BIfabsl: 8952 return Builtin::BIcabsf; 8953 } 8954 } 8955 llvm_unreachable("Unable to convert function"); 8956 } 8957 8958 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8959 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8960 if (!FnInfo) 8961 return 0; 8962 8963 switch (FDecl->getBuiltinID()) { 8964 default: 8965 return 0; 8966 case Builtin::BI__builtin_abs: 8967 case Builtin::BI__builtin_fabs: 8968 case Builtin::BI__builtin_fabsf: 8969 case Builtin::BI__builtin_fabsl: 8970 case Builtin::BI__builtin_labs: 8971 case Builtin::BI__builtin_llabs: 8972 case Builtin::BI__builtin_cabs: 8973 case Builtin::BI__builtin_cabsf: 8974 case Builtin::BI__builtin_cabsl: 8975 case Builtin::BIabs: 8976 case Builtin::BIlabs: 8977 case Builtin::BIllabs: 8978 case Builtin::BIfabs: 8979 case Builtin::BIfabsf: 8980 case Builtin::BIfabsl: 8981 case Builtin::BIcabs: 8982 case Builtin::BIcabsf: 8983 case Builtin::BIcabsl: 8984 return FDecl->getBuiltinID(); 8985 } 8986 llvm_unreachable("Unknown Builtin type"); 8987 } 8988 8989 // If the replacement is valid, emit a note with replacement function. 8990 // Additionally, suggest including the proper header if not already included. 8991 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8992 unsigned AbsKind, QualType ArgType) { 8993 bool EmitHeaderHint = true; 8994 const char *HeaderName = nullptr; 8995 const char *FunctionName = nullptr; 8996 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8997 FunctionName = "std::abs"; 8998 if (ArgType->isIntegralOrEnumerationType()) { 8999 HeaderName = "cstdlib"; 9000 } else if (ArgType->isRealFloatingType()) { 9001 HeaderName = "cmath"; 9002 } else { 9003 llvm_unreachable("Invalid Type"); 9004 } 9005 9006 // Lookup all std::abs 9007 if (NamespaceDecl *Std = S.getStdNamespace()) { 9008 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9009 R.suppressDiagnostics(); 9010 S.LookupQualifiedName(R, Std); 9011 9012 for (const auto *I : R) { 9013 const FunctionDecl *FDecl = nullptr; 9014 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9015 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9016 } else { 9017 FDecl = dyn_cast<FunctionDecl>(I); 9018 } 9019 if (!FDecl) 9020 continue; 9021 9022 // Found std::abs(), check that they are the right ones. 9023 if (FDecl->getNumParams() != 1) 9024 continue; 9025 9026 // Check that the parameter type can handle the argument. 9027 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9028 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9029 S.Context.getTypeSize(ArgType) <= 9030 S.Context.getTypeSize(ParamType)) { 9031 // Found a function, don't need the header hint. 9032 EmitHeaderHint = false; 9033 break; 9034 } 9035 } 9036 } 9037 } else { 9038 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9039 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9040 9041 if (HeaderName) { 9042 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9043 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9044 R.suppressDiagnostics(); 9045 S.LookupName(R, S.getCurScope()); 9046 9047 if (R.isSingleResult()) { 9048 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9049 if (FD && FD->getBuiltinID() == AbsKind) { 9050 EmitHeaderHint = false; 9051 } else { 9052 return; 9053 } 9054 } else if (!R.empty()) { 9055 return; 9056 } 9057 } 9058 } 9059 9060 S.Diag(Loc, diag::note_replace_abs_function) 9061 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9062 9063 if (!HeaderName) 9064 return; 9065 9066 if (!EmitHeaderHint) 9067 return; 9068 9069 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9070 << FunctionName; 9071 } 9072 9073 template <std::size_t StrLen> 9074 static bool IsStdFunction(const FunctionDecl *FDecl, 9075 const char (&Str)[StrLen]) { 9076 if (!FDecl) 9077 return false; 9078 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9079 return false; 9080 if (!FDecl->isInStdNamespace()) 9081 return false; 9082 9083 return true; 9084 } 9085 9086 // Warn when using the wrong abs() function. 9087 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9088 const FunctionDecl *FDecl) { 9089 if (Call->getNumArgs() != 1) 9090 return; 9091 9092 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9093 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9094 if (AbsKind == 0 && !IsStdAbs) 9095 return; 9096 9097 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9098 QualType ParamType = Call->getArg(0)->getType(); 9099 9100 // Unsigned types cannot be negative. Suggest removing the absolute value 9101 // function call. 9102 if (ArgType->isUnsignedIntegerType()) { 9103 const char *FunctionName = 9104 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9105 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9106 Diag(Call->getExprLoc(), diag::note_remove_abs) 9107 << FunctionName 9108 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9109 return; 9110 } 9111 9112 // Taking the absolute value of a pointer is very suspicious, they probably 9113 // wanted to index into an array, dereference a pointer, call a function, etc. 9114 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9115 unsigned DiagType = 0; 9116 if (ArgType->isFunctionType()) 9117 DiagType = 1; 9118 else if (ArgType->isArrayType()) 9119 DiagType = 2; 9120 9121 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9122 return; 9123 } 9124 9125 // std::abs has overloads which prevent most of the absolute value problems 9126 // from occurring. 9127 if (IsStdAbs) 9128 return; 9129 9130 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9131 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9132 9133 // The argument and parameter are the same kind. Check if they are the right 9134 // size. 9135 if (ArgValueKind == ParamValueKind) { 9136 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9137 return; 9138 9139 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9140 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9141 << FDecl << ArgType << ParamType; 9142 9143 if (NewAbsKind == 0) 9144 return; 9145 9146 emitReplacement(*this, Call->getExprLoc(), 9147 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9148 return; 9149 } 9150 9151 // ArgValueKind != ParamValueKind 9152 // The wrong type of absolute value function was used. Attempt to find the 9153 // proper one. 9154 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9155 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9156 if (NewAbsKind == 0) 9157 return; 9158 9159 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9160 << FDecl << ParamValueKind << ArgValueKind; 9161 9162 emitReplacement(*this, Call->getExprLoc(), 9163 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9164 } 9165 9166 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9167 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9168 const FunctionDecl *FDecl) { 9169 if (!Call || !FDecl) return; 9170 9171 // Ignore template specializations and macros. 9172 if (inTemplateInstantiation()) return; 9173 if (Call->getExprLoc().isMacroID()) return; 9174 9175 // Only care about the one template argument, two function parameter std::max 9176 if (Call->getNumArgs() != 2) return; 9177 if (!IsStdFunction(FDecl, "max")) return; 9178 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9179 if (!ArgList) return; 9180 if (ArgList->size() != 1) return; 9181 9182 // Check that template type argument is unsigned integer. 9183 const auto& TA = ArgList->get(0); 9184 if (TA.getKind() != TemplateArgument::Type) return; 9185 QualType ArgType = TA.getAsType(); 9186 if (!ArgType->isUnsignedIntegerType()) return; 9187 9188 // See if either argument is a literal zero. 9189 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9190 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9191 if (!MTE) return false; 9192 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9193 if (!Num) return false; 9194 if (Num->getValue() != 0) return false; 9195 return true; 9196 }; 9197 9198 const Expr *FirstArg = Call->getArg(0); 9199 const Expr *SecondArg = Call->getArg(1); 9200 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9201 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9202 9203 // Only warn when exactly one argument is zero. 9204 if (IsFirstArgZero == IsSecondArgZero) return; 9205 9206 SourceRange FirstRange = FirstArg->getSourceRange(); 9207 SourceRange SecondRange = SecondArg->getSourceRange(); 9208 9209 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9210 9211 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9212 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9213 9214 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9215 SourceRange RemovalRange; 9216 if (IsFirstArgZero) { 9217 RemovalRange = SourceRange(FirstRange.getBegin(), 9218 SecondRange.getBegin().getLocWithOffset(-1)); 9219 } else { 9220 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9221 SecondRange.getEnd()); 9222 } 9223 9224 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9225 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9226 << FixItHint::CreateRemoval(RemovalRange); 9227 } 9228 9229 //===--- CHECK: Standard memory functions ---------------------------------===// 9230 9231 /// Takes the expression passed to the size_t parameter of functions 9232 /// such as memcmp, strncat, etc and warns if it's a comparison. 9233 /// 9234 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9235 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9236 IdentifierInfo *FnName, 9237 SourceLocation FnLoc, 9238 SourceLocation RParenLoc) { 9239 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9240 if (!Size) 9241 return false; 9242 9243 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9244 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9245 return false; 9246 9247 SourceRange SizeRange = Size->getSourceRange(); 9248 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9249 << SizeRange << FnName; 9250 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9251 << FnName 9252 << FixItHint::CreateInsertion( 9253 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9254 << FixItHint::CreateRemoval(RParenLoc); 9255 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9256 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9257 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9258 ")"); 9259 9260 return true; 9261 } 9262 9263 /// Determine whether the given type is or contains a dynamic class type 9264 /// (e.g., whether it has a vtable). 9265 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9266 bool &IsContained) { 9267 // Look through array types while ignoring qualifiers. 9268 const Type *Ty = T->getBaseElementTypeUnsafe(); 9269 IsContained = false; 9270 9271 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9272 RD = RD ? RD->getDefinition() : nullptr; 9273 if (!RD || RD->isInvalidDecl()) 9274 return nullptr; 9275 9276 if (RD->isDynamicClass()) 9277 return RD; 9278 9279 // Check all the fields. If any bases were dynamic, the class is dynamic. 9280 // It's impossible for a class to transitively contain itself by value, so 9281 // infinite recursion is impossible. 9282 for (auto *FD : RD->fields()) { 9283 bool SubContained; 9284 if (const CXXRecordDecl *ContainedRD = 9285 getContainedDynamicClass(FD->getType(), SubContained)) { 9286 IsContained = true; 9287 return ContainedRD; 9288 } 9289 } 9290 9291 return nullptr; 9292 } 9293 9294 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9295 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9296 if (Unary->getKind() == UETT_SizeOf) 9297 return Unary; 9298 return nullptr; 9299 } 9300 9301 /// If E is a sizeof expression, returns its argument expression, 9302 /// otherwise returns NULL. 9303 static const Expr *getSizeOfExprArg(const Expr *E) { 9304 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9305 if (!SizeOf->isArgumentType()) 9306 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9307 return nullptr; 9308 } 9309 9310 /// If E is a sizeof expression, returns its argument type. 9311 static QualType getSizeOfArgType(const Expr *E) { 9312 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9313 return SizeOf->getTypeOfArgument(); 9314 return QualType(); 9315 } 9316 9317 namespace { 9318 9319 struct SearchNonTrivialToInitializeField 9320 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9321 using Super = 9322 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9323 9324 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9325 9326 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9327 SourceLocation SL) { 9328 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9329 asDerived().visitArray(PDIK, AT, SL); 9330 return; 9331 } 9332 9333 Super::visitWithKind(PDIK, FT, SL); 9334 } 9335 9336 void visitARCStrong(QualType FT, SourceLocation SL) { 9337 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9338 } 9339 void visitARCWeak(QualType FT, SourceLocation SL) { 9340 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9341 } 9342 void visitStruct(QualType FT, SourceLocation SL) { 9343 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9344 visit(FD->getType(), FD->getLocation()); 9345 } 9346 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9347 const ArrayType *AT, SourceLocation SL) { 9348 visit(getContext().getBaseElementType(AT), SL); 9349 } 9350 void visitTrivial(QualType FT, SourceLocation SL) {} 9351 9352 static void diag(QualType RT, const Expr *E, Sema &S) { 9353 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9354 } 9355 9356 ASTContext &getContext() { return S.getASTContext(); } 9357 9358 const Expr *E; 9359 Sema &S; 9360 }; 9361 9362 struct SearchNonTrivialToCopyField 9363 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9364 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9365 9366 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9367 9368 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9369 SourceLocation SL) { 9370 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9371 asDerived().visitArray(PCK, AT, SL); 9372 return; 9373 } 9374 9375 Super::visitWithKind(PCK, FT, SL); 9376 } 9377 9378 void visitARCStrong(QualType FT, SourceLocation SL) { 9379 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9380 } 9381 void visitARCWeak(QualType FT, SourceLocation SL) { 9382 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9383 } 9384 void visitStruct(QualType FT, SourceLocation SL) { 9385 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9386 visit(FD->getType(), FD->getLocation()); 9387 } 9388 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9389 SourceLocation SL) { 9390 visit(getContext().getBaseElementType(AT), SL); 9391 } 9392 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9393 SourceLocation SL) {} 9394 void visitTrivial(QualType FT, SourceLocation SL) {} 9395 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9396 9397 static void diag(QualType RT, const Expr *E, Sema &S) { 9398 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9399 } 9400 9401 ASTContext &getContext() { return S.getASTContext(); } 9402 9403 const Expr *E; 9404 Sema &S; 9405 }; 9406 9407 } 9408 9409 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9410 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9411 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9412 9413 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9414 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9415 return false; 9416 9417 return doesExprLikelyComputeSize(BO->getLHS()) || 9418 doesExprLikelyComputeSize(BO->getRHS()); 9419 } 9420 9421 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9422 } 9423 9424 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9425 /// 9426 /// \code 9427 /// #define MACRO 0 9428 /// foo(MACRO); 9429 /// foo(0); 9430 /// \endcode 9431 /// 9432 /// This should return true for the first call to foo, but not for the second 9433 /// (regardless of whether foo is a macro or function). 9434 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9435 SourceLocation CallLoc, 9436 SourceLocation ArgLoc) { 9437 if (!CallLoc.isMacroID()) 9438 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9439 9440 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9441 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9442 } 9443 9444 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9445 /// last two arguments transposed. 9446 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9447 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9448 return; 9449 9450 const Expr *SizeArg = 9451 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9452 9453 auto isLiteralZero = [](const Expr *E) { 9454 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9455 }; 9456 9457 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9458 SourceLocation CallLoc = Call->getRParenLoc(); 9459 SourceManager &SM = S.getSourceManager(); 9460 if (isLiteralZero(SizeArg) && 9461 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9462 9463 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9464 9465 // Some platforms #define bzero to __builtin_memset. See if this is the 9466 // case, and if so, emit a better diagnostic. 9467 if (BId == Builtin::BIbzero || 9468 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9469 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9470 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9471 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9472 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9473 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9474 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9475 } 9476 return; 9477 } 9478 9479 // If the second argument to a memset is a sizeof expression and the third 9480 // isn't, this is also likely an error. This should catch 9481 // 'memset(buf, sizeof(buf), 0xff)'. 9482 if (BId == Builtin::BImemset && 9483 doesExprLikelyComputeSize(Call->getArg(1)) && 9484 !doesExprLikelyComputeSize(Call->getArg(2))) { 9485 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9486 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9487 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9488 return; 9489 } 9490 } 9491 9492 /// Check for dangerous or invalid arguments to memset(). 9493 /// 9494 /// This issues warnings on known problematic, dangerous or unspecified 9495 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9496 /// function calls. 9497 /// 9498 /// \param Call The call expression to diagnose. 9499 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9500 unsigned BId, 9501 IdentifierInfo *FnName) { 9502 assert(BId != 0); 9503 9504 // It is possible to have a non-standard definition of memset. Validate 9505 // we have enough arguments, and if not, abort further checking. 9506 unsigned ExpectedNumArgs = 9507 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9508 if (Call->getNumArgs() < ExpectedNumArgs) 9509 return; 9510 9511 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9512 BId == Builtin::BIstrndup ? 1 : 2); 9513 unsigned LenArg = 9514 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9515 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9516 9517 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9518 Call->getBeginLoc(), Call->getRParenLoc())) 9519 return; 9520 9521 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9522 CheckMemaccessSize(*this, BId, Call); 9523 9524 // We have special checking when the length is a sizeof expression. 9525 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9526 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9527 llvm::FoldingSetNodeID SizeOfArgID; 9528 9529 // Although widely used, 'bzero' is not a standard function. Be more strict 9530 // with the argument types before allowing diagnostics and only allow the 9531 // form bzero(ptr, sizeof(...)). 9532 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9533 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9534 return; 9535 9536 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9537 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9538 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9539 9540 QualType DestTy = Dest->getType(); 9541 QualType PointeeTy; 9542 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9543 PointeeTy = DestPtrTy->getPointeeType(); 9544 9545 // Never warn about void type pointers. This can be used to suppress 9546 // false positives. 9547 if (PointeeTy->isVoidType()) 9548 continue; 9549 9550 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9551 // actually comparing the expressions for equality. Because computing the 9552 // expression IDs can be expensive, we only do this if the diagnostic is 9553 // enabled. 9554 if (SizeOfArg && 9555 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9556 SizeOfArg->getExprLoc())) { 9557 // We only compute IDs for expressions if the warning is enabled, and 9558 // cache the sizeof arg's ID. 9559 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9560 SizeOfArg->Profile(SizeOfArgID, Context, true); 9561 llvm::FoldingSetNodeID DestID; 9562 Dest->Profile(DestID, Context, true); 9563 if (DestID == SizeOfArgID) { 9564 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9565 // over sizeof(src) as well. 9566 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9567 StringRef ReadableName = FnName->getName(); 9568 9569 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9570 if (UnaryOp->getOpcode() == UO_AddrOf) 9571 ActionIdx = 1; // If its an address-of operator, just remove it. 9572 if (!PointeeTy->isIncompleteType() && 9573 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9574 ActionIdx = 2; // If the pointee's size is sizeof(char), 9575 // suggest an explicit length. 9576 9577 // If the function is defined as a builtin macro, do not show macro 9578 // expansion. 9579 SourceLocation SL = SizeOfArg->getExprLoc(); 9580 SourceRange DSR = Dest->getSourceRange(); 9581 SourceRange SSR = SizeOfArg->getSourceRange(); 9582 SourceManager &SM = getSourceManager(); 9583 9584 if (SM.isMacroArgExpansion(SL)) { 9585 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9586 SL = SM.getSpellingLoc(SL); 9587 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9588 SM.getSpellingLoc(DSR.getEnd())); 9589 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9590 SM.getSpellingLoc(SSR.getEnd())); 9591 } 9592 9593 DiagRuntimeBehavior(SL, SizeOfArg, 9594 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9595 << ReadableName 9596 << PointeeTy 9597 << DestTy 9598 << DSR 9599 << SSR); 9600 DiagRuntimeBehavior(SL, SizeOfArg, 9601 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9602 << ActionIdx 9603 << SSR); 9604 9605 break; 9606 } 9607 } 9608 9609 // Also check for cases where the sizeof argument is the exact same 9610 // type as the memory argument, and where it points to a user-defined 9611 // record type. 9612 if (SizeOfArgTy != QualType()) { 9613 if (PointeeTy->isRecordType() && 9614 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9615 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9616 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9617 << FnName << SizeOfArgTy << ArgIdx 9618 << PointeeTy << Dest->getSourceRange() 9619 << LenExpr->getSourceRange()); 9620 break; 9621 } 9622 } 9623 } else if (DestTy->isArrayType()) { 9624 PointeeTy = DestTy; 9625 } 9626 9627 if (PointeeTy == QualType()) 9628 continue; 9629 9630 // Always complain about dynamic classes. 9631 bool IsContained; 9632 if (const CXXRecordDecl *ContainedRD = 9633 getContainedDynamicClass(PointeeTy, IsContained)) { 9634 9635 unsigned OperationType = 0; 9636 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9637 // "overwritten" if we're warning about the destination for any call 9638 // but memcmp; otherwise a verb appropriate to the call. 9639 if (ArgIdx != 0 || IsCmp) { 9640 if (BId == Builtin::BImemcpy) 9641 OperationType = 1; 9642 else if(BId == Builtin::BImemmove) 9643 OperationType = 2; 9644 else if (IsCmp) 9645 OperationType = 3; 9646 } 9647 9648 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9649 PDiag(diag::warn_dyn_class_memaccess) 9650 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9651 << IsContained << ContainedRD << OperationType 9652 << Call->getCallee()->getSourceRange()); 9653 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9654 BId != Builtin::BImemset) 9655 DiagRuntimeBehavior( 9656 Dest->getExprLoc(), Dest, 9657 PDiag(diag::warn_arc_object_memaccess) 9658 << ArgIdx << FnName << PointeeTy 9659 << Call->getCallee()->getSourceRange()); 9660 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9661 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9662 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9663 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9664 PDiag(diag::warn_cstruct_memaccess) 9665 << ArgIdx << FnName << PointeeTy << 0); 9666 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9667 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9668 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9669 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9670 PDiag(diag::warn_cstruct_memaccess) 9671 << ArgIdx << FnName << PointeeTy << 1); 9672 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9673 } else { 9674 continue; 9675 } 9676 } else 9677 continue; 9678 9679 DiagRuntimeBehavior( 9680 Dest->getExprLoc(), Dest, 9681 PDiag(diag::note_bad_memaccess_silence) 9682 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9683 break; 9684 } 9685 } 9686 9687 // A little helper routine: ignore addition and subtraction of integer literals. 9688 // This intentionally does not ignore all integer constant expressions because 9689 // we don't want to remove sizeof(). 9690 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9691 Ex = Ex->IgnoreParenCasts(); 9692 9693 while (true) { 9694 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9695 if (!BO || !BO->isAdditiveOp()) 9696 break; 9697 9698 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9699 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9700 9701 if (isa<IntegerLiteral>(RHS)) 9702 Ex = LHS; 9703 else if (isa<IntegerLiteral>(LHS)) 9704 Ex = RHS; 9705 else 9706 break; 9707 } 9708 9709 return Ex; 9710 } 9711 9712 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9713 ASTContext &Context) { 9714 // Only handle constant-sized or VLAs, but not flexible members. 9715 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9716 // Only issue the FIXIT for arrays of size > 1. 9717 if (CAT->getSize().getSExtValue() <= 1) 9718 return false; 9719 } else if (!Ty->isVariableArrayType()) { 9720 return false; 9721 } 9722 return true; 9723 } 9724 9725 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9726 // be the size of the source, instead of the destination. 9727 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9728 IdentifierInfo *FnName) { 9729 9730 // Don't crash if the user has the wrong number of arguments 9731 unsigned NumArgs = Call->getNumArgs(); 9732 if ((NumArgs != 3) && (NumArgs != 4)) 9733 return; 9734 9735 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9736 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9737 const Expr *CompareWithSrc = nullptr; 9738 9739 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9740 Call->getBeginLoc(), Call->getRParenLoc())) 9741 return; 9742 9743 // Look for 'strlcpy(dst, x, sizeof(x))' 9744 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9745 CompareWithSrc = Ex; 9746 else { 9747 // Look for 'strlcpy(dst, x, strlen(x))' 9748 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9749 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9750 SizeCall->getNumArgs() == 1) 9751 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9752 } 9753 } 9754 9755 if (!CompareWithSrc) 9756 return; 9757 9758 // Determine if the argument to sizeof/strlen is equal to the source 9759 // argument. In principle there's all kinds of things you could do 9760 // here, for instance creating an == expression and evaluating it with 9761 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9762 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9763 if (!SrcArgDRE) 9764 return; 9765 9766 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9767 if (!CompareWithSrcDRE || 9768 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9769 return; 9770 9771 const Expr *OriginalSizeArg = Call->getArg(2); 9772 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9773 << OriginalSizeArg->getSourceRange() << FnName; 9774 9775 // Output a FIXIT hint if the destination is an array (rather than a 9776 // pointer to an array). This could be enhanced to handle some 9777 // pointers if we know the actual size, like if DstArg is 'array+2' 9778 // we could say 'sizeof(array)-2'. 9779 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9780 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9781 return; 9782 9783 SmallString<128> sizeString; 9784 llvm::raw_svector_ostream OS(sizeString); 9785 OS << "sizeof("; 9786 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9787 OS << ")"; 9788 9789 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9790 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9791 OS.str()); 9792 } 9793 9794 /// Check if two expressions refer to the same declaration. 9795 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9796 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9797 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9798 return D1->getDecl() == D2->getDecl(); 9799 return false; 9800 } 9801 9802 static const Expr *getStrlenExprArg(const Expr *E) { 9803 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9804 const FunctionDecl *FD = CE->getDirectCallee(); 9805 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9806 return nullptr; 9807 return CE->getArg(0)->IgnoreParenCasts(); 9808 } 9809 return nullptr; 9810 } 9811 9812 // Warn on anti-patterns as the 'size' argument to strncat. 9813 // The correct size argument should look like following: 9814 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9815 void Sema::CheckStrncatArguments(const CallExpr *CE, 9816 IdentifierInfo *FnName) { 9817 // Don't crash if the user has the wrong number of arguments. 9818 if (CE->getNumArgs() < 3) 9819 return; 9820 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9821 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9822 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9823 9824 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9825 CE->getRParenLoc())) 9826 return; 9827 9828 // Identify common expressions, which are wrongly used as the size argument 9829 // to strncat and may lead to buffer overflows. 9830 unsigned PatternType = 0; 9831 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9832 // - sizeof(dst) 9833 if (referToTheSameDecl(SizeOfArg, DstArg)) 9834 PatternType = 1; 9835 // - sizeof(src) 9836 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9837 PatternType = 2; 9838 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9839 if (BE->getOpcode() == BO_Sub) { 9840 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9841 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9842 // - sizeof(dst) - strlen(dst) 9843 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9844 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9845 PatternType = 1; 9846 // - sizeof(src) - (anything) 9847 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9848 PatternType = 2; 9849 } 9850 } 9851 9852 if (PatternType == 0) 9853 return; 9854 9855 // Generate the diagnostic. 9856 SourceLocation SL = LenArg->getBeginLoc(); 9857 SourceRange SR = LenArg->getSourceRange(); 9858 SourceManager &SM = getSourceManager(); 9859 9860 // If the function is defined as a builtin macro, do not show macro expansion. 9861 if (SM.isMacroArgExpansion(SL)) { 9862 SL = SM.getSpellingLoc(SL); 9863 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9864 SM.getSpellingLoc(SR.getEnd())); 9865 } 9866 9867 // Check if the destination is an array (rather than a pointer to an array). 9868 QualType DstTy = DstArg->getType(); 9869 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9870 Context); 9871 if (!isKnownSizeArray) { 9872 if (PatternType == 1) 9873 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9874 else 9875 Diag(SL, diag::warn_strncat_src_size) << SR; 9876 return; 9877 } 9878 9879 if (PatternType == 1) 9880 Diag(SL, diag::warn_strncat_large_size) << SR; 9881 else 9882 Diag(SL, diag::warn_strncat_src_size) << SR; 9883 9884 SmallString<128> sizeString; 9885 llvm::raw_svector_ostream OS(sizeString); 9886 OS << "sizeof("; 9887 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9888 OS << ") - "; 9889 OS << "strlen("; 9890 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9891 OS << ") - 1"; 9892 9893 Diag(SL, diag::note_strncat_wrong_size) 9894 << FixItHint::CreateReplacement(SR, OS.str()); 9895 } 9896 9897 void 9898 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9899 SourceLocation ReturnLoc, 9900 bool isObjCMethod, 9901 const AttrVec *Attrs, 9902 const FunctionDecl *FD) { 9903 // Check if the return value is null but should not be. 9904 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9905 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9906 CheckNonNullExpr(*this, RetValExp)) 9907 Diag(ReturnLoc, diag::warn_null_ret) 9908 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9909 9910 // C++11 [basic.stc.dynamic.allocation]p4: 9911 // If an allocation function declared with a non-throwing 9912 // exception-specification fails to allocate storage, it shall return 9913 // a null pointer. Any other allocation function that fails to allocate 9914 // storage shall indicate failure only by throwing an exception [...] 9915 if (FD) { 9916 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9917 if (Op == OO_New || Op == OO_Array_New) { 9918 const FunctionProtoType *Proto 9919 = FD->getType()->castAs<FunctionProtoType>(); 9920 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9921 CheckNonNullExpr(*this, RetValExp)) 9922 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9923 << FD << getLangOpts().CPlusPlus11; 9924 } 9925 } 9926 } 9927 9928 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9929 9930 /// Check for comparisons of floating point operands using != and ==. 9931 /// Issue a warning if these are no self-comparisons, as they are not likely 9932 /// to do what the programmer intended. 9933 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9934 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9935 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9936 9937 // Special case: check for x == x (which is OK). 9938 // Do not emit warnings for such cases. 9939 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9940 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9941 if (DRL->getDecl() == DRR->getDecl()) 9942 return; 9943 9944 // Special case: check for comparisons against literals that can be exactly 9945 // represented by APFloat. In such cases, do not emit a warning. This 9946 // is a heuristic: often comparison against such literals are used to 9947 // detect if a value in a variable has not changed. This clearly can 9948 // lead to false negatives. 9949 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9950 if (FLL->isExact()) 9951 return; 9952 } else 9953 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9954 if (FLR->isExact()) 9955 return; 9956 9957 // Check for comparisons with builtin types. 9958 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9959 if (CL->getBuiltinCallee()) 9960 return; 9961 9962 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9963 if (CR->getBuiltinCallee()) 9964 return; 9965 9966 // Emit the diagnostic. 9967 Diag(Loc, diag::warn_floatingpoint_eq) 9968 << LHS->getSourceRange() << RHS->getSourceRange(); 9969 } 9970 9971 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9972 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9973 9974 namespace { 9975 9976 /// Structure recording the 'active' range of an integer-valued 9977 /// expression. 9978 struct IntRange { 9979 /// The number of bits active in the int. 9980 unsigned Width; 9981 9982 /// True if the int is known not to have negative values. 9983 bool NonNegative; 9984 9985 IntRange(unsigned Width, bool NonNegative) 9986 : Width(Width), NonNegative(NonNegative) {} 9987 9988 /// Returns the range of the bool type. 9989 static IntRange forBoolType() { 9990 return IntRange(1, true); 9991 } 9992 9993 /// Returns the range of an opaque value of the given integral type. 9994 static IntRange forValueOfType(ASTContext &C, QualType T) { 9995 return forValueOfCanonicalType(C, 9996 T->getCanonicalTypeInternal().getTypePtr()); 9997 } 9998 9999 /// Returns the range of an opaque value of a canonical integral type. 10000 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10001 assert(T->isCanonicalUnqualified()); 10002 10003 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10004 T = VT->getElementType().getTypePtr(); 10005 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10006 T = CT->getElementType().getTypePtr(); 10007 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10008 T = AT->getValueType().getTypePtr(); 10009 10010 if (!C.getLangOpts().CPlusPlus) { 10011 // For enum types in C code, use the underlying datatype. 10012 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10013 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10014 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10015 // For enum types in C++, use the known bit width of the enumerators. 10016 EnumDecl *Enum = ET->getDecl(); 10017 // In C++11, enums can have a fixed underlying type. Use this type to 10018 // compute the range. 10019 if (Enum->isFixed()) { 10020 return IntRange(C.getIntWidth(QualType(T, 0)), 10021 !ET->isSignedIntegerOrEnumerationType()); 10022 } 10023 10024 unsigned NumPositive = Enum->getNumPositiveBits(); 10025 unsigned NumNegative = Enum->getNumNegativeBits(); 10026 10027 if (NumNegative == 0) 10028 return IntRange(NumPositive, true/*NonNegative*/); 10029 else 10030 return IntRange(std::max(NumPositive + 1, NumNegative), 10031 false/*NonNegative*/); 10032 } 10033 10034 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10035 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10036 10037 const BuiltinType *BT = cast<BuiltinType>(T); 10038 assert(BT->isInteger()); 10039 10040 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10041 } 10042 10043 /// Returns the "target" range of a canonical integral type, i.e. 10044 /// the range of values expressible in the type. 10045 /// 10046 /// This matches forValueOfCanonicalType except that enums have the 10047 /// full range of their type, not the range of their enumerators. 10048 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10049 assert(T->isCanonicalUnqualified()); 10050 10051 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10052 T = VT->getElementType().getTypePtr(); 10053 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10054 T = CT->getElementType().getTypePtr(); 10055 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10056 T = AT->getValueType().getTypePtr(); 10057 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10058 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10059 10060 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10061 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10062 10063 const BuiltinType *BT = cast<BuiltinType>(T); 10064 assert(BT->isInteger()); 10065 10066 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10067 } 10068 10069 /// Returns the supremum of two ranges: i.e. their conservative merge. 10070 static IntRange join(IntRange L, IntRange R) { 10071 return IntRange(std::max(L.Width, R.Width), 10072 L.NonNegative && R.NonNegative); 10073 } 10074 10075 /// Returns the infinum of two ranges: i.e. their aggressive merge. 10076 static IntRange meet(IntRange L, IntRange R) { 10077 return IntRange(std::min(L.Width, R.Width), 10078 L.NonNegative || R.NonNegative); 10079 } 10080 }; 10081 10082 } // namespace 10083 10084 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10085 unsigned MaxWidth) { 10086 if (value.isSigned() && value.isNegative()) 10087 return IntRange(value.getMinSignedBits(), false); 10088 10089 if (value.getBitWidth() > MaxWidth) 10090 value = value.trunc(MaxWidth); 10091 10092 // isNonNegative() just checks the sign bit without considering 10093 // signedness. 10094 return IntRange(value.getActiveBits(), true); 10095 } 10096 10097 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10098 unsigned MaxWidth) { 10099 if (result.isInt()) 10100 return GetValueRange(C, result.getInt(), MaxWidth); 10101 10102 if (result.isVector()) { 10103 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10104 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10105 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10106 R = IntRange::join(R, El); 10107 } 10108 return R; 10109 } 10110 10111 if (result.isComplexInt()) { 10112 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10113 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10114 return IntRange::join(R, I); 10115 } 10116 10117 // This can happen with lossless casts to intptr_t of "based" lvalues. 10118 // Assume it might use arbitrary bits. 10119 // FIXME: The only reason we need to pass the type in here is to get 10120 // the sign right on this one case. It would be nice if APValue 10121 // preserved this. 10122 assert(result.isLValue() || result.isAddrLabelDiff()); 10123 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10124 } 10125 10126 static QualType GetExprType(const Expr *E) { 10127 QualType Ty = E->getType(); 10128 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10129 Ty = AtomicRHS->getValueType(); 10130 return Ty; 10131 } 10132 10133 /// Pseudo-evaluate the given integer expression, estimating the 10134 /// range of values it might take. 10135 /// 10136 /// \param MaxWidth - the width to which the value will be truncated 10137 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10138 bool InConstantContext) { 10139 E = E->IgnoreParens(); 10140 10141 // Try a full evaluation first. 10142 Expr::EvalResult result; 10143 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10144 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10145 10146 // I think we only want to look through implicit casts here; if the 10147 // user has an explicit widening cast, we should treat the value as 10148 // being of the new, wider type. 10149 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10150 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10151 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 10152 10153 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10154 10155 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10156 CE->getCastKind() == CK_BooleanToSignedIntegral; 10157 10158 // Assume that non-integer casts can span the full range of the type. 10159 if (!isIntegerCast) 10160 return OutputTypeRange; 10161 10162 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10163 std::min(MaxWidth, OutputTypeRange.Width), 10164 InConstantContext); 10165 10166 // Bail out if the subexpr's range is as wide as the cast type. 10167 if (SubRange.Width >= OutputTypeRange.Width) 10168 return OutputTypeRange; 10169 10170 // Otherwise, we take the smaller width, and we're non-negative if 10171 // either the output type or the subexpr is. 10172 return IntRange(SubRange.Width, 10173 SubRange.NonNegative || OutputTypeRange.NonNegative); 10174 } 10175 10176 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10177 // If we can fold the condition, just take that operand. 10178 bool CondResult; 10179 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10180 return GetExprRange(C, 10181 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10182 MaxWidth, InConstantContext); 10183 10184 // Otherwise, conservatively merge. 10185 IntRange L = 10186 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 10187 IntRange R = 10188 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 10189 return IntRange::join(L, R); 10190 } 10191 10192 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10193 switch (BO->getOpcode()) { 10194 case BO_Cmp: 10195 llvm_unreachable("builtin <=> should have class type"); 10196 10197 // Boolean-valued operations are single-bit and positive. 10198 case BO_LAnd: 10199 case BO_LOr: 10200 case BO_LT: 10201 case BO_GT: 10202 case BO_LE: 10203 case BO_GE: 10204 case BO_EQ: 10205 case BO_NE: 10206 return IntRange::forBoolType(); 10207 10208 // The type of the assignments is the type of the LHS, so the RHS 10209 // is not necessarily the same type. 10210 case BO_MulAssign: 10211 case BO_DivAssign: 10212 case BO_RemAssign: 10213 case BO_AddAssign: 10214 case BO_SubAssign: 10215 case BO_XorAssign: 10216 case BO_OrAssign: 10217 // TODO: bitfields? 10218 return IntRange::forValueOfType(C, GetExprType(E)); 10219 10220 // Simple assignments just pass through the RHS, which will have 10221 // been coerced to the LHS type. 10222 case BO_Assign: 10223 // TODO: bitfields? 10224 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10225 10226 // Operations with opaque sources are black-listed. 10227 case BO_PtrMemD: 10228 case BO_PtrMemI: 10229 return IntRange::forValueOfType(C, GetExprType(E)); 10230 10231 // Bitwise-and uses the *infinum* of the two source ranges. 10232 case BO_And: 10233 case BO_AndAssign: 10234 return IntRange::meet( 10235 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10236 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10237 10238 // Left shift gets black-listed based on a judgement call. 10239 case BO_Shl: 10240 // ...except that we want to treat '1 << (blah)' as logically 10241 // positive. It's an important idiom. 10242 if (IntegerLiteral *I 10243 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10244 if (I->getValue() == 1) { 10245 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10246 return IntRange(R.Width, /*NonNegative*/ true); 10247 } 10248 } 10249 LLVM_FALLTHROUGH; 10250 10251 case BO_ShlAssign: 10252 return IntRange::forValueOfType(C, GetExprType(E)); 10253 10254 // Right shift by a constant can narrow its left argument. 10255 case BO_Shr: 10256 case BO_ShrAssign: { 10257 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10258 10259 // If the shift amount is a positive constant, drop the width by 10260 // that much. 10261 llvm::APSInt shift; 10262 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 10263 shift.isNonNegative()) { 10264 unsigned zext = shift.getZExtValue(); 10265 if (zext >= L.Width) 10266 L.Width = (L.NonNegative ? 0 : 1); 10267 else 10268 L.Width -= zext; 10269 } 10270 10271 return L; 10272 } 10273 10274 // Comma acts as its right operand. 10275 case BO_Comma: 10276 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10277 10278 // Black-list pointer subtractions. 10279 case BO_Sub: 10280 if (BO->getLHS()->getType()->isPointerType()) 10281 return IntRange::forValueOfType(C, GetExprType(E)); 10282 break; 10283 10284 // The width of a division result is mostly determined by the size 10285 // of the LHS. 10286 case BO_Div: { 10287 // Don't 'pre-truncate' the operands. 10288 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10289 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10290 10291 // If the divisor is constant, use that. 10292 llvm::APSInt divisor; 10293 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 10294 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 10295 if (log2 >= L.Width) 10296 L.Width = (L.NonNegative ? 0 : 1); 10297 else 10298 L.Width = std::min(L.Width - log2, MaxWidth); 10299 return L; 10300 } 10301 10302 // Otherwise, just use the LHS's width. 10303 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10304 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10305 } 10306 10307 // The result of a remainder can't be larger than the result of 10308 // either side. 10309 case BO_Rem: { 10310 // Don't 'pre-truncate' the operands. 10311 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10312 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10313 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10314 10315 IntRange meet = IntRange::meet(L, R); 10316 meet.Width = std::min(meet.Width, MaxWidth); 10317 return meet; 10318 } 10319 10320 // The default behavior is okay for these. 10321 case BO_Mul: 10322 case BO_Add: 10323 case BO_Xor: 10324 case BO_Or: 10325 break; 10326 } 10327 10328 // The default case is to treat the operation as if it were closed 10329 // on the narrowest type that encompasses both operands. 10330 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10331 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10332 return IntRange::join(L, R); 10333 } 10334 10335 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10336 switch (UO->getOpcode()) { 10337 // Boolean-valued operations are white-listed. 10338 case UO_LNot: 10339 return IntRange::forBoolType(); 10340 10341 // Operations with opaque sources are black-listed. 10342 case UO_Deref: 10343 case UO_AddrOf: // should be impossible 10344 return IntRange::forValueOfType(C, GetExprType(E)); 10345 10346 default: 10347 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10348 } 10349 } 10350 10351 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10352 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10353 10354 if (const auto *BitField = E->getSourceBitField()) 10355 return IntRange(BitField->getBitWidthValue(C), 10356 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10357 10358 return IntRange::forValueOfType(C, GetExprType(E)); 10359 } 10360 10361 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10362 bool InConstantContext) { 10363 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10364 } 10365 10366 /// Checks whether the given value, which currently has the given 10367 /// source semantics, has the same value when coerced through the 10368 /// target semantics. 10369 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10370 const llvm::fltSemantics &Src, 10371 const llvm::fltSemantics &Tgt) { 10372 llvm::APFloat truncated = value; 10373 10374 bool ignored; 10375 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10376 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10377 10378 return truncated.bitwiseIsEqual(value); 10379 } 10380 10381 /// Checks whether the given value, which currently has the given 10382 /// source semantics, has the same value when coerced through the 10383 /// target semantics. 10384 /// 10385 /// The value might be a vector of floats (or a complex number). 10386 static bool IsSameFloatAfterCast(const APValue &value, 10387 const llvm::fltSemantics &Src, 10388 const llvm::fltSemantics &Tgt) { 10389 if (value.isFloat()) 10390 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10391 10392 if (value.isVector()) { 10393 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10394 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10395 return false; 10396 return true; 10397 } 10398 10399 assert(value.isComplexFloat()); 10400 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10401 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10402 } 10403 10404 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10405 bool IsListInit = false); 10406 10407 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10408 // Suppress cases where we are comparing against an enum constant. 10409 if (const DeclRefExpr *DR = 10410 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10411 if (isa<EnumConstantDecl>(DR->getDecl())) 10412 return true; 10413 10414 // Suppress cases where the value is expanded from a macro, unless that macro 10415 // is how a language represents a boolean literal. This is the case in both C 10416 // and Objective-C. 10417 SourceLocation BeginLoc = E->getBeginLoc(); 10418 if (BeginLoc.isMacroID()) { 10419 StringRef MacroName = Lexer::getImmediateMacroName( 10420 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10421 return MacroName != "YES" && MacroName != "NO" && 10422 MacroName != "true" && MacroName != "false"; 10423 } 10424 10425 return false; 10426 } 10427 10428 static bool isKnownToHaveUnsignedValue(Expr *E) { 10429 return E->getType()->isIntegerType() && 10430 (!E->getType()->isSignedIntegerType() || 10431 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10432 } 10433 10434 namespace { 10435 /// The promoted range of values of a type. In general this has the 10436 /// following structure: 10437 /// 10438 /// |-----------| . . . |-----------| 10439 /// ^ ^ ^ ^ 10440 /// Min HoleMin HoleMax Max 10441 /// 10442 /// ... where there is only a hole if a signed type is promoted to unsigned 10443 /// (in which case Min and Max are the smallest and largest representable 10444 /// values). 10445 struct PromotedRange { 10446 // Min, or HoleMax if there is a hole. 10447 llvm::APSInt PromotedMin; 10448 // Max, or HoleMin if there is a hole. 10449 llvm::APSInt PromotedMax; 10450 10451 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10452 if (R.Width == 0) 10453 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10454 else if (R.Width >= BitWidth && !Unsigned) { 10455 // Promotion made the type *narrower*. This happens when promoting 10456 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10457 // Treat all values of 'signed int' as being in range for now. 10458 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10459 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10460 } else { 10461 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10462 .extOrTrunc(BitWidth); 10463 PromotedMin.setIsUnsigned(Unsigned); 10464 10465 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10466 .extOrTrunc(BitWidth); 10467 PromotedMax.setIsUnsigned(Unsigned); 10468 } 10469 } 10470 10471 // Determine whether this range is contiguous (has no hole). 10472 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10473 10474 // Where a constant value is within the range. 10475 enum ComparisonResult { 10476 LT = 0x1, 10477 LE = 0x2, 10478 GT = 0x4, 10479 GE = 0x8, 10480 EQ = 0x10, 10481 NE = 0x20, 10482 InRangeFlag = 0x40, 10483 10484 Less = LE | LT | NE, 10485 Min = LE | InRangeFlag, 10486 InRange = InRangeFlag, 10487 Max = GE | InRangeFlag, 10488 Greater = GE | GT | NE, 10489 10490 OnlyValue = LE | GE | EQ | InRangeFlag, 10491 InHole = NE 10492 }; 10493 10494 ComparisonResult compare(const llvm::APSInt &Value) const { 10495 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10496 Value.isUnsigned() == PromotedMin.isUnsigned()); 10497 if (!isContiguous()) { 10498 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10499 if (Value.isMinValue()) return Min; 10500 if (Value.isMaxValue()) return Max; 10501 if (Value >= PromotedMin) return InRange; 10502 if (Value <= PromotedMax) return InRange; 10503 return InHole; 10504 } 10505 10506 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10507 case -1: return Less; 10508 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10509 case 1: 10510 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10511 case -1: return InRange; 10512 case 0: return Max; 10513 case 1: return Greater; 10514 } 10515 } 10516 10517 llvm_unreachable("impossible compare result"); 10518 } 10519 10520 static llvm::Optional<StringRef> 10521 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10522 if (Op == BO_Cmp) { 10523 ComparisonResult LTFlag = LT, GTFlag = GT; 10524 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10525 10526 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10527 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10528 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10529 return llvm::None; 10530 } 10531 10532 ComparisonResult TrueFlag, FalseFlag; 10533 if (Op == BO_EQ) { 10534 TrueFlag = EQ; 10535 FalseFlag = NE; 10536 } else if (Op == BO_NE) { 10537 TrueFlag = NE; 10538 FalseFlag = EQ; 10539 } else { 10540 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10541 TrueFlag = LT; 10542 FalseFlag = GE; 10543 } else { 10544 TrueFlag = GT; 10545 FalseFlag = LE; 10546 } 10547 if (Op == BO_GE || Op == BO_LE) 10548 std::swap(TrueFlag, FalseFlag); 10549 } 10550 if (R & TrueFlag) 10551 return StringRef("true"); 10552 if (R & FalseFlag) 10553 return StringRef("false"); 10554 return llvm::None; 10555 } 10556 }; 10557 } 10558 10559 static bool HasEnumType(Expr *E) { 10560 // Strip off implicit integral promotions. 10561 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10562 if (ICE->getCastKind() != CK_IntegralCast && 10563 ICE->getCastKind() != CK_NoOp) 10564 break; 10565 E = ICE->getSubExpr(); 10566 } 10567 10568 return E->getType()->isEnumeralType(); 10569 } 10570 10571 static int classifyConstantValue(Expr *Constant) { 10572 // The values of this enumeration are used in the diagnostics 10573 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10574 enum ConstantValueKind { 10575 Miscellaneous = 0, 10576 LiteralTrue, 10577 LiteralFalse 10578 }; 10579 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10580 return BL->getValue() ? ConstantValueKind::LiteralTrue 10581 : ConstantValueKind::LiteralFalse; 10582 return ConstantValueKind::Miscellaneous; 10583 } 10584 10585 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10586 Expr *Constant, Expr *Other, 10587 const llvm::APSInt &Value, 10588 bool RhsConstant) { 10589 if (S.inTemplateInstantiation()) 10590 return false; 10591 10592 Expr *OriginalOther = Other; 10593 10594 Constant = Constant->IgnoreParenImpCasts(); 10595 Other = Other->IgnoreParenImpCasts(); 10596 10597 // Suppress warnings on tautological comparisons between values of the same 10598 // enumeration type. There are only two ways we could warn on this: 10599 // - If the constant is outside the range of representable values of 10600 // the enumeration. In such a case, we should warn about the cast 10601 // to enumeration type, not about the comparison. 10602 // - If the constant is the maximum / minimum in-range value. For an 10603 // enumeratin type, such comparisons can be meaningful and useful. 10604 if (Constant->getType()->isEnumeralType() && 10605 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10606 return false; 10607 10608 // TODO: Investigate using GetExprRange() to get tighter bounds 10609 // on the bit ranges. 10610 QualType OtherT = Other->getType(); 10611 if (const auto *AT = OtherT->getAs<AtomicType>()) 10612 OtherT = AT->getValueType(); 10613 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10614 10615 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10616 // (Namely, macOS). 10617 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10618 S.NSAPIObj->isObjCBOOLType(OtherT) && 10619 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10620 10621 // Whether we're treating Other as being a bool because of the form of 10622 // expression despite it having another type (typically 'int' in C). 10623 bool OtherIsBooleanDespiteType = 10624 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10625 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10626 OtherRange = IntRange::forBoolType(); 10627 10628 // Determine the promoted range of the other type and see if a comparison of 10629 // the constant against that range is tautological. 10630 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10631 Value.isUnsigned()); 10632 auto Cmp = OtherPromotedRange.compare(Value); 10633 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10634 if (!Result) 10635 return false; 10636 10637 // Suppress the diagnostic for an in-range comparison if the constant comes 10638 // from a macro or enumerator. We don't want to diagnose 10639 // 10640 // some_long_value <= INT_MAX 10641 // 10642 // when sizeof(int) == sizeof(long). 10643 bool InRange = Cmp & PromotedRange::InRangeFlag; 10644 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10645 return false; 10646 10647 // If this is a comparison to an enum constant, include that 10648 // constant in the diagnostic. 10649 const EnumConstantDecl *ED = nullptr; 10650 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10651 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10652 10653 // Should be enough for uint128 (39 decimal digits) 10654 SmallString<64> PrettySourceValue; 10655 llvm::raw_svector_ostream OS(PrettySourceValue); 10656 if (ED) { 10657 OS << '\'' << *ED << "' (" << Value << ")"; 10658 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10659 Constant->IgnoreParenImpCasts())) { 10660 OS << (BL->getValue() ? "YES" : "NO"); 10661 } else { 10662 OS << Value; 10663 } 10664 10665 if (IsObjCSignedCharBool) { 10666 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10667 S.PDiag(diag::warn_tautological_compare_objc_bool) 10668 << OS.str() << *Result); 10669 return true; 10670 } 10671 10672 // FIXME: We use a somewhat different formatting for the in-range cases and 10673 // cases involving boolean values for historical reasons. We should pick a 10674 // consistent way of presenting these diagnostics. 10675 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10676 10677 S.DiagRuntimeBehavior( 10678 E->getOperatorLoc(), E, 10679 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10680 : diag::warn_tautological_bool_compare) 10681 << OS.str() << classifyConstantValue(Constant) << OtherT 10682 << OtherIsBooleanDespiteType << *Result 10683 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10684 } else { 10685 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10686 ? (HasEnumType(OriginalOther) 10687 ? diag::warn_unsigned_enum_always_true_comparison 10688 : diag::warn_unsigned_always_true_comparison) 10689 : diag::warn_tautological_constant_compare; 10690 10691 S.Diag(E->getOperatorLoc(), Diag) 10692 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10693 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10694 } 10695 10696 return true; 10697 } 10698 10699 /// Analyze the operands of the given comparison. Implements the 10700 /// fallback case from AnalyzeComparison. 10701 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10702 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10703 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10704 } 10705 10706 /// Implements -Wsign-compare. 10707 /// 10708 /// \param E the binary operator to check for warnings 10709 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10710 // The type the comparison is being performed in. 10711 QualType T = E->getLHS()->getType(); 10712 10713 // Only analyze comparison operators where both sides have been converted to 10714 // the same type. 10715 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10716 return AnalyzeImpConvsInComparison(S, E); 10717 10718 // Don't analyze value-dependent comparisons directly. 10719 if (E->isValueDependent()) 10720 return AnalyzeImpConvsInComparison(S, E); 10721 10722 Expr *LHS = E->getLHS(); 10723 Expr *RHS = E->getRHS(); 10724 10725 if (T->isIntegralType(S.Context)) { 10726 llvm::APSInt RHSValue; 10727 llvm::APSInt LHSValue; 10728 10729 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10730 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10731 10732 // We don't care about expressions whose result is a constant. 10733 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10734 return AnalyzeImpConvsInComparison(S, E); 10735 10736 // We only care about expressions where just one side is literal 10737 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10738 // Is the constant on the RHS or LHS? 10739 const bool RhsConstant = IsRHSIntegralLiteral; 10740 Expr *Const = RhsConstant ? RHS : LHS; 10741 Expr *Other = RhsConstant ? LHS : RHS; 10742 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10743 10744 // Check whether an integer constant comparison results in a value 10745 // of 'true' or 'false'. 10746 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10747 return AnalyzeImpConvsInComparison(S, E); 10748 } 10749 } 10750 10751 if (!T->hasUnsignedIntegerRepresentation()) { 10752 // We don't do anything special if this isn't an unsigned integral 10753 // comparison: we're only interested in integral comparisons, and 10754 // signed comparisons only happen in cases we don't care to warn about. 10755 return AnalyzeImpConvsInComparison(S, E); 10756 } 10757 10758 LHS = LHS->IgnoreParenImpCasts(); 10759 RHS = RHS->IgnoreParenImpCasts(); 10760 10761 if (!S.getLangOpts().CPlusPlus) { 10762 // Avoid warning about comparison of integers with different signs when 10763 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10764 // the type of `E`. 10765 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10766 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10767 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10768 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10769 } 10770 10771 // Check to see if one of the (unmodified) operands is of different 10772 // signedness. 10773 Expr *signedOperand, *unsignedOperand; 10774 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10775 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10776 "unsigned comparison between two signed integer expressions?"); 10777 signedOperand = LHS; 10778 unsignedOperand = RHS; 10779 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10780 signedOperand = RHS; 10781 unsignedOperand = LHS; 10782 } else { 10783 return AnalyzeImpConvsInComparison(S, E); 10784 } 10785 10786 // Otherwise, calculate the effective range of the signed operand. 10787 IntRange signedRange = 10788 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10789 10790 // Go ahead and analyze implicit conversions in the operands. Note 10791 // that we skip the implicit conversions on both sides. 10792 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10793 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10794 10795 // If the signed range is non-negative, -Wsign-compare won't fire. 10796 if (signedRange.NonNegative) 10797 return; 10798 10799 // For (in)equality comparisons, if the unsigned operand is a 10800 // constant which cannot collide with a overflowed signed operand, 10801 // then reinterpreting the signed operand as unsigned will not 10802 // change the result of the comparison. 10803 if (E->isEqualityOp()) { 10804 unsigned comparisonWidth = S.Context.getIntWidth(T); 10805 IntRange unsignedRange = 10806 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10807 10808 // We should never be unable to prove that the unsigned operand is 10809 // non-negative. 10810 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10811 10812 if (unsignedRange.Width < comparisonWidth) 10813 return; 10814 } 10815 10816 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10817 S.PDiag(diag::warn_mixed_sign_comparison) 10818 << LHS->getType() << RHS->getType() 10819 << LHS->getSourceRange() << RHS->getSourceRange()); 10820 } 10821 10822 /// Analyzes an attempt to assign the given value to a bitfield. 10823 /// 10824 /// Returns true if there was something fishy about the attempt. 10825 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10826 SourceLocation InitLoc) { 10827 assert(Bitfield->isBitField()); 10828 if (Bitfield->isInvalidDecl()) 10829 return false; 10830 10831 // White-list bool bitfields. 10832 QualType BitfieldType = Bitfield->getType(); 10833 if (BitfieldType->isBooleanType()) 10834 return false; 10835 10836 if (BitfieldType->isEnumeralType()) { 10837 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10838 // If the underlying enum type was not explicitly specified as an unsigned 10839 // type and the enum contain only positive values, MSVC++ will cause an 10840 // inconsistency by storing this as a signed type. 10841 if (S.getLangOpts().CPlusPlus11 && 10842 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10843 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10844 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10845 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10846 << BitfieldEnumDecl->getNameAsString(); 10847 } 10848 } 10849 10850 if (Bitfield->getType()->isBooleanType()) 10851 return false; 10852 10853 // Ignore value- or type-dependent expressions. 10854 if (Bitfield->getBitWidth()->isValueDependent() || 10855 Bitfield->getBitWidth()->isTypeDependent() || 10856 Init->isValueDependent() || 10857 Init->isTypeDependent()) 10858 return false; 10859 10860 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10861 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10862 10863 Expr::EvalResult Result; 10864 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10865 Expr::SE_AllowSideEffects)) { 10866 // The RHS is not constant. If the RHS has an enum type, make sure the 10867 // bitfield is wide enough to hold all the values of the enum without 10868 // truncation. 10869 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10870 EnumDecl *ED = EnumTy->getDecl(); 10871 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10872 10873 // Enum types are implicitly signed on Windows, so check if there are any 10874 // negative enumerators to see if the enum was intended to be signed or 10875 // not. 10876 bool SignedEnum = ED->getNumNegativeBits() > 0; 10877 10878 // Check for surprising sign changes when assigning enum values to a 10879 // bitfield of different signedness. If the bitfield is signed and we 10880 // have exactly the right number of bits to store this unsigned enum, 10881 // suggest changing the enum to an unsigned type. This typically happens 10882 // on Windows where unfixed enums always use an underlying type of 'int'. 10883 unsigned DiagID = 0; 10884 if (SignedEnum && !SignedBitfield) { 10885 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10886 } else if (SignedBitfield && !SignedEnum && 10887 ED->getNumPositiveBits() == FieldWidth) { 10888 DiagID = diag::warn_signed_bitfield_enum_conversion; 10889 } 10890 10891 if (DiagID) { 10892 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10893 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10894 SourceRange TypeRange = 10895 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10896 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10897 << SignedEnum << TypeRange; 10898 } 10899 10900 // Compute the required bitwidth. If the enum has negative values, we need 10901 // one more bit than the normal number of positive bits to represent the 10902 // sign bit. 10903 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10904 ED->getNumNegativeBits()) 10905 : ED->getNumPositiveBits(); 10906 10907 // Check the bitwidth. 10908 if (BitsNeeded > FieldWidth) { 10909 Expr *WidthExpr = Bitfield->getBitWidth(); 10910 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10911 << Bitfield << ED; 10912 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10913 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10914 } 10915 } 10916 10917 return false; 10918 } 10919 10920 llvm::APSInt Value = Result.Val.getInt(); 10921 10922 unsigned OriginalWidth = Value.getBitWidth(); 10923 10924 if (!Value.isSigned() || Value.isNegative()) 10925 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10926 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10927 OriginalWidth = Value.getMinSignedBits(); 10928 10929 if (OriginalWidth <= FieldWidth) 10930 return false; 10931 10932 // Compute the value which the bitfield will contain. 10933 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10934 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10935 10936 // Check whether the stored value is equal to the original value. 10937 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10938 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10939 return false; 10940 10941 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10942 // therefore don't strictly fit into a signed bitfield of width 1. 10943 if (FieldWidth == 1 && Value == 1) 10944 return false; 10945 10946 std::string PrettyValue = Value.toString(10); 10947 std::string PrettyTrunc = TruncatedValue.toString(10); 10948 10949 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10950 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10951 << Init->getSourceRange(); 10952 10953 return true; 10954 } 10955 10956 /// Analyze the given simple or compound assignment for warning-worthy 10957 /// operations. 10958 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10959 // Just recurse on the LHS. 10960 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10961 10962 // We want to recurse on the RHS as normal unless we're assigning to 10963 // a bitfield. 10964 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10965 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10966 E->getOperatorLoc())) { 10967 // Recurse, ignoring any implicit conversions on the RHS. 10968 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10969 E->getOperatorLoc()); 10970 } 10971 } 10972 10973 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10974 10975 // Diagnose implicitly sequentially-consistent atomic assignment. 10976 if (E->getLHS()->getType()->isAtomicType()) 10977 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10978 } 10979 10980 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10981 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10982 SourceLocation CContext, unsigned diag, 10983 bool pruneControlFlow = false) { 10984 if (pruneControlFlow) { 10985 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10986 S.PDiag(diag) 10987 << SourceType << T << E->getSourceRange() 10988 << SourceRange(CContext)); 10989 return; 10990 } 10991 S.Diag(E->getExprLoc(), diag) 10992 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10993 } 10994 10995 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10996 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10997 SourceLocation CContext, 10998 unsigned diag, bool pruneControlFlow = false) { 10999 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11000 } 11001 11002 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11003 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11004 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11005 } 11006 11007 static void adornObjCBoolConversionDiagWithTernaryFixit( 11008 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11009 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11010 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11011 Ignored = OVE->getSourceExpr(); 11012 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11013 isa<BinaryOperator>(Ignored) || 11014 isa<CXXOperatorCallExpr>(Ignored); 11015 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11016 if (NeedsParens) 11017 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11018 << FixItHint::CreateInsertion(EndLoc, ")"); 11019 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11020 } 11021 11022 /// Diagnose an implicit cast from a floating point value to an integer value. 11023 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11024 SourceLocation CContext) { 11025 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11026 const bool PruneWarnings = S.inTemplateInstantiation(); 11027 11028 Expr *InnerE = E->IgnoreParenImpCasts(); 11029 // We also want to warn on, e.g., "int i = -1.234" 11030 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11031 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11032 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11033 11034 const bool IsLiteral = 11035 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11036 11037 llvm::APFloat Value(0.0); 11038 bool IsConstant = 11039 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11040 if (!IsConstant) { 11041 if (isObjCSignedCharBool(S, T)) { 11042 return adornObjCBoolConversionDiagWithTernaryFixit( 11043 S, E, 11044 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11045 << E->getType()); 11046 } 11047 11048 return DiagnoseImpCast(S, E, T, CContext, 11049 diag::warn_impcast_float_integer, PruneWarnings); 11050 } 11051 11052 bool isExact = false; 11053 11054 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11055 T->hasUnsignedIntegerRepresentation()); 11056 llvm::APFloat::opStatus Result = Value.convertToInteger( 11057 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11058 11059 // FIXME: Force the precision of the source value down so we don't print 11060 // digits which are usually useless (we don't really care here if we 11061 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11062 // would automatically print the shortest representation, but it's a bit 11063 // tricky to implement. 11064 SmallString<16> PrettySourceValue; 11065 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11066 precision = (precision * 59 + 195) / 196; 11067 Value.toString(PrettySourceValue, precision); 11068 11069 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11070 return adornObjCBoolConversionDiagWithTernaryFixit( 11071 S, E, 11072 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11073 << PrettySourceValue); 11074 } 11075 11076 if (Result == llvm::APFloat::opOK && isExact) { 11077 if (IsLiteral) return; 11078 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11079 PruneWarnings); 11080 } 11081 11082 // Conversion of a floating-point value to a non-bool integer where the 11083 // integral part cannot be represented by the integer type is undefined. 11084 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11085 return DiagnoseImpCast( 11086 S, E, T, CContext, 11087 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11088 : diag::warn_impcast_float_to_integer_out_of_range, 11089 PruneWarnings); 11090 11091 unsigned DiagID = 0; 11092 if (IsLiteral) { 11093 // Warn on floating point literal to integer. 11094 DiagID = diag::warn_impcast_literal_float_to_integer; 11095 } else if (IntegerValue == 0) { 11096 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11097 return DiagnoseImpCast(S, E, T, CContext, 11098 diag::warn_impcast_float_integer, PruneWarnings); 11099 } 11100 // Warn on non-zero to zero conversion. 11101 DiagID = diag::warn_impcast_float_to_integer_zero; 11102 } else { 11103 if (IntegerValue.isUnsigned()) { 11104 if (!IntegerValue.isMaxValue()) { 11105 return DiagnoseImpCast(S, E, T, CContext, 11106 diag::warn_impcast_float_integer, PruneWarnings); 11107 } 11108 } else { // IntegerValue.isSigned() 11109 if (!IntegerValue.isMaxSignedValue() && 11110 !IntegerValue.isMinSignedValue()) { 11111 return DiagnoseImpCast(S, E, T, CContext, 11112 diag::warn_impcast_float_integer, PruneWarnings); 11113 } 11114 } 11115 // Warn on evaluatable floating point expression to integer conversion. 11116 DiagID = diag::warn_impcast_float_to_integer; 11117 } 11118 11119 SmallString<16> PrettyTargetValue; 11120 if (IsBool) 11121 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11122 else 11123 IntegerValue.toString(PrettyTargetValue); 11124 11125 if (PruneWarnings) { 11126 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11127 S.PDiag(DiagID) 11128 << E->getType() << T.getUnqualifiedType() 11129 << PrettySourceValue << PrettyTargetValue 11130 << E->getSourceRange() << SourceRange(CContext)); 11131 } else { 11132 S.Diag(E->getExprLoc(), DiagID) 11133 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11134 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11135 } 11136 } 11137 11138 /// Analyze the given compound assignment for the possible losing of 11139 /// floating-point precision. 11140 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11141 assert(isa<CompoundAssignOperator>(E) && 11142 "Must be compound assignment operation"); 11143 // Recurse on the LHS and RHS in here 11144 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11145 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11146 11147 if (E->getLHS()->getType()->isAtomicType()) 11148 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11149 11150 // Now check the outermost expression 11151 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11152 const auto *RBT = cast<CompoundAssignOperator>(E) 11153 ->getComputationResultType() 11154 ->getAs<BuiltinType>(); 11155 11156 // The below checks assume source is floating point. 11157 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11158 11159 // If source is floating point but target is an integer. 11160 if (ResultBT->isInteger()) 11161 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11162 E->getExprLoc(), diag::warn_impcast_float_integer); 11163 11164 if (!ResultBT->isFloatingPoint()) 11165 return; 11166 11167 // If both source and target are floating points, warn about losing precision. 11168 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11169 QualType(ResultBT, 0), QualType(RBT, 0)); 11170 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11171 // warn about dropping FP rank. 11172 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11173 diag::warn_impcast_float_result_precision); 11174 } 11175 11176 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11177 IntRange Range) { 11178 if (!Range.Width) return "0"; 11179 11180 llvm::APSInt ValueInRange = Value; 11181 ValueInRange.setIsSigned(!Range.NonNegative); 11182 ValueInRange = ValueInRange.trunc(Range.Width); 11183 return ValueInRange.toString(10); 11184 } 11185 11186 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11187 if (!isa<ImplicitCastExpr>(Ex)) 11188 return false; 11189 11190 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11191 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11192 const Type *Source = 11193 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11194 if (Target->isDependentType()) 11195 return false; 11196 11197 const BuiltinType *FloatCandidateBT = 11198 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11199 const Type *BoolCandidateType = ToBool ? Target : Source; 11200 11201 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11202 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11203 } 11204 11205 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11206 SourceLocation CC) { 11207 unsigned NumArgs = TheCall->getNumArgs(); 11208 for (unsigned i = 0; i < NumArgs; ++i) { 11209 Expr *CurrA = TheCall->getArg(i); 11210 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11211 continue; 11212 11213 bool IsSwapped = ((i > 0) && 11214 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11215 IsSwapped |= ((i < (NumArgs - 1)) && 11216 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11217 if (IsSwapped) { 11218 // Warn on this floating-point to bool conversion. 11219 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11220 CurrA->getType(), CC, 11221 diag::warn_impcast_floating_point_to_bool); 11222 } 11223 } 11224 } 11225 11226 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11227 SourceLocation CC) { 11228 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11229 E->getExprLoc())) 11230 return; 11231 11232 // Don't warn on functions which have return type nullptr_t. 11233 if (isa<CallExpr>(E)) 11234 return; 11235 11236 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11237 const Expr::NullPointerConstantKind NullKind = 11238 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11239 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11240 return; 11241 11242 // Return if target type is a safe conversion. 11243 if (T->isAnyPointerType() || T->isBlockPointerType() || 11244 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11245 return; 11246 11247 SourceLocation Loc = E->getSourceRange().getBegin(); 11248 11249 // Venture through the macro stacks to get to the source of macro arguments. 11250 // The new location is a better location than the complete location that was 11251 // passed in. 11252 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11253 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11254 11255 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11256 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11257 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11258 Loc, S.SourceMgr, S.getLangOpts()); 11259 if (MacroName == "NULL") 11260 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11261 } 11262 11263 // Only warn if the null and context location are in the same macro expansion. 11264 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11265 return; 11266 11267 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11268 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11269 << FixItHint::CreateReplacement(Loc, 11270 S.getFixItZeroLiteralForType(T, Loc)); 11271 } 11272 11273 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11274 ObjCArrayLiteral *ArrayLiteral); 11275 11276 static void 11277 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11278 ObjCDictionaryLiteral *DictionaryLiteral); 11279 11280 /// Check a single element within a collection literal against the 11281 /// target element type. 11282 static void checkObjCCollectionLiteralElement(Sema &S, 11283 QualType TargetElementType, 11284 Expr *Element, 11285 unsigned ElementKind) { 11286 // Skip a bitcast to 'id' or qualified 'id'. 11287 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11288 if (ICE->getCastKind() == CK_BitCast && 11289 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11290 Element = ICE->getSubExpr(); 11291 } 11292 11293 QualType ElementType = Element->getType(); 11294 ExprResult ElementResult(Element); 11295 if (ElementType->getAs<ObjCObjectPointerType>() && 11296 S.CheckSingleAssignmentConstraints(TargetElementType, 11297 ElementResult, 11298 false, false) 11299 != Sema::Compatible) { 11300 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11301 << ElementType << ElementKind << TargetElementType 11302 << Element->getSourceRange(); 11303 } 11304 11305 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11306 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11307 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11308 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11309 } 11310 11311 /// Check an Objective-C array literal being converted to the given 11312 /// target type. 11313 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11314 ObjCArrayLiteral *ArrayLiteral) { 11315 if (!S.NSArrayDecl) 11316 return; 11317 11318 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11319 if (!TargetObjCPtr) 11320 return; 11321 11322 if (TargetObjCPtr->isUnspecialized() || 11323 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11324 != S.NSArrayDecl->getCanonicalDecl()) 11325 return; 11326 11327 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11328 if (TypeArgs.size() != 1) 11329 return; 11330 11331 QualType TargetElementType = TypeArgs[0]; 11332 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11333 checkObjCCollectionLiteralElement(S, TargetElementType, 11334 ArrayLiteral->getElement(I), 11335 0); 11336 } 11337 } 11338 11339 /// Check an Objective-C dictionary literal being converted to the given 11340 /// target type. 11341 static void 11342 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11343 ObjCDictionaryLiteral *DictionaryLiteral) { 11344 if (!S.NSDictionaryDecl) 11345 return; 11346 11347 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11348 if (!TargetObjCPtr) 11349 return; 11350 11351 if (TargetObjCPtr->isUnspecialized() || 11352 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11353 != S.NSDictionaryDecl->getCanonicalDecl()) 11354 return; 11355 11356 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11357 if (TypeArgs.size() != 2) 11358 return; 11359 11360 QualType TargetKeyType = TypeArgs[0]; 11361 QualType TargetObjectType = TypeArgs[1]; 11362 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11363 auto Element = DictionaryLiteral->getKeyValueElement(I); 11364 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11365 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11366 } 11367 } 11368 11369 // Helper function to filter out cases for constant width constant conversion. 11370 // Don't warn on char array initialization or for non-decimal values. 11371 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11372 SourceLocation CC) { 11373 // If initializing from a constant, and the constant starts with '0', 11374 // then it is a binary, octal, or hexadecimal. Allow these constants 11375 // to fill all the bits, even if there is a sign change. 11376 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11377 const char FirstLiteralCharacter = 11378 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11379 if (FirstLiteralCharacter == '0') 11380 return false; 11381 } 11382 11383 // If the CC location points to a '{', and the type is char, then assume 11384 // assume it is an array initialization. 11385 if (CC.isValid() && T->isCharType()) { 11386 const char FirstContextCharacter = 11387 S.getSourceManager().getCharacterData(CC)[0]; 11388 if (FirstContextCharacter == '{') 11389 return false; 11390 } 11391 11392 return true; 11393 } 11394 11395 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11396 const auto *IL = dyn_cast<IntegerLiteral>(E); 11397 if (!IL) { 11398 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11399 if (UO->getOpcode() == UO_Minus) 11400 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11401 } 11402 } 11403 11404 return IL; 11405 } 11406 11407 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11408 E = E->IgnoreParenImpCasts(); 11409 SourceLocation ExprLoc = E->getExprLoc(); 11410 11411 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11412 BinaryOperator::Opcode Opc = BO->getOpcode(); 11413 Expr::EvalResult Result; 11414 // Do not diagnose unsigned shifts. 11415 if (Opc == BO_Shl) { 11416 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11417 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11418 if (LHS && LHS->getValue() == 0) 11419 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11420 else if (!E->isValueDependent() && LHS && RHS && 11421 RHS->getValue().isNonNegative() && 11422 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11423 S.Diag(ExprLoc, diag::warn_left_shift_always) 11424 << (Result.Val.getInt() != 0); 11425 else if (E->getType()->isSignedIntegerType()) 11426 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11427 } 11428 } 11429 11430 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11431 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11432 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11433 if (!LHS || !RHS) 11434 return; 11435 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11436 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11437 // Do not diagnose common idioms. 11438 return; 11439 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11440 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11441 } 11442 } 11443 11444 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11445 SourceLocation CC, 11446 bool *ICContext = nullptr, 11447 bool IsListInit = false) { 11448 if (E->isTypeDependent() || E->isValueDependent()) return; 11449 11450 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11451 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11452 if (Source == Target) return; 11453 if (Target->isDependentType()) return; 11454 11455 // If the conversion context location is invalid don't complain. We also 11456 // don't want to emit a warning if the issue occurs from the expansion of 11457 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11458 // delay this check as long as possible. Once we detect we are in that 11459 // scenario, we just return. 11460 if (CC.isInvalid()) 11461 return; 11462 11463 if (Source->isAtomicType()) 11464 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11465 11466 // Diagnose implicit casts to bool. 11467 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11468 if (isa<StringLiteral>(E)) 11469 // Warn on string literal to bool. Checks for string literals in logical 11470 // and expressions, for instance, assert(0 && "error here"), are 11471 // prevented by a check in AnalyzeImplicitConversions(). 11472 return DiagnoseImpCast(S, E, T, CC, 11473 diag::warn_impcast_string_literal_to_bool); 11474 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11475 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11476 // This covers the literal expressions that evaluate to Objective-C 11477 // objects. 11478 return DiagnoseImpCast(S, E, T, CC, 11479 diag::warn_impcast_objective_c_literal_to_bool); 11480 } 11481 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11482 // Warn on pointer to bool conversion that is always true. 11483 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11484 SourceRange(CC)); 11485 } 11486 } 11487 11488 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11489 // is a typedef for signed char (macOS), then that constant value has to be 1 11490 // or 0. 11491 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11492 Expr::EvalResult Result; 11493 if (E->EvaluateAsInt(Result, S.getASTContext(), 11494 Expr::SE_AllowSideEffects)) { 11495 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11496 adornObjCBoolConversionDiagWithTernaryFixit( 11497 S, E, 11498 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11499 << Result.Val.getInt().toString(10)); 11500 } 11501 return; 11502 } 11503 } 11504 11505 // Check implicit casts from Objective-C collection literals to specialized 11506 // collection types, e.g., NSArray<NSString *> *. 11507 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11508 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11509 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11510 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11511 11512 // Strip vector types. 11513 if (isa<VectorType>(Source)) { 11514 if (!isa<VectorType>(Target)) { 11515 if (S.SourceMgr.isInSystemMacro(CC)) 11516 return; 11517 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11518 } 11519 11520 // If the vector cast is cast between two vectors of the same size, it is 11521 // a bitcast, not a conversion. 11522 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11523 return; 11524 11525 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11526 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11527 } 11528 if (auto VecTy = dyn_cast<VectorType>(Target)) 11529 Target = VecTy->getElementType().getTypePtr(); 11530 11531 // Strip complex types. 11532 if (isa<ComplexType>(Source)) { 11533 if (!isa<ComplexType>(Target)) { 11534 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11535 return; 11536 11537 return DiagnoseImpCast(S, E, T, CC, 11538 S.getLangOpts().CPlusPlus 11539 ? diag::err_impcast_complex_scalar 11540 : diag::warn_impcast_complex_scalar); 11541 } 11542 11543 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11544 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11545 } 11546 11547 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11548 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11549 11550 // If the source is floating point... 11551 if (SourceBT && SourceBT->isFloatingPoint()) { 11552 // ...and the target is floating point... 11553 if (TargetBT && TargetBT->isFloatingPoint()) { 11554 // ...then warn if we're dropping FP rank. 11555 11556 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11557 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11558 if (Order > 0) { 11559 // Don't warn about float constants that are precisely 11560 // representable in the target type. 11561 Expr::EvalResult result; 11562 if (E->EvaluateAsRValue(result, S.Context)) { 11563 // Value might be a float, a float vector, or a float complex. 11564 if (IsSameFloatAfterCast(result.Val, 11565 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11566 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11567 return; 11568 } 11569 11570 if (S.SourceMgr.isInSystemMacro(CC)) 11571 return; 11572 11573 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11574 } 11575 // ... or possibly if we're increasing rank, too 11576 else if (Order < 0) { 11577 if (S.SourceMgr.isInSystemMacro(CC)) 11578 return; 11579 11580 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11581 } 11582 return; 11583 } 11584 11585 // If the target is integral, always warn. 11586 if (TargetBT && TargetBT->isInteger()) { 11587 if (S.SourceMgr.isInSystemMacro(CC)) 11588 return; 11589 11590 DiagnoseFloatingImpCast(S, E, T, CC); 11591 } 11592 11593 // Detect the case where a call result is converted from floating-point to 11594 // to bool, and the final argument to the call is converted from bool, to 11595 // discover this typo: 11596 // 11597 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11598 // 11599 // FIXME: This is an incredibly special case; is there some more general 11600 // way to detect this class of misplaced-parentheses bug? 11601 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11602 // Check last argument of function call to see if it is an 11603 // implicit cast from a type matching the type the result 11604 // is being cast to. 11605 CallExpr *CEx = cast<CallExpr>(E); 11606 if (unsigned NumArgs = CEx->getNumArgs()) { 11607 Expr *LastA = CEx->getArg(NumArgs - 1); 11608 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11609 if (isa<ImplicitCastExpr>(LastA) && 11610 InnerE->getType()->isBooleanType()) { 11611 // Warn on this floating-point to bool conversion 11612 DiagnoseImpCast(S, E, T, CC, 11613 diag::warn_impcast_floating_point_to_bool); 11614 } 11615 } 11616 } 11617 return; 11618 } 11619 11620 // Valid casts involving fixed point types should be accounted for here. 11621 if (Source->isFixedPointType()) { 11622 if (Target->isUnsaturatedFixedPointType()) { 11623 Expr::EvalResult Result; 11624 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11625 S.isConstantEvaluated())) { 11626 APFixedPoint Value = Result.Val.getFixedPoint(); 11627 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11628 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11629 if (Value > MaxVal || Value < MinVal) { 11630 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11631 S.PDiag(diag::warn_impcast_fixed_point_range) 11632 << Value.toString() << T 11633 << E->getSourceRange() 11634 << clang::SourceRange(CC)); 11635 return; 11636 } 11637 } 11638 } else if (Target->isIntegerType()) { 11639 Expr::EvalResult Result; 11640 if (!S.isConstantEvaluated() && 11641 E->EvaluateAsFixedPoint(Result, S.Context, 11642 Expr::SE_AllowSideEffects)) { 11643 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11644 11645 bool Overflowed; 11646 llvm::APSInt IntResult = FXResult.convertToInt( 11647 S.Context.getIntWidth(T), 11648 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11649 11650 if (Overflowed) { 11651 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11652 S.PDiag(diag::warn_impcast_fixed_point_range) 11653 << FXResult.toString() << T 11654 << E->getSourceRange() 11655 << clang::SourceRange(CC)); 11656 return; 11657 } 11658 } 11659 } 11660 } else if (Target->isUnsaturatedFixedPointType()) { 11661 if (Source->isIntegerType()) { 11662 Expr::EvalResult Result; 11663 if (!S.isConstantEvaluated() && 11664 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11665 llvm::APSInt Value = Result.Val.getInt(); 11666 11667 bool Overflowed; 11668 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11669 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11670 11671 if (Overflowed) { 11672 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11673 S.PDiag(diag::warn_impcast_fixed_point_range) 11674 << Value.toString(/*Radix=*/10) << T 11675 << E->getSourceRange() 11676 << clang::SourceRange(CC)); 11677 return; 11678 } 11679 } 11680 } 11681 } 11682 11683 // If we are casting an integer type to a floating point type without 11684 // initialization-list syntax, we might lose accuracy if the floating 11685 // point type has a narrower significand than the integer type. 11686 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11687 TargetBT->isFloatingType() && !IsListInit) { 11688 // Determine the number of precision bits in the source integer type. 11689 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11690 unsigned int SourcePrecision = SourceRange.Width; 11691 11692 // Determine the number of precision bits in the 11693 // target floating point type. 11694 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11695 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11696 11697 if (SourcePrecision > 0 && TargetPrecision > 0 && 11698 SourcePrecision > TargetPrecision) { 11699 11700 llvm::APSInt SourceInt; 11701 if (E->isIntegerConstantExpr(SourceInt, S.Context)) { 11702 // If the source integer is a constant, convert it to the target 11703 // floating point type. Issue a warning if the value changes 11704 // during the whole conversion. 11705 llvm::APFloat TargetFloatValue( 11706 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11707 llvm::APFloat::opStatus ConversionStatus = 11708 TargetFloatValue.convertFromAPInt( 11709 SourceInt, SourceBT->isSignedInteger(), 11710 llvm::APFloat::rmNearestTiesToEven); 11711 11712 if (ConversionStatus != llvm::APFloat::opOK) { 11713 std::string PrettySourceValue = SourceInt.toString(10); 11714 SmallString<32> PrettyTargetValue; 11715 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11716 11717 S.DiagRuntimeBehavior( 11718 E->getExprLoc(), E, 11719 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11720 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11721 << E->getSourceRange() << clang::SourceRange(CC)); 11722 } 11723 } else { 11724 // Otherwise, the implicit conversion may lose precision. 11725 DiagnoseImpCast(S, E, T, CC, 11726 diag::warn_impcast_integer_float_precision); 11727 } 11728 } 11729 } 11730 11731 DiagnoseNullConversion(S, E, T, CC); 11732 11733 S.DiscardMisalignedMemberAddress(Target, E); 11734 11735 if (Target->isBooleanType()) 11736 DiagnoseIntInBoolContext(S, E); 11737 11738 if (!Source->isIntegerType() || !Target->isIntegerType()) 11739 return; 11740 11741 // TODO: remove this early return once the false positives for constant->bool 11742 // in templates, macros, etc, are reduced or removed. 11743 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11744 return; 11745 11746 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11747 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11748 return adornObjCBoolConversionDiagWithTernaryFixit( 11749 S, E, 11750 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11751 << E->getType()); 11752 } 11753 11754 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11755 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11756 11757 if (SourceRange.Width > TargetRange.Width) { 11758 // If the source is a constant, use a default-on diagnostic. 11759 // TODO: this should happen for bitfield stores, too. 11760 Expr::EvalResult Result; 11761 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11762 S.isConstantEvaluated())) { 11763 llvm::APSInt Value(32); 11764 Value = Result.Val.getInt(); 11765 11766 if (S.SourceMgr.isInSystemMacro(CC)) 11767 return; 11768 11769 std::string PrettySourceValue = Value.toString(10); 11770 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11771 11772 S.DiagRuntimeBehavior( 11773 E->getExprLoc(), E, 11774 S.PDiag(diag::warn_impcast_integer_precision_constant) 11775 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11776 << E->getSourceRange() << clang::SourceRange(CC)); 11777 return; 11778 } 11779 11780 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11781 if (S.SourceMgr.isInSystemMacro(CC)) 11782 return; 11783 11784 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11785 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11786 /* pruneControlFlow */ true); 11787 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11788 } 11789 11790 if (TargetRange.Width > SourceRange.Width) { 11791 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11792 if (UO->getOpcode() == UO_Minus) 11793 if (Source->isUnsignedIntegerType()) { 11794 if (Target->isUnsignedIntegerType()) 11795 return DiagnoseImpCast(S, E, T, CC, 11796 diag::warn_impcast_high_order_zero_bits); 11797 if (Target->isSignedIntegerType()) 11798 return DiagnoseImpCast(S, E, T, CC, 11799 diag::warn_impcast_nonnegative_result); 11800 } 11801 } 11802 11803 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11804 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11805 // Warn when doing a signed to signed conversion, warn if the positive 11806 // source value is exactly the width of the target type, which will 11807 // cause a negative value to be stored. 11808 11809 Expr::EvalResult Result; 11810 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11811 !S.SourceMgr.isInSystemMacro(CC)) { 11812 llvm::APSInt Value = Result.Val.getInt(); 11813 if (isSameWidthConstantConversion(S, E, T, CC)) { 11814 std::string PrettySourceValue = Value.toString(10); 11815 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11816 11817 S.DiagRuntimeBehavior( 11818 E->getExprLoc(), E, 11819 S.PDiag(diag::warn_impcast_integer_precision_constant) 11820 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11821 << E->getSourceRange() << clang::SourceRange(CC)); 11822 return; 11823 } 11824 } 11825 11826 // Fall through for non-constants to give a sign conversion warning. 11827 } 11828 11829 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11830 (!TargetRange.NonNegative && SourceRange.NonNegative && 11831 SourceRange.Width == TargetRange.Width)) { 11832 if (S.SourceMgr.isInSystemMacro(CC)) 11833 return; 11834 11835 unsigned DiagID = diag::warn_impcast_integer_sign; 11836 11837 // Traditionally, gcc has warned about this under -Wsign-compare. 11838 // We also want to warn about it in -Wconversion. 11839 // So if -Wconversion is off, use a completely identical diagnostic 11840 // in the sign-compare group. 11841 // The conditional-checking code will 11842 if (ICContext) { 11843 DiagID = diag::warn_impcast_integer_sign_conditional; 11844 *ICContext = true; 11845 } 11846 11847 return DiagnoseImpCast(S, E, T, CC, DiagID); 11848 } 11849 11850 // Diagnose conversions between different enumeration types. 11851 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11852 // type, to give us better diagnostics. 11853 QualType SourceType = E->getType(); 11854 if (!S.getLangOpts().CPlusPlus) { 11855 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11856 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11857 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11858 SourceType = S.Context.getTypeDeclType(Enum); 11859 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11860 } 11861 } 11862 11863 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11864 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11865 if (SourceEnum->getDecl()->hasNameForLinkage() && 11866 TargetEnum->getDecl()->hasNameForLinkage() && 11867 SourceEnum != TargetEnum) { 11868 if (S.SourceMgr.isInSystemMacro(CC)) 11869 return; 11870 11871 return DiagnoseImpCast(S, E, SourceType, T, CC, 11872 diag::warn_impcast_different_enum_types); 11873 } 11874 } 11875 11876 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11877 SourceLocation CC, QualType T); 11878 11879 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11880 SourceLocation CC, bool &ICContext) { 11881 E = E->IgnoreParenImpCasts(); 11882 11883 if (isa<ConditionalOperator>(E)) 11884 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11885 11886 AnalyzeImplicitConversions(S, E, CC); 11887 if (E->getType() != T) 11888 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11889 } 11890 11891 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11892 SourceLocation CC, QualType T) { 11893 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11894 11895 bool Suspicious = false; 11896 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11897 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11898 11899 if (T->isBooleanType()) 11900 DiagnoseIntInBoolContext(S, E); 11901 11902 // If -Wconversion would have warned about either of the candidates 11903 // for a signedness conversion to the context type... 11904 if (!Suspicious) return; 11905 11906 // ...but it's currently ignored... 11907 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11908 return; 11909 11910 // ...then check whether it would have warned about either of the 11911 // candidates for a signedness conversion to the condition type. 11912 if (E->getType() == T) return; 11913 11914 Suspicious = false; 11915 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11916 E->getType(), CC, &Suspicious); 11917 if (!Suspicious) 11918 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11919 E->getType(), CC, &Suspicious); 11920 } 11921 11922 /// Check conversion of given expression to boolean. 11923 /// Input argument E is a logical expression. 11924 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11925 if (S.getLangOpts().Bool) 11926 return; 11927 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11928 return; 11929 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11930 } 11931 11932 namespace { 11933 struct AnalyzeImplicitConversionsWorkItem { 11934 Expr *E; 11935 SourceLocation CC; 11936 bool IsListInit; 11937 }; 11938 } 11939 11940 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 11941 /// that should be visited are added to WorkList. 11942 static void AnalyzeImplicitConversions( 11943 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 11944 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 11945 Expr *OrigE = Item.E; 11946 SourceLocation CC = Item.CC; 11947 11948 QualType T = OrigE->getType(); 11949 Expr *E = OrigE->IgnoreParenImpCasts(); 11950 11951 // Propagate whether we are in a C++ list initialization expression. 11952 // If so, we do not issue warnings for implicit int-float conversion 11953 // precision loss, because C++11 narrowing already handles it. 11954 bool IsListInit = Item.IsListInit || 11955 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 11956 11957 if (E->isTypeDependent() || E->isValueDependent()) 11958 return; 11959 11960 Expr *SourceExpr = E; 11961 // Examine, but don't traverse into the source expression of an 11962 // OpaqueValueExpr, since it may have multiple parents and we don't want to 11963 // emit duplicate diagnostics. Its fine to examine the form or attempt to 11964 // evaluate it in the context of checking the specific conversion to T though. 11965 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11966 if (auto *Src = OVE->getSourceExpr()) 11967 SourceExpr = Src; 11968 11969 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 11970 if (UO->getOpcode() == UO_Not && 11971 UO->getSubExpr()->isKnownToHaveBooleanValue()) 11972 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 11973 << OrigE->getSourceRange() << T->isBooleanType() 11974 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 11975 11976 // For conditional operators, we analyze the arguments as if they 11977 // were being fed directly into the output. 11978 if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) { 11979 CheckConditionalOperator(S, CO, CC, T); 11980 return; 11981 } 11982 11983 // Check implicit argument conversions for function calls. 11984 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 11985 CheckImplicitArgumentConversions(S, Call, CC); 11986 11987 // Go ahead and check any implicit conversions we might have skipped. 11988 // The non-canonical typecheck is just an optimization; 11989 // CheckImplicitConversion will filter out dead implicit conversions. 11990 if (SourceExpr->getType() != T) 11991 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 11992 11993 // Now continue drilling into this expression. 11994 11995 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11996 // The bound subexpressions in a PseudoObjectExpr are not reachable 11997 // as transitive children. 11998 // FIXME: Use a more uniform representation for this. 11999 for (auto *SE : POE->semantics()) 12000 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12001 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12002 } 12003 12004 // Skip past explicit casts. 12005 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12006 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12007 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12008 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12009 WorkList.push_back({E, CC, IsListInit}); 12010 return; 12011 } 12012 12013 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12014 // Do a somewhat different check with comparison operators. 12015 if (BO->isComparisonOp()) 12016 return AnalyzeComparison(S, BO); 12017 12018 // And with simple assignments. 12019 if (BO->getOpcode() == BO_Assign) 12020 return AnalyzeAssignment(S, BO); 12021 // And with compound assignments. 12022 if (BO->isAssignmentOp()) 12023 return AnalyzeCompoundAssignment(S, BO); 12024 } 12025 12026 // These break the otherwise-useful invariant below. Fortunately, 12027 // we don't really need to recurse into them, because any internal 12028 // expressions should have been analyzed already when they were 12029 // built into statements. 12030 if (isa<StmtExpr>(E)) return; 12031 12032 // Don't descend into unevaluated contexts. 12033 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12034 12035 // Now just recurse over the expression's children. 12036 CC = E->getExprLoc(); 12037 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12038 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12039 for (Stmt *SubStmt : E->children()) { 12040 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12041 if (!ChildExpr) 12042 continue; 12043 12044 if (IsLogicalAndOperator && 12045 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12046 // Ignore checking string literals that are in logical and operators. 12047 // This is a common pattern for asserts. 12048 continue; 12049 WorkList.push_back({ChildExpr, CC, IsListInit}); 12050 } 12051 12052 if (BO && BO->isLogicalOp()) { 12053 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12054 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12055 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12056 12057 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12058 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12059 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12060 } 12061 12062 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12063 if (U->getOpcode() == UO_LNot) { 12064 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12065 } else if (U->getOpcode() != UO_AddrOf) { 12066 if (U->getSubExpr()->getType()->isAtomicType()) 12067 S.Diag(U->getSubExpr()->getBeginLoc(), 12068 diag::warn_atomic_implicit_seq_cst); 12069 } 12070 } 12071 } 12072 12073 /// AnalyzeImplicitConversions - Find and report any interesting 12074 /// implicit conversions in the given expression. There are a couple 12075 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12076 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12077 bool IsListInit/*= false*/) { 12078 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12079 WorkList.push_back({OrigE, CC, IsListInit}); 12080 while (!WorkList.empty()) 12081 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12082 } 12083 12084 /// Diagnose integer type and any valid implicit conversion to it. 12085 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12086 // Taking into account implicit conversions, 12087 // allow any integer. 12088 if (!E->getType()->isIntegerType()) { 12089 S.Diag(E->getBeginLoc(), 12090 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12091 return true; 12092 } 12093 // Potentially emit standard warnings for implicit conversions if enabled 12094 // using -Wconversion. 12095 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12096 return false; 12097 } 12098 12099 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12100 // Returns true when emitting a warning about taking the address of a reference. 12101 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12102 const PartialDiagnostic &PD) { 12103 E = E->IgnoreParenImpCasts(); 12104 12105 const FunctionDecl *FD = nullptr; 12106 12107 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12108 if (!DRE->getDecl()->getType()->isReferenceType()) 12109 return false; 12110 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12111 if (!M->getMemberDecl()->getType()->isReferenceType()) 12112 return false; 12113 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12114 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12115 return false; 12116 FD = Call->getDirectCallee(); 12117 } else { 12118 return false; 12119 } 12120 12121 SemaRef.Diag(E->getExprLoc(), PD); 12122 12123 // If possible, point to location of function. 12124 if (FD) { 12125 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12126 } 12127 12128 return true; 12129 } 12130 12131 // Returns true if the SourceLocation is expanded from any macro body. 12132 // Returns false if the SourceLocation is invalid, is from not in a macro 12133 // expansion, or is from expanded from a top-level macro argument. 12134 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12135 if (Loc.isInvalid()) 12136 return false; 12137 12138 while (Loc.isMacroID()) { 12139 if (SM.isMacroBodyExpansion(Loc)) 12140 return true; 12141 Loc = SM.getImmediateMacroCallerLoc(Loc); 12142 } 12143 12144 return false; 12145 } 12146 12147 /// Diagnose pointers that are always non-null. 12148 /// \param E the expression containing the pointer 12149 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12150 /// compared to a null pointer 12151 /// \param IsEqual True when the comparison is equal to a null pointer 12152 /// \param Range Extra SourceRange to highlight in the diagnostic 12153 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12154 Expr::NullPointerConstantKind NullKind, 12155 bool IsEqual, SourceRange Range) { 12156 if (!E) 12157 return; 12158 12159 // Don't warn inside macros. 12160 if (E->getExprLoc().isMacroID()) { 12161 const SourceManager &SM = getSourceManager(); 12162 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12163 IsInAnyMacroBody(SM, Range.getBegin())) 12164 return; 12165 } 12166 E = E->IgnoreImpCasts(); 12167 12168 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12169 12170 if (isa<CXXThisExpr>(E)) { 12171 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12172 : diag::warn_this_bool_conversion; 12173 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12174 return; 12175 } 12176 12177 bool IsAddressOf = false; 12178 12179 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12180 if (UO->getOpcode() != UO_AddrOf) 12181 return; 12182 IsAddressOf = true; 12183 E = UO->getSubExpr(); 12184 } 12185 12186 if (IsAddressOf) { 12187 unsigned DiagID = IsCompare 12188 ? diag::warn_address_of_reference_null_compare 12189 : diag::warn_address_of_reference_bool_conversion; 12190 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12191 << IsEqual; 12192 if (CheckForReference(*this, E, PD)) { 12193 return; 12194 } 12195 } 12196 12197 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12198 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12199 std::string Str; 12200 llvm::raw_string_ostream S(Str); 12201 E->printPretty(S, nullptr, getPrintingPolicy()); 12202 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12203 : diag::warn_cast_nonnull_to_bool; 12204 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12205 << E->getSourceRange() << Range << IsEqual; 12206 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12207 }; 12208 12209 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12210 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12211 if (auto *Callee = Call->getDirectCallee()) { 12212 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12213 ComplainAboutNonnullParamOrCall(A); 12214 return; 12215 } 12216 } 12217 } 12218 12219 // Expect to find a single Decl. Skip anything more complicated. 12220 ValueDecl *D = nullptr; 12221 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12222 D = R->getDecl(); 12223 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12224 D = M->getMemberDecl(); 12225 } 12226 12227 // Weak Decls can be null. 12228 if (!D || D->isWeak()) 12229 return; 12230 12231 // Check for parameter decl with nonnull attribute 12232 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12233 if (getCurFunction() && 12234 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12235 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12236 ComplainAboutNonnullParamOrCall(A); 12237 return; 12238 } 12239 12240 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12241 // Skip function template not specialized yet. 12242 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12243 return; 12244 auto ParamIter = llvm::find(FD->parameters(), PV); 12245 assert(ParamIter != FD->param_end()); 12246 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12247 12248 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12249 if (!NonNull->args_size()) { 12250 ComplainAboutNonnullParamOrCall(NonNull); 12251 return; 12252 } 12253 12254 for (const ParamIdx &ArgNo : NonNull->args()) { 12255 if (ArgNo.getASTIndex() == ParamNo) { 12256 ComplainAboutNonnullParamOrCall(NonNull); 12257 return; 12258 } 12259 } 12260 } 12261 } 12262 } 12263 } 12264 12265 QualType T = D->getType(); 12266 const bool IsArray = T->isArrayType(); 12267 const bool IsFunction = T->isFunctionType(); 12268 12269 // Address of function is used to silence the function warning. 12270 if (IsAddressOf && IsFunction) { 12271 return; 12272 } 12273 12274 // Found nothing. 12275 if (!IsAddressOf && !IsFunction && !IsArray) 12276 return; 12277 12278 // Pretty print the expression for the diagnostic. 12279 std::string Str; 12280 llvm::raw_string_ostream S(Str); 12281 E->printPretty(S, nullptr, getPrintingPolicy()); 12282 12283 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12284 : diag::warn_impcast_pointer_to_bool; 12285 enum { 12286 AddressOf, 12287 FunctionPointer, 12288 ArrayPointer 12289 } DiagType; 12290 if (IsAddressOf) 12291 DiagType = AddressOf; 12292 else if (IsFunction) 12293 DiagType = FunctionPointer; 12294 else if (IsArray) 12295 DiagType = ArrayPointer; 12296 else 12297 llvm_unreachable("Could not determine diagnostic."); 12298 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12299 << Range << IsEqual; 12300 12301 if (!IsFunction) 12302 return; 12303 12304 // Suggest '&' to silence the function warning. 12305 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12306 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12307 12308 // Check to see if '()' fixit should be emitted. 12309 QualType ReturnType; 12310 UnresolvedSet<4> NonTemplateOverloads; 12311 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12312 if (ReturnType.isNull()) 12313 return; 12314 12315 if (IsCompare) { 12316 // There are two cases here. If there is null constant, the only suggest 12317 // for a pointer return type. If the null is 0, then suggest if the return 12318 // type is a pointer or an integer type. 12319 if (!ReturnType->isPointerType()) { 12320 if (NullKind == Expr::NPCK_ZeroExpression || 12321 NullKind == Expr::NPCK_ZeroLiteral) { 12322 if (!ReturnType->isIntegerType()) 12323 return; 12324 } else { 12325 return; 12326 } 12327 } 12328 } else { // !IsCompare 12329 // For function to bool, only suggest if the function pointer has bool 12330 // return type. 12331 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12332 return; 12333 } 12334 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12335 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12336 } 12337 12338 /// Diagnoses "dangerous" implicit conversions within the given 12339 /// expression (which is a full expression). Implements -Wconversion 12340 /// and -Wsign-compare. 12341 /// 12342 /// \param CC the "context" location of the implicit conversion, i.e. 12343 /// the most location of the syntactic entity requiring the implicit 12344 /// conversion 12345 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12346 // Don't diagnose in unevaluated contexts. 12347 if (isUnevaluatedContext()) 12348 return; 12349 12350 // Don't diagnose for value- or type-dependent expressions. 12351 if (E->isTypeDependent() || E->isValueDependent()) 12352 return; 12353 12354 // Check for array bounds violations in cases where the check isn't triggered 12355 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12356 // ArraySubscriptExpr is on the RHS of a variable initialization. 12357 CheckArrayAccess(E); 12358 12359 // This is not the right CC for (e.g.) a variable initialization. 12360 AnalyzeImplicitConversions(*this, E, CC); 12361 } 12362 12363 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12364 /// Input argument E is a logical expression. 12365 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12366 ::CheckBoolLikeConversion(*this, E, CC); 12367 } 12368 12369 /// Diagnose when expression is an integer constant expression and its evaluation 12370 /// results in integer overflow 12371 void Sema::CheckForIntOverflow (Expr *E) { 12372 // Use a work list to deal with nested struct initializers. 12373 SmallVector<Expr *, 2> Exprs(1, E); 12374 12375 do { 12376 Expr *OriginalE = Exprs.pop_back_val(); 12377 Expr *E = OriginalE->IgnoreParenCasts(); 12378 12379 if (isa<BinaryOperator>(E)) { 12380 E->EvaluateForOverflow(Context); 12381 continue; 12382 } 12383 12384 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12385 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12386 else if (isa<ObjCBoxedExpr>(OriginalE)) 12387 E->EvaluateForOverflow(Context); 12388 else if (auto Call = dyn_cast<CallExpr>(E)) 12389 Exprs.append(Call->arg_begin(), Call->arg_end()); 12390 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12391 Exprs.append(Message->arg_begin(), Message->arg_end()); 12392 } while (!Exprs.empty()); 12393 } 12394 12395 namespace { 12396 12397 /// Visitor for expressions which looks for unsequenced operations on the 12398 /// same object. 12399 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12400 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12401 12402 /// A tree of sequenced regions within an expression. Two regions are 12403 /// unsequenced if one is an ancestor or a descendent of the other. When we 12404 /// finish processing an expression with sequencing, such as a comma 12405 /// expression, we fold its tree nodes into its parent, since they are 12406 /// unsequenced with respect to nodes we will visit later. 12407 class SequenceTree { 12408 struct Value { 12409 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12410 unsigned Parent : 31; 12411 unsigned Merged : 1; 12412 }; 12413 SmallVector<Value, 8> Values; 12414 12415 public: 12416 /// A region within an expression which may be sequenced with respect 12417 /// to some other region. 12418 class Seq { 12419 friend class SequenceTree; 12420 12421 unsigned Index; 12422 12423 explicit Seq(unsigned N) : Index(N) {} 12424 12425 public: 12426 Seq() : Index(0) {} 12427 }; 12428 12429 SequenceTree() { Values.push_back(Value(0)); } 12430 Seq root() const { return Seq(0); } 12431 12432 /// Create a new sequence of operations, which is an unsequenced 12433 /// subset of \p Parent. This sequence of operations is sequenced with 12434 /// respect to other children of \p Parent. 12435 Seq allocate(Seq Parent) { 12436 Values.push_back(Value(Parent.Index)); 12437 return Seq(Values.size() - 1); 12438 } 12439 12440 /// Merge a sequence of operations into its parent. 12441 void merge(Seq S) { 12442 Values[S.Index].Merged = true; 12443 } 12444 12445 /// Determine whether two operations are unsequenced. This operation 12446 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12447 /// should have been merged into its parent as appropriate. 12448 bool isUnsequenced(Seq Cur, Seq Old) { 12449 unsigned C = representative(Cur.Index); 12450 unsigned Target = representative(Old.Index); 12451 while (C >= Target) { 12452 if (C == Target) 12453 return true; 12454 C = Values[C].Parent; 12455 } 12456 return false; 12457 } 12458 12459 private: 12460 /// Pick a representative for a sequence. 12461 unsigned representative(unsigned K) { 12462 if (Values[K].Merged) 12463 // Perform path compression as we go. 12464 return Values[K].Parent = representative(Values[K].Parent); 12465 return K; 12466 } 12467 }; 12468 12469 /// An object for which we can track unsequenced uses. 12470 using Object = const NamedDecl *; 12471 12472 /// Different flavors of object usage which we track. We only track the 12473 /// least-sequenced usage of each kind. 12474 enum UsageKind { 12475 /// A read of an object. Multiple unsequenced reads are OK. 12476 UK_Use, 12477 12478 /// A modification of an object which is sequenced before the value 12479 /// computation of the expression, such as ++n in C++. 12480 UK_ModAsValue, 12481 12482 /// A modification of an object which is not sequenced before the value 12483 /// computation of the expression, such as n++. 12484 UK_ModAsSideEffect, 12485 12486 UK_Count = UK_ModAsSideEffect + 1 12487 }; 12488 12489 /// Bundle together a sequencing region and the expression corresponding 12490 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12491 struct Usage { 12492 const Expr *UsageExpr; 12493 SequenceTree::Seq Seq; 12494 12495 Usage() : UsageExpr(nullptr), Seq() {} 12496 }; 12497 12498 struct UsageInfo { 12499 Usage Uses[UK_Count]; 12500 12501 /// Have we issued a diagnostic for this object already? 12502 bool Diagnosed; 12503 12504 UsageInfo() : Uses(), Diagnosed(false) {} 12505 }; 12506 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12507 12508 Sema &SemaRef; 12509 12510 /// Sequenced regions within the expression. 12511 SequenceTree Tree; 12512 12513 /// Declaration modifications and references which we have seen. 12514 UsageInfoMap UsageMap; 12515 12516 /// The region we are currently within. 12517 SequenceTree::Seq Region; 12518 12519 /// Filled in with declarations which were modified as a side-effect 12520 /// (that is, post-increment operations). 12521 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12522 12523 /// Expressions to check later. We defer checking these to reduce 12524 /// stack usage. 12525 SmallVectorImpl<const Expr *> &WorkList; 12526 12527 /// RAII object wrapping the visitation of a sequenced subexpression of an 12528 /// expression. At the end of this process, the side-effects of the evaluation 12529 /// become sequenced with respect to the value computation of the result, so 12530 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12531 /// UK_ModAsValue. 12532 struct SequencedSubexpression { 12533 SequencedSubexpression(SequenceChecker &Self) 12534 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12535 Self.ModAsSideEffect = &ModAsSideEffect; 12536 } 12537 12538 ~SequencedSubexpression() { 12539 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12540 // Add a new usage with usage kind UK_ModAsValue, and then restore 12541 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12542 // the previous one was empty). 12543 UsageInfo &UI = Self.UsageMap[M.first]; 12544 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12545 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12546 SideEffectUsage = M.second; 12547 } 12548 Self.ModAsSideEffect = OldModAsSideEffect; 12549 } 12550 12551 SequenceChecker &Self; 12552 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12553 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12554 }; 12555 12556 /// RAII object wrapping the visitation of a subexpression which we might 12557 /// choose to evaluate as a constant. If any subexpression is evaluated and 12558 /// found to be non-constant, this allows us to suppress the evaluation of 12559 /// the outer expression. 12560 class EvaluationTracker { 12561 public: 12562 EvaluationTracker(SequenceChecker &Self) 12563 : Self(Self), Prev(Self.EvalTracker) { 12564 Self.EvalTracker = this; 12565 } 12566 12567 ~EvaluationTracker() { 12568 Self.EvalTracker = Prev; 12569 if (Prev) 12570 Prev->EvalOK &= EvalOK; 12571 } 12572 12573 bool evaluate(const Expr *E, bool &Result) { 12574 if (!EvalOK || E->isValueDependent()) 12575 return false; 12576 EvalOK = E->EvaluateAsBooleanCondition( 12577 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12578 return EvalOK; 12579 } 12580 12581 private: 12582 SequenceChecker &Self; 12583 EvaluationTracker *Prev; 12584 bool EvalOK = true; 12585 } *EvalTracker = nullptr; 12586 12587 /// Find the object which is produced by the specified expression, 12588 /// if any. 12589 Object getObject(const Expr *E, bool Mod) const { 12590 E = E->IgnoreParenCasts(); 12591 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12592 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12593 return getObject(UO->getSubExpr(), Mod); 12594 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12595 if (BO->getOpcode() == BO_Comma) 12596 return getObject(BO->getRHS(), Mod); 12597 if (Mod && BO->isAssignmentOp()) 12598 return getObject(BO->getLHS(), Mod); 12599 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12600 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12601 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12602 return ME->getMemberDecl(); 12603 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12604 // FIXME: If this is a reference, map through to its value. 12605 return DRE->getDecl(); 12606 return nullptr; 12607 } 12608 12609 /// Note that an object \p O was modified or used by an expression 12610 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12611 /// the object \p O as obtained via the \p UsageMap. 12612 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12613 // Get the old usage for the given object and usage kind. 12614 Usage &U = UI.Uses[UK]; 12615 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12616 // If we have a modification as side effect and are in a sequenced 12617 // subexpression, save the old Usage so that we can restore it later 12618 // in SequencedSubexpression::~SequencedSubexpression. 12619 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12620 ModAsSideEffect->push_back(std::make_pair(O, U)); 12621 // Then record the new usage with the current sequencing region. 12622 U.UsageExpr = UsageExpr; 12623 U.Seq = Region; 12624 } 12625 } 12626 12627 /// Check whether a modification or use of an object \p O in an expression 12628 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12629 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12630 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12631 /// usage and false we are checking for a mod-use unsequenced usage. 12632 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12633 UsageKind OtherKind, bool IsModMod) { 12634 if (UI.Diagnosed) 12635 return; 12636 12637 const Usage &U = UI.Uses[OtherKind]; 12638 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12639 return; 12640 12641 const Expr *Mod = U.UsageExpr; 12642 const Expr *ModOrUse = UsageExpr; 12643 if (OtherKind == UK_Use) 12644 std::swap(Mod, ModOrUse); 12645 12646 SemaRef.DiagRuntimeBehavior( 12647 Mod->getExprLoc(), {Mod, ModOrUse}, 12648 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12649 : diag::warn_unsequenced_mod_use) 12650 << O << SourceRange(ModOrUse->getExprLoc())); 12651 UI.Diagnosed = true; 12652 } 12653 12654 // A note on note{Pre, Post}{Use, Mod}: 12655 // 12656 // (It helps to follow the algorithm with an expression such as 12657 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12658 // operations before C++17 and both are well-defined in C++17). 12659 // 12660 // When visiting a node which uses/modify an object we first call notePreUse 12661 // or notePreMod before visiting its sub-expression(s). At this point the 12662 // children of the current node have not yet been visited and so the eventual 12663 // uses/modifications resulting from the children of the current node have not 12664 // been recorded yet. 12665 // 12666 // We then visit the children of the current node. After that notePostUse or 12667 // notePostMod is called. These will 1) detect an unsequenced modification 12668 // as side effect (as in "k++ + k") and 2) add a new usage with the 12669 // appropriate usage kind. 12670 // 12671 // We also have to be careful that some operation sequences modification as 12672 // side effect as well (for example: || or ,). To account for this we wrap 12673 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12674 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12675 // which record usages which are modifications as side effect, and then 12676 // downgrade them (or more accurately restore the previous usage which was a 12677 // modification as side effect) when exiting the scope of the sequenced 12678 // subexpression. 12679 12680 void notePreUse(Object O, const Expr *UseExpr) { 12681 UsageInfo &UI = UsageMap[O]; 12682 // Uses conflict with other modifications. 12683 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12684 } 12685 12686 void notePostUse(Object O, const Expr *UseExpr) { 12687 UsageInfo &UI = UsageMap[O]; 12688 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12689 /*IsModMod=*/false); 12690 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12691 } 12692 12693 void notePreMod(Object O, const Expr *ModExpr) { 12694 UsageInfo &UI = UsageMap[O]; 12695 // Modifications conflict with other modifications and with uses. 12696 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12697 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12698 } 12699 12700 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12701 UsageInfo &UI = UsageMap[O]; 12702 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12703 /*IsModMod=*/true); 12704 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12705 } 12706 12707 public: 12708 SequenceChecker(Sema &S, const Expr *E, 12709 SmallVectorImpl<const Expr *> &WorkList) 12710 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12711 Visit(E); 12712 // Silence a -Wunused-private-field since WorkList is now unused. 12713 // TODO: Evaluate if it can be used, and if not remove it. 12714 (void)this->WorkList; 12715 } 12716 12717 void VisitStmt(const Stmt *S) { 12718 // Skip all statements which aren't expressions for now. 12719 } 12720 12721 void VisitExpr(const Expr *E) { 12722 // By default, just recurse to evaluated subexpressions. 12723 Base::VisitStmt(E); 12724 } 12725 12726 void VisitCastExpr(const CastExpr *E) { 12727 Object O = Object(); 12728 if (E->getCastKind() == CK_LValueToRValue) 12729 O = getObject(E->getSubExpr(), false); 12730 12731 if (O) 12732 notePreUse(O, E); 12733 VisitExpr(E); 12734 if (O) 12735 notePostUse(O, E); 12736 } 12737 12738 void VisitSequencedExpressions(const Expr *SequencedBefore, 12739 const Expr *SequencedAfter) { 12740 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12741 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12742 SequenceTree::Seq OldRegion = Region; 12743 12744 { 12745 SequencedSubexpression SeqBefore(*this); 12746 Region = BeforeRegion; 12747 Visit(SequencedBefore); 12748 } 12749 12750 Region = AfterRegion; 12751 Visit(SequencedAfter); 12752 12753 Region = OldRegion; 12754 12755 Tree.merge(BeforeRegion); 12756 Tree.merge(AfterRegion); 12757 } 12758 12759 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12760 // C++17 [expr.sub]p1: 12761 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12762 // expression E1 is sequenced before the expression E2. 12763 if (SemaRef.getLangOpts().CPlusPlus17) 12764 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12765 else { 12766 Visit(ASE->getLHS()); 12767 Visit(ASE->getRHS()); 12768 } 12769 } 12770 12771 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12772 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12773 void VisitBinPtrMem(const BinaryOperator *BO) { 12774 // C++17 [expr.mptr.oper]p4: 12775 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12776 // the expression E1 is sequenced before the expression E2. 12777 if (SemaRef.getLangOpts().CPlusPlus17) 12778 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12779 else { 12780 Visit(BO->getLHS()); 12781 Visit(BO->getRHS()); 12782 } 12783 } 12784 12785 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12786 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12787 void VisitBinShlShr(const BinaryOperator *BO) { 12788 // C++17 [expr.shift]p4: 12789 // The expression E1 is sequenced before the expression E2. 12790 if (SemaRef.getLangOpts().CPlusPlus17) 12791 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12792 else { 12793 Visit(BO->getLHS()); 12794 Visit(BO->getRHS()); 12795 } 12796 } 12797 12798 void VisitBinComma(const BinaryOperator *BO) { 12799 // C++11 [expr.comma]p1: 12800 // Every value computation and side effect associated with the left 12801 // expression is sequenced before every value computation and side 12802 // effect associated with the right expression. 12803 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12804 } 12805 12806 void VisitBinAssign(const BinaryOperator *BO) { 12807 SequenceTree::Seq RHSRegion; 12808 SequenceTree::Seq LHSRegion; 12809 if (SemaRef.getLangOpts().CPlusPlus17) { 12810 RHSRegion = Tree.allocate(Region); 12811 LHSRegion = Tree.allocate(Region); 12812 } else { 12813 RHSRegion = Region; 12814 LHSRegion = Region; 12815 } 12816 SequenceTree::Seq OldRegion = Region; 12817 12818 // C++11 [expr.ass]p1: 12819 // [...] the assignment is sequenced after the value computation 12820 // of the right and left operands, [...] 12821 // 12822 // so check it before inspecting the operands and update the 12823 // map afterwards. 12824 Object O = getObject(BO->getLHS(), /*Mod=*/true); 12825 if (O) 12826 notePreMod(O, BO); 12827 12828 if (SemaRef.getLangOpts().CPlusPlus17) { 12829 // C++17 [expr.ass]p1: 12830 // [...] The right operand is sequenced before the left operand. [...] 12831 { 12832 SequencedSubexpression SeqBefore(*this); 12833 Region = RHSRegion; 12834 Visit(BO->getRHS()); 12835 } 12836 12837 Region = LHSRegion; 12838 Visit(BO->getLHS()); 12839 12840 if (O && isa<CompoundAssignOperator>(BO)) 12841 notePostUse(O, BO); 12842 12843 } else { 12844 // C++11 does not specify any sequencing between the LHS and RHS. 12845 Region = LHSRegion; 12846 Visit(BO->getLHS()); 12847 12848 if (O && isa<CompoundAssignOperator>(BO)) 12849 notePostUse(O, BO); 12850 12851 Region = RHSRegion; 12852 Visit(BO->getRHS()); 12853 } 12854 12855 // C++11 [expr.ass]p1: 12856 // the assignment is sequenced [...] before the value computation of the 12857 // assignment expression. 12858 // C11 6.5.16/3 has no such rule. 12859 Region = OldRegion; 12860 if (O) 12861 notePostMod(O, BO, 12862 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12863 : UK_ModAsSideEffect); 12864 if (SemaRef.getLangOpts().CPlusPlus17) { 12865 Tree.merge(RHSRegion); 12866 Tree.merge(LHSRegion); 12867 } 12868 } 12869 12870 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 12871 VisitBinAssign(CAO); 12872 } 12873 12874 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12875 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12876 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 12877 Object O = getObject(UO->getSubExpr(), true); 12878 if (!O) 12879 return VisitExpr(UO); 12880 12881 notePreMod(O, UO); 12882 Visit(UO->getSubExpr()); 12883 // C++11 [expr.pre.incr]p1: 12884 // the expression ++x is equivalent to x+=1 12885 notePostMod(O, UO, 12886 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12887 : UK_ModAsSideEffect); 12888 } 12889 12890 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12891 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12892 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 12893 Object O = getObject(UO->getSubExpr(), true); 12894 if (!O) 12895 return VisitExpr(UO); 12896 12897 notePreMod(O, UO); 12898 Visit(UO->getSubExpr()); 12899 notePostMod(O, UO, UK_ModAsSideEffect); 12900 } 12901 12902 void VisitBinLOr(const BinaryOperator *BO) { 12903 // C++11 [expr.log.or]p2: 12904 // If the second expression is evaluated, every value computation and 12905 // side effect associated with the first expression is sequenced before 12906 // every value computation and side effect associated with the 12907 // second expression. 12908 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12909 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12910 SequenceTree::Seq OldRegion = Region; 12911 12912 EvaluationTracker Eval(*this); 12913 { 12914 SequencedSubexpression Sequenced(*this); 12915 Region = LHSRegion; 12916 Visit(BO->getLHS()); 12917 } 12918 12919 // C++11 [expr.log.or]p1: 12920 // [...] the second operand is not evaluated if the first operand 12921 // evaluates to true. 12922 bool EvalResult = false; 12923 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12924 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 12925 if (ShouldVisitRHS) { 12926 Region = RHSRegion; 12927 Visit(BO->getRHS()); 12928 } 12929 12930 Region = OldRegion; 12931 Tree.merge(LHSRegion); 12932 Tree.merge(RHSRegion); 12933 } 12934 12935 void VisitBinLAnd(const BinaryOperator *BO) { 12936 // C++11 [expr.log.and]p2: 12937 // If the second expression is evaluated, every value computation and 12938 // side effect associated with the first expression is sequenced before 12939 // every value computation and side effect associated with the 12940 // second expression. 12941 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12942 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12943 SequenceTree::Seq OldRegion = Region; 12944 12945 EvaluationTracker Eval(*this); 12946 { 12947 SequencedSubexpression Sequenced(*this); 12948 Region = LHSRegion; 12949 Visit(BO->getLHS()); 12950 } 12951 12952 // C++11 [expr.log.and]p1: 12953 // [...] the second operand is not evaluated if the first operand is false. 12954 bool EvalResult = false; 12955 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12956 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 12957 if (ShouldVisitRHS) { 12958 Region = RHSRegion; 12959 Visit(BO->getRHS()); 12960 } 12961 12962 Region = OldRegion; 12963 Tree.merge(LHSRegion); 12964 Tree.merge(RHSRegion); 12965 } 12966 12967 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 12968 // C++11 [expr.cond]p1: 12969 // [...] Every value computation and side effect associated with the first 12970 // expression is sequenced before every value computation and side effect 12971 // associated with the second or third expression. 12972 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 12973 12974 // No sequencing is specified between the true and false expression. 12975 // However since exactly one of both is going to be evaluated we can 12976 // consider them to be sequenced. This is needed to avoid warning on 12977 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 12978 // both the true and false expressions because we can't evaluate x. 12979 // This will still allow us to detect an expression like (pre C++17) 12980 // "(x ? y += 1 : y += 2) = y". 12981 // 12982 // We don't wrap the visitation of the true and false expression with 12983 // SequencedSubexpression because we don't want to downgrade modifications 12984 // as side effect in the true and false expressions after the visition 12985 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 12986 // not warn between the two "y++", but we should warn between the "y++" 12987 // and the "y". 12988 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 12989 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 12990 SequenceTree::Seq OldRegion = Region; 12991 12992 EvaluationTracker Eval(*this); 12993 { 12994 SequencedSubexpression Sequenced(*this); 12995 Region = ConditionRegion; 12996 Visit(CO->getCond()); 12997 } 12998 12999 // C++11 [expr.cond]p1: 13000 // [...] The first expression is contextually converted to bool (Clause 4). 13001 // It is evaluated and if it is true, the result of the conditional 13002 // expression is the value of the second expression, otherwise that of the 13003 // third expression. Only one of the second and third expressions is 13004 // evaluated. [...] 13005 bool EvalResult = false; 13006 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13007 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13008 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13009 if (ShouldVisitTrueExpr) { 13010 Region = TrueRegion; 13011 Visit(CO->getTrueExpr()); 13012 } 13013 if (ShouldVisitFalseExpr) { 13014 Region = FalseRegion; 13015 Visit(CO->getFalseExpr()); 13016 } 13017 13018 Region = OldRegion; 13019 Tree.merge(ConditionRegion); 13020 Tree.merge(TrueRegion); 13021 Tree.merge(FalseRegion); 13022 } 13023 13024 void VisitCallExpr(const CallExpr *CE) { 13025 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13026 13027 if (CE->isUnevaluatedBuiltinCall(Context)) 13028 return; 13029 13030 // C++11 [intro.execution]p15: 13031 // When calling a function [...], every value computation and side effect 13032 // associated with any argument expression, or with the postfix expression 13033 // designating the called function, is sequenced before execution of every 13034 // expression or statement in the body of the function [and thus before 13035 // the value computation of its result]. 13036 SequencedSubexpression Sequenced(*this); 13037 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13038 // C++17 [expr.call]p5 13039 // The postfix-expression is sequenced before each expression in the 13040 // expression-list and any default argument. [...] 13041 SequenceTree::Seq CalleeRegion; 13042 SequenceTree::Seq OtherRegion; 13043 if (SemaRef.getLangOpts().CPlusPlus17) { 13044 CalleeRegion = Tree.allocate(Region); 13045 OtherRegion = Tree.allocate(Region); 13046 } else { 13047 CalleeRegion = Region; 13048 OtherRegion = Region; 13049 } 13050 SequenceTree::Seq OldRegion = Region; 13051 13052 // Visit the callee expression first. 13053 Region = CalleeRegion; 13054 if (SemaRef.getLangOpts().CPlusPlus17) { 13055 SequencedSubexpression Sequenced(*this); 13056 Visit(CE->getCallee()); 13057 } else { 13058 Visit(CE->getCallee()); 13059 } 13060 13061 // Then visit the argument expressions. 13062 Region = OtherRegion; 13063 for (const Expr *Argument : CE->arguments()) 13064 Visit(Argument); 13065 13066 Region = OldRegion; 13067 if (SemaRef.getLangOpts().CPlusPlus17) { 13068 Tree.merge(CalleeRegion); 13069 Tree.merge(OtherRegion); 13070 } 13071 }); 13072 } 13073 13074 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13075 // C++17 [over.match.oper]p2: 13076 // [...] the operator notation is first transformed to the equivalent 13077 // function-call notation as summarized in Table 12 (where @ denotes one 13078 // of the operators covered in the specified subclause). However, the 13079 // operands are sequenced in the order prescribed for the built-in 13080 // operator (Clause 8). 13081 // 13082 // From the above only overloaded binary operators and overloaded call 13083 // operators have sequencing rules in C++17 that we need to handle 13084 // separately. 13085 if (!SemaRef.getLangOpts().CPlusPlus17 || 13086 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13087 return VisitCallExpr(CXXOCE); 13088 13089 enum { 13090 NoSequencing, 13091 LHSBeforeRHS, 13092 RHSBeforeLHS, 13093 LHSBeforeRest 13094 } SequencingKind; 13095 switch (CXXOCE->getOperator()) { 13096 case OO_Equal: 13097 case OO_PlusEqual: 13098 case OO_MinusEqual: 13099 case OO_StarEqual: 13100 case OO_SlashEqual: 13101 case OO_PercentEqual: 13102 case OO_CaretEqual: 13103 case OO_AmpEqual: 13104 case OO_PipeEqual: 13105 case OO_LessLessEqual: 13106 case OO_GreaterGreaterEqual: 13107 SequencingKind = RHSBeforeLHS; 13108 break; 13109 13110 case OO_LessLess: 13111 case OO_GreaterGreater: 13112 case OO_AmpAmp: 13113 case OO_PipePipe: 13114 case OO_Comma: 13115 case OO_ArrowStar: 13116 case OO_Subscript: 13117 SequencingKind = LHSBeforeRHS; 13118 break; 13119 13120 case OO_Call: 13121 SequencingKind = LHSBeforeRest; 13122 break; 13123 13124 default: 13125 SequencingKind = NoSequencing; 13126 break; 13127 } 13128 13129 if (SequencingKind == NoSequencing) 13130 return VisitCallExpr(CXXOCE); 13131 13132 // This is a call, so all subexpressions are sequenced before the result. 13133 SequencedSubexpression Sequenced(*this); 13134 13135 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13136 assert(SemaRef.getLangOpts().CPlusPlus17 && 13137 "Should only get there with C++17 and above!"); 13138 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13139 "Should only get there with an overloaded binary operator" 13140 " or an overloaded call operator!"); 13141 13142 if (SequencingKind == LHSBeforeRest) { 13143 assert(CXXOCE->getOperator() == OO_Call && 13144 "We should only have an overloaded call operator here!"); 13145 13146 // This is very similar to VisitCallExpr, except that we only have the 13147 // C++17 case. The postfix-expression is the first argument of the 13148 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13149 // are in the following arguments. 13150 // 13151 // Note that we intentionally do not visit the callee expression since 13152 // it is just a decayed reference to a function. 13153 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13154 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13155 SequenceTree::Seq OldRegion = Region; 13156 13157 assert(CXXOCE->getNumArgs() >= 1 && 13158 "An overloaded call operator must have at least one argument" 13159 " for the postfix-expression!"); 13160 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13161 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13162 CXXOCE->getNumArgs() - 1); 13163 13164 // Visit the postfix-expression first. 13165 { 13166 Region = PostfixExprRegion; 13167 SequencedSubexpression Sequenced(*this); 13168 Visit(PostfixExpr); 13169 } 13170 13171 // Then visit the argument expressions. 13172 Region = ArgsRegion; 13173 for (const Expr *Arg : Args) 13174 Visit(Arg); 13175 13176 Region = OldRegion; 13177 Tree.merge(PostfixExprRegion); 13178 Tree.merge(ArgsRegion); 13179 } else { 13180 assert(CXXOCE->getNumArgs() == 2 && 13181 "Should only have two arguments here!"); 13182 assert((SequencingKind == LHSBeforeRHS || 13183 SequencingKind == RHSBeforeLHS) && 13184 "Unexpected sequencing kind!"); 13185 13186 // We do not visit the callee expression since it is just a decayed 13187 // reference to a function. 13188 const Expr *E1 = CXXOCE->getArg(0); 13189 const Expr *E2 = CXXOCE->getArg(1); 13190 if (SequencingKind == RHSBeforeLHS) 13191 std::swap(E1, E2); 13192 13193 return VisitSequencedExpressions(E1, E2); 13194 } 13195 }); 13196 } 13197 13198 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13199 // This is a call, so all subexpressions are sequenced before the result. 13200 SequencedSubexpression Sequenced(*this); 13201 13202 if (!CCE->isListInitialization()) 13203 return VisitExpr(CCE); 13204 13205 // In C++11, list initializations are sequenced. 13206 SmallVector<SequenceTree::Seq, 32> Elts; 13207 SequenceTree::Seq Parent = Region; 13208 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13209 E = CCE->arg_end(); 13210 I != E; ++I) { 13211 Region = Tree.allocate(Parent); 13212 Elts.push_back(Region); 13213 Visit(*I); 13214 } 13215 13216 // Forget that the initializers are sequenced. 13217 Region = Parent; 13218 for (unsigned I = 0; I < Elts.size(); ++I) 13219 Tree.merge(Elts[I]); 13220 } 13221 13222 void VisitInitListExpr(const InitListExpr *ILE) { 13223 if (!SemaRef.getLangOpts().CPlusPlus11) 13224 return VisitExpr(ILE); 13225 13226 // In C++11, list initializations are sequenced. 13227 SmallVector<SequenceTree::Seq, 32> Elts; 13228 SequenceTree::Seq Parent = Region; 13229 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13230 const Expr *E = ILE->getInit(I); 13231 if (!E) 13232 continue; 13233 Region = Tree.allocate(Parent); 13234 Elts.push_back(Region); 13235 Visit(E); 13236 } 13237 13238 // Forget that the initializers are sequenced. 13239 Region = Parent; 13240 for (unsigned I = 0; I < Elts.size(); ++I) 13241 Tree.merge(Elts[I]); 13242 } 13243 }; 13244 13245 } // namespace 13246 13247 void Sema::CheckUnsequencedOperations(const Expr *E) { 13248 SmallVector<const Expr *, 8> WorkList; 13249 WorkList.push_back(E); 13250 while (!WorkList.empty()) { 13251 const Expr *Item = WorkList.pop_back_val(); 13252 SequenceChecker(*this, Item, WorkList); 13253 } 13254 } 13255 13256 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13257 bool IsConstexpr) { 13258 llvm::SaveAndRestore<bool> ConstantContext( 13259 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13260 CheckImplicitConversions(E, CheckLoc); 13261 if (!E->isInstantiationDependent()) 13262 CheckUnsequencedOperations(E); 13263 if (!IsConstexpr && !E->isValueDependent()) 13264 CheckForIntOverflow(E); 13265 DiagnoseMisalignedMembers(); 13266 } 13267 13268 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13269 FieldDecl *BitField, 13270 Expr *Init) { 13271 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13272 } 13273 13274 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13275 SourceLocation Loc) { 13276 if (!PType->isVariablyModifiedType()) 13277 return; 13278 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13279 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13280 return; 13281 } 13282 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13283 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13284 return; 13285 } 13286 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13287 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13288 return; 13289 } 13290 13291 const ArrayType *AT = S.Context.getAsArrayType(PType); 13292 if (!AT) 13293 return; 13294 13295 if (AT->getSizeModifier() != ArrayType::Star) { 13296 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13297 return; 13298 } 13299 13300 S.Diag(Loc, diag::err_array_star_in_function_definition); 13301 } 13302 13303 /// CheckParmsForFunctionDef - Check that the parameters of the given 13304 /// function are appropriate for the definition of a function. This 13305 /// takes care of any checks that cannot be performed on the 13306 /// declaration itself, e.g., that the types of each of the function 13307 /// parameters are complete. 13308 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13309 bool CheckParameterNames) { 13310 bool HasInvalidParm = false; 13311 for (ParmVarDecl *Param : Parameters) { 13312 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13313 // function declarator that is part of a function definition of 13314 // that function shall not have incomplete type. 13315 // 13316 // This is also C++ [dcl.fct]p6. 13317 if (!Param->isInvalidDecl() && 13318 RequireCompleteType(Param->getLocation(), Param->getType(), 13319 diag::err_typecheck_decl_incomplete_type)) { 13320 Param->setInvalidDecl(); 13321 HasInvalidParm = true; 13322 } 13323 13324 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13325 // declaration of each parameter shall include an identifier. 13326 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13327 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13328 // Diagnose this as an extension in C17 and earlier. 13329 if (!getLangOpts().C2x) 13330 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 13331 } 13332 13333 // C99 6.7.5.3p12: 13334 // If the function declarator is not part of a definition of that 13335 // function, parameters may have incomplete type and may use the [*] 13336 // notation in their sequences of declarator specifiers to specify 13337 // variable length array types. 13338 QualType PType = Param->getOriginalType(); 13339 // FIXME: This diagnostic should point the '[*]' if source-location 13340 // information is added for it. 13341 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13342 13343 // If the parameter is a c++ class type and it has to be destructed in the 13344 // callee function, declare the destructor so that it can be called by the 13345 // callee function. Do not perform any direct access check on the dtor here. 13346 if (!Param->isInvalidDecl()) { 13347 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13348 if (!ClassDecl->isInvalidDecl() && 13349 !ClassDecl->hasIrrelevantDestructor() && 13350 !ClassDecl->isDependentContext() && 13351 ClassDecl->isParamDestroyedInCallee()) { 13352 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13353 MarkFunctionReferenced(Param->getLocation(), Destructor); 13354 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13355 } 13356 } 13357 } 13358 13359 // Parameters with the pass_object_size attribute only need to be marked 13360 // constant at function definitions. Because we lack information about 13361 // whether we're on a declaration or definition when we're instantiating the 13362 // attribute, we need to check for constness here. 13363 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13364 if (!Param->getType().isConstQualified()) 13365 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13366 << Attr->getSpelling() << 1; 13367 13368 // Check for parameter names shadowing fields from the class. 13369 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13370 // The owning context for the parameter should be the function, but we 13371 // want to see if this function's declaration context is a record. 13372 DeclContext *DC = Param->getDeclContext(); 13373 if (DC && DC->isFunctionOrMethod()) { 13374 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13375 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13376 RD, /*DeclIsField*/ false); 13377 } 13378 } 13379 } 13380 13381 return HasInvalidParm; 13382 } 13383 13384 Optional<std::pair<CharUnits, CharUnits>> 13385 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 13386 13387 /// Compute the alignment and offset of the base class object given the 13388 /// derived-to-base cast expression and the alignment and offset of the derived 13389 /// class object. 13390 static std::pair<CharUnits, CharUnits> 13391 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 13392 CharUnits BaseAlignment, CharUnits Offset, 13393 ASTContext &Ctx) { 13394 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 13395 ++PathI) { 13396 const CXXBaseSpecifier *Base = *PathI; 13397 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 13398 if (Base->isVirtual()) { 13399 // The complete object may have a lower alignment than the non-virtual 13400 // alignment of the base, in which case the base may be misaligned. Choose 13401 // the smaller of the non-virtual alignment and BaseAlignment, which is a 13402 // conservative lower bound of the complete object alignment. 13403 CharUnits NonVirtualAlignment = 13404 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 13405 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 13406 Offset = CharUnits::Zero(); 13407 } else { 13408 const ASTRecordLayout &RL = 13409 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 13410 Offset += RL.getBaseClassOffset(BaseDecl); 13411 } 13412 DerivedType = Base->getType(); 13413 } 13414 13415 return std::make_pair(BaseAlignment, Offset); 13416 } 13417 13418 /// Compute the alignment and offset of a binary additive operator. 13419 static Optional<std::pair<CharUnits, CharUnits>> 13420 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 13421 bool IsSub, ASTContext &Ctx) { 13422 QualType PointeeType = PtrE->getType()->getPointeeType(); 13423 13424 if (!PointeeType->isConstantSizeType()) 13425 return llvm::None; 13426 13427 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 13428 13429 if (!P) 13430 return llvm::None; 13431 13432 llvm::APSInt IdxRes; 13433 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 13434 if (IntE->isIntegerConstantExpr(IdxRes, Ctx)) { 13435 CharUnits Offset = EltSize * IdxRes.getExtValue(); 13436 if (IsSub) 13437 Offset = -Offset; 13438 return std::make_pair(P->first, P->second + Offset); 13439 } 13440 13441 // If the integer expression isn't a constant expression, compute the lower 13442 // bound of the alignment using the alignment and offset of the pointer 13443 // expression and the element size. 13444 return std::make_pair( 13445 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 13446 CharUnits::Zero()); 13447 } 13448 13449 /// This helper function takes an lvalue expression and returns the alignment of 13450 /// a VarDecl and a constant offset from the VarDecl. 13451 Optional<std::pair<CharUnits, CharUnits>> 13452 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 13453 E = E->IgnoreParens(); 13454 switch (E->getStmtClass()) { 13455 default: 13456 break; 13457 case Stmt::CStyleCastExprClass: 13458 case Stmt::CXXStaticCastExprClass: 13459 case Stmt::ImplicitCastExprClass: { 13460 auto *CE = cast<CastExpr>(E); 13461 const Expr *From = CE->getSubExpr(); 13462 switch (CE->getCastKind()) { 13463 default: 13464 break; 13465 case CK_NoOp: 13466 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13467 case CK_UncheckedDerivedToBase: 13468 case CK_DerivedToBase: { 13469 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13470 if (!P) 13471 break; 13472 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 13473 P->second, Ctx); 13474 } 13475 } 13476 break; 13477 } 13478 case Stmt::ArraySubscriptExprClass: { 13479 auto *ASE = cast<ArraySubscriptExpr>(E); 13480 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 13481 false, Ctx); 13482 } 13483 case Stmt::DeclRefExprClass: { 13484 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 13485 // FIXME: If VD is captured by copy or is an escaping __block variable, 13486 // use the alignment of VD's type. 13487 if (!VD->getType()->isReferenceType()) 13488 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 13489 if (VD->hasInit()) 13490 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 13491 } 13492 break; 13493 } 13494 case Stmt::MemberExprClass: { 13495 auto *ME = cast<MemberExpr>(E); 13496 if (ME->isArrow()) 13497 break; 13498 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 13499 if (!FD || FD->getType()->isReferenceType()) 13500 break; 13501 auto P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 13502 if (!P) 13503 break; 13504 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 13505 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 13506 return std::make_pair(P->first, 13507 P->second + CharUnits::fromQuantity(Offset)); 13508 } 13509 case Stmt::UnaryOperatorClass: { 13510 auto *UO = cast<UnaryOperator>(E); 13511 switch (UO->getOpcode()) { 13512 default: 13513 break; 13514 case UO_Deref: 13515 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 13516 } 13517 break; 13518 } 13519 case Stmt::BinaryOperatorClass: { 13520 auto *BO = cast<BinaryOperator>(E); 13521 auto Opcode = BO->getOpcode(); 13522 switch (Opcode) { 13523 default: 13524 break; 13525 case BO_Comma: 13526 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 13527 } 13528 break; 13529 } 13530 } 13531 return llvm::None; 13532 } 13533 13534 /// This helper function takes a pointer expression and returns the alignment of 13535 /// a VarDecl and a constant offset from the VarDecl. 13536 Optional<std::pair<CharUnits, CharUnits>> 13537 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 13538 E = E->IgnoreParens(); 13539 switch (E->getStmtClass()) { 13540 default: 13541 break; 13542 case Stmt::CStyleCastExprClass: 13543 case Stmt::CXXStaticCastExprClass: 13544 case Stmt::ImplicitCastExprClass: { 13545 auto *CE = cast<CastExpr>(E); 13546 const Expr *From = CE->getSubExpr(); 13547 switch (CE->getCastKind()) { 13548 default: 13549 break; 13550 case CK_NoOp: 13551 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13552 case CK_ArrayToPointerDecay: 13553 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13554 case CK_UncheckedDerivedToBase: 13555 case CK_DerivedToBase: { 13556 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13557 if (!P) 13558 break; 13559 return getDerivedToBaseAlignmentAndOffset( 13560 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 13561 } 13562 } 13563 break; 13564 } 13565 case Stmt::UnaryOperatorClass: { 13566 auto *UO = cast<UnaryOperator>(E); 13567 if (UO->getOpcode() == UO_AddrOf) 13568 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 13569 break; 13570 } 13571 case Stmt::BinaryOperatorClass: { 13572 auto *BO = cast<BinaryOperator>(E); 13573 auto Opcode = BO->getOpcode(); 13574 switch (Opcode) { 13575 default: 13576 break; 13577 case BO_Add: 13578 case BO_Sub: { 13579 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 13580 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 13581 std::swap(LHS, RHS); 13582 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 13583 Ctx); 13584 } 13585 case BO_Comma: 13586 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 13587 } 13588 break; 13589 } 13590 } 13591 return llvm::None; 13592 } 13593 13594 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 13595 // See if we can compute the alignment of a VarDecl and an offset from it. 13596 Optional<std::pair<CharUnits, CharUnits>> P = 13597 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 13598 13599 if (P) 13600 return P->first.alignmentAtOffset(P->second); 13601 13602 // If that failed, return the type's alignment. 13603 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 13604 } 13605 13606 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13607 /// pointer cast increases the alignment requirements. 13608 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13609 // This is actually a lot of work to potentially be doing on every 13610 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13611 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13612 return; 13613 13614 // Ignore dependent types. 13615 if (T->isDependentType() || Op->getType()->isDependentType()) 13616 return; 13617 13618 // Require that the destination be a pointer type. 13619 const PointerType *DestPtr = T->getAs<PointerType>(); 13620 if (!DestPtr) return; 13621 13622 // If the destination has alignment 1, we're done. 13623 QualType DestPointee = DestPtr->getPointeeType(); 13624 if (DestPointee->isIncompleteType()) return; 13625 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13626 if (DestAlign.isOne()) return; 13627 13628 // Require that the source be a pointer type. 13629 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13630 if (!SrcPtr) return; 13631 QualType SrcPointee = SrcPtr->getPointeeType(); 13632 13633 // Explicitly allow casts from cv void*. We already implicitly 13634 // allowed casts to cv void*, since they have alignment 1. 13635 // Also allow casts involving incomplete types, which implicitly 13636 // includes 'void'. 13637 if (SrcPointee->isIncompleteType()) return; 13638 13639 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 13640 13641 if (SrcAlign >= DestAlign) return; 13642 13643 Diag(TRange.getBegin(), diag::warn_cast_align) 13644 << Op->getType() << T 13645 << static_cast<unsigned>(SrcAlign.getQuantity()) 13646 << static_cast<unsigned>(DestAlign.getQuantity()) 13647 << TRange << Op->getSourceRange(); 13648 } 13649 13650 /// Check whether this array fits the idiom of a size-one tail padded 13651 /// array member of a struct. 13652 /// 13653 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 13654 /// commonly used to emulate flexible arrays in C89 code. 13655 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 13656 const NamedDecl *ND) { 13657 if (Size != 1 || !ND) return false; 13658 13659 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 13660 if (!FD) return false; 13661 13662 // Don't consider sizes resulting from macro expansions or template argument 13663 // substitution to form C89 tail-padded arrays. 13664 13665 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 13666 while (TInfo) { 13667 TypeLoc TL = TInfo->getTypeLoc(); 13668 // Look through typedefs. 13669 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13670 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13671 TInfo = TDL->getTypeSourceInfo(); 13672 continue; 13673 } 13674 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13675 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13676 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13677 return false; 13678 } 13679 break; 13680 } 13681 13682 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13683 if (!RD) return false; 13684 if (RD->isUnion()) return false; 13685 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13686 if (!CRD->isStandardLayout()) return false; 13687 } 13688 13689 // See if this is the last field decl in the record. 13690 const Decl *D = FD; 13691 while ((D = D->getNextDeclInContext())) 13692 if (isa<FieldDecl>(D)) 13693 return false; 13694 return true; 13695 } 13696 13697 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13698 const ArraySubscriptExpr *ASE, 13699 bool AllowOnePastEnd, bool IndexNegated) { 13700 // Already diagnosed by the constant evaluator. 13701 if (isConstantEvaluated()) 13702 return; 13703 13704 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13705 if (IndexExpr->isValueDependent()) 13706 return; 13707 13708 const Type *EffectiveType = 13709 BaseExpr->getType()->getPointeeOrArrayElementType(); 13710 BaseExpr = BaseExpr->IgnoreParenCasts(); 13711 const ConstantArrayType *ArrayTy = 13712 Context.getAsConstantArrayType(BaseExpr->getType()); 13713 13714 if (!ArrayTy) 13715 return; 13716 13717 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13718 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13719 return; 13720 13721 Expr::EvalResult Result; 13722 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13723 return; 13724 13725 llvm::APSInt index = Result.Val.getInt(); 13726 if (IndexNegated) 13727 index = -index; 13728 13729 const NamedDecl *ND = nullptr; 13730 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13731 ND = DRE->getDecl(); 13732 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13733 ND = ME->getMemberDecl(); 13734 13735 if (index.isUnsigned() || !index.isNegative()) { 13736 // It is possible that the type of the base expression after 13737 // IgnoreParenCasts is incomplete, even though the type of the base 13738 // expression before IgnoreParenCasts is complete (see PR39746 for an 13739 // example). In this case we have no information about whether the array 13740 // access exceeds the array bounds. However we can still diagnose an array 13741 // access which precedes the array bounds. 13742 if (BaseType->isIncompleteType()) 13743 return; 13744 13745 llvm::APInt size = ArrayTy->getSize(); 13746 if (!size.isStrictlyPositive()) 13747 return; 13748 13749 if (BaseType != EffectiveType) { 13750 // Make sure we're comparing apples to apples when comparing index to size 13751 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13752 uint64_t array_typesize = Context.getTypeSize(BaseType); 13753 // Handle ptrarith_typesize being zero, such as when casting to void* 13754 if (!ptrarith_typesize) ptrarith_typesize = 1; 13755 if (ptrarith_typesize != array_typesize) { 13756 // There's a cast to a different size type involved 13757 uint64_t ratio = array_typesize / ptrarith_typesize; 13758 // TODO: Be smarter about handling cases where array_typesize is not a 13759 // multiple of ptrarith_typesize 13760 if (ptrarith_typesize * ratio == array_typesize) 13761 size *= llvm::APInt(size.getBitWidth(), ratio); 13762 } 13763 } 13764 13765 if (size.getBitWidth() > index.getBitWidth()) 13766 index = index.zext(size.getBitWidth()); 13767 else if (size.getBitWidth() < index.getBitWidth()) 13768 size = size.zext(index.getBitWidth()); 13769 13770 // For array subscripting the index must be less than size, but for pointer 13771 // arithmetic also allow the index (offset) to be equal to size since 13772 // computing the next address after the end of the array is legal and 13773 // commonly done e.g. in C++ iterators and range-based for loops. 13774 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13775 return; 13776 13777 // Also don't warn for arrays of size 1 which are members of some 13778 // structure. These are often used to approximate flexible arrays in C89 13779 // code. 13780 if (IsTailPaddedMemberArray(*this, size, ND)) 13781 return; 13782 13783 // Suppress the warning if the subscript expression (as identified by the 13784 // ']' location) and the index expression are both from macro expansions 13785 // within a system header. 13786 if (ASE) { 13787 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13788 ASE->getRBracketLoc()); 13789 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13790 SourceLocation IndexLoc = 13791 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13792 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13793 return; 13794 } 13795 } 13796 13797 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13798 if (ASE) 13799 DiagID = diag::warn_array_index_exceeds_bounds; 13800 13801 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13802 PDiag(DiagID) << index.toString(10, true) 13803 << size.toString(10, true) 13804 << (unsigned)size.getLimitedValue(~0U) 13805 << IndexExpr->getSourceRange()); 13806 } else { 13807 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13808 if (!ASE) { 13809 DiagID = diag::warn_ptr_arith_precedes_bounds; 13810 if (index.isNegative()) index = -index; 13811 } 13812 13813 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13814 PDiag(DiagID) << index.toString(10, true) 13815 << IndexExpr->getSourceRange()); 13816 } 13817 13818 if (!ND) { 13819 // Try harder to find a NamedDecl to point at in the note. 13820 while (const ArraySubscriptExpr *ASE = 13821 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13822 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13823 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13824 ND = DRE->getDecl(); 13825 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13826 ND = ME->getMemberDecl(); 13827 } 13828 13829 if (ND) 13830 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13831 PDiag(diag::note_array_declared_here) 13832 << ND->getDeclName()); 13833 } 13834 13835 void Sema::CheckArrayAccess(const Expr *expr) { 13836 int AllowOnePastEnd = 0; 13837 while (expr) { 13838 expr = expr->IgnoreParenImpCasts(); 13839 switch (expr->getStmtClass()) { 13840 case Stmt::ArraySubscriptExprClass: { 13841 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13842 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13843 AllowOnePastEnd > 0); 13844 expr = ASE->getBase(); 13845 break; 13846 } 13847 case Stmt::MemberExprClass: { 13848 expr = cast<MemberExpr>(expr)->getBase(); 13849 break; 13850 } 13851 case Stmt::OMPArraySectionExprClass: { 13852 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13853 if (ASE->getLowerBound()) 13854 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13855 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13856 return; 13857 } 13858 case Stmt::UnaryOperatorClass: { 13859 // Only unwrap the * and & unary operators 13860 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13861 expr = UO->getSubExpr(); 13862 switch (UO->getOpcode()) { 13863 case UO_AddrOf: 13864 AllowOnePastEnd++; 13865 break; 13866 case UO_Deref: 13867 AllowOnePastEnd--; 13868 break; 13869 default: 13870 return; 13871 } 13872 break; 13873 } 13874 case Stmt::ConditionalOperatorClass: { 13875 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13876 if (const Expr *lhs = cond->getLHS()) 13877 CheckArrayAccess(lhs); 13878 if (const Expr *rhs = cond->getRHS()) 13879 CheckArrayAccess(rhs); 13880 return; 13881 } 13882 case Stmt::CXXOperatorCallExprClass: { 13883 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13884 for (const auto *Arg : OCE->arguments()) 13885 CheckArrayAccess(Arg); 13886 return; 13887 } 13888 default: 13889 return; 13890 } 13891 } 13892 } 13893 13894 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13895 13896 namespace { 13897 13898 struct RetainCycleOwner { 13899 VarDecl *Variable = nullptr; 13900 SourceRange Range; 13901 SourceLocation Loc; 13902 bool Indirect = false; 13903 13904 RetainCycleOwner() = default; 13905 13906 void setLocsFrom(Expr *e) { 13907 Loc = e->getExprLoc(); 13908 Range = e->getSourceRange(); 13909 } 13910 }; 13911 13912 } // namespace 13913 13914 /// Consider whether capturing the given variable can possibly lead to 13915 /// a retain cycle. 13916 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 13917 // In ARC, it's captured strongly iff the variable has __strong 13918 // lifetime. In MRR, it's captured strongly if the variable is 13919 // __block and has an appropriate type. 13920 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13921 return false; 13922 13923 owner.Variable = var; 13924 if (ref) 13925 owner.setLocsFrom(ref); 13926 return true; 13927 } 13928 13929 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13930 while (true) { 13931 e = e->IgnoreParens(); 13932 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13933 switch (cast->getCastKind()) { 13934 case CK_BitCast: 13935 case CK_LValueBitCast: 13936 case CK_LValueToRValue: 13937 case CK_ARCReclaimReturnedObject: 13938 e = cast->getSubExpr(); 13939 continue; 13940 13941 default: 13942 return false; 13943 } 13944 } 13945 13946 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13947 ObjCIvarDecl *ivar = ref->getDecl(); 13948 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13949 return false; 13950 13951 // Try to find a retain cycle in the base. 13952 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13953 return false; 13954 13955 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13956 owner.Indirect = true; 13957 return true; 13958 } 13959 13960 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13961 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13962 if (!var) return false; 13963 return considerVariable(var, ref, owner); 13964 } 13965 13966 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13967 if (member->isArrow()) return false; 13968 13969 // Don't count this as an indirect ownership. 13970 e = member->getBase(); 13971 continue; 13972 } 13973 13974 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13975 // Only pay attention to pseudo-objects on property references. 13976 ObjCPropertyRefExpr *pre 13977 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13978 ->IgnoreParens()); 13979 if (!pre) return false; 13980 if (pre->isImplicitProperty()) return false; 13981 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13982 if (!property->isRetaining() && 13983 !(property->getPropertyIvarDecl() && 13984 property->getPropertyIvarDecl()->getType() 13985 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13986 return false; 13987 13988 owner.Indirect = true; 13989 if (pre->isSuperReceiver()) { 13990 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13991 if (!owner.Variable) 13992 return false; 13993 owner.Loc = pre->getLocation(); 13994 owner.Range = pre->getSourceRange(); 13995 return true; 13996 } 13997 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13998 ->getSourceExpr()); 13999 continue; 14000 } 14001 14002 // Array ivars? 14003 14004 return false; 14005 } 14006 } 14007 14008 namespace { 14009 14010 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14011 ASTContext &Context; 14012 VarDecl *Variable; 14013 Expr *Capturer = nullptr; 14014 bool VarWillBeReased = false; 14015 14016 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14017 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14018 Context(Context), Variable(variable) {} 14019 14020 void VisitDeclRefExpr(DeclRefExpr *ref) { 14021 if (ref->getDecl() == Variable && !Capturer) 14022 Capturer = ref; 14023 } 14024 14025 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14026 if (Capturer) return; 14027 Visit(ref->getBase()); 14028 if (Capturer && ref->isFreeIvar()) 14029 Capturer = ref; 14030 } 14031 14032 void VisitBlockExpr(BlockExpr *block) { 14033 // Look inside nested blocks 14034 if (block->getBlockDecl()->capturesVariable(Variable)) 14035 Visit(block->getBlockDecl()->getBody()); 14036 } 14037 14038 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14039 if (Capturer) return; 14040 if (OVE->getSourceExpr()) 14041 Visit(OVE->getSourceExpr()); 14042 } 14043 14044 void VisitBinaryOperator(BinaryOperator *BinOp) { 14045 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14046 return; 14047 Expr *LHS = BinOp->getLHS(); 14048 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14049 if (DRE->getDecl() != Variable) 14050 return; 14051 if (Expr *RHS = BinOp->getRHS()) { 14052 RHS = RHS->IgnoreParenCasts(); 14053 llvm::APSInt Value; 14054 VarWillBeReased = 14055 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 14056 } 14057 } 14058 } 14059 }; 14060 14061 } // namespace 14062 14063 /// Check whether the given argument is a block which captures a 14064 /// variable. 14065 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14066 assert(owner.Variable && owner.Loc.isValid()); 14067 14068 e = e->IgnoreParenCasts(); 14069 14070 // Look through [^{...} copy] and Block_copy(^{...}). 14071 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14072 Selector Cmd = ME->getSelector(); 14073 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14074 e = ME->getInstanceReceiver(); 14075 if (!e) 14076 return nullptr; 14077 e = e->IgnoreParenCasts(); 14078 } 14079 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14080 if (CE->getNumArgs() == 1) { 14081 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14082 if (Fn) { 14083 const IdentifierInfo *FnI = Fn->getIdentifier(); 14084 if (FnI && FnI->isStr("_Block_copy")) { 14085 e = CE->getArg(0)->IgnoreParenCasts(); 14086 } 14087 } 14088 } 14089 } 14090 14091 BlockExpr *block = dyn_cast<BlockExpr>(e); 14092 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14093 return nullptr; 14094 14095 FindCaptureVisitor visitor(S.Context, owner.Variable); 14096 visitor.Visit(block->getBlockDecl()->getBody()); 14097 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14098 } 14099 14100 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14101 RetainCycleOwner &owner) { 14102 assert(capturer); 14103 assert(owner.Variable && owner.Loc.isValid()); 14104 14105 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14106 << owner.Variable << capturer->getSourceRange(); 14107 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14108 << owner.Indirect << owner.Range; 14109 } 14110 14111 /// Check for a keyword selector that starts with the word 'add' or 14112 /// 'set'. 14113 static bool isSetterLikeSelector(Selector sel) { 14114 if (sel.isUnarySelector()) return false; 14115 14116 StringRef str = sel.getNameForSlot(0); 14117 while (!str.empty() && str.front() == '_') str = str.substr(1); 14118 if (str.startswith("set")) 14119 str = str.substr(3); 14120 else if (str.startswith("add")) { 14121 // Specially allow 'addOperationWithBlock:'. 14122 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14123 return false; 14124 str = str.substr(3); 14125 } 14126 else 14127 return false; 14128 14129 if (str.empty()) return true; 14130 return !isLowercase(str.front()); 14131 } 14132 14133 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14134 ObjCMessageExpr *Message) { 14135 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14136 Message->getReceiverInterface(), 14137 NSAPI::ClassId_NSMutableArray); 14138 if (!IsMutableArray) { 14139 return None; 14140 } 14141 14142 Selector Sel = Message->getSelector(); 14143 14144 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14145 S.NSAPIObj->getNSArrayMethodKind(Sel); 14146 if (!MKOpt) { 14147 return None; 14148 } 14149 14150 NSAPI::NSArrayMethodKind MK = *MKOpt; 14151 14152 switch (MK) { 14153 case NSAPI::NSMutableArr_addObject: 14154 case NSAPI::NSMutableArr_insertObjectAtIndex: 14155 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14156 return 0; 14157 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14158 return 1; 14159 14160 default: 14161 return None; 14162 } 14163 14164 return None; 14165 } 14166 14167 static 14168 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14169 ObjCMessageExpr *Message) { 14170 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14171 Message->getReceiverInterface(), 14172 NSAPI::ClassId_NSMutableDictionary); 14173 if (!IsMutableDictionary) { 14174 return None; 14175 } 14176 14177 Selector Sel = Message->getSelector(); 14178 14179 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14180 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14181 if (!MKOpt) { 14182 return None; 14183 } 14184 14185 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14186 14187 switch (MK) { 14188 case NSAPI::NSMutableDict_setObjectForKey: 14189 case NSAPI::NSMutableDict_setValueForKey: 14190 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14191 return 0; 14192 14193 default: 14194 return None; 14195 } 14196 14197 return None; 14198 } 14199 14200 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14201 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14202 Message->getReceiverInterface(), 14203 NSAPI::ClassId_NSMutableSet); 14204 14205 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14206 Message->getReceiverInterface(), 14207 NSAPI::ClassId_NSMutableOrderedSet); 14208 if (!IsMutableSet && !IsMutableOrderedSet) { 14209 return None; 14210 } 14211 14212 Selector Sel = Message->getSelector(); 14213 14214 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14215 if (!MKOpt) { 14216 return None; 14217 } 14218 14219 NSAPI::NSSetMethodKind MK = *MKOpt; 14220 14221 switch (MK) { 14222 case NSAPI::NSMutableSet_addObject: 14223 case NSAPI::NSOrderedSet_setObjectAtIndex: 14224 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14225 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14226 return 0; 14227 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14228 return 1; 14229 } 14230 14231 return None; 14232 } 14233 14234 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14235 if (!Message->isInstanceMessage()) { 14236 return; 14237 } 14238 14239 Optional<int> ArgOpt; 14240 14241 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14242 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14243 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14244 return; 14245 } 14246 14247 int ArgIndex = *ArgOpt; 14248 14249 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14250 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14251 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14252 } 14253 14254 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14255 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14256 if (ArgRE->isObjCSelfExpr()) { 14257 Diag(Message->getSourceRange().getBegin(), 14258 diag::warn_objc_circular_container) 14259 << ArgRE->getDecl() << StringRef("'super'"); 14260 } 14261 } 14262 } else { 14263 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14264 14265 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14266 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14267 } 14268 14269 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14270 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14271 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14272 ValueDecl *Decl = ReceiverRE->getDecl(); 14273 Diag(Message->getSourceRange().getBegin(), 14274 diag::warn_objc_circular_container) 14275 << Decl << Decl; 14276 if (!ArgRE->isObjCSelfExpr()) { 14277 Diag(Decl->getLocation(), 14278 diag::note_objc_circular_container_declared_here) 14279 << Decl; 14280 } 14281 } 14282 } 14283 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 14284 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 14285 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 14286 ObjCIvarDecl *Decl = IvarRE->getDecl(); 14287 Diag(Message->getSourceRange().getBegin(), 14288 diag::warn_objc_circular_container) 14289 << Decl << Decl; 14290 Diag(Decl->getLocation(), 14291 diag::note_objc_circular_container_declared_here) 14292 << Decl; 14293 } 14294 } 14295 } 14296 } 14297 } 14298 14299 /// Check a message send to see if it's likely to cause a retain cycle. 14300 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14301 // Only check instance methods whose selector looks like a setter. 14302 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14303 return; 14304 14305 // Try to find a variable that the receiver is strongly owned by. 14306 RetainCycleOwner owner; 14307 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14308 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14309 return; 14310 } else { 14311 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14312 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14313 owner.Loc = msg->getSuperLoc(); 14314 owner.Range = msg->getSuperLoc(); 14315 } 14316 14317 // Check whether the receiver is captured by any of the arguments. 14318 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14319 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14320 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14321 // noescape blocks should not be retained by the method. 14322 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14323 continue; 14324 return diagnoseRetainCycle(*this, capturer, owner); 14325 } 14326 } 14327 } 14328 14329 /// Check a property assign to see if it's likely to cause a retain cycle. 14330 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14331 RetainCycleOwner owner; 14332 if (!findRetainCycleOwner(*this, receiver, owner)) 14333 return; 14334 14335 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14336 diagnoseRetainCycle(*this, capturer, owner); 14337 } 14338 14339 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14340 RetainCycleOwner Owner; 14341 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14342 return; 14343 14344 // Because we don't have an expression for the variable, we have to set the 14345 // location explicitly here. 14346 Owner.Loc = Var->getLocation(); 14347 Owner.Range = Var->getSourceRange(); 14348 14349 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14350 diagnoseRetainCycle(*this, Capturer, Owner); 14351 } 14352 14353 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14354 Expr *RHS, bool isProperty) { 14355 // Check if RHS is an Objective-C object literal, which also can get 14356 // immediately zapped in a weak reference. Note that we explicitly 14357 // allow ObjCStringLiterals, since those are designed to never really die. 14358 RHS = RHS->IgnoreParenImpCasts(); 14359 14360 // This enum needs to match with the 'select' in 14361 // warn_objc_arc_literal_assign (off-by-1). 14362 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14363 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14364 return false; 14365 14366 S.Diag(Loc, diag::warn_arc_literal_assign) 14367 << (unsigned) Kind 14368 << (isProperty ? 0 : 1) 14369 << RHS->getSourceRange(); 14370 14371 return true; 14372 } 14373 14374 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 14375 Qualifiers::ObjCLifetime LT, 14376 Expr *RHS, bool isProperty) { 14377 // Strip off any implicit cast added to get to the one ARC-specific. 14378 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14379 if (cast->getCastKind() == CK_ARCConsumeObject) { 14380 S.Diag(Loc, diag::warn_arc_retained_assign) 14381 << (LT == Qualifiers::OCL_ExplicitNone) 14382 << (isProperty ? 0 : 1) 14383 << RHS->getSourceRange(); 14384 return true; 14385 } 14386 RHS = cast->getSubExpr(); 14387 } 14388 14389 if (LT == Qualifiers::OCL_Weak && 14390 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 14391 return true; 14392 14393 return false; 14394 } 14395 14396 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 14397 QualType LHS, Expr *RHS) { 14398 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 14399 14400 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 14401 return false; 14402 14403 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 14404 return true; 14405 14406 return false; 14407 } 14408 14409 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 14410 Expr *LHS, Expr *RHS) { 14411 QualType LHSType; 14412 // PropertyRef on LHS type need be directly obtained from 14413 // its declaration as it has a PseudoType. 14414 ObjCPropertyRefExpr *PRE 14415 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 14416 if (PRE && !PRE->isImplicitProperty()) { 14417 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14418 if (PD) 14419 LHSType = PD->getType(); 14420 } 14421 14422 if (LHSType.isNull()) 14423 LHSType = LHS->getType(); 14424 14425 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 14426 14427 if (LT == Qualifiers::OCL_Weak) { 14428 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14429 getCurFunction()->markSafeWeakUse(LHS); 14430 } 14431 14432 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14433 return; 14434 14435 // FIXME. Check for other life times. 14436 if (LT != Qualifiers::OCL_None) 14437 return; 14438 14439 if (PRE) { 14440 if (PRE->isImplicitProperty()) 14441 return; 14442 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14443 if (!PD) 14444 return; 14445 14446 unsigned Attributes = PD->getPropertyAttributes(); 14447 if (Attributes & ObjCPropertyAttribute::kind_assign) { 14448 // when 'assign' attribute was not explicitly specified 14449 // by user, ignore it and rely on property type itself 14450 // for lifetime info. 14451 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 14452 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 14453 LHSType->isObjCRetainableType()) 14454 return; 14455 14456 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14457 if (cast->getCastKind() == CK_ARCConsumeObject) { 14458 Diag(Loc, diag::warn_arc_retained_property_assign) 14459 << RHS->getSourceRange(); 14460 return; 14461 } 14462 RHS = cast->getSubExpr(); 14463 } 14464 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 14465 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 14466 return; 14467 } 14468 } 14469 } 14470 14471 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 14472 14473 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 14474 SourceLocation StmtLoc, 14475 const NullStmt *Body) { 14476 // Do not warn if the body is a macro that expands to nothing, e.g: 14477 // 14478 // #define CALL(x) 14479 // if (condition) 14480 // CALL(0); 14481 if (Body->hasLeadingEmptyMacro()) 14482 return false; 14483 14484 // Get line numbers of statement and body. 14485 bool StmtLineInvalid; 14486 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 14487 &StmtLineInvalid); 14488 if (StmtLineInvalid) 14489 return false; 14490 14491 bool BodyLineInvalid; 14492 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 14493 &BodyLineInvalid); 14494 if (BodyLineInvalid) 14495 return false; 14496 14497 // Warn if null statement and body are on the same line. 14498 if (StmtLine != BodyLine) 14499 return false; 14500 14501 return true; 14502 } 14503 14504 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 14505 const Stmt *Body, 14506 unsigned DiagID) { 14507 // Since this is a syntactic check, don't emit diagnostic for template 14508 // instantiations, this just adds noise. 14509 if (CurrentInstantiationScope) 14510 return; 14511 14512 // The body should be a null statement. 14513 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14514 if (!NBody) 14515 return; 14516 14517 // Do the usual checks. 14518 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14519 return; 14520 14521 Diag(NBody->getSemiLoc(), DiagID); 14522 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14523 } 14524 14525 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14526 const Stmt *PossibleBody) { 14527 assert(!CurrentInstantiationScope); // Ensured by caller 14528 14529 SourceLocation StmtLoc; 14530 const Stmt *Body; 14531 unsigned DiagID; 14532 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14533 StmtLoc = FS->getRParenLoc(); 14534 Body = FS->getBody(); 14535 DiagID = diag::warn_empty_for_body; 14536 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14537 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14538 Body = WS->getBody(); 14539 DiagID = diag::warn_empty_while_body; 14540 } else 14541 return; // Neither `for' nor `while'. 14542 14543 // The body should be a null statement. 14544 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14545 if (!NBody) 14546 return; 14547 14548 // Skip expensive checks if diagnostic is disabled. 14549 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14550 return; 14551 14552 // Do the usual checks. 14553 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14554 return; 14555 14556 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14557 // noise level low, emit diagnostics only if for/while is followed by a 14558 // CompoundStmt, e.g.: 14559 // for (int i = 0; i < n; i++); 14560 // { 14561 // a(i); 14562 // } 14563 // or if for/while is followed by a statement with more indentation 14564 // than for/while itself: 14565 // for (int i = 0; i < n; i++); 14566 // a(i); 14567 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14568 if (!ProbableTypo) { 14569 bool BodyColInvalid; 14570 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14571 PossibleBody->getBeginLoc(), &BodyColInvalid); 14572 if (BodyColInvalid) 14573 return; 14574 14575 bool StmtColInvalid; 14576 unsigned StmtCol = 14577 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14578 if (StmtColInvalid) 14579 return; 14580 14581 if (BodyCol > StmtCol) 14582 ProbableTypo = true; 14583 } 14584 14585 if (ProbableTypo) { 14586 Diag(NBody->getSemiLoc(), DiagID); 14587 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14588 } 14589 } 14590 14591 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14592 14593 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14594 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14595 SourceLocation OpLoc) { 14596 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14597 return; 14598 14599 if (inTemplateInstantiation()) 14600 return; 14601 14602 // Strip parens and casts away. 14603 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14604 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14605 14606 // Check for a call expression 14607 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14608 if (!CE || CE->getNumArgs() != 1) 14609 return; 14610 14611 // Check for a call to std::move 14612 if (!CE->isCallToStdMove()) 14613 return; 14614 14615 // Get argument from std::move 14616 RHSExpr = CE->getArg(0); 14617 14618 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14619 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14620 14621 // Two DeclRefExpr's, check that the decls are the same. 14622 if (LHSDeclRef && RHSDeclRef) { 14623 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14624 return; 14625 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14626 RHSDeclRef->getDecl()->getCanonicalDecl()) 14627 return; 14628 14629 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14630 << LHSExpr->getSourceRange() 14631 << RHSExpr->getSourceRange(); 14632 return; 14633 } 14634 14635 // Member variables require a different approach to check for self moves. 14636 // MemberExpr's are the same if every nested MemberExpr refers to the same 14637 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14638 // the base Expr's are CXXThisExpr's. 14639 const Expr *LHSBase = LHSExpr; 14640 const Expr *RHSBase = RHSExpr; 14641 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14642 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14643 if (!LHSME || !RHSME) 14644 return; 14645 14646 while (LHSME && RHSME) { 14647 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14648 RHSME->getMemberDecl()->getCanonicalDecl()) 14649 return; 14650 14651 LHSBase = LHSME->getBase(); 14652 RHSBase = RHSME->getBase(); 14653 LHSME = dyn_cast<MemberExpr>(LHSBase); 14654 RHSME = dyn_cast<MemberExpr>(RHSBase); 14655 } 14656 14657 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14658 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14659 if (LHSDeclRef && RHSDeclRef) { 14660 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14661 return; 14662 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14663 RHSDeclRef->getDecl()->getCanonicalDecl()) 14664 return; 14665 14666 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14667 << LHSExpr->getSourceRange() 14668 << RHSExpr->getSourceRange(); 14669 return; 14670 } 14671 14672 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14673 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14674 << LHSExpr->getSourceRange() 14675 << RHSExpr->getSourceRange(); 14676 } 14677 14678 //===--- Layout compatibility ----------------------------------------------// 14679 14680 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14681 14682 /// Check if two enumeration types are layout-compatible. 14683 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14684 // C++11 [dcl.enum] p8: 14685 // Two enumeration types are layout-compatible if they have the same 14686 // underlying type. 14687 return ED1->isComplete() && ED2->isComplete() && 14688 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14689 } 14690 14691 /// Check if two fields are layout-compatible. 14692 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14693 FieldDecl *Field2) { 14694 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14695 return false; 14696 14697 if (Field1->isBitField() != Field2->isBitField()) 14698 return false; 14699 14700 if (Field1->isBitField()) { 14701 // Make sure that the bit-fields are the same length. 14702 unsigned Bits1 = Field1->getBitWidthValue(C); 14703 unsigned Bits2 = Field2->getBitWidthValue(C); 14704 14705 if (Bits1 != Bits2) 14706 return false; 14707 } 14708 14709 return true; 14710 } 14711 14712 /// Check if two standard-layout structs are layout-compatible. 14713 /// (C++11 [class.mem] p17) 14714 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14715 RecordDecl *RD2) { 14716 // If both records are C++ classes, check that base classes match. 14717 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14718 // If one of records is a CXXRecordDecl we are in C++ mode, 14719 // thus the other one is a CXXRecordDecl, too. 14720 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14721 // Check number of base classes. 14722 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14723 return false; 14724 14725 // Check the base classes. 14726 for (CXXRecordDecl::base_class_const_iterator 14727 Base1 = D1CXX->bases_begin(), 14728 BaseEnd1 = D1CXX->bases_end(), 14729 Base2 = D2CXX->bases_begin(); 14730 Base1 != BaseEnd1; 14731 ++Base1, ++Base2) { 14732 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14733 return false; 14734 } 14735 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14736 // If only RD2 is a C++ class, it should have zero base classes. 14737 if (D2CXX->getNumBases() > 0) 14738 return false; 14739 } 14740 14741 // Check the fields. 14742 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14743 Field2End = RD2->field_end(), 14744 Field1 = RD1->field_begin(), 14745 Field1End = RD1->field_end(); 14746 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14747 if (!isLayoutCompatible(C, *Field1, *Field2)) 14748 return false; 14749 } 14750 if (Field1 != Field1End || Field2 != Field2End) 14751 return false; 14752 14753 return true; 14754 } 14755 14756 /// Check if two standard-layout unions are layout-compatible. 14757 /// (C++11 [class.mem] p18) 14758 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14759 RecordDecl *RD2) { 14760 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14761 for (auto *Field2 : RD2->fields()) 14762 UnmatchedFields.insert(Field2); 14763 14764 for (auto *Field1 : RD1->fields()) { 14765 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14766 I = UnmatchedFields.begin(), 14767 E = UnmatchedFields.end(); 14768 14769 for ( ; I != E; ++I) { 14770 if (isLayoutCompatible(C, Field1, *I)) { 14771 bool Result = UnmatchedFields.erase(*I); 14772 (void) Result; 14773 assert(Result); 14774 break; 14775 } 14776 } 14777 if (I == E) 14778 return false; 14779 } 14780 14781 return UnmatchedFields.empty(); 14782 } 14783 14784 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14785 RecordDecl *RD2) { 14786 if (RD1->isUnion() != RD2->isUnion()) 14787 return false; 14788 14789 if (RD1->isUnion()) 14790 return isLayoutCompatibleUnion(C, RD1, RD2); 14791 else 14792 return isLayoutCompatibleStruct(C, RD1, RD2); 14793 } 14794 14795 /// Check if two types are layout-compatible in C++11 sense. 14796 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14797 if (T1.isNull() || T2.isNull()) 14798 return false; 14799 14800 // C++11 [basic.types] p11: 14801 // If two types T1 and T2 are the same type, then T1 and T2 are 14802 // layout-compatible types. 14803 if (C.hasSameType(T1, T2)) 14804 return true; 14805 14806 T1 = T1.getCanonicalType().getUnqualifiedType(); 14807 T2 = T2.getCanonicalType().getUnqualifiedType(); 14808 14809 const Type::TypeClass TC1 = T1->getTypeClass(); 14810 const Type::TypeClass TC2 = T2->getTypeClass(); 14811 14812 if (TC1 != TC2) 14813 return false; 14814 14815 if (TC1 == Type::Enum) { 14816 return isLayoutCompatible(C, 14817 cast<EnumType>(T1)->getDecl(), 14818 cast<EnumType>(T2)->getDecl()); 14819 } else if (TC1 == Type::Record) { 14820 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14821 return false; 14822 14823 return isLayoutCompatible(C, 14824 cast<RecordType>(T1)->getDecl(), 14825 cast<RecordType>(T2)->getDecl()); 14826 } 14827 14828 return false; 14829 } 14830 14831 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14832 14833 /// Given a type tag expression find the type tag itself. 14834 /// 14835 /// \param TypeExpr Type tag expression, as it appears in user's code. 14836 /// 14837 /// \param VD Declaration of an identifier that appears in a type tag. 14838 /// 14839 /// \param MagicValue Type tag magic value. 14840 /// 14841 /// \param isConstantEvaluated wether the evalaution should be performed in 14842 14843 /// constant context. 14844 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14845 const ValueDecl **VD, uint64_t *MagicValue, 14846 bool isConstantEvaluated) { 14847 while(true) { 14848 if (!TypeExpr) 14849 return false; 14850 14851 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14852 14853 switch (TypeExpr->getStmtClass()) { 14854 case Stmt::UnaryOperatorClass: { 14855 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14856 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14857 TypeExpr = UO->getSubExpr(); 14858 continue; 14859 } 14860 return false; 14861 } 14862 14863 case Stmt::DeclRefExprClass: { 14864 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14865 *VD = DRE->getDecl(); 14866 return true; 14867 } 14868 14869 case Stmt::IntegerLiteralClass: { 14870 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14871 llvm::APInt MagicValueAPInt = IL->getValue(); 14872 if (MagicValueAPInt.getActiveBits() <= 64) { 14873 *MagicValue = MagicValueAPInt.getZExtValue(); 14874 return true; 14875 } else 14876 return false; 14877 } 14878 14879 case Stmt::BinaryConditionalOperatorClass: 14880 case Stmt::ConditionalOperatorClass: { 14881 const AbstractConditionalOperator *ACO = 14882 cast<AbstractConditionalOperator>(TypeExpr); 14883 bool Result; 14884 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14885 isConstantEvaluated)) { 14886 if (Result) 14887 TypeExpr = ACO->getTrueExpr(); 14888 else 14889 TypeExpr = ACO->getFalseExpr(); 14890 continue; 14891 } 14892 return false; 14893 } 14894 14895 case Stmt::BinaryOperatorClass: { 14896 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14897 if (BO->getOpcode() == BO_Comma) { 14898 TypeExpr = BO->getRHS(); 14899 continue; 14900 } 14901 return false; 14902 } 14903 14904 default: 14905 return false; 14906 } 14907 } 14908 } 14909 14910 /// Retrieve the C type corresponding to type tag TypeExpr. 14911 /// 14912 /// \param TypeExpr Expression that specifies a type tag. 14913 /// 14914 /// \param MagicValues Registered magic values. 14915 /// 14916 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14917 /// kind. 14918 /// 14919 /// \param TypeInfo Information about the corresponding C type. 14920 /// 14921 /// \param isConstantEvaluated wether the evalaution should be performed in 14922 /// constant context. 14923 /// 14924 /// \returns true if the corresponding C type was found. 14925 static bool GetMatchingCType( 14926 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14927 const ASTContext &Ctx, 14928 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14929 *MagicValues, 14930 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14931 bool isConstantEvaluated) { 14932 FoundWrongKind = false; 14933 14934 // Variable declaration that has type_tag_for_datatype attribute. 14935 const ValueDecl *VD = nullptr; 14936 14937 uint64_t MagicValue; 14938 14939 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14940 return false; 14941 14942 if (VD) { 14943 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14944 if (I->getArgumentKind() != ArgumentKind) { 14945 FoundWrongKind = true; 14946 return false; 14947 } 14948 TypeInfo.Type = I->getMatchingCType(); 14949 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14950 TypeInfo.MustBeNull = I->getMustBeNull(); 14951 return true; 14952 } 14953 return false; 14954 } 14955 14956 if (!MagicValues) 14957 return false; 14958 14959 llvm::DenseMap<Sema::TypeTagMagicValue, 14960 Sema::TypeTagData>::const_iterator I = 14961 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14962 if (I == MagicValues->end()) 14963 return false; 14964 14965 TypeInfo = I->second; 14966 return true; 14967 } 14968 14969 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14970 uint64_t MagicValue, QualType Type, 14971 bool LayoutCompatible, 14972 bool MustBeNull) { 14973 if (!TypeTagForDatatypeMagicValues) 14974 TypeTagForDatatypeMagicValues.reset( 14975 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14976 14977 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14978 (*TypeTagForDatatypeMagicValues)[Magic] = 14979 TypeTagData(Type, LayoutCompatible, MustBeNull); 14980 } 14981 14982 static bool IsSameCharType(QualType T1, QualType T2) { 14983 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14984 if (!BT1) 14985 return false; 14986 14987 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14988 if (!BT2) 14989 return false; 14990 14991 BuiltinType::Kind T1Kind = BT1->getKind(); 14992 BuiltinType::Kind T2Kind = BT2->getKind(); 14993 14994 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14995 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14996 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14997 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14998 } 14999 15000 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15001 const ArrayRef<const Expr *> ExprArgs, 15002 SourceLocation CallSiteLoc) { 15003 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15004 bool IsPointerAttr = Attr->getIsPointer(); 15005 15006 // Retrieve the argument representing the 'type_tag'. 15007 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15008 if (TypeTagIdxAST >= ExprArgs.size()) { 15009 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15010 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15011 return; 15012 } 15013 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15014 bool FoundWrongKind; 15015 TypeTagData TypeInfo; 15016 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15017 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15018 TypeInfo, isConstantEvaluated())) { 15019 if (FoundWrongKind) 15020 Diag(TypeTagExpr->getExprLoc(), 15021 diag::warn_type_tag_for_datatype_wrong_kind) 15022 << TypeTagExpr->getSourceRange(); 15023 return; 15024 } 15025 15026 // Retrieve the argument representing the 'arg_idx'. 15027 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15028 if (ArgumentIdxAST >= ExprArgs.size()) { 15029 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15030 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15031 return; 15032 } 15033 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15034 if (IsPointerAttr) { 15035 // Skip implicit cast of pointer to `void *' (as a function argument). 15036 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15037 if (ICE->getType()->isVoidPointerType() && 15038 ICE->getCastKind() == CK_BitCast) 15039 ArgumentExpr = ICE->getSubExpr(); 15040 } 15041 QualType ArgumentType = ArgumentExpr->getType(); 15042 15043 // Passing a `void*' pointer shouldn't trigger a warning. 15044 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15045 return; 15046 15047 if (TypeInfo.MustBeNull) { 15048 // Type tag with matching void type requires a null pointer. 15049 if (!ArgumentExpr->isNullPointerConstant(Context, 15050 Expr::NPC_ValueDependentIsNotNull)) { 15051 Diag(ArgumentExpr->getExprLoc(), 15052 diag::warn_type_safety_null_pointer_required) 15053 << ArgumentKind->getName() 15054 << ArgumentExpr->getSourceRange() 15055 << TypeTagExpr->getSourceRange(); 15056 } 15057 return; 15058 } 15059 15060 QualType RequiredType = TypeInfo.Type; 15061 if (IsPointerAttr) 15062 RequiredType = Context.getPointerType(RequiredType); 15063 15064 bool mismatch = false; 15065 if (!TypeInfo.LayoutCompatible) { 15066 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15067 15068 // C++11 [basic.fundamental] p1: 15069 // Plain char, signed char, and unsigned char are three distinct types. 15070 // 15071 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15072 // char' depending on the current char signedness mode. 15073 if (mismatch) 15074 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15075 RequiredType->getPointeeType())) || 15076 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15077 mismatch = false; 15078 } else 15079 if (IsPointerAttr) 15080 mismatch = !isLayoutCompatible(Context, 15081 ArgumentType->getPointeeType(), 15082 RequiredType->getPointeeType()); 15083 else 15084 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15085 15086 if (mismatch) 15087 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15088 << ArgumentType << ArgumentKind 15089 << TypeInfo.LayoutCompatible << RequiredType 15090 << ArgumentExpr->getSourceRange() 15091 << TypeTagExpr->getSourceRange(); 15092 } 15093 15094 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15095 CharUnits Alignment) { 15096 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15097 } 15098 15099 void Sema::DiagnoseMisalignedMembers() { 15100 for (MisalignedMember &m : MisalignedMembers) { 15101 const NamedDecl *ND = m.RD; 15102 if (ND->getName().empty()) { 15103 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15104 ND = TD; 15105 } 15106 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15107 << m.MD << ND << m.E->getSourceRange(); 15108 } 15109 MisalignedMembers.clear(); 15110 } 15111 15112 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15113 E = E->IgnoreParens(); 15114 if (!T->isPointerType() && !T->isIntegerType()) 15115 return; 15116 if (isa<UnaryOperator>(E) && 15117 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15118 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15119 if (isa<MemberExpr>(Op)) { 15120 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15121 if (MA != MisalignedMembers.end() && 15122 (T->isIntegerType() || 15123 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15124 Context.getTypeAlignInChars( 15125 T->getPointeeType()) <= MA->Alignment)))) 15126 MisalignedMembers.erase(MA); 15127 } 15128 } 15129 } 15130 15131 void Sema::RefersToMemberWithReducedAlignment( 15132 Expr *E, 15133 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15134 Action) { 15135 const auto *ME = dyn_cast<MemberExpr>(E); 15136 if (!ME) 15137 return; 15138 15139 // No need to check expressions with an __unaligned-qualified type. 15140 if (E->getType().getQualifiers().hasUnaligned()) 15141 return; 15142 15143 // For a chain of MemberExpr like "a.b.c.d" this list 15144 // will keep FieldDecl's like [d, c, b]. 15145 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15146 const MemberExpr *TopME = nullptr; 15147 bool AnyIsPacked = false; 15148 do { 15149 QualType BaseType = ME->getBase()->getType(); 15150 if (BaseType->isDependentType()) 15151 return; 15152 if (ME->isArrow()) 15153 BaseType = BaseType->getPointeeType(); 15154 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15155 if (RD->isInvalidDecl()) 15156 return; 15157 15158 ValueDecl *MD = ME->getMemberDecl(); 15159 auto *FD = dyn_cast<FieldDecl>(MD); 15160 // We do not care about non-data members. 15161 if (!FD || FD->isInvalidDecl()) 15162 return; 15163 15164 AnyIsPacked = 15165 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15166 ReverseMemberChain.push_back(FD); 15167 15168 TopME = ME; 15169 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15170 } while (ME); 15171 assert(TopME && "We did not compute a topmost MemberExpr!"); 15172 15173 // Not the scope of this diagnostic. 15174 if (!AnyIsPacked) 15175 return; 15176 15177 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15178 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15179 // TODO: The innermost base of the member expression may be too complicated. 15180 // For now, just disregard these cases. This is left for future 15181 // improvement. 15182 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15183 return; 15184 15185 // Alignment expected by the whole expression. 15186 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15187 15188 // No need to do anything else with this case. 15189 if (ExpectedAlignment.isOne()) 15190 return; 15191 15192 // Synthesize offset of the whole access. 15193 CharUnits Offset; 15194 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15195 I++) { 15196 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15197 } 15198 15199 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15200 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15201 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15202 15203 // The base expression of the innermost MemberExpr may give 15204 // stronger guarantees than the class containing the member. 15205 if (DRE && !TopME->isArrow()) { 15206 const ValueDecl *VD = DRE->getDecl(); 15207 if (!VD->getType()->isReferenceType()) 15208 CompleteObjectAlignment = 15209 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15210 } 15211 15212 // Check if the synthesized offset fulfills the alignment. 15213 if (Offset % ExpectedAlignment != 0 || 15214 // It may fulfill the offset it but the effective alignment may still be 15215 // lower than the expected expression alignment. 15216 CompleteObjectAlignment < ExpectedAlignment) { 15217 // If this happens, we want to determine a sensible culprit of this. 15218 // Intuitively, watching the chain of member expressions from right to 15219 // left, we start with the required alignment (as required by the field 15220 // type) but some packed attribute in that chain has reduced the alignment. 15221 // It may happen that another packed structure increases it again. But if 15222 // we are here such increase has not been enough. So pointing the first 15223 // FieldDecl that either is packed or else its RecordDecl is, 15224 // seems reasonable. 15225 FieldDecl *FD = nullptr; 15226 CharUnits Alignment; 15227 for (FieldDecl *FDI : ReverseMemberChain) { 15228 if (FDI->hasAttr<PackedAttr>() || 15229 FDI->getParent()->hasAttr<PackedAttr>()) { 15230 FD = FDI; 15231 Alignment = std::min( 15232 Context.getTypeAlignInChars(FD->getType()), 15233 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15234 break; 15235 } 15236 } 15237 assert(FD && "We did not find a packed FieldDecl!"); 15238 Action(E, FD->getParent(), FD, Alignment); 15239 } 15240 } 15241 15242 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15243 using namespace std::placeholders; 15244 15245 RefersToMemberWithReducedAlignment( 15246 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15247 _2, _3, _4)); 15248 } 15249 15250 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15251 ExprResult CallResult) { 15252 if (checkArgCount(*this, TheCall, 1)) 15253 return ExprError(); 15254 15255 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15256 if (MatrixArg.isInvalid()) 15257 return MatrixArg; 15258 Expr *Matrix = MatrixArg.get(); 15259 15260 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15261 if (!MType) { 15262 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 15263 return ExprError(); 15264 } 15265 15266 // Create returned matrix type by swapping rows and columns of the argument 15267 // matrix type. 15268 QualType ResultType = Context.getConstantMatrixType( 15269 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15270 15271 // Change the return type to the type of the returned matrix. 15272 TheCall->setType(ResultType); 15273 15274 // Update call argument to use the possibly converted matrix argument. 15275 TheCall->setArg(0, Matrix); 15276 return CallResult; 15277 } 15278 15279 // Get and verify the matrix dimensions. 15280 static llvm::Optional<unsigned> 15281 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 15282 llvm::APSInt Value(64); 15283 SourceLocation ErrorPos; 15284 if (!Expr->isIntegerConstantExpr(Value, S.Context, &ErrorPos)) { 15285 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 15286 << Name; 15287 return {}; 15288 } 15289 uint64_t Dim = Value.getZExtValue(); 15290 if (!ConstantMatrixType::isDimensionValid(Dim)) { 15291 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 15292 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 15293 return {}; 15294 } 15295 return Dim; 15296 } 15297 15298 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 15299 ExprResult CallResult) { 15300 if (!getLangOpts().MatrixTypes) { 15301 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 15302 return ExprError(); 15303 } 15304 15305 if (checkArgCount(*this, TheCall, 4)) 15306 return ExprError(); 15307 15308 unsigned PtrArgIdx = 0; 15309 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15310 Expr *RowsExpr = TheCall->getArg(1); 15311 Expr *ColumnsExpr = TheCall->getArg(2); 15312 Expr *StrideExpr = TheCall->getArg(3); 15313 15314 bool ArgError = false; 15315 15316 // Check pointer argument. 15317 { 15318 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15319 if (PtrConv.isInvalid()) 15320 return PtrConv; 15321 PtrExpr = PtrConv.get(); 15322 TheCall->setArg(0, PtrExpr); 15323 if (PtrExpr->isTypeDependent()) { 15324 TheCall->setType(Context.DependentTy); 15325 return TheCall; 15326 } 15327 } 15328 15329 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15330 QualType ElementTy; 15331 if (!PtrTy) { 15332 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15333 << PtrArgIdx + 1; 15334 ArgError = true; 15335 } else { 15336 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 15337 15338 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 15339 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15340 << PtrArgIdx + 1; 15341 ArgError = true; 15342 } 15343 } 15344 15345 // Apply default Lvalue conversions and convert the expression to size_t. 15346 auto ApplyArgumentConversions = [this](Expr *E) { 15347 ExprResult Conv = DefaultLvalueConversion(E); 15348 if (Conv.isInvalid()) 15349 return Conv; 15350 15351 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 15352 }; 15353 15354 // Apply conversion to row and column expressions. 15355 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 15356 if (!RowsConv.isInvalid()) { 15357 RowsExpr = RowsConv.get(); 15358 TheCall->setArg(1, RowsExpr); 15359 } else 15360 RowsExpr = nullptr; 15361 15362 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 15363 if (!ColumnsConv.isInvalid()) { 15364 ColumnsExpr = ColumnsConv.get(); 15365 TheCall->setArg(2, ColumnsExpr); 15366 } else 15367 ColumnsExpr = nullptr; 15368 15369 // If any any part of the result matrix type is still pending, just use 15370 // Context.DependentTy, until all parts are resolved. 15371 if ((RowsExpr && RowsExpr->isTypeDependent()) || 15372 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 15373 TheCall->setType(Context.DependentTy); 15374 return CallResult; 15375 } 15376 15377 // Check row and column dimenions. 15378 llvm::Optional<unsigned> MaybeRows; 15379 if (RowsExpr) 15380 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 15381 15382 llvm::Optional<unsigned> MaybeColumns; 15383 if (ColumnsExpr) 15384 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 15385 15386 // Check stride argument. 15387 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 15388 if (StrideConv.isInvalid()) 15389 return ExprError(); 15390 StrideExpr = StrideConv.get(); 15391 TheCall->setArg(3, StrideExpr); 15392 15393 llvm::APSInt Value(64); 15394 if (MaybeRows && StrideExpr->isIntegerConstantExpr(Value, Context)) { 15395 uint64_t Stride = Value.getZExtValue(); 15396 if (Stride < *MaybeRows) { 15397 Diag(StrideExpr->getBeginLoc(), 15398 diag::err_builtin_matrix_stride_too_small); 15399 ArgError = true; 15400 } 15401 } 15402 15403 if (ArgError || !MaybeRows || !MaybeColumns) 15404 return ExprError(); 15405 15406 TheCall->setType( 15407 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 15408 return CallResult; 15409 } 15410 15411 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 15412 ExprResult CallResult) { 15413 if (checkArgCount(*this, TheCall, 3)) 15414 return ExprError(); 15415 15416 unsigned PtrArgIdx = 1; 15417 Expr *MatrixExpr = TheCall->getArg(0); 15418 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15419 Expr *StrideExpr = TheCall->getArg(2); 15420 15421 bool ArgError = false; 15422 15423 { 15424 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 15425 if (MatrixConv.isInvalid()) 15426 return MatrixConv; 15427 MatrixExpr = MatrixConv.get(); 15428 TheCall->setArg(0, MatrixExpr); 15429 } 15430 if (MatrixExpr->isTypeDependent()) { 15431 TheCall->setType(Context.DependentTy); 15432 return TheCall; 15433 } 15434 15435 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 15436 if (!MatrixTy) { 15437 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 15438 ArgError = true; 15439 } 15440 15441 { 15442 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15443 if (PtrConv.isInvalid()) 15444 return PtrConv; 15445 PtrExpr = PtrConv.get(); 15446 TheCall->setArg(1, PtrExpr); 15447 if (PtrExpr->isTypeDependent()) { 15448 TheCall->setType(Context.DependentTy); 15449 return TheCall; 15450 } 15451 } 15452 15453 // Check pointer argument. 15454 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15455 if (!PtrTy) { 15456 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15457 << PtrArgIdx + 1; 15458 ArgError = true; 15459 } else { 15460 QualType ElementTy = PtrTy->getPointeeType(); 15461 if (ElementTy.isConstQualified()) { 15462 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 15463 ArgError = true; 15464 } 15465 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 15466 if (MatrixTy && 15467 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 15468 Diag(PtrExpr->getBeginLoc(), 15469 diag::err_builtin_matrix_pointer_arg_mismatch) 15470 << ElementTy << MatrixTy->getElementType(); 15471 ArgError = true; 15472 } 15473 } 15474 15475 // Apply default Lvalue conversions and convert the stride expression to 15476 // size_t. 15477 { 15478 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 15479 if (StrideConv.isInvalid()) 15480 return StrideConv; 15481 15482 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 15483 if (StrideConv.isInvalid()) 15484 return StrideConv; 15485 StrideExpr = StrideConv.get(); 15486 TheCall->setArg(2, StrideExpr); 15487 } 15488 15489 // Check stride argument. 15490 llvm::APSInt Value(64); 15491 if (MatrixTy && StrideExpr->isIntegerConstantExpr(Value, Context)) { 15492 uint64_t Stride = Value.getZExtValue(); 15493 if (Stride < MatrixTy->getNumRows()) { 15494 Diag(StrideExpr->getBeginLoc(), 15495 diag::err_builtin_matrix_stride_too_small); 15496 ArgError = true; 15497 } 15498 } 15499 15500 if (ArgError) 15501 return ExprError(); 15502 15503 return CallResult; 15504 } 15505