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/Stmt.h" 34 #include "clang/AST/TemplateBase.h" 35 #include "clang/AST/Type.h" 36 #include "clang/AST/TypeLoc.h" 37 #include "clang/AST/UnresolvedSet.h" 38 #include "clang/Basic/AddressSpaces.h" 39 #include "clang/Basic/CharInfo.h" 40 #include "clang/Basic/Diagnostic.h" 41 #include "clang/Basic/IdentifierTable.h" 42 #include "clang/Basic/LLVM.h" 43 #include "clang/Basic/LangOptions.h" 44 #include "clang/Basic/OpenCLOptions.h" 45 #include "clang/Basic/OperatorKinds.h" 46 #include "clang/Basic/PartialDiagnostic.h" 47 #include "clang/Basic/SourceLocation.h" 48 #include "clang/Basic/SourceManager.h" 49 #include "clang/Basic/Specifiers.h" 50 #include "clang/Basic/SyncScope.h" 51 #include "clang/Basic/TargetBuiltins.h" 52 #include "clang/Basic/TargetCXXABI.h" 53 #include "clang/Basic/TargetInfo.h" 54 #include "clang/Basic/TypeTraits.h" 55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 56 #include "clang/Sema/Initialization.h" 57 #include "clang/Sema/Lookup.h" 58 #include "clang/Sema/Ownership.h" 59 #include "clang/Sema/Scope.h" 60 #include "clang/Sema/ScopeInfo.h" 61 #include "clang/Sema/Sema.h" 62 #include "clang/Sema/SemaInternal.h" 63 #include "llvm/ADT/APFloat.h" 64 #include "llvm/ADT/APInt.h" 65 #include "llvm/ADT/APSInt.h" 66 #include "llvm/ADT/ArrayRef.h" 67 #include "llvm/ADT/DenseMap.h" 68 #include "llvm/ADT/FoldingSet.h" 69 #include "llvm/ADT/None.h" 70 #include "llvm/ADT/Optional.h" 71 #include "llvm/ADT/STLExtras.h" 72 #include "llvm/ADT/SmallBitVector.h" 73 #include "llvm/ADT/SmallPtrSet.h" 74 #include "llvm/ADT/SmallString.h" 75 #include "llvm/ADT/SmallVector.h" 76 #include "llvm/ADT/StringRef.h" 77 #include "llvm/ADT/StringSwitch.h" 78 #include "llvm/ADT/Triple.h" 79 #include "llvm/Support/AtomicOrdering.h" 80 #include "llvm/Support/Casting.h" 81 #include "llvm/Support/Compiler.h" 82 #include "llvm/Support/ConvertUTF.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/Format.h" 85 #include "llvm/Support/Locale.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/SaveAndRestore.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include <algorithm> 90 #include <cassert> 91 #include <cstddef> 92 #include <cstdint> 93 #include <functional> 94 #include <limits> 95 #include <string> 96 #include <tuple> 97 #include <utility> 98 99 using namespace clang; 100 using namespace sema; 101 102 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 103 unsigned ByteNo) const { 104 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 105 Context.getTargetInfo()); 106 } 107 108 /// Checks that a call expression's argument count is the desired number. 109 /// This is useful when doing custom type-checking. Returns true on error. 110 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 111 unsigned argCount = call->getNumArgs(); 112 if (argCount == desiredArgCount) return false; 113 114 if (argCount < desiredArgCount) 115 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 116 << 0 /*function call*/ << desiredArgCount << argCount 117 << call->getSourceRange(); 118 119 // Highlight all the excess arguments. 120 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 121 call->getArg(argCount - 1)->getEndLoc()); 122 123 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 124 << 0 /*function call*/ << desiredArgCount << argCount 125 << call->getArg(1)->getSourceRange(); 126 } 127 128 /// Check that the first argument to __builtin_annotation is an integer 129 /// and the second argument is a non-wide string literal. 130 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 131 if (checkArgCount(S, TheCall, 2)) 132 return true; 133 134 // First argument should be an integer. 135 Expr *ValArg = TheCall->getArg(0); 136 QualType Ty = ValArg->getType(); 137 if (!Ty->isIntegerType()) { 138 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 139 << ValArg->getSourceRange(); 140 return true; 141 } 142 143 // Second argument should be a constant string. 144 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 145 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 146 if (!Literal || !Literal->isAscii()) { 147 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 148 << StrArg->getSourceRange(); 149 return true; 150 } 151 152 TheCall->setType(Ty); 153 return false; 154 } 155 156 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 157 // We need at least one argument. 158 if (TheCall->getNumArgs() < 1) { 159 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 160 << 0 << 1 << TheCall->getNumArgs() 161 << TheCall->getCallee()->getSourceRange(); 162 return true; 163 } 164 165 // All arguments should be wide string literals. 166 for (Expr *Arg : TheCall->arguments()) { 167 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 168 if (!Literal || !Literal->isWide()) { 169 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 170 << Arg->getSourceRange(); 171 return true; 172 } 173 } 174 175 return false; 176 } 177 178 /// Check that the argument to __builtin_addressof is a glvalue, and set the 179 /// result type to the corresponding pointer type. 180 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 181 if (checkArgCount(S, TheCall, 1)) 182 return true; 183 184 ExprResult Arg(TheCall->getArg(0)); 185 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 186 if (ResultType.isNull()) 187 return true; 188 189 TheCall->setArg(0, Arg.get()); 190 TheCall->setType(ResultType); 191 return false; 192 } 193 194 /// Check the number of arguments and set the result type to 195 /// the argument type. 196 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 197 if (checkArgCount(S, TheCall, 1)) 198 return true; 199 200 TheCall->setType(TheCall->getArg(0)->getType()); 201 return false; 202 } 203 204 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 205 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 206 /// type (but not a function pointer) and that the alignment is a power-of-two. 207 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 208 if (checkArgCount(S, TheCall, 2)) 209 return true; 210 211 clang::Expr *Source = TheCall->getArg(0); 212 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 213 214 auto IsValidIntegerType = [](QualType Ty) { 215 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 216 }; 217 QualType SrcTy = Source->getType(); 218 // We should also be able to use it with arrays (but not functions!). 219 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 220 SrcTy = S.Context.getDecayedType(SrcTy); 221 } 222 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 223 SrcTy->isFunctionPointerType()) { 224 // FIXME: this is not quite the right error message since we don't allow 225 // floating point types, or member pointers. 226 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 227 << SrcTy; 228 return true; 229 } 230 231 clang::Expr *AlignOp = TheCall->getArg(1); 232 if (!IsValidIntegerType(AlignOp->getType())) { 233 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 234 << AlignOp->getType(); 235 return true; 236 } 237 Expr::EvalResult AlignResult; 238 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 239 // We can't check validity of alignment if it is type dependent. 240 if (!AlignOp->isInstantiationDependent() && 241 AlignOp->EvaluateAsInt(AlignResult, S.Context, 242 Expr::SE_AllowSideEffects)) { 243 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 244 llvm::APSInt MaxValue( 245 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 246 if (AlignValue < 1) { 247 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 248 return true; 249 } 250 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 252 << MaxValue.toString(10); 253 return true; 254 } 255 if (!AlignValue.isPowerOf2()) { 256 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 257 return true; 258 } 259 if (AlignValue == 1) { 260 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 261 << IsBooleanAlignBuiltin; 262 } 263 } 264 265 ExprResult SrcArg = S.PerformCopyInitialization( 266 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 267 SourceLocation(), Source); 268 if (SrcArg.isInvalid()) 269 return true; 270 TheCall->setArg(0, SrcArg.get()); 271 ExprResult AlignArg = 272 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 273 S.Context, AlignOp->getType(), false), 274 SourceLocation(), AlignOp); 275 if (AlignArg.isInvalid()) 276 return true; 277 TheCall->setArg(1, AlignArg.get()); 278 // For align_up/align_down, the return type is the same as the (potentially 279 // decayed) argument type including qualifiers. For is_aligned(), the result 280 // is always bool. 281 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 282 return false; 283 } 284 285 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) { 286 if (checkArgCount(S, TheCall, 3)) 287 return true; 288 289 // First two arguments should be integers. 290 for (unsigned I = 0; I < 2; ++I) { 291 ExprResult Arg = TheCall->getArg(I); 292 QualType Ty = Arg.get()->getType(); 293 if (!Ty->isIntegerType()) { 294 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 295 << Ty << Arg.get()->getSourceRange(); 296 return true; 297 } 298 InitializedEntity Entity = InitializedEntity::InitializeParameter( 299 S.getASTContext(), Ty, /*consume*/ false); 300 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 301 if (Arg.isInvalid()) 302 return true; 303 TheCall->setArg(I, Arg.get()); 304 } 305 306 // Third argument should be a pointer to a non-const integer. 307 // IRGen correctly handles volatile, restrict, and address spaces, and 308 // the other qualifiers aren't possible. 309 { 310 ExprResult Arg = TheCall->getArg(2); 311 QualType Ty = Arg.get()->getType(); 312 const auto *PtrTy = Ty->getAs<PointerType>(); 313 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() && 314 !PtrTy->getPointeeType().isConstQualified())) { 315 S.Diag(Arg.get()->getBeginLoc(), 316 diag::err_overflow_builtin_must_be_ptr_int) 317 << Ty << Arg.get()->getSourceRange(); 318 return true; 319 } 320 InitializedEntity Entity = InitializedEntity::InitializeParameter( 321 S.getASTContext(), Ty, /*consume*/ false); 322 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 323 if (Arg.isInvalid()) 324 return true; 325 TheCall->setArg(2, Arg.get()); 326 } 327 return false; 328 } 329 330 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 331 if (checkArgCount(S, BuiltinCall, 2)) 332 return true; 333 334 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 335 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 336 Expr *Call = BuiltinCall->getArg(0); 337 Expr *Chain = BuiltinCall->getArg(1); 338 339 if (Call->getStmtClass() != Stmt::CallExprClass) { 340 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 341 << Call->getSourceRange(); 342 return true; 343 } 344 345 auto CE = cast<CallExpr>(Call); 346 if (CE->getCallee()->getType()->isBlockPointerType()) { 347 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 348 << Call->getSourceRange(); 349 return true; 350 } 351 352 const Decl *TargetDecl = CE->getCalleeDecl(); 353 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 354 if (FD->getBuiltinID()) { 355 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 356 << Call->getSourceRange(); 357 return true; 358 } 359 360 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 361 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 362 << Call->getSourceRange(); 363 return true; 364 } 365 366 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 367 if (ChainResult.isInvalid()) 368 return true; 369 if (!ChainResult.get()->getType()->isPointerType()) { 370 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 371 << Chain->getSourceRange(); 372 return true; 373 } 374 375 QualType ReturnTy = CE->getCallReturnType(S.Context); 376 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 377 QualType BuiltinTy = S.Context.getFunctionType( 378 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 379 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 380 381 Builtin = 382 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 383 384 BuiltinCall->setType(CE->getType()); 385 BuiltinCall->setValueKind(CE->getValueKind()); 386 BuiltinCall->setObjectKind(CE->getObjectKind()); 387 BuiltinCall->setCallee(Builtin); 388 BuiltinCall->setArg(1, ChainResult.get()); 389 390 return false; 391 } 392 393 namespace { 394 395 class EstimateSizeFormatHandler 396 : public analyze_format_string::FormatStringHandler { 397 size_t Size; 398 399 public: 400 EstimateSizeFormatHandler(StringRef Format) 401 : Size(std::min(Format.find(0), Format.size()) + 402 1 /* null byte always written by sprintf */) {} 403 404 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 405 const char *, unsigned SpecifierLen) override { 406 407 const size_t FieldWidth = computeFieldWidth(FS); 408 const size_t Precision = computePrecision(FS); 409 410 // The actual format. 411 switch (FS.getConversionSpecifier().getKind()) { 412 // Just a char. 413 case analyze_format_string::ConversionSpecifier::cArg: 414 case analyze_format_string::ConversionSpecifier::CArg: 415 Size += std::max(FieldWidth, (size_t)1); 416 break; 417 // Just an integer. 418 case analyze_format_string::ConversionSpecifier::dArg: 419 case analyze_format_string::ConversionSpecifier::DArg: 420 case analyze_format_string::ConversionSpecifier::iArg: 421 case analyze_format_string::ConversionSpecifier::oArg: 422 case analyze_format_string::ConversionSpecifier::OArg: 423 case analyze_format_string::ConversionSpecifier::uArg: 424 case analyze_format_string::ConversionSpecifier::UArg: 425 case analyze_format_string::ConversionSpecifier::xArg: 426 case analyze_format_string::ConversionSpecifier::XArg: 427 Size += std::max(FieldWidth, Precision); 428 break; 429 430 // %g style conversion switches between %f or %e style dynamically. 431 // %f always takes less space, so default to it. 432 case analyze_format_string::ConversionSpecifier::gArg: 433 case analyze_format_string::ConversionSpecifier::GArg: 434 435 // Floating point number in the form '[+]ddd.ddd'. 436 case analyze_format_string::ConversionSpecifier::fArg: 437 case analyze_format_string::ConversionSpecifier::FArg: 438 Size += std::max(FieldWidth, 1 /* integer part */ + 439 (Precision ? 1 + Precision 440 : 0) /* period + decimal */); 441 break; 442 443 // Floating point number in the form '[-]d.ddde[+-]dd'. 444 case analyze_format_string::ConversionSpecifier::eArg: 445 case analyze_format_string::ConversionSpecifier::EArg: 446 Size += 447 std::max(FieldWidth, 448 1 /* integer part */ + 449 (Precision ? 1 + Precision : 0) /* period + decimal */ + 450 1 /* e or E letter */ + 2 /* exponent */); 451 break; 452 453 // Floating point number in the form '[-]0xh.hhhhp±dd'. 454 case analyze_format_string::ConversionSpecifier::aArg: 455 case analyze_format_string::ConversionSpecifier::AArg: 456 Size += 457 std::max(FieldWidth, 458 2 /* 0x */ + 1 /* integer part */ + 459 (Precision ? 1 + Precision : 0) /* period + decimal */ + 460 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 461 break; 462 463 // Just a string. 464 case analyze_format_string::ConversionSpecifier::sArg: 465 case analyze_format_string::ConversionSpecifier::SArg: 466 Size += FieldWidth; 467 break; 468 469 // Just a pointer in the form '0xddd'. 470 case analyze_format_string::ConversionSpecifier::pArg: 471 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 472 break; 473 474 // A plain percent. 475 case analyze_format_string::ConversionSpecifier::PercentArg: 476 Size += 1; 477 break; 478 479 default: 480 break; 481 } 482 483 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 484 485 if (FS.hasAlternativeForm()) { 486 switch (FS.getConversionSpecifier().getKind()) { 487 default: 488 break; 489 // Force a leading '0'. 490 case analyze_format_string::ConversionSpecifier::oArg: 491 Size += 1; 492 break; 493 // Force a leading '0x'. 494 case analyze_format_string::ConversionSpecifier::xArg: 495 case analyze_format_string::ConversionSpecifier::XArg: 496 Size += 2; 497 break; 498 // Force a period '.' before decimal, even if precision is 0. 499 case analyze_format_string::ConversionSpecifier::aArg: 500 case analyze_format_string::ConversionSpecifier::AArg: 501 case analyze_format_string::ConversionSpecifier::eArg: 502 case analyze_format_string::ConversionSpecifier::EArg: 503 case analyze_format_string::ConversionSpecifier::fArg: 504 case analyze_format_string::ConversionSpecifier::FArg: 505 case analyze_format_string::ConversionSpecifier::gArg: 506 case analyze_format_string::ConversionSpecifier::GArg: 507 Size += (Precision ? 0 : 1); 508 break; 509 } 510 } 511 assert(SpecifierLen <= Size && "no underflow"); 512 Size -= SpecifierLen; 513 return true; 514 } 515 516 size_t getSizeLowerBound() const { return Size; } 517 518 private: 519 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 520 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 521 size_t FieldWidth = 0; 522 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 523 FieldWidth = FW.getConstantAmount(); 524 return FieldWidth; 525 } 526 527 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 528 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 529 size_t Precision = 0; 530 531 // See man 3 printf for default precision value based on the specifier. 532 switch (FW.getHowSpecified()) { 533 case analyze_format_string::OptionalAmount::NotSpecified: 534 switch (FS.getConversionSpecifier().getKind()) { 535 default: 536 break; 537 case analyze_format_string::ConversionSpecifier::dArg: // %d 538 case analyze_format_string::ConversionSpecifier::DArg: // %D 539 case analyze_format_string::ConversionSpecifier::iArg: // %i 540 Precision = 1; 541 break; 542 case analyze_format_string::ConversionSpecifier::oArg: // %d 543 case analyze_format_string::ConversionSpecifier::OArg: // %D 544 case analyze_format_string::ConversionSpecifier::uArg: // %d 545 case analyze_format_string::ConversionSpecifier::UArg: // %D 546 case analyze_format_string::ConversionSpecifier::xArg: // %d 547 case analyze_format_string::ConversionSpecifier::XArg: // %D 548 Precision = 1; 549 break; 550 case analyze_format_string::ConversionSpecifier::fArg: // %f 551 case analyze_format_string::ConversionSpecifier::FArg: // %F 552 case analyze_format_string::ConversionSpecifier::eArg: // %e 553 case analyze_format_string::ConversionSpecifier::EArg: // %E 554 case analyze_format_string::ConversionSpecifier::gArg: // %g 555 case analyze_format_string::ConversionSpecifier::GArg: // %G 556 Precision = 6; 557 break; 558 case analyze_format_string::ConversionSpecifier::pArg: // %d 559 Precision = 1; 560 break; 561 } 562 break; 563 case analyze_format_string::OptionalAmount::Constant: 564 Precision = FW.getConstantAmount(); 565 break; 566 default: 567 break; 568 } 569 return Precision; 570 } 571 }; 572 573 } // namespace 574 575 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 576 /// __builtin_*_chk function, then use the object size argument specified in the 577 /// source. Otherwise, infer the object size using __builtin_object_size. 578 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 579 CallExpr *TheCall) { 580 // FIXME: There are some more useful checks we could be doing here: 581 // - Evaluate strlen of strcpy arguments, use as object size. 582 583 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 584 isConstantEvaluated()) 585 return; 586 587 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 588 if (!BuiltinID) 589 return; 590 591 const TargetInfo &TI = getASTContext().getTargetInfo(); 592 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 593 594 unsigned DiagID = 0; 595 bool IsChkVariant = false; 596 Optional<llvm::APSInt> UsedSize; 597 unsigned SizeIndex, ObjectIndex; 598 switch (BuiltinID) { 599 default: 600 return; 601 case Builtin::BIsprintf: 602 case Builtin::BI__builtin___sprintf_chk: { 603 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 604 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 605 606 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 607 608 if (!Format->isAscii() && !Format->isUTF8()) 609 return; 610 611 StringRef FormatStrRef = Format->getString(); 612 EstimateSizeFormatHandler H(FormatStrRef); 613 const char *FormatBytes = FormatStrRef.data(); 614 const ConstantArrayType *T = 615 Context.getAsConstantArrayType(Format->getType()); 616 assert(T && "String literal not of constant array type!"); 617 size_t TypeSize = T->getSize().getZExtValue(); 618 619 // In case there's a null byte somewhere. 620 size_t StrLen = 621 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 622 if (!analyze_format_string::ParsePrintfString( 623 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 624 Context.getTargetInfo(), false)) { 625 DiagID = diag::warn_fortify_source_format_overflow; 626 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 627 .extOrTrunc(SizeTypeWidth); 628 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 629 IsChkVariant = true; 630 ObjectIndex = 2; 631 } else { 632 IsChkVariant = false; 633 ObjectIndex = 0; 634 } 635 break; 636 } 637 } 638 return; 639 } 640 case Builtin::BI__builtin___memcpy_chk: 641 case Builtin::BI__builtin___memmove_chk: 642 case Builtin::BI__builtin___memset_chk: 643 case Builtin::BI__builtin___strlcat_chk: 644 case Builtin::BI__builtin___strlcpy_chk: 645 case Builtin::BI__builtin___strncat_chk: 646 case Builtin::BI__builtin___strncpy_chk: 647 case Builtin::BI__builtin___stpncpy_chk: 648 case Builtin::BI__builtin___memccpy_chk: 649 case Builtin::BI__builtin___mempcpy_chk: { 650 DiagID = diag::warn_builtin_chk_overflow; 651 IsChkVariant = true; 652 SizeIndex = TheCall->getNumArgs() - 2; 653 ObjectIndex = TheCall->getNumArgs() - 1; 654 break; 655 } 656 657 case Builtin::BI__builtin___snprintf_chk: 658 case Builtin::BI__builtin___vsnprintf_chk: { 659 DiagID = diag::warn_builtin_chk_overflow; 660 IsChkVariant = true; 661 SizeIndex = 1; 662 ObjectIndex = 3; 663 break; 664 } 665 666 case Builtin::BIstrncat: 667 case Builtin::BI__builtin_strncat: 668 case Builtin::BIstrncpy: 669 case Builtin::BI__builtin_strncpy: 670 case Builtin::BIstpncpy: 671 case Builtin::BI__builtin_stpncpy: { 672 // Whether these functions overflow depends on the runtime strlen of the 673 // string, not just the buffer size, so emitting the "always overflow" 674 // diagnostic isn't quite right. We should still diagnose passing a buffer 675 // size larger than the destination buffer though; this is a runtime abort 676 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 677 DiagID = diag::warn_fortify_source_size_mismatch; 678 SizeIndex = TheCall->getNumArgs() - 1; 679 ObjectIndex = 0; 680 break; 681 } 682 683 case Builtin::BImemcpy: 684 case Builtin::BI__builtin_memcpy: 685 case Builtin::BImemmove: 686 case Builtin::BI__builtin_memmove: 687 case Builtin::BImemset: 688 case Builtin::BI__builtin_memset: 689 case Builtin::BImempcpy: 690 case Builtin::BI__builtin_mempcpy: { 691 DiagID = diag::warn_fortify_source_overflow; 692 SizeIndex = TheCall->getNumArgs() - 1; 693 ObjectIndex = 0; 694 break; 695 } 696 case Builtin::BIsnprintf: 697 case Builtin::BI__builtin_snprintf: 698 case Builtin::BIvsnprintf: 699 case Builtin::BI__builtin_vsnprintf: { 700 DiagID = diag::warn_fortify_source_size_mismatch; 701 SizeIndex = 1; 702 ObjectIndex = 0; 703 break; 704 } 705 } 706 707 llvm::APSInt ObjectSize; 708 // For __builtin___*_chk, the object size is explicitly provided by the caller 709 // (usually using __builtin_object_size). Use that value to check this call. 710 if (IsChkVariant) { 711 Expr::EvalResult Result; 712 Expr *SizeArg = TheCall->getArg(ObjectIndex); 713 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 714 return; 715 ObjectSize = Result.Val.getInt(); 716 717 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 718 } else { 719 // If the parameter has a pass_object_size attribute, then we should use its 720 // (potentially) more strict checking mode. Otherwise, conservatively assume 721 // type 0. 722 int BOSType = 0; 723 if (const auto *POS = 724 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 725 BOSType = POS->getType(); 726 727 Expr *ObjArg = TheCall->getArg(ObjectIndex); 728 uint64_t Result; 729 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 730 return; 731 // Get the object size in the target's size_t width. 732 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 733 } 734 735 // Evaluate the number of bytes of the object that this call will use. 736 if (!UsedSize) { 737 Expr::EvalResult Result; 738 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 739 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 740 return; 741 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 742 } 743 744 if (UsedSize.getValue().ule(ObjectSize)) 745 return; 746 747 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 748 // Skim off the details of whichever builtin was called to produce a better 749 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 750 if (IsChkVariant) { 751 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 752 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 753 } else if (FunctionName.startswith("__builtin_")) { 754 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 755 } 756 757 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 758 PDiag(DiagID) 759 << FunctionName << ObjectSize.toString(/*Radix=*/10) 760 << UsedSize.getValue().toString(/*Radix=*/10)); 761 } 762 763 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 764 Scope::ScopeFlags NeededScopeFlags, 765 unsigned DiagID) { 766 // Scopes aren't available during instantiation. Fortunately, builtin 767 // functions cannot be template args so they cannot be formed through template 768 // instantiation. Therefore checking once during the parse is sufficient. 769 if (SemaRef.inTemplateInstantiation()) 770 return false; 771 772 Scope *S = SemaRef.getCurScope(); 773 while (S && !S->isSEHExceptScope()) 774 S = S->getParent(); 775 if (!S || !(S->getFlags() & NeededScopeFlags)) { 776 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 777 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 778 << DRE->getDecl()->getIdentifier(); 779 return true; 780 } 781 782 return false; 783 } 784 785 static inline bool isBlockPointer(Expr *Arg) { 786 return Arg->getType()->isBlockPointerType(); 787 } 788 789 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 790 /// void*, which is a requirement of device side enqueue. 791 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 792 const BlockPointerType *BPT = 793 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 794 ArrayRef<QualType> Params = 795 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 796 unsigned ArgCounter = 0; 797 bool IllegalParams = false; 798 // Iterate through the block parameters until either one is found that is not 799 // a local void*, or the block is valid. 800 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 801 I != E; ++I, ++ArgCounter) { 802 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 803 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 804 LangAS::opencl_local) { 805 // Get the location of the error. If a block literal has been passed 806 // (BlockExpr) then we can point straight to the offending argument, 807 // else we just point to the variable reference. 808 SourceLocation ErrorLoc; 809 if (isa<BlockExpr>(BlockArg)) { 810 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 811 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 812 } else if (isa<DeclRefExpr>(BlockArg)) { 813 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 814 } 815 S.Diag(ErrorLoc, 816 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 817 IllegalParams = true; 818 } 819 } 820 821 return IllegalParams; 822 } 823 824 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 825 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 826 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 827 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 828 return true; 829 } 830 return false; 831 } 832 833 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 834 if (checkArgCount(S, TheCall, 2)) 835 return true; 836 837 if (checkOpenCLSubgroupExt(S, TheCall)) 838 return true; 839 840 // First argument is an ndrange_t type. 841 Expr *NDRangeArg = TheCall->getArg(0); 842 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 843 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 844 << TheCall->getDirectCallee() << "'ndrange_t'"; 845 return true; 846 } 847 848 Expr *BlockArg = TheCall->getArg(1); 849 if (!isBlockPointer(BlockArg)) { 850 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 851 << TheCall->getDirectCallee() << "block"; 852 return true; 853 } 854 return checkOpenCLBlockArgs(S, BlockArg); 855 } 856 857 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 858 /// get_kernel_work_group_size 859 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 860 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 861 if (checkArgCount(S, TheCall, 1)) 862 return true; 863 864 Expr *BlockArg = TheCall->getArg(0); 865 if (!isBlockPointer(BlockArg)) { 866 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 867 << TheCall->getDirectCallee() << "block"; 868 return true; 869 } 870 return checkOpenCLBlockArgs(S, BlockArg); 871 } 872 873 /// Diagnose integer type and any valid implicit conversion to it. 874 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 875 const QualType &IntType); 876 877 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 878 unsigned Start, unsigned End) { 879 bool IllegalParams = false; 880 for (unsigned I = Start; I <= End; ++I) 881 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 882 S.Context.getSizeType()); 883 return IllegalParams; 884 } 885 886 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 887 /// 'local void*' parameter of passed block. 888 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 889 Expr *BlockArg, 890 unsigned NumNonVarArgs) { 891 const BlockPointerType *BPT = 892 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 893 unsigned NumBlockParams = 894 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 895 unsigned TotalNumArgs = TheCall->getNumArgs(); 896 897 // For each argument passed to the block, a corresponding uint needs to 898 // be passed to describe the size of the local memory. 899 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 900 S.Diag(TheCall->getBeginLoc(), 901 diag::err_opencl_enqueue_kernel_local_size_args); 902 return true; 903 } 904 905 // Check that the sizes of the local memory are specified by integers. 906 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 907 TotalNumArgs - 1); 908 } 909 910 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 911 /// overload formats specified in Table 6.13.17.1. 912 /// int enqueue_kernel(queue_t queue, 913 /// kernel_enqueue_flags_t flags, 914 /// const ndrange_t ndrange, 915 /// void (^block)(void)) 916 /// int enqueue_kernel(queue_t queue, 917 /// kernel_enqueue_flags_t flags, 918 /// const ndrange_t ndrange, 919 /// uint num_events_in_wait_list, 920 /// clk_event_t *event_wait_list, 921 /// clk_event_t *event_ret, 922 /// void (^block)(void)) 923 /// int enqueue_kernel(queue_t queue, 924 /// kernel_enqueue_flags_t flags, 925 /// const ndrange_t ndrange, 926 /// void (^block)(local void*, ...), 927 /// uint size0, ...) 928 /// int enqueue_kernel(queue_t queue, 929 /// kernel_enqueue_flags_t flags, 930 /// const ndrange_t ndrange, 931 /// uint num_events_in_wait_list, 932 /// clk_event_t *event_wait_list, 933 /// clk_event_t *event_ret, 934 /// void (^block)(local void*, ...), 935 /// uint size0, ...) 936 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 937 unsigned NumArgs = TheCall->getNumArgs(); 938 939 if (NumArgs < 4) { 940 S.Diag(TheCall->getBeginLoc(), 941 diag::err_typecheck_call_too_few_args_at_least) 942 << 0 << 4 << NumArgs; 943 return true; 944 } 945 946 Expr *Arg0 = TheCall->getArg(0); 947 Expr *Arg1 = TheCall->getArg(1); 948 Expr *Arg2 = TheCall->getArg(2); 949 Expr *Arg3 = TheCall->getArg(3); 950 951 // First argument always needs to be a queue_t type. 952 if (!Arg0->getType()->isQueueT()) { 953 S.Diag(TheCall->getArg(0)->getBeginLoc(), 954 diag::err_opencl_builtin_expected_type) 955 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 956 return true; 957 } 958 959 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 960 if (!Arg1->getType()->isIntegerType()) { 961 S.Diag(TheCall->getArg(1)->getBeginLoc(), 962 diag::err_opencl_builtin_expected_type) 963 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 964 return true; 965 } 966 967 // Third argument is always an ndrange_t type. 968 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 969 S.Diag(TheCall->getArg(2)->getBeginLoc(), 970 diag::err_opencl_builtin_expected_type) 971 << TheCall->getDirectCallee() << "'ndrange_t'"; 972 return true; 973 } 974 975 // With four arguments, there is only one form that the function could be 976 // called in: no events and no variable arguments. 977 if (NumArgs == 4) { 978 // check that the last argument is the right block type. 979 if (!isBlockPointer(Arg3)) { 980 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 981 << TheCall->getDirectCallee() << "block"; 982 return true; 983 } 984 // we have a block type, check the prototype 985 const BlockPointerType *BPT = 986 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 987 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 988 S.Diag(Arg3->getBeginLoc(), 989 diag::err_opencl_enqueue_kernel_blocks_no_args); 990 return true; 991 } 992 return false; 993 } 994 // we can have block + varargs. 995 if (isBlockPointer(Arg3)) 996 return (checkOpenCLBlockArgs(S, Arg3) || 997 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 998 // last two cases with either exactly 7 args or 7 args and varargs. 999 if (NumArgs >= 7) { 1000 // check common block argument. 1001 Expr *Arg6 = TheCall->getArg(6); 1002 if (!isBlockPointer(Arg6)) { 1003 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1004 << TheCall->getDirectCallee() << "block"; 1005 return true; 1006 } 1007 if (checkOpenCLBlockArgs(S, Arg6)) 1008 return true; 1009 1010 // Forth argument has to be any integer type. 1011 if (!Arg3->getType()->isIntegerType()) { 1012 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1013 diag::err_opencl_builtin_expected_type) 1014 << TheCall->getDirectCallee() << "integer"; 1015 return true; 1016 } 1017 // check remaining common arguments. 1018 Expr *Arg4 = TheCall->getArg(4); 1019 Expr *Arg5 = TheCall->getArg(5); 1020 1021 // Fifth argument is always passed as a pointer to clk_event_t. 1022 if (!Arg4->isNullPointerConstant(S.Context, 1023 Expr::NPC_ValueDependentIsNotNull) && 1024 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1025 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1026 diag::err_opencl_builtin_expected_type) 1027 << TheCall->getDirectCallee() 1028 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1029 return true; 1030 } 1031 1032 // Sixth argument is always passed as a pointer to clk_event_t. 1033 if (!Arg5->isNullPointerConstant(S.Context, 1034 Expr::NPC_ValueDependentIsNotNull) && 1035 !(Arg5->getType()->isPointerType() && 1036 Arg5->getType()->getPointeeType()->isClkEventT())) { 1037 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1038 diag::err_opencl_builtin_expected_type) 1039 << TheCall->getDirectCallee() 1040 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1041 return true; 1042 } 1043 1044 if (NumArgs == 7) 1045 return false; 1046 1047 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1048 } 1049 1050 // None of the specific case has been detected, give generic error 1051 S.Diag(TheCall->getBeginLoc(), 1052 diag::err_opencl_enqueue_kernel_incorrect_args); 1053 return true; 1054 } 1055 1056 /// Returns OpenCL access qual. 1057 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1058 return D->getAttr<OpenCLAccessAttr>(); 1059 } 1060 1061 /// Returns true if pipe element type is different from the pointer. 1062 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1063 const Expr *Arg0 = Call->getArg(0); 1064 // First argument type should always be pipe. 1065 if (!Arg0->getType()->isPipeType()) { 1066 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1067 << Call->getDirectCallee() << Arg0->getSourceRange(); 1068 return true; 1069 } 1070 OpenCLAccessAttr *AccessQual = 1071 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1072 // Validates the access qualifier is compatible with the call. 1073 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1074 // read_only and write_only, and assumed to be read_only if no qualifier is 1075 // specified. 1076 switch (Call->getDirectCallee()->getBuiltinID()) { 1077 case Builtin::BIread_pipe: 1078 case Builtin::BIreserve_read_pipe: 1079 case Builtin::BIcommit_read_pipe: 1080 case Builtin::BIwork_group_reserve_read_pipe: 1081 case Builtin::BIsub_group_reserve_read_pipe: 1082 case Builtin::BIwork_group_commit_read_pipe: 1083 case Builtin::BIsub_group_commit_read_pipe: 1084 if (!(!AccessQual || AccessQual->isReadOnly())) { 1085 S.Diag(Arg0->getBeginLoc(), 1086 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1087 << "read_only" << Arg0->getSourceRange(); 1088 return true; 1089 } 1090 break; 1091 case Builtin::BIwrite_pipe: 1092 case Builtin::BIreserve_write_pipe: 1093 case Builtin::BIcommit_write_pipe: 1094 case Builtin::BIwork_group_reserve_write_pipe: 1095 case Builtin::BIsub_group_reserve_write_pipe: 1096 case Builtin::BIwork_group_commit_write_pipe: 1097 case Builtin::BIsub_group_commit_write_pipe: 1098 if (!(AccessQual && AccessQual->isWriteOnly())) { 1099 S.Diag(Arg0->getBeginLoc(), 1100 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1101 << "write_only" << Arg0->getSourceRange(); 1102 return true; 1103 } 1104 break; 1105 default: 1106 break; 1107 } 1108 return false; 1109 } 1110 1111 /// Returns true if pipe element type is different from the pointer. 1112 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1113 const Expr *Arg0 = Call->getArg(0); 1114 const Expr *ArgIdx = Call->getArg(Idx); 1115 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1116 const QualType EltTy = PipeTy->getElementType(); 1117 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1118 // The Idx argument should be a pointer and the type of the pointer and 1119 // the type of pipe element should also be the same. 1120 if (!ArgTy || 1121 !S.Context.hasSameType( 1122 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1123 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1124 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1125 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1126 return true; 1127 } 1128 return false; 1129 } 1130 1131 // Performs semantic analysis for the read/write_pipe call. 1132 // \param S Reference to the semantic analyzer. 1133 // \param Call A pointer to the builtin call. 1134 // \return True if a semantic error has been found, false otherwise. 1135 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1136 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1137 // functions have two forms. 1138 switch (Call->getNumArgs()) { 1139 case 2: 1140 if (checkOpenCLPipeArg(S, Call)) 1141 return true; 1142 // The call with 2 arguments should be 1143 // read/write_pipe(pipe T, T*). 1144 // Check packet type T. 1145 if (checkOpenCLPipePacketType(S, Call, 1)) 1146 return true; 1147 break; 1148 1149 case 4: { 1150 if (checkOpenCLPipeArg(S, Call)) 1151 return true; 1152 // The call with 4 arguments should be 1153 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1154 // Check reserve_id_t. 1155 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1156 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1157 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1158 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1159 return true; 1160 } 1161 1162 // Check the index. 1163 const Expr *Arg2 = Call->getArg(2); 1164 if (!Arg2->getType()->isIntegerType() && 1165 !Arg2->getType()->isUnsignedIntegerType()) { 1166 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1167 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1168 << Arg2->getType() << Arg2->getSourceRange(); 1169 return true; 1170 } 1171 1172 // Check packet type T. 1173 if (checkOpenCLPipePacketType(S, Call, 3)) 1174 return true; 1175 } break; 1176 default: 1177 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1178 << Call->getDirectCallee() << Call->getSourceRange(); 1179 return true; 1180 } 1181 1182 return false; 1183 } 1184 1185 // Performs a semantic analysis on the {work_group_/sub_group_ 1186 // /_}reserve_{read/write}_pipe 1187 // \param S Reference to the semantic analyzer. 1188 // \param Call The call to the builtin function to be analyzed. 1189 // \return True if a semantic error was found, false otherwise. 1190 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1191 if (checkArgCount(S, Call, 2)) 1192 return true; 1193 1194 if (checkOpenCLPipeArg(S, Call)) 1195 return true; 1196 1197 // Check the reserve size. 1198 if (!Call->getArg(1)->getType()->isIntegerType() && 1199 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1200 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1201 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1202 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1203 return true; 1204 } 1205 1206 // Since return type of reserve_read/write_pipe built-in function is 1207 // reserve_id_t, which is not defined in the builtin def file , we used int 1208 // as return type and need to override the return type of these functions. 1209 Call->setType(S.Context.OCLReserveIDTy); 1210 1211 return false; 1212 } 1213 1214 // Performs a semantic analysis on {work_group_/sub_group_ 1215 // /_}commit_{read/write}_pipe 1216 // \param S Reference to the semantic analyzer. 1217 // \param Call The call to the builtin function to be analyzed. 1218 // \return True if a semantic error was found, false otherwise. 1219 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1220 if (checkArgCount(S, Call, 2)) 1221 return true; 1222 1223 if (checkOpenCLPipeArg(S, Call)) 1224 return true; 1225 1226 // Check reserve_id_t. 1227 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1228 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1229 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1230 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1231 return true; 1232 } 1233 1234 return false; 1235 } 1236 1237 // Performs a semantic analysis on the call to built-in Pipe 1238 // Query Functions. 1239 // \param S Reference to the semantic analyzer. 1240 // \param Call The call to the builtin function to be analyzed. 1241 // \return True if a semantic error was found, false otherwise. 1242 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1243 if (checkArgCount(S, Call, 1)) 1244 return true; 1245 1246 if (!Call->getArg(0)->getType()->isPipeType()) { 1247 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1248 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1249 return true; 1250 } 1251 1252 return false; 1253 } 1254 1255 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1256 // Performs semantic analysis for the to_global/local/private call. 1257 // \param S Reference to the semantic analyzer. 1258 // \param BuiltinID ID of the builtin function. 1259 // \param Call A pointer to the builtin call. 1260 // \return True if a semantic error has been found, false otherwise. 1261 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1262 CallExpr *Call) { 1263 if (Call->getNumArgs() != 1) { 1264 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 1265 << Call->getDirectCallee() << Call->getSourceRange(); 1266 return true; 1267 } 1268 1269 auto RT = Call->getArg(0)->getType(); 1270 if (!RT->isPointerType() || RT->getPointeeType() 1271 .getAddressSpace() == LangAS::opencl_constant) { 1272 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1273 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1274 return true; 1275 } 1276 1277 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1278 S.Diag(Call->getArg(0)->getBeginLoc(), 1279 diag::warn_opencl_generic_address_space_arg) 1280 << Call->getDirectCallee()->getNameInfo().getAsString() 1281 << Call->getArg(0)->getSourceRange(); 1282 } 1283 1284 RT = RT->getPointeeType(); 1285 auto Qual = RT.getQualifiers(); 1286 switch (BuiltinID) { 1287 case Builtin::BIto_global: 1288 Qual.setAddressSpace(LangAS::opencl_global); 1289 break; 1290 case Builtin::BIto_local: 1291 Qual.setAddressSpace(LangAS::opencl_local); 1292 break; 1293 case Builtin::BIto_private: 1294 Qual.setAddressSpace(LangAS::opencl_private); 1295 break; 1296 default: 1297 llvm_unreachable("Invalid builtin function"); 1298 } 1299 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1300 RT.getUnqualifiedType(), Qual))); 1301 1302 return false; 1303 } 1304 1305 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1306 if (checkArgCount(S, TheCall, 1)) 1307 return ExprError(); 1308 1309 // Compute __builtin_launder's parameter type from the argument. 1310 // The parameter type is: 1311 // * The type of the argument if it's not an array or function type, 1312 // Otherwise, 1313 // * The decayed argument type. 1314 QualType ParamTy = [&]() { 1315 QualType ArgTy = TheCall->getArg(0)->getType(); 1316 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1317 return S.Context.getPointerType(Ty->getElementType()); 1318 if (ArgTy->isFunctionType()) { 1319 return S.Context.getPointerType(ArgTy); 1320 } 1321 return ArgTy; 1322 }(); 1323 1324 TheCall->setType(ParamTy); 1325 1326 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1327 if (!ParamTy->isPointerType()) 1328 return 0; 1329 if (ParamTy->isFunctionPointerType()) 1330 return 1; 1331 if (ParamTy->isVoidPointerType()) 1332 return 2; 1333 return llvm::Optional<unsigned>{}; 1334 }(); 1335 if (DiagSelect.hasValue()) { 1336 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1337 << DiagSelect.getValue() << TheCall->getSourceRange(); 1338 return ExprError(); 1339 } 1340 1341 // We either have an incomplete class type, or we have a class template 1342 // whose instantiation has not been forced. Example: 1343 // 1344 // template <class T> struct Foo { T value; }; 1345 // Foo<int> *p = nullptr; 1346 // auto *d = __builtin_launder(p); 1347 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1348 diag::err_incomplete_type)) 1349 return ExprError(); 1350 1351 assert(ParamTy->getPointeeType()->isObjectType() && 1352 "Unhandled non-object pointer case"); 1353 1354 InitializedEntity Entity = 1355 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1356 ExprResult Arg = 1357 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1358 if (Arg.isInvalid()) 1359 return ExprError(); 1360 TheCall->setArg(0, Arg.get()); 1361 1362 return TheCall; 1363 } 1364 1365 // Emit an error and return true if the current architecture is not in the list 1366 // of supported architectures. 1367 static bool 1368 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1369 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1370 llvm::Triple::ArchType CurArch = 1371 S.getASTContext().getTargetInfo().getTriple().getArch(); 1372 if (llvm::is_contained(SupportedArchs, CurArch)) 1373 return false; 1374 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1375 << TheCall->getSourceRange(); 1376 return true; 1377 } 1378 1379 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1380 SourceLocation CallSiteLoc); 1381 1382 ExprResult 1383 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1384 CallExpr *TheCall) { 1385 ExprResult TheCallResult(TheCall); 1386 1387 // Find out if any arguments are required to be integer constant expressions. 1388 unsigned ICEArguments = 0; 1389 ASTContext::GetBuiltinTypeError Error; 1390 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1391 if (Error != ASTContext::GE_None) 1392 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1393 1394 // If any arguments are required to be ICE's, check and diagnose. 1395 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1396 // Skip arguments not required to be ICE's. 1397 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1398 1399 llvm::APSInt Result; 1400 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1401 return true; 1402 ICEArguments &= ~(1 << ArgNo); 1403 } 1404 1405 switch (BuiltinID) { 1406 case Builtin::BI__builtin___CFStringMakeConstantString: 1407 assert(TheCall->getNumArgs() == 1 && 1408 "Wrong # arguments to builtin CFStringMakeConstantString"); 1409 if (CheckObjCString(TheCall->getArg(0))) 1410 return ExprError(); 1411 break; 1412 case Builtin::BI__builtin_ms_va_start: 1413 case Builtin::BI__builtin_stdarg_start: 1414 case Builtin::BI__builtin_va_start: 1415 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1416 return ExprError(); 1417 break; 1418 case Builtin::BI__va_start: { 1419 switch (Context.getTargetInfo().getTriple().getArch()) { 1420 case llvm::Triple::aarch64: 1421 case llvm::Triple::arm: 1422 case llvm::Triple::thumb: 1423 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1424 return ExprError(); 1425 break; 1426 default: 1427 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1428 return ExprError(); 1429 break; 1430 } 1431 break; 1432 } 1433 1434 // The acquire, release, and no fence variants are ARM and AArch64 only. 1435 case Builtin::BI_interlockedbittestandset_acq: 1436 case Builtin::BI_interlockedbittestandset_rel: 1437 case Builtin::BI_interlockedbittestandset_nf: 1438 case Builtin::BI_interlockedbittestandreset_acq: 1439 case Builtin::BI_interlockedbittestandreset_rel: 1440 case Builtin::BI_interlockedbittestandreset_nf: 1441 if (CheckBuiltinTargetSupport( 1442 *this, BuiltinID, TheCall, 1443 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1444 return ExprError(); 1445 break; 1446 1447 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1448 case Builtin::BI_bittest64: 1449 case Builtin::BI_bittestandcomplement64: 1450 case Builtin::BI_bittestandreset64: 1451 case Builtin::BI_bittestandset64: 1452 case Builtin::BI_interlockedbittestandreset64: 1453 case Builtin::BI_interlockedbittestandset64: 1454 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1455 {llvm::Triple::x86_64, llvm::Triple::arm, 1456 llvm::Triple::thumb, llvm::Triple::aarch64})) 1457 return ExprError(); 1458 break; 1459 1460 case Builtin::BI__builtin_isgreater: 1461 case Builtin::BI__builtin_isgreaterequal: 1462 case Builtin::BI__builtin_isless: 1463 case Builtin::BI__builtin_islessequal: 1464 case Builtin::BI__builtin_islessgreater: 1465 case Builtin::BI__builtin_isunordered: 1466 if (SemaBuiltinUnorderedCompare(TheCall)) 1467 return ExprError(); 1468 break; 1469 case Builtin::BI__builtin_fpclassify: 1470 if (SemaBuiltinFPClassification(TheCall, 6)) 1471 return ExprError(); 1472 break; 1473 case Builtin::BI__builtin_isfinite: 1474 case Builtin::BI__builtin_isinf: 1475 case Builtin::BI__builtin_isinf_sign: 1476 case Builtin::BI__builtin_isnan: 1477 case Builtin::BI__builtin_isnormal: 1478 case Builtin::BI__builtin_signbit: 1479 case Builtin::BI__builtin_signbitf: 1480 case Builtin::BI__builtin_signbitl: 1481 if (SemaBuiltinFPClassification(TheCall, 1)) 1482 return ExprError(); 1483 break; 1484 case Builtin::BI__builtin_shufflevector: 1485 return SemaBuiltinShuffleVector(TheCall); 1486 // TheCall will be freed by the smart pointer here, but that's fine, since 1487 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1488 case Builtin::BI__builtin_prefetch: 1489 if (SemaBuiltinPrefetch(TheCall)) 1490 return ExprError(); 1491 break; 1492 case Builtin::BI__builtin_alloca_with_align: 1493 if (SemaBuiltinAllocaWithAlign(TheCall)) 1494 return ExprError(); 1495 LLVM_FALLTHROUGH; 1496 case Builtin::BI__builtin_alloca: 1497 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1498 << TheCall->getDirectCallee(); 1499 break; 1500 case Builtin::BI__assume: 1501 case Builtin::BI__builtin_assume: 1502 if (SemaBuiltinAssume(TheCall)) 1503 return ExprError(); 1504 break; 1505 case Builtin::BI__builtin_assume_aligned: 1506 if (SemaBuiltinAssumeAligned(TheCall)) 1507 return ExprError(); 1508 break; 1509 case Builtin::BI__builtin_dynamic_object_size: 1510 case Builtin::BI__builtin_object_size: 1511 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1512 return ExprError(); 1513 break; 1514 case Builtin::BI__builtin_longjmp: 1515 if (SemaBuiltinLongjmp(TheCall)) 1516 return ExprError(); 1517 break; 1518 case Builtin::BI__builtin_setjmp: 1519 if (SemaBuiltinSetjmp(TheCall)) 1520 return ExprError(); 1521 break; 1522 case Builtin::BI_setjmp: 1523 case Builtin::BI_setjmpex: 1524 if (checkArgCount(*this, TheCall, 1)) 1525 return true; 1526 break; 1527 case Builtin::BI__builtin_classify_type: 1528 if (checkArgCount(*this, TheCall, 1)) return true; 1529 TheCall->setType(Context.IntTy); 1530 break; 1531 case Builtin::BI__builtin_constant_p: { 1532 if (checkArgCount(*this, TheCall, 1)) return true; 1533 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1534 if (Arg.isInvalid()) return true; 1535 TheCall->setArg(0, Arg.get()); 1536 TheCall->setType(Context.IntTy); 1537 break; 1538 } 1539 case Builtin::BI__builtin_launder: 1540 return SemaBuiltinLaunder(*this, TheCall); 1541 case Builtin::BI__sync_fetch_and_add: 1542 case Builtin::BI__sync_fetch_and_add_1: 1543 case Builtin::BI__sync_fetch_and_add_2: 1544 case Builtin::BI__sync_fetch_and_add_4: 1545 case Builtin::BI__sync_fetch_and_add_8: 1546 case Builtin::BI__sync_fetch_and_add_16: 1547 case Builtin::BI__sync_fetch_and_sub: 1548 case Builtin::BI__sync_fetch_and_sub_1: 1549 case Builtin::BI__sync_fetch_and_sub_2: 1550 case Builtin::BI__sync_fetch_and_sub_4: 1551 case Builtin::BI__sync_fetch_and_sub_8: 1552 case Builtin::BI__sync_fetch_and_sub_16: 1553 case Builtin::BI__sync_fetch_and_or: 1554 case Builtin::BI__sync_fetch_and_or_1: 1555 case Builtin::BI__sync_fetch_and_or_2: 1556 case Builtin::BI__sync_fetch_and_or_4: 1557 case Builtin::BI__sync_fetch_and_or_8: 1558 case Builtin::BI__sync_fetch_and_or_16: 1559 case Builtin::BI__sync_fetch_and_and: 1560 case Builtin::BI__sync_fetch_and_and_1: 1561 case Builtin::BI__sync_fetch_and_and_2: 1562 case Builtin::BI__sync_fetch_and_and_4: 1563 case Builtin::BI__sync_fetch_and_and_8: 1564 case Builtin::BI__sync_fetch_and_and_16: 1565 case Builtin::BI__sync_fetch_and_xor: 1566 case Builtin::BI__sync_fetch_and_xor_1: 1567 case Builtin::BI__sync_fetch_and_xor_2: 1568 case Builtin::BI__sync_fetch_and_xor_4: 1569 case Builtin::BI__sync_fetch_and_xor_8: 1570 case Builtin::BI__sync_fetch_and_xor_16: 1571 case Builtin::BI__sync_fetch_and_nand: 1572 case Builtin::BI__sync_fetch_and_nand_1: 1573 case Builtin::BI__sync_fetch_and_nand_2: 1574 case Builtin::BI__sync_fetch_and_nand_4: 1575 case Builtin::BI__sync_fetch_and_nand_8: 1576 case Builtin::BI__sync_fetch_and_nand_16: 1577 case Builtin::BI__sync_add_and_fetch: 1578 case Builtin::BI__sync_add_and_fetch_1: 1579 case Builtin::BI__sync_add_and_fetch_2: 1580 case Builtin::BI__sync_add_and_fetch_4: 1581 case Builtin::BI__sync_add_and_fetch_8: 1582 case Builtin::BI__sync_add_and_fetch_16: 1583 case Builtin::BI__sync_sub_and_fetch: 1584 case Builtin::BI__sync_sub_and_fetch_1: 1585 case Builtin::BI__sync_sub_and_fetch_2: 1586 case Builtin::BI__sync_sub_and_fetch_4: 1587 case Builtin::BI__sync_sub_and_fetch_8: 1588 case Builtin::BI__sync_sub_and_fetch_16: 1589 case Builtin::BI__sync_and_and_fetch: 1590 case Builtin::BI__sync_and_and_fetch_1: 1591 case Builtin::BI__sync_and_and_fetch_2: 1592 case Builtin::BI__sync_and_and_fetch_4: 1593 case Builtin::BI__sync_and_and_fetch_8: 1594 case Builtin::BI__sync_and_and_fetch_16: 1595 case Builtin::BI__sync_or_and_fetch: 1596 case Builtin::BI__sync_or_and_fetch_1: 1597 case Builtin::BI__sync_or_and_fetch_2: 1598 case Builtin::BI__sync_or_and_fetch_4: 1599 case Builtin::BI__sync_or_and_fetch_8: 1600 case Builtin::BI__sync_or_and_fetch_16: 1601 case Builtin::BI__sync_xor_and_fetch: 1602 case Builtin::BI__sync_xor_and_fetch_1: 1603 case Builtin::BI__sync_xor_and_fetch_2: 1604 case Builtin::BI__sync_xor_and_fetch_4: 1605 case Builtin::BI__sync_xor_and_fetch_8: 1606 case Builtin::BI__sync_xor_and_fetch_16: 1607 case Builtin::BI__sync_nand_and_fetch: 1608 case Builtin::BI__sync_nand_and_fetch_1: 1609 case Builtin::BI__sync_nand_and_fetch_2: 1610 case Builtin::BI__sync_nand_and_fetch_4: 1611 case Builtin::BI__sync_nand_and_fetch_8: 1612 case Builtin::BI__sync_nand_and_fetch_16: 1613 case Builtin::BI__sync_val_compare_and_swap: 1614 case Builtin::BI__sync_val_compare_and_swap_1: 1615 case Builtin::BI__sync_val_compare_and_swap_2: 1616 case Builtin::BI__sync_val_compare_and_swap_4: 1617 case Builtin::BI__sync_val_compare_and_swap_8: 1618 case Builtin::BI__sync_val_compare_and_swap_16: 1619 case Builtin::BI__sync_bool_compare_and_swap: 1620 case Builtin::BI__sync_bool_compare_and_swap_1: 1621 case Builtin::BI__sync_bool_compare_and_swap_2: 1622 case Builtin::BI__sync_bool_compare_and_swap_4: 1623 case Builtin::BI__sync_bool_compare_and_swap_8: 1624 case Builtin::BI__sync_bool_compare_and_swap_16: 1625 case Builtin::BI__sync_lock_test_and_set: 1626 case Builtin::BI__sync_lock_test_and_set_1: 1627 case Builtin::BI__sync_lock_test_and_set_2: 1628 case Builtin::BI__sync_lock_test_and_set_4: 1629 case Builtin::BI__sync_lock_test_and_set_8: 1630 case Builtin::BI__sync_lock_test_and_set_16: 1631 case Builtin::BI__sync_lock_release: 1632 case Builtin::BI__sync_lock_release_1: 1633 case Builtin::BI__sync_lock_release_2: 1634 case Builtin::BI__sync_lock_release_4: 1635 case Builtin::BI__sync_lock_release_8: 1636 case Builtin::BI__sync_lock_release_16: 1637 case Builtin::BI__sync_swap: 1638 case Builtin::BI__sync_swap_1: 1639 case Builtin::BI__sync_swap_2: 1640 case Builtin::BI__sync_swap_4: 1641 case Builtin::BI__sync_swap_8: 1642 case Builtin::BI__sync_swap_16: 1643 return SemaBuiltinAtomicOverloaded(TheCallResult); 1644 case Builtin::BI__sync_synchronize: 1645 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1646 << TheCall->getCallee()->getSourceRange(); 1647 break; 1648 case Builtin::BI__builtin_nontemporal_load: 1649 case Builtin::BI__builtin_nontemporal_store: 1650 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1651 case Builtin::BI__builtin_memcpy_inline: { 1652 clang::Expr *SizeOp = TheCall->getArg(2); 1653 // We warn about copying to or from `nullptr` pointers when `size` is 1654 // greater than 0. When `size` is value dependent we cannot evaluate its 1655 // value so we bail out. 1656 if (SizeOp->isValueDependent()) 1657 break; 1658 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1659 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1660 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1661 } 1662 break; 1663 } 1664 #define BUILTIN(ID, TYPE, ATTRS) 1665 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1666 case Builtin::BI##ID: \ 1667 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1668 #include "clang/Basic/Builtins.def" 1669 case Builtin::BI__annotation: 1670 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1671 return ExprError(); 1672 break; 1673 case Builtin::BI__builtin_annotation: 1674 if (SemaBuiltinAnnotation(*this, TheCall)) 1675 return ExprError(); 1676 break; 1677 case Builtin::BI__builtin_addressof: 1678 if (SemaBuiltinAddressof(*this, TheCall)) 1679 return ExprError(); 1680 break; 1681 case Builtin::BI__builtin_is_aligned: 1682 case Builtin::BI__builtin_align_up: 1683 case Builtin::BI__builtin_align_down: 1684 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1685 return ExprError(); 1686 break; 1687 case Builtin::BI__builtin_add_overflow: 1688 case Builtin::BI__builtin_sub_overflow: 1689 case Builtin::BI__builtin_mul_overflow: 1690 if (SemaBuiltinOverflow(*this, TheCall)) 1691 return ExprError(); 1692 break; 1693 case Builtin::BI__builtin_operator_new: 1694 case Builtin::BI__builtin_operator_delete: { 1695 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1696 ExprResult Res = 1697 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1698 if (Res.isInvalid()) 1699 CorrectDelayedTyposInExpr(TheCallResult.get()); 1700 return Res; 1701 } 1702 case Builtin::BI__builtin_dump_struct: { 1703 // We first want to ensure we are called with 2 arguments 1704 if (checkArgCount(*this, TheCall, 2)) 1705 return ExprError(); 1706 // Ensure that the first argument is of type 'struct XX *' 1707 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1708 const QualType PtrArgType = PtrArg->getType(); 1709 if (!PtrArgType->isPointerType() || 1710 !PtrArgType->getPointeeType()->isRecordType()) { 1711 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1712 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1713 << "structure pointer"; 1714 return ExprError(); 1715 } 1716 1717 // Ensure that the second argument is of type 'FunctionType' 1718 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1719 const QualType FnPtrArgType = FnPtrArg->getType(); 1720 if (!FnPtrArgType->isPointerType()) { 1721 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1722 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1723 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1724 return ExprError(); 1725 } 1726 1727 const auto *FuncType = 1728 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1729 1730 if (!FuncType) { 1731 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1732 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1733 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1734 return ExprError(); 1735 } 1736 1737 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1738 if (!FT->getNumParams()) { 1739 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1740 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1741 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1742 return ExprError(); 1743 } 1744 QualType PT = FT->getParamType(0); 1745 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1746 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1747 !PT->getPointeeType().isConstQualified()) { 1748 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1749 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1750 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1751 return ExprError(); 1752 } 1753 } 1754 1755 TheCall->setType(Context.IntTy); 1756 break; 1757 } 1758 case Builtin::BI__builtin_preserve_access_index: 1759 if (SemaBuiltinPreserveAI(*this, TheCall)) 1760 return ExprError(); 1761 break; 1762 case Builtin::BI__builtin_call_with_static_chain: 1763 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1764 return ExprError(); 1765 break; 1766 case Builtin::BI__exception_code: 1767 case Builtin::BI_exception_code: 1768 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1769 diag::err_seh___except_block)) 1770 return ExprError(); 1771 break; 1772 case Builtin::BI__exception_info: 1773 case Builtin::BI_exception_info: 1774 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1775 diag::err_seh___except_filter)) 1776 return ExprError(); 1777 break; 1778 case Builtin::BI__GetExceptionInfo: 1779 if (checkArgCount(*this, TheCall, 1)) 1780 return ExprError(); 1781 1782 if (CheckCXXThrowOperand( 1783 TheCall->getBeginLoc(), 1784 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1785 TheCall)) 1786 return ExprError(); 1787 1788 TheCall->setType(Context.VoidPtrTy); 1789 break; 1790 // OpenCL v2.0, s6.13.16 - Pipe functions 1791 case Builtin::BIread_pipe: 1792 case Builtin::BIwrite_pipe: 1793 // Since those two functions are declared with var args, we need a semantic 1794 // check for the argument. 1795 if (SemaBuiltinRWPipe(*this, TheCall)) 1796 return ExprError(); 1797 break; 1798 case Builtin::BIreserve_read_pipe: 1799 case Builtin::BIreserve_write_pipe: 1800 case Builtin::BIwork_group_reserve_read_pipe: 1801 case Builtin::BIwork_group_reserve_write_pipe: 1802 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1803 return ExprError(); 1804 break; 1805 case Builtin::BIsub_group_reserve_read_pipe: 1806 case Builtin::BIsub_group_reserve_write_pipe: 1807 if (checkOpenCLSubgroupExt(*this, TheCall) || 1808 SemaBuiltinReserveRWPipe(*this, TheCall)) 1809 return ExprError(); 1810 break; 1811 case Builtin::BIcommit_read_pipe: 1812 case Builtin::BIcommit_write_pipe: 1813 case Builtin::BIwork_group_commit_read_pipe: 1814 case Builtin::BIwork_group_commit_write_pipe: 1815 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1816 return ExprError(); 1817 break; 1818 case Builtin::BIsub_group_commit_read_pipe: 1819 case Builtin::BIsub_group_commit_write_pipe: 1820 if (checkOpenCLSubgroupExt(*this, TheCall) || 1821 SemaBuiltinCommitRWPipe(*this, TheCall)) 1822 return ExprError(); 1823 break; 1824 case Builtin::BIget_pipe_num_packets: 1825 case Builtin::BIget_pipe_max_packets: 1826 if (SemaBuiltinPipePackets(*this, TheCall)) 1827 return ExprError(); 1828 break; 1829 case Builtin::BIto_global: 1830 case Builtin::BIto_local: 1831 case Builtin::BIto_private: 1832 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1833 return ExprError(); 1834 break; 1835 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1836 case Builtin::BIenqueue_kernel: 1837 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1838 return ExprError(); 1839 break; 1840 case Builtin::BIget_kernel_work_group_size: 1841 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1842 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1843 return ExprError(); 1844 break; 1845 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1846 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1847 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1848 return ExprError(); 1849 break; 1850 case Builtin::BI__builtin_os_log_format: 1851 Cleanup.setExprNeedsCleanups(true); 1852 LLVM_FALLTHROUGH; 1853 case Builtin::BI__builtin_os_log_format_buffer_size: 1854 if (SemaBuiltinOSLogFormat(TheCall)) 1855 return ExprError(); 1856 break; 1857 case Builtin::BI__builtin_frame_address: 1858 case Builtin::BI__builtin_return_address: 1859 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1860 return ExprError(); 1861 1862 // -Wframe-address warning if non-zero passed to builtin 1863 // return/frame address. 1864 Expr::EvalResult Result; 1865 if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1866 Result.Val.getInt() != 0) 1867 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1868 << ((BuiltinID == Builtin::BI__builtin_return_address) 1869 ? "__builtin_return_address" 1870 : "__builtin_frame_address") 1871 << TheCall->getSourceRange(); 1872 break; 1873 } 1874 1875 // Since the target specific builtins for each arch overlap, only check those 1876 // of the arch we are compiling for. 1877 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1878 switch (Context.getTargetInfo().getTriple().getArch()) { 1879 case llvm::Triple::arm: 1880 case llvm::Triple::armeb: 1881 case llvm::Triple::thumb: 1882 case llvm::Triple::thumbeb: 1883 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1884 return ExprError(); 1885 break; 1886 case llvm::Triple::aarch64: 1887 case llvm::Triple::aarch64_32: 1888 case llvm::Triple::aarch64_be: 1889 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1890 return ExprError(); 1891 break; 1892 case llvm::Triple::bpfeb: 1893 case llvm::Triple::bpfel: 1894 if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall)) 1895 return ExprError(); 1896 break; 1897 case llvm::Triple::hexagon: 1898 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1899 return ExprError(); 1900 break; 1901 case llvm::Triple::mips: 1902 case llvm::Triple::mipsel: 1903 case llvm::Triple::mips64: 1904 case llvm::Triple::mips64el: 1905 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1906 return ExprError(); 1907 break; 1908 case llvm::Triple::systemz: 1909 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1910 return ExprError(); 1911 break; 1912 case llvm::Triple::x86: 1913 case llvm::Triple::x86_64: 1914 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1915 return ExprError(); 1916 break; 1917 case llvm::Triple::ppc: 1918 case llvm::Triple::ppc64: 1919 case llvm::Triple::ppc64le: 1920 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1921 return ExprError(); 1922 break; 1923 default: 1924 break; 1925 } 1926 } 1927 1928 return TheCallResult; 1929 } 1930 1931 // Get the valid immediate range for the specified NEON type code. 1932 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1933 NeonTypeFlags Type(t); 1934 int IsQuad = ForceQuad ? true : Type.isQuad(); 1935 switch (Type.getEltType()) { 1936 case NeonTypeFlags::Int8: 1937 case NeonTypeFlags::Poly8: 1938 return shift ? 7 : (8 << IsQuad) - 1; 1939 case NeonTypeFlags::Int16: 1940 case NeonTypeFlags::Poly16: 1941 return shift ? 15 : (4 << IsQuad) - 1; 1942 case NeonTypeFlags::Int32: 1943 return shift ? 31 : (2 << IsQuad) - 1; 1944 case NeonTypeFlags::Int64: 1945 case NeonTypeFlags::Poly64: 1946 return shift ? 63 : (1 << IsQuad) - 1; 1947 case NeonTypeFlags::Poly128: 1948 return shift ? 127 : (1 << IsQuad) - 1; 1949 case NeonTypeFlags::Float16: 1950 assert(!shift && "cannot shift float types!"); 1951 return (4 << IsQuad) - 1; 1952 case NeonTypeFlags::Float32: 1953 assert(!shift && "cannot shift float types!"); 1954 return (2 << IsQuad) - 1; 1955 case NeonTypeFlags::Float64: 1956 assert(!shift && "cannot shift float types!"); 1957 return (1 << IsQuad) - 1; 1958 } 1959 llvm_unreachable("Invalid NeonTypeFlag!"); 1960 } 1961 1962 /// getNeonEltType - Return the QualType corresponding to the elements of 1963 /// the vector type specified by the NeonTypeFlags. This is used to check 1964 /// the pointer arguments for Neon load/store intrinsics. 1965 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1966 bool IsPolyUnsigned, bool IsInt64Long) { 1967 switch (Flags.getEltType()) { 1968 case NeonTypeFlags::Int8: 1969 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1970 case NeonTypeFlags::Int16: 1971 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1972 case NeonTypeFlags::Int32: 1973 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1974 case NeonTypeFlags::Int64: 1975 if (IsInt64Long) 1976 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1977 else 1978 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1979 : Context.LongLongTy; 1980 case NeonTypeFlags::Poly8: 1981 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1982 case NeonTypeFlags::Poly16: 1983 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1984 case NeonTypeFlags::Poly64: 1985 if (IsInt64Long) 1986 return Context.UnsignedLongTy; 1987 else 1988 return Context.UnsignedLongLongTy; 1989 case NeonTypeFlags::Poly128: 1990 break; 1991 case NeonTypeFlags::Float16: 1992 return Context.HalfTy; 1993 case NeonTypeFlags::Float32: 1994 return Context.FloatTy; 1995 case NeonTypeFlags::Float64: 1996 return Context.DoubleTy; 1997 } 1998 llvm_unreachable("Invalid NeonTypeFlag!"); 1999 } 2000 2001 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2002 llvm::APSInt Result; 2003 uint64_t mask = 0; 2004 unsigned TV = 0; 2005 int PtrArgNum = -1; 2006 bool HasConstPtr = false; 2007 switch (BuiltinID) { 2008 #define GET_NEON_OVERLOAD_CHECK 2009 #include "clang/Basic/arm_neon.inc" 2010 #include "clang/Basic/arm_fp16.inc" 2011 #undef GET_NEON_OVERLOAD_CHECK 2012 } 2013 2014 // For NEON intrinsics which are overloaded on vector element type, validate 2015 // the immediate which specifies which variant to emit. 2016 unsigned ImmArg = TheCall->getNumArgs()-1; 2017 if (mask) { 2018 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2019 return true; 2020 2021 TV = Result.getLimitedValue(64); 2022 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2023 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2024 << TheCall->getArg(ImmArg)->getSourceRange(); 2025 } 2026 2027 if (PtrArgNum >= 0) { 2028 // Check that pointer arguments have the specified type. 2029 Expr *Arg = TheCall->getArg(PtrArgNum); 2030 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2031 Arg = ICE->getSubExpr(); 2032 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2033 QualType RHSTy = RHS.get()->getType(); 2034 2035 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 2036 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2037 Arch == llvm::Triple::aarch64_32 || 2038 Arch == llvm::Triple::aarch64_be; 2039 bool IsInt64Long = 2040 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 2041 QualType EltTy = 2042 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2043 if (HasConstPtr) 2044 EltTy = EltTy.withConst(); 2045 QualType LHSTy = Context.getPointerType(EltTy); 2046 AssignConvertType ConvTy; 2047 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2048 if (RHS.isInvalid()) 2049 return true; 2050 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2051 RHS.get(), AA_Assigning)) 2052 return true; 2053 } 2054 2055 // For NEON intrinsics which take an immediate value as part of the 2056 // instruction, range check them here. 2057 unsigned i = 0, l = 0, u = 0; 2058 switch (BuiltinID) { 2059 default: 2060 return false; 2061 #define GET_NEON_IMMEDIATE_CHECK 2062 #include "clang/Basic/arm_neon.inc" 2063 #include "clang/Basic/arm_fp16.inc" 2064 #undef GET_NEON_IMMEDIATE_CHECK 2065 } 2066 2067 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2068 } 2069 2070 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2071 switch (BuiltinID) { 2072 default: 2073 return false; 2074 #include "clang/Basic/arm_mve_builtin_sema.inc" 2075 } 2076 } 2077 2078 bool Sema::CheckCDEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2079 bool Err = false; 2080 switch (BuiltinID) { 2081 default: 2082 return false; 2083 #include "clang/Basic/arm_cde_builtin_sema.inc" 2084 } 2085 2086 if (Err) 2087 return true; 2088 2089 return CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ true); 2090 } 2091 2092 bool Sema::CheckARMCoprocessorImmediate(const Expr *CoprocArg, bool WantCDE) { 2093 if (isConstantEvaluated()) 2094 return false; 2095 2096 // We can't check the value of a dependent argument. 2097 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2098 return false; 2099 2100 llvm::APSInt CoprocNoAP; 2101 bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context); 2102 (void)IsICE; 2103 assert(IsICE && "Coprocossor immediate is not a constant expression"); 2104 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2105 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2106 2107 uint32_t CDECoprocMask = Context.getTargetInfo().getARMCDECoprocMask(); 2108 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2109 2110 if (IsCDECoproc != WantCDE) 2111 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2112 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2113 2114 return false; 2115 } 2116 2117 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2118 unsigned MaxWidth) { 2119 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2120 BuiltinID == ARM::BI__builtin_arm_ldaex || 2121 BuiltinID == ARM::BI__builtin_arm_strex || 2122 BuiltinID == ARM::BI__builtin_arm_stlex || 2123 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2124 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2125 BuiltinID == AArch64::BI__builtin_arm_strex || 2126 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2127 "unexpected ARM builtin"); 2128 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2129 BuiltinID == ARM::BI__builtin_arm_ldaex || 2130 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2131 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2132 2133 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2134 2135 // Ensure that we have the proper number of arguments. 2136 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2137 return true; 2138 2139 // Inspect the pointer argument of the atomic builtin. This should always be 2140 // a pointer type, whose element is an integral scalar or pointer type. 2141 // Because it is a pointer type, we don't have to worry about any implicit 2142 // casts here. 2143 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2144 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2145 if (PointerArgRes.isInvalid()) 2146 return true; 2147 PointerArg = PointerArgRes.get(); 2148 2149 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2150 if (!pointerType) { 2151 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2152 << PointerArg->getType() << PointerArg->getSourceRange(); 2153 return true; 2154 } 2155 2156 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2157 // task is to insert the appropriate casts into the AST. First work out just 2158 // what the appropriate type is. 2159 QualType ValType = pointerType->getPointeeType(); 2160 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2161 if (IsLdrex) 2162 AddrType.addConst(); 2163 2164 // Issue a warning if the cast is dodgy. 2165 CastKind CastNeeded = CK_NoOp; 2166 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2167 CastNeeded = CK_BitCast; 2168 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2169 << PointerArg->getType() << Context.getPointerType(AddrType) 2170 << AA_Passing << PointerArg->getSourceRange(); 2171 } 2172 2173 // Finally, do the cast and replace the argument with the corrected version. 2174 AddrType = Context.getPointerType(AddrType); 2175 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2176 if (PointerArgRes.isInvalid()) 2177 return true; 2178 PointerArg = PointerArgRes.get(); 2179 2180 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2181 2182 // In general, we allow ints, floats and pointers to be loaded and stored. 2183 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2184 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2185 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2186 << PointerArg->getType() << PointerArg->getSourceRange(); 2187 return true; 2188 } 2189 2190 // But ARM doesn't have instructions to deal with 128-bit versions. 2191 if (Context.getTypeSize(ValType) > MaxWidth) { 2192 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2193 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2194 << PointerArg->getType() << PointerArg->getSourceRange(); 2195 return true; 2196 } 2197 2198 switch (ValType.getObjCLifetime()) { 2199 case Qualifiers::OCL_None: 2200 case Qualifiers::OCL_ExplicitNone: 2201 // okay 2202 break; 2203 2204 case Qualifiers::OCL_Weak: 2205 case Qualifiers::OCL_Strong: 2206 case Qualifiers::OCL_Autoreleasing: 2207 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2208 << ValType << PointerArg->getSourceRange(); 2209 return true; 2210 } 2211 2212 if (IsLdrex) { 2213 TheCall->setType(ValType); 2214 return false; 2215 } 2216 2217 // Initialize the argument to be stored. 2218 ExprResult ValArg = TheCall->getArg(0); 2219 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2220 Context, ValType, /*consume*/ false); 2221 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2222 if (ValArg.isInvalid()) 2223 return true; 2224 TheCall->setArg(0, ValArg.get()); 2225 2226 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2227 // but the custom checker bypasses all default analysis. 2228 TheCall->setType(Context.IntTy); 2229 return false; 2230 } 2231 2232 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2233 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2234 BuiltinID == ARM::BI__builtin_arm_ldaex || 2235 BuiltinID == ARM::BI__builtin_arm_strex || 2236 BuiltinID == ARM::BI__builtin_arm_stlex) { 2237 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2238 } 2239 2240 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2241 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2242 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2243 } 2244 2245 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2246 BuiltinID == ARM::BI__builtin_arm_wsr64) 2247 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2248 2249 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2250 BuiltinID == ARM::BI__builtin_arm_rsrp || 2251 BuiltinID == ARM::BI__builtin_arm_wsr || 2252 BuiltinID == ARM::BI__builtin_arm_wsrp) 2253 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2254 2255 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 2256 return true; 2257 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2258 return true; 2259 if (CheckCDEBuiltinFunctionCall(BuiltinID, TheCall)) 2260 return true; 2261 2262 // For intrinsics which take an immediate value as part of the instruction, 2263 // range check them here. 2264 // FIXME: VFP Intrinsics should error if VFP not present. 2265 switch (BuiltinID) { 2266 default: return false; 2267 case ARM::BI__builtin_arm_ssat: 2268 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2269 case ARM::BI__builtin_arm_usat: 2270 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2271 case ARM::BI__builtin_arm_ssat16: 2272 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2273 case ARM::BI__builtin_arm_usat16: 2274 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2275 case ARM::BI__builtin_arm_vcvtr_f: 2276 case ARM::BI__builtin_arm_vcvtr_d: 2277 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2278 case ARM::BI__builtin_arm_dmb: 2279 case ARM::BI__builtin_arm_dsb: 2280 case ARM::BI__builtin_arm_isb: 2281 case ARM::BI__builtin_arm_dbg: 2282 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2283 case ARM::BI__builtin_arm_cdp: 2284 case ARM::BI__builtin_arm_cdp2: 2285 case ARM::BI__builtin_arm_mcr: 2286 case ARM::BI__builtin_arm_mcr2: 2287 case ARM::BI__builtin_arm_mrc: 2288 case ARM::BI__builtin_arm_mrc2: 2289 case ARM::BI__builtin_arm_mcrr: 2290 case ARM::BI__builtin_arm_mcrr2: 2291 case ARM::BI__builtin_arm_mrrc: 2292 case ARM::BI__builtin_arm_mrrc2: 2293 case ARM::BI__builtin_arm_ldc: 2294 case ARM::BI__builtin_arm_ldcl: 2295 case ARM::BI__builtin_arm_ldc2: 2296 case ARM::BI__builtin_arm_ldc2l: 2297 case ARM::BI__builtin_arm_stc: 2298 case ARM::BI__builtin_arm_stcl: 2299 case ARM::BI__builtin_arm_stc2: 2300 case ARM::BI__builtin_arm_stc2l: 2301 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2302 CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ false); 2303 } 2304 } 2305 2306 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 2307 CallExpr *TheCall) { 2308 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2309 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2310 BuiltinID == AArch64::BI__builtin_arm_strex || 2311 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2312 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2313 } 2314 2315 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2316 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2317 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2318 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2319 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2320 } 2321 2322 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2323 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2324 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2325 2326 // Memory Tagging Extensions (MTE) Intrinsics 2327 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2328 BuiltinID == AArch64::BI__builtin_arm_addg || 2329 BuiltinID == AArch64::BI__builtin_arm_gmi || 2330 BuiltinID == AArch64::BI__builtin_arm_ldg || 2331 BuiltinID == AArch64::BI__builtin_arm_stg || 2332 BuiltinID == AArch64::BI__builtin_arm_subp) { 2333 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2334 } 2335 2336 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2337 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2338 BuiltinID == AArch64::BI__builtin_arm_wsr || 2339 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2340 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2341 2342 // Only check the valid encoding range. Any constant in this range would be 2343 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2344 // an exception for incorrect registers. This matches MSVC behavior. 2345 if (BuiltinID == AArch64::BI_ReadStatusReg || 2346 BuiltinID == AArch64::BI_WriteStatusReg) 2347 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2348 2349 if (BuiltinID == AArch64::BI__getReg) 2350 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2351 2352 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 2353 return true; 2354 2355 // For intrinsics which take an immediate value as part of the instruction, 2356 // range check them here. 2357 unsigned i = 0, l = 0, u = 0; 2358 switch (BuiltinID) { 2359 default: return false; 2360 case AArch64::BI__builtin_arm_dmb: 2361 case AArch64::BI__builtin_arm_dsb: 2362 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2363 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2364 } 2365 2366 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2367 } 2368 2369 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2370 CallExpr *TheCall) { 2371 assert(BuiltinID == BPF::BI__builtin_preserve_field_info && 2372 "unexpected ARM builtin"); 2373 2374 if (checkArgCount(*this, TheCall, 2)) 2375 return true; 2376 2377 // The first argument needs to be a record field access. 2378 // If it is an array element access, we delay decision 2379 // to BPF backend to check whether the access is a 2380 // field access or not. 2381 Expr *Arg = TheCall->getArg(0); 2382 if (Arg->getType()->getAsPlaceholderType() || 2383 (Arg->IgnoreParens()->getObjectKind() != OK_BitField && 2384 !dyn_cast<MemberExpr>(Arg->IgnoreParens()) && 2385 !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) { 2386 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field) 2387 << 1 << Arg->getSourceRange(); 2388 return true; 2389 } 2390 2391 // The second argument needs to be a constant int 2392 llvm::APSInt Value; 2393 if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) { 2394 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const) 2395 << 2 << Arg->getSourceRange(); 2396 return true; 2397 } 2398 2399 TheCall->setType(Context.UnsignedIntTy); 2400 return false; 2401 } 2402 2403 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2404 struct ArgInfo { 2405 uint8_t OpNum; 2406 bool IsSigned; 2407 uint8_t BitWidth; 2408 uint8_t Align; 2409 }; 2410 struct BuiltinInfo { 2411 unsigned BuiltinID; 2412 ArgInfo Infos[2]; 2413 }; 2414 2415 static BuiltinInfo Infos[] = { 2416 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2417 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2418 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2419 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2420 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2421 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2422 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2423 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2424 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2425 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2426 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2427 2428 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2429 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2430 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2431 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2432 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2433 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2434 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2435 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2436 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2437 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2438 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2439 2440 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2441 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2442 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2443 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2444 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2445 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2446 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2447 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2448 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2449 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2450 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2451 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2452 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2453 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2454 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2455 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2456 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2457 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2458 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2459 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2460 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2461 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2462 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2463 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2464 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2465 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2466 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2467 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2468 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2469 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2470 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2471 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2472 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2473 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2474 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2475 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2476 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2477 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2478 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2479 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2480 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2481 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2482 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2483 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2484 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2485 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2486 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2487 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2488 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2489 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2490 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2491 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2492 {{ 1, false, 6, 0 }} }, 2493 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2494 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2495 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2496 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2497 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2498 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2499 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2500 {{ 1, false, 5, 0 }} }, 2501 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2502 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2503 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2504 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2505 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2506 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2507 { 2, false, 5, 0 }} }, 2508 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2509 { 2, false, 6, 0 }} }, 2510 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2511 { 3, false, 5, 0 }} }, 2512 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2513 { 3, false, 6, 0 }} }, 2514 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2515 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2516 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2517 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2518 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2519 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2520 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2521 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2522 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2523 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2524 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2525 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2526 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2527 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2528 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2529 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2530 {{ 2, false, 4, 0 }, 2531 { 3, false, 5, 0 }} }, 2532 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2533 {{ 2, false, 4, 0 }, 2534 { 3, false, 5, 0 }} }, 2535 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2536 {{ 2, false, 4, 0 }, 2537 { 3, false, 5, 0 }} }, 2538 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2539 {{ 2, false, 4, 0 }, 2540 { 3, false, 5, 0 }} }, 2541 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2542 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2543 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2544 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2545 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2546 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2547 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2548 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2549 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2550 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2551 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2552 { 2, false, 5, 0 }} }, 2553 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2554 { 2, false, 6, 0 }} }, 2555 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2556 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2557 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2558 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2559 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2560 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2561 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2562 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2563 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2564 {{ 1, false, 4, 0 }} }, 2565 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2566 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2567 {{ 1, false, 4, 0 }} }, 2568 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2569 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2570 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2571 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2572 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2573 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2574 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2575 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2576 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2577 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2578 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2579 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2580 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2581 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2582 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2583 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2584 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2585 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2586 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2587 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2588 {{ 3, false, 1, 0 }} }, 2589 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2590 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2591 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2592 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2593 {{ 3, false, 1, 0 }} }, 2594 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2595 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2596 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2597 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2598 {{ 3, false, 1, 0 }} }, 2599 }; 2600 2601 // Use a dynamically initialized static to sort the table exactly once on 2602 // first run. 2603 static const bool SortOnce = 2604 (llvm::sort(Infos, 2605 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2606 return LHS.BuiltinID < RHS.BuiltinID; 2607 }), 2608 true); 2609 (void)SortOnce; 2610 2611 const BuiltinInfo *F = llvm::partition_point( 2612 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2613 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2614 return false; 2615 2616 bool Error = false; 2617 2618 for (const ArgInfo &A : F->Infos) { 2619 // Ignore empty ArgInfo elements. 2620 if (A.BitWidth == 0) 2621 continue; 2622 2623 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2624 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2625 if (!A.Align) { 2626 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2627 } else { 2628 unsigned M = 1 << A.Align; 2629 Min *= M; 2630 Max *= M; 2631 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2632 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2633 } 2634 } 2635 return Error; 2636 } 2637 2638 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2639 CallExpr *TheCall) { 2640 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2641 } 2642 2643 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2644 return CheckMipsBuiltinCpu(BuiltinID, TheCall) || 2645 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2646 } 2647 2648 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 2649 const TargetInfo &TI = Context.getTargetInfo(); 2650 2651 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2652 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2653 if (!TI.hasFeature("dsp")) 2654 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2655 } 2656 2657 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2658 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2659 if (!TI.hasFeature("dspr2")) 2660 return Diag(TheCall->getBeginLoc(), 2661 diag::err_mips_builtin_requires_dspr2); 2662 } 2663 2664 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2665 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2666 if (!TI.hasFeature("msa")) 2667 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2668 } 2669 2670 return false; 2671 } 2672 2673 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2674 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2675 // ordering for DSP is unspecified. MSA is ordered by the data format used 2676 // by the underlying instruction i.e., df/m, df/n and then by size. 2677 // 2678 // FIXME: The size tests here should instead be tablegen'd along with the 2679 // definitions from include/clang/Basic/BuiltinsMips.def. 2680 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2681 // be too. 2682 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2683 unsigned i = 0, l = 0, u = 0, m = 0; 2684 switch (BuiltinID) { 2685 default: return false; 2686 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2687 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2688 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2689 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2690 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2691 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2692 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2693 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 2694 // df/m field. 2695 // These intrinsics take an unsigned 3 bit immediate. 2696 case Mips::BI__builtin_msa_bclri_b: 2697 case Mips::BI__builtin_msa_bnegi_b: 2698 case Mips::BI__builtin_msa_bseti_b: 2699 case Mips::BI__builtin_msa_sat_s_b: 2700 case Mips::BI__builtin_msa_sat_u_b: 2701 case Mips::BI__builtin_msa_slli_b: 2702 case Mips::BI__builtin_msa_srai_b: 2703 case Mips::BI__builtin_msa_srari_b: 2704 case Mips::BI__builtin_msa_srli_b: 2705 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2706 case Mips::BI__builtin_msa_binsli_b: 2707 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2708 // These intrinsics take an unsigned 4 bit immediate. 2709 case Mips::BI__builtin_msa_bclri_h: 2710 case Mips::BI__builtin_msa_bnegi_h: 2711 case Mips::BI__builtin_msa_bseti_h: 2712 case Mips::BI__builtin_msa_sat_s_h: 2713 case Mips::BI__builtin_msa_sat_u_h: 2714 case Mips::BI__builtin_msa_slli_h: 2715 case Mips::BI__builtin_msa_srai_h: 2716 case Mips::BI__builtin_msa_srari_h: 2717 case Mips::BI__builtin_msa_srli_h: 2718 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2719 case Mips::BI__builtin_msa_binsli_h: 2720 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2721 // These intrinsics take an unsigned 5 bit immediate. 2722 // The first block of intrinsics actually have an unsigned 5 bit field, 2723 // not a df/n field. 2724 case Mips::BI__builtin_msa_cfcmsa: 2725 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 2726 case Mips::BI__builtin_msa_clei_u_b: 2727 case Mips::BI__builtin_msa_clei_u_h: 2728 case Mips::BI__builtin_msa_clei_u_w: 2729 case Mips::BI__builtin_msa_clei_u_d: 2730 case Mips::BI__builtin_msa_clti_u_b: 2731 case Mips::BI__builtin_msa_clti_u_h: 2732 case Mips::BI__builtin_msa_clti_u_w: 2733 case Mips::BI__builtin_msa_clti_u_d: 2734 case Mips::BI__builtin_msa_maxi_u_b: 2735 case Mips::BI__builtin_msa_maxi_u_h: 2736 case Mips::BI__builtin_msa_maxi_u_w: 2737 case Mips::BI__builtin_msa_maxi_u_d: 2738 case Mips::BI__builtin_msa_mini_u_b: 2739 case Mips::BI__builtin_msa_mini_u_h: 2740 case Mips::BI__builtin_msa_mini_u_w: 2741 case Mips::BI__builtin_msa_mini_u_d: 2742 case Mips::BI__builtin_msa_addvi_b: 2743 case Mips::BI__builtin_msa_addvi_h: 2744 case Mips::BI__builtin_msa_addvi_w: 2745 case Mips::BI__builtin_msa_addvi_d: 2746 case Mips::BI__builtin_msa_bclri_w: 2747 case Mips::BI__builtin_msa_bnegi_w: 2748 case Mips::BI__builtin_msa_bseti_w: 2749 case Mips::BI__builtin_msa_sat_s_w: 2750 case Mips::BI__builtin_msa_sat_u_w: 2751 case Mips::BI__builtin_msa_slli_w: 2752 case Mips::BI__builtin_msa_srai_w: 2753 case Mips::BI__builtin_msa_srari_w: 2754 case Mips::BI__builtin_msa_srli_w: 2755 case Mips::BI__builtin_msa_srlri_w: 2756 case Mips::BI__builtin_msa_subvi_b: 2757 case Mips::BI__builtin_msa_subvi_h: 2758 case Mips::BI__builtin_msa_subvi_w: 2759 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2760 case Mips::BI__builtin_msa_binsli_w: 2761 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2762 // These intrinsics take an unsigned 6 bit immediate. 2763 case Mips::BI__builtin_msa_bclri_d: 2764 case Mips::BI__builtin_msa_bnegi_d: 2765 case Mips::BI__builtin_msa_bseti_d: 2766 case Mips::BI__builtin_msa_sat_s_d: 2767 case Mips::BI__builtin_msa_sat_u_d: 2768 case Mips::BI__builtin_msa_slli_d: 2769 case Mips::BI__builtin_msa_srai_d: 2770 case Mips::BI__builtin_msa_srari_d: 2771 case Mips::BI__builtin_msa_srli_d: 2772 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2773 case Mips::BI__builtin_msa_binsli_d: 2774 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2775 // These intrinsics take a signed 5 bit immediate. 2776 case Mips::BI__builtin_msa_ceqi_b: 2777 case Mips::BI__builtin_msa_ceqi_h: 2778 case Mips::BI__builtin_msa_ceqi_w: 2779 case Mips::BI__builtin_msa_ceqi_d: 2780 case Mips::BI__builtin_msa_clti_s_b: 2781 case Mips::BI__builtin_msa_clti_s_h: 2782 case Mips::BI__builtin_msa_clti_s_w: 2783 case Mips::BI__builtin_msa_clti_s_d: 2784 case Mips::BI__builtin_msa_clei_s_b: 2785 case Mips::BI__builtin_msa_clei_s_h: 2786 case Mips::BI__builtin_msa_clei_s_w: 2787 case Mips::BI__builtin_msa_clei_s_d: 2788 case Mips::BI__builtin_msa_maxi_s_b: 2789 case Mips::BI__builtin_msa_maxi_s_h: 2790 case Mips::BI__builtin_msa_maxi_s_w: 2791 case Mips::BI__builtin_msa_maxi_s_d: 2792 case Mips::BI__builtin_msa_mini_s_b: 2793 case Mips::BI__builtin_msa_mini_s_h: 2794 case Mips::BI__builtin_msa_mini_s_w: 2795 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2796 // These intrinsics take an unsigned 8 bit immediate. 2797 case Mips::BI__builtin_msa_andi_b: 2798 case Mips::BI__builtin_msa_nori_b: 2799 case Mips::BI__builtin_msa_ori_b: 2800 case Mips::BI__builtin_msa_shf_b: 2801 case Mips::BI__builtin_msa_shf_h: 2802 case Mips::BI__builtin_msa_shf_w: 2803 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2804 case Mips::BI__builtin_msa_bseli_b: 2805 case Mips::BI__builtin_msa_bmnzi_b: 2806 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2807 // df/n format 2808 // These intrinsics take an unsigned 4 bit immediate. 2809 case Mips::BI__builtin_msa_copy_s_b: 2810 case Mips::BI__builtin_msa_copy_u_b: 2811 case Mips::BI__builtin_msa_insve_b: 2812 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2813 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2814 // These intrinsics take an unsigned 3 bit immediate. 2815 case Mips::BI__builtin_msa_copy_s_h: 2816 case Mips::BI__builtin_msa_copy_u_h: 2817 case Mips::BI__builtin_msa_insve_h: 2818 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2819 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2820 // These intrinsics take an unsigned 2 bit immediate. 2821 case Mips::BI__builtin_msa_copy_s_w: 2822 case Mips::BI__builtin_msa_copy_u_w: 2823 case Mips::BI__builtin_msa_insve_w: 2824 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2825 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2826 // These intrinsics take an unsigned 1 bit immediate. 2827 case Mips::BI__builtin_msa_copy_s_d: 2828 case Mips::BI__builtin_msa_copy_u_d: 2829 case Mips::BI__builtin_msa_insve_d: 2830 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2831 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2832 // Memory offsets and immediate loads. 2833 // These intrinsics take a signed 10 bit immediate. 2834 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2835 case Mips::BI__builtin_msa_ldi_h: 2836 case Mips::BI__builtin_msa_ldi_w: 2837 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2838 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 2839 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 2840 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 2841 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 2842 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 2843 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 2844 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 2845 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 2846 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 2847 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 2848 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 2849 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 2850 } 2851 2852 if (!m) 2853 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2854 2855 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 2856 SemaBuiltinConstantArgMultiple(TheCall, i, m); 2857 } 2858 2859 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2860 unsigned i = 0, l = 0, u = 0; 2861 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 2862 BuiltinID == PPC::BI__builtin_divdeu || 2863 BuiltinID == PPC::BI__builtin_bpermd; 2864 bool IsTarget64Bit = Context.getTargetInfo() 2865 .getTypeWidth(Context 2866 .getTargetInfo() 2867 .getIntPtrType()) == 64; 2868 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 2869 BuiltinID == PPC::BI__builtin_divweu || 2870 BuiltinID == PPC::BI__builtin_divde || 2871 BuiltinID == PPC::BI__builtin_divdeu; 2872 2873 if (Is64BitBltin && !IsTarget64Bit) 2874 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 2875 << TheCall->getSourceRange(); 2876 2877 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 2878 (BuiltinID == PPC::BI__builtin_bpermd && 2879 !Context.getTargetInfo().hasFeature("bpermd"))) 2880 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2881 << TheCall->getSourceRange(); 2882 2883 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 2884 if (!Context.getTargetInfo().hasFeature("vsx")) 2885 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2886 << TheCall->getSourceRange(); 2887 return false; 2888 }; 2889 2890 switch (BuiltinID) { 2891 default: return false; 2892 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 2893 case PPC::BI__builtin_altivec_crypto_vshasigmad: 2894 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2895 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2896 case PPC::BI__builtin_altivec_dss: 2897 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 2898 case PPC::BI__builtin_tbegin: 2899 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 2900 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 2901 case PPC::BI__builtin_tabortwc: 2902 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 2903 case PPC::BI__builtin_tabortwci: 2904 case PPC::BI__builtin_tabortdci: 2905 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 2906 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 2907 case PPC::BI__builtin_altivec_dst: 2908 case PPC::BI__builtin_altivec_dstt: 2909 case PPC::BI__builtin_altivec_dstst: 2910 case PPC::BI__builtin_altivec_dststt: 2911 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 2912 case PPC::BI__builtin_vsx_xxpermdi: 2913 case PPC::BI__builtin_vsx_xxsldwi: 2914 return SemaBuiltinVSX(TheCall); 2915 case PPC::BI__builtin_unpack_vector_int128: 2916 return SemaVSXCheck(TheCall) || 2917 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2918 case PPC::BI__builtin_pack_vector_int128: 2919 return SemaVSXCheck(TheCall); 2920 } 2921 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2922 } 2923 2924 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 2925 CallExpr *TheCall) { 2926 if (BuiltinID == SystemZ::BI__builtin_tabort) { 2927 Expr *Arg = TheCall->getArg(0); 2928 llvm::APSInt AbortCode(32); 2929 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 2930 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 2931 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 2932 << Arg->getSourceRange(); 2933 } 2934 2935 // For intrinsics which take an immediate value as part of the instruction, 2936 // range check them here. 2937 unsigned i = 0, l = 0, u = 0; 2938 switch (BuiltinID) { 2939 default: return false; 2940 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 2941 case SystemZ::BI__builtin_s390_verimb: 2942 case SystemZ::BI__builtin_s390_verimh: 2943 case SystemZ::BI__builtin_s390_verimf: 2944 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 2945 case SystemZ::BI__builtin_s390_vfaeb: 2946 case SystemZ::BI__builtin_s390_vfaeh: 2947 case SystemZ::BI__builtin_s390_vfaef: 2948 case SystemZ::BI__builtin_s390_vfaebs: 2949 case SystemZ::BI__builtin_s390_vfaehs: 2950 case SystemZ::BI__builtin_s390_vfaefs: 2951 case SystemZ::BI__builtin_s390_vfaezb: 2952 case SystemZ::BI__builtin_s390_vfaezh: 2953 case SystemZ::BI__builtin_s390_vfaezf: 2954 case SystemZ::BI__builtin_s390_vfaezbs: 2955 case SystemZ::BI__builtin_s390_vfaezhs: 2956 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 2957 case SystemZ::BI__builtin_s390_vfisb: 2958 case SystemZ::BI__builtin_s390_vfidb: 2959 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 2960 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2961 case SystemZ::BI__builtin_s390_vftcisb: 2962 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 2963 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 2964 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 2965 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 2966 case SystemZ::BI__builtin_s390_vstrcb: 2967 case SystemZ::BI__builtin_s390_vstrch: 2968 case SystemZ::BI__builtin_s390_vstrcf: 2969 case SystemZ::BI__builtin_s390_vstrczb: 2970 case SystemZ::BI__builtin_s390_vstrczh: 2971 case SystemZ::BI__builtin_s390_vstrczf: 2972 case SystemZ::BI__builtin_s390_vstrcbs: 2973 case SystemZ::BI__builtin_s390_vstrchs: 2974 case SystemZ::BI__builtin_s390_vstrcfs: 2975 case SystemZ::BI__builtin_s390_vstrczbs: 2976 case SystemZ::BI__builtin_s390_vstrczhs: 2977 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 2978 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 2979 case SystemZ::BI__builtin_s390_vfminsb: 2980 case SystemZ::BI__builtin_s390_vfmaxsb: 2981 case SystemZ::BI__builtin_s390_vfmindb: 2982 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 2983 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 2984 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 2985 } 2986 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2987 } 2988 2989 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 2990 /// This checks that the target supports __builtin_cpu_supports and 2991 /// that the string argument is constant and valid. 2992 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 2993 Expr *Arg = TheCall->getArg(0); 2994 2995 // Check if the argument is a string literal. 2996 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 2997 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 2998 << Arg->getSourceRange(); 2999 3000 // Check the contents of the string. 3001 StringRef Feature = 3002 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3003 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 3004 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3005 << Arg->getSourceRange(); 3006 return false; 3007 } 3008 3009 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3010 /// This checks that the target supports __builtin_cpu_is and 3011 /// that the string argument is constant and valid. 3012 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3013 Expr *Arg = TheCall->getArg(0); 3014 3015 // Check if the argument is a string literal. 3016 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3017 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3018 << Arg->getSourceRange(); 3019 3020 // Check the contents of the string. 3021 StringRef Feature = 3022 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3023 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3024 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3025 << Arg->getSourceRange(); 3026 return false; 3027 } 3028 3029 // Check if the rounding mode is legal. 3030 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3031 // Indicates if this instruction has rounding control or just SAE. 3032 bool HasRC = false; 3033 3034 unsigned ArgNum = 0; 3035 switch (BuiltinID) { 3036 default: 3037 return false; 3038 case X86::BI__builtin_ia32_vcvttsd2si32: 3039 case X86::BI__builtin_ia32_vcvttsd2si64: 3040 case X86::BI__builtin_ia32_vcvttsd2usi32: 3041 case X86::BI__builtin_ia32_vcvttsd2usi64: 3042 case X86::BI__builtin_ia32_vcvttss2si32: 3043 case X86::BI__builtin_ia32_vcvttss2si64: 3044 case X86::BI__builtin_ia32_vcvttss2usi32: 3045 case X86::BI__builtin_ia32_vcvttss2usi64: 3046 ArgNum = 1; 3047 break; 3048 case X86::BI__builtin_ia32_maxpd512: 3049 case X86::BI__builtin_ia32_maxps512: 3050 case X86::BI__builtin_ia32_minpd512: 3051 case X86::BI__builtin_ia32_minps512: 3052 ArgNum = 2; 3053 break; 3054 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3055 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3056 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3057 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3058 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3059 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3060 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3061 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3062 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3063 case X86::BI__builtin_ia32_exp2pd_mask: 3064 case X86::BI__builtin_ia32_exp2ps_mask: 3065 case X86::BI__builtin_ia32_getexppd512_mask: 3066 case X86::BI__builtin_ia32_getexpps512_mask: 3067 case X86::BI__builtin_ia32_rcp28pd_mask: 3068 case X86::BI__builtin_ia32_rcp28ps_mask: 3069 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3070 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3071 case X86::BI__builtin_ia32_vcomisd: 3072 case X86::BI__builtin_ia32_vcomiss: 3073 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3074 ArgNum = 3; 3075 break; 3076 case X86::BI__builtin_ia32_cmppd512_mask: 3077 case X86::BI__builtin_ia32_cmpps512_mask: 3078 case X86::BI__builtin_ia32_cmpsd_mask: 3079 case X86::BI__builtin_ia32_cmpss_mask: 3080 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3081 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3082 case X86::BI__builtin_ia32_getexpss128_round_mask: 3083 case X86::BI__builtin_ia32_getmantpd512_mask: 3084 case X86::BI__builtin_ia32_getmantps512_mask: 3085 case X86::BI__builtin_ia32_maxsd_round_mask: 3086 case X86::BI__builtin_ia32_maxss_round_mask: 3087 case X86::BI__builtin_ia32_minsd_round_mask: 3088 case X86::BI__builtin_ia32_minss_round_mask: 3089 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3090 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3091 case X86::BI__builtin_ia32_reducepd512_mask: 3092 case X86::BI__builtin_ia32_reduceps512_mask: 3093 case X86::BI__builtin_ia32_rndscalepd_mask: 3094 case X86::BI__builtin_ia32_rndscaleps_mask: 3095 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3096 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3097 ArgNum = 4; 3098 break; 3099 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3100 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3101 case X86::BI__builtin_ia32_fixupimmps512_mask: 3102 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3103 case X86::BI__builtin_ia32_fixupimmsd_mask: 3104 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3105 case X86::BI__builtin_ia32_fixupimmss_mask: 3106 case X86::BI__builtin_ia32_fixupimmss_maskz: 3107 case X86::BI__builtin_ia32_getmantsd_round_mask: 3108 case X86::BI__builtin_ia32_getmantss_round_mask: 3109 case X86::BI__builtin_ia32_rangepd512_mask: 3110 case X86::BI__builtin_ia32_rangeps512_mask: 3111 case X86::BI__builtin_ia32_rangesd128_round_mask: 3112 case X86::BI__builtin_ia32_rangess128_round_mask: 3113 case X86::BI__builtin_ia32_reducesd_mask: 3114 case X86::BI__builtin_ia32_reducess_mask: 3115 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3116 case X86::BI__builtin_ia32_rndscaless_round_mask: 3117 ArgNum = 5; 3118 break; 3119 case X86::BI__builtin_ia32_vcvtsd2si64: 3120 case X86::BI__builtin_ia32_vcvtsd2si32: 3121 case X86::BI__builtin_ia32_vcvtsd2usi32: 3122 case X86::BI__builtin_ia32_vcvtsd2usi64: 3123 case X86::BI__builtin_ia32_vcvtss2si32: 3124 case X86::BI__builtin_ia32_vcvtss2si64: 3125 case X86::BI__builtin_ia32_vcvtss2usi32: 3126 case X86::BI__builtin_ia32_vcvtss2usi64: 3127 case X86::BI__builtin_ia32_sqrtpd512: 3128 case X86::BI__builtin_ia32_sqrtps512: 3129 ArgNum = 1; 3130 HasRC = true; 3131 break; 3132 case X86::BI__builtin_ia32_addpd512: 3133 case X86::BI__builtin_ia32_addps512: 3134 case X86::BI__builtin_ia32_divpd512: 3135 case X86::BI__builtin_ia32_divps512: 3136 case X86::BI__builtin_ia32_mulpd512: 3137 case X86::BI__builtin_ia32_mulps512: 3138 case X86::BI__builtin_ia32_subpd512: 3139 case X86::BI__builtin_ia32_subps512: 3140 case X86::BI__builtin_ia32_cvtsi2sd64: 3141 case X86::BI__builtin_ia32_cvtsi2ss32: 3142 case X86::BI__builtin_ia32_cvtsi2ss64: 3143 case X86::BI__builtin_ia32_cvtusi2sd64: 3144 case X86::BI__builtin_ia32_cvtusi2ss32: 3145 case X86::BI__builtin_ia32_cvtusi2ss64: 3146 ArgNum = 2; 3147 HasRC = true; 3148 break; 3149 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3150 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3151 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3152 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3153 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3154 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3155 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3156 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3157 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3158 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3159 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3160 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3161 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3162 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3163 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3164 ArgNum = 3; 3165 HasRC = true; 3166 break; 3167 case X86::BI__builtin_ia32_addss_round_mask: 3168 case X86::BI__builtin_ia32_addsd_round_mask: 3169 case X86::BI__builtin_ia32_divss_round_mask: 3170 case X86::BI__builtin_ia32_divsd_round_mask: 3171 case X86::BI__builtin_ia32_mulss_round_mask: 3172 case X86::BI__builtin_ia32_mulsd_round_mask: 3173 case X86::BI__builtin_ia32_subss_round_mask: 3174 case X86::BI__builtin_ia32_subsd_round_mask: 3175 case X86::BI__builtin_ia32_scalefpd512_mask: 3176 case X86::BI__builtin_ia32_scalefps512_mask: 3177 case X86::BI__builtin_ia32_scalefsd_round_mask: 3178 case X86::BI__builtin_ia32_scalefss_round_mask: 3179 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3180 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3181 case X86::BI__builtin_ia32_sqrtss_round_mask: 3182 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3183 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3184 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3185 case X86::BI__builtin_ia32_vfmaddss3_mask: 3186 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3187 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3188 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3189 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3190 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3191 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3192 case X86::BI__builtin_ia32_vfmaddps512_mask: 3193 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3194 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3195 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3196 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3197 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3198 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3199 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3200 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3201 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3202 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3203 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3204 ArgNum = 4; 3205 HasRC = true; 3206 break; 3207 } 3208 3209 llvm::APSInt Result; 3210 3211 // We can't check the value of a dependent argument. 3212 Expr *Arg = TheCall->getArg(ArgNum); 3213 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3214 return false; 3215 3216 // Check constant-ness first. 3217 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3218 return true; 3219 3220 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3221 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3222 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3223 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3224 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3225 Result == 8/*ROUND_NO_EXC*/ || 3226 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3227 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3228 return false; 3229 3230 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3231 << Arg->getSourceRange(); 3232 } 3233 3234 // Check if the gather/scatter scale is legal. 3235 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3236 CallExpr *TheCall) { 3237 unsigned ArgNum = 0; 3238 switch (BuiltinID) { 3239 default: 3240 return false; 3241 case X86::BI__builtin_ia32_gatherpfdpd: 3242 case X86::BI__builtin_ia32_gatherpfdps: 3243 case X86::BI__builtin_ia32_gatherpfqpd: 3244 case X86::BI__builtin_ia32_gatherpfqps: 3245 case X86::BI__builtin_ia32_scatterpfdpd: 3246 case X86::BI__builtin_ia32_scatterpfdps: 3247 case X86::BI__builtin_ia32_scatterpfqpd: 3248 case X86::BI__builtin_ia32_scatterpfqps: 3249 ArgNum = 3; 3250 break; 3251 case X86::BI__builtin_ia32_gatherd_pd: 3252 case X86::BI__builtin_ia32_gatherd_pd256: 3253 case X86::BI__builtin_ia32_gatherq_pd: 3254 case X86::BI__builtin_ia32_gatherq_pd256: 3255 case X86::BI__builtin_ia32_gatherd_ps: 3256 case X86::BI__builtin_ia32_gatherd_ps256: 3257 case X86::BI__builtin_ia32_gatherq_ps: 3258 case X86::BI__builtin_ia32_gatherq_ps256: 3259 case X86::BI__builtin_ia32_gatherd_q: 3260 case X86::BI__builtin_ia32_gatherd_q256: 3261 case X86::BI__builtin_ia32_gatherq_q: 3262 case X86::BI__builtin_ia32_gatherq_q256: 3263 case X86::BI__builtin_ia32_gatherd_d: 3264 case X86::BI__builtin_ia32_gatherd_d256: 3265 case X86::BI__builtin_ia32_gatherq_d: 3266 case X86::BI__builtin_ia32_gatherq_d256: 3267 case X86::BI__builtin_ia32_gather3div2df: 3268 case X86::BI__builtin_ia32_gather3div2di: 3269 case X86::BI__builtin_ia32_gather3div4df: 3270 case X86::BI__builtin_ia32_gather3div4di: 3271 case X86::BI__builtin_ia32_gather3div4sf: 3272 case X86::BI__builtin_ia32_gather3div4si: 3273 case X86::BI__builtin_ia32_gather3div8sf: 3274 case X86::BI__builtin_ia32_gather3div8si: 3275 case X86::BI__builtin_ia32_gather3siv2df: 3276 case X86::BI__builtin_ia32_gather3siv2di: 3277 case X86::BI__builtin_ia32_gather3siv4df: 3278 case X86::BI__builtin_ia32_gather3siv4di: 3279 case X86::BI__builtin_ia32_gather3siv4sf: 3280 case X86::BI__builtin_ia32_gather3siv4si: 3281 case X86::BI__builtin_ia32_gather3siv8sf: 3282 case X86::BI__builtin_ia32_gather3siv8si: 3283 case X86::BI__builtin_ia32_gathersiv8df: 3284 case X86::BI__builtin_ia32_gathersiv16sf: 3285 case X86::BI__builtin_ia32_gatherdiv8df: 3286 case X86::BI__builtin_ia32_gatherdiv16sf: 3287 case X86::BI__builtin_ia32_gathersiv8di: 3288 case X86::BI__builtin_ia32_gathersiv16si: 3289 case X86::BI__builtin_ia32_gatherdiv8di: 3290 case X86::BI__builtin_ia32_gatherdiv16si: 3291 case X86::BI__builtin_ia32_scatterdiv2df: 3292 case X86::BI__builtin_ia32_scatterdiv2di: 3293 case X86::BI__builtin_ia32_scatterdiv4df: 3294 case X86::BI__builtin_ia32_scatterdiv4di: 3295 case X86::BI__builtin_ia32_scatterdiv4sf: 3296 case X86::BI__builtin_ia32_scatterdiv4si: 3297 case X86::BI__builtin_ia32_scatterdiv8sf: 3298 case X86::BI__builtin_ia32_scatterdiv8si: 3299 case X86::BI__builtin_ia32_scattersiv2df: 3300 case X86::BI__builtin_ia32_scattersiv2di: 3301 case X86::BI__builtin_ia32_scattersiv4df: 3302 case X86::BI__builtin_ia32_scattersiv4di: 3303 case X86::BI__builtin_ia32_scattersiv4sf: 3304 case X86::BI__builtin_ia32_scattersiv4si: 3305 case X86::BI__builtin_ia32_scattersiv8sf: 3306 case X86::BI__builtin_ia32_scattersiv8si: 3307 case X86::BI__builtin_ia32_scattersiv8df: 3308 case X86::BI__builtin_ia32_scattersiv16sf: 3309 case X86::BI__builtin_ia32_scatterdiv8df: 3310 case X86::BI__builtin_ia32_scatterdiv16sf: 3311 case X86::BI__builtin_ia32_scattersiv8di: 3312 case X86::BI__builtin_ia32_scattersiv16si: 3313 case X86::BI__builtin_ia32_scatterdiv8di: 3314 case X86::BI__builtin_ia32_scatterdiv16si: 3315 ArgNum = 4; 3316 break; 3317 } 3318 3319 llvm::APSInt Result; 3320 3321 // We can't check the value of a dependent argument. 3322 Expr *Arg = TheCall->getArg(ArgNum); 3323 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3324 return false; 3325 3326 // Check constant-ness first. 3327 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3328 return true; 3329 3330 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3331 return false; 3332 3333 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3334 << Arg->getSourceRange(); 3335 } 3336 3337 static bool isX86_32Builtin(unsigned BuiltinID) { 3338 // These builtins only work on x86-32 targets. 3339 switch (BuiltinID) { 3340 case X86::BI__builtin_ia32_readeflags_u32: 3341 case X86::BI__builtin_ia32_writeeflags_u32: 3342 return true; 3343 } 3344 3345 return false; 3346 } 3347 3348 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3349 if (BuiltinID == X86::BI__builtin_cpu_supports) 3350 return SemaBuiltinCpuSupports(*this, TheCall); 3351 3352 if (BuiltinID == X86::BI__builtin_cpu_is) 3353 return SemaBuiltinCpuIs(*this, TheCall); 3354 3355 // Check for 32-bit only builtins on a 64-bit target. 3356 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3357 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3358 return Diag(TheCall->getCallee()->getBeginLoc(), 3359 diag::err_32_bit_builtin_64_bit_tgt); 3360 3361 // If the intrinsic has rounding or SAE make sure its valid. 3362 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3363 return true; 3364 3365 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3366 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3367 return true; 3368 3369 // For intrinsics which take an immediate value as part of the instruction, 3370 // range check them here. 3371 int i = 0, l = 0, u = 0; 3372 switch (BuiltinID) { 3373 default: 3374 return false; 3375 case X86::BI__builtin_ia32_vec_ext_v2si: 3376 case X86::BI__builtin_ia32_vec_ext_v2di: 3377 case X86::BI__builtin_ia32_vextractf128_pd256: 3378 case X86::BI__builtin_ia32_vextractf128_ps256: 3379 case X86::BI__builtin_ia32_vextractf128_si256: 3380 case X86::BI__builtin_ia32_extract128i256: 3381 case X86::BI__builtin_ia32_extractf64x4_mask: 3382 case X86::BI__builtin_ia32_extracti64x4_mask: 3383 case X86::BI__builtin_ia32_extractf32x8_mask: 3384 case X86::BI__builtin_ia32_extracti32x8_mask: 3385 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3386 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3387 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3388 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3389 i = 1; l = 0; u = 1; 3390 break; 3391 case X86::BI__builtin_ia32_vec_set_v2di: 3392 case X86::BI__builtin_ia32_vinsertf128_pd256: 3393 case X86::BI__builtin_ia32_vinsertf128_ps256: 3394 case X86::BI__builtin_ia32_vinsertf128_si256: 3395 case X86::BI__builtin_ia32_insert128i256: 3396 case X86::BI__builtin_ia32_insertf32x8: 3397 case X86::BI__builtin_ia32_inserti32x8: 3398 case X86::BI__builtin_ia32_insertf64x4: 3399 case X86::BI__builtin_ia32_inserti64x4: 3400 case X86::BI__builtin_ia32_insertf64x2_256: 3401 case X86::BI__builtin_ia32_inserti64x2_256: 3402 case X86::BI__builtin_ia32_insertf32x4_256: 3403 case X86::BI__builtin_ia32_inserti32x4_256: 3404 i = 2; l = 0; u = 1; 3405 break; 3406 case X86::BI__builtin_ia32_vpermilpd: 3407 case X86::BI__builtin_ia32_vec_ext_v4hi: 3408 case X86::BI__builtin_ia32_vec_ext_v4si: 3409 case X86::BI__builtin_ia32_vec_ext_v4sf: 3410 case X86::BI__builtin_ia32_vec_ext_v4di: 3411 case X86::BI__builtin_ia32_extractf32x4_mask: 3412 case X86::BI__builtin_ia32_extracti32x4_mask: 3413 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3414 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3415 i = 1; l = 0; u = 3; 3416 break; 3417 case X86::BI_mm_prefetch: 3418 case X86::BI__builtin_ia32_vec_ext_v8hi: 3419 case X86::BI__builtin_ia32_vec_ext_v8si: 3420 i = 1; l = 0; u = 7; 3421 break; 3422 case X86::BI__builtin_ia32_sha1rnds4: 3423 case X86::BI__builtin_ia32_blendpd: 3424 case X86::BI__builtin_ia32_shufpd: 3425 case X86::BI__builtin_ia32_vec_set_v4hi: 3426 case X86::BI__builtin_ia32_vec_set_v4si: 3427 case X86::BI__builtin_ia32_vec_set_v4di: 3428 case X86::BI__builtin_ia32_shuf_f32x4_256: 3429 case X86::BI__builtin_ia32_shuf_f64x2_256: 3430 case X86::BI__builtin_ia32_shuf_i32x4_256: 3431 case X86::BI__builtin_ia32_shuf_i64x2_256: 3432 case X86::BI__builtin_ia32_insertf64x2_512: 3433 case X86::BI__builtin_ia32_inserti64x2_512: 3434 case X86::BI__builtin_ia32_insertf32x4: 3435 case X86::BI__builtin_ia32_inserti32x4: 3436 i = 2; l = 0; u = 3; 3437 break; 3438 case X86::BI__builtin_ia32_vpermil2pd: 3439 case X86::BI__builtin_ia32_vpermil2pd256: 3440 case X86::BI__builtin_ia32_vpermil2ps: 3441 case X86::BI__builtin_ia32_vpermil2ps256: 3442 i = 3; l = 0; u = 3; 3443 break; 3444 case X86::BI__builtin_ia32_cmpb128_mask: 3445 case X86::BI__builtin_ia32_cmpw128_mask: 3446 case X86::BI__builtin_ia32_cmpd128_mask: 3447 case X86::BI__builtin_ia32_cmpq128_mask: 3448 case X86::BI__builtin_ia32_cmpb256_mask: 3449 case X86::BI__builtin_ia32_cmpw256_mask: 3450 case X86::BI__builtin_ia32_cmpd256_mask: 3451 case X86::BI__builtin_ia32_cmpq256_mask: 3452 case X86::BI__builtin_ia32_cmpb512_mask: 3453 case X86::BI__builtin_ia32_cmpw512_mask: 3454 case X86::BI__builtin_ia32_cmpd512_mask: 3455 case X86::BI__builtin_ia32_cmpq512_mask: 3456 case X86::BI__builtin_ia32_ucmpb128_mask: 3457 case X86::BI__builtin_ia32_ucmpw128_mask: 3458 case X86::BI__builtin_ia32_ucmpd128_mask: 3459 case X86::BI__builtin_ia32_ucmpq128_mask: 3460 case X86::BI__builtin_ia32_ucmpb256_mask: 3461 case X86::BI__builtin_ia32_ucmpw256_mask: 3462 case X86::BI__builtin_ia32_ucmpd256_mask: 3463 case X86::BI__builtin_ia32_ucmpq256_mask: 3464 case X86::BI__builtin_ia32_ucmpb512_mask: 3465 case X86::BI__builtin_ia32_ucmpw512_mask: 3466 case X86::BI__builtin_ia32_ucmpd512_mask: 3467 case X86::BI__builtin_ia32_ucmpq512_mask: 3468 case X86::BI__builtin_ia32_vpcomub: 3469 case X86::BI__builtin_ia32_vpcomuw: 3470 case X86::BI__builtin_ia32_vpcomud: 3471 case X86::BI__builtin_ia32_vpcomuq: 3472 case X86::BI__builtin_ia32_vpcomb: 3473 case X86::BI__builtin_ia32_vpcomw: 3474 case X86::BI__builtin_ia32_vpcomd: 3475 case X86::BI__builtin_ia32_vpcomq: 3476 case X86::BI__builtin_ia32_vec_set_v8hi: 3477 case X86::BI__builtin_ia32_vec_set_v8si: 3478 i = 2; l = 0; u = 7; 3479 break; 3480 case X86::BI__builtin_ia32_vpermilpd256: 3481 case X86::BI__builtin_ia32_roundps: 3482 case X86::BI__builtin_ia32_roundpd: 3483 case X86::BI__builtin_ia32_roundps256: 3484 case X86::BI__builtin_ia32_roundpd256: 3485 case X86::BI__builtin_ia32_getmantpd128_mask: 3486 case X86::BI__builtin_ia32_getmantpd256_mask: 3487 case X86::BI__builtin_ia32_getmantps128_mask: 3488 case X86::BI__builtin_ia32_getmantps256_mask: 3489 case X86::BI__builtin_ia32_getmantpd512_mask: 3490 case X86::BI__builtin_ia32_getmantps512_mask: 3491 case X86::BI__builtin_ia32_vec_ext_v16qi: 3492 case X86::BI__builtin_ia32_vec_ext_v16hi: 3493 i = 1; l = 0; u = 15; 3494 break; 3495 case X86::BI__builtin_ia32_pblendd128: 3496 case X86::BI__builtin_ia32_blendps: 3497 case X86::BI__builtin_ia32_blendpd256: 3498 case X86::BI__builtin_ia32_shufpd256: 3499 case X86::BI__builtin_ia32_roundss: 3500 case X86::BI__builtin_ia32_roundsd: 3501 case X86::BI__builtin_ia32_rangepd128_mask: 3502 case X86::BI__builtin_ia32_rangepd256_mask: 3503 case X86::BI__builtin_ia32_rangepd512_mask: 3504 case X86::BI__builtin_ia32_rangeps128_mask: 3505 case X86::BI__builtin_ia32_rangeps256_mask: 3506 case X86::BI__builtin_ia32_rangeps512_mask: 3507 case X86::BI__builtin_ia32_getmantsd_round_mask: 3508 case X86::BI__builtin_ia32_getmantss_round_mask: 3509 case X86::BI__builtin_ia32_vec_set_v16qi: 3510 case X86::BI__builtin_ia32_vec_set_v16hi: 3511 i = 2; l = 0; u = 15; 3512 break; 3513 case X86::BI__builtin_ia32_vec_ext_v32qi: 3514 i = 1; l = 0; u = 31; 3515 break; 3516 case X86::BI__builtin_ia32_cmpps: 3517 case X86::BI__builtin_ia32_cmpss: 3518 case X86::BI__builtin_ia32_cmppd: 3519 case X86::BI__builtin_ia32_cmpsd: 3520 case X86::BI__builtin_ia32_cmpps256: 3521 case X86::BI__builtin_ia32_cmppd256: 3522 case X86::BI__builtin_ia32_cmpps128_mask: 3523 case X86::BI__builtin_ia32_cmppd128_mask: 3524 case X86::BI__builtin_ia32_cmpps256_mask: 3525 case X86::BI__builtin_ia32_cmppd256_mask: 3526 case X86::BI__builtin_ia32_cmpps512_mask: 3527 case X86::BI__builtin_ia32_cmppd512_mask: 3528 case X86::BI__builtin_ia32_cmpsd_mask: 3529 case X86::BI__builtin_ia32_cmpss_mask: 3530 case X86::BI__builtin_ia32_vec_set_v32qi: 3531 i = 2; l = 0; u = 31; 3532 break; 3533 case X86::BI__builtin_ia32_permdf256: 3534 case X86::BI__builtin_ia32_permdi256: 3535 case X86::BI__builtin_ia32_permdf512: 3536 case X86::BI__builtin_ia32_permdi512: 3537 case X86::BI__builtin_ia32_vpermilps: 3538 case X86::BI__builtin_ia32_vpermilps256: 3539 case X86::BI__builtin_ia32_vpermilpd512: 3540 case X86::BI__builtin_ia32_vpermilps512: 3541 case X86::BI__builtin_ia32_pshufd: 3542 case X86::BI__builtin_ia32_pshufd256: 3543 case X86::BI__builtin_ia32_pshufd512: 3544 case X86::BI__builtin_ia32_pshufhw: 3545 case X86::BI__builtin_ia32_pshufhw256: 3546 case X86::BI__builtin_ia32_pshufhw512: 3547 case X86::BI__builtin_ia32_pshuflw: 3548 case X86::BI__builtin_ia32_pshuflw256: 3549 case X86::BI__builtin_ia32_pshuflw512: 3550 case X86::BI__builtin_ia32_vcvtps2ph: 3551 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3552 case X86::BI__builtin_ia32_vcvtps2ph256: 3553 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3554 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3555 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3556 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3557 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3558 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3559 case X86::BI__builtin_ia32_rndscaleps_mask: 3560 case X86::BI__builtin_ia32_rndscalepd_mask: 3561 case X86::BI__builtin_ia32_reducepd128_mask: 3562 case X86::BI__builtin_ia32_reducepd256_mask: 3563 case X86::BI__builtin_ia32_reducepd512_mask: 3564 case X86::BI__builtin_ia32_reduceps128_mask: 3565 case X86::BI__builtin_ia32_reduceps256_mask: 3566 case X86::BI__builtin_ia32_reduceps512_mask: 3567 case X86::BI__builtin_ia32_prold512: 3568 case X86::BI__builtin_ia32_prolq512: 3569 case X86::BI__builtin_ia32_prold128: 3570 case X86::BI__builtin_ia32_prold256: 3571 case X86::BI__builtin_ia32_prolq128: 3572 case X86::BI__builtin_ia32_prolq256: 3573 case X86::BI__builtin_ia32_prord512: 3574 case X86::BI__builtin_ia32_prorq512: 3575 case X86::BI__builtin_ia32_prord128: 3576 case X86::BI__builtin_ia32_prord256: 3577 case X86::BI__builtin_ia32_prorq128: 3578 case X86::BI__builtin_ia32_prorq256: 3579 case X86::BI__builtin_ia32_fpclasspd128_mask: 3580 case X86::BI__builtin_ia32_fpclasspd256_mask: 3581 case X86::BI__builtin_ia32_fpclassps128_mask: 3582 case X86::BI__builtin_ia32_fpclassps256_mask: 3583 case X86::BI__builtin_ia32_fpclassps512_mask: 3584 case X86::BI__builtin_ia32_fpclasspd512_mask: 3585 case X86::BI__builtin_ia32_fpclasssd_mask: 3586 case X86::BI__builtin_ia32_fpclassss_mask: 3587 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3588 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3589 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3590 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3591 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3592 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3593 case X86::BI__builtin_ia32_kshiftliqi: 3594 case X86::BI__builtin_ia32_kshiftlihi: 3595 case X86::BI__builtin_ia32_kshiftlisi: 3596 case X86::BI__builtin_ia32_kshiftlidi: 3597 case X86::BI__builtin_ia32_kshiftriqi: 3598 case X86::BI__builtin_ia32_kshiftrihi: 3599 case X86::BI__builtin_ia32_kshiftrisi: 3600 case X86::BI__builtin_ia32_kshiftridi: 3601 i = 1; l = 0; u = 255; 3602 break; 3603 case X86::BI__builtin_ia32_vperm2f128_pd256: 3604 case X86::BI__builtin_ia32_vperm2f128_ps256: 3605 case X86::BI__builtin_ia32_vperm2f128_si256: 3606 case X86::BI__builtin_ia32_permti256: 3607 case X86::BI__builtin_ia32_pblendw128: 3608 case X86::BI__builtin_ia32_pblendw256: 3609 case X86::BI__builtin_ia32_blendps256: 3610 case X86::BI__builtin_ia32_pblendd256: 3611 case X86::BI__builtin_ia32_palignr128: 3612 case X86::BI__builtin_ia32_palignr256: 3613 case X86::BI__builtin_ia32_palignr512: 3614 case X86::BI__builtin_ia32_alignq512: 3615 case X86::BI__builtin_ia32_alignd512: 3616 case X86::BI__builtin_ia32_alignd128: 3617 case X86::BI__builtin_ia32_alignd256: 3618 case X86::BI__builtin_ia32_alignq128: 3619 case X86::BI__builtin_ia32_alignq256: 3620 case X86::BI__builtin_ia32_vcomisd: 3621 case X86::BI__builtin_ia32_vcomiss: 3622 case X86::BI__builtin_ia32_shuf_f32x4: 3623 case X86::BI__builtin_ia32_shuf_f64x2: 3624 case X86::BI__builtin_ia32_shuf_i32x4: 3625 case X86::BI__builtin_ia32_shuf_i64x2: 3626 case X86::BI__builtin_ia32_shufpd512: 3627 case X86::BI__builtin_ia32_shufps: 3628 case X86::BI__builtin_ia32_shufps256: 3629 case X86::BI__builtin_ia32_shufps512: 3630 case X86::BI__builtin_ia32_dbpsadbw128: 3631 case X86::BI__builtin_ia32_dbpsadbw256: 3632 case X86::BI__builtin_ia32_dbpsadbw512: 3633 case X86::BI__builtin_ia32_vpshldd128: 3634 case X86::BI__builtin_ia32_vpshldd256: 3635 case X86::BI__builtin_ia32_vpshldd512: 3636 case X86::BI__builtin_ia32_vpshldq128: 3637 case X86::BI__builtin_ia32_vpshldq256: 3638 case X86::BI__builtin_ia32_vpshldq512: 3639 case X86::BI__builtin_ia32_vpshldw128: 3640 case X86::BI__builtin_ia32_vpshldw256: 3641 case X86::BI__builtin_ia32_vpshldw512: 3642 case X86::BI__builtin_ia32_vpshrdd128: 3643 case X86::BI__builtin_ia32_vpshrdd256: 3644 case X86::BI__builtin_ia32_vpshrdd512: 3645 case X86::BI__builtin_ia32_vpshrdq128: 3646 case X86::BI__builtin_ia32_vpshrdq256: 3647 case X86::BI__builtin_ia32_vpshrdq512: 3648 case X86::BI__builtin_ia32_vpshrdw128: 3649 case X86::BI__builtin_ia32_vpshrdw256: 3650 case X86::BI__builtin_ia32_vpshrdw512: 3651 i = 2; l = 0; u = 255; 3652 break; 3653 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3654 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3655 case X86::BI__builtin_ia32_fixupimmps512_mask: 3656 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3657 case X86::BI__builtin_ia32_fixupimmsd_mask: 3658 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3659 case X86::BI__builtin_ia32_fixupimmss_mask: 3660 case X86::BI__builtin_ia32_fixupimmss_maskz: 3661 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3662 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3663 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3664 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3665 case X86::BI__builtin_ia32_fixupimmps128_mask: 3666 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3667 case X86::BI__builtin_ia32_fixupimmps256_mask: 3668 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3669 case X86::BI__builtin_ia32_pternlogd512_mask: 3670 case X86::BI__builtin_ia32_pternlogd512_maskz: 3671 case X86::BI__builtin_ia32_pternlogq512_mask: 3672 case X86::BI__builtin_ia32_pternlogq512_maskz: 3673 case X86::BI__builtin_ia32_pternlogd128_mask: 3674 case X86::BI__builtin_ia32_pternlogd128_maskz: 3675 case X86::BI__builtin_ia32_pternlogd256_mask: 3676 case X86::BI__builtin_ia32_pternlogd256_maskz: 3677 case X86::BI__builtin_ia32_pternlogq128_mask: 3678 case X86::BI__builtin_ia32_pternlogq128_maskz: 3679 case X86::BI__builtin_ia32_pternlogq256_mask: 3680 case X86::BI__builtin_ia32_pternlogq256_maskz: 3681 i = 3; l = 0; u = 255; 3682 break; 3683 case X86::BI__builtin_ia32_gatherpfdpd: 3684 case X86::BI__builtin_ia32_gatherpfdps: 3685 case X86::BI__builtin_ia32_gatherpfqpd: 3686 case X86::BI__builtin_ia32_gatherpfqps: 3687 case X86::BI__builtin_ia32_scatterpfdpd: 3688 case X86::BI__builtin_ia32_scatterpfdps: 3689 case X86::BI__builtin_ia32_scatterpfqpd: 3690 case X86::BI__builtin_ia32_scatterpfqps: 3691 i = 4; l = 2; u = 3; 3692 break; 3693 case X86::BI__builtin_ia32_reducesd_mask: 3694 case X86::BI__builtin_ia32_reducess_mask: 3695 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3696 case X86::BI__builtin_ia32_rndscaless_round_mask: 3697 i = 4; l = 0; u = 255; 3698 break; 3699 } 3700 3701 // Note that we don't force a hard error on the range check here, allowing 3702 // template-generated or macro-generated dead code to potentially have out-of- 3703 // range values. These need to code generate, but don't need to necessarily 3704 // make any sense. We use a warning that defaults to an error. 3705 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3706 } 3707 3708 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3709 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3710 /// Returns true when the format fits the function and the FormatStringInfo has 3711 /// been populated. 3712 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3713 FormatStringInfo *FSI) { 3714 FSI->HasVAListArg = Format->getFirstArg() == 0; 3715 FSI->FormatIdx = Format->getFormatIdx() - 1; 3716 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3717 3718 // The way the format attribute works in GCC, the implicit this argument 3719 // of member functions is counted. However, it doesn't appear in our own 3720 // lists, so decrement format_idx in that case. 3721 if (IsCXXMember) { 3722 if(FSI->FormatIdx == 0) 3723 return false; 3724 --FSI->FormatIdx; 3725 if (FSI->FirstDataArg != 0) 3726 --FSI->FirstDataArg; 3727 } 3728 return true; 3729 } 3730 3731 /// Checks if a the given expression evaluates to null. 3732 /// 3733 /// Returns true if the value evaluates to null. 3734 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3735 // If the expression has non-null type, it doesn't evaluate to null. 3736 if (auto nullability 3737 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3738 if (*nullability == NullabilityKind::NonNull) 3739 return false; 3740 } 3741 3742 // As a special case, transparent unions initialized with zero are 3743 // considered null for the purposes of the nonnull attribute. 3744 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3745 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3746 if (const CompoundLiteralExpr *CLE = 3747 dyn_cast<CompoundLiteralExpr>(Expr)) 3748 if (const InitListExpr *ILE = 3749 dyn_cast<InitListExpr>(CLE->getInitializer())) 3750 Expr = ILE->getInit(0); 3751 } 3752 3753 bool Result; 3754 return (!Expr->isValueDependent() && 3755 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3756 !Result); 3757 } 3758 3759 static void CheckNonNullArgument(Sema &S, 3760 const Expr *ArgExpr, 3761 SourceLocation CallSiteLoc) { 3762 if (CheckNonNullExpr(S, ArgExpr)) 3763 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3764 S.PDiag(diag::warn_null_arg) 3765 << ArgExpr->getSourceRange()); 3766 } 3767 3768 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3769 FormatStringInfo FSI; 3770 if ((GetFormatStringType(Format) == FST_NSString) && 3771 getFormatStringInfo(Format, false, &FSI)) { 3772 Idx = FSI.FormatIdx; 3773 return true; 3774 } 3775 return false; 3776 } 3777 3778 /// Diagnose use of %s directive in an NSString which is being passed 3779 /// as formatting string to formatting method. 3780 static void 3781 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3782 const NamedDecl *FDecl, 3783 Expr **Args, 3784 unsigned NumArgs) { 3785 unsigned Idx = 0; 3786 bool Format = false; 3787 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3788 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3789 Idx = 2; 3790 Format = true; 3791 } 3792 else 3793 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3794 if (S.GetFormatNSStringIdx(I, Idx)) { 3795 Format = true; 3796 break; 3797 } 3798 } 3799 if (!Format || NumArgs <= Idx) 3800 return; 3801 const Expr *FormatExpr = Args[Idx]; 3802 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 3803 FormatExpr = CSCE->getSubExpr(); 3804 const StringLiteral *FormatString; 3805 if (const ObjCStringLiteral *OSL = 3806 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 3807 FormatString = OSL->getString(); 3808 else 3809 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 3810 if (!FormatString) 3811 return; 3812 if (S.FormatStringHasSArg(FormatString)) { 3813 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 3814 << "%s" << 1 << 1; 3815 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 3816 << FDecl->getDeclName(); 3817 } 3818 } 3819 3820 /// Determine whether the given type has a non-null nullability annotation. 3821 static bool isNonNullType(ASTContext &ctx, QualType type) { 3822 if (auto nullability = type->getNullability(ctx)) 3823 return *nullability == NullabilityKind::NonNull; 3824 3825 return false; 3826 } 3827 3828 static void CheckNonNullArguments(Sema &S, 3829 const NamedDecl *FDecl, 3830 const FunctionProtoType *Proto, 3831 ArrayRef<const Expr *> Args, 3832 SourceLocation CallSiteLoc) { 3833 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3834 3835 // Already checked by by constant evaluator. 3836 if (S.isConstantEvaluated()) 3837 return; 3838 // Check the attributes attached to the method/function itself. 3839 llvm::SmallBitVector NonNullArgs; 3840 if (FDecl) { 3841 // Handle the nonnull attribute on the function/method declaration itself. 3842 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 3843 if (!NonNull->args_size()) { 3844 // Easy case: all pointer arguments are nonnull. 3845 for (const auto *Arg : Args) 3846 if (S.isValidPointerAttrType(Arg->getType())) 3847 CheckNonNullArgument(S, Arg, CallSiteLoc); 3848 return; 3849 } 3850 3851 for (const ParamIdx &Idx : NonNull->args()) { 3852 unsigned IdxAST = Idx.getASTIndex(); 3853 if (IdxAST >= Args.size()) 3854 continue; 3855 if (NonNullArgs.empty()) 3856 NonNullArgs.resize(Args.size()); 3857 NonNullArgs.set(IdxAST); 3858 } 3859 } 3860 } 3861 3862 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 3863 // Handle the nonnull attribute on the parameters of the 3864 // function/method. 3865 ArrayRef<ParmVarDecl*> parms; 3866 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 3867 parms = FD->parameters(); 3868 else 3869 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 3870 3871 unsigned ParamIndex = 0; 3872 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 3873 I != E; ++I, ++ParamIndex) { 3874 const ParmVarDecl *PVD = *I; 3875 if (PVD->hasAttr<NonNullAttr>() || 3876 isNonNullType(S.Context, PVD->getType())) { 3877 if (NonNullArgs.empty()) 3878 NonNullArgs.resize(Args.size()); 3879 3880 NonNullArgs.set(ParamIndex); 3881 } 3882 } 3883 } else { 3884 // If we have a non-function, non-method declaration but no 3885 // function prototype, try to dig out the function prototype. 3886 if (!Proto) { 3887 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 3888 QualType type = VD->getType().getNonReferenceType(); 3889 if (auto pointerType = type->getAs<PointerType>()) 3890 type = pointerType->getPointeeType(); 3891 else if (auto blockType = type->getAs<BlockPointerType>()) 3892 type = blockType->getPointeeType(); 3893 // FIXME: data member pointers? 3894 3895 // Dig out the function prototype, if there is one. 3896 Proto = type->getAs<FunctionProtoType>(); 3897 } 3898 } 3899 3900 // Fill in non-null argument information from the nullability 3901 // information on the parameter types (if we have them). 3902 if (Proto) { 3903 unsigned Index = 0; 3904 for (auto paramType : Proto->getParamTypes()) { 3905 if (isNonNullType(S.Context, paramType)) { 3906 if (NonNullArgs.empty()) 3907 NonNullArgs.resize(Args.size()); 3908 3909 NonNullArgs.set(Index); 3910 } 3911 3912 ++Index; 3913 } 3914 } 3915 } 3916 3917 // Check for non-null arguments. 3918 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 3919 ArgIndex != ArgIndexEnd; ++ArgIndex) { 3920 if (NonNullArgs[ArgIndex]) 3921 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 3922 } 3923 } 3924 3925 /// Handles the checks for format strings, non-POD arguments to vararg 3926 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 3927 /// attributes. 3928 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 3929 const Expr *ThisArg, ArrayRef<const Expr *> Args, 3930 bool IsMemberFunction, SourceLocation Loc, 3931 SourceRange Range, VariadicCallType CallType) { 3932 // FIXME: We should check as much as we can in the template definition. 3933 if (CurContext->isDependentContext()) 3934 return; 3935 3936 // Printf and scanf checking. 3937 llvm::SmallBitVector CheckedVarArgs; 3938 if (FDecl) { 3939 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3940 // Only create vector if there are format attributes. 3941 CheckedVarArgs.resize(Args.size()); 3942 3943 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 3944 CheckedVarArgs); 3945 } 3946 } 3947 3948 // Refuse POD arguments that weren't caught by the format string 3949 // checks above. 3950 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 3951 if (CallType != VariadicDoesNotApply && 3952 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 3953 unsigned NumParams = Proto ? Proto->getNumParams() 3954 : FDecl && isa<FunctionDecl>(FDecl) 3955 ? cast<FunctionDecl>(FDecl)->getNumParams() 3956 : FDecl && isa<ObjCMethodDecl>(FDecl) 3957 ? cast<ObjCMethodDecl>(FDecl)->param_size() 3958 : 0; 3959 3960 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 3961 // Args[ArgIdx] can be null in malformed code. 3962 if (const Expr *Arg = Args[ArgIdx]) { 3963 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 3964 checkVariadicArgument(Arg, CallType); 3965 } 3966 } 3967 } 3968 3969 if (FDecl || Proto) { 3970 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 3971 3972 // Type safety checking. 3973 if (FDecl) { 3974 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 3975 CheckArgumentWithTypeTag(I, Args, Loc); 3976 } 3977 } 3978 3979 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 3980 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 3981 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 3982 if (!Arg->isValueDependent()) { 3983 Expr::EvalResult Align; 3984 if (Arg->EvaluateAsInt(Align, Context)) { 3985 const llvm::APSInt &I = Align.Val.getInt(); 3986 if (!I.isPowerOf2()) 3987 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 3988 << Arg->getSourceRange(); 3989 3990 if (I > Sema::MaximumAlignment) 3991 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 3992 << Arg->getSourceRange() << Sema::MaximumAlignment; 3993 } 3994 } 3995 } 3996 3997 if (FD) 3998 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 3999 } 4000 4001 /// CheckConstructorCall - Check a constructor call for correctness and safety 4002 /// properties not enforced by the C type system. 4003 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4004 ArrayRef<const Expr *> Args, 4005 const FunctionProtoType *Proto, 4006 SourceLocation Loc) { 4007 VariadicCallType CallType = 4008 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4009 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4010 Loc, SourceRange(), CallType); 4011 } 4012 4013 /// CheckFunctionCall - Check a direct function call for various correctness 4014 /// and safety properties not strictly enforced by the C type system. 4015 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4016 const FunctionProtoType *Proto) { 4017 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4018 isa<CXXMethodDecl>(FDecl); 4019 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4020 IsMemberOperatorCall; 4021 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4022 TheCall->getCallee()); 4023 Expr** Args = TheCall->getArgs(); 4024 unsigned NumArgs = TheCall->getNumArgs(); 4025 4026 Expr *ImplicitThis = nullptr; 4027 if (IsMemberOperatorCall) { 4028 // If this is a call to a member operator, hide the first argument 4029 // from checkCall. 4030 // FIXME: Our choice of AST representation here is less than ideal. 4031 ImplicitThis = Args[0]; 4032 ++Args; 4033 --NumArgs; 4034 } else if (IsMemberFunction) 4035 ImplicitThis = 4036 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4037 4038 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4039 IsMemberFunction, TheCall->getRParenLoc(), 4040 TheCall->getCallee()->getSourceRange(), CallType); 4041 4042 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4043 // None of the checks below are needed for functions that don't have 4044 // simple names (e.g., C++ conversion functions). 4045 if (!FnInfo) 4046 return false; 4047 4048 CheckAbsoluteValueFunction(TheCall, FDecl); 4049 CheckMaxUnsignedZero(TheCall, FDecl); 4050 4051 if (getLangOpts().ObjC) 4052 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4053 4054 unsigned CMId = FDecl->getMemoryFunctionKind(); 4055 if (CMId == 0) 4056 return false; 4057 4058 // Handle memory setting and copying functions. 4059 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4060 CheckStrlcpycatArguments(TheCall, FnInfo); 4061 else if (CMId == Builtin::BIstrncat) 4062 CheckStrncatArguments(TheCall, FnInfo); 4063 else 4064 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4065 4066 return false; 4067 } 4068 4069 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4070 ArrayRef<const Expr *> Args) { 4071 VariadicCallType CallType = 4072 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4073 4074 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4075 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4076 CallType); 4077 4078 return false; 4079 } 4080 4081 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4082 const FunctionProtoType *Proto) { 4083 QualType Ty; 4084 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4085 Ty = V->getType().getNonReferenceType(); 4086 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4087 Ty = F->getType().getNonReferenceType(); 4088 else 4089 return false; 4090 4091 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4092 !Ty->isFunctionProtoType()) 4093 return false; 4094 4095 VariadicCallType CallType; 4096 if (!Proto || !Proto->isVariadic()) { 4097 CallType = VariadicDoesNotApply; 4098 } else if (Ty->isBlockPointerType()) { 4099 CallType = VariadicBlock; 4100 } else { // Ty->isFunctionPointerType() 4101 CallType = VariadicFunction; 4102 } 4103 4104 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4105 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4106 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4107 TheCall->getCallee()->getSourceRange(), CallType); 4108 4109 return false; 4110 } 4111 4112 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4113 /// such as function pointers returned from functions. 4114 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4115 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4116 TheCall->getCallee()); 4117 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4118 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4119 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4120 TheCall->getCallee()->getSourceRange(), CallType); 4121 4122 return false; 4123 } 4124 4125 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4126 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4127 return false; 4128 4129 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4130 switch (Op) { 4131 case AtomicExpr::AO__c11_atomic_init: 4132 case AtomicExpr::AO__opencl_atomic_init: 4133 llvm_unreachable("There is no ordering argument for an init"); 4134 4135 case AtomicExpr::AO__c11_atomic_load: 4136 case AtomicExpr::AO__opencl_atomic_load: 4137 case AtomicExpr::AO__atomic_load_n: 4138 case AtomicExpr::AO__atomic_load: 4139 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4140 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4141 4142 case AtomicExpr::AO__c11_atomic_store: 4143 case AtomicExpr::AO__opencl_atomic_store: 4144 case AtomicExpr::AO__atomic_store: 4145 case AtomicExpr::AO__atomic_store_n: 4146 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4147 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4148 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4149 4150 default: 4151 return true; 4152 } 4153 } 4154 4155 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4156 AtomicExpr::AtomicOp Op) { 4157 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4158 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4159 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4160 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4161 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4162 Op); 4163 } 4164 4165 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4166 SourceLocation RParenLoc, MultiExprArg Args, 4167 AtomicExpr::AtomicOp Op, 4168 AtomicArgumentOrder ArgOrder) { 4169 // All the non-OpenCL operations take one of the following forms. 4170 // The OpenCL operations take the __c11 forms with one extra argument for 4171 // synchronization scope. 4172 enum { 4173 // C __c11_atomic_init(A *, C) 4174 Init, 4175 4176 // C __c11_atomic_load(A *, int) 4177 Load, 4178 4179 // void __atomic_load(A *, CP, int) 4180 LoadCopy, 4181 4182 // void __atomic_store(A *, CP, int) 4183 Copy, 4184 4185 // C __c11_atomic_add(A *, M, int) 4186 Arithmetic, 4187 4188 // C __atomic_exchange_n(A *, CP, int) 4189 Xchg, 4190 4191 // void __atomic_exchange(A *, C *, CP, int) 4192 GNUXchg, 4193 4194 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4195 C11CmpXchg, 4196 4197 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4198 GNUCmpXchg 4199 } Form = Init; 4200 4201 const unsigned NumForm = GNUCmpXchg + 1; 4202 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4203 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4204 // where: 4205 // C is an appropriate type, 4206 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4207 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4208 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4209 // the int parameters are for orderings. 4210 4211 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4212 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4213 "need to update code for modified forms"); 4214 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4215 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4216 AtomicExpr::AO__atomic_load, 4217 "need to update code for modified C11 atomics"); 4218 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4219 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4220 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4221 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4222 IsOpenCL; 4223 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4224 Op == AtomicExpr::AO__atomic_store_n || 4225 Op == AtomicExpr::AO__atomic_exchange_n || 4226 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4227 bool IsAddSub = false; 4228 4229 switch (Op) { 4230 case AtomicExpr::AO__c11_atomic_init: 4231 case AtomicExpr::AO__opencl_atomic_init: 4232 Form = Init; 4233 break; 4234 4235 case AtomicExpr::AO__c11_atomic_load: 4236 case AtomicExpr::AO__opencl_atomic_load: 4237 case AtomicExpr::AO__atomic_load_n: 4238 Form = Load; 4239 break; 4240 4241 case AtomicExpr::AO__atomic_load: 4242 Form = LoadCopy; 4243 break; 4244 4245 case AtomicExpr::AO__c11_atomic_store: 4246 case AtomicExpr::AO__opencl_atomic_store: 4247 case AtomicExpr::AO__atomic_store: 4248 case AtomicExpr::AO__atomic_store_n: 4249 Form = Copy; 4250 break; 4251 4252 case AtomicExpr::AO__c11_atomic_fetch_add: 4253 case AtomicExpr::AO__c11_atomic_fetch_sub: 4254 case AtomicExpr::AO__opencl_atomic_fetch_add: 4255 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4256 case AtomicExpr::AO__atomic_fetch_add: 4257 case AtomicExpr::AO__atomic_fetch_sub: 4258 case AtomicExpr::AO__atomic_add_fetch: 4259 case AtomicExpr::AO__atomic_sub_fetch: 4260 IsAddSub = true; 4261 LLVM_FALLTHROUGH; 4262 case AtomicExpr::AO__c11_atomic_fetch_and: 4263 case AtomicExpr::AO__c11_atomic_fetch_or: 4264 case AtomicExpr::AO__c11_atomic_fetch_xor: 4265 case AtomicExpr::AO__opencl_atomic_fetch_and: 4266 case AtomicExpr::AO__opencl_atomic_fetch_or: 4267 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4268 case AtomicExpr::AO__atomic_fetch_and: 4269 case AtomicExpr::AO__atomic_fetch_or: 4270 case AtomicExpr::AO__atomic_fetch_xor: 4271 case AtomicExpr::AO__atomic_fetch_nand: 4272 case AtomicExpr::AO__atomic_and_fetch: 4273 case AtomicExpr::AO__atomic_or_fetch: 4274 case AtomicExpr::AO__atomic_xor_fetch: 4275 case AtomicExpr::AO__atomic_nand_fetch: 4276 case AtomicExpr::AO__c11_atomic_fetch_min: 4277 case AtomicExpr::AO__c11_atomic_fetch_max: 4278 case AtomicExpr::AO__opencl_atomic_fetch_min: 4279 case AtomicExpr::AO__opencl_atomic_fetch_max: 4280 case AtomicExpr::AO__atomic_min_fetch: 4281 case AtomicExpr::AO__atomic_max_fetch: 4282 case AtomicExpr::AO__atomic_fetch_min: 4283 case AtomicExpr::AO__atomic_fetch_max: 4284 Form = Arithmetic; 4285 break; 4286 4287 case AtomicExpr::AO__c11_atomic_exchange: 4288 case AtomicExpr::AO__opencl_atomic_exchange: 4289 case AtomicExpr::AO__atomic_exchange_n: 4290 Form = Xchg; 4291 break; 4292 4293 case AtomicExpr::AO__atomic_exchange: 4294 Form = GNUXchg; 4295 break; 4296 4297 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4298 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4299 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4300 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4301 Form = C11CmpXchg; 4302 break; 4303 4304 case AtomicExpr::AO__atomic_compare_exchange: 4305 case AtomicExpr::AO__atomic_compare_exchange_n: 4306 Form = GNUCmpXchg; 4307 break; 4308 } 4309 4310 unsigned AdjustedNumArgs = NumArgs[Form]; 4311 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4312 ++AdjustedNumArgs; 4313 // Check we have the right number of arguments. 4314 if (Args.size() < AdjustedNumArgs) { 4315 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4316 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4317 << ExprRange; 4318 return ExprError(); 4319 } else if (Args.size() > AdjustedNumArgs) { 4320 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4321 diag::err_typecheck_call_too_many_args) 4322 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4323 << ExprRange; 4324 return ExprError(); 4325 } 4326 4327 // Inspect the first argument of the atomic operation. 4328 Expr *Ptr = Args[0]; 4329 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4330 if (ConvertedPtr.isInvalid()) 4331 return ExprError(); 4332 4333 Ptr = ConvertedPtr.get(); 4334 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4335 if (!pointerType) { 4336 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4337 << Ptr->getType() << Ptr->getSourceRange(); 4338 return ExprError(); 4339 } 4340 4341 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4342 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4343 QualType ValType = AtomTy; // 'C' 4344 if (IsC11) { 4345 if (!AtomTy->isAtomicType()) { 4346 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4347 << Ptr->getType() << Ptr->getSourceRange(); 4348 return ExprError(); 4349 } 4350 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4351 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4352 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4353 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4354 << Ptr->getSourceRange(); 4355 return ExprError(); 4356 } 4357 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4358 } else if (Form != Load && Form != LoadCopy) { 4359 if (ValType.isConstQualified()) { 4360 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4361 << Ptr->getType() << Ptr->getSourceRange(); 4362 return ExprError(); 4363 } 4364 } 4365 4366 // For an arithmetic operation, the implied arithmetic must be well-formed. 4367 if (Form == Arithmetic) { 4368 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4369 if (IsAddSub && !ValType->isIntegerType() 4370 && !ValType->isPointerType()) { 4371 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4372 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4373 return ExprError(); 4374 } 4375 if (!IsAddSub && !ValType->isIntegerType()) { 4376 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4377 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4378 return ExprError(); 4379 } 4380 if (IsC11 && ValType->isPointerType() && 4381 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4382 diag::err_incomplete_type)) { 4383 return ExprError(); 4384 } 4385 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4386 // For __atomic_*_n operations, the value type must be a scalar integral or 4387 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4388 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4389 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4390 return ExprError(); 4391 } 4392 4393 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4394 !AtomTy->isScalarType()) { 4395 // For GNU atomics, require a trivially-copyable type. This is not part of 4396 // the GNU atomics specification, but we enforce it for sanity. 4397 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4398 << Ptr->getType() << Ptr->getSourceRange(); 4399 return ExprError(); 4400 } 4401 4402 switch (ValType.getObjCLifetime()) { 4403 case Qualifiers::OCL_None: 4404 case Qualifiers::OCL_ExplicitNone: 4405 // okay 4406 break; 4407 4408 case Qualifiers::OCL_Weak: 4409 case Qualifiers::OCL_Strong: 4410 case Qualifiers::OCL_Autoreleasing: 4411 // FIXME: Can this happen? By this point, ValType should be known 4412 // to be trivially copyable. 4413 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4414 << ValType << Ptr->getSourceRange(); 4415 return ExprError(); 4416 } 4417 4418 // All atomic operations have an overload which takes a pointer to a volatile 4419 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4420 // into the result or the other operands. Similarly atomic_load takes a 4421 // pointer to a const 'A'. 4422 ValType.removeLocalVolatile(); 4423 ValType.removeLocalConst(); 4424 QualType ResultType = ValType; 4425 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4426 Form == Init) 4427 ResultType = Context.VoidTy; 4428 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4429 ResultType = Context.BoolTy; 4430 4431 // The type of a parameter passed 'by value'. In the GNU atomics, such 4432 // arguments are actually passed as pointers. 4433 QualType ByValType = ValType; // 'CP' 4434 bool IsPassedByAddress = false; 4435 if (!IsC11 && !IsN) { 4436 ByValType = Ptr->getType(); 4437 IsPassedByAddress = true; 4438 } 4439 4440 SmallVector<Expr *, 5> APIOrderedArgs; 4441 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4442 APIOrderedArgs.push_back(Args[0]); 4443 switch (Form) { 4444 case Init: 4445 case Load: 4446 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4447 break; 4448 case LoadCopy: 4449 case Copy: 4450 case Arithmetic: 4451 case Xchg: 4452 APIOrderedArgs.push_back(Args[2]); // Val1 4453 APIOrderedArgs.push_back(Args[1]); // Order 4454 break; 4455 case GNUXchg: 4456 APIOrderedArgs.push_back(Args[2]); // Val1 4457 APIOrderedArgs.push_back(Args[3]); // Val2 4458 APIOrderedArgs.push_back(Args[1]); // Order 4459 break; 4460 case C11CmpXchg: 4461 APIOrderedArgs.push_back(Args[2]); // Val1 4462 APIOrderedArgs.push_back(Args[4]); // Val2 4463 APIOrderedArgs.push_back(Args[1]); // Order 4464 APIOrderedArgs.push_back(Args[3]); // OrderFail 4465 break; 4466 case GNUCmpXchg: 4467 APIOrderedArgs.push_back(Args[2]); // Val1 4468 APIOrderedArgs.push_back(Args[4]); // Val2 4469 APIOrderedArgs.push_back(Args[5]); // Weak 4470 APIOrderedArgs.push_back(Args[1]); // Order 4471 APIOrderedArgs.push_back(Args[3]); // OrderFail 4472 break; 4473 } 4474 } else 4475 APIOrderedArgs.append(Args.begin(), Args.end()); 4476 4477 // The first argument's non-CV pointer type is used to deduce the type of 4478 // subsequent arguments, except for: 4479 // - weak flag (always converted to bool) 4480 // - memory order (always converted to int) 4481 // - scope (always converted to int) 4482 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4483 QualType Ty; 4484 if (i < NumVals[Form] + 1) { 4485 switch (i) { 4486 case 0: 4487 // The first argument is always a pointer. It has a fixed type. 4488 // It is always dereferenced, a nullptr is undefined. 4489 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4490 // Nothing else to do: we already know all we want about this pointer. 4491 continue; 4492 case 1: 4493 // The second argument is the non-atomic operand. For arithmetic, this 4494 // is always passed by value, and for a compare_exchange it is always 4495 // passed by address. For the rest, GNU uses by-address and C11 uses 4496 // by-value. 4497 assert(Form != Load); 4498 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4499 Ty = ValType; 4500 else if (Form == Copy || Form == Xchg) { 4501 if (IsPassedByAddress) { 4502 // The value pointer is always dereferenced, a nullptr is undefined. 4503 CheckNonNullArgument(*this, APIOrderedArgs[i], 4504 ExprRange.getBegin()); 4505 } 4506 Ty = ByValType; 4507 } else if (Form == Arithmetic) 4508 Ty = Context.getPointerDiffType(); 4509 else { 4510 Expr *ValArg = APIOrderedArgs[i]; 4511 // The value pointer is always dereferenced, a nullptr is undefined. 4512 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4513 LangAS AS = LangAS::Default; 4514 // Keep address space of non-atomic pointer type. 4515 if (const PointerType *PtrTy = 4516 ValArg->getType()->getAs<PointerType>()) { 4517 AS = PtrTy->getPointeeType().getAddressSpace(); 4518 } 4519 Ty = Context.getPointerType( 4520 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4521 } 4522 break; 4523 case 2: 4524 // The third argument to compare_exchange / GNU exchange is the desired 4525 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4526 if (IsPassedByAddress) 4527 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4528 Ty = ByValType; 4529 break; 4530 case 3: 4531 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4532 Ty = Context.BoolTy; 4533 break; 4534 } 4535 } else { 4536 // The order(s) and scope are always converted to int. 4537 Ty = Context.IntTy; 4538 } 4539 4540 InitializedEntity Entity = 4541 InitializedEntity::InitializeParameter(Context, Ty, false); 4542 ExprResult Arg = APIOrderedArgs[i]; 4543 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4544 if (Arg.isInvalid()) 4545 return true; 4546 APIOrderedArgs[i] = Arg.get(); 4547 } 4548 4549 // Permute the arguments into a 'consistent' order. 4550 SmallVector<Expr*, 5> SubExprs; 4551 SubExprs.push_back(Ptr); 4552 switch (Form) { 4553 case Init: 4554 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4555 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4556 break; 4557 case Load: 4558 SubExprs.push_back(APIOrderedArgs[1]); // Order 4559 break; 4560 case LoadCopy: 4561 case Copy: 4562 case Arithmetic: 4563 case Xchg: 4564 SubExprs.push_back(APIOrderedArgs[2]); // Order 4565 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4566 break; 4567 case GNUXchg: 4568 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4569 SubExprs.push_back(APIOrderedArgs[3]); // Order 4570 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4571 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4572 break; 4573 case C11CmpXchg: 4574 SubExprs.push_back(APIOrderedArgs[3]); // Order 4575 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4576 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 4577 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4578 break; 4579 case GNUCmpXchg: 4580 SubExprs.push_back(APIOrderedArgs[4]); // Order 4581 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4582 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 4583 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4584 SubExprs.push_back(APIOrderedArgs[3]); // Weak 4585 break; 4586 } 4587 4588 if (SubExprs.size() >= 2 && Form != Init) { 4589 llvm::APSInt Result(32); 4590 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4591 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4592 Diag(SubExprs[1]->getBeginLoc(), 4593 diag::warn_atomic_op_has_invalid_memory_order) 4594 << SubExprs[1]->getSourceRange(); 4595 } 4596 4597 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4598 auto *Scope = Args[Args.size() - 1]; 4599 llvm::APSInt Result(32); 4600 if (Scope->isIntegerConstantExpr(Result, Context) && 4601 !ScopeModel->isValid(Result.getZExtValue())) { 4602 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4603 << Scope->getSourceRange(); 4604 } 4605 SubExprs.push_back(Scope); 4606 } 4607 4608 AtomicExpr *AE = new (Context) 4609 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 4610 4611 if ((Op == AtomicExpr::AO__c11_atomic_load || 4612 Op == AtomicExpr::AO__c11_atomic_store || 4613 Op == AtomicExpr::AO__opencl_atomic_load || 4614 Op == AtomicExpr::AO__opencl_atomic_store ) && 4615 Context.AtomicUsesUnsupportedLibcall(AE)) 4616 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4617 << ((Op == AtomicExpr::AO__c11_atomic_load || 4618 Op == AtomicExpr::AO__opencl_atomic_load) 4619 ? 0 4620 : 1); 4621 4622 return AE; 4623 } 4624 4625 /// checkBuiltinArgument - Given a call to a builtin function, perform 4626 /// normal type-checking on the given argument, updating the call in 4627 /// place. This is useful when a builtin function requires custom 4628 /// type-checking for some of its arguments but not necessarily all of 4629 /// them. 4630 /// 4631 /// Returns true on error. 4632 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4633 FunctionDecl *Fn = E->getDirectCallee(); 4634 assert(Fn && "builtin call without direct callee!"); 4635 4636 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4637 InitializedEntity Entity = 4638 InitializedEntity::InitializeParameter(S.Context, Param); 4639 4640 ExprResult Arg = E->getArg(0); 4641 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4642 if (Arg.isInvalid()) 4643 return true; 4644 4645 E->setArg(ArgIndex, Arg.get()); 4646 return false; 4647 } 4648 4649 /// We have a call to a function like __sync_fetch_and_add, which is an 4650 /// overloaded function based on the pointer type of its first argument. 4651 /// The main BuildCallExpr routines have already promoted the types of 4652 /// arguments because all of these calls are prototyped as void(...). 4653 /// 4654 /// This function goes through and does final semantic checking for these 4655 /// builtins, as well as generating any warnings. 4656 ExprResult 4657 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4658 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4659 Expr *Callee = TheCall->getCallee(); 4660 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4661 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4662 4663 // Ensure that we have at least one argument to do type inference from. 4664 if (TheCall->getNumArgs() < 1) { 4665 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4666 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4667 return ExprError(); 4668 } 4669 4670 // Inspect the first argument of the atomic builtin. This should always be 4671 // a pointer type, whose element is an integral scalar or pointer type. 4672 // Because it is a pointer type, we don't have to worry about any implicit 4673 // casts here. 4674 // FIXME: We don't allow floating point scalars as input. 4675 Expr *FirstArg = TheCall->getArg(0); 4676 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4677 if (FirstArgResult.isInvalid()) 4678 return ExprError(); 4679 FirstArg = FirstArgResult.get(); 4680 TheCall->setArg(0, FirstArg); 4681 4682 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4683 if (!pointerType) { 4684 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4685 << FirstArg->getType() << FirstArg->getSourceRange(); 4686 return ExprError(); 4687 } 4688 4689 QualType ValType = pointerType->getPointeeType(); 4690 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4691 !ValType->isBlockPointerType()) { 4692 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4693 << FirstArg->getType() << FirstArg->getSourceRange(); 4694 return ExprError(); 4695 } 4696 4697 if (ValType.isConstQualified()) { 4698 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4699 << FirstArg->getType() << FirstArg->getSourceRange(); 4700 return ExprError(); 4701 } 4702 4703 switch (ValType.getObjCLifetime()) { 4704 case Qualifiers::OCL_None: 4705 case Qualifiers::OCL_ExplicitNone: 4706 // okay 4707 break; 4708 4709 case Qualifiers::OCL_Weak: 4710 case Qualifiers::OCL_Strong: 4711 case Qualifiers::OCL_Autoreleasing: 4712 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4713 << ValType << FirstArg->getSourceRange(); 4714 return ExprError(); 4715 } 4716 4717 // Strip any qualifiers off ValType. 4718 ValType = ValType.getUnqualifiedType(); 4719 4720 // The majority of builtins return a value, but a few have special return 4721 // types, so allow them to override appropriately below. 4722 QualType ResultType = ValType; 4723 4724 // We need to figure out which concrete builtin this maps onto. For example, 4725 // __sync_fetch_and_add with a 2 byte object turns into 4726 // __sync_fetch_and_add_2. 4727 #define BUILTIN_ROW(x) \ 4728 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4729 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4730 4731 static const unsigned BuiltinIndices[][5] = { 4732 BUILTIN_ROW(__sync_fetch_and_add), 4733 BUILTIN_ROW(__sync_fetch_and_sub), 4734 BUILTIN_ROW(__sync_fetch_and_or), 4735 BUILTIN_ROW(__sync_fetch_and_and), 4736 BUILTIN_ROW(__sync_fetch_and_xor), 4737 BUILTIN_ROW(__sync_fetch_and_nand), 4738 4739 BUILTIN_ROW(__sync_add_and_fetch), 4740 BUILTIN_ROW(__sync_sub_and_fetch), 4741 BUILTIN_ROW(__sync_and_and_fetch), 4742 BUILTIN_ROW(__sync_or_and_fetch), 4743 BUILTIN_ROW(__sync_xor_and_fetch), 4744 BUILTIN_ROW(__sync_nand_and_fetch), 4745 4746 BUILTIN_ROW(__sync_val_compare_and_swap), 4747 BUILTIN_ROW(__sync_bool_compare_and_swap), 4748 BUILTIN_ROW(__sync_lock_test_and_set), 4749 BUILTIN_ROW(__sync_lock_release), 4750 BUILTIN_ROW(__sync_swap) 4751 }; 4752 #undef BUILTIN_ROW 4753 4754 // Determine the index of the size. 4755 unsigned SizeIndex; 4756 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4757 case 1: SizeIndex = 0; break; 4758 case 2: SizeIndex = 1; break; 4759 case 4: SizeIndex = 2; break; 4760 case 8: SizeIndex = 3; break; 4761 case 16: SizeIndex = 4; break; 4762 default: 4763 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4764 << FirstArg->getType() << FirstArg->getSourceRange(); 4765 return ExprError(); 4766 } 4767 4768 // Each of these builtins has one pointer argument, followed by some number of 4769 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4770 // that we ignore. Find out which row of BuiltinIndices to read from as well 4771 // as the number of fixed args. 4772 unsigned BuiltinID = FDecl->getBuiltinID(); 4773 unsigned BuiltinIndex, NumFixed = 1; 4774 bool WarnAboutSemanticsChange = false; 4775 switch (BuiltinID) { 4776 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4777 case Builtin::BI__sync_fetch_and_add: 4778 case Builtin::BI__sync_fetch_and_add_1: 4779 case Builtin::BI__sync_fetch_and_add_2: 4780 case Builtin::BI__sync_fetch_and_add_4: 4781 case Builtin::BI__sync_fetch_and_add_8: 4782 case Builtin::BI__sync_fetch_and_add_16: 4783 BuiltinIndex = 0; 4784 break; 4785 4786 case Builtin::BI__sync_fetch_and_sub: 4787 case Builtin::BI__sync_fetch_and_sub_1: 4788 case Builtin::BI__sync_fetch_and_sub_2: 4789 case Builtin::BI__sync_fetch_and_sub_4: 4790 case Builtin::BI__sync_fetch_and_sub_8: 4791 case Builtin::BI__sync_fetch_and_sub_16: 4792 BuiltinIndex = 1; 4793 break; 4794 4795 case Builtin::BI__sync_fetch_and_or: 4796 case Builtin::BI__sync_fetch_and_or_1: 4797 case Builtin::BI__sync_fetch_and_or_2: 4798 case Builtin::BI__sync_fetch_and_or_4: 4799 case Builtin::BI__sync_fetch_and_or_8: 4800 case Builtin::BI__sync_fetch_and_or_16: 4801 BuiltinIndex = 2; 4802 break; 4803 4804 case Builtin::BI__sync_fetch_and_and: 4805 case Builtin::BI__sync_fetch_and_and_1: 4806 case Builtin::BI__sync_fetch_and_and_2: 4807 case Builtin::BI__sync_fetch_and_and_4: 4808 case Builtin::BI__sync_fetch_and_and_8: 4809 case Builtin::BI__sync_fetch_and_and_16: 4810 BuiltinIndex = 3; 4811 break; 4812 4813 case Builtin::BI__sync_fetch_and_xor: 4814 case Builtin::BI__sync_fetch_and_xor_1: 4815 case Builtin::BI__sync_fetch_and_xor_2: 4816 case Builtin::BI__sync_fetch_and_xor_4: 4817 case Builtin::BI__sync_fetch_and_xor_8: 4818 case Builtin::BI__sync_fetch_and_xor_16: 4819 BuiltinIndex = 4; 4820 break; 4821 4822 case Builtin::BI__sync_fetch_and_nand: 4823 case Builtin::BI__sync_fetch_and_nand_1: 4824 case Builtin::BI__sync_fetch_and_nand_2: 4825 case Builtin::BI__sync_fetch_and_nand_4: 4826 case Builtin::BI__sync_fetch_and_nand_8: 4827 case Builtin::BI__sync_fetch_and_nand_16: 4828 BuiltinIndex = 5; 4829 WarnAboutSemanticsChange = true; 4830 break; 4831 4832 case Builtin::BI__sync_add_and_fetch: 4833 case Builtin::BI__sync_add_and_fetch_1: 4834 case Builtin::BI__sync_add_and_fetch_2: 4835 case Builtin::BI__sync_add_and_fetch_4: 4836 case Builtin::BI__sync_add_and_fetch_8: 4837 case Builtin::BI__sync_add_and_fetch_16: 4838 BuiltinIndex = 6; 4839 break; 4840 4841 case Builtin::BI__sync_sub_and_fetch: 4842 case Builtin::BI__sync_sub_and_fetch_1: 4843 case Builtin::BI__sync_sub_and_fetch_2: 4844 case Builtin::BI__sync_sub_and_fetch_4: 4845 case Builtin::BI__sync_sub_and_fetch_8: 4846 case Builtin::BI__sync_sub_and_fetch_16: 4847 BuiltinIndex = 7; 4848 break; 4849 4850 case Builtin::BI__sync_and_and_fetch: 4851 case Builtin::BI__sync_and_and_fetch_1: 4852 case Builtin::BI__sync_and_and_fetch_2: 4853 case Builtin::BI__sync_and_and_fetch_4: 4854 case Builtin::BI__sync_and_and_fetch_8: 4855 case Builtin::BI__sync_and_and_fetch_16: 4856 BuiltinIndex = 8; 4857 break; 4858 4859 case Builtin::BI__sync_or_and_fetch: 4860 case Builtin::BI__sync_or_and_fetch_1: 4861 case Builtin::BI__sync_or_and_fetch_2: 4862 case Builtin::BI__sync_or_and_fetch_4: 4863 case Builtin::BI__sync_or_and_fetch_8: 4864 case Builtin::BI__sync_or_and_fetch_16: 4865 BuiltinIndex = 9; 4866 break; 4867 4868 case Builtin::BI__sync_xor_and_fetch: 4869 case Builtin::BI__sync_xor_and_fetch_1: 4870 case Builtin::BI__sync_xor_and_fetch_2: 4871 case Builtin::BI__sync_xor_and_fetch_4: 4872 case Builtin::BI__sync_xor_and_fetch_8: 4873 case Builtin::BI__sync_xor_and_fetch_16: 4874 BuiltinIndex = 10; 4875 break; 4876 4877 case Builtin::BI__sync_nand_and_fetch: 4878 case Builtin::BI__sync_nand_and_fetch_1: 4879 case Builtin::BI__sync_nand_and_fetch_2: 4880 case Builtin::BI__sync_nand_and_fetch_4: 4881 case Builtin::BI__sync_nand_and_fetch_8: 4882 case Builtin::BI__sync_nand_and_fetch_16: 4883 BuiltinIndex = 11; 4884 WarnAboutSemanticsChange = true; 4885 break; 4886 4887 case Builtin::BI__sync_val_compare_and_swap: 4888 case Builtin::BI__sync_val_compare_and_swap_1: 4889 case Builtin::BI__sync_val_compare_and_swap_2: 4890 case Builtin::BI__sync_val_compare_and_swap_4: 4891 case Builtin::BI__sync_val_compare_and_swap_8: 4892 case Builtin::BI__sync_val_compare_and_swap_16: 4893 BuiltinIndex = 12; 4894 NumFixed = 2; 4895 break; 4896 4897 case Builtin::BI__sync_bool_compare_and_swap: 4898 case Builtin::BI__sync_bool_compare_and_swap_1: 4899 case Builtin::BI__sync_bool_compare_and_swap_2: 4900 case Builtin::BI__sync_bool_compare_and_swap_4: 4901 case Builtin::BI__sync_bool_compare_and_swap_8: 4902 case Builtin::BI__sync_bool_compare_and_swap_16: 4903 BuiltinIndex = 13; 4904 NumFixed = 2; 4905 ResultType = Context.BoolTy; 4906 break; 4907 4908 case Builtin::BI__sync_lock_test_and_set: 4909 case Builtin::BI__sync_lock_test_and_set_1: 4910 case Builtin::BI__sync_lock_test_and_set_2: 4911 case Builtin::BI__sync_lock_test_and_set_4: 4912 case Builtin::BI__sync_lock_test_and_set_8: 4913 case Builtin::BI__sync_lock_test_and_set_16: 4914 BuiltinIndex = 14; 4915 break; 4916 4917 case Builtin::BI__sync_lock_release: 4918 case Builtin::BI__sync_lock_release_1: 4919 case Builtin::BI__sync_lock_release_2: 4920 case Builtin::BI__sync_lock_release_4: 4921 case Builtin::BI__sync_lock_release_8: 4922 case Builtin::BI__sync_lock_release_16: 4923 BuiltinIndex = 15; 4924 NumFixed = 0; 4925 ResultType = Context.VoidTy; 4926 break; 4927 4928 case Builtin::BI__sync_swap: 4929 case Builtin::BI__sync_swap_1: 4930 case Builtin::BI__sync_swap_2: 4931 case Builtin::BI__sync_swap_4: 4932 case Builtin::BI__sync_swap_8: 4933 case Builtin::BI__sync_swap_16: 4934 BuiltinIndex = 16; 4935 break; 4936 } 4937 4938 // Now that we know how many fixed arguments we expect, first check that we 4939 // have at least that many. 4940 if (TheCall->getNumArgs() < 1+NumFixed) { 4941 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4942 << 0 << 1 + NumFixed << TheCall->getNumArgs() 4943 << Callee->getSourceRange(); 4944 return ExprError(); 4945 } 4946 4947 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 4948 << Callee->getSourceRange(); 4949 4950 if (WarnAboutSemanticsChange) { 4951 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 4952 << Callee->getSourceRange(); 4953 } 4954 4955 // Get the decl for the concrete builtin from this, we can tell what the 4956 // concrete integer type we should convert to is. 4957 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 4958 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 4959 FunctionDecl *NewBuiltinDecl; 4960 if (NewBuiltinID == BuiltinID) 4961 NewBuiltinDecl = FDecl; 4962 else { 4963 // Perform builtin lookup to avoid redeclaring it. 4964 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 4965 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 4966 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 4967 assert(Res.getFoundDecl()); 4968 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 4969 if (!NewBuiltinDecl) 4970 return ExprError(); 4971 } 4972 4973 // The first argument --- the pointer --- has a fixed type; we 4974 // deduce the types of the rest of the arguments accordingly. Walk 4975 // the remaining arguments, converting them to the deduced value type. 4976 for (unsigned i = 0; i != NumFixed; ++i) { 4977 ExprResult Arg = TheCall->getArg(i+1); 4978 4979 // GCC does an implicit conversion to the pointer or integer ValType. This 4980 // can fail in some cases (1i -> int**), check for this error case now. 4981 // Initialize the argument. 4982 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4983 ValType, /*consume*/ false); 4984 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4985 if (Arg.isInvalid()) 4986 return ExprError(); 4987 4988 // Okay, we have something that *can* be converted to the right type. Check 4989 // to see if there is a potentially weird extension going on here. This can 4990 // happen when you do an atomic operation on something like an char* and 4991 // pass in 42. The 42 gets converted to char. This is even more strange 4992 // for things like 45.123 -> char, etc. 4993 // FIXME: Do this check. 4994 TheCall->setArg(i+1, Arg.get()); 4995 } 4996 4997 // Create a new DeclRefExpr to refer to the new decl. 4998 DeclRefExpr *NewDRE = DeclRefExpr::Create( 4999 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5000 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5001 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5002 5003 // Set the callee in the CallExpr. 5004 // FIXME: This loses syntactic information. 5005 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5006 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5007 CK_BuiltinFnToFnPtr); 5008 TheCall->setCallee(PromotedCall.get()); 5009 5010 // Change the result type of the call to match the original value type. This 5011 // is arbitrary, but the codegen for these builtins ins design to handle it 5012 // gracefully. 5013 TheCall->setType(ResultType); 5014 5015 return TheCallResult; 5016 } 5017 5018 /// SemaBuiltinNontemporalOverloaded - We have a call to 5019 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5020 /// overloaded function based on the pointer type of its last argument. 5021 /// 5022 /// This function goes through and does final semantic checking for these 5023 /// builtins. 5024 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5025 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5026 DeclRefExpr *DRE = 5027 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5028 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5029 unsigned BuiltinID = FDecl->getBuiltinID(); 5030 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5031 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5032 "Unexpected nontemporal load/store builtin!"); 5033 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5034 unsigned numArgs = isStore ? 2 : 1; 5035 5036 // Ensure that we have the proper number of arguments. 5037 if (checkArgCount(*this, TheCall, numArgs)) 5038 return ExprError(); 5039 5040 // Inspect the last argument of the nontemporal builtin. This should always 5041 // be a pointer type, from which we imply the type of the memory access. 5042 // Because it is a pointer type, we don't have to worry about any implicit 5043 // casts here. 5044 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5045 ExprResult PointerArgResult = 5046 DefaultFunctionArrayLvalueConversion(PointerArg); 5047 5048 if (PointerArgResult.isInvalid()) 5049 return ExprError(); 5050 PointerArg = PointerArgResult.get(); 5051 TheCall->setArg(numArgs - 1, PointerArg); 5052 5053 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5054 if (!pointerType) { 5055 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5056 << PointerArg->getType() << PointerArg->getSourceRange(); 5057 return ExprError(); 5058 } 5059 5060 QualType ValType = pointerType->getPointeeType(); 5061 5062 // Strip any qualifiers off ValType. 5063 ValType = ValType.getUnqualifiedType(); 5064 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5065 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5066 !ValType->isVectorType()) { 5067 Diag(DRE->getBeginLoc(), 5068 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5069 << PointerArg->getType() << PointerArg->getSourceRange(); 5070 return ExprError(); 5071 } 5072 5073 if (!isStore) { 5074 TheCall->setType(ValType); 5075 return TheCallResult; 5076 } 5077 5078 ExprResult ValArg = TheCall->getArg(0); 5079 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5080 Context, ValType, /*consume*/ false); 5081 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5082 if (ValArg.isInvalid()) 5083 return ExprError(); 5084 5085 TheCall->setArg(0, ValArg.get()); 5086 TheCall->setType(Context.VoidTy); 5087 return TheCallResult; 5088 } 5089 5090 /// CheckObjCString - Checks that the argument to the builtin 5091 /// CFString constructor is correct 5092 /// Note: It might also make sense to do the UTF-16 conversion here (would 5093 /// simplify the backend). 5094 bool Sema::CheckObjCString(Expr *Arg) { 5095 Arg = Arg->IgnoreParenCasts(); 5096 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5097 5098 if (!Literal || !Literal->isAscii()) { 5099 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5100 << Arg->getSourceRange(); 5101 return true; 5102 } 5103 5104 if (Literal->containsNonAsciiOrNull()) { 5105 StringRef String = Literal->getString(); 5106 unsigned NumBytes = String.size(); 5107 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5108 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5109 llvm::UTF16 *ToPtr = &ToBuf[0]; 5110 5111 llvm::ConversionResult Result = 5112 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5113 ToPtr + NumBytes, llvm::strictConversion); 5114 // Check for conversion failure. 5115 if (Result != llvm::conversionOK) 5116 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5117 << Arg->getSourceRange(); 5118 } 5119 return false; 5120 } 5121 5122 /// CheckObjCString - Checks that the format string argument to the os_log() 5123 /// and os_trace() functions is correct, and converts it to const char *. 5124 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5125 Arg = Arg->IgnoreParenCasts(); 5126 auto *Literal = dyn_cast<StringLiteral>(Arg); 5127 if (!Literal) { 5128 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5129 Literal = ObjcLiteral->getString(); 5130 } 5131 } 5132 5133 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5134 return ExprError( 5135 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5136 << Arg->getSourceRange()); 5137 } 5138 5139 ExprResult Result(Literal); 5140 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5141 InitializedEntity Entity = 5142 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5143 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5144 return Result; 5145 } 5146 5147 /// Check that the user is calling the appropriate va_start builtin for the 5148 /// target and calling convention. 5149 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5150 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5151 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5152 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5153 TT.getArch() == llvm::Triple::aarch64_32); 5154 bool IsWindows = TT.isOSWindows(); 5155 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5156 if (IsX64 || IsAArch64) { 5157 CallingConv CC = CC_C; 5158 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5159 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5160 if (IsMSVAStart) { 5161 // Don't allow this in System V ABI functions. 5162 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5163 return S.Diag(Fn->getBeginLoc(), 5164 diag::err_ms_va_start_used_in_sysv_function); 5165 } else { 5166 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5167 // On x64 Windows, don't allow this in System V ABI functions. 5168 // (Yes, that means there's no corresponding way to support variadic 5169 // System V ABI functions on Windows.) 5170 if ((IsWindows && CC == CC_X86_64SysV) || 5171 (!IsWindows && CC == CC_Win64)) 5172 return S.Diag(Fn->getBeginLoc(), 5173 diag::err_va_start_used_in_wrong_abi_function) 5174 << !IsWindows; 5175 } 5176 return false; 5177 } 5178 5179 if (IsMSVAStart) 5180 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5181 return false; 5182 } 5183 5184 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5185 ParmVarDecl **LastParam = nullptr) { 5186 // Determine whether the current function, block, or obj-c method is variadic 5187 // and get its parameter list. 5188 bool IsVariadic = false; 5189 ArrayRef<ParmVarDecl *> Params; 5190 DeclContext *Caller = S.CurContext; 5191 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5192 IsVariadic = Block->isVariadic(); 5193 Params = Block->parameters(); 5194 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5195 IsVariadic = FD->isVariadic(); 5196 Params = FD->parameters(); 5197 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5198 IsVariadic = MD->isVariadic(); 5199 // FIXME: This isn't correct for methods (results in bogus warning). 5200 Params = MD->parameters(); 5201 } else if (isa<CapturedDecl>(Caller)) { 5202 // We don't support va_start in a CapturedDecl. 5203 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5204 return true; 5205 } else { 5206 // This must be some other declcontext that parses exprs. 5207 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5208 return true; 5209 } 5210 5211 if (!IsVariadic) { 5212 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5213 return true; 5214 } 5215 5216 if (LastParam) 5217 *LastParam = Params.empty() ? nullptr : Params.back(); 5218 5219 return false; 5220 } 5221 5222 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5223 /// for validity. Emit an error and return true on failure; return false 5224 /// on success. 5225 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5226 Expr *Fn = TheCall->getCallee(); 5227 5228 if (checkVAStartABI(*this, BuiltinID, Fn)) 5229 return true; 5230 5231 if (TheCall->getNumArgs() > 2) { 5232 Diag(TheCall->getArg(2)->getBeginLoc(), 5233 diag::err_typecheck_call_too_many_args) 5234 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5235 << Fn->getSourceRange() 5236 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5237 (*(TheCall->arg_end() - 1))->getEndLoc()); 5238 return true; 5239 } 5240 5241 if (TheCall->getNumArgs() < 2) { 5242 return Diag(TheCall->getEndLoc(), 5243 diag::err_typecheck_call_too_few_args_at_least) 5244 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5245 } 5246 5247 // Type-check the first argument normally. 5248 if (checkBuiltinArgument(*this, TheCall, 0)) 5249 return true; 5250 5251 // Check that the current function is variadic, and get its last parameter. 5252 ParmVarDecl *LastParam; 5253 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5254 return true; 5255 5256 // Verify that the second argument to the builtin is the last argument of the 5257 // current function or method. 5258 bool SecondArgIsLastNamedArgument = false; 5259 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5260 5261 // These are valid if SecondArgIsLastNamedArgument is false after the next 5262 // block. 5263 QualType Type; 5264 SourceLocation ParamLoc; 5265 bool IsCRegister = false; 5266 5267 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5268 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5269 SecondArgIsLastNamedArgument = PV == LastParam; 5270 5271 Type = PV->getType(); 5272 ParamLoc = PV->getLocation(); 5273 IsCRegister = 5274 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5275 } 5276 } 5277 5278 if (!SecondArgIsLastNamedArgument) 5279 Diag(TheCall->getArg(1)->getBeginLoc(), 5280 diag::warn_second_arg_of_va_start_not_last_named_param); 5281 else if (IsCRegister || Type->isReferenceType() || 5282 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5283 // Promotable integers are UB, but enumerations need a bit of 5284 // extra checking to see what their promotable type actually is. 5285 if (!Type->isPromotableIntegerType()) 5286 return false; 5287 if (!Type->isEnumeralType()) 5288 return true; 5289 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5290 return !(ED && 5291 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5292 }()) { 5293 unsigned Reason = 0; 5294 if (Type->isReferenceType()) Reason = 1; 5295 else if (IsCRegister) Reason = 2; 5296 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5297 Diag(ParamLoc, diag::note_parameter_type) << Type; 5298 } 5299 5300 TheCall->setType(Context.VoidTy); 5301 return false; 5302 } 5303 5304 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5305 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5306 // const char *named_addr); 5307 5308 Expr *Func = Call->getCallee(); 5309 5310 if (Call->getNumArgs() < 3) 5311 return Diag(Call->getEndLoc(), 5312 diag::err_typecheck_call_too_few_args_at_least) 5313 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5314 5315 // Type-check the first argument normally. 5316 if (checkBuiltinArgument(*this, Call, 0)) 5317 return true; 5318 5319 // Check that the current function is variadic. 5320 if (checkVAStartIsInVariadicFunction(*this, Func)) 5321 return true; 5322 5323 // __va_start on Windows does not validate the parameter qualifiers 5324 5325 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5326 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5327 5328 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5329 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5330 5331 const QualType &ConstCharPtrTy = 5332 Context.getPointerType(Context.CharTy.withConst()); 5333 if (!Arg1Ty->isPointerType() || 5334 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5335 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5336 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5337 << 0 /* qualifier difference */ 5338 << 3 /* parameter mismatch */ 5339 << 2 << Arg1->getType() << ConstCharPtrTy; 5340 5341 const QualType SizeTy = Context.getSizeType(); 5342 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5343 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5344 << Arg2->getType() << SizeTy << 1 /* different class */ 5345 << 0 /* qualifier difference */ 5346 << 3 /* parameter mismatch */ 5347 << 3 << Arg2->getType() << SizeTy; 5348 5349 return false; 5350 } 5351 5352 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5353 /// friends. This is declared to take (...), so we have to check everything. 5354 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5355 if (TheCall->getNumArgs() < 2) 5356 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5357 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5358 if (TheCall->getNumArgs() > 2) 5359 return Diag(TheCall->getArg(2)->getBeginLoc(), 5360 diag::err_typecheck_call_too_many_args) 5361 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5362 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5363 (*(TheCall->arg_end() - 1))->getEndLoc()); 5364 5365 ExprResult OrigArg0 = TheCall->getArg(0); 5366 ExprResult OrigArg1 = TheCall->getArg(1); 5367 5368 // Do standard promotions between the two arguments, returning their common 5369 // type. 5370 QualType Res = UsualArithmeticConversions( 5371 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5372 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5373 return true; 5374 5375 // Make sure any conversions are pushed back into the call; this is 5376 // type safe since unordered compare builtins are declared as "_Bool 5377 // foo(...)". 5378 TheCall->setArg(0, OrigArg0.get()); 5379 TheCall->setArg(1, OrigArg1.get()); 5380 5381 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5382 return false; 5383 5384 // If the common type isn't a real floating type, then the arguments were 5385 // invalid for this operation. 5386 if (Res.isNull() || !Res->isRealFloatingType()) 5387 return Diag(OrigArg0.get()->getBeginLoc(), 5388 diag::err_typecheck_call_invalid_ordered_compare) 5389 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5390 << SourceRange(OrigArg0.get()->getBeginLoc(), 5391 OrigArg1.get()->getEndLoc()); 5392 5393 return false; 5394 } 5395 5396 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5397 /// __builtin_isnan and friends. This is declared to take (...), so we have 5398 /// to check everything. We expect the last argument to be a floating point 5399 /// value. 5400 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5401 if (TheCall->getNumArgs() < NumArgs) 5402 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5403 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5404 if (TheCall->getNumArgs() > NumArgs) 5405 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5406 diag::err_typecheck_call_too_many_args) 5407 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5408 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5409 (*(TheCall->arg_end() - 1))->getEndLoc()); 5410 5411 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5412 // on all preceding parameters just being int. Try all of those. 5413 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5414 Expr *Arg = TheCall->getArg(i); 5415 5416 if (Arg->isTypeDependent()) 5417 return false; 5418 5419 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5420 5421 if (Res.isInvalid()) 5422 return true; 5423 TheCall->setArg(i, Res.get()); 5424 } 5425 5426 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5427 5428 if (OrigArg->isTypeDependent()) 5429 return false; 5430 5431 // Usual Unary Conversions will convert half to float, which we want for 5432 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5433 // type how it is, but do normal L->Rvalue conversions. 5434 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5435 OrigArg = UsualUnaryConversions(OrigArg).get(); 5436 else 5437 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5438 TheCall->setArg(NumArgs - 1, OrigArg); 5439 5440 // This operation requires a non-_Complex floating-point number. 5441 if (!OrigArg->getType()->isRealFloatingType()) 5442 return Diag(OrigArg->getBeginLoc(), 5443 diag::err_typecheck_call_invalid_unary_fp) 5444 << OrigArg->getType() << OrigArg->getSourceRange(); 5445 5446 return false; 5447 } 5448 5449 // Customized Sema Checking for VSX builtins that have the following signature: 5450 // vector [...] builtinName(vector [...], vector [...], const int); 5451 // Which takes the same type of vectors (any legal vector type) for the first 5452 // two arguments and takes compile time constant for the third argument. 5453 // Example builtins are : 5454 // vector double vec_xxpermdi(vector double, vector double, int); 5455 // vector short vec_xxsldwi(vector short, vector short, int); 5456 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5457 unsigned ExpectedNumArgs = 3; 5458 if (TheCall->getNumArgs() < ExpectedNumArgs) 5459 return Diag(TheCall->getEndLoc(), 5460 diag::err_typecheck_call_too_few_args_at_least) 5461 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5462 << TheCall->getSourceRange(); 5463 5464 if (TheCall->getNumArgs() > ExpectedNumArgs) 5465 return Diag(TheCall->getEndLoc(), 5466 diag::err_typecheck_call_too_many_args_at_most) 5467 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5468 << TheCall->getSourceRange(); 5469 5470 // Check the third argument is a compile time constant 5471 llvm::APSInt Value; 5472 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5473 return Diag(TheCall->getBeginLoc(), 5474 diag::err_vsx_builtin_nonconstant_argument) 5475 << 3 /* argument index */ << TheCall->getDirectCallee() 5476 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5477 TheCall->getArg(2)->getEndLoc()); 5478 5479 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5480 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5481 5482 // Check the type of argument 1 and argument 2 are vectors. 5483 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5484 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5485 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5486 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5487 << TheCall->getDirectCallee() 5488 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5489 TheCall->getArg(1)->getEndLoc()); 5490 } 5491 5492 // Check the first two arguments are the same type. 5493 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5494 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5495 << TheCall->getDirectCallee() 5496 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5497 TheCall->getArg(1)->getEndLoc()); 5498 } 5499 5500 // When default clang type checking is turned off and the customized type 5501 // checking is used, the returning type of the function must be explicitly 5502 // set. Otherwise it is _Bool by default. 5503 TheCall->setType(Arg1Ty); 5504 5505 return false; 5506 } 5507 5508 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5509 // This is declared to take (...), so we have to check everything. 5510 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5511 if (TheCall->getNumArgs() < 2) 5512 return ExprError(Diag(TheCall->getEndLoc(), 5513 diag::err_typecheck_call_too_few_args_at_least) 5514 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5515 << TheCall->getSourceRange()); 5516 5517 // Determine which of the following types of shufflevector we're checking: 5518 // 1) unary, vector mask: (lhs, mask) 5519 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5520 QualType resType = TheCall->getArg(0)->getType(); 5521 unsigned numElements = 0; 5522 5523 if (!TheCall->getArg(0)->isTypeDependent() && 5524 !TheCall->getArg(1)->isTypeDependent()) { 5525 QualType LHSType = TheCall->getArg(0)->getType(); 5526 QualType RHSType = TheCall->getArg(1)->getType(); 5527 5528 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5529 return ExprError( 5530 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5531 << TheCall->getDirectCallee() 5532 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5533 TheCall->getArg(1)->getEndLoc())); 5534 5535 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5536 unsigned numResElements = TheCall->getNumArgs() - 2; 5537 5538 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5539 // with mask. If so, verify that RHS is an integer vector type with the 5540 // same number of elts as lhs. 5541 if (TheCall->getNumArgs() == 2) { 5542 if (!RHSType->hasIntegerRepresentation() || 5543 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5544 return ExprError(Diag(TheCall->getBeginLoc(), 5545 diag::err_vec_builtin_incompatible_vector) 5546 << TheCall->getDirectCallee() 5547 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5548 TheCall->getArg(1)->getEndLoc())); 5549 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5550 return ExprError(Diag(TheCall->getBeginLoc(), 5551 diag::err_vec_builtin_incompatible_vector) 5552 << TheCall->getDirectCallee() 5553 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5554 TheCall->getArg(1)->getEndLoc())); 5555 } else if (numElements != numResElements) { 5556 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5557 resType = Context.getVectorType(eltType, numResElements, 5558 VectorType::GenericVector); 5559 } 5560 } 5561 5562 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5563 if (TheCall->getArg(i)->isTypeDependent() || 5564 TheCall->getArg(i)->isValueDependent()) 5565 continue; 5566 5567 llvm::APSInt Result(32); 5568 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5569 return ExprError(Diag(TheCall->getBeginLoc(), 5570 diag::err_shufflevector_nonconstant_argument) 5571 << TheCall->getArg(i)->getSourceRange()); 5572 5573 // Allow -1 which will be translated to undef in the IR. 5574 if (Result.isSigned() && Result.isAllOnesValue()) 5575 continue; 5576 5577 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5578 return ExprError(Diag(TheCall->getBeginLoc(), 5579 diag::err_shufflevector_argument_too_large) 5580 << TheCall->getArg(i)->getSourceRange()); 5581 } 5582 5583 SmallVector<Expr*, 32> exprs; 5584 5585 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5586 exprs.push_back(TheCall->getArg(i)); 5587 TheCall->setArg(i, nullptr); 5588 } 5589 5590 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5591 TheCall->getCallee()->getBeginLoc(), 5592 TheCall->getRParenLoc()); 5593 } 5594 5595 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5596 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5597 SourceLocation BuiltinLoc, 5598 SourceLocation RParenLoc) { 5599 ExprValueKind VK = VK_RValue; 5600 ExprObjectKind OK = OK_Ordinary; 5601 QualType DstTy = TInfo->getType(); 5602 QualType SrcTy = E->getType(); 5603 5604 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5605 return ExprError(Diag(BuiltinLoc, 5606 diag::err_convertvector_non_vector) 5607 << E->getSourceRange()); 5608 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5609 return ExprError(Diag(BuiltinLoc, 5610 diag::err_convertvector_non_vector_type)); 5611 5612 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5613 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 5614 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 5615 if (SrcElts != DstElts) 5616 return ExprError(Diag(BuiltinLoc, 5617 diag::err_convertvector_incompatible_vector) 5618 << E->getSourceRange()); 5619 } 5620 5621 return new (Context) 5622 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5623 } 5624 5625 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5626 // This is declared to take (const void*, ...) and can take two 5627 // optional constant int args. 5628 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5629 unsigned NumArgs = TheCall->getNumArgs(); 5630 5631 if (NumArgs > 3) 5632 return Diag(TheCall->getEndLoc(), 5633 diag::err_typecheck_call_too_many_args_at_most) 5634 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5635 5636 // Argument 0 is checked for us and the remaining arguments must be 5637 // constant integers. 5638 for (unsigned i = 1; i != NumArgs; ++i) 5639 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5640 return true; 5641 5642 return false; 5643 } 5644 5645 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5646 // __assume does not evaluate its arguments, and should warn if its argument 5647 // has side effects. 5648 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5649 Expr *Arg = TheCall->getArg(0); 5650 if (Arg->isInstantiationDependent()) return false; 5651 5652 if (Arg->HasSideEffects(Context)) 5653 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5654 << Arg->getSourceRange() 5655 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5656 5657 return false; 5658 } 5659 5660 /// Handle __builtin_alloca_with_align. This is declared 5661 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5662 /// than 8. 5663 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5664 // The alignment must be a constant integer. 5665 Expr *Arg = TheCall->getArg(1); 5666 5667 // We can't check the value of a dependent argument. 5668 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5669 if (const auto *UE = 5670 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5671 if (UE->getKind() == UETT_AlignOf || 5672 UE->getKind() == UETT_PreferredAlignOf) 5673 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5674 << Arg->getSourceRange(); 5675 5676 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5677 5678 if (!Result.isPowerOf2()) 5679 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5680 << Arg->getSourceRange(); 5681 5682 if (Result < Context.getCharWidth()) 5683 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5684 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5685 5686 if (Result > std::numeric_limits<int32_t>::max()) 5687 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5688 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5689 } 5690 5691 return false; 5692 } 5693 5694 /// Handle __builtin_assume_aligned. This is declared 5695 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5696 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5697 unsigned NumArgs = TheCall->getNumArgs(); 5698 5699 if (NumArgs > 3) 5700 return Diag(TheCall->getEndLoc(), 5701 diag::err_typecheck_call_too_many_args_at_most) 5702 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5703 5704 // The alignment must be a constant integer. 5705 Expr *Arg = TheCall->getArg(1); 5706 5707 // We can't check the value of a dependent argument. 5708 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5709 llvm::APSInt Result; 5710 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5711 return true; 5712 5713 if (!Result.isPowerOf2()) 5714 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5715 << Arg->getSourceRange(); 5716 5717 if (Result > Sema::MaximumAlignment) 5718 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 5719 << Arg->getSourceRange() << Sema::MaximumAlignment; 5720 } 5721 5722 if (NumArgs > 2) { 5723 ExprResult Arg(TheCall->getArg(2)); 5724 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5725 Context.getSizeType(), false); 5726 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5727 if (Arg.isInvalid()) return true; 5728 TheCall->setArg(2, Arg.get()); 5729 } 5730 5731 return false; 5732 } 5733 5734 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5735 unsigned BuiltinID = 5736 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5737 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5738 5739 unsigned NumArgs = TheCall->getNumArgs(); 5740 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5741 if (NumArgs < NumRequiredArgs) { 5742 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5743 << 0 /* function call */ << NumRequiredArgs << NumArgs 5744 << TheCall->getSourceRange(); 5745 } 5746 if (NumArgs >= NumRequiredArgs + 0x100) { 5747 return Diag(TheCall->getEndLoc(), 5748 diag::err_typecheck_call_too_many_args_at_most) 5749 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5750 << TheCall->getSourceRange(); 5751 } 5752 unsigned i = 0; 5753 5754 // For formatting call, check buffer arg. 5755 if (!IsSizeCall) { 5756 ExprResult Arg(TheCall->getArg(i)); 5757 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5758 Context, Context.VoidPtrTy, false); 5759 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5760 if (Arg.isInvalid()) 5761 return true; 5762 TheCall->setArg(i, Arg.get()); 5763 i++; 5764 } 5765 5766 // Check string literal arg. 5767 unsigned FormatIdx = i; 5768 { 5769 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5770 if (Arg.isInvalid()) 5771 return true; 5772 TheCall->setArg(i, Arg.get()); 5773 i++; 5774 } 5775 5776 // Make sure variadic args are scalar. 5777 unsigned FirstDataArg = i; 5778 while (i < NumArgs) { 5779 ExprResult Arg = DefaultVariadicArgumentPromotion( 5780 TheCall->getArg(i), VariadicFunction, nullptr); 5781 if (Arg.isInvalid()) 5782 return true; 5783 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5784 if (ArgSize.getQuantity() >= 0x100) { 5785 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5786 << i << (int)ArgSize.getQuantity() << 0xff 5787 << TheCall->getSourceRange(); 5788 } 5789 TheCall->setArg(i, Arg.get()); 5790 i++; 5791 } 5792 5793 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5794 // call to avoid duplicate diagnostics. 5795 if (!IsSizeCall) { 5796 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 5797 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 5798 bool Success = CheckFormatArguments( 5799 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 5800 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 5801 CheckedVarArgs); 5802 if (!Success) 5803 return true; 5804 } 5805 5806 if (IsSizeCall) { 5807 TheCall->setType(Context.getSizeType()); 5808 } else { 5809 TheCall->setType(Context.VoidPtrTy); 5810 } 5811 return false; 5812 } 5813 5814 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 5815 /// TheCall is a constant expression. 5816 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5817 llvm::APSInt &Result) { 5818 Expr *Arg = TheCall->getArg(ArgNum); 5819 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5820 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5821 5822 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5823 5824 if (!Arg->isIntegerConstantExpr(Result, Context)) 5825 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 5826 << FDecl->getDeclName() << Arg->getSourceRange(); 5827 5828 return false; 5829 } 5830 5831 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5832 /// TheCall is a constant expression in the range [Low, High]. 5833 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5834 int Low, int High, bool RangeIsError) { 5835 if (isConstantEvaluated()) 5836 return false; 5837 llvm::APSInt Result; 5838 5839 // We can't check the value of a dependent argument. 5840 Expr *Arg = TheCall->getArg(ArgNum); 5841 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5842 return false; 5843 5844 // Check constant-ness first. 5845 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5846 return true; 5847 5848 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 5849 if (RangeIsError) 5850 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 5851 << Result.toString(10) << Low << High << Arg->getSourceRange(); 5852 else 5853 // Defer the warning until we know if the code will be emitted so that 5854 // dead code can ignore this. 5855 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 5856 PDiag(diag::warn_argument_invalid_range) 5857 << Result.toString(10) << Low << High 5858 << Arg->getSourceRange()); 5859 } 5860 5861 return false; 5862 } 5863 5864 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 5865 /// TheCall is a constant expression is a multiple of Num.. 5866 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 5867 unsigned Num) { 5868 llvm::APSInt Result; 5869 5870 // We can't check the value of a dependent argument. 5871 Expr *Arg = TheCall->getArg(ArgNum); 5872 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5873 return false; 5874 5875 // Check constant-ness first. 5876 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5877 return true; 5878 5879 if (Result.getSExtValue() % Num != 0) 5880 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 5881 << Num << Arg->getSourceRange(); 5882 5883 return false; 5884 } 5885 5886 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 5887 /// constant expression representing a power of 2. 5888 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 5889 llvm::APSInt Result; 5890 5891 // We can't check the value of a dependent argument. 5892 Expr *Arg = TheCall->getArg(ArgNum); 5893 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5894 return false; 5895 5896 // Check constant-ness first. 5897 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5898 return true; 5899 5900 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 5901 // and only if x is a power of 2. 5902 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 5903 return false; 5904 5905 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 5906 << Arg->getSourceRange(); 5907 } 5908 5909 static bool IsShiftedByte(llvm::APSInt Value) { 5910 if (Value.isNegative()) 5911 return false; 5912 5913 // Check if it's a shifted byte, by shifting it down 5914 while (true) { 5915 // If the value fits in the bottom byte, the check passes. 5916 if (Value < 0x100) 5917 return true; 5918 5919 // Otherwise, if the value has _any_ bits in the bottom byte, the check 5920 // fails. 5921 if ((Value & 0xFF) != 0) 5922 return false; 5923 5924 // If the bottom 8 bits are all 0, but something above that is nonzero, 5925 // then shifting the value right by 8 bits won't affect whether it's a 5926 // shifted byte or not. So do that, and go round again. 5927 Value >>= 8; 5928 } 5929 } 5930 5931 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 5932 /// a constant expression representing an arbitrary byte value shifted left by 5933 /// a multiple of 8 bits. 5934 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 5935 unsigned ArgBits) { 5936 llvm::APSInt Result; 5937 5938 // We can't check the value of a dependent argument. 5939 Expr *Arg = TheCall->getArg(ArgNum); 5940 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5941 return false; 5942 5943 // Check constant-ness first. 5944 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5945 return true; 5946 5947 // Truncate to the given size. 5948 Result = Result.getLoBits(ArgBits); 5949 Result.setIsUnsigned(true); 5950 5951 if (IsShiftedByte(Result)) 5952 return false; 5953 5954 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 5955 << Arg->getSourceRange(); 5956 } 5957 5958 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 5959 /// TheCall is a constant expression representing either a shifted byte value, 5960 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 5961 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 5962 /// Arm MVE intrinsics. 5963 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 5964 int ArgNum, 5965 unsigned ArgBits) { 5966 llvm::APSInt Result; 5967 5968 // We can't check the value of a dependent argument. 5969 Expr *Arg = TheCall->getArg(ArgNum); 5970 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5971 return false; 5972 5973 // Check constant-ness first. 5974 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5975 return true; 5976 5977 // Truncate to the given size. 5978 Result = Result.getLoBits(ArgBits); 5979 Result.setIsUnsigned(true); 5980 5981 // Check to see if it's in either of the required forms. 5982 if (IsShiftedByte(Result) || 5983 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 5984 return false; 5985 5986 return Diag(TheCall->getBeginLoc(), 5987 diag::err_argument_not_shifted_byte_or_xxff) 5988 << Arg->getSourceRange(); 5989 } 5990 5991 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 5992 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 5993 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 5994 if (checkArgCount(*this, TheCall, 2)) 5995 return true; 5996 Expr *Arg0 = TheCall->getArg(0); 5997 Expr *Arg1 = TheCall->getArg(1); 5998 5999 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6000 if (FirstArg.isInvalid()) 6001 return true; 6002 QualType FirstArgType = FirstArg.get()->getType(); 6003 if (!FirstArgType->isAnyPointerType()) 6004 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6005 << "first" << FirstArgType << Arg0->getSourceRange(); 6006 TheCall->setArg(0, FirstArg.get()); 6007 6008 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6009 if (SecArg.isInvalid()) 6010 return true; 6011 QualType SecArgType = SecArg.get()->getType(); 6012 if (!SecArgType->isIntegerType()) 6013 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6014 << "second" << SecArgType << Arg1->getSourceRange(); 6015 6016 // Derive the return type from the pointer argument. 6017 TheCall->setType(FirstArgType); 6018 return false; 6019 } 6020 6021 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6022 if (checkArgCount(*this, TheCall, 2)) 6023 return true; 6024 6025 Expr *Arg0 = TheCall->getArg(0); 6026 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6027 if (FirstArg.isInvalid()) 6028 return true; 6029 QualType FirstArgType = FirstArg.get()->getType(); 6030 if (!FirstArgType->isAnyPointerType()) 6031 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6032 << "first" << FirstArgType << Arg0->getSourceRange(); 6033 TheCall->setArg(0, FirstArg.get()); 6034 6035 // Derive the return type from the pointer argument. 6036 TheCall->setType(FirstArgType); 6037 6038 // Second arg must be an constant in range [0,15] 6039 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6040 } 6041 6042 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6043 if (checkArgCount(*this, TheCall, 2)) 6044 return true; 6045 Expr *Arg0 = TheCall->getArg(0); 6046 Expr *Arg1 = TheCall->getArg(1); 6047 6048 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6049 if (FirstArg.isInvalid()) 6050 return true; 6051 QualType FirstArgType = FirstArg.get()->getType(); 6052 if (!FirstArgType->isAnyPointerType()) 6053 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6054 << "first" << FirstArgType << Arg0->getSourceRange(); 6055 6056 QualType SecArgType = Arg1->getType(); 6057 if (!SecArgType->isIntegerType()) 6058 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6059 << "second" << SecArgType << Arg1->getSourceRange(); 6060 TheCall->setType(Context.IntTy); 6061 return false; 6062 } 6063 6064 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6065 BuiltinID == AArch64::BI__builtin_arm_stg) { 6066 if (checkArgCount(*this, TheCall, 1)) 6067 return true; 6068 Expr *Arg0 = TheCall->getArg(0); 6069 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6070 if (FirstArg.isInvalid()) 6071 return true; 6072 6073 QualType FirstArgType = FirstArg.get()->getType(); 6074 if (!FirstArgType->isAnyPointerType()) 6075 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6076 << "first" << FirstArgType << Arg0->getSourceRange(); 6077 TheCall->setArg(0, FirstArg.get()); 6078 6079 // Derive the return type from the pointer argument. 6080 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6081 TheCall->setType(FirstArgType); 6082 return false; 6083 } 6084 6085 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6086 Expr *ArgA = TheCall->getArg(0); 6087 Expr *ArgB = TheCall->getArg(1); 6088 6089 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6090 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6091 6092 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6093 return true; 6094 6095 QualType ArgTypeA = ArgExprA.get()->getType(); 6096 QualType ArgTypeB = ArgExprB.get()->getType(); 6097 6098 auto isNull = [&] (Expr *E) -> bool { 6099 return E->isNullPointerConstant( 6100 Context, Expr::NPC_ValueDependentIsNotNull); }; 6101 6102 // argument should be either a pointer or null 6103 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6104 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6105 << "first" << ArgTypeA << ArgA->getSourceRange(); 6106 6107 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6108 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6109 << "second" << ArgTypeB << ArgB->getSourceRange(); 6110 6111 // Ensure Pointee types are compatible 6112 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6113 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6114 QualType pointeeA = ArgTypeA->getPointeeType(); 6115 QualType pointeeB = ArgTypeB->getPointeeType(); 6116 if (!Context.typesAreCompatible( 6117 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6118 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6119 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6120 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6121 << ArgB->getSourceRange(); 6122 } 6123 } 6124 6125 // at least one argument should be pointer type 6126 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6127 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6128 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6129 6130 if (isNull(ArgA)) // adopt type of the other pointer 6131 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6132 6133 if (isNull(ArgB)) 6134 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6135 6136 TheCall->setArg(0, ArgExprA.get()); 6137 TheCall->setArg(1, ArgExprB.get()); 6138 TheCall->setType(Context.LongLongTy); 6139 return false; 6140 } 6141 assert(false && "Unhandled ARM MTE intrinsic"); 6142 return true; 6143 } 6144 6145 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6146 /// TheCall is an ARM/AArch64 special register string literal. 6147 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6148 int ArgNum, unsigned ExpectedFieldNum, 6149 bool AllowName) { 6150 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6151 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6152 BuiltinID == ARM::BI__builtin_arm_rsr || 6153 BuiltinID == ARM::BI__builtin_arm_rsrp || 6154 BuiltinID == ARM::BI__builtin_arm_wsr || 6155 BuiltinID == ARM::BI__builtin_arm_wsrp; 6156 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6157 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6158 BuiltinID == AArch64::BI__builtin_arm_rsr || 6159 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6160 BuiltinID == AArch64::BI__builtin_arm_wsr || 6161 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6162 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6163 6164 // We can't check the value of a dependent argument. 6165 Expr *Arg = TheCall->getArg(ArgNum); 6166 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6167 return false; 6168 6169 // Check if the argument is a string literal. 6170 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6171 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6172 << Arg->getSourceRange(); 6173 6174 // Check the type of special register given. 6175 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6176 SmallVector<StringRef, 6> Fields; 6177 Reg.split(Fields, ":"); 6178 6179 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6180 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6181 << Arg->getSourceRange(); 6182 6183 // If the string is the name of a register then we cannot check that it is 6184 // valid here but if the string is of one the forms described in ACLE then we 6185 // can check that the supplied fields are integers and within the valid 6186 // ranges. 6187 if (Fields.size() > 1) { 6188 bool FiveFields = Fields.size() == 5; 6189 6190 bool ValidString = true; 6191 if (IsARMBuiltin) { 6192 ValidString &= Fields[0].startswith_lower("cp") || 6193 Fields[0].startswith_lower("p"); 6194 if (ValidString) 6195 Fields[0] = 6196 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6197 6198 ValidString &= Fields[2].startswith_lower("c"); 6199 if (ValidString) 6200 Fields[2] = Fields[2].drop_front(1); 6201 6202 if (FiveFields) { 6203 ValidString &= Fields[3].startswith_lower("c"); 6204 if (ValidString) 6205 Fields[3] = Fields[3].drop_front(1); 6206 } 6207 } 6208 6209 SmallVector<int, 5> Ranges; 6210 if (FiveFields) 6211 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6212 else 6213 Ranges.append({15, 7, 15}); 6214 6215 for (unsigned i=0; i<Fields.size(); ++i) { 6216 int IntField; 6217 ValidString &= !Fields[i].getAsInteger(10, IntField); 6218 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6219 } 6220 6221 if (!ValidString) 6222 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6223 << Arg->getSourceRange(); 6224 } else if (IsAArch64Builtin && Fields.size() == 1) { 6225 // If the register name is one of those that appear in the condition below 6226 // and the special register builtin being used is one of the write builtins, 6227 // then we require that the argument provided for writing to the register 6228 // is an integer constant expression. This is because it will be lowered to 6229 // an MSR (immediate) instruction, so we need to know the immediate at 6230 // compile time. 6231 if (TheCall->getNumArgs() != 2) 6232 return false; 6233 6234 std::string RegLower = Reg.lower(); 6235 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6236 RegLower != "pan" && RegLower != "uao") 6237 return false; 6238 6239 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6240 } 6241 6242 return false; 6243 } 6244 6245 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6246 /// This checks that the target supports __builtin_longjmp and 6247 /// that val is a constant 1. 6248 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6249 if (!Context.getTargetInfo().hasSjLjLowering()) 6250 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6251 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6252 6253 Expr *Arg = TheCall->getArg(1); 6254 llvm::APSInt Result; 6255 6256 // TODO: This is less than ideal. Overload this to take a value. 6257 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6258 return true; 6259 6260 if (Result != 1) 6261 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6262 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6263 6264 return false; 6265 } 6266 6267 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6268 /// This checks that the target supports __builtin_setjmp. 6269 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6270 if (!Context.getTargetInfo().hasSjLjLowering()) 6271 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6272 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6273 return false; 6274 } 6275 6276 namespace { 6277 6278 class UncoveredArgHandler { 6279 enum { Unknown = -1, AllCovered = -2 }; 6280 6281 signed FirstUncoveredArg = Unknown; 6282 SmallVector<const Expr *, 4> DiagnosticExprs; 6283 6284 public: 6285 UncoveredArgHandler() = default; 6286 6287 bool hasUncoveredArg() const { 6288 return (FirstUncoveredArg >= 0); 6289 } 6290 6291 unsigned getUncoveredArg() const { 6292 assert(hasUncoveredArg() && "no uncovered argument"); 6293 return FirstUncoveredArg; 6294 } 6295 6296 void setAllCovered() { 6297 // A string has been found with all arguments covered, so clear out 6298 // the diagnostics. 6299 DiagnosticExprs.clear(); 6300 FirstUncoveredArg = AllCovered; 6301 } 6302 6303 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6304 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6305 6306 // Don't update if a previous string covers all arguments. 6307 if (FirstUncoveredArg == AllCovered) 6308 return; 6309 6310 // UncoveredArgHandler tracks the highest uncovered argument index 6311 // and with it all the strings that match this index. 6312 if (NewFirstUncoveredArg == FirstUncoveredArg) 6313 DiagnosticExprs.push_back(StrExpr); 6314 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6315 DiagnosticExprs.clear(); 6316 DiagnosticExprs.push_back(StrExpr); 6317 FirstUncoveredArg = NewFirstUncoveredArg; 6318 } 6319 } 6320 6321 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6322 }; 6323 6324 enum StringLiteralCheckType { 6325 SLCT_NotALiteral, 6326 SLCT_UncheckedLiteral, 6327 SLCT_CheckedLiteral 6328 }; 6329 6330 } // namespace 6331 6332 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6333 BinaryOperatorKind BinOpKind, 6334 bool AddendIsRight) { 6335 unsigned BitWidth = Offset.getBitWidth(); 6336 unsigned AddendBitWidth = Addend.getBitWidth(); 6337 // There might be negative interim results. 6338 if (Addend.isUnsigned()) { 6339 Addend = Addend.zext(++AddendBitWidth); 6340 Addend.setIsSigned(true); 6341 } 6342 // Adjust the bit width of the APSInts. 6343 if (AddendBitWidth > BitWidth) { 6344 Offset = Offset.sext(AddendBitWidth); 6345 BitWidth = AddendBitWidth; 6346 } else if (BitWidth > AddendBitWidth) { 6347 Addend = Addend.sext(BitWidth); 6348 } 6349 6350 bool Ov = false; 6351 llvm::APSInt ResOffset = Offset; 6352 if (BinOpKind == BO_Add) 6353 ResOffset = Offset.sadd_ov(Addend, Ov); 6354 else { 6355 assert(AddendIsRight && BinOpKind == BO_Sub && 6356 "operator must be add or sub with addend on the right"); 6357 ResOffset = Offset.ssub_ov(Addend, Ov); 6358 } 6359 6360 // We add an offset to a pointer here so we should support an offset as big as 6361 // possible. 6362 if (Ov) { 6363 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6364 "index (intermediate) result too big"); 6365 Offset = Offset.sext(2 * BitWidth); 6366 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6367 return; 6368 } 6369 6370 Offset = ResOffset; 6371 } 6372 6373 namespace { 6374 6375 // This is a wrapper class around StringLiteral to support offsetted string 6376 // literals as format strings. It takes the offset into account when returning 6377 // the string and its length or the source locations to display notes correctly. 6378 class FormatStringLiteral { 6379 const StringLiteral *FExpr; 6380 int64_t Offset; 6381 6382 public: 6383 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6384 : FExpr(fexpr), Offset(Offset) {} 6385 6386 StringRef getString() const { 6387 return FExpr->getString().drop_front(Offset); 6388 } 6389 6390 unsigned getByteLength() const { 6391 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6392 } 6393 6394 unsigned getLength() const { return FExpr->getLength() - Offset; } 6395 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6396 6397 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6398 6399 QualType getType() const { return FExpr->getType(); } 6400 6401 bool isAscii() const { return FExpr->isAscii(); } 6402 bool isWide() const { return FExpr->isWide(); } 6403 bool isUTF8() const { return FExpr->isUTF8(); } 6404 bool isUTF16() const { return FExpr->isUTF16(); } 6405 bool isUTF32() const { return FExpr->isUTF32(); } 6406 bool isPascal() const { return FExpr->isPascal(); } 6407 6408 SourceLocation getLocationOfByte( 6409 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6410 const TargetInfo &Target, unsigned *StartToken = nullptr, 6411 unsigned *StartTokenByteOffset = nullptr) const { 6412 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6413 StartToken, StartTokenByteOffset); 6414 } 6415 6416 SourceLocation getBeginLoc() const LLVM_READONLY { 6417 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6418 } 6419 6420 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6421 }; 6422 6423 } // namespace 6424 6425 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6426 const Expr *OrigFormatExpr, 6427 ArrayRef<const Expr *> Args, 6428 bool HasVAListArg, unsigned format_idx, 6429 unsigned firstDataArg, 6430 Sema::FormatStringType Type, 6431 bool inFunctionCall, 6432 Sema::VariadicCallType CallType, 6433 llvm::SmallBitVector &CheckedVarArgs, 6434 UncoveredArgHandler &UncoveredArg, 6435 bool IgnoreStringsWithoutSpecifiers); 6436 6437 // Determine if an expression is a string literal or constant string. 6438 // If this function returns false on the arguments to a function expecting a 6439 // format string, we will usually need to emit a warning. 6440 // True string literals are then checked by CheckFormatString. 6441 static StringLiteralCheckType 6442 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6443 bool HasVAListArg, unsigned format_idx, 6444 unsigned firstDataArg, Sema::FormatStringType Type, 6445 Sema::VariadicCallType CallType, bool InFunctionCall, 6446 llvm::SmallBitVector &CheckedVarArgs, 6447 UncoveredArgHandler &UncoveredArg, 6448 llvm::APSInt Offset, 6449 bool IgnoreStringsWithoutSpecifiers = false) { 6450 if (S.isConstantEvaluated()) 6451 return SLCT_NotALiteral; 6452 tryAgain: 6453 assert(Offset.isSigned() && "invalid offset"); 6454 6455 if (E->isTypeDependent() || E->isValueDependent()) 6456 return SLCT_NotALiteral; 6457 6458 E = E->IgnoreParenCasts(); 6459 6460 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6461 // Technically -Wformat-nonliteral does not warn about this case. 6462 // The behavior of printf and friends in this case is implementation 6463 // dependent. Ideally if the format string cannot be null then 6464 // it should have a 'nonnull' attribute in the function prototype. 6465 return SLCT_UncheckedLiteral; 6466 6467 switch (E->getStmtClass()) { 6468 case Stmt::BinaryConditionalOperatorClass: 6469 case Stmt::ConditionalOperatorClass: { 6470 // The expression is a literal if both sub-expressions were, and it was 6471 // completely checked only if both sub-expressions were checked. 6472 const AbstractConditionalOperator *C = 6473 cast<AbstractConditionalOperator>(E); 6474 6475 // Determine whether it is necessary to check both sub-expressions, for 6476 // example, because the condition expression is a constant that can be 6477 // evaluated at compile time. 6478 bool CheckLeft = true, CheckRight = true; 6479 6480 bool Cond; 6481 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6482 S.isConstantEvaluated())) { 6483 if (Cond) 6484 CheckRight = false; 6485 else 6486 CheckLeft = false; 6487 } 6488 6489 // We need to maintain the offsets for the right and the left hand side 6490 // separately to check if every possible indexed expression is a valid 6491 // string literal. They might have different offsets for different string 6492 // literals in the end. 6493 StringLiteralCheckType Left; 6494 if (!CheckLeft) 6495 Left = SLCT_UncheckedLiteral; 6496 else { 6497 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6498 HasVAListArg, format_idx, firstDataArg, 6499 Type, CallType, InFunctionCall, 6500 CheckedVarArgs, UncoveredArg, Offset, 6501 IgnoreStringsWithoutSpecifiers); 6502 if (Left == SLCT_NotALiteral || !CheckRight) { 6503 return Left; 6504 } 6505 } 6506 6507 StringLiteralCheckType Right = checkFormatStringExpr( 6508 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6509 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6510 IgnoreStringsWithoutSpecifiers); 6511 6512 return (CheckLeft && Left < Right) ? Left : Right; 6513 } 6514 6515 case Stmt::ImplicitCastExprClass: 6516 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6517 goto tryAgain; 6518 6519 case Stmt::OpaqueValueExprClass: 6520 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6521 E = src; 6522 goto tryAgain; 6523 } 6524 return SLCT_NotALiteral; 6525 6526 case Stmt::PredefinedExprClass: 6527 // While __func__, etc., are technically not string literals, they 6528 // cannot contain format specifiers and thus are not a security 6529 // liability. 6530 return SLCT_UncheckedLiteral; 6531 6532 case Stmt::DeclRefExprClass: { 6533 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6534 6535 // As an exception, do not flag errors for variables binding to 6536 // const string literals. 6537 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6538 bool isConstant = false; 6539 QualType T = DR->getType(); 6540 6541 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6542 isConstant = AT->getElementType().isConstant(S.Context); 6543 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6544 isConstant = T.isConstant(S.Context) && 6545 PT->getPointeeType().isConstant(S.Context); 6546 } else if (T->isObjCObjectPointerType()) { 6547 // In ObjC, there is usually no "const ObjectPointer" type, 6548 // so don't check if the pointee type is constant. 6549 isConstant = T.isConstant(S.Context); 6550 } 6551 6552 if (isConstant) { 6553 if (const Expr *Init = VD->getAnyInitializer()) { 6554 // Look through initializers like const char c[] = { "foo" } 6555 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6556 if (InitList->isStringLiteralInit()) 6557 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6558 } 6559 return checkFormatStringExpr(S, Init, Args, 6560 HasVAListArg, format_idx, 6561 firstDataArg, Type, CallType, 6562 /*InFunctionCall*/ false, CheckedVarArgs, 6563 UncoveredArg, Offset); 6564 } 6565 } 6566 6567 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6568 // special check to see if the format string is a function parameter 6569 // of the function calling the printf function. If the function 6570 // has an attribute indicating it is a printf-like function, then we 6571 // should suppress warnings concerning non-literals being used in a call 6572 // to a vprintf function. For example: 6573 // 6574 // void 6575 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6576 // va_list ap; 6577 // va_start(ap, fmt); 6578 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6579 // ... 6580 // } 6581 if (HasVAListArg) { 6582 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6583 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6584 int PVIndex = PV->getFunctionScopeIndex() + 1; 6585 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6586 // adjust for implicit parameter 6587 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6588 if (MD->isInstance()) 6589 ++PVIndex; 6590 // We also check if the formats are compatible. 6591 // We can't pass a 'scanf' string to a 'printf' function. 6592 if (PVIndex == PVFormat->getFormatIdx() && 6593 Type == S.GetFormatStringType(PVFormat)) 6594 return SLCT_UncheckedLiteral; 6595 } 6596 } 6597 } 6598 } 6599 } 6600 6601 return SLCT_NotALiteral; 6602 } 6603 6604 case Stmt::CallExprClass: 6605 case Stmt::CXXMemberCallExprClass: { 6606 const CallExpr *CE = cast<CallExpr>(E); 6607 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6608 bool IsFirst = true; 6609 StringLiteralCheckType CommonResult; 6610 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6611 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6612 StringLiteralCheckType Result = checkFormatStringExpr( 6613 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6614 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6615 IgnoreStringsWithoutSpecifiers); 6616 if (IsFirst) { 6617 CommonResult = Result; 6618 IsFirst = false; 6619 } 6620 } 6621 if (!IsFirst) 6622 return CommonResult; 6623 6624 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6625 unsigned BuiltinID = FD->getBuiltinID(); 6626 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6627 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6628 const Expr *Arg = CE->getArg(0); 6629 return checkFormatStringExpr(S, Arg, Args, 6630 HasVAListArg, format_idx, 6631 firstDataArg, Type, CallType, 6632 InFunctionCall, CheckedVarArgs, 6633 UncoveredArg, Offset, 6634 IgnoreStringsWithoutSpecifiers); 6635 } 6636 } 6637 } 6638 6639 return SLCT_NotALiteral; 6640 } 6641 case Stmt::ObjCMessageExprClass: { 6642 const auto *ME = cast<ObjCMessageExpr>(E); 6643 if (const auto *MD = ME->getMethodDecl()) { 6644 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 6645 // As a special case heuristic, if we're using the method -[NSBundle 6646 // localizedStringForKey:value:table:], ignore any key strings that lack 6647 // format specifiers. The idea is that if the key doesn't have any 6648 // format specifiers then its probably just a key to map to the 6649 // localized strings. If it does have format specifiers though, then its 6650 // likely that the text of the key is the format string in the 6651 // programmer's language, and should be checked. 6652 const ObjCInterfaceDecl *IFace; 6653 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 6654 IFace->getIdentifier()->isStr("NSBundle") && 6655 MD->getSelector().isKeywordSelector( 6656 {"localizedStringForKey", "value", "table"})) { 6657 IgnoreStringsWithoutSpecifiers = true; 6658 } 6659 6660 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6661 return checkFormatStringExpr( 6662 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6663 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6664 IgnoreStringsWithoutSpecifiers); 6665 } 6666 } 6667 6668 return SLCT_NotALiteral; 6669 } 6670 case Stmt::ObjCStringLiteralClass: 6671 case Stmt::StringLiteralClass: { 6672 const StringLiteral *StrE = nullptr; 6673 6674 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6675 StrE = ObjCFExpr->getString(); 6676 else 6677 StrE = cast<StringLiteral>(E); 6678 6679 if (StrE) { 6680 if (Offset.isNegative() || Offset > StrE->getLength()) { 6681 // TODO: It would be better to have an explicit warning for out of 6682 // bounds literals. 6683 return SLCT_NotALiteral; 6684 } 6685 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6686 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6687 firstDataArg, Type, InFunctionCall, CallType, 6688 CheckedVarArgs, UncoveredArg, 6689 IgnoreStringsWithoutSpecifiers); 6690 return SLCT_CheckedLiteral; 6691 } 6692 6693 return SLCT_NotALiteral; 6694 } 6695 case Stmt::BinaryOperatorClass: { 6696 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6697 6698 // A string literal + an int offset is still a string literal. 6699 if (BinOp->isAdditiveOp()) { 6700 Expr::EvalResult LResult, RResult; 6701 6702 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 6703 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6704 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 6705 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6706 6707 if (LIsInt != RIsInt) { 6708 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6709 6710 if (LIsInt) { 6711 if (BinOpKind == BO_Add) { 6712 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6713 E = BinOp->getRHS(); 6714 goto tryAgain; 6715 } 6716 } else { 6717 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6718 E = BinOp->getLHS(); 6719 goto tryAgain; 6720 } 6721 } 6722 } 6723 6724 return SLCT_NotALiteral; 6725 } 6726 case Stmt::UnaryOperatorClass: { 6727 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6728 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6729 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6730 Expr::EvalResult IndexResult; 6731 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 6732 Expr::SE_NoSideEffects, 6733 S.isConstantEvaluated())) { 6734 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6735 /*RHS is int*/ true); 6736 E = ASE->getBase(); 6737 goto tryAgain; 6738 } 6739 } 6740 6741 return SLCT_NotALiteral; 6742 } 6743 6744 default: 6745 return SLCT_NotALiteral; 6746 } 6747 } 6748 6749 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6750 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6751 .Case("scanf", FST_Scanf) 6752 .Cases("printf", "printf0", FST_Printf) 6753 .Cases("NSString", "CFString", FST_NSString) 6754 .Case("strftime", FST_Strftime) 6755 .Case("strfmon", FST_Strfmon) 6756 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6757 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6758 .Case("os_trace", FST_OSLog) 6759 .Case("os_log", FST_OSLog) 6760 .Default(FST_Unknown); 6761 } 6762 6763 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6764 /// functions) for correct use of format strings. 6765 /// Returns true if a format string has been fully checked. 6766 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6767 ArrayRef<const Expr *> Args, 6768 bool IsCXXMember, 6769 VariadicCallType CallType, 6770 SourceLocation Loc, SourceRange Range, 6771 llvm::SmallBitVector &CheckedVarArgs) { 6772 FormatStringInfo FSI; 6773 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6774 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6775 FSI.FirstDataArg, GetFormatStringType(Format), 6776 CallType, Loc, Range, CheckedVarArgs); 6777 return false; 6778 } 6779 6780 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6781 bool HasVAListArg, unsigned format_idx, 6782 unsigned firstDataArg, FormatStringType Type, 6783 VariadicCallType CallType, 6784 SourceLocation Loc, SourceRange Range, 6785 llvm::SmallBitVector &CheckedVarArgs) { 6786 // CHECK: printf/scanf-like function is called with no format string. 6787 if (format_idx >= Args.size()) { 6788 Diag(Loc, diag::warn_missing_format_string) << Range; 6789 return false; 6790 } 6791 6792 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6793 6794 // CHECK: format string is not a string literal. 6795 // 6796 // Dynamically generated format strings are difficult to 6797 // automatically vet at compile time. Requiring that format strings 6798 // are string literals: (1) permits the checking of format strings by 6799 // the compiler and thereby (2) can practically remove the source of 6800 // many format string exploits. 6801 6802 // Format string can be either ObjC string (e.g. @"%d") or 6803 // C string (e.g. "%d") 6804 // ObjC string uses the same format specifiers as C string, so we can use 6805 // the same format string checking logic for both ObjC and C strings. 6806 UncoveredArgHandler UncoveredArg; 6807 StringLiteralCheckType CT = 6808 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6809 format_idx, firstDataArg, Type, CallType, 6810 /*IsFunctionCall*/ true, CheckedVarArgs, 6811 UncoveredArg, 6812 /*no string offset*/ llvm::APSInt(64, false) = 0); 6813 6814 // Generate a diagnostic where an uncovered argument is detected. 6815 if (UncoveredArg.hasUncoveredArg()) { 6816 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6817 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6818 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6819 } 6820 6821 if (CT != SLCT_NotALiteral) 6822 // Literal format string found, check done! 6823 return CT == SLCT_CheckedLiteral; 6824 6825 // Strftime is particular as it always uses a single 'time' argument, 6826 // so it is safe to pass a non-literal string. 6827 if (Type == FST_Strftime) 6828 return false; 6829 6830 // Do not emit diag when the string param is a macro expansion and the 6831 // format is either NSString or CFString. This is a hack to prevent 6832 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6833 // which are usually used in place of NS and CF string literals. 6834 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6835 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6836 return false; 6837 6838 // If there are no arguments specified, warn with -Wformat-security, otherwise 6839 // warn only with -Wformat-nonliteral. 6840 if (Args.size() == firstDataArg) { 6841 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6842 << OrigFormatExpr->getSourceRange(); 6843 switch (Type) { 6844 default: 6845 break; 6846 case FST_Kprintf: 6847 case FST_FreeBSDKPrintf: 6848 case FST_Printf: 6849 Diag(FormatLoc, diag::note_format_security_fixit) 6850 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6851 break; 6852 case FST_NSString: 6853 Diag(FormatLoc, diag::note_format_security_fixit) 6854 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6855 break; 6856 } 6857 } else { 6858 Diag(FormatLoc, diag::warn_format_nonliteral) 6859 << OrigFormatExpr->getSourceRange(); 6860 } 6861 return false; 6862 } 6863 6864 namespace { 6865 6866 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6867 protected: 6868 Sema &S; 6869 const FormatStringLiteral *FExpr; 6870 const Expr *OrigFormatExpr; 6871 const Sema::FormatStringType FSType; 6872 const unsigned FirstDataArg; 6873 const unsigned NumDataArgs; 6874 const char *Beg; // Start of format string. 6875 const bool HasVAListArg; 6876 ArrayRef<const Expr *> Args; 6877 unsigned FormatIdx; 6878 llvm::SmallBitVector CoveredArgs; 6879 bool usesPositionalArgs = false; 6880 bool atFirstArg = true; 6881 bool inFunctionCall; 6882 Sema::VariadicCallType CallType; 6883 llvm::SmallBitVector &CheckedVarArgs; 6884 UncoveredArgHandler &UncoveredArg; 6885 6886 public: 6887 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6888 const Expr *origFormatExpr, 6889 const Sema::FormatStringType type, unsigned firstDataArg, 6890 unsigned numDataArgs, const char *beg, bool hasVAListArg, 6891 ArrayRef<const Expr *> Args, unsigned formatIdx, 6892 bool inFunctionCall, Sema::VariadicCallType callType, 6893 llvm::SmallBitVector &CheckedVarArgs, 6894 UncoveredArgHandler &UncoveredArg) 6895 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 6896 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 6897 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 6898 inFunctionCall(inFunctionCall), CallType(callType), 6899 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 6900 CoveredArgs.resize(numDataArgs); 6901 CoveredArgs.reset(); 6902 } 6903 6904 void DoneProcessing(); 6905 6906 void HandleIncompleteSpecifier(const char *startSpecifier, 6907 unsigned specifierLen) override; 6908 6909 void HandleInvalidLengthModifier( 6910 const analyze_format_string::FormatSpecifier &FS, 6911 const analyze_format_string::ConversionSpecifier &CS, 6912 const char *startSpecifier, unsigned specifierLen, 6913 unsigned DiagID); 6914 6915 void HandleNonStandardLengthModifier( 6916 const analyze_format_string::FormatSpecifier &FS, 6917 const char *startSpecifier, unsigned specifierLen); 6918 6919 void HandleNonStandardConversionSpecifier( 6920 const analyze_format_string::ConversionSpecifier &CS, 6921 const char *startSpecifier, unsigned specifierLen); 6922 6923 void HandlePosition(const char *startPos, unsigned posLen) override; 6924 6925 void HandleInvalidPosition(const char *startSpecifier, 6926 unsigned specifierLen, 6927 analyze_format_string::PositionContext p) override; 6928 6929 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 6930 6931 void HandleNullChar(const char *nullCharacter) override; 6932 6933 template <typename Range> 6934 static void 6935 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 6936 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 6937 bool IsStringLocation, Range StringRange, 6938 ArrayRef<FixItHint> Fixit = None); 6939 6940 protected: 6941 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 6942 const char *startSpec, 6943 unsigned specifierLen, 6944 const char *csStart, unsigned csLen); 6945 6946 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 6947 const char *startSpec, 6948 unsigned specifierLen); 6949 6950 SourceRange getFormatStringRange(); 6951 CharSourceRange getSpecifierRange(const char *startSpecifier, 6952 unsigned specifierLen); 6953 SourceLocation getLocationOfByte(const char *x); 6954 6955 const Expr *getDataArg(unsigned i) const; 6956 6957 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 6958 const analyze_format_string::ConversionSpecifier &CS, 6959 const char *startSpecifier, unsigned specifierLen, 6960 unsigned argIndex); 6961 6962 template <typename Range> 6963 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 6964 bool IsStringLocation, Range StringRange, 6965 ArrayRef<FixItHint> Fixit = None); 6966 }; 6967 6968 } // namespace 6969 6970 SourceRange CheckFormatHandler::getFormatStringRange() { 6971 return OrigFormatExpr->getSourceRange(); 6972 } 6973 6974 CharSourceRange CheckFormatHandler:: 6975 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 6976 SourceLocation Start = getLocationOfByte(startSpecifier); 6977 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 6978 6979 // Advance the end SourceLocation by one due to half-open ranges. 6980 End = End.getLocWithOffset(1); 6981 6982 return CharSourceRange::getCharRange(Start, End); 6983 } 6984 6985 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 6986 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 6987 S.getLangOpts(), S.Context.getTargetInfo()); 6988 } 6989 6990 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 6991 unsigned specifierLen){ 6992 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 6993 getLocationOfByte(startSpecifier), 6994 /*IsStringLocation*/true, 6995 getSpecifierRange(startSpecifier, specifierLen)); 6996 } 6997 6998 void CheckFormatHandler::HandleInvalidLengthModifier( 6999 const analyze_format_string::FormatSpecifier &FS, 7000 const analyze_format_string::ConversionSpecifier &CS, 7001 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7002 using namespace analyze_format_string; 7003 7004 const LengthModifier &LM = FS.getLengthModifier(); 7005 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7006 7007 // See if we know how to fix this length modifier. 7008 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7009 if (FixedLM) { 7010 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7011 getLocationOfByte(LM.getStart()), 7012 /*IsStringLocation*/true, 7013 getSpecifierRange(startSpecifier, specifierLen)); 7014 7015 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7016 << FixedLM->toString() 7017 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7018 7019 } else { 7020 FixItHint Hint; 7021 if (DiagID == diag::warn_format_nonsensical_length) 7022 Hint = FixItHint::CreateRemoval(LMRange); 7023 7024 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7025 getLocationOfByte(LM.getStart()), 7026 /*IsStringLocation*/true, 7027 getSpecifierRange(startSpecifier, specifierLen), 7028 Hint); 7029 } 7030 } 7031 7032 void CheckFormatHandler::HandleNonStandardLengthModifier( 7033 const analyze_format_string::FormatSpecifier &FS, 7034 const char *startSpecifier, unsigned specifierLen) { 7035 using namespace analyze_format_string; 7036 7037 const LengthModifier &LM = FS.getLengthModifier(); 7038 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7039 7040 // See if we know how to fix this length modifier. 7041 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7042 if (FixedLM) { 7043 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7044 << LM.toString() << 0, 7045 getLocationOfByte(LM.getStart()), 7046 /*IsStringLocation*/true, 7047 getSpecifierRange(startSpecifier, specifierLen)); 7048 7049 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7050 << FixedLM->toString() 7051 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7052 7053 } else { 7054 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7055 << LM.toString() << 0, 7056 getLocationOfByte(LM.getStart()), 7057 /*IsStringLocation*/true, 7058 getSpecifierRange(startSpecifier, specifierLen)); 7059 } 7060 } 7061 7062 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7063 const analyze_format_string::ConversionSpecifier &CS, 7064 const char *startSpecifier, unsigned specifierLen) { 7065 using namespace analyze_format_string; 7066 7067 // See if we know how to fix this conversion specifier. 7068 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7069 if (FixedCS) { 7070 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7071 << CS.toString() << /*conversion specifier*/1, 7072 getLocationOfByte(CS.getStart()), 7073 /*IsStringLocation*/true, 7074 getSpecifierRange(startSpecifier, specifierLen)); 7075 7076 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7077 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7078 << FixedCS->toString() 7079 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7080 } else { 7081 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7082 << CS.toString() << /*conversion specifier*/1, 7083 getLocationOfByte(CS.getStart()), 7084 /*IsStringLocation*/true, 7085 getSpecifierRange(startSpecifier, specifierLen)); 7086 } 7087 } 7088 7089 void CheckFormatHandler::HandlePosition(const char *startPos, 7090 unsigned posLen) { 7091 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7092 getLocationOfByte(startPos), 7093 /*IsStringLocation*/true, 7094 getSpecifierRange(startPos, posLen)); 7095 } 7096 7097 void 7098 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7099 analyze_format_string::PositionContext p) { 7100 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7101 << (unsigned) p, 7102 getLocationOfByte(startPos), /*IsStringLocation*/true, 7103 getSpecifierRange(startPos, posLen)); 7104 } 7105 7106 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7107 unsigned posLen) { 7108 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7109 getLocationOfByte(startPos), 7110 /*IsStringLocation*/true, 7111 getSpecifierRange(startPos, posLen)); 7112 } 7113 7114 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7115 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7116 // The presence of a null character is likely an error. 7117 EmitFormatDiagnostic( 7118 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7119 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7120 getFormatStringRange()); 7121 } 7122 } 7123 7124 // Note that this may return NULL if there was an error parsing or building 7125 // one of the argument expressions. 7126 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7127 return Args[FirstDataArg + i]; 7128 } 7129 7130 void CheckFormatHandler::DoneProcessing() { 7131 // Does the number of data arguments exceed the number of 7132 // format conversions in the format string? 7133 if (!HasVAListArg) { 7134 // Find any arguments that weren't covered. 7135 CoveredArgs.flip(); 7136 signed notCoveredArg = CoveredArgs.find_first(); 7137 if (notCoveredArg >= 0) { 7138 assert((unsigned)notCoveredArg < NumDataArgs); 7139 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7140 } else { 7141 UncoveredArg.setAllCovered(); 7142 } 7143 } 7144 } 7145 7146 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7147 const Expr *ArgExpr) { 7148 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7149 "Invalid state"); 7150 7151 if (!ArgExpr) 7152 return; 7153 7154 SourceLocation Loc = ArgExpr->getBeginLoc(); 7155 7156 if (S.getSourceManager().isInSystemMacro(Loc)) 7157 return; 7158 7159 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7160 for (auto E : DiagnosticExprs) 7161 PDiag << E->getSourceRange(); 7162 7163 CheckFormatHandler::EmitFormatDiagnostic( 7164 S, IsFunctionCall, DiagnosticExprs[0], 7165 PDiag, Loc, /*IsStringLocation*/false, 7166 DiagnosticExprs[0]->getSourceRange()); 7167 } 7168 7169 bool 7170 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7171 SourceLocation Loc, 7172 const char *startSpec, 7173 unsigned specifierLen, 7174 const char *csStart, 7175 unsigned csLen) { 7176 bool keepGoing = true; 7177 if (argIndex < NumDataArgs) { 7178 // Consider the argument coverered, even though the specifier doesn't 7179 // make sense. 7180 CoveredArgs.set(argIndex); 7181 } 7182 else { 7183 // If argIndex exceeds the number of data arguments we 7184 // don't issue a warning because that is just a cascade of warnings (and 7185 // they may have intended '%%' anyway). We don't want to continue processing 7186 // the format string after this point, however, as we will like just get 7187 // gibberish when trying to match arguments. 7188 keepGoing = false; 7189 } 7190 7191 StringRef Specifier(csStart, csLen); 7192 7193 // If the specifier in non-printable, it could be the first byte of a UTF-8 7194 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7195 // hex value. 7196 std::string CodePointStr; 7197 if (!llvm::sys::locale::isPrint(*csStart)) { 7198 llvm::UTF32 CodePoint; 7199 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7200 const llvm::UTF8 *E = 7201 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7202 llvm::ConversionResult Result = 7203 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7204 7205 if (Result != llvm::conversionOK) { 7206 unsigned char FirstChar = *csStart; 7207 CodePoint = (llvm::UTF32)FirstChar; 7208 } 7209 7210 llvm::raw_string_ostream OS(CodePointStr); 7211 if (CodePoint < 256) 7212 OS << "\\x" << llvm::format("%02x", CodePoint); 7213 else if (CodePoint <= 0xFFFF) 7214 OS << "\\u" << llvm::format("%04x", CodePoint); 7215 else 7216 OS << "\\U" << llvm::format("%08x", CodePoint); 7217 OS.flush(); 7218 Specifier = CodePointStr; 7219 } 7220 7221 EmitFormatDiagnostic( 7222 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7223 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7224 7225 return keepGoing; 7226 } 7227 7228 void 7229 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7230 const char *startSpec, 7231 unsigned specifierLen) { 7232 EmitFormatDiagnostic( 7233 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7234 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7235 } 7236 7237 bool 7238 CheckFormatHandler::CheckNumArgs( 7239 const analyze_format_string::FormatSpecifier &FS, 7240 const analyze_format_string::ConversionSpecifier &CS, 7241 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7242 7243 if (argIndex >= NumDataArgs) { 7244 PartialDiagnostic PDiag = FS.usesPositionalArg() 7245 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7246 << (argIndex+1) << NumDataArgs) 7247 : S.PDiag(diag::warn_printf_insufficient_data_args); 7248 EmitFormatDiagnostic( 7249 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7250 getSpecifierRange(startSpecifier, specifierLen)); 7251 7252 // Since more arguments than conversion tokens are given, by extension 7253 // all arguments are covered, so mark this as so. 7254 UncoveredArg.setAllCovered(); 7255 return false; 7256 } 7257 return true; 7258 } 7259 7260 template<typename Range> 7261 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7262 SourceLocation Loc, 7263 bool IsStringLocation, 7264 Range StringRange, 7265 ArrayRef<FixItHint> FixIt) { 7266 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7267 Loc, IsStringLocation, StringRange, FixIt); 7268 } 7269 7270 /// If the format string is not within the function call, emit a note 7271 /// so that the function call and string are in diagnostic messages. 7272 /// 7273 /// \param InFunctionCall if true, the format string is within the function 7274 /// call and only one diagnostic message will be produced. Otherwise, an 7275 /// extra note will be emitted pointing to location of the format string. 7276 /// 7277 /// \param ArgumentExpr the expression that is passed as the format string 7278 /// argument in the function call. Used for getting locations when two 7279 /// diagnostics are emitted. 7280 /// 7281 /// \param PDiag the callee should already have provided any strings for the 7282 /// diagnostic message. This function only adds locations and fixits 7283 /// to diagnostics. 7284 /// 7285 /// \param Loc primary location for diagnostic. If two diagnostics are 7286 /// required, one will be at Loc and a new SourceLocation will be created for 7287 /// the other one. 7288 /// 7289 /// \param IsStringLocation if true, Loc points to the format string should be 7290 /// used for the note. Otherwise, Loc points to the argument list and will 7291 /// be used with PDiag. 7292 /// 7293 /// \param StringRange some or all of the string to highlight. This is 7294 /// templated so it can accept either a CharSourceRange or a SourceRange. 7295 /// 7296 /// \param FixIt optional fix it hint for the format string. 7297 template <typename Range> 7298 void CheckFormatHandler::EmitFormatDiagnostic( 7299 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7300 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7301 Range StringRange, ArrayRef<FixItHint> FixIt) { 7302 if (InFunctionCall) { 7303 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7304 D << StringRange; 7305 D << FixIt; 7306 } else { 7307 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7308 << ArgumentExpr->getSourceRange(); 7309 7310 const Sema::SemaDiagnosticBuilder &Note = 7311 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7312 diag::note_format_string_defined); 7313 7314 Note << StringRange; 7315 Note << FixIt; 7316 } 7317 } 7318 7319 //===--- CHECK: Printf format string checking ------------------------------===// 7320 7321 namespace { 7322 7323 class CheckPrintfHandler : public CheckFormatHandler { 7324 public: 7325 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7326 const Expr *origFormatExpr, 7327 const Sema::FormatStringType type, unsigned firstDataArg, 7328 unsigned numDataArgs, bool isObjC, const char *beg, 7329 bool hasVAListArg, ArrayRef<const Expr *> Args, 7330 unsigned formatIdx, bool inFunctionCall, 7331 Sema::VariadicCallType CallType, 7332 llvm::SmallBitVector &CheckedVarArgs, 7333 UncoveredArgHandler &UncoveredArg) 7334 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7335 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7336 inFunctionCall, CallType, CheckedVarArgs, 7337 UncoveredArg) {} 7338 7339 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7340 7341 /// Returns true if '%@' specifiers are allowed in the format string. 7342 bool allowsObjCArg() const { 7343 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7344 FSType == Sema::FST_OSTrace; 7345 } 7346 7347 bool HandleInvalidPrintfConversionSpecifier( 7348 const analyze_printf::PrintfSpecifier &FS, 7349 const char *startSpecifier, 7350 unsigned specifierLen) override; 7351 7352 void handleInvalidMaskType(StringRef MaskType) override; 7353 7354 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7355 const char *startSpecifier, 7356 unsigned specifierLen) override; 7357 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7358 const char *StartSpecifier, 7359 unsigned SpecifierLen, 7360 const Expr *E); 7361 7362 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7363 const char *startSpecifier, unsigned specifierLen); 7364 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7365 const analyze_printf::OptionalAmount &Amt, 7366 unsigned type, 7367 const char *startSpecifier, unsigned specifierLen); 7368 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7369 const analyze_printf::OptionalFlag &flag, 7370 const char *startSpecifier, unsigned specifierLen); 7371 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7372 const analyze_printf::OptionalFlag &ignoredFlag, 7373 const analyze_printf::OptionalFlag &flag, 7374 const char *startSpecifier, unsigned specifierLen); 7375 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7376 const Expr *E); 7377 7378 void HandleEmptyObjCModifierFlag(const char *startFlag, 7379 unsigned flagLen) override; 7380 7381 void HandleInvalidObjCModifierFlag(const char *startFlag, 7382 unsigned flagLen) override; 7383 7384 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7385 const char *flagsEnd, 7386 const char *conversionPosition) 7387 override; 7388 }; 7389 7390 } // namespace 7391 7392 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7393 const analyze_printf::PrintfSpecifier &FS, 7394 const char *startSpecifier, 7395 unsigned specifierLen) { 7396 const analyze_printf::PrintfConversionSpecifier &CS = 7397 FS.getConversionSpecifier(); 7398 7399 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7400 getLocationOfByte(CS.getStart()), 7401 startSpecifier, specifierLen, 7402 CS.getStart(), CS.getLength()); 7403 } 7404 7405 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7406 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7407 } 7408 7409 bool CheckPrintfHandler::HandleAmount( 7410 const analyze_format_string::OptionalAmount &Amt, 7411 unsigned k, const char *startSpecifier, 7412 unsigned specifierLen) { 7413 if (Amt.hasDataArgument()) { 7414 if (!HasVAListArg) { 7415 unsigned argIndex = Amt.getArgIndex(); 7416 if (argIndex >= NumDataArgs) { 7417 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7418 << k, 7419 getLocationOfByte(Amt.getStart()), 7420 /*IsStringLocation*/true, 7421 getSpecifierRange(startSpecifier, specifierLen)); 7422 // Don't do any more checking. We will just emit 7423 // spurious errors. 7424 return false; 7425 } 7426 7427 // Type check the data argument. It should be an 'int'. 7428 // Although not in conformance with C99, we also allow the argument to be 7429 // an 'unsigned int' as that is a reasonably safe case. GCC also 7430 // doesn't emit a warning for that case. 7431 CoveredArgs.set(argIndex); 7432 const Expr *Arg = getDataArg(argIndex); 7433 if (!Arg) 7434 return false; 7435 7436 QualType T = Arg->getType(); 7437 7438 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7439 assert(AT.isValid()); 7440 7441 if (!AT.matchesType(S.Context, T)) { 7442 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7443 << k << AT.getRepresentativeTypeName(S.Context) 7444 << T << Arg->getSourceRange(), 7445 getLocationOfByte(Amt.getStart()), 7446 /*IsStringLocation*/true, 7447 getSpecifierRange(startSpecifier, specifierLen)); 7448 // Don't do any more checking. We will just emit 7449 // spurious errors. 7450 return false; 7451 } 7452 } 7453 } 7454 return true; 7455 } 7456 7457 void CheckPrintfHandler::HandleInvalidAmount( 7458 const analyze_printf::PrintfSpecifier &FS, 7459 const analyze_printf::OptionalAmount &Amt, 7460 unsigned type, 7461 const char *startSpecifier, 7462 unsigned specifierLen) { 7463 const analyze_printf::PrintfConversionSpecifier &CS = 7464 FS.getConversionSpecifier(); 7465 7466 FixItHint fixit = 7467 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7468 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7469 Amt.getConstantLength())) 7470 : FixItHint(); 7471 7472 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7473 << type << CS.toString(), 7474 getLocationOfByte(Amt.getStart()), 7475 /*IsStringLocation*/true, 7476 getSpecifierRange(startSpecifier, specifierLen), 7477 fixit); 7478 } 7479 7480 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7481 const analyze_printf::OptionalFlag &flag, 7482 const char *startSpecifier, 7483 unsigned specifierLen) { 7484 // Warn about pointless flag with a fixit removal. 7485 const analyze_printf::PrintfConversionSpecifier &CS = 7486 FS.getConversionSpecifier(); 7487 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7488 << flag.toString() << CS.toString(), 7489 getLocationOfByte(flag.getPosition()), 7490 /*IsStringLocation*/true, 7491 getSpecifierRange(startSpecifier, specifierLen), 7492 FixItHint::CreateRemoval( 7493 getSpecifierRange(flag.getPosition(), 1))); 7494 } 7495 7496 void CheckPrintfHandler::HandleIgnoredFlag( 7497 const analyze_printf::PrintfSpecifier &FS, 7498 const analyze_printf::OptionalFlag &ignoredFlag, 7499 const analyze_printf::OptionalFlag &flag, 7500 const char *startSpecifier, 7501 unsigned specifierLen) { 7502 // Warn about ignored flag with a fixit removal. 7503 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7504 << ignoredFlag.toString() << flag.toString(), 7505 getLocationOfByte(ignoredFlag.getPosition()), 7506 /*IsStringLocation*/true, 7507 getSpecifierRange(startSpecifier, specifierLen), 7508 FixItHint::CreateRemoval( 7509 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7510 } 7511 7512 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7513 unsigned flagLen) { 7514 // Warn about an empty flag. 7515 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7516 getLocationOfByte(startFlag), 7517 /*IsStringLocation*/true, 7518 getSpecifierRange(startFlag, flagLen)); 7519 } 7520 7521 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7522 unsigned flagLen) { 7523 // Warn about an invalid flag. 7524 auto Range = getSpecifierRange(startFlag, flagLen); 7525 StringRef flag(startFlag, flagLen); 7526 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7527 getLocationOfByte(startFlag), 7528 /*IsStringLocation*/true, 7529 Range, FixItHint::CreateRemoval(Range)); 7530 } 7531 7532 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7533 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7534 // Warn about using '[...]' without a '@' conversion. 7535 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7536 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7537 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7538 getLocationOfByte(conversionPosition), 7539 /*IsStringLocation*/true, 7540 Range, FixItHint::CreateRemoval(Range)); 7541 } 7542 7543 // Determines if the specified is a C++ class or struct containing 7544 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7545 // "c_str()"). 7546 template<typename MemberKind> 7547 static llvm::SmallPtrSet<MemberKind*, 1> 7548 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7549 const RecordType *RT = Ty->getAs<RecordType>(); 7550 llvm::SmallPtrSet<MemberKind*, 1> Results; 7551 7552 if (!RT) 7553 return Results; 7554 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7555 if (!RD || !RD->getDefinition()) 7556 return Results; 7557 7558 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7559 Sema::LookupMemberName); 7560 R.suppressDiagnostics(); 7561 7562 // We just need to include all members of the right kind turned up by the 7563 // filter, at this point. 7564 if (S.LookupQualifiedName(R, RT->getDecl())) 7565 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7566 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7567 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7568 Results.insert(FK); 7569 } 7570 return Results; 7571 } 7572 7573 /// Check if we could call '.c_str()' on an object. 7574 /// 7575 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7576 /// allow the call, or if it would be ambiguous). 7577 bool Sema::hasCStrMethod(const Expr *E) { 7578 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7579 7580 MethodSet Results = 7581 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7582 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7583 MI != ME; ++MI) 7584 if ((*MI)->getMinRequiredArguments() == 0) 7585 return true; 7586 return false; 7587 } 7588 7589 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7590 // better diagnostic if so. AT is assumed to be valid. 7591 // Returns true when a c_str() conversion method is found. 7592 bool CheckPrintfHandler::checkForCStrMembers( 7593 const analyze_printf::ArgType &AT, const Expr *E) { 7594 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7595 7596 MethodSet Results = 7597 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7598 7599 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7600 MI != ME; ++MI) { 7601 const CXXMethodDecl *Method = *MI; 7602 if (Method->getMinRequiredArguments() == 0 && 7603 AT.matchesType(S.Context, Method->getReturnType())) { 7604 // FIXME: Suggest parens if the expression needs them. 7605 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7606 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7607 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7608 return true; 7609 } 7610 } 7611 7612 return false; 7613 } 7614 7615 bool 7616 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7617 &FS, 7618 const char *startSpecifier, 7619 unsigned specifierLen) { 7620 using namespace analyze_format_string; 7621 using namespace analyze_printf; 7622 7623 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7624 7625 if (FS.consumesDataArgument()) { 7626 if (atFirstArg) { 7627 atFirstArg = false; 7628 usesPositionalArgs = FS.usesPositionalArg(); 7629 } 7630 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7631 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7632 startSpecifier, specifierLen); 7633 return false; 7634 } 7635 } 7636 7637 // First check if the field width, precision, and conversion specifier 7638 // have matching data arguments. 7639 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7640 startSpecifier, specifierLen)) { 7641 return false; 7642 } 7643 7644 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7645 startSpecifier, specifierLen)) { 7646 return false; 7647 } 7648 7649 if (!CS.consumesDataArgument()) { 7650 // FIXME: Technically specifying a precision or field width here 7651 // makes no sense. Worth issuing a warning at some point. 7652 return true; 7653 } 7654 7655 // Consume the argument. 7656 unsigned argIndex = FS.getArgIndex(); 7657 if (argIndex < NumDataArgs) { 7658 // The check to see if the argIndex is valid will come later. 7659 // We set the bit here because we may exit early from this 7660 // function if we encounter some other error. 7661 CoveredArgs.set(argIndex); 7662 } 7663 7664 // FreeBSD kernel extensions. 7665 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7666 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7667 // We need at least two arguments. 7668 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7669 return false; 7670 7671 // Claim the second argument. 7672 CoveredArgs.set(argIndex + 1); 7673 7674 // Type check the first argument (int for %b, pointer for %D) 7675 const Expr *Ex = getDataArg(argIndex); 7676 const analyze_printf::ArgType &AT = 7677 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7678 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7679 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7680 EmitFormatDiagnostic( 7681 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7682 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7683 << false << Ex->getSourceRange(), 7684 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7685 getSpecifierRange(startSpecifier, specifierLen)); 7686 7687 // Type check the second argument (char * for both %b and %D) 7688 Ex = getDataArg(argIndex + 1); 7689 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7690 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7691 EmitFormatDiagnostic( 7692 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7693 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7694 << false << Ex->getSourceRange(), 7695 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7696 getSpecifierRange(startSpecifier, specifierLen)); 7697 7698 return true; 7699 } 7700 7701 // Check for using an Objective-C specific conversion specifier 7702 // in a non-ObjC literal. 7703 if (!allowsObjCArg() && CS.isObjCArg()) { 7704 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7705 specifierLen); 7706 } 7707 7708 // %P can only be used with os_log. 7709 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7710 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7711 specifierLen); 7712 } 7713 7714 // %n is not allowed with os_log. 7715 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7716 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7717 getLocationOfByte(CS.getStart()), 7718 /*IsStringLocation*/ false, 7719 getSpecifierRange(startSpecifier, specifierLen)); 7720 7721 return true; 7722 } 7723 7724 // Only scalars are allowed for os_trace. 7725 if (FSType == Sema::FST_OSTrace && 7726 (CS.getKind() == ConversionSpecifier::PArg || 7727 CS.getKind() == ConversionSpecifier::sArg || 7728 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7729 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7730 specifierLen); 7731 } 7732 7733 // Check for use of public/private annotation outside of os_log(). 7734 if (FSType != Sema::FST_OSLog) { 7735 if (FS.isPublic().isSet()) { 7736 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7737 << "public", 7738 getLocationOfByte(FS.isPublic().getPosition()), 7739 /*IsStringLocation*/ false, 7740 getSpecifierRange(startSpecifier, specifierLen)); 7741 } 7742 if (FS.isPrivate().isSet()) { 7743 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7744 << "private", 7745 getLocationOfByte(FS.isPrivate().getPosition()), 7746 /*IsStringLocation*/ false, 7747 getSpecifierRange(startSpecifier, specifierLen)); 7748 } 7749 } 7750 7751 // Check for invalid use of field width 7752 if (!FS.hasValidFieldWidth()) { 7753 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7754 startSpecifier, specifierLen); 7755 } 7756 7757 // Check for invalid use of precision 7758 if (!FS.hasValidPrecision()) { 7759 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7760 startSpecifier, specifierLen); 7761 } 7762 7763 // Precision is mandatory for %P specifier. 7764 if (CS.getKind() == ConversionSpecifier::PArg && 7765 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7766 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7767 getLocationOfByte(startSpecifier), 7768 /*IsStringLocation*/ false, 7769 getSpecifierRange(startSpecifier, specifierLen)); 7770 } 7771 7772 // Check each flag does not conflict with any other component. 7773 if (!FS.hasValidThousandsGroupingPrefix()) 7774 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7775 if (!FS.hasValidLeadingZeros()) 7776 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7777 if (!FS.hasValidPlusPrefix()) 7778 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7779 if (!FS.hasValidSpacePrefix()) 7780 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7781 if (!FS.hasValidAlternativeForm()) 7782 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7783 if (!FS.hasValidLeftJustified()) 7784 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7785 7786 // Check that flags are not ignored by another flag 7787 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7788 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7789 startSpecifier, specifierLen); 7790 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7791 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7792 startSpecifier, specifierLen); 7793 7794 // Check the length modifier is valid with the given conversion specifier. 7795 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 7796 S.getLangOpts())) 7797 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7798 diag::warn_format_nonsensical_length); 7799 else if (!FS.hasStandardLengthModifier()) 7800 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7801 else if (!FS.hasStandardLengthConversionCombination()) 7802 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7803 diag::warn_format_non_standard_conversion_spec); 7804 7805 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7806 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7807 7808 // The remaining checks depend on the data arguments. 7809 if (HasVAListArg) 7810 return true; 7811 7812 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7813 return false; 7814 7815 const Expr *Arg = getDataArg(argIndex); 7816 if (!Arg) 7817 return true; 7818 7819 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7820 } 7821 7822 static bool requiresParensToAddCast(const Expr *E) { 7823 // FIXME: We should have a general way to reason about operator 7824 // precedence and whether parens are actually needed here. 7825 // Take care of a few common cases where they aren't. 7826 const Expr *Inside = E->IgnoreImpCasts(); 7827 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7828 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7829 7830 switch (Inside->getStmtClass()) { 7831 case Stmt::ArraySubscriptExprClass: 7832 case Stmt::CallExprClass: 7833 case Stmt::CharacterLiteralClass: 7834 case Stmt::CXXBoolLiteralExprClass: 7835 case Stmt::DeclRefExprClass: 7836 case Stmt::FloatingLiteralClass: 7837 case Stmt::IntegerLiteralClass: 7838 case Stmt::MemberExprClass: 7839 case Stmt::ObjCArrayLiteralClass: 7840 case Stmt::ObjCBoolLiteralExprClass: 7841 case Stmt::ObjCBoxedExprClass: 7842 case Stmt::ObjCDictionaryLiteralClass: 7843 case Stmt::ObjCEncodeExprClass: 7844 case Stmt::ObjCIvarRefExprClass: 7845 case Stmt::ObjCMessageExprClass: 7846 case Stmt::ObjCPropertyRefExprClass: 7847 case Stmt::ObjCStringLiteralClass: 7848 case Stmt::ObjCSubscriptRefExprClass: 7849 case Stmt::ParenExprClass: 7850 case Stmt::StringLiteralClass: 7851 case Stmt::UnaryOperatorClass: 7852 return false; 7853 default: 7854 return true; 7855 } 7856 } 7857 7858 static std::pair<QualType, StringRef> 7859 shouldNotPrintDirectly(const ASTContext &Context, 7860 QualType IntendedTy, 7861 const Expr *E) { 7862 // Use a 'while' to peel off layers of typedefs. 7863 QualType TyTy = IntendedTy; 7864 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7865 StringRef Name = UserTy->getDecl()->getName(); 7866 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7867 .Case("CFIndex", Context.getNSIntegerType()) 7868 .Case("NSInteger", Context.getNSIntegerType()) 7869 .Case("NSUInteger", Context.getNSUIntegerType()) 7870 .Case("SInt32", Context.IntTy) 7871 .Case("UInt32", Context.UnsignedIntTy) 7872 .Default(QualType()); 7873 7874 if (!CastTy.isNull()) 7875 return std::make_pair(CastTy, Name); 7876 7877 TyTy = UserTy->desugar(); 7878 } 7879 7880 // Strip parens if necessary. 7881 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7882 return shouldNotPrintDirectly(Context, 7883 PE->getSubExpr()->getType(), 7884 PE->getSubExpr()); 7885 7886 // If this is a conditional expression, then its result type is constructed 7887 // via usual arithmetic conversions and thus there might be no necessary 7888 // typedef sugar there. Recurse to operands to check for NSInteger & 7889 // Co. usage condition. 7890 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7891 QualType TrueTy, FalseTy; 7892 StringRef TrueName, FalseName; 7893 7894 std::tie(TrueTy, TrueName) = 7895 shouldNotPrintDirectly(Context, 7896 CO->getTrueExpr()->getType(), 7897 CO->getTrueExpr()); 7898 std::tie(FalseTy, FalseName) = 7899 shouldNotPrintDirectly(Context, 7900 CO->getFalseExpr()->getType(), 7901 CO->getFalseExpr()); 7902 7903 if (TrueTy == FalseTy) 7904 return std::make_pair(TrueTy, TrueName); 7905 else if (TrueTy.isNull()) 7906 return std::make_pair(FalseTy, FalseName); 7907 else if (FalseTy.isNull()) 7908 return std::make_pair(TrueTy, TrueName); 7909 } 7910 7911 return std::make_pair(QualType(), StringRef()); 7912 } 7913 7914 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 7915 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 7916 /// type do not count. 7917 static bool 7918 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 7919 QualType From = ICE->getSubExpr()->getType(); 7920 QualType To = ICE->getType(); 7921 // It's an integer promotion if the destination type is the promoted 7922 // source type. 7923 if (ICE->getCastKind() == CK_IntegralCast && 7924 From->isPromotableIntegerType() && 7925 S.Context.getPromotedIntegerType(From) == To) 7926 return true; 7927 // Look through vector types, since we do default argument promotion for 7928 // those in OpenCL. 7929 if (const auto *VecTy = From->getAs<ExtVectorType>()) 7930 From = VecTy->getElementType(); 7931 if (const auto *VecTy = To->getAs<ExtVectorType>()) 7932 To = VecTy->getElementType(); 7933 // It's a floating promotion if the source type is a lower rank. 7934 return ICE->getCastKind() == CK_FloatingCast && 7935 S.Context.getFloatingTypeOrder(From, To) < 0; 7936 } 7937 7938 bool 7939 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7940 const char *StartSpecifier, 7941 unsigned SpecifierLen, 7942 const Expr *E) { 7943 using namespace analyze_format_string; 7944 using namespace analyze_printf; 7945 7946 // Now type check the data expression that matches the 7947 // format specifier. 7948 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 7949 if (!AT.isValid()) 7950 return true; 7951 7952 QualType ExprTy = E->getType(); 7953 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 7954 ExprTy = TET->getUnderlyingExpr()->getType(); 7955 } 7956 7957 // Diagnose attempts to print a boolean value as a character. Unlike other 7958 // -Wformat diagnostics, this is fine from a type perspective, but it still 7959 // doesn't make sense. 7960 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 7961 E->isKnownToHaveBooleanValue()) { 7962 const CharSourceRange &CSR = 7963 getSpecifierRange(StartSpecifier, SpecifierLen); 7964 SmallString<4> FSString; 7965 llvm::raw_svector_ostream os(FSString); 7966 FS.toString(os); 7967 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 7968 << FSString, 7969 E->getExprLoc(), false, CSR); 7970 return true; 7971 } 7972 7973 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 7974 if (Match == analyze_printf::ArgType::Match) 7975 return true; 7976 7977 // Look through argument promotions for our error message's reported type. 7978 // This includes the integral and floating promotions, but excludes array 7979 // and function pointer decay (seeing that an argument intended to be a 7980 // string has type 'char [6]' is probably more confusing than 'char *') and 7981 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 7982 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7983 if (isArithmeticArgumentPromotion(S, ICE)) { 7984 E = ICE->getSubExpr(); 7985 ExprTy = E->getType(); 7986 7987 // Check if we didn't match because of an implicit cast from a 'char' 7988 // or 'short' to an 'int'. This is done because printf is a varargs 7989 // function. 7990 if (ICE->getType() == S.Context.IntTy || 7991 ICE->getType() == S.Context.UnsignedIntTy) { 7992 // All further checking is done on the subexpression 7993 const analyze_printf::ArgType::MatchKind ImplicitMatch = 7994 AT.matchesType(S.Context, ExprTy); 7995 if (ImplicitMatch == analyze_printf::ArgType::Match) 7996 return true; 7997 if (ImplicitMatch == ArgType::NoMatchPedantic || 7998 ImplicitMatch == ArgType::NoMatchTypeConfusion) 7999 Match = ImplicitMatch; 8000 } 8001 } 8002 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8003 // Special case for 'a', which has type 'int' in C. 8004 // Note, however, that we do /not/ want to treat multibyte constants like 8005 // 'MooV' as characters! This form is deprecated but still exists. 8006 if (ExprTy == S.Context.IntTy) 8007 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8008 ExprTy = S.Context.CharTy; 8009 } 8010 8011 // Look through enums to their underlying type. 8012 bool IsEnum = false; 8013 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8014 ExprTy = EnumTy->getDecl()->getIntegerType(); 8015 IsEnum = true; 8016 } 8017 8018 // %C in an Objective-C context prints a unichar, not a wchar_t. 8019 // If the argument is an integer of some kind, believe the %C and suggest 8020 // a cast instead of changing the conversion specifier. 8021 QualType IntendedTy = ExprTy; 8022 if (isObjCContext() && 8023 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8024 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8025 !ExprTy->isCharType()) { 8026 // 'unichar' is defined as a typedef of unsigned short, but we should 8027 // prefer using the typedef if it is visible. 8028 IntendedTy = S.Context.UnsignedShortTy; 8029 8030 // While we are here, check if the value is an IntegerLiteral that happens 8031 // to be within the valid range. 8032 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8033 const llvm::APInt &V = IL->getValue(); 8034 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8035 return true; 8036 } 8037 8038 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8039 Sema::LookupOrdinaryName); 8040 if (S.LookupName(Result, S.getCurScope())) { 8041 NamedDecl *ND = Result.getFoundDecl(); 8042 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8043 if (TD->getUnderlyingType() == IntendedTy) 8044 IntendedTy = S.Context.getTypedefType(TD); 8045 } 8046 } 8047 } 8048 8049 // Special-case some of Darwin's platform-independence types by suggesting 8050 // casts to primitive types that are known to be large enough. 8051 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8052 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8053 QualType CastTy; 8054 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8055 if (!CastTy.isNull()) { 8056 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8057 // (long in ASTContext). Only complain to pedants. 8058 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8059 (AT.isSizeT() || AT.isPtrdiffT()) && 8060 AT.matchesType(S.Context, CastTy)) 8061 Match = ArgType::NoMatchPedantic; 8062 IntendedTy = CastTy; 8063 ShouldNotPrintDirectly = true; 8064 } 8065 } 8066 8067 // We may be able to offer a FixItHint if it is a supported type. 8068 PrintfSpecifier fixedFS = FS; 8069 bool Success = 8070 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8071 8072 if (Success) { 8073 // Get the fix string from the fixed format specifier 8074 SmallString<16> buf; 8075 llvm::raw_svector_ostream os(buf); 8076 fixedFS.toString(os); 8077 8078 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8079 8080 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8081 unsigned Diag; 8082 switch (Match) { 8083 case ArgType::Match: llvm_unreachable("expected non-matching"); 8084 case ArgType::NoMatchPedantic: 8085 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8086 break; 8087 case ArgType::NoMatchTypeConfusion: 8088 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8089 break; 8090 case ArgType::NoMatch: 8091 Diag = diag::warn_format_conversion_argument_type_mismatch; 8092 break; 8093 } 8094 8095 // In this case, the specifier is wrong and should be changed to match 8096 // the argument. 8097 EmitFormatDiagnostic(S.PDiag(Diag) 8098 << AT.getRepresentativeTypeName(S.Context) 8099 << IntendedTy << IsEnum << E->getSourceRange(), 8100 E->getBeginLoc(), 8101 /*IsStringLocation*/ false, SpecRange, 8102 FixItHint::CreateReplacement(SpecRange, os.str())); 8103 } else { 8104 // The canonical type for formatting this value is different from the 8105 // actual type of the expression. (This occurs, for example, with Darwin's 8106 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8107 // should be printed as 'long' for 64-bit compatibility.) 8108 // Rather than emitting a normal format/argument mismatch, we want to 8109 // add a cast to the recommended type (and correct the format string 8110 // if necessary). 8111 SmallString<16> CastBuf; 8112 llvm::raw_svector_ostream CastFix(CastBuf); 8113 CastFix << "("; 8114 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8115 CastFix << ")"; 8116 8117 SmallVector<FixItHint,4> Hints; 8118 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8119 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8120 8121 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8122 // If there's already a cast present, just replace it. 8123 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8124 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8125 8126 } else if (!requiresParensToAddCast(E)) { 8127 // If the expression has high enough precedence, 8128 // just write the C-style cast. 8129 Hints.push_back( 8130 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8131 } else { 8132 // Otherwise, add parens around the expression as well as the cast. 8133 CastFix << "("; 8134 Hints.push_back( 8135 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8136 8137 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8138 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8139 } 8140 8141 if (ShouldNotPrintDirectly) { 8142 // The expression has a type that should not be printed directly. 8143 // We extract the name from the typedef because we don't want to show 8144 // the underlying type in the diagnostic. 8145 StringRef Name; 8146 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8147 Name = TypedefTy->getDecl()->getName(); 8148 else 8149 Name = CastTyName; 8150 unsigned Diag = Match == ArgType::NoMatchPedantic 8151 ? diag::warn_format_argument_needs_cast_pedantic 8152 : diag::warn_format_argument_needs_cast; 8153 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8154 << E->getSourceRange(), 8155 E->getBeginLoc(), /*IsStringLocation=*/false, 8156 SpecRange, Hints); 8157 } else { 8158 // In this case, the expression could be printed using a different 8159 // specifier, but we've decided that the specifier is probably correct 8160 // and we should cast instead. Just use the normal warning message. 8161 EmitFormatDiagnostic( 8162 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8163 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8164 << E->getSourceRange(), 8165 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8166 } 8167 } 8168 } else { 8169 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8170 SpecifierLen); 8171 // Since the warning for passing non-POD types to variadic functions 8172 // was deferred until now, we emit a warning for non-POD 8173 // arguments here. 8174 switch (S.isValidVarArgType(ExprTy)) { 8175 case Sema::VAK_Valid: 8176 case Sema::VAK_ValidInCXX11: { 8177 unsigned Diag; 8178 switch (Match) { 8179 case ArgType::Match: llvm_unreachable("expected non-matching"); 8180 case ArgType::NoMatchPedantic: 8181 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8182 break; 8183 case ArgType::NoMatchTypeConfusion: 8184 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8185 break; 8186 case ArgType::NoMatch: 8187 Diag = diag::warn_format_conversion_argument_type_mismatch; 8188 break; 8189 } 8190 8191 EmitFormatDiagnostic( 8192 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8193 << IsEnum << CSR << E->getSourceRange(), 8194 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8195 break; 8196 } 8197 case Sema::VAK_Undefined: 8198 case Sema::VAK_MSVCUndefined: 8199 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8200 << S.getLangOpts().CPlusPlus11 << ExprTy 8201 << CallType 8202 << AT.getRepresentativeTypeName(S.Context) << CSR 8203 << E->getSourceRange(), 8204 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8205 checkForCStrMembers(AT, E); 8206 break; 8207 8208 case Sema::VAK_Invalid: 8209 if (ExprTy->isObjCObjectType()) 8210 EmitFormatDiagnostic( 8211 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8212 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8213 << AT.getRepresentativeTypeName(S.Context) << CSR 8214 << E->getSourceRange(), 8215 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8216 else 8217 // FIXME: If this is an initializer list, suggest removing the braces 8218 // or inserting a cast to the target type. 8219 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8220 << isa<InitListExpr>(E) << ExprTy << CallType 8221 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8222 break; 8223 } 8224 8225 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8226 "format string specifier index out of range"); 8227 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8228 } 8229 8230 return true; 8231 } 8232 8233 //===--- CHECK: Scanf format string checking ------------------------------===// 8234 8235 namespace { 8236 8237 class CheckScanfHandler : public CheckFormatHandler { 8238 public: 8239 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8240 const Expr *origFormatExpr, Sema::FormatStringType type, 8241 unsigned firstDataArg, unsigned numDataArgs, 8242 const char *beg, bool hasVAListArg, 8243 ArrayRef<const Expr *> Args, unsigned formatIdx, 8244 bool inFunctionCall, Sema::VariadicCallType CallType, 8245 llvm::SmallBitVector &CheckedVarArgs, 8246 UncoveredArgHandler &UncoveredArg) 8247 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8248 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8249 inFunctionCall, CallType, CheckedVarArgs, 8250 UncoveredArg) {} 8251 8252 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8253 const char *startSpecifier, 8254 unsigned specifierLen) override; 8255 8256 bool HandleInvalidScanfConversionSpecifier( 8257 const analyze_scanf::ScanfSpecifier &FS, 8258 const char *startSpecifier, 8259 unsigned specifierLen) override; 8260 8261 void HandleIncompleteScanList(const char *start, const char *end) override; 8262 }; 8263 8264 } // namespace 8265 8266 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8267 const char *end) { 8268 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8269 getLocationOfByte(end), /*IsStringLocation*/true, 8270 getSpecifierRange(start, end - start)); 8271 } 8272 8273 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8274 const analyze_scanf::ScanfSpecifier &FS, 8275 const char *startSpecifier, 8276 unsigned specifierLen) { 8277 const analyze_scanf::ScanfConversionSpecifier &CS = 8278 FS.getConversionSpecifier(); 8279 8280 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8281 getLocationOfByte(CS.getStart()), 8282 startSpecifier, specifierLen, 8283 CS.getStart(), CS.getLength()); 8284 } 8285 8286 bool CheckScanfHandler::HandleScanfSpecifier( 8287 const analyze_scanf::ScanfSpecifier &FS, 8288 const char *startSpecifier, 8289 unsigned specifierLen) { 8290 using namespace analyze_scanf; 8291 using namespace analyze_format_string; 8292 8293 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8294 8295 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8296 // be used to decide if we are using positional arguments consistently. 8297 if (FS.consumesDataArgument()) { 8298 if (atFirstArg) { 8299 atFirstArg = false; 8300 usesPositionalArgs = FS.usesPositionalArg(); 8301 } 8302 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8303 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8304 startSpecifier, specifierLen); 8305 return false; 8306 } 8307 } 8308 8309 // Check if the field with is non-zero. 8310 const OptionalAmount &Amt = FS.getFieldWidth(); 8311 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8312 if (Amt.getConstantAmount() == 0) { 8313 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8314 Amt.getConstantLength()); 8315 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8316 getLocationOfByte(Amt.getStart()), 8317 /*IsStringLocation*/true, R, 8318 FixItHint::CreateRemoval(R)); 8319 } 8320 } 8321 8322 if (!FS.consumesDataArgument()) { 8323 // FIXME: Technically specifying a precision or field width here 8324 // makes no sense. Worth issuing a warning at some point. 8325 return true; 8326 } 8327 8328 // Consume the argument. 8329 unsigned argIndex = FS.getArgIndex(); 8330 if (argIndex < NumDataArgs) { 8331 // The check to see if the argIndex is valid will come later. 8332 // We set the bit here because we may exit early from this 8333 // function if we encounter some other error. 8334 CoveredArgs.set(argIndex); 8335 } 8336 8337 // Check the length modifier is valid with the given conversion specifier. 8338 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8339 S.getLangOpts())) 8340 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8341 diag::warn_format_nonsensical_length); 8342 else if (!FS.hasStandardLengthModifier()) 8343 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8344 else if (!FS.hasStandardLengthConversionCombination()) 8345 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8346 diag::warn_format_non_standard_conversion_spec); 8347 8348 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8349 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8350 8351 // The remaining checks depend on the data arguments. 8352 if (HasVAListArg) 8353 return true; 8354 8355 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8356 return false; 8357 8358 // Check that the argument type matches the format specifier. 8359 const Expr *Ex = getDataArg(argIndex); 8360 if (!Ex) 8361 return true; 8362 8363 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8364 8365 if (!AT.isValid()) { 8366 return true; 8367 } 8368 8369 analyze_format_string::ArgType::MatchKind Match = 8370 AT.matchesType(S.Context, Ex->getType()); 8371 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8372 if (Match == analyze_format_string::ArgType::Match) 8373 return true; 8374 8375 ScanfSpecifier fixedFS = FS; 8376 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8377 S.getLangOpts(), S.Context); 8378 8379 unsigned Diag = 8380 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8381 : diag::warn_format_conversion_argument_type_mismatch; 8382 8383 if (Success) { 8384 // Get the fix string from the fixed format specifier. 8385 SmallString<128> buf; 8386 llvm::raw_svector_ostream os(buf); 8387 fixedFS.toString(os); 8388 8389 EmitFormatDiagnostic( 8390 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8391 << Ex->getType() << false << Ex->getSourceRange(), 8392 Ex->getBeginLoc(), 8393 /*IsStringLocation*/ false, 8394 getSpecifierRange(startSpecifier, specifierLen), 8395 FixItHint::CreateReplacement( 8396 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8397 } else { 8398 EmitFormatDiagnostic(S.PDiag(Diag) 8399 << AT.getRepresentativeTypeName(S.Context) 8400 << Ex->getType() << false << Ex->getSourceRange(), 8401 Ex->getBeginLoc(), 8402 /*IsStringLocation*/ false, 8403 getSpecifierRange(startSpecifier, specifierLen)); 8404 } 8405 8406 return true; 8407 } 8408 8409 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8410 const Expr *OrigFormatExpr, 8411 ArrayRef<const Expr *> Args, 8412 bool HasVAListArg, unsigned format_idx, 8413 unsigned firstDataArg, 8414 Sema::FormatStringType Type, 8415 bool inFunctionCall, 8416 Sema::VariadicCallType CallType, 8417 llvm::SmallBitVector &CheckedVarArgs, 8418 UncoveredArgHandler &UncoveredArg, 8419 bool IgnoreStringsWithoutSpecifiers) { 8420 // CHECK: is the format string a wide literal? 8421 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8422 CheckFormatHandler::EmitFormatDiagnostic( 8423 S, inFunctionCall, Args[format_idx], 8424 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8425 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8426 return; 8427 } 8428 8429 // Str - The format string. NOTE: this is NOT null-terminated! 8430 StringRef StrRef = FExpr->getString(); 8431 const char *Str = StrRef.data(); 8432 // Account for cases where the string literal is truncated in a declaration. 8433 const ConstantArrayType *T = 8434 S.Context.getAsConstantArrayType(FExpr->getType()); 8435 assert(T && "String literal not of constant array type!"); 8436 size_t TypeSize = T->getSize().getZExtValue(); 8437 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8438 const unsigned numDataArgs = Args.size() - firstDataArg; 8439 8440 if (IgnoreStringsWithoutSpecifiers && 8441 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8442 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8443 return; 8444 8445 // Emit a warning if the string literal is truncated and does not contain an 8446 // embedded null character. 8447 if (TypeSize <= StrRef.size() && 8448 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8449 CheckFormatHandler::EmitFormatDiagnostic( 8450 S, inFunctionCall, Args[format_idx], 8451 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8452 FExpr->getBeginLoc(), 8453 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8454 return; 8455 } 8456 8457 // CHECK: empty format string? 8458 if (StrLen == 0 && numDataArgs > 0) { 8459 CheckFormatHandler::EmitFormatDiagnostic( 8460 S, inFunctionCall, Args[format_idx], 8461 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8462 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8463 return; 8464 } 8465 8466 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8467 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8468 Type == Sema::FST_OSTrace) { 8469 CheckPrintfHandler H( 8470 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8471 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8472 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8473 CheckedVarArgs, UncoveredArg); 8474 8475 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8476 S.getLangOpts(), 8477 S.Context.getTargetInfo(), 8478 Type == Sema::FST_FreeBSDKPrintf)) 8479 H.DoneProcessing(); 8480 } else if (Type == Sema::FST_Scanf) { 8481 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8482 numDataArgs, Str, HasVAListArg, Args, format_idx, 8483 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8484 8485 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8486 S.getLangOpts(), 8487 S.Context.getTargetInfo())) 8488 H.DoneProcessing(); 8489 } // TODO: handle other formats 8490 } 8491 8492 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8493 // Str - The format string. NOTE: this is NOT null-terminated! 8494 StringRef StrRef = FExpr->getString(); 8495 const char *Str = StrRef.data(); 8496 // Account for cases where the string literal is truncated in a declaration. 8497 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8498 assert(T && "String literal not of constant array type!"); 8499 size_t TypeSize = T->getSize().getZExtValue(); 8500 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8501 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8502 getLangOpts(), 8503 Context.getTargetInfo()); 8504 } 8505 8506 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8507 8508 // Returns the related absolute value function that is larger, of 0 if one 8509 // does not exist. 8510 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8511 switch (AbsFunction) { 8512 default: 8513 return 0; 8514 8515 case Builtin::BI__builtin_abs: 8516 return Builtin::BI__builtin_labs; 8517 case Builtin::BI__builtin_labs: 8518 return Builtin::BI__builtin_llabs; 8519 case Builtin::BI__builtin_llabs: 8520 return 0; 8521 8522 case Builtin::BI__builtin_fabsf: 8523 return Builtin::BI__builtin_fabs; 8524 case Builtin::BI__builtin_fabs: 8525 return Builtin::BI__builtin_fabsl; 8526 case Builtin::BI__builtin_fabsl: 8527 return 0; 8528 8529 case Builtin::BI__builtin_cabsf: 8530 return Builtin::BI__builtin_cabs; 8531 case Builtin::BI__builtin_cabs: 8532 return Builtin::BI__builtin_cabsl; 8533 case Builtin::BI__builtin_cabsl: 8534 return 0; 8535 8536 case Builtin::BIabs: 8537 return Builtin::BIlabs; 8538 case Builtin::BIlabs: 8539 return Builtin::BIllabs; 8540 case Builtin::BIllabs: 8541 return 0; 8542 8543 case Builtin::BIfabsf: 8544 return Builtin::BIfabs; 8545 case Builtin::BIfabs: 8546 return Builtin::BIfabsl; 8547 case Builtin::BIfabsl: 8548 return 0; 8549 8550 case Builtin::BIcabsf: 8551 return Builtin::BIcabs; 8552 case Builtin::BIcabs: 8553 return Builtin::BIcabsl; 8554 case Builtin::BIcabsl: 8555 return 0; 8556 } 8557 } 8558 8559 // Returns the argument type of the absolute value function. 8560 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8561 unsigned AbsType) { 8562 if (AbsType == 0) 8563 return QualType(); 8564 8565 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8566 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8567 if (Error != ASTContext::GE_None) 8568 return QualType(); 8569 8570 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8571 if (!FT) 8572 return QualType(); 8573 8574 if (FT->getNumParams() != 1) 8575 return QualType(); 8576 8577 return FT->getParamType(0); 8578 } 8579 8580 // Returns the best absolute value function, or zero, based on type and 8581 // current absolute value function. 8582 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8583 unsigned AbsFunctionKind) { 8584 unsigned BestKind = 0; 8585 uint64_t ArgSize = Context.getTypeSize(ArgType); 8586 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8587 Kind = getLargerAbsoluteValueFunction(Kind)) { 8588 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8589 if (Context.getTypeSize(ParamType) >= ArgSize) { 8590 if (BestKind == 0) 8591 BestKind = Kind; 8592 else if (Context.hasSameType(ParamType, ArgType)) { 8593 BestKind = Kind; 8594 break; 8595 } 8596 } 8597 } 8598 return BestKind; 8599 } 8600 8601 enum AbsoluteValueKind { 8602 AVK_Integer, 8603 AVK_Floating, 8604 AVK_Complex 8605 }; 8606 8607 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8608 if (T->isIntegralOrEnumerationType()) 8609 return AVK_Integer; 8610 if (T->isRealFloatingType()) 8611 return AVK_Floating; 8612 if (T->isAnyComplexType()) 8613 return AVK_Complex; 8614 8615 llvm_unreachable("Type not integer, floating, or complex"); 8616 } 8617 8618 // Changes the absolute value function to a different type. Preserves whether 8619 // the function is a builtin. 8620 static unsigned changeAbsFunction(unsigned AbsKind, 8621 AbsoluteValueKind ValueKind) { 8622 switch (ValueKind) { 8623 case AVK_Integer: 8624 switch (AbsKind) { 8625 default: 8626 return 0; 8627 case Builtin::BI__builtin_fabsf: 8628 case Builtin::BI__builtin_fabs: 8629 case Builtin::BI__builtin_fabsl: 8630 case Builtin::BI__builtin_cabsf: 8631 case Builtin::BI__builtin_cabs: 8632 case Builtin::BI__builtin_cabsl: 8633 return Builtin::BI__builtin_abs; 8634 case Builtin::BIfabsf: 8635 case Builtin::BIfabs: 8636 case Builtin::BIfabsl: 8637 case Builtin::BIcabsf: 8638 case Builtin::BIcabs: 8639 case Builtin::BIcabsl: 8640 return Builtin::BIabs; 8641 } 8642 case AVK_Floating: 8643 switch (AbsKind) { 8644 default: 8645 return 0; 8646 case Builtin::BI__builtin_abs: 8647 case Builtin::BI__builtin_labs: 8648 case Builtin::BI__builtin_llabs: 8649 case Builtin::BI__builtin_cabsf: 8650 case Builtin::BI__builtin_cabs: 8651 case Builtin::BI__builtin_cabsl: 8652 return Builtin::BI__builtin_fabsf; 8653 case Builtin::BIabs: 8654 case Builtin::BIlabs: 8655 case Builtin::BIllabs: 8656 case Builtin::BIcabsf: 8657 case Builtin::BIcabs: 8658 case Builtin::BIcabsl: 8659 return Builtin::BIfabsf; 8660 } 8661 case AVK_Complex: 8662 switch (AbsKind) { 8663 default: 8664 return 0; 8665 case Builtin::BI__builtin_abs: 8666 case Builtin::BI__builtin_labs: 8667 case Builtin::BI__builtin_llabs: 8668 case Builtin::BI__builtin_fabsf: 8669 case Builtin::BI__builtin_fabs: 8670 case Builtin::BI__builtin_fabsl: 8671 return Builtin::BI__builtin_cabsf; 8672 case Builtin::BIabs: 8673 case Builtin::BIlabs: 8674 case Builtin::BIllabs: 8675 case Builtin::BIfabsf: 8676 case Builtin::BIfabs: 8677 case Builtin::BIfabsl: 8678 return Builtin::BIcabsf; 8679 } 8680 } 8681 llvm_unreachable("Unable to convert function"); 8682 } 8683 8684 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8685 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8686 if (!FnInfo) 8687 return 0; 8688 8689 switch (FDecl->getBuiltinID()) { 8690 default: 8691 return 0; 8692 case Builtin::BI__builtin_abs: 8693 case Builtin::BI__builtin_fabs: 8694 case Builtin::BI__builtin_fabsf: 8695 case Builtin::BI__builtin_fabsl: 8696 case Builtin::BI__builtin_labs: 8697 case Builtin::BI__builtin_llabs: 8698 case Builtin::BI__builtin_cabs: 8699 case Builtin::BI__builtin_cabsf: 8700 case Builtin::BI__builtin_cabsl: 8701 case Builtin::BIabs: 8702 case Builtin::BIlabs: 8703 case Builtin::BIllabs: 8704 case Builtin::BIfabs: 8705 case Builtin::BIfabsf: 8706 case Builtin::BIfabsl: 8707 case Builtin::BIcabs: 8708 case Builtin::BIcabsf: 8709 case Builtin::BIcabsl: 8710 return FDecl->getBuiltinID(); 8711 } 8712 llvm_unreachable("Unknown Builtin type"); 8713 } 8714 8715 // If the replacement is valid, emit a note with replacement function. 8716 // Additionally, suggest including the proper header if not already included. 8717 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8718 unsigned AbsKind, QualType ArgType) { 8719 bool EmitHeaderHint = true; 8720 const char *HeaderName = nullptr; 8721 const char *FunctionName = nullptr; 8722 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8723 FunctionName = "std::abs"; 8724 if (ArgType->isIntegralOrEnumerationType()) { 8725 HeaderName = "cstdlib"; 8726 } else if (ArgType->isRealFloatingType()) { 8727 HeaderName = "cmath"; 8728 } else { 8729 llvm_unreachable("Invalid Type"); 8730 } 8731 8732 // Lookup all std::abs 8733 if (NamespaceDecl *Std = S.getStdNamespace()) { 8734 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8735 R.suppressDiagnostics(); 8736 S.LookupQualifiedName(R, Std); 8737 8738 for (const auto *I : R) { 8739 const FunctionDecl *FDecl = nullptr; 8740 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8741 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8742 } else { 8743 FDecl = dyn_cast<FunctionDecl>(I); 8744 } 8745 if (!FDecl) 8746 continue; 8747 8748 // Found std::abs(), check that they are the right ones. 8749 if (FDecl->getNumParams() != 1) 8750 continue; 8751 8752 // Check that the parameter type can handle the argument. 8753 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8754 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8755 S.Context.getTypeSize(ArgType) <= 8756 S.Context.getTypeSize(ParamType)) { 8757 // Found a function, don't need the header hint. 8758 EmitHeaderHint = false; 8759 break; 8760 } 8761 } 8762 } 8763 } else { 8764 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8765 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8766 8767 if (HeaderName) { 8768 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8769 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8770 R.suppressDiagnostics(); 8771 S.LookupName(R, S.getCurScope()); 8772 8773 if (R.isSingleResult()) { 8774 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8775 if (FD && FD->getBuiltinID() == AbsKind) { 8776 EmitHeaderHint = false; 8777 } else { 8778 return; 8779 } 8780 } else if (!R.empty()) { 8781 return; 8782 } 8783 } 8784 } 8785 8786 S.Diag(Loc, diag::note_replace_abs_function) 8787 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8788 8789 if (!HeaderName) 8790 return; 8791 8792 if (!EmitHeaderHint) 8793 return; 8794 8795 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8796 << FunctionName; 8797 } 8798 8799 template <std::size_t StrLen> 8800 static bool IsStdFunction(const FunctionDecl *FDecl, 8801 const char (&Str)[StrLen]) { 8802 if (!FDecl) 8803 return false; 8804 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8805 return false; 8806 if (!FDecl->isInStdNamespace()) 8807 return false; 8808 8809 return true; 8810 } 8811 8812 // Warn when using the wrong abs() function. 8813 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8814 const FunctionDecl *FDecl) { 8815 if (Call->getNumArgs() != 1) 8816 return; 8817 8818 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8819 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8820 if (AbsKind == 0 && !IsStdAbs) 8821 return; 8822 8823 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8824 QualType ParamType = Call->getArg(0)->getType(); 8825 8826 // Unsigned types cannot be negative. Suggest removing the absolute value 8827 // function call. 8828 if (ArgType->isUnsignedIntegerType()) { 8829 const char *FunctionName = 8830 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8831 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8832 Diag(Call->getExprLoc(), diag::note_remove_abs) 8833 << FunctionName 8834 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8835 return; 8836 } 8837 8838 // Taking the absolute value of a pointer is very suspicious, they probably 8839 // wanted to index into an array, dereference a pointer, call a function, etc. 8840 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8841 unsigned DiagType = 0; 8842 if (ArgType->isFunctionType()) 8843 DiagType = 1; 8844 else if (ArgType->isArrayType()) 8845 DiagType = 2; 8846 8847 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8848 return; 8849 } 8850 8851 // std::abs has overloads which prevent most of the absolute value problems 8852 // from occurring. 8853 if (IsStdAbs) 8854 return; 8855 8856 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8857 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8858 8859 // The argument and parameter are the same kind. Check if they are the right 8860 // size. 8861 if (ArgValueKind == ParamValueKind) { 8862 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8863 return; 8864 8865 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8866 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8867 << FDecl << ArgType << ParamType; 8868 8869 if (NewAbsKind == 0) 8870 return; 8871 8872 emitReplacement(*this, Call->getExprLoc(), 8873 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8874 return; 8875 } 8876 8877 // ArgValueKind != ParamValueKind 8878 // The wrong type of absolute value function was used. Attempt to find the 8879 // proper one. 8880 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8881 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8882 if (NewAbsKind == 0) 8883 return; 8884 8885 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8886 << FDecl << ParamValueKind << ArgValueKind; 8887 8888 emitReplacement(*this, Call->getExprLoc(), 8889 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8890 } 8891 8892 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8893 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8894 const FunctionDecl *FDecl) { 8895 if (!Call || !FDecl) return; 8896 8897 // Ignore template specializations and macros. 8898 if (inTemplateInstantiation()) return; 8899 if (Call->getExprLoc().isMacroID()) return; 8900 8901 // Only care about the one template argument, two function parameter std::max 8902 if (Call->getNumArgs() != 2) return; 8903 if (!IsStdFunction(FDecl, "max")) return; 8904 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8905 if (!ArgList) return; 8906 if (ArgList->size() != 1) return; 8907 8908 // Check that template type argument is unsigned integer. 8909 const auto& TA = ArgList->get(0); 8910 if (TA.getKind() != TemplateArgument::Type) return; 8911 QualType ArgType = TA.getAsType(); 8912 if (!ArgType->isUnsignedIntegerType()) return; 8913 8914 // See if either argument is a literal zero. 8915 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8916 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8917 if (!MTE) return false; 8918 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 8919 if (!Num) return false; 8920 if (Num->getValue() != 0) return false; 8921 return true; 8922 }; 8923 8924 const Expr *FirstArg = Call->getArg(0); 8925 const Expr *SecondArg = Call->getArg(1); 8926 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8927 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 8928 8929 // Only warn when exactly one argument is zero. 8930 if (IsFirstArgZero == IsSecondArgZero) return; 8931 8932 SourceRange FirstRange = FirstArg->getSourceRange(); 8933 SourceRange SecondRange = SecondArg->getSourceRange(); 8934 8935 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 8936 8937 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 8938 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 8939 8940 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 8941 SourceRange RemovalRange; 8942 if (IsFirstArgZero) { 8943 RemovalRange = SourceRange(FirstRange.getBegin(), 8944 SecondRange.getBegin().getLocWithOffset(-1)); 8945 } else { 8946 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 8947 SecondRange.getEnd()); 8948 } 8949 8950 Diag(Call->getExprLoc(), diag::note_remove_max_call) 8951 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 8952 << FixItHint::CreateRemoval(RemovalRange); 8953 } 8954 8955 //===--- CHECK: Standard memory functions ---------------------------------===// 8956 8957 /// Takes the expression passed to the size_t parameter of functions 8958 /// such as memcmp, strncat, etc and warns if it's a comparison. 8959 /// 8960 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 8961 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 8962 IdentifierInfo *FnName, 8963 SourceLocation FnLoc, 8964 SourceLocation RParenLoc) { 8965 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 8966 if (!Size) 8967 return false; 8968 8969 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 8970 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 8971 return false; 8972 8973 SourceRange SizeRange = Size->getSourceRange(); 8974 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 8975 << SizeRange << FnName; 8976 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 8977 << FnName 8978 << FixItHint::CreateInsertion( 8979 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 8980 << FixItHint::CreateRemoval(RParenLoc); 8981 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 8982 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 8983 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 8984 ")"); 8985 8986 return true; 8987 } 8988 8989 /// Determine whether the given type is or contains a dynamic class type 8990 /// (e.g., whether it has a vtable). 8991 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 8992 bool &IsContained) { 8993 // Look through array types while ignoring qualifiers. 8994 const Type *Ty = T->getBaseElementTypeUnsafe(); 8995 IsContained = false; 8996 8997 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 8998 RD = RD ? RD->getDefinition() : nullptr; 8999 if (!RD || RD->isInvalidDecl()) 9000 return nullptr; 9001 9002 if (RD->isDynamicClass()) 9003 return RD; 9004 9005 // Check all the fields. If any bases were dynamic, the class is dynamic. 9006 // It's impossible for a class to transitively contain itself by value, so 9007 // infinite recursion is impossible. 9008 for (auto *FD : RD->fields()) { 9009 bool SubContained; 9010 if (const CXXRecordDecl *ContainedRD = 9011 getContainedDynamicClass(FD->getType(), SubContained)) { 9012 IsContained = true; 9013 return ContainedRD; 9014 } 9015 } 9016 9017 return nullptr; 9018 } 9019 9020 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9021 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9022 if (Unary->getKind() == UETT_SizeOf) 9023 return Unary; 9024 return nullptr; 9025 } 9026 9027 /// If E is a sizeof expression, returns its argument expression, 9028 /// otherwise returns NULL. 9029 static const Expr *getSizeOfExprArg(const Expr *E) { 9030 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9031 if (!SizeOf->isArgumentType()) 9032 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9033 return nullptr; 9034 } 9035 9036 /// If E is a sizeof expression, returns its argument type. 9037 static QualType getSizeOfArgType(const Expr *E) { 9038 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9039 return SizeOf->getTypeOfArgument(); 9040 return QualType(); 9041 } 9042 9043 namespace { 9044 9045 struct SearchNonTrivialToInitializeField 9046 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9047 using Super = 9048 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9049 9050 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9051 9052 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9053 SourceLocation SL) { 9054 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9055 asDerived().visitArray(PDIK, AT, SL); 9056 return; 9057 } 9058 9059 Super::visitWithKind(PDIK, FT, SL); 9060 } 9061 9062 void visitARCStrong(QualType FT, SourceLocation SL) { 9063 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9064 } 9065 void visitARCWeak(QualType FT, SourceLocation SL) { 9066 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9067 } 9068 void visitStruct(QualType FT, SourceLocation SL) { 9069 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9070 visit(FD->getType(), FD->getLocation()); 9071 } 9072 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9073 const ArrayType *AT, SourceLocation SL) { 9074 visit(getContext().getBaseElementType(AT), SL); 9075 } 9076 void visitTrivial(QualType FT, SourceLocation SL) {} 9077 9078 static void diag(QualType RT, const Expr *E, Sema &S) { 9079 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9080 } 9081 9082 ASTContext &getContext() { return S.getASTContext(); } 9083 9084 const Expr *E; 9085 Sema &S; 9086 }; 9087 9088 struct SearchNonTrivialToCopyField 9089 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9090 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9091 9092 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9093 9094 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9095 SourceLocation SL) { 9096 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9097 asDerived().visitArray(PCK, AT, SL); 9098 return; 9099 } 9100 9101 Super::visitWithKind(PCK, FT, SL); 9102 } 9103 9104 void visitARCStrong(QualType FT, SourceLocation SL) { 9105 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9106 } 9107 void visitARCWeak(QualType FT, SourceLocation SL) { 9108 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9109 } 9110 void visitStruct(QualType FT, SourceLocation SL) { 9111 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9112 visit(FD->getType(), FD->getLocation()); 9113 } 9114 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9115 SourceLocation SL) { 9116 visit(getContext().getBaseElementType(AT), SL); 9117 } 9118 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9119 SourceLocation SL) {} 9120 void visitTrivial(QualType FT, SourceLocation SL) {} 9121 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9122 9123 static void diag(QualType RT, const Expr *E, Sema &S) { 9124 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9125 } 9126 9127 ASTContext &getContext() { return S.getASTContext(); } 9128 9129 const Expr *E; 9130 Sema &S; 9131 }; 9132 9133 } 9134 9135 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9136 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9137 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9138 9139 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9140 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9141 return false; 9142 9143 return doesExprLikelyComputeSize(BO->getLHS()) || 9144 doesExprLikelyComputeSize(BO->getRHS()); 9145 } 9146 9147 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9148 } 9149 9150 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9151 /// 9152 /// \code 9153 /// #define MACRO 0 9154 /// foo(MACRO); 9155 /// foo(0); 9156 /// \endcode 9157 /// 9158 /// This should return true for the first call to foo, but not for the second 9159 /// (regardless of whether foo is a macro or function). 9160 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9161 SourceLocation CallLoc, 9162 SourceLocation ArgLoc) { 9163 if (!CallLoc.isMacroID()) 9164 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9165 9166 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9167 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9168 } 9169 9170 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9171 /// last two arguments transposed. 9172 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9173 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9174 return; 9175 9176 const Expr *SizeArg = 9177 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9178 9179 auto isLiteralZero = [](const Expr *E) { 9180 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9181 }; 9182 9183 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9184 SourceLocation CallLoc = Call->getRParenLoc(); 9185 SourceManager &SM = S.getSourceManager(); 9186 if (isLiteralZero(SizeArg) && 9187 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9188 9189 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9190 9191 // Some platforms #define bzero to __builtin_memset. See if this is the 9192 // case, and if so, emit a better diagnostic. 9193 if (BId == Builtin::BIbzero || 9194 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9195 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9196 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9197 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9198 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9199 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9200 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9201 } 9202 return; 9203 } 9204 9205 // If the second argument to a memset is a sizeof expression and the third 9206 // isn't, this is also likely an error. This should catch 9207 // 'memset(buf, sizeof(buf), 0xff)'. 9208 if (BId == Builtin::BImemset && 9209 doesExprLikelyComputeSize(Call->getArg(1)) && 9210 !doesExprLikelyComputeSize(Call->getArg(2))) { 9211 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9212 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9213 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9214 return; 9215 } 9216 } 9217 9218 /// Check for dangerous or invalid arguments to memset(). 9219 /// 9220 /// This issues warnings on known problematic, dangerous or unspecified 9221 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9222 /// function calls. 9223 /// 9224 /// \param Call The call expression to diagnose. 9225 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9226 unsigned BId, 9227 IdentifierInfo *FnName) { 9228 assert(BId != 0); 9229 9230 // It is possible to have a non-standard definition of memset. Validate 9231 // we have enough arguments, and if not, abort further checking. 9232 unsigned ExpectedNumArgs = 9233 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9234 if (Call->getNumArgs() < ExpectedNumArgs) 9235 return; 9236 9237 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9238 BId == Builtin::BIstrndup ? 1 : 2); 9239 unsigned LenArg = 9240 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9241 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9242 9243 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9244 Call->getBeginLoc(), Call->getRParenLoc())) 9245 return; 9246 9247 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9248 CheckMemaccessSize(*this, BId, Call); 9249 9250 // We have special checking when the length is a sizeof expression. 9251 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9252 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9253 llvm::FoldingSetNodeID SizeOfArgID; 9254 9255 // Although widely used, 'bzero' is not a standard function. Be more strict 9256 // with the argument types before allowing diagnostics and only allow the 9257 // form bzero(ptr, sizeof(...)). 9258 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9259 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9260 return; 9261 9262 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9263 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9264 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9265 9266 QualType DestTy = Dest->getType(); 9267 QualType PointeeTy; 9268 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9269 PointeeTy = DestPtrTy->getPointeeType(); 9270 9271 // Never warn about void type pointers. This can be used to suppress 9272 // false positives. 9273 if (PointeeTy->isVoidType()) 9274 continue; 9275 9276 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9277 // actually comparing the expressions for equality. Because computing the 9278 // expression IDs can be expensive, we only do this if the diagnostic is 9279 // enabled. 9280 if (SizeOfArg && 9281 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9282 SizeOfArg->getExprLoc())) { 9283 // We only compute IDs for expressions if the warning is enabled, and 9284 // cache the sizeof arg's ID. 9285 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9286 SizeOfArg->Profile(SizeOfArgID, Context, true); 9287 llvm::FoldingSetNodeID DestID; 9288 Dest->Profile(DestID, Context, true); 9289 if (DestID == SizeOfArgID) { 9290 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9291 // over sizeof(src) as well. 9292 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9293 StringRef ReadableName = FnName->getName(); 9294 9295 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9296 if (UnaryOp->getOpcode() == UO_AddrOf) 9297 ActionIdx = 1; // If its an address-of operator, just remove it. 9298 if (!PointeeTy->isIncompleteType() && 9299 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9300 ActionIdx = 2; // If the pointee's size is sizeof(char), 9301 // suggest an explicit length. 9302 9303 // If the function is defined as a builtin macro, do not show macro 9304 // expansion. 9305 SourceLocation SL = SizeOfArg->getExprLoc(); 9306 SourceRange DSR = Dest->getSourceRange(); 9307 SourceRange SSR = SizeOfArg->getSourceRange(); 9308 SourceManager &SM = getSourceManager(); 9309 9310 if (SM.isMacroArgExpansion(SL)) { 9311 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9312 SL = SM.getSpellingLoc(SL); 9313 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9314 SM.getSpellingLoc(DSR.getEnd())); 9315 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9316 SM.getSpellingLoc(SSR.getEnd())); 9317 } 9318 9319 DiagRuntimeBehavior(SL, SizeOfArg, 9320 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9321 << ReadableName 9322 << PointeeTy 9323 << DestTy 9324 << DSR 9325 << SSR); 9326 DiagRuntimeBehavior(SL, SizeOfArg, 9327 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9328 << ActionIdx 9329 << SSR); 9330 9331 break; 9332 } 9333 } 9334 9335 // Also check for cases where the sizeof argument is the exact same 9336 // type as the memory argument, and where it points to a user-defined 9337 // record type. 9338 if (SizeOfArgTy != QualType()) { 9339 if (PointeeTy->isRecordType() && 9340 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9341 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9342 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9343 << FnName << SizeOfArgTy << ArgIdx 9344 << PointeeTy << Dest->getSourceRange() 9345 << LenExpr->getSourceRange()); 9346 break; 9347 } 9348 } 9349 } else if (DestTy->isArrayType()) { 9350 PointeeTy = DestTy; 9351 } 9352 9353 if (PointeeTy == QualType()) 9354 continue; 9355 9356 // Always complain about dynamic classes. 9357 bool IsContained; 9358 if (const CXXRecordDecl *ContainedRD = 9359 getContainedDynamicClass(PointeeTy, IsContained)) { 9360 9361 unsigned OperationType = 0; 9362 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9363 // "overwritten" if we're warning about the destination for any call 9364 // but memcmp; otherwise a verb appropriate to the call. 9365 if (ArgIdx != 0 || IsCmp) { 9366 if (BId == Builtin::BImemcpy) 9367 OperationType = 1; 9368 else if(BId == Builtin::BImemmove) 9369 OperationType = 2; 9370 else if (IsCmp) 9371 OperationType = 3; 9372 } 9373 9374 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9375 PDiag(diag::warn_dyn_class_memaccess) 9376 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9377 << IsContained << ContainedRD << OperationType 9378 << Call->getCallee()->getSourceRange()); 9379 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9380 BId != Builtin::BImemset) 9381 DiagRuntimeBehavior( 9382 Dest->getExprLoc(), Dest, 9383 PDiag(diag::warn_arc_object_memaccess) 9384 << ArgIdx << FnName << PointeeTy 9385 << Call->getCallee()->getSourceRange()); 9386 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9387 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9388 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9389 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9390 PDiag(diag::warn_cstruct_memaccess) 9391 << ArgIdx << FnName << PointeeTy << 0); 9392 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9393 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9394 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9395 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9396 PDiag(diag::warn_cstruct_memaccess) 9397 << ArgIdx << FnName << PointeeTy << 1); 9398 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9399 } else { 9400 continue; 9401 } 9402 } else 9403 continue; 9404 9405 DiagRuntimeBehavior( 9406 Dest->getExprLoc(), Dest, 9407 PDiag(diag::note_bad_memaccess_silence) 9408 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9409 break; 9410 } 9411 } 9412 9413 // A little helper routine: ignore addition and subtraction of integer literals. 9414 // This intentionally does not ignore all integer constant expressions because 9415 // we don't want to remove sizeof(). 9416 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9417 Ex = Ex->IgnoreParenCasts(); 9418 9419 while (true) { 9420 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9421 if (!BO || !BO->isAdditiveOp()) 9422 break; 9423 9424 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9425 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9426 9427 if (isa<IntegerLiteral>(RHS)) 9428 Ex = LHS; 9429 else if (isa<IntegerLiteral>(LHS)) 9430 Ex = RHS; 9431 else 9432 break; 9433 } 9434 9435 return Ex; 9436 } 9437 9438 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9439 ASTContext &Context) { 9440 // Only handle constant-sized or VLAs, but not flexible members. 9441 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9442 // Only issue the FIXIT for arrays of size > 1. 9443 if (CAT->getSize().getSExtValue() <= 1) 9444 return false; 9445 } else if (!Ty->isVariableArrayType()) { 9446 return false; 9447 } 9448 return true; 9449 } 9450 9451 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9452 // be the size of the source, instead of the destination. 9453 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9454 IdentifierInfo *FnName) { 9455 9456 // Don't crash if the user has the wrong number of arguments 9457 unsigned NumArgs = Call->getNumArgs(); 9458 if ((NumArgs != 3) && (NumArgs != 4)) 9459 return; 9460 9461 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9462 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9463 const Expr *CompareWithSrc = nullptr; 9464 9465 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9466 Call->getBeginLoc(), Call->getRParenLoc())) 9467 return; 9468 9469 // Look for 'strlcpy(dst, x, sizeof(x))' 9470 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9471 CompareWithSrc = Ex; 9472 else { 9473 // Look for 'strlcpy(dst, x, strlen(x))' 9474 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9475 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9476 SizeCall->getNumArgs() == 1) 9477 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9478 } 9479 } 9480 9481 if (!CompareWithSrc) 9482 return; 9483 9484 // Determine if the argument to sizeof/strlen is equal to the source 9485 // argument. In principle there's all kinds of things you could do 9486 // here, for instance creating an == expression and evaluating it with 9487 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9488 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9489 if (!SrcArgDRE) 9490 return; 9491 9492 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9493 if (!CompareWithSrcDRE || 9494 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9495 return; 9496 9497 const Expr *OriginalSizeArg = Call->getArg(2); 9498 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9499 << OriginalSizeArg->getSourceRange() << FnName; 9500 9501 // Output a FIXIT hint if the destination is an array (rather than a 9502 // pointer to an array). This could be enhanced to handle some 9503 // pointers if we know the actual size, like if DstArg is 'array+2' 9504 // we could say 'sizeof(array)-2'. 9505 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9506 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9507 return; 9508 9509 SmallString<128> sizeString; 9510 llvm::raw_svector_ostream OS(sizeString); 9511 OS << "sizeof("; 9512 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9513 OS << ")"; 9514 9515 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9516 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9517 OS.str()); 9518 } 9519 9520 /// Check if two expressions refer to the same declaration. 9521 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9522 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9523 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9524 return D1->getDecl() == D2->getDecl(); 9525 return false; 9526 } 9527 9528 static const Expr *getStrlenExprArg(const Expr *E) { 9529 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9530 const FunctionDecl *FD = CE->getDirectCallee(); 9531 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9532 return nullptr; 9533 return CE->getArg(0)->IgnoreParenCasts(); 9534 } 9535 return nullptr; 9536 } 9537 9538 // Warn on anti-patterns as the 'size' argument to strncat. 9539 // The correct size argument should look like following: 9540 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9541 void Sema::CheckStrncatArguments(const CallExpr *CE, 9542 IdentifierInfo *FnName) { 9543 // Don't crash if the user has the wrong number of arguments. 9544 if (CE->getNumArgs() < 3) 9545 return; 9546 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9547 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9548 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9549 9550 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9551 CE->getRParenLoc())) 9552 return; 9553 9554 // Identify common expressions, which are wrongly used as the size argument 9555 // to strncat and may lead to buffer overflows. 9556 unsigned PatternType = 0; 9557 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9558 // - sizeof(dst) 9559 if (referToTheSameDecl(SizeOfArg, DstArg)) 9560 PatternType = 1; 9561 // - sizeof(src) 9562 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9563 PatternType = 2; 9564 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9565 if (BE->getOpcode() == BO_Sub) { 9566 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9567 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9568 // - sizeof(dst) - strlen(dst) 9569 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9570 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9571 PatternType = 1; 9572 // - sizeof(src) - (anything) 9573 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9574 PatternType = 2; 9575 } 9576 } 9577 9578 if (PatternType == 0) 9579 return; 9580 9581 // Generate the diagnostic. 9582 SourceLocation SL = LenArg->getBeginLoc(); 9583 SourceRange SR = LenArg->getSourceRange(); 9584 SourceManager &SM = getSourceManager(); 9585 9586 // If the function is defined as a builtin macro, do not show macro expansion. 9587 if (SM.isMacroArgExpansion(SL)) { 9588 SL = SM.getSpellingLoc(SL); 9589 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9590 SM.getSpellingLoc(SR.getEnd())); 9591 } 9592 9593 // Check if the destination is an array (rather than a pointer to an array). 9594 QualType DstTy = DstArg->getType(); 9595 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9596 Context); 9597 if (!isKnownSizeArray) { 9598 if (PatternType == 1) 9599 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9600 else 9601 Diag(SL, diag::warn_strncat_src_size) << SR; 9602 return; 9603 } 9604 9605 if (PatternType == 1) 9606 Diag(SL, diag::warn_strncat_large_size) << SR; 9607 else 9608 Diag(SL, diag::warn_strncat_src_size) << SR; 9609 9610 SmallString<128> sizeString; 9611 llvm::raw_svector_ostream OS(sizeString); 9612 OS << "sizeof("; 9613 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9614 OS << ") - "; 9615 OS << "strlen("; 9616 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9617 OS << ") - 1"; 9618 9619 Diag(SL, diag::note_strncat_wrong_size) 9620 << FixItHint::CreateReplacement(SR, OS.str()); 9621 } 9622 9623 void 9624 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9625 SourceLocation ReturnLoc, 9626 bool isObjCMethod, 9627 const AttrVec *Attrs, 9628 const FunctionDecl *FD) { 9629 // Check if the return value is null but should not be. 9630 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9631 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9632 CheckNonNullExpr(*this, RetValExp)) 9633 Diag(ReturnLoc, diag::warn_null_ret) 9634 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9635 9636 // C++11 [basic.stc.dynamic.allocation]p4: 9637 // If an allocation function declared with a non-throwing 9638 // exception-specification fails to allocate storage, it shall return 9639 // a null pointer. Any other allocation function that fails to allocate 9640 // storage shall indicate failure only by throwing an exception [...] 9641 if (FD) { 9642 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9643 if (Op == OO_New || Op == OO_Array_New) { 9644 const FunctionProtoType *Proto 9645 = FD->getType()->castAs<FunctionProtoType>(); 9646 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9647 CheckNonNullExpr(*this, RetValExp)) 9648 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9649 << FD << getLangOpts().CPlusPlus11; 9650 } 9651 } 9652 } 9653 9654 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9655 9656 /// Check for comparisons of floating point operands using != and ==. 9657 /// Issue a warning if these are no self-comparisons, as they are not likely 9658 /// to do what the programmer intended. 9659 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9660 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9661 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9662 9663 // Special case: check for x == x (which is OK). 9664 // Do not emit warnings for such cases. 9665 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9666 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9667 if (DRL->getDecl() == DRR->getDecl()) 9668 return; 9669 9670 // Special case: check for comparisons against literals that can be exactly 9671 // represented by APFloat. In such cases, do not emit a warning. This 9672 // is a heuristic: often comparison against such literals are used to 9673 // detect if a value in a variable has not changed. This clearly can 9674 // lead to false negatives. 9675 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9676 if (FLL->isExact()) 9677 return; 9678 } else 9679 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9680 if (FLR->isExact()) 9681 return; 9682 9683 // Check for comparisons with builtin types. 9684 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9685 if (CL->getBuiltinCallee()) 9686 return; 9687 9688 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9689 if (CR->getBuiltinCallee()) 9690 return; 9691 9692 // Emit the diagnostic. 9693 Diag(Loc, diag::warn_floatingpoint_eq) 9694 << LHS->getSourceRange() << RHS->getSourceRange(); 9695 } 9696 9697 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9698 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9699 9700 namespace { 9701 9702 /// Structure recording the 'active' range of an integer-valued 9703 /// expression. 9704 struct IntRange { 9705 /// The number of bits active in the int. 9706 unsigned Width; 9707 9708 /// True if the int is known not to have negative values. 9709 bool NonNegative; 9710 9711 IntRange(unsigned Width, bool NonNegative) 9712 : Width(Width), NonNegative(NonNegative) {} 9713 9714 /// Returns the range of the bool type. 9715 static IntRange forBoolType() { 9716 return IntRange(1, true); 9717 } 9718 9719 /// Returns the range of an opaque value of the given integral type. 9720 static IntRange forValueOfType(ASTContext &C, QualType T) { 9721 return forValueOfCanonicalType(C, 9722 T->getCanonicalTypeInternal().getTypePtr()); 9723 } 9724 9725 /// Returns the range of an opaque value of a canonical integral type. 9726 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9727 assert(T->isCanonicalUnqualified()); 9728 9729 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9730 T = VT->getElementType().getTypePtr(); 9731 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9732 T = CT->getElementType().getTypePtr(); 9733 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9734 T = AT->getValueType().getTypePtr(); 9735 9736 if (!C.getLangOpts().CPlusPlus) { 9737 // For enum types in C code, use the underlying datatype. 9738 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9739 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9740 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9741 // For enum types in C++, use the known bit width of the enumerators. 9742 EnumDecl *Enum = ET->getDecl(); 9743 // In C++11, enums can have a fixed underlying type. Use this type to 9744 // compute the range. 9745 if (Enum->isFixed()) { 9746 return IntRange(C.getIntWidth(QualType(T, 0)), 9747 !ET->isSignedIntegerOrEnumerationType()); 9748 } 9749 9750 unsigned NumPositive = Enum->getNumPositiveBits(); 9751 unsigned NumNegative = Enum->getNumNegativeBits(); 9752 9753 if (NumNegative == 0) 9754 return IntRange(NumPositive, true/*NonNegative*/); 9755 else 9756 return IntRange(std::max(NumPositive + 1, NumNegative), 9757 false/*NonNegative*/); 9758 } 9759 9760 const BuiltinType *BT = cast<BuiltinType>(T); 9761 assert(BT->isInteger()); 9762 9763 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9764 } 9765 9766 /// Returns the "target" range of a canonical integral type, i.e. 9767 /// the range of values expressible in the type. 9768 /// 9769 /// This matches forValueOfCanonicalType except that enums have the 9770 /// full range of their type, not the range of their enumerators. 9771 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9772 assert(T->isCanonicalUnqualified()); 9773 9774 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9775 T = VT->getElementType().getTypePtr(); 9776 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9777 T = CT->getElementType().getTypePtr(); 9778 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9779 T = AT->getValueType().getTypePtr(); 9780 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9781 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9782 9783 const BuiltinType *BT = cast<BuiltinType>(T); 9784 assert(BT->isInteger()); 9785 9786 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9787 } 9788 9789 /// Returns the supremum of two ranges: i.e. their conservative merge. 9790 static IntRange join(IntRange L, IntRange R) { 9791 return IntRange(std::max(L.Width, R.Width), 9792 L.NonNegative && R.NonNegative); 9793 } 9794 9795 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9796 static IntRange meet(IntRange L, IntRange R) { 9797 return IntRange(std::min(L.Width, R.Width), 9798 L.NonNegative || R.NonNegative); 9799 } 9800 }; 9801 9802 } // namespace 9803 9804 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9805 unsigned MaxWidth) { 9806 if (value.isSigned() && value.isNegative()) 9807 return IntRange(value.getMinSignedBits(), false); 9808 9809 if (value.getBitWidth() > MaxWidth) 9810 value = value.trunc(MaxWidth); 9811 9812 // isNonNegative() just checks the sign bit without considering 9813 // signedness. 9814 return IntRange(value.getActiveBits(), true); 9815 } 9816 9817 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9818 unsigned MaxWidth) { 9819 if (result.isInt()) 9820 return GetValueRange(C, result.getInt(), MaxWidth); 9821 9822 if (result.isVector()) { 9823 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9824 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9825 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9826 R = IntRange::join(R, El); 9827 } 9828 return R; 9829 } 9830 9831 if (result.isComplexInt()) { 9832 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9833 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9834 return IntRange::join(R, I); 9835 } 9836 9837 // This can happen with lossless casts to intptr_t of "based" lvalues. 9838 // Assume it might use arbitrary bits. 9839 // FIXME: The only reason we need to pass the type in here is to get 9840 // the sign right on this one case. It would be nice if APValue 9841 // preserved this. 9842 assert(result.isLValue() || result.isAddrLabelDiff()); 9843 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9844 } 9845 9846 static QualType GetExprType(const Expr *E) { 9847 QualType Ty = E->getType(); 9848 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9849 Ty = AtomicRHS->getValueType(); 9850 return Ty; 9851 } 9852 9853 /// Pseudo-evaluate the given integer expression, estimating the 9854 /// range of values it might take. 9855 /// 9856 /// \param MaxWidth - the width to which the value will be truncated 9857 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 9858 bool InConstantContext) { 9859 E = E->IgnoreParens(); 9860 9861 // Try a full evaluation first. 9862 Expr::EvalResult result; 9863 if (E->EvaluateAsRValue(result, C, InConstantContext)) 9864 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9865 9866 // I think we only want to look through implicit casts here; if the 9867 // user has an explicit widening cast, we should treat the value as 9868 // being of the new, wider type. 9869 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9870 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9871 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 9872 9873 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9874 9875 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9876 CE->getCastKind() == CK_BooleanToSignedIntegral; 9877 9878 // Assume that non-integer casts can span the full range of the type. 9879 if (!isIntegerCast) 9880 return OutputTypeRange; 9881 9882 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 9883 std::min(MaxWidth, OutputTypeRange.Width), 9884 InConstantContext); 9885 9886 // Bail out if the subexpr's range is as wide as the cast type. 9887 if (SubRange.Width >= OutputTypeRange.Width) 9888 return OutputTypeRange; 9889 9890 // Otherwise, we take the smaller width, and we're non-negative if 9891 // either the output type or the subexpr is. 9892 return IntRange(SubRange.Width, 9893 SubRange.NonNegative || OutputTypeRange.NonNegative); 9894 } 9895 9896 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9897 // If we can fold the condition, just take that operand. 9898 bool CondResult; 9899 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9900 return GetExprRange(C, 9901 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 9902 MaxWidth, InConstantContext); 9903 9904 // Otherwise, conservatively merge. 9905 IntRange L = 9906 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 9907 IntRange R = 9908 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 9909 return IntRange::join(L, R); 9910 } 9911 9912 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9913 switch (BO->getOpcode()) { 9914 case BO_Cmp: 9915 llvm_unreachable("builtin <=> should have class type"); 9916 9917 // Boolean-valued operations are single-bit and positive. 9918 case BO_LAnd: 9919 case BO_LOr: 9920 case BO_LT: 9921 case BO_GT: 9922 case BO_LE: 9923 case BO_GE: 9924 case BO_EQ: 9925 case BO_NE: 9926 return IntRange::forBoolType(); 9927 9928 // The type of the assignments is the type of the LHS, so the RHS 9929 // is not necessarily the same type. 9930 case BO_MulAssign: 9931 case BO_DivAssign: 9932 case BO_RemAssign: 9933 case BO_AddAssign: 9934 case BO_SubAssign: 9935 case BO_XorAssign: 9936 case BO_OrAssign: 9937 // TODO: bitfields? 9938 return IntRange::forValueOfType(C, GetExprType(E)); 9939 9940 // Simple assignments just pass through the RHS, which will have 9941 // been coerced to the LHS type. 9942 case BO_Assign: 9943 // TODO: bitfields? 9944 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 9945 9946 // Operations with opaque sources are black-listed. 9947 case BO_PtrMemD: 9948 case BO_PtrMemI: 9949 return IntRange::forValueOfType(C, GetExprType(E)); 9950 9951 // Bitwise-and uses the *infinum* of the two source ranges. 9952 case BO_And: 9953 case BO_AndAssign: 9954 return IntRange::meet( 9955 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 9956 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 9957 9958 // Left shift gets black-listed based on a judgement call. 9959 case BO_Shl: 9960 // ...except that we want to treat '1 << (blah)' as logically 9961 // positive. It's an important idiom. 9962 if (IntegerLiteral *I 9963 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9964 if (I->getValue() == 1) { 9965 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9966 return IntRange(R.Width, /*NonNegative*/ true); 9967 } 9968 } 9969 LLVM_FALLTHROUGH; 9970 9971 case BO_ShlAssign: 9972 return IntRange::forValueOfType(C, GetExprType(E)); 9973 9974 // Right shift by a constant can narrow its left argument. 9975 case BO_Shr: 9976 case BO_ShrAssign: { 9977 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 9978 9979 // If the shift amount is a positive constant, drop the width by 9980 // that much. 9981 llvm::APSInt shift; 9982 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9983 shift.isNonNegative()) { 9984 unsigned zext = shift.getZExtValue(); 9985 if (zext >= L.Width) 9986 L.Width = (L.NonNegative ? 0 : 1); 9987 else 9988 L.Width -= zext; 9989 } 9990 9991 return L; 9992 } 9993 9994 // Comma acts as its right operand. 9995 case BO_Comma: 9996 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 9997 9998 // Black-list pointer subtractions. 9999 case BO_Sub: 10000 if (BO->getLHS()->getType()->isPointerType()) 10001 return IntRange::forValueOfType(C, GetExprType(E)); 10002 break; 10003 10004 // The width of a division result is mostly determined by the size 10005 // of the LHS. 10006 case BO_Div: { 10007 // Don't 'pre-truncate' the operands. 10008 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10009 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10010 10011 // If the divisor is constant, use that. 10012 llvm::APSInt divisor; 10013 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 10014 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 10015 if (log2 >= L.Width) 10016 L.Width = (L.NonNegative ? 0 : 1); 10017 else 10018 L.Width = std::min(L.Width - log2, MaxWidth); 10019 return L; 10020 } 10021 10022 // Otherwise, just use the LHS's width. 10023 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10024 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10025 } 10026 10027 // The result of a remainder can't be larger than the result of 10028 // either side. 10029 case BO_Rem: { 10030 // Don't 'pre-truncate' the operands. 10031 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10032 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10033 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10034 10035 IntRange meet = IntRange::meet(L, R); 10036 meet.Width = std::min(meet.Width, MaxWidth); 10037 return meet; 10038 } 10039 10040 // The default behavior is okay for these. 10041 case BO_Mul: 10042 case BO_Add: 10043 case BO_Xor: 10044 case BO_Or: 10045 break; 10046 } 10047 10048 // The default case is to treat the operation as if it were closed 10049 // on the narrowest type that encompasses both operands. 10050 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10051 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10052 return IntRange::join(L, R); 10053 } 10054 10055 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10056 switch (UO->getOpcode()) { 10057 // Boolean-valued operations are white-listed. 10058 case UO_LNot: 10059 return IntRange::forBoolType(); 10060 10061 // Operations with opaque sources are black-listed. 10062 case UO_Deref: 10063 case UO_AddrOf: // should be impossible 10064 return IntRange::forValueOfType(C, GetExprType(E)); 10065 10066 default: 10067 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10068 } 10069 } 10070 10071 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10072 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10073 10074 if (const auto *BitField = E->getSourceBitField()) 10075 return IntRange(BitField->getBitWidthValue(C), 10076 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10077 10078 return IntRange::forValueOfType(C, GetExprType(E)); 10079 } 10080 10081 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10082 bool InConstantContext) { 10083 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10084 } 10085 10086 /// Checks whether the given value, which currently has the given 10087 /// source semantics, has the same value when coerced through the 10088 /// target semantics. 10089 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10090 const llvm::fltSemantics &Src, 10091 const llvm::fltSemantics &Tgt) { 10092 llvm::APFloat truncated = value; 10093 10094 bool ignored; 10095 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10096 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10097 10098 return truncated.bitwiseIsEqual(value); 10099 } 10100 10101 /// Checks whether the given value, which currently has the given 10102 /// source semantics, has the same value when coerced through the 10103 /// target semantics. 10104 /// 10105 /// The value might be a vector of floats (or a complex number). 10106 static bool IsSameFloatAfterCast(const APValue &value, 10107 const llvm::fltSemantics &Src, 10108 const llvm::fltSemantics &Tgt) { 10109 if (value.isFloat()) 10110 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10111 10112 if (value.isVector()) { 10113 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10114 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10115 return false; 10116 return true; 10117 } 10118 10119 assert(value.isComplexFloat()); 10120 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10121 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10122 } 10123 10124 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10125 bool IsListInit = false); 10126 10127 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10128 // Suppress cases where we are comparing against an enum constant. 10129 if (const DeclRefExpr *DR = 10130 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10131 if (isa<EnumConstantDecl>(DR->getDecl())) 10132 return true; 10133 10134 // Suppress cases where the value is expanded from a macro, unless that macro 10135 // is how a language represents a boolean literal. This is the case in both C 10136 // and Objective-C. 10137 SourceLocation BeginLoc = E->getBeginLoc(); 10138 if (BeginLoc.isMacroID()) { 10139 StringRef MacroName = Lexer::getImmediateMacroName( 10140 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10141 return MacroName != "YES" && MacroName != "NO" && 10142 MacroName != "true" && MacroName != "false"; 10143 } 10144 10145 return false; 10146 } 10147 10148 static bool isKnownToHaveUnsignedValue(Expr *E) { 10149 return E->getType()->isIntegerType() && 10150 (!E->getType()->isSignedIntegerType() || 10151 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10152 } 10153 10154 namespace { 10155 /// The promoted range of values of a type. In general this has the 10156 /// following structure: 10157 /// 10158 /// |-----------| . . . |-----------| 10159 /// ^ ^ ^ ^ 10160 /// Min HoleMin HoleMax Max 10161 /// 10162 /// ... where there is only a hole if a signed type is promoted to unsigned 10163 /// (in which case Min and Max are the smallest and largest representable 10164 /// values). 10165 struct PromotedRange { 10166 // Min, or HoleMax if there is a hole. 10167 llvm::APSInt PromotedMin; 10168 // Max, or HoleMin if there is a hole. 10169 llvm::APSInt PromotedMax; 10170 10171 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10172 if (R.Width == 0) 10173 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10174 else if (R.Width >= BitWidth && !Unsigned) { 10175 // Promotion made the type *narrower*. This happens when promoting 10176 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10177 // Treat all values of 'signed int' as being in range for now. 10178 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10179 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10180 } else { 10181 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10182 .extOrTrunc(BitWidth); 10183 PromotedMin.setIsUnsigned(Unsigned); 10184 10185 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10186 .extOrTrunc(BitWidth); 10187 PromotedMax.setIsUnsigned(Unsigned); 10188 } 10189 } 10190 10191 // Determine whether this range is contiguous (has no hole). 10192 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10193 10194 // Where a constant value is within the range. 10195 enum ComparisonResult { 10196 LT = 0x1, 10197 LE = 0x2, 10198 GT = 0x4, 10199 GE = 0x8, 10200 EQ = 0x10, 10201 NE = 0x20, 10202 InRangeFlag = 0x40, 10203 10204 Less = LE | LT | NE, 10205 Min = LE | InRangeFlag, 10206 InRange = InRangeFlag, 10207 Max = GE | InRangeFlag, 10208 Greater = GE | GT | NE, 10209 10210 OnlyValue = LE | GE | EQ | InRangeFlag, 10211 InHole = NE 10212 }; 10213 10214 ComparisonResult compare(const llvm::APSInt &Value) const { 10215 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10216 Value.isUnsigned() == PromotedMin.isUnsigned()); 10217 if (!isContiguous()) { 10218 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10219 if (Value.isMinValue()) return Min; 10220 if (Value.isMaxValue()) return Max; 10221 if (Value >= PromotedMin) return InRange; 10222 if (Value <= PromotedMax) return InRange; 10223 return InHole; 10224 } 10225 10226 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10227 case -1: return Less; 10228 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10229 case 1: 10230 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10231 case -1: return InRange; 10232 case 0: return Max; 10233 case 1: return Greater; 10234 } 10235 } 10236 10237 llvm_unreachable("impossible compare result"); 10238 } 10239 10240 static llvm::Optional<StringRef> 10241 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10242 if (Op == BO_Cmp) { 10243 ComparisonResult LTFlag = LT, GTFlag = GT; 10244 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10245 10246 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10247 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10248 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10249 return llvm::None; 10250 } 10251 10252 ComparisonResult TrueFlag, FalseFlag; 10253 if (Op == BO_EQ) { 10254 TrueFlag = EQ; 10255 FalseFlag = NE; 10256 } else if (Op == BO_NE) { 10257 TrueFlag = NE; 10258 FalseFlag = EQ; 10259 } else { 10260 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10261 TrueFlag = LT; 10262 FalseFlag = GE; 10263 } else { 10264 TrueFlag = GT; 10265 FalseFlag = LE; 10266 } 10267 if (Op == BO_GE || Op == BO_LE) 10268 std::swap(TrueFlag, FalseFlag); 10269 } 10270 if (R & TrueFlag) 10271 return StringRef("true"); 10272 if (R & FalseFlag) 10273 return StringRef("false"); 10274 return llvm::None; 10275 } 10276 }; 10277 } 10278 10279 static bool HasEnumType(Expr *E) { 10280 // Strip off implicit integral promotions. 10281 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10282 if (ICE->getCastKind() != CK_IntegralCast && 10283 ICE->getCastKind() != CK_NoOp) 10284 break; 10285 E = ICE->getSubExpr(); 10286 } 10287 10288 return E->getType()->isEnumeralType(); 10289 } 10290 10291 static int classifyConstantValue(Expr *Constant) { 10292 // The values of this enumeration are used in the diagnostics 10293 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10294 enum ConstantValueKind { 10295 Miscellaneous = 0, 10296 LiteralTrue, 10297 LiteralFalse 10298 }; 10299 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10300 return BL->getValue() ? ConstantValueKind::LiteralTrue 10301 : ConstantValueKind::LiteralFalse; 10302 return ConstantValueKind::Miscellaneous; 10303 } 10304 10305 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10306 Expr *Constant, Expr *Other, 10307 const llvm::APSInt &Value, 10308 bool RhsConstant) { 10309 if (S.inTemplateInstantiation()) 10310 return false; 10311 10312 Expr *OriginalOther = Other; 10313 10314 Constant = Constant->IgnoreParenImpCasts(); 10315 Other = Other->IgnoreParenImpCasts(); 10316 10317 // Suppress warnings on tautological comparisons between values of the same 10318 // enumeration type. There are only two ways we could warn on this: 10319 // - If the constant is outside the range of representable values of 10320 // the enumeration. In such a case, we should warn about the cast 10321 // to enumeration type, not about the comparison. 10322 // - If the constant is the maximum / minimum in-range value. For an 10323 // enumeratin type, such comparisons can be meaningful and useful. 10324 if (Constant->getType()->isEnumeralType() && 10325 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10326 return false; 10327 10328 // TODO: Investigate using GetExprRange() to get tighter bounds 10329 // on the bit ranges. 10330 QualType OtherT = Other->getType(); 10331 if (const auto *AT = OtherT->getAs<AtomicType>()) 10332 OtherT = AT->getValueType(); 10333 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10334 10335 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10336 // (Namely, macOS). 10337 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10338 S.NSAPIObj->isObjCBOOLType(OtherT) && 10339 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10340 10341 // Whether we're treating Other as being a bool because of the form of 10342 // expression despite it having another type (typically 'int' in C). 10343 bool OtherIsBooleanDespiteType = 10344 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10345 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10346 OtherRange = IntRange::forBoolType(); 10347 10348 // Determine the promoted range of the other type and see if a comparison of 10349 // the constant against that range is tautological. 10350 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10351 Value.isUnsigned()); 10352 auto Cmp = OtherPromotedRange.compare(Value); 10353 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10354 if (!Result) 10355 return false; 10356 10357 // Suppress the diagnostic for an in-range comparison if the constant comes 10358 // from a macro or enumerator. We don't want to diagnose 10359 // 10360 // some_long_value <= INT_MAX 10361 // 10362 // when sizeof(int) == sizeof(long). 10363 bool InRange = Cmp & PromotedRange::InRangeFlag; 10364 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10365 return false; 10366 10367 // If this is a comparison to an enum constant, include that 10368 // constant in the diagnostic. 10369 const EnumConstantDecl *ED = nullptr; 10370 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10371 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10372 10373 // Should be enough for uint128 (39 decimal digits) 10374 SmallString<64> PrettySourceValue; 10375 llvm::raw_svector_ostream OS(PrettySourceValue); 10376 if (ED) { 10377 OS << '\'' << *ED << "' (" << Value << ")"; 10378 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10379 Constant->IgnoreParenImpCasts())) { 10380 OS << (BL->getValue() ? "YES" : "NO"); 10381 } else { 10382 OS << Value; 10383 } 10384 10385 if (IsObjCSignedCharBool) { 10386 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10387 S.PDiag(diag::warn_tautological_compare_objc_bool) 10388 << OS.str() << *Result); 10389 return true; 10390 } 10391 10392 // FIXME: We use a somewhat different formatting for the in-range cases and 10393 // cases involving boolean values for historical reasons. We should pick a 10394 // consistent way of presenting these diagnostics. 10395 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10396 10397 S.DiagRuntimeBehavior( 10398 E->getOperatorLoc(), E, 10399 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10400 : diag::warn_tautological_bool_compare) 10401 << OS.str() << classifyConstantValue(Constant) << OtherT 10402 << OtherIsBooleanDespiteType << *Result 10403 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10404 } else { 10405 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10406 ? (HasEnumType(OriginalOther) 10407 ? diag::warn_unsigned_enum_always_true_comparison 10408 : diag::warn_unsigned_always_true_comparison) 10409 : diag::warn_tautological_constant_compare; 10410 10411 S.Diag(E->getOperatorLoc(), Diag) 10412 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10413 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10414 } 10415 10416 return true; 10417 } 10418 10419 /// Analyze the operands of the given comparison. Implements the 10420 /// fallback case from AnalyzeComparison. 10421 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10422 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10423 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10424 } 10425 10426 /// Implements -Wsign-compare. 10427 /// 10428 /// \param E the binary operator to check for warnings 10429 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10430 // The type the comparison is being performed in. 10431 QualType T = E->getLHS()->getType(); 10432 10433 // Only analyze comparison operators where both sides have been converted to 10434 // the same type. 10435 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10436 return AnalyzeImpConvsInComparison(S, E); 10437 10438 // Don't analyze value-dependent comparisons directly. 10439 if (E->isValueDependent()) 10440 return AnalyzeImpConvsInComparison(S, E); 10441 10442 Expr *LHS = E->getLHS(); 10443 Expr *RHS = E->getRHS(); 10444 10445 if (T->isIntegralType(S.Context)) { 10446 llvm::APSInt RHSValue; 10447 llvm::APSInt LHSValue; 10448 10449 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10450 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10451 10452 // We don't care about expressions whose result is a constant. 10453 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10454 return AnalyzeImpConvsInComparison(S, E); 10455 10456 // We only care about expressions where just one side is literal 10457 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10458 // Is the constant on the RHS or LHS? 10459 const bool RhsConstant = IsRHSIntegralLiteral; 10460 Expr *Const = RhsConstant ? RHS : LHS; 10461 Expr *Other = RhsConstant ? LHS : RHS; 10462 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10463 10464 // Check whether an integer constant comparison results in a value 10465 // of 'true' or 'false'. 10466 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10467 return AnalyzeImpConvsInComparison(S, E); 10468 } 10469 } 10470 10471 if (!T->hasUnsignedIntegerRepresentation()) { 10472 // We don't do anything special if this isn't an unsigned integral 10473 // comparison: we're only interested in integral comparisons, and 10474 // signed comparisons only happen in cases we don't care to warn about. 10475 return AnalyzeImpConvsInComparison(S, E); 10476 } 10477 10478 LHS = LHS->IgnoreParenImpCasts(); 10479 RHS = RHS->IgnoreParenImpCasts(); 10480 10481 if (!S.getLangOpts().CPlusPlus) { 10482 // Avoid warning about comparison of integers with different signs when 10483 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10484 // the type of `E`. 10485 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10486 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10487 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10488 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10489 } 10490 10491 // Check to see if one of the (unmodified) operands is of different 10492 // signedness. 10493 Expr *signedOperand, *unsignedOperand; 10494 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10495 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10496 "unsigned comparison between two signed integer expressions?"); 10497 signedOperand = LHS; 10498 unsignedOperand = RHS; 10499 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10500 signedOperand = RHS; 10501 unsignedOperand = LHS; 10502 } else { 10503 return AnalyzeImpConvsInComparison(S, E); 10504 } 10505 10506 // Otherwise, calculate the effective range of the signed operand. 10507 IntRange signedRange = 10508 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10509 10510 // Go ahead and analyze implicit conversions in the operands. Note 10511 // that we skip the implicit conversions on both sides. 10512 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10513 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10514 10515 // If the signed range is non-negative, -Wsign-compare won't fire. 10516 if (signedRange.NonNegative) 10517 return; 10518 10519 // For (in)equality comparisons, if the unsigned operand is a 10520 // constant which cannot collide with a overflowed signed operand, 10521 // then reinterpreting the signed operand as unsigned will not 10522 // change the result of the comparison. 10523 if (E->isEqualityOp()) { 10524 unsigned comparisonWidth = S.Context.getIntWidth(T); 10525 IntRange unsignedRange = 10526 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10527 10528 // We should never be unable to prove that the unsigned operand is 10529 // non-negative. 10530 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10531 10532 if (unsignedRange.Width < comparisonWidth) 10533 return; 10534 } 10535 10536 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10537 S.PDiag(diag::warn_mixed_sign_comparison) 10538 << LHS->getType() << RHS->getType() 10539 << LHS->getSourceRange() << RHS->getSourceRange()); 10540 } 10541 10542 /// Analyzes an attempt to assign the given value to a bitfield. 10543 /// 10544 /// Returns true if there was something fishy about the attempt. 10545 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10546 SourceLocation InitLoc) { 10547 assert(Bitfield->isBitField()); 10548 if (Bitfield->isInvalidDecl()) 10549 return false; 10550 10551 // White-list bool bitfields. 10552 QualType BitfieldType = Bitfield->getType(); 10553 if (BitfieldType->isBooleanType()) 10554 return false; 10555 10556 if (BitfieldType->isEnumeralType()) { 10557 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10558 // If the underlying enum type was not explicitly specified as an unsigned 10559 // type and the enum contain only positive values, MSVC++ will cause an 10560 // inconsistency by storing this as a signed type. 10561 if (S.getLangOpts().CPlusPlus11 && 10562 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10563 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10564 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10565 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10566 << BitfieldEnumDecl->getNameAsString(); 10567 } 10568 } 10569 10570 if (Bitfield->getType()->isBooleanType()) 10571 return false; 10572 10573 // Ignore value- or type-dependent expressions. 10574 if (Bitfield->getBitWidth()->isValueDependent() || 10575 Bitfield->getBitWidth()->isTypeDependent() || 10576 Init->isValueDependent() || 10577 Init->isTypeDependent()) 10578 return false; 10579 10580 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10581 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10582 10583 Expr::EvalResult Result; 10584 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10585 Expr::SE_AllowSideEffects)) { 10586 // The RHS is not constant. If the RHS has an enum type, make sure the 10587 // bitfield is wide enough to hold all the values of the enum without 10588 // truncation. 10589 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10590 EnumDecl *ED = EnumTy->getDecl(); 10591 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10592 10593 // Enum types are implicitly signed on Windows, so check if there are any 10594 // negative enumerators to see if the enum was intended to be signed or 10595 // not. 10596 bool SignedEnum = ED->getNumNegativeBits() > 0; 10597 10598 // Check for surprising sign changes when assigning enum values to a 10599 // bitfield of different signedness. If the bitfield is signed and we 10600 // have exactly the right number of bits to store this unsigned enum, 10601 // suggest changing the enum to an unsigned type. This typically happens 10602 // on Windows where unfixed enums always use an underlying type of 'int'. 10603 unsigned DiagID = 0; 10604 if (SignedEnum && !SignedBitfield) { 10605 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10606 } else if (SignedBitfield && !SignedEnum && 10607 ED->getNumPositiveBits() == FieldWidth) { 10608 DiagID = diag::warn_signed_bitfield_enum_conversion; 10609 } 10610 10611 if (DiagID) { 10612 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10613 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10614 SourceRange TypeRange = 10615 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10616 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10617 << SignedEnum << TypeRange; 10618 } 10619 10620 // Compute the required bitwidth. If the enum has negative values, we need 10621 // one more bit than the normal number of positive bits to represent the 10622 // sign bit. 10623 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10624 ED->getNumNegativeBits()) 10625 : ED->getNumPositiveBits(); 10626 10627 // Check the bitwidth. 10628 if (BitsNeeded > FieldWidth) { 10629 Expr *WidthExpr = Bitfield->getBitWidth(); 10630 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10631 << Bitfield << ED; 10632 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10633 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10634 } 10635 } 10636 10637 return false; 10638 } 10639 10640 llvm::APSInt Value = Result.Val.getInt(); 10641 10642 unsigned OriginalWidth = Value.getBitWidth(); 10643 10644 if (!Value.isSigned() || Value.isNegative()) 10645 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10646 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10647 OriginalWidth = Value.getMinSignedBits(); 10648 10649 if (OriginalWidth <= FieldWidth) 10650 return false; 10651 10652 // Compute the value which the bitfield will contain. 10653 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10654 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10655 10656 // Check whether the stored value is equal to the original value. 10657 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10658 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10659 return false; 10660 10661 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10662 // therefore don't strictly fit into a signed bitfield of width 1. 10663 if (FieldWidth == 1 && Value == 1) 10664 return false; 10665 10666 std::string PrettyValue = Value.toString(10); 10667 std::string PrettyTrunc = TruncatedValue.toString(10); 10668 10669 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10670 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10671 << Init->getSourceRange(); 10672 10673 return true; 10674 } 10675 10676 /// Analyze the given simple or compound assignment for warning-worthy 10677 /// operations. 10678 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10679 // Just recurse on the LHS. 10680 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10681 10682 // We want to recurse on the RHS as normal unless we're assigning to 10683 // a bitfield. 10684 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10685 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10686 E->getOperatorLoc())) { 10687 // Recurse, ignoring any implicit conversions on the RHS. 10688 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10689 E->getOperatorLoc()); 10690 } 10691 } 10692 10693 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10694 10695 // Diagnose implicitly sequentially-consistent atomic assignment. 10696 if (E->getLHS()->getType()->isAtomicType()) 10697 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10698 } 10699 10700 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10701 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10702 SourceLocation CContext, unsigned diag, 10703 bool pruneControlFlow = false) { 10704 if (pruneControlFlow) { 10705 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10706 S.PDiag(diag) 10707 << SourceType << T << E->getSourceRange() 10708 << SourceRange(CContext)); 10709 return; 10710 } 10711 S.Diag(E->getExprLoc(), diag) 10712 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10713 } 10714 10715 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10716 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10717 SourceLocation CContext, 10718 unsigned diag, bool pruneControlFlow = false) { 10719 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10720 } 10721 10722 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 10723 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 10724 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 10725 } 10726 10727 static void adornObjCBoolConversionDiagWithTernaryFixit( 10728 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 10729 Expr *Ignored = SourceExpr->IgnoreImplicit(); 10730 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 10731 Ignored = OVE->getSourceExpr(); 10732 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 10733 isa<BinaryOperator>(Ignored) || 10734 isa<CXXOperatorCallExpr>(Ignored); 10735 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 10736 if (NeedsParens) 10737 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 10738 << FixItHint::CreateInsertion(EndLoc, ")"); 10739 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 10740 } 10741 10742 /// Diagnose an implicit cast from a floating point value to an integer value. 10743 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10744 SourceLocation CContext) { 10745 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10746 const bool PruneWarnings = S.inTemplateInstantiation(); 10747 10748 Expr *InnerE = E->IgnoreParenImpCasts(); 10749 // We also want to warn on, e.g., "int i = -1.234" 10750 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10751 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10752 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10753 10754 const bool IsLiteral = 10755 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10756 10757 llvm::APFloat Value(0.0); 10758 bool IsConstant = 10759 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10760 if (!IsConstant) { 10761 if (isObjCSignedCharBool(S, T)) { 10762 return adornObjCBoolConversionDiagWithTernaryFixit( 10763 S, E, 10764 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 10765 << E->getType()); 10766 } 10767 10768 return DiagnoseImpCast(S, E, T, CContext, 10769 diag::warn_impcast_float_integer, PruneWarnings); 10770 } 10771 10772 bool isExact = false; 10773 10774 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10775 T->hasUnsignedIntegerRepresentation()); 10776 llvm::APFloat::opStatus Result = Value.convertToInteger( 10777 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10778 10779 // FIXME: Force the precision of the source value down so we don't print 10780 // digits which are usually useless (we don't really care here if we 10781 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10782 // would automatically print the shortest representation, but it's a bit 10783 // tricky to implement. 10784 SmallString<16> PrettySourceValue; 10785 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10786 precision = (precision * 59 + 195) / 196; 10787 Value.toString(PrettySourceValue, precision); 10788 10789 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 10790 return adornObjCBoolConversionDiagWithTernaryFixit( 10791 S, E, 10792 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 10793 << PrettySourceValue); 10794 } 10795 10796 if (Result == llvm::APFloat::opOK && isExact) { 10797 if (IsLiteral) return; 10798 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10799 PruneWarnings); 10800 } 10801 10802 // Conversion of a floating-point value to a non-bool integer where the 10803 // integral part cannot be represented by the integer type is undefined. 10804 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10805 return DiagnoseImpCast( 10806 S, E, T, CContext, 10807 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10808 : diag::warn_impcast_float_to_integer_out_of_range, 10809 PruneWarnings); 10810 10811 unsigned DiagID = 0; 10812 if (IsLiteral) { 10813 // Warn on floating point literal to integer. 10814 DiagID = diag::warn_impcast_literal_float_to_integer; 10815 } else if (IntegerValue == 0) { 10816 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10817 return DiagnoseImpCast(S, E, T, CContext, 10818 diag::warn_impcast_float_integer, PruneWarnings); 10819 } 10820 // Warn on non-zero to zero conversion. 10821 DiagID = diag::warn_impcast_float_to_integer_zero; 10822 } else { 10823 if (IntegerValue.isUnsigned()) { 10824 if (!IntegerValue.isMaxValue()) { 10825 return DiagnoseImpCast(S, E, T, CContext, 10826 diag::warn_impcast_float_integer, PruneWarnings); 10827 } 10828 } else { // IntegerValue.isSigned() 10829 if (!IntegerValue.isMaxSignedValue() && 10830 !IntegerValue.isMinSignedValue()) { 10831 return DiagnoseImpCast(S, E, T, CContext, 10832 diag::warn_impcast_float_integer, PruneWarnings); 10833 } 10834 } 10835 // Warn on evaluatable floating point expression to integer conversion. 10836 DiagID = diag::warn_impcast_float_to_integer; 10837 } 10838 10839 SmallString<16> PrettyTargetValue; 10840 if (IsBool) 10841 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10842 else 10843 IntegerValue.toString(PrettyTargetValue); 10844 10845 if (PruneWarnings) { 10846 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10847 S.PDiag(DiagID) 10848 << E->getType() << T.getUnqualifiedType() 10849 << PrettySourceValue << PrettyTargetValue 10850 << E->getSourceRange() << SourceRange(CContext)); 10851 } else { 10852 S.Diag(E->getExprLoc(), DiagID) 10853 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10854 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10855 } 10856 } 10857 10858 /// Analyze the given compound assignment for the possible losing of 10859 /// floating-point precision. 10860 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10861 assert(isa<CompoundAssignOperator>(E) && 10862 "Must be compound assignment operation"); 10863 // Recurse on the LHS and RHS in here 10864 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10865 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10866 10867 if (E->getLHS()->getType()->isAtomicType()) 10868 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10869 10870 // Now check the outermost expression 10871 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10872 const auto *RBT = cast<CompoundAssignOperator>(E) 10873 ->getComputationResultType() 10874 ->getAs<BuiltinType>(); 10875 10876 // The below checks assume source is floating point. 10877 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10878 10879 // If source is floating point but target is an integer. 10880 if (ResultBT->isInteger()) 10881 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 10882 E->getExprLoc(), diag::warn_impcast_float_integer); 10883 10884 if (!ResultBT->isFloatingPoint()) 10885 return; 10886 10887 // If both source and target are floating points, warn about losing precision. 10888 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 10889 QualType(ResultBT, 0), QualType(RBT, 0)); 10890 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10891 // warn about dropping FP rank. 10892 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10893 diag::warn_impcast_float_result_precision); 10894 } 10895 10896 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10897 IntRange Range) { 10898 if (!Range.Width) return "0"; 10899 10900 llvm::APSInt ValueInRange = Value; 10901 ValueInRange.setIsSigned(!Range.NonNegative); 10902 ValueInRange = ValueInRange.trunc(Range.Width); 10903 return ValueInRange.toString(10); 10904 } 10905 10906 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10907 if (!isa<ImplicitCastExpr>(Ex)) 10908 return false; 10909 10910 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10911 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10912 const Type *Source = 10913 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10914 if (Target->isDependentType()) 10915 return false; 10916 10917 const BuiltinType *FloatCandidateBT = 10918 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10919 const Type *BoolCandidateType = ToBool ? Target : Source; 10920 10921 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10922 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10923 } 10924 10925 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10926 SourceLocation CC) { 10927 unsigned NumArgs = TheCall->getNumArgs(); 10928 for (unsigned i = 0; i < NumArgs; ++i) { 10929 Expr *CurrA = TheCall->getArg(i); 10930 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10931 continue; 10932 10933 bool IsSwapped = ((i > 0) && 10934 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10935 IsSwapped |= ((i < (NumArgs - 1)) && 10936 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10937 if (IsSwapped) { 10938 // Warn on this floating-point to bool conversion. 10939 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10940 CurrA->getType(), CC, 10941 diag::warn_impcast_floating_point_to_bool); 10942 } 10943 } 10944 } 10945 10946 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10947 SourceLocation CC) { 10948 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10949 E->getExprLoc())) 10950 return; 10951 10952 // Don't warn on functions which have return type nullptr_t. 10953 if (isa<CallExpr>(E)) 10954 return; 10955 10956 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10957 const Expr::NullPointerConstantKind NullKind = 10958 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10959 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10960 return; 10961 10962 // Return if target type is a safe conversion. 10963 if (T->isAnyPointerType() || T->isBlockPointerType() || 10964 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 10965 return; 10966 10967 SourceLocation Loc = E->getSourceRange().getBegin(); 10968 10969 // Venture through the macro stacks to get to the source of macro arguments. 10970 // The new location is a better location than the complete location that was 10971 // passed in. 10972 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10973 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10974 10975 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10976 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10977 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10978 Loc, S.SourceMgr, S.getLangOpts()); 10979 if (MacroName == "NULL") 10980 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10981 } 10982 10983 // Only warn if the null and context location are in the same macro expansion. 10984 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10985 return; 10986 10987 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10988 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10989 << FixItHint::CreateReplacement(Loc, 10990 S.getFixItZeroLiteralForType(T, Loc)); 10991 } 10992 10993 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10994 ObjCArrayLiteral *ArrayLiteral); 10995 10996 static void 10997 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10998 ObjCDictionaryLiteral *DictionaryLiteral); 10999 11000 /// Check a single element within a collection literal against the 11001 /// target element type. 11002 static void checkObjCCollectionLiteralElement(Sema &S, 11003 QualType TargetElementType, 11004 Expr *Element, 11005 unsigned ElementKind) { 11006 // Skip a bitcast to 'id' or qualified 'id'. 11007 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11008 if (ICE->getCastKind() == CK_BitCast && 11009 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11010 Element = ICE->getSubExpr(); 11011 } 11012 11013 QualType ElementType = Element->getType(); 11014 ExprResult ElementResult(Element); 11015 if (ElementType->getAs<ObjCObjectPointerType>() && 11016 S.CheckSingleAssignmentConstraints(TargetElementType, 11017 ElementResult, 11018 false, false) 11019 != Sema::Compatible) { 11020 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11021 << ElementType << ElementKind << TargetElementType 11022 << Element->getSourceRange(); 11023 } 11024 11025 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11026 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11027 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11028 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11029 } 11030 11031 /// Check an Objective-C array literal being converted to the given 11032 /// target type. 11033 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11034 ObjCArrayLiteral *ArrayLiteral) { 11035 if (!S.NSArrayDecl) 11036 return; 11037 11038 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11039 if (!TargetObjCPtr) 11040 return; 11041 11042 if (TargetObjCPtr->isUnspecialized() || 11043 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11044 != S.NSArrayDecl->getCanonicalDecl()) 11045 return; 11046 11047 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11048 if (TypeArgs.size() != 1) 11049 return; 11050 11051 QualType TargetElementType = TypeArgs[0]; 11052 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11053 checkObjCCollectionLiteralElement(S, TargetElementType, 11054 ArrayLiteral->getElement(I), 11055 0); 11056 } 11057 } 11058 11059 /// Check an Objective-C dictionary literal being converted to the given 11060 /// target type. 11061 static void 11062 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11063 ObjCDictionaryLiteral *DictionaryLiteral) { 11064 if (!S.NSDictionaryDecl) 11065 return; 11066 11067 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11068 if (!TargetObjCPtr) 11069 return; 11070 11071 if (TargetObjCPtr->isUnspecialized() || 11072 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11073 != S.NSDictionaryDecl->getCanonicalDecl()) 11074 return; 11075 11076 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11077 if (TypeArgs.size() != 2) 11078 return; 11079 11080 QualType TargetKeyType = TypeArgs[0]; 11081 QualType TargetObjectType = TypeArgs[1]; 11082 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11083 auto Element = DictionaryLiteral->getKeyValueElement(I); 11084 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11085 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11086 } 11087 } 11088 11089 // Helper function to filter out cases for constant width constant conversion. 11090 // Don't warn on char array initialization or for non-decimal values. 11091 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11092 SourceLocation CC) { 11093 // If initializing from a constant, and the constant starts with '0', 11094 // then it is a binary, octal, or hexadecimal. Allow these constants 11095 // to fill all the bits, even if there is a sign change. 11096 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11097 const char FirstLiteralCharacter = 11098 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11099 if (FirstLiteralCharacter == '0') 11100 return false; 11101 } 11102 11103 // If the CC location points to a '{', and the type is char, then assume 11104 // assume it is an array initialization. 11105 if (CC.isValid() && T->isCharType()) { 11106 const char FirstContextCharacter = 11107 S.getSourceManager().getCharacterData(CC)[0]; 11108 if (FirstContextCharacter == '{') 11109 return false; 11110 } 11111 11112 return true; 11113 } 11114 11115 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11116 const auto *IL = dyn_cast<IntegerLiteral>(E); 11117 if (!IL) { 11118 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11119 if (UO->getOpcode() == UO_Minus) 11120 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11121 } 11122 } 11123 11124 return IL; 11125 } 11126 11127 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11128 E = E->IgnoreParenImpCasts(); 11129 SourceLocation ExprLoc = E->getExprLoc(); 11130 11131 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11132 BinaryOperator::Opcode Opc = BO->getOpcode(); 11133 Expr::EvalResult Result; 11134 // Do not diagnose unsigned shifts. 11135 if (Opc == BO_Shl) { 11136 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11137 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11138 if (LHS && LHS->getValue() == 0) 11139 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11140 else if (!E->isValueDependent() && LHS && RHS && 11141 RHS->getValue().isNonNegative() && 11142 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11143 S.Diag(ExprLoc, diag::warn_left_shift_always) 11144 << (Result.Val.getInt() != 0); 11145 else if (E->getType()->isSignedIntegerType()) 11146 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11147 } 11148 } 11149 11150 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11151 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11152 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11153 if (!LHS || !RHS) 11154 return; 11155 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11156 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11157 // Do not diagnose common idioms. 11158 return; 11159 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11160 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11161 } 11162 } 11163 11164 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11165 SourceLocation CC, 11166 bool *ICContext = nullptr, 11167 bool IsListInit = false) { 11168 if (E->isTypeDependent() || E->isValueDependent()) return; 11169 11170 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11171 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11172 if (Source == Target) return; 11173 if (Target->isDependentType()) return; 11174 11175 // If the conversion context location is invalid don't complain. We also 11176 // don't want to emit a warning if the issue occurs from the expansion of 11177 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11178 // delay this check as long as possible. Once we detect we are in that 11179 // scenario, we just return. 11180 if (CC.isInvalid()) 11181 return; 11182 11183 if (Source->isAtomicType()) 11184 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11185 11186 // Diagnose implicit casts to bool. 11187 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11188 if (isa<StringLiteral>(E)) 11189 // Warn on string literal to bool. Checks for string literals in logical 11190 // and expressions, for instance, assert(0 && "error here"), are 11191 // prevented by a check in AnalyzeImplicitConversions(). 11192 return DiagnoseImpCast(S, E, T, CC, 11193 diag::warn_impcast_string_literal_to_bool); 11194 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11195 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11196 // This covers the literal expressions that evaluate to Objective-C 11197 // objects. 11198 return DiagnoseImpCast(S, E, T, CC, 11199 diag::warn_impcast_objective_c_literal_to_bool); 11200 } 11201 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11202 // Warn on pointer to bool conversion that is always true. 11203 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11204 SourceRange(CC)); 11205 } 11206 } 11207 11208 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11209 // is a typedef for signed char (macOS), then that constant value has to be 1 11210 // or 0. 11211 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11212 Expr::EvalResult Result; 11213 if (E->EvaluateAsInt(Result, S.getASTContext(), 11214 Expr::SE_AllowSideEffects)) { 11215 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11216 adornObjCBoolConversionDiagWithTernaryFixit( 11217 S, E, 11218 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11219 << Result.Val.getInt().toString(10)); 11220 } 11221 return; 11222 } 11223 } 11224 11225 // Check implicit casts from Objective-C collection literals to specialized 11226 // collection types, e.g., NSArray<NSString *> *. 11227 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11228 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11229 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11230 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11231 11232 // Strip vector types. 11233 if (isa<VectorType>(Source)) { 11234 if (!isa<VectorType>(Target)) { 11235 if (S.SourceMgr.isInSystemMacro(CC)) 11236 return; 11237 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11238 } 11239 11240 // If the vector cast is cast between two vectors of the same size, it is 11241 // a bitcast, not a conversion. 11242 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11243 return; 11244 11245 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11246 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11247 } 11248 if (auto VecTy = dyn_cast<VectorType>(Target)) 11249 Target = VecTy->getElementType().getTypePtr(); 11250 11251 // Strip complex types. 11252 if (isa<ComplexType>(Source)) { 11253 if (!isa<ComplexType>(Target)) { 11254 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11255 return; 11256 11257 return DiagnoseImpCast(S, E, T, CC, 11258 S.getLangOpts().CPlusPlus 11259 ? diag::err_impcast_complex_scalar 11260 : diag::warn_impcast_complex_scalar); 11261 } 11262 11263 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11264 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11265 } 11266 11267 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11268 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11269 11270 // If the source is floating point... 11271 if (SourceBT && SourceBT->isFloatingPoint()) { 11272 // ...and the target is floating point... 11273 if (TargetBT && TargetBT->isFloatingPoint()) { 11274 // ...then warn if we're dropping FP rank. 11275 11276 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11277 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11278 if (Order > 0) { 11279 // Don't warn about float constants that are precisely 11280 // representable in the target type. 11281 Expr::EvalResult result; 11282 if (E->EvaluateAsRValue(result, S.Context)) { 11283 // Value might be a float, a float vector, or a float complex. 11284 if (IsSameFloatAfterCast(result.Val, 11285 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11286 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11287 return; 11288 } 11289 11290 if (S.SourceMgr.isInSystemMacro(CC)) 11291 return; 11292 11293 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11294 } 11295 // ... or possibly if we're increasing rank, too 11296 else if (Order < 0) { 11297 if (S.SourceMgr.isInSystemMacro(CC)) 11298 return; 11299 11300 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11301 } 11302 return; 11303 } 11304 11305 // If the target is integral, always warn. 11306 if (TargetBT && TargetBT->isInteger()) { 11307 if (S.SourceMgr.isInSystemMacro(CC)) 11308 return; 11309 11310 DiagnoseFloatingImpCast(S, E, T, CC); 11311 } 11312 11313 // Detect the case where a call result is converted from floating-point to 11314 // to bool, and the final argument to the call is converted from bool, to 11315 // discover this typo: 11316 // 11317 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11318 // 11319 // FIXME: This is an incredibly special case; is there some more general 11320 // way to detect this class of misplaced-parentheses bug? 11321 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11322 // Check last argument of function call to see if it is an 11323 // implicit cast from a type matching the type the result 11324 // is being cast to. 11325 CallExpr *CEx = cast<CallExpr>(E); 11326 if (unsigned NumArgs = CEx->getNumArgs()) { 11327 Expr *LastA = CEx->getArg(NumArgs - 1); 11328 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11329 if (isa<ImplicitCastExpr>(LastA) && 11330 InnerE->getType()->isBooleanType()) { 11331 // Warn on this floating-point to bool conversion 11332 DiagnoseImpCast(S, E, T, CC, 11333 diag::warn_impcast_floating_point_to_bool); 11334 } 11335 } 11336 } 11337 return; 11338 } 11339 11340 // Valid casts involving fixed point types should be accounted for here. 11341 if (Source->isFixedPointType()) { 11342 if (Target->isUnsaturatedFixedPointType()) { 11343 Expr::EvalResult Result; 11344 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11345 S.isConstantEvaluated())) { 11346 APFixedPoint Value = Result.Val.getFixedPoint(); 11347 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11348 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11349 if (Value > MaxVal || Value < MinVal) { 11350 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11351 S.PDiag(diag::warn_impcast_fixed_point_range) 11352 << Value.toString() << T 11353 << E->getSourceRange() 11354 << clang::SourceRange(CC)); 11355 return; 11356 } 11357 } 11358 } else if (Target->isIntegerType()) { 11359 Expr::EvalResult Result; 11360 if (!S.isConstantEvaluated() && 11361 E->EvaluateAsFixedPoint(Result, S.Context, 11362 Expr::SE_AllowSideEffects)) { 11363 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11364 11365 bool Overflowed; 11366 llvm::APSInt IntResult = FXResult.convertToInt( 11367 S.Context.getIntWidth(T), 11368 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11369 11370 if (Overflowed) { 11371 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11372 S.PDiag(diag::warn_impcast_fixed_point_range) 11373 << FXResult.toString() << T 11374 << E->getSourceRange() 11375 << clang::SourceRange(CC)); 11376 return; 11377 } 11378 } 11379 } 11380 } else if (Target->isUnsaturatedFixedPointType()) { 11381 if (Source->isIntegerType()) { 11382 Expr::EvalResult Result; 11383 if (!S.isConstantEvaluated() && 11384 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11385 llvm::APSInt Value = Result.Val.getInt(); 11386 11387 bool Overflowed; 11388 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11389 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11390 11391 if (Overflowed) { 11392 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11393 S.PDiag(diag::warn_impcast_fixed_point_range) 11394 << Value.toString(/*Radix=*/10) << T 11395 << E->getSourceRange() 11396 << clang::SourceRange(CC)); 11397 return; 11398 } 11399 } 11400 } 11401 } 11402 11403 // If we are casting an integer type to a floating point type without 11404 // initialization-list syntax, we might lose accuracy if the floating 11405 // point type has a narrower significand than the integer type. 11406 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11407 TargetBT->isFloatingType() && !IsListInit) { 11408 // Determine the number of precision bits in the source integer type. 11409 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11410 unsigned int SourcePrecision = SourceRange.Width; 11411 11412 // Determine the number of precision bits in the 11413 // target floating point type. 11414 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11415 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11416 11417 if (SourcePrecision > 0 && TargetPrecision > 0 && 11418 SourcePrecision > TargetPrecision) { 11419 11420 llvm::APSInt SourceInt; 11421 if (E->isIntegerConstantExpr(SourceInt, S.Context)) { 11422 // If the source integer is a constant, convert it to the target 11423 // floating point type. Issue a warning if the value changes 11424 // during the whole conversion. 11425 llvm::APFloat TargetFloatValue( 11426 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11427 llvm::APFloat::opStatus ConversionStatus = 11428 TargetFloatValue.convertFromAPInt( 11429 SourceInt, SourceBT->isSignedInteger(), 11430 llvm::APFloat::rmNearestTiesToEven); 11431 11432 if (ConversionStatus != llvm::APFloat::opOK) { 11433 std::string PrettySourceValue = SourceInt.toString(10); 11434 SmallString<32> PrettyTargetValue; 11435 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11436 11437 S.DiagRuntimeBehavior( 11438 E->getExprLoc(), E, 11439 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11440 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11441 << E->getSourceRange() << clang::SourceRange(CC)); 11442 } 11443 } else { 11444 // Otherwise, the implicit conversion may lose precision. 11445 DiagnoseImpCast(S, E, T, CC, 11446 diag::warn_impcast_integer_float_precision); 11447 } 11448 } 11449 } 11450 11451 DiagnoseNullConversion(S, E, T, CC); 11452 11453 S.DiscardMisalignedMemberAddress(Target, E); 11454 11455 if (Target->isBooleanType()) 11456 DiagnoseIntInBoolContext(S, E); 11457 11458 if (!Source->isIntegerType() || !Target->isIntegerType()) 11459 return; 11460 11461 // TODO: remove this early return once the false positives for constant->bool 11462 // in templates, macros, etc, are reduced or removed. 11463 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11464 return; 11465 11466 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11467 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11468 return adornObjCBoolConversionDiagWithTernaryFixit( 11469 S, E, 11470 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11471 << E->getType()); 11472 } 11473 11474 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11475 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11476 11477 if (SourceRange.Width > TargetRange.Width) { 11478 // If the source is a constant, use a default-on diagnostic. 11479 // TODO: this should happen for bitfield stores, too. 11480 Expr::EvalResult Result; 11481 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11482 S.isConstantEvaluated())) { 11483 llvm::APSInt Value(32); 11484 Value = Result.Val.getInt(); 11485 11486 if (S.SourceMgr.isInSystemMacro(CC)) 11487 return; 11488 11489 std::string PrettySourceValue = Value.toString(10); 11490 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11491 11492 S.DiagRuntimeBehavior( 11493 E->getExprLoc(), E, 11494 S.PDiag(diag::warn_impcast_integer_precision_constant) 11495 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11496 << E->getSourceRange() << clang::SourceRange(CC)); 11497 return; 11498 } 11499 11500 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11501 if (S.SourceMgr.isInSystemMacro(CC)) 11502 return; 11503 11504 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11505 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11506 /* pruneControlFlow */ true); 11507 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11508 } 11509 11510 if (TargetRange.Width > SourceRange.Width) { 11511 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11512 if (UO->getOpcode() == UO_Minus) 11513 if (Source->isUnsignedIntegerType()) { 11514 if (Target->isUnsignedIntegerType()) 11515 return DiagnoseImpCast(S, E, T, CC, 11516 diag::warn_impcast_high_order_zero_bits); 11517 if (Target->isSignedIntegerType()) 11518 return DiagnoseImpCast(S, E, T, CC, 11519 diag::warn_impcast_nonnegative_result); 11520 } 11521 } 11522 11523 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11524 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11525 // Warn when doing a signed to signed conversion, warn if the positive 11526 // source value is exactly the width of the target type, which will 11527 // cause a negative value to be stored. 11528 11529 Expr::EvalResult Result; 11530 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11531 !S.SourceMgr.isInSystemMacro(CC)) { 11532 llvm::APSInt Value = Result.Val.getInt(); 11533 if (isSameWidthConstantConversion(S, E, T, CC)) { 11534 std::string PrettySourceValue = Value.toString(10); 11535 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11536 11537 S.DiagRuntimeBehavior( 11538 E->getExprLoc(), E, 11539 S.PDiag(diag::warn_impcast_integer_precision_constant) 11540 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11541 << E->getSourceRange() << clang::SourceRange(CC)); 11542 return; 11543 } 11544 } 11545 11546 // Fall through for non-constants to give a sign conversion warning. 11547 } 11548 11549 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11550 (!TargetRange.NonNegative && SourceRange.NonNegative && 11551 SourceRange.Width == TargetRange.Width)) { 11552 if (S.SourceMgr.isInSystemMacro(CC)) 11553 return; 11554 11555 unsigned DiagID = diag::warn_impcast_integer_sign; 11556 11557 // Traditionally, gcc has warned about this under -Wsign-compare. 11558 // We also want to warn about it in -Wconversion. 11559 // So if -Wconversion is off, use a completely identical diagnostic 11560 // in the sign-compare group. 11561 // The conditional-checking code will 11562 if (ICContext) { 11563 DiagID = diag::warn_impcast_integer_sign_conditional; 11564 *ICContext = true; 11565 } 11566 11567 return DiagnoseImpCast(S, E, T, CC, DiagID); 11568 } 11569 11570 // Diagnose conversions between different enumeration types. 11571 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11572 // type, to give us better diagnostics. 11573 QualType SourceType = E->getType(); 11574 if (!S.getLangOpts().CPlusPlus) { 11575 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11576 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11577 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11578 SourceType = S.Context.getTypeDeclType(Enum); 11579 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11580 } 11581 } 11582 11583 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11584 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11585 if (SourceEnum->getDecl()->hasNameForLinkage() && 11586 TargetEnum->getDecl()->hasNameForLinkage() && 11587 SourceEnum != TargetEnum) { 11588 if (S.SourceMgr.isInSystemMacro(CC)) 11589 return; 11590 11591 return DiagnoseImpCast(S, E, SourceType, T, CC, 11592 diag::warn_impcast_different_enum_types); 11593 } 11594 } 11595 11596 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11597 SourceLocation CC, QualType T); 11598 11599 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11600 SourceLocation CC, bool &ICContext) { 11601 E = E->IgnoreParenImpCasts(); 11602 11603 if (isa<ConditionalOperator>(E)) 11604 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11605 11606 AnalyzeImplicitConversions(S, E, CC); 11607 if (E->getType() != T) 11608 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11609 } 11610 11611 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11612 SourceLocation CC, QualType T) { 11613 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11614 11615 bool Suspicious = false; 11616 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11617 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11618 11619 if (T->isBooleanType()) 11620 DiagnoseIntInBoolContext(S, E); 11621 11622 // If -Wconversion would have warned about either of the candidates 11623 // for a signedness conversion to the context type... 11624 if (!Suspicious) return; 11625 11626 // ...but it's currently ignored... 11627 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11628 return; 11629 11630 // ...then check whether it would have warned about either of the 11631 // candidates for a signedness conversion to the condition type. 11632 if (E->getType() == T) return; 11633 11634 Suspicious = false; 11635 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11636 E->getType(), CC, &Suspicious); 11637 if (!Suspicious) 11638 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11639 E->getType(), CC, &Suspicious); 11640 } 11641 11642 /// Check conversion of given expression to boolean. 11643 /// Input argument E is a logical expression. 11644 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11645 if (S.getLangOpts().Bool) 11646 return; 11647 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11648 return; 11649 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11650 } 11651 11652 /// AnalyzeImplicitConversions - Find and report any interesting 11653 /// implicit conversions in the given expression. There are a couple 11654 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11655 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 11656 bool IsListInit/*= false*/) { 11657 QualType T = OrigE->getType(); 11658 Expr *E = OrigE->IgnoreParenImpCasts(); 11659 11660 // Propagate whether we are in a C++ list initialization expression. 11661 // If so, we do not issue warnings for implicit int-float conversion 11662 // precision loss, because C++11 narrowing already handles it. 11663 IsListInit = 11664 IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 11665 11666 if (E->isTypeDependent() || E->isValueDependent()) 11667 return; 11668 11669 Expr *SourceExpr = E; 11670 // Examine, but don't traverse into the source expression of an 11671 // OpaqueValueExpr, since it may have multiple parents and we don't want to 11672 // emit duplicate diagnostics. Its fine to examine the form or attempt to 11673 // evaluate it in the context of checking the specific conversion to T though. 11674 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11675 if (auto *Src = OVE->getSourceExpr()) 11676 SourceExpr = Src; 11677 11678 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 11679 if (UO->getOpcode() == UO_Not && 11680 UO->getSubExpr()->isKnownToHaveBooleanValue()) 11681 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 11682 << OrigE->getSourceRange() << T->isBooleanType() 11683 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 11684 11685 // For conditional operators, we analyze the arguments as if they 11686 // were being fed directly into the output. 11687 if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) { 11688 CheckConditionalOperator(S, CO, CC, T); 11689 return; 11690 } 11691 11692 // Check implicit argument conversions for function calls. 11693 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 11694 CheckImplicitArgumentConversions(S, Call, CC); 11695 11696 // Go ahead and check any implicit conversions we might have skipped. 11697 // The non-canonical typecheck is just an optimization; 11698 // CheckImplicitConversion will filter out dead implicit conversions. 11699 if (SourceExpr->getType() != T) 11700 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 11701 11702 // Now continue drilling into this expression. 11703 11704 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11705 // The bound subexpressions in a PseudoObjectExpr are not reachable 11706 // as transitive children. 11707 // FIXME: Use a more uniform representation for this. 11708 for (auto *SE : POE->semantics()) 11709 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11710 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit); 11711 } 11712 11713 // Skip past explicit casts. 11714 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11715 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11716 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11717 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11718 return AnalyzeImplicitConversions(S, E, CC, IsListInit); 11719 } 11720 11721 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11722 // Do a somewhat different check with comparison operators. 11723 if (BO->isComparisonOp()) 11724 return AnalyzeComparison(S, BO); 11725 11726 // And with simple assignments. 11727 if (BO->getOpcode() == BO_Assign) 11728 return AnalyzeAssignment(S, BO); 11729 // And with compound assignments. 11730 if (BO->isAssignmentOp()) 11731 return AnalyzeCompoundAssignment(S, BO); 11732 } 11733 11734 // These break the otherwise-useful invariant below. Fortunately, 11735 // we don't really need to recurse into them, because any internal 11736 // expressions should have been analyzed already when they were 11737 // built into statements. 11738 if (isa<StmtExpr>(E)) return; 11739 11740 // Don't descend into unevaluated contexts. 11741 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11742 11743 // Now just recurse over the expression's children. 11744 CC = E->getExprLoc(); 11745 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11746 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11747 for (Stmt *SubStmt : E->children()) { 11748 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11749 if (!ChildExpr) 11750 continue; 11751 11752 if (IsLogicalAndOperator && 11753 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11754 // Ignore checking string literals that are in logical and operators. 11755 // This is a common pattern for asserts. 11756 continue; 11757 AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit); 11758 } 11759 11760 if (BO && BO->isLogicalOp()) { 11761 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11762 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11763 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11764 11765 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11766 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11767 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11768 } 11769 11770 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11771 if (U->getOpcode() == UO_LNot) { 11772 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11773 } else if (U->getOpcode() != UO_AddrOf) { 11774 if (U->getSubExpr()->getType()->isAtomicType()) 11775 S.Diag(U->getSubExpr()->getBeginLoc(), 11776 diag::warn_atomic_implicit_seq_cst); 11777 } 11778 } 11779 } 11780 11781 /// Diagnose integer type and any valid implicit conversion to it. 11782 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11783 // Taking into account implicit conversions, 11784 // allow any integer. 11785 if (!E->getType()->isIntegerType()) { 11786 S.Diag(E->getBeginLoc(), 11787 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11788 return true; 11789 } 11790 // Potentially emit standard warnings for implicit conversions if enabled 11791 // using -Wconversion. 11792 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11793 return false; 11794 } 11795 11796 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11797 // Returns true when emitting a warning about taking the address of a reference. 11798 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11799 const PartialDiagnostic &PD) { 11800 E = E->IgnoreParenImpCasts(); 11801 11802 const FunctionDecl *FD = nullptr; 11803 11804 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11805 if (!DRE->getDecl()->getType()->isReferenceType()) 11806 return false; 11807 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11808 if (!M->getMemberDecl()->getType()->isReferenceType()) 11809 return false; 11810 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11811 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11812 return false; 11813 FD = Call->getDirectCallee(); 11814 } else { 11815 return false; 11816 } 11817 11818 SemaRef.Diag(E->getExprLoc(), PD); 11819 11820 // If possible, point to location of function. 11821 if (FD) { 11822 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11823 } 11824 11825 return true; 11826 } 11827 11828 // Returns true if the SourceLocation is expanded from any macro body. 11829 // Returns false if the SourceLocation is invalid, is from not in a macro 11830 // expansion, or is from expanded from a top-level macro argument. 11831 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11832 if (Loc.isInvalid()) 11833 return false; 11834 11835 while (Loc.isMacroID()) { 11836 if (SM.isMacroBodyExpansion(Loc)) 11837 return true; 11838 Loc = SM.getImmediateMacroCallerLoc(Loc); 11839 } 11840 11841 return false; 11842 } 11843 11844 /// Diagnose pointers that are always non-null. 11845 /// \param E the expression containing the pointer 11846 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11847 /// compared to a null pointer 11848 /// \param IsEqual True when the comparison is equal to a null pointer 11849 /// \param Range Extra SourceRange to highlight in the diagnostic 11850 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11851 Expr::NullPointerConstantKind NullKind, 11852 bool IsEqual, SourceRange Range) { 11853 if (!E) 11854 return; 11855 11856 // Don't warn inside macros. 11857 if (E->getExprLoc().isMacroID()) { 11858 const SourceManager &SM = getSourceManager(); 11859 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11860 IsInAnyMacroBody(SM, Range.getBegin())) 11861 return; 11862 } 11863 E = E->IgnoreImpCasts(); 11864 11865 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11866 11867 if (isa<CXXThisExpr>(E)) { 11868 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11869 : diag::warn_this_bool_conversion; 11870 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11871 return; 11872 } 11873 11874 bool IsAddressOf = false; 11875 11876 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11877 if (UO->getOpcode() != UO_AddrOf) 11878 return; 11879 IsAddressOf = true; 11880 E = UO->getSubExpr(); 11881 } 11882 11883 if (IsAddressOf) { 11884 unsigned DiagID = IsCompare 11885 ? diag::warn_address_of_reference_null_compare 11886 : diag::warn_address_of_reference_bool_conversion; 11887 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11888 << IsEqual; 11889 if (CheckForReference(*this, E, PD)) { 11890 return; 11891 } 11892 } 11893 11894 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11895 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11896 std::string Str; 11897 llvm::raw_string_ostream S(Str); 11898 E->printPretty(S, nullptr, getPrintingPolicy()); 11899 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11900 : diag::warn_cast_nonnull_to_bool; 11901 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11902 << E->getSourceRange() << Range << IsEqual; 11903 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11904 }; 11905 11906 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11907 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11908 if (auto *Callee = Call->getDirectCallee()) { 11909 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11910 ComplainAboutNonnullParamOrCall(A); 11911 return; 11912 } 11913 } 11914 } 11915 11916 // Expect to find a single Decl. Skip anything more complicated. 11917 ValueDecl *D = nullptr; 11918 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11919 D = R->getDecl(); 11920 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11921 D = M->getMemberDecl(); 11922 } 11923 11924 // Weak Decls can be null. 11925 if (!D || D->isWeak()) 11926 return; 11927 11928 // Check for parameter decl with nonnull attribute 11929 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11930 if (getCurFunction() && 11931 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11932 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11933 ComplainAboutNonnullParamOrCall(A); 11934 return; 11935 } 11936 11937 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11938 // Skip function template not specialized yet. 11939 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11940 return; 11941 auto ParamIter = llvm::find(FD->parameters(), PV); 11942 assert(ParamIter != FD->param_end()); 11943 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11944 11945 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11946 if (!NonNull->args_size()) { 11947 ComplainAboutNonnullParamOrCall(NonNull); 11948 return; 11949 } 11950 11951 for (const ParamIdx &ArgNo : NonNull->args()) { 11952 if (ArgNo.getASTIndex() == ParamNo) { 11953 ComplainAboutNonnullParamOrCall(NonNull); 11954 return; 11955 } 11956 } 11957 } 11958 } 11959 } 11960 } 11961 11962 QualType T = D->getType(); 11963 const bool IsArray = T->isArrayType(); 11964 const bool IsFunction = T->isFunctionType(); 11965 11966 // Address of function is used to silence the function warning. 11967 if (IsAddressOf && IsFunction) { 11968 return; 11969 } 11970 11971 // Found nothing. 11972 if (!IsAddressOf && !IsFunction && !IsArray) 11973 return; 11974 11975 // Pretty print the expression for the diagnostic. 11976 std::string Str; 11977 llvm::raw_string_ostream S(Str); 11978 E->printPretty(S, nullptr, getPrintingPolicy()); 11979 11980 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11981 : diag::warn_impcast_pointer_to_bool; 11982 enum { 11983 AddressOf, 11984 FunctionPointer, 11985 ArrayPointer 11986 } DiagType; 11987 if (IsAddressOf) 11988 DiagType = AddressOf; 11989 else if (IsFunction) 11990 DiagType = FunctionPointer; 11991 else if (IsArray) 11992 DiagType = ArrayPointer; 11993 else 11994 llvm_unreachable("Could not determine diagnostic."); 11995 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11996 << Range << IsEqual; 11997 11998 if (!IsFunction) 11999 return; 12000 12001 // Suggest '&' to silence the function warning. 12002 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12003 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12004 12005 // Check to see if '()' fixit should be emitted. 12006 QualType ReturnType; 12007 UnresolvedSet<4> NonTemplateOverloads; 12008 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12009 if (ReturnType.isNull()) 12010 return; 12011 12012 if (IsCompare) { 12013 // There are two cases here. If there is null constant, the only suggest 12014 // for a pointer return type. If the null is 0, then suggest if the return 12015 // type is a pointer or an integer type. 12016 if (!ReturnType->isPointerType()) { 12017 if (NullKind == Expr::NPCK_ZeroExpression || 12018 NullKind == Expr::NPCK_ZeroLiteral) { 12019 if (!ReturnType->isIntegerType()) 12020 return; 12021 } else { 12022 return; 12023 } 12024 } 12025 } else { // !IsCompare 12026 // For function to bool, only suggest if the function pointer has bool 12027 // return type. 12028 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12029 return; 12030 } 12031 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12032 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12033 } 12034 12035 /// Diagnoses "dangerous" implicit conversions within the given 12036 /// expression (which is a full expression). Implements -Wconversion 12037 /// and -Wsign-compare. 12038 /// 12039 /// \param CC the "context" location of the implicit conversion, i.e. 12040 /// the most location of the syntactic entity requiring the implicit 12041 /// conversion 12042 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12043 // Don't diagnose in unevaluated contexts. 12044 if (isUnevaluatedContext()) 12045 return; 12046 12047 // Don't diagnose for value- or type-dependent expressions. 12048 if (E->isTypeDependent() || E->isValueDependent()) 12049 return; 12050 12051 // Check for array bounds violations in cases where the check isn't triggered 12052 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12053 // ArraySubscriptExpr is on the RHS of a variable initialization. 12054 CheckArrayAccess(E); 12055 12056 // This is not the right CC for (e.g.) a variable initialization. 12057 AnalyzeImplicitConversions(*this, E, CC); 12058 } 12059 12060 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12061 /// Input argument E is a logical expression. 12062 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12063 ::CheckBoolLikeConversion(*this, E, CC); 12064 } 12065 12066 /// Diagnose when expression is an integer constant expression and its evaluation 12067 /// results in integer overflow 12068 void Sema::CheckForIntOverflow (Expr *E) { 12069 // Use a work list to deal with nested struct initializers. 12070 SmallVector<Expr *, 2> Exprs(1, E); 12071 12072 do { 12073 Expr *OriginalE = Exprs.pop_back_val(); 12074 Expr *E = OriginalE->IgnoreParenCasts(); 12075 12076 if (isa<BinaryOperator>(E)) { 12077 E->EvaluateForOverflow(Context); 12078 continue; 12079 } 12080 12081 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12082 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12083 else if (isa<ObjCBoxedExpr>(OriginalE)) 12084 E->EvaluateForOverflow(Context); 12085 else if (auto Call = dyn_cast<CallExpr>(E)) 12086 Exprs.append(Call->arg_begin(), Call->arg_end()); 12087 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12088 Exprs.append(Message->arg_begin(), Message->arg_end()); 12089 } while (!Exprs.empty()); 12090 } 12091 12092 namespace { 12093 12094 /// Visitor for expressions which looks for unsequenced operations on the 12095 /// same object. 12096 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12097 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12098 12099 /// A tree of sequenced regions within an expression. Two regions are 12100 /// unsequenced if one is an ancestor or a descendent of the other. When we 12101 /// finish processing an expression with sequencing, such as a comma 12102 /// expression, we fold its tree nodes into its parent, since they are 12103 /// unsequenced with respect to nodes we will visit later. 12104 class SequenceTree { 12105 struct Value { 12106 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12107 unsigned Parent : 31; 12108 unsigned Merged : 1; 12109 }; 12110 SmallVector<Value, 8> Values; 12111 12112 public: 12113 /// A region within an expression which may be sequenced with respect 12114 /// to some other region. 12115 class Seq { 12116 friend class SequenceTree; 12117 12118 unsigned Index; 12119 12120 explicit Seq(unsigned N) : Index(N) {} 12121 12122 public: 12123 Seq() : Index(0) {} 12124 }; 12125 12126 SequenceTree() { Values.push_back(Value(0)); } 12127 Seq root() const { return Seq(0); } 12128 12129 /// Create a new sequence of operations, which is an unsequenced 12130 /// subset of \p Parent. This sequence of operations is sequenced with 12131 /// respect to other children of \p Parent. 12132 Seq allocate(Seq Parent) { 12133 Values.push_back(Value(Parent.Index)); 12134 return Seq(Values.size() - 1); 12135 } 12136 12137 /// Merge a sequence of operations into its parent. 12138 void merge(Seq S) { 12139 Values[S.Index].Merged = true; 12140 } 12141 12142 /// Determine whether two operations are unsequenced. This operation 12143 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12144 /// should have been merged into its parent as appropriate. 12145 bool isUnsequenced(Seq Cur, Seq Old) { 12146 unsigned C = representative(Cur.Index); 12147 unsigned Target = representative(Old.Index); 12148 while (C >= Target) { 12149 if (C == Target) 12150 return true; 12151 C = Values[C].Parent; 12152 } 12153 return false; 12154 } 12155 12156 private: 12157 /// Pick a representative for a sequence. 12158 unsigned representative(unsigned K) { 12159 if (Values[K].Merged) 12160 // Perform path compression as we go. 12161 return Values[K].Parent = representative(Values[K].Parent); 12162 return K; 12163 } 12164 }; 12165 12166 /// An object for which we can track unsequenced uses. 12167 using Object = const NamedDecl *; 12168 12169 /// Different flavors of object usage which we track. We only track the 12170 /// least-sequenced usage of each kind. 12171 enum UsageKind { 12172 /// A read of an object. Multiple unsequenced reads are OK. 12173 UK_Use, 12174 12175 /// A modification of an object which is sequenced before the value 12176 /// computation of the expression, such as ++n in C++. 12177 UK_ModAsValue, 12178 12179 /// A modification of an object which is not sequenced before the value 12180 /// computation of the expression, such as n++. 12181 UK_ModAsSideEffect, 12182 12183 UK_Count = UK_ModAsSideEffect + 1 12184 }; 12185 12186 /// Bundle together a sequencing region and the expression corresponding 12187 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12188 struct Usage { 12189 const Expr *UsageExpr; 12190 SequenceTree::Seq Seq; 12191 12192 Usage() : UsageExpr(nullptr), Seq() {} 12193 }; 12194 12195 struct UsageInfo { 12196 Usage Uses[UK_Count]; 12197 12198 /// Have we issued a diagnostic for this object already? 12199 bool Diagnosed; 12200 12201 UsageInfo() : Uses(), Diagnosed(false) {} 12202 }; 12203 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12204 12205 Sema &SemaRef; 12206 12207 /// Sequenced regions within the expression. 12208 SequenceTree Tree; 12209 12210 /// Declaration modifications and references which we have seen. 12211 UsageInfoMap UsageMap; 12212 12213 /// The region we are currently within. 12214 SequenceTree::Seq Region; 12215 12216 /// Filled in with declarations which were modified as a side-effect 12217 /// (that is, post-increment operations). 12218 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12219 12220 /// Expressions to check later. We defer checking these to reduce 12221 /// stack usage. 12222 SmallVectorImpl<const Expr *> &WorkList; 12223 12224 /// RAII object wrapping the visitation of a sequenced subexpression of an 12225 /// expression. At the end of this process, the side-effects of the evaluation 12226 /// become sequenced with respect to the value computation of the result, so 12227 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12228 /// UK_ModAsValue. 12229 struct SequencedSubexpression { 12230 SequencedSubexpression(SequenceChecker &Self) 12231 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12232 Self.ModAsSideEffect = &ModAsSideEffect; 12233 } 12234 12235 ~SequencedSubexpression() { 12236 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12237 // Add a new usage with usage kind UK_ModAsValue, and then restore 12238 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12239 // the previous one was empty). 12240 UsageInfo &UI = Self.UsageMap[M.first]; 12241 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12242 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12243 SideEffectUsage = M.second; 12244 } 12245 Self.ModAsSideEffect = OldModAsSideEffect; 12246 } 12247 12248 SequenceChecker &Self; 12249 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12250 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12251 }; 12252 12253 /// RAII object wrapping the visitation of a subexpression which we might 12254 /// choose to evaluate as a constant. If any subexpression is evaluated and 12255 /// found to be non-constant, this allows us to suppress the evaluation of 12256 /// the outer expression. 12257 class EvaluationTracker { 12258 public: 12259 EvaluationTracker(SequenceChecker &Self) 12260 : Self(Self), Prev(Self.EvalTracker) { 12261 Self.EvalTracker = this; 12262 } 12263 12264 ~EvaluationTracker() { 12265 Self.EvalTracker = Prev; 12266 if (Prev) 12267 Prev->EvalOK &= EvalOK; 12268 } 12269 12270 bool evaluate(const Expr *E, bool &Result) { 12271 if (!EvalOK || E->isValueDependent()) 12272 return false; 12273 EvalOK = E->EvaluateAsBooleanCondition( 12274 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12275 return EvalOK; 12276 } 12277 12278 private: 12279 SequenceChecker &Self; 12280 EvaluationTracker *Prev; 12281 bool EvalOK = true; 12282 } *EvalTracker = nullptr; 12283 12284 /// Find the object which is produced by the specified expression, 12285 /// if any. 12286 Object getObject(const Expr *E, bool Mod) const { 12287 E = E->IgnoreParenCasts(); 12288 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12289 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12290 return getObject(UO->getSubExpr(), Mod); 12291 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12292 if (BO->getOpcode() == BO_Comma) 12293 return getObject(BO->getRHS(), Mod); 12294 if (Mod && BO->isAssignmentOp()) 12295 return getObject(BO->getLHS(), Mod); 12296 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12297 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12298 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12299 return ME->getMemberDecl(); 12300 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12301 // FIXME: If this is a reference, map through to its value. 12302 return DRE->getDecl(); 12303 return nullptr; 12304 } 12305 12306 /// Note that an object \p O was modified or used by an expression 12307 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12308 /// the object \p O as obtained via the \p UsageMap. 12309 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12310 // Get the old usage for the given object and usage kind. 12311 Usage &U = UI.Uses[UK]; 12312 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12313 // If we have a modification as side effect and are in a sequenced 12314 // subexpression, save the old Usage so that we can restore it later 12315 // in SequencedSubexpression::~SequencedSubexpression. 12316 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12317 ModAsSideEffect->push_back(std::make_pair(O, U)); 12318 // Then record the new usage with the current sequencing region. 12319 U.UsageExpr = UsageExpr; 12320 U.Seq = Region; 12321 } 12322 } 12323 12324 /// Check whether a modification or use of an object \p O in an expression 12325 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12326 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12327 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12328 /// usage and false we are checking for a mod-use unsequenced usage. 12329 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12330 UsageKind OtherKind, bool IsModMod) { 12331 if (UI.Diagnosed) 12332 return; 12333 12334 const Usage &U = UI.Uses[OtherKind]; 12335 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12336 return; 12337 12338 const Expr *Mod = U.UsageExpr; 12339 const Expr *ModOrUse = UsageExpr; 12340 if (OtherKind == UK_Use) 12341 std::swap(Mod, ModOrUse); 12342 12343 SemaRef.DiagRuntimeBehavior( 12344 Mod->getExprLoc(), {Mod, ModOrUse}, 12345 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12346 : diag::warn_unsequenced_mod_use) 12347 << O << SourceRange(ModOrUse->getExprLoc())); 12348 UI.Diagnosed = true; 12349 } 12350 12351 // A note on note{Pre, Post}{Use, Mod}: 12352 // 12353 // (It helps to follow the algorithm with an expression such as 12354 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12355 // operations before C++17 and both are well-defined in C++17). 12356 // 12357 // When visiting a node which uses/modify an object we first call notePreUse 12358 // or notePreMod before visiting its sub-expression(s). At this point the 12359 // children of the current node have not yet been visited and so the eventual 12360 // uses/modifications resulting from the children of the current node have not 12361 // been recorded yet. 12362 // 12363 // We then visit the children of the current node. After that notePostUse or 12364 // notePostMod is called. These will 1) detect an unsequenced modification 12365 // as side effect (as in "k++ + k") and 2) add a new usage with the 12366 // appropriate usage kind. 12367 // 12368 // We also have to be careful that some operation sequences modification as 12369 // side effect as well (for example: || or ,). To account for this we wrap 12370 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12371 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12372 // which record usages which are modifications as side effect, and then 12373 // downgrade them (or more accurately restore the previous usage which was a 12374 // modification as side effect) when exiting the scope of the sequenced 12375 // subexpression. 12376 12377 void notePreUse(Object O, const Expr *UseExpr) { 12378 UsageInfo &UI = UsageMap[O]; 12379 // Uses conflict with other modifications. 12380 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12381 } 12382 12383 void notePostUse(Object O, const Expr *UseExpr) { 12384 UsageInfo &UI = UsageMap[O]; 12385 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12386 /*IsModMod=*/false); 12387 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12388 } 12389 12390 void notePreMod(Object O, const Expr *ModExpr) { 12391 UsageInfo &UI = UsageMap[O]; 12392 // Modifications conflict with other modifications and with uses. 12393 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12394 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12395 } 12396 12397 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12398 UsageInfo &UI = UsageMap[O]; 12399 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12400 /*IsModMod=*/true); 12401 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12402 } 12403 12404 public: 12405 SequenceChecker(Sema &S, const Expr *E, 12406 SmallVectorImpl<const Expr *> &WorkList) 12407 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12408 Visit(E); 12409 // Silence a -Wunused-private-field since WorkList is now unused. 12410 // TODO: Evaluate if it can be used, and if not remove it. 12411 (void)this->WorkList; 12412 } 12413 12414 void VisitStmt(const Stmt *S) { 12415 // Skip all statements which aren't expressions for now. 12416 } 12417 12418 void VisitExpr(const Expr *E) { 12419 // By default, just recurse to evaluated subexpressions. 12420 Base::VisitStmt(E); 12421 } 12422 12423 void VisitCastExpr(const CastExpr *E) { 12424 Object O = Object(); 12425 if (E->getCastKind() == CK_LValueToRValue) 12426 O = getObject(E->getSubExpr(), false); 12427 12428 if (O) 12429 notePreUse(O, E); 12430 VisitExpr(E); 12431 if (O) 12432 notePostUse(O, E); 12433 } 12434 12435 void VisitSequencedExpressions(const Expr *SequencedBefore, 12436 const Expr *SequencedAfter) { 12437 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12438 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12439 SequenceTree::Seq OldRegion = Region; 12440 12441 { 12442 SequencedSubexpression SeqBefore(*this); 12443 Region = BeforeRegion; 12444 Visit(SequencedBefore); 12445 } 12446 12447 Region = AfterRegion; 12448 Visit(SequencedAfter); 12449 12450 Region = OldRegion; 12451 12452 Tree.merge(BeforeRegion); 12453 Tree.merge(AfterRegion); 12454 } 12455 12456 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12457 // C++17 [expr.sub]p1: 12458 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12459 // expression E1 is sequenced before the expression E2. 12460 if (SemaRef.getLangOpts().CPlusPlus17) 12461 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12462 else { 12463 Visit(ASE->getLHS()); 12464 Visit(ASE->getRHS()); 12465 } 12466 } 12467 12468 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12469 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12470 void VisitBinPtrMem(const BinaryOperator *BO) { 12471 // C++17 [expr.mptr.oper]p4: 12472 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12473 // the expression E1 is sequenced before the expression E2. 12474 if (SemaRef.getLangOpts().CPlusPlus17) 12475 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12476 else { 12477 Visit(BO->getLHS()); 12478 Visit(BO->getRHS()); 12479 } 12480 } 12481 12482 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12483 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12484 void VisitBinShlShr(const BinaryOperator *BO) { 12485 // C++17 [expr.shift]p4: 12486 // The expression E1 is sequenced before the expression E2. 12487 if (SemaRef.getLangOpts().CPlusPlus17) 12488 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12489 else { 12490 Visit(BO->getLHS()); 12491 Visit(BO->getRHS()); 12492 } 12493 } 12494 12495 void VisitBinComma(const BinaryOperator *BO) { 12496 // C++11 [expr.comma]p1: 12497 // Every value computation and side effect associated with the left 12498 // expression is sequenced before every value computation and side 12499 // effect associated with the right expression. 12500 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12501 } 12502 12503 void VisitBinAssign(const BinaryOperator *BO) { 12504 SequenceTree::Seq RHSRegion; 12505 SequenceTree::Seq LHSRegion; 12506 if (SemaRef.getLangOpts().CPlusPlus17) { 12507 RHSRegion = Tree.allocate(Region); 12508 LHSRegion = Tree.allocate(Region); 12509 } else { 12510 RHSRegion = Region; 12511 LHSRegion = Region; 12512 } 12513 SequenceTree::Seq OldRegion = Region; 12514 12515 // C++11 [expr.ass]p1: 12516 // [...] the assignment is sequenced after the value computation 12517 // of the right and left operands, [...] 12518 // 12519 // so check it before inspecting the operands and update the 12520 // map afterwards. 12521 Object O = getObject(BO->getLHS(), /*Mod=*/true); 12522 if (O) 12523 notePreMod(O, BO); 12524 12525 if (SemaRef.getLangOpts().CPlusPlus17) { 12526 // C++17 [expr.ass]p1: 12527 // [...] The right operand is sequenced before the left operand. [...] 12528 { 12529 SequencedSubexpression SeqBefore(*this); 12530 Region = RHSRegion; 12531 Visit(BO->getRHS()); 12532 } 12533 12534 Region = LHSRegion; 12535 Visit(BO->getLHS()); 12536 12537 if (O && isa<CompoundAssignOperator>(BO)) 12538 notePostUse(O, BO); 12539 12540 } else { 12541 // C++11 does not specify any sequencing between the LHS and RHS. 12542 Region = LHSRegion; 12543 Visit(BO->getLHS()); 12544 12545 if (O && isa<CompoundAssignOperator>(BO)) 12546 notePostUse(O, BO); 12547 12548 Region = RHSRegion; 12549 Visit(BO->getRHS()); 12550 } 12551 12552 // C++11 [expr.ass]p1: 12553 // the assignment is sequenced [...] before the value computation of the 12554 // assignment expression. 12555 // C11 6.5.16/3 has no such rule. 12556 Region = OldRegion; 12557 if (O) 12558 notePostMod(O, BO, 12559 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12560 : UK_ModAsSideEffect); 12561 if (SemaRef.getLangOpts().CPlusPlus17) { 12562 Tree.merge(RHSRegion); 12563 Tree.merge(LHSRegion); 12564 } 12565 } 12566 12567 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 12568 VisitBinAssign(CAO); 12569 } 12570 12571 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12572 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12573 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 12574 Object O = getObject(UO->getSubExpr(), true); 12575 if (!O) 12576 return VisitExpr(UO); 12577 12578 notePreMod(O, UO); 12579 Visit(UO->getSubExpr()); 12580 // C++11 [expr.pre.incr]p1: 12581 // the expression ++x is equivalent to x+=1 12582 notePostMod(O, UO, 12583 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12584 : UK_ModAsSideEffect); 12585 } 12586 12587 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12588 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12589 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 12590 Object O = getObject(UO->getSubExpr(), true); 12591 if (!O) 12592 return VisitExpr(UO); 12593 12594 notePreMod(O, UO); 12595 Visit(UO->getSubExpr()); 12596 notePostMod(O, UO, UK_ModAsSideEffect); 12597 } 12598 12599 void VisitBinLOr(const BinaryOperator *BO) { 12600 // C++11 [expr.log.or]p2: 12601 // If the second expression is evaluated, every value computation and 12602 // side effect associated with the first expression is sequenced before 12603 // every value computation and side effect associated with the 12604 // second expression. 12605 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12606 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12607 SequenceTree::Seq OldRegion = Region; 12608 12609 EvaluationTracker Eval(*this); 12610 { 12611 SequencedSubexpression Sequenced(*this); 12612 Region = LHSRegion; 12613 Visit(BO->getLHS()); 12614 } 12615 12616 // C++11 [expr.log.or]p1: 12617 // [...] the second operand is not evaluated if the first operand 12618 // evaluates to true. 12619 bool EvalResult = false; 12620 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12621 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 12622 if (ShouldVisitRHS) { 12623 Region = RHSRegion; 12624 Visit(BO->getRHS()); 12625 } 12626 12627 Region = OldRegion; 12628 Tree.merge(LHSRegion); 12629 Tree.merge(RHSRegion); 12630 } 12631 12632 void VisitBinLAnd(const BinaryOperator *BO) { 12633 // C++11 [expr.log.and]p2: 12634 // If the second expression is evaluated, every value computation and 12635 // side effect associated with the first expression is sequenced before 12636 // every value computation and side effect associated with the 12637 // second expression. 12638 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12639 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12640 SequenceTree::Seq OldRegion = Region; 12641 12642 EvaluationTracker Eval(*this); 12643 { 12644 SequencedSubexpression Sequenced(*this); 12645 Region = LHSRegion; 12646 Visit(BO->getLHS()); 12647 } 12648 12649 // C++11 [expr.log.and]p1: 12650 // [...] the second operand is not evaluated if the first operand is false. 12651 bool EvalResult = false; 12652 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12653 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 12654 if (ShouldVisitRHS) { 12655 Region = RHSRegion; 12656 Visit(BO->getRHS()); 12657 } 12658 12659 Region = OldRegion; 12660 Tree.merge(LHSRegion); 12661 Tree.merge(RHSRegion); 12662 } 12663 12664 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 12665 // C++11 [expr.cond]p1: 12666 // [...] Every value computation and side effect associated with the first 12667 // expression is sequenced before every value computation and side effect 12668 // associated with the second or third expression. 12669 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 12670 12671 // No sequencing is specified between the true and false expression. 12672 // However since exactly one of both is going to be evaluated we can 12673 // consider them to be sequenced. This is needed to avoid warning on 12674 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 12675 // both the true and false expressions because we can't evaluate x. 12676 // This will still allow us to detect an expression like (pre C++17) 12677 // "(x ? y += 1 : y += 2) = y". 12678 // 12679 // We don't wrap the visitation of the true and false expression with 12680 // SequencedSubexpression because we don't want to downgrade modifications 12681 // as side effect in the true and false expressions after the visition 12682 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 12683 // not warn between the two "y++", but we should warn between the "y++" 12684 // and the "y". 12685 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 12686 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 12687 SequenceTree::Seq OldRegion = Region; 12688 12689 EvaluationTracker Eval(*this); 12690 { 12691 SequencedSubexpression Sequenced(*this); 12692 Region = ConditionRegion; 12693 Visit(CO->getCond()); 12694 } 12695 12696 // C++11 [expr.cond]p1: 12697 // [...] The first expression is contextually converted to bool (Clause 4). 12698 // It is evaluated and if it is true, the result of the conditional 12699 // expression is the value of the second expression, otherwise that of the 12700 // third expression. Only one of the second and third expressions is 12701 // evaluated. [...] 12702 bool EvalResult = false; 12703 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 12704 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 12705 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 12706 if (ShouldVisitTrueExpr) { 12707 Region = TrueRegion; 12708 Visit(CO->getTrueExpr()); 12709 } 12710 if (ShouldVisitFalseExpr) { 12711 Region = FalseRegion; 12712 Visit(CO->getFalseExpr()); 12713 } 12714 12715 Region = OldRegion; 12716 Tree.merge(ConditionRegion); 12717 Tree.merge(TrueRegion); 12718 Tree.merge(FalseRegion); 12719 } 12720 12721 void VisitCallExpr(const CallExpr *CE) { 12722 // C++11 [intro.execution]p15: 12723 // When calling a function [...], every value computation and side effect 12724 // associated with any argument expression, or with the postfix expression 12725 // designating the called function, is sequenced before execution of every 12726 // expression or statement in the body of the function [and thus before 12727 // the value computation of its result]. 12728 SequencedSubexpression Sequenced(*this); 12729 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), 12730 [&] { Base::VisitCallExpr(CE); }); 12731 12732 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12733 } 12734 12735 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 12736 // This is a call, so all subexpressions are sequenced before the result. 12737 SequencedSubexpression Sequenced(*this); 12738 12739 if (!CCE->isListInitialization()) 12740 return VisitExpr(CCE); 12741 12742 // In C++11, list initializations are sequenced. 12743 SmallVector<SequenceTree::Seq, 32> Elts; 12744 SequenceTree::Seq Parent = Region; 12745 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 12746 E = CCE->arg_end(); 12747 I != E; ++I) { 12748 Region = Tree.allocate(Parent); 12749 Elts.push_back(Region); 12750 Visit(*I); 12751 } 12752 12753 // Forget that the initializers are sequenced. 12754 Region = Parent; 12755 for (unsigned I = 0; I < Elts.size(); ++I) 12756 Tree.merge(Elts[I]); 12757 } 12758 12759 void VisitInitListExpr(const InitListExpr *ILE) { 12760 if (!SemaRef.getLangOpts().CPlusPlus11) 12761 return VisitExpr(ILE); 12762 12763 // In C++11, list initializations are sequenced. 12764 SmallVector<SequenceTree::Seq, 32> Elts; 12765 SequenceTree::Seq Parent = Region; 12766 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 12767 const Expr *E = ILE->getInit(I); 12768 if (!E) 12769 continue; 12770 Region = Tree.allocate(Parent); 12771 Elts.push_back(Region); 12772 Visit(E); 12773 } 12774 12775 // Forget that the initializers are sequenced. 12776 Region = Parent; 12777 for (unsigned I = 0; I < Elts.size(); ++I) 12778 Tree.merge(Elts[I]); 12779 } 12780 }; 12781 12782 } // namespace 12783 12784 void Sema::CheckUnsequencedOperations(const Expr *E) { 12785 SmallVector<const Expr *, 8> WorkList; 12786 WorkList.push_back(E); 12787 while (!WorkList.empty()) { 12788 const Expr *Item = WorkList.pop_back_val(); 12789 SequenceChecker(*this, Item, WorkList); 12790 } 12791 } 12792 12793 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 12794 bool IsConstexpr) { 12795 llvm::SaveAndRestore<bool> ConstantContext( 12796 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 12797 CheckImplicitConversions(E, CheckLoc); 12798 if (!E->isInstantiationDependent()) 12799 CheckUnsequencedOperations(E); 12800 if (!IsConstexpr && !E->isValueDependent()) 12801 CheckForIntOverflow(E); 12802 DiagnoseMisalignedMembers(); 12803 } 12804 12805 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 12806 FieldDecl *BitField, 12807 Expr *Init) { 12808 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 12809 } 12810 12811 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 12812 SourceLocation Loc) { 12813 if (!PType->isVariablyModifiedType()) 12814 return; 12815 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 12816 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 12817 return; 12818 } 12819 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 12820 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 12821 return; 12822 } 12823 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 12824 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 12825 return; 12826 } 12827 12828 const ArrayType *AT = S.Context.getAsArrayType(PType); 12829 if (!AT) 12830 return; 12831 12832 if (AT->getSizeModifier() != ArrayType::Star) { 12833 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 12834 return; 12835 } 12836 12837 S.Diag(Loc, diag::err_array_star_in_function_definition); 12838 } 12839 12840 /// CheckParmsForFunctionDef - Check that the parameters of the given 12841 /// function are appropriate for the definition of a function. This 12842 /// takes care of any checks that cannot be performed on the 12843 /// declaration itself, e.g., that the types of each of the function 12844 /// parameters are complete. 12845 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 12846 bool CheckParameterNames) { 12847 bool HasInvalidParm = false; 12848 for (ParmVarDecl *Param : Parameters) { 12849 // C99 6.7.5.3p4: the parameters in a parameter type list in a 12850 // function declarator that is part of a function definition of 12851 // that function shall not have incomplete type. 12852 // 12853 // This is also C++ [dcl.fct]p6. 12854 if (!Param->isInvalidDecl() && 12855 RequireCompleteType(Param->getLocation(), Param->getType(), 12856 diag::err_typecheck_decl_incomplete_type)) { 12857 Param->setInvalidDecl(); 12858 HasInvalidParm = true; 12859 } 12860 12861 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12862 // declaration of each parameter shall include an identifier. 12863 if (CheckParameterNames && 12864 Param->getIdentifier() == nullptr && 12865 !Param->isImplicit() && 12866 !getLangOpts().CPlusPlus) 12867 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12868 12869 // C99 6.7.5.3p12: 12870 // If the function declarator is not part of a definition of that 12871 // function, parameters may have incomplete type and may use the [*] 12872 // notation in their sequences of declarator specifiers to specify 12873 // variable length array types. 12874 QualType PType = Param->getOriginalType(); 12875 // FIXME: This diagnostic should point the '[*]' if source-location 12876 // information is added for it. 12877 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 12878 12879 // If the parameter is a c++ class type and it has to be destructed in the 12880 // callee function, declare the destructor so that it can be called by the 12881 // callee function. Do not perform any direct access check on the dtor here. 12882 if (!Param->isInvalidDecl()) { 12883 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 12884 if (!ClassDecl->isInvalidDecl() && 12885 !ClassDecl->hasIrrelevantDestructor() && 12886 !ClassDecl->isDependentContext() && 12887 ClassDecl->isParamDestroyedInCallee()) { 12888 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12889 MarkFunctionReferenced(Param->getLocation(), Destructor); 12890 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 12891 } 12892 } 12893 } 12894 12895 // Parameters with the pass_object_size attribute only need to be marked 12896 // constant at function definitions. Because we lack information about 12897 // whether we're on a declaration or definition when we're instantiating the 12898 // attribute, we need to check for constness here. 12899 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 12900 if (!Param->getType().isConstQualified()) 12901 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 12902 << Attr->getSpelling() << 1; 12903 12904 // Check for parameter names shadowing fields from the class. 12905 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 12906 // The owning context for the parameter should be the function, but we 12907 // want to see if this function's declaration context is a record. 12908 DeclContext *DC = Param->getDeclContext(); 12909 if (DC && DC->isFunctionOrMethod()) { 12910 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 12911 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 12912 RD, /*DeclIsField*/ false); 12913 } 12914 } 12915 } 12916 12917 return HasInvalidParm; 12918 } 12919 12920 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 12921 /// or MemberExpr. 12922 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 12923 ASTContext &Context) { 12924 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 12925 return Context.getDeclAlign(DRE->getDecl()); 12926 12927 if (const auto *ME = dyn_cast<MemberExpr>(E)) 12928 return Context.getDeclAlign(ME->getMemberDecl()); 12929 12930 return TypeAlign; 12931 } 12932 12933 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12934 /// pointer cast increases the alignment requirements. 12935 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12936 // This is actually a lot of work to potentially be doing on every 12937 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12938 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12939 return; 12940 12941 // Ignore dependent types. 12942 if (T->isDependentType() || Op->getType()->isDependentType()) 12943 return; 12944 12945 // Require that the destination be a pointer type. 12946 const PointerType *DestPtr = T->getAs<PointerType>(); 12947 if (!DestPtr) return; 12948 12949 // If the destination has alignment 1, we're done. 12950 QualType DestPointee = DestPtr->getPointeeType(); 12951 if (DestPointee->isIncompleteType()) return; 12952 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12953 if (DestAlign.isOne()) return; 12954 12955 // Require that the source be a pointer type. 12956 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12957 if (!SrcPtr) return; 12958 QualType SrcPointee = SrcPtr->getPointeeType(); 12959 12960 // Whitelist casts from cv void*. We already implicitly 12961 // whitelisted casts to cv void*, since they have alignment 1. 12962 // Also whitelist casts involving incomplete types, which implicitly 12963 // includes 'void'. 12964 if (SrcPointee->isIncompleteType()) return; 12965 12966 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12967 12968 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12969 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12970 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12971 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12972 if (UO->getOpcode() == UO_AddrOf) 12973 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12974 } 12975 12976 if (SrcAlign >= DestAlign) return; 12977 12978 Diag(TRange.getBegin(), diag::warn_cast_align) 12979 << Op->getType() << T 12980 << static_cast<unsigned>(SrcAlign.getQuantity()) 12981 << static_cast<unsigned>(DestAlign.getQuantity()) 12982 << TRange << Op->getSourceRange(); 12983 } 12984 12985 /// Check whether this array fits the idiom of a size-one tail padded 12986 /// array member of a struct. 12987 /// 12988 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12989 /// commonly used to emulate flexible arrays in C89 code. 12990 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12991 const NamedDecl *ND) { 12992 if (Size != 1 || !ND) return false; 12993 12994 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12995 if (!FD) return false; 12996 12997 // Don't consider sizes resulting from macro expansions or template argument 12998 // substitution to form C89 tail-padded arrays. 12999 13000 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 13001 while (TInfo) { 13002 TypeLoc TL = TInfo->getTypeLoc(); 13003 // Look through typedefs. 13004 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13005 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13006 TInfo = TDL->getTypeSourceInfo(); 13007 continue; 13008 } 13009 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13010 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13011 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13012 return false; 13013 } 13014 break; 13015 } 13016 13017 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13018 if (!RD) return false; 13019 if (RD->isUnion()) return false; 13020 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13021 if (!CRD->isStandardLayout()) return false; 13022 } 13023 13024 // See if this is the last field decl in the record. 13025 const Decl *D = FD; 13026 while ((D = D->getNextDeclInContext())) 13027 if (isa<FieldDecl>(D)) 13028 return false; 13029 return true; 13030 } 13031 13032 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13033 const ArraySubscriptExpr *ASE, 13034 bool AllowOnePastEnd, bool IndexNegated) { 13035 // Already diagnosed by the constant evaluator. 13036 if (isConstantEvaluated()) 13037 return; 13038 13039 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13040 if (IndexExpr->isValueDependent()) 13041 return; 13042 13043 const Type *EffectiveType = 13044 BaseExpr->getType()->getPointeeOrArrayElementType(); 13045 BaseExpr = BaseExpr->IgnoreParenCasts(); 13046 const ConstantArrayType *ArrayTy = 13047 Context.getAsConstantArrayType(BaseExpr->getType()); 13048 13049 if (!ArrayTy) 13050 return; 13051 13052 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13053 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13054 return; 13055 13056 Expr::EvalResult Result; 13057 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13058 return; 13059 13060 llvm::APSInt index = Result.Val.getInt(); 13061 if (IndexNegated) 13062 index = -index; 13063 13064 const NamedDecl *ND = nullptr; 13065 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13066 ND = DRE->getDecl(); 13067 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13068 ND = ME->getMemberDecl(); 13069 13070 if (index.isUnsigned() || !index.isNegative()) { 13071 // It is possible that the type of the base expression after 13072 // IgnoreParenCasts is incomplete, even though the type of the base 13073 // expression before IgnoreParenCasts is complete (see PR39746 for an 13074 // example). In this case we have no information about whether the array 13075 // access exceeds the array bounds. However we can still diagnose an array 13076 // access which precedes the array bounds. 13077 if (BaseType->isIncompleteType()) 13078 return; 13079 13080 llvm::APInt size = ArrayTy->getSize(); 13081 if (!size.isStrictlyPositive()) 13082 return; 13083 13084 if (BaseType != EffectiveType) { 13085 // Make sure we're comparing apples to apples when comparing index to size 13086 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13087 uint64_t array_typesize = Context.getTypeSize(BaseType); 13088 // Handle ptrarith_typesize being zero, such as when casting to void* 13089 if (!ptrarith_typesize) ptrarith_typesize = 1; 13090 if (ptrarith_typesize != array_typesize) { 13091 // There's a cast to a different size type involved 13092 uint64_t ratio = array_typesize / ptrarith_typesize; 13093 // TODO: Be smarter about handling cases where array_typesize is not a 13094 // multiple of ptrarith_typesize 13095 if (ptrarith_typesize * ratio == array_typesize) 13096 size *= llvm::APInt(size.getBitWidth(), ratio); 13097 } 13098 } 13099 13100 if (size.getBitWidth() > index.getBitWidth()) 13101 index = index.zext(size.getBitWidth()); 13102 else if (size.getBitWidth() < index.getBitWidth()) 13103 size = size.zext(index.getBitWidth()); 13104 13105 // For array subscripting the index must be less than size, but for pointer 13106 // arithmetic also allow the index (offset) to be equal to size since 13107 // computing the next address after the end of the array is legal and 13108 // commonly done e.g. in C++ iterators and range-based for loops. 13109 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13110 return; 13111 13112 // Also don't warn for arrays of size 1 which are members of some 13113 // structure. These are often used to approximate flexible arrays in C89 13114 // code. 13115 if (IsTailPaddedMemberArray(*this, size, ND)) 13116 return; 13117 13118 // Suppress the warning if the subscript expression (as identified by the 13119 // ']' location) and the index expression are both from macro expansions 13120 // within a system header. 13121 if (ASE) { 13122 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13123 ASE->getRBracketLoc()); 13124 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13125 SourceLocation IndexLoc = 13126 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13127 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13128 return; 13129 } 13130 } 13131 13132 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13133 if (ASE) 13134 DiagID = diag::warn_array_index_exceeds_bounds; 13135 13136 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13137 PDiag(DiagID) << index.toString(10, true) 13138 << size.toString(10, true) 13139 << (unsigned)size.getLimitedValue(~0U) 13140 << IndexExpr->getSourceRange()); 13141 } else { 13142 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13143 if (!ASE) { 13144 DiagID = diag::warn_ptr_arith_precedes_bounds; 13145 if (index.isNegative()) index = -index; 13146 } 13147 13148 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13149 PDiag(DiagID) << index.toString(10, true) 13150 << IndexExpr->getSourceRange()); 13151 } 13152 13153 if (!ND) { 13154 // Try harder to find a NamedDecl to point at in the note. 13155 while (const ArraySubscriptExpr *ASE = 13156 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13157 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13158 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13159 ND = DRE->getDecl(); 13160 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13161 ND = ME->getMemberDecl(); 13162 } 13163 13164 if (ND) 13165 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13166 PDiag(diag::note_array_declared_here) 13167 << ND->getDeclName()); 13168 } 13169 13170 void Sema::CheckArrayAccess(const Expr *expr) { 13171 int AllowOnePastEnd = 0; 13172 while (expr) { 13173 expr = expr->IgnoreParenImpCasts(); 13174 switch (expr->getStmtClass()) { 13175 case Stmt::ArraySubscriptExprClass: { 13176 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13177 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13178 AllowOnePastEnd > 0); 13179 expr = ASE->getBase(); 13180 break; 13181 } 13182 case Stmt::MemberExprClass: { 13183 expr = cast<MemberExpr>(expr)->getBase(); 13184 break; 13185 } 13186 case Stmt::OMPArraySectionExprClass: { 13187 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13188 if (ASE->getLowerBound()) 13189 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13190 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13191 return; 13192 } 13193 case Stmt::UnaryOperatorClass: { 13194 // Only unwrap the * and & unary operators 13195 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13196 expr = UO->getSubExpr(); 13197 switch (UO->getOpcode()) { 13198 case UO_AddrOf: 13199 AllowOnePastEnd++; 13200 break; 13201 case UO_Deref: 13202 AllowOnePastEnd--; 13203 break; 13204 default: 13205 return; 13206 } 13207 break; 13208 } 13209 case Stmt::ConditionalOperatorClass: { 13210 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13211 if (const Expr *lhs = cond->getLHS()) 13212 CheckArrayAccess(lhs); 13213 if (const Expr *rhs = cond->getRHS()) 13214 CheckArrayAccess(rhs); 13215 return; 13216 } 13217 case Stmt::CXXOperatorCallExprClass: { 13218 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13219 for (const auto *Arg : OCE->arguments()) 13220 CheckArrayAccess(Arg); 13221 return; 13222 } 13223 default: 13224 return; 13225 } 13226 } 13227 } 13228 13229 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13230 13231 namespace { 13232 13233 struct RetainCycleOwner { 13234 VarDecl *Variable = nullptr; 13235 SourceRange Range; 13236 SourceLocation Loc; 13237 bool Indirect = false; 13238 13239 RetainCycleOwner() = default; 13240 13241 void setLocsFrom(Expr *e) { 13242 Loc = e->getExprLoc(); 13243 Range = e->getSourceRange(); 13244 } 13245 }; 13246 13247 } // namespace 13248 13249 /// Consider whether capturing the given variable can possibly lead to 13250 /// a retain cycle. 13251 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 13252 // In ARC, it's captured strongly iff the variable has __strong 13253 // lifetime. In MRR, it's captured strongly if the variable is 13254 // __block and has an appropriate type. 13255 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13256 return false; 13257 13258 owner.Variable = var; 13259 if (ref) 13260 owner.setLocsFrom(ref); 13261 return true; 13262 } 13263 13264 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13265 while (true) { 13266 e = e->IgnoreParens(); 13267 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13268 switch (cast->getCastKind()) { 13269 case CK_BitCast: 13270 case CK_LValueBitCast: 13271 case CK_LValueToRValue: 13272 case CK_ARCReclaimReturnedObject: 13273 e = cast->getSubExpr(); 13274 continue; 13275 13276 default: 13277 return false; 13278 } 13279 } 13280 13281 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13282 ObjCIvarDecl *ivar = ref->getDecl(); 13283 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13284 return false; 13285 13286 // Try to find a retain cycle in the base. 13287 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13288 return false; 13289 13290 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13291 owner.Indirect = true; 13292 return true; 13293 } 13294 13295 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13296 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13297 if (!var) return false; 13298 return considerVariable(var, ref, owner); 13299 } 13300 13301 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13302 if (member->isArrow()) return false; 13303 13304 // Don't count this as an indirect ownership. 13305 e = member->getBase(); 13306 continue; 13307 } 13308 13309 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13310 // Only pay attention to pseudo-objects on property references. 13311 ObjCPropertyRefExpr *pre 13312 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13313 ->IgnoreParens()); 13314 if (!pre) return false; 13315 if (pre->isImplicitProperty()) return false; 13316 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13317 if (!property->isRetaining() && 13318 !(property->getPropertyIvarDecl() && 13319 property->getPropertyIvarDecl()->getType() 13320 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13321 return false; 13322 13323 owner.Indirect = true; 13324 if (pre->isSuperReceiver()) { 13325 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13326 if (!owner.Variable) 13327 return false; 13328 owner.Loc = pre->getLocation(); 13329 owner.Range = pre->getSourceRange(); 13330 return true; 13331 } 13332 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13333 ->getSourceExpr()); 13334 continue; 13335 } 13336 13337 // Array ivars? 13338 13339 return false; 13340 } 13341 } 13342 13343 namespace { 13344 13345 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 13346 ASTContext &Context; 13347 VarDecl *Variable; 13348 Expr *Capturer = nullptr; 13349 bool VarWillBeReased = false; 13350 13351 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 13352 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 13353 Context(Context), Variable(variable) {} 13354 13355 void VisitDeclRefExpr(DeclRefExpr *ref) { 13356 if (ref->getDecl() == Variable && !Capturer) 13357 Capturer = ref; 13358 } 13359 13360 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 13361 if (Capturer) return; 13362 Visit(ref->getBase()); 13363 if (Capturer && ref->isFreeIvar()) 13364 Capturer = ref; 13365 } 13366 13367 void VisitBlockExpr(BlockExpr *block) { 13368 // Look inside nested blocks 13369 if (block->getBlockDecl()->capturesVariable(Variable)) 13370 Visit(block->getBlockDecl()->getBody()); 13371 } 13372 13373 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 13374 if (Capturer) return; 13375 if (OVE->getSourceExpr()) 13376 Visit(OVE->getSourceExpr()); 13377 } 13378 13379 void VisitBinaryOperator(BinaryOperator *BinOp) { 13380 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 13381 return; 13382 Expr *LHS = BinOp->getLHS(); 13383 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 13384 if (DRE->getDecl() != Variable) 13385 return; 13386 if (Expr *RHS = BinOp->getRHS()) { 13387 RHS = RHS->IgnoreParenCasts(); 13388 llvm::APSInt Value; 13389 VarWillBeReased = 13390 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 13391 } 13392 } 13393 } 13394 }; 13395 13396 } // namespace 13397 13398 /// Check whether the given argument is a block which captures a 13399 /// variable. 13400 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 13401 assert(owner.Variable && owner.Loc.isValid()); 13402 13403 e = e->IgnoreParenCasts(); 13404 13405 // Look through [^{...} copy] and Block_copy(^{...}). 13406 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 13407 Selector Cmd = ME->getSelector(); 13408 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 13409 e = ME->getInstanceReceiver(); 13410 if (!e) 13411 return nullptr; 13412 e = e->IgnoreParenCasts(); 13413 } 13414 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 13415 if (CE->getNumArgs() == 1) { 13416 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 13417 if (Fn) { 13418 const IdentifierInfo *FnI = Fn->getIdentifier(); 13419 if (FnI && FnI->isStr("_Block_copy")) { 13420 e = CE->getArg(0)->IgnoreParenCasts(); 13421 } 13422 } 13423 } 13424 } 13425 13426 BlockExpr *block = dyn_cast<BlockExpr>(e); 13427 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 13428 return nullptr; 13429 13430 FindCaptureVisitor visitor(S.Context, owner.Variable); 13431 visitor.Visit(block->getBlockDecl()->getBody()); 13432 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 13433 } 13434 13435 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 13436 RetainCycleOwner &owner) { 13437 assert(capturer); 13438 assert(owner.Variable && owner.Loc.isValid()); 13439 13440 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 13441 << owner.Variable << capturer->getSourceRange(); 13442 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 13443 << owner.Indirect << owner.Range; 13444 } 13445 13446 /// Check for a keyword selector that starts with the word 'add' or 13447 /// 'set'. 13448 static bool isSetterLikeSelector(Selector sel) { 13449 if (sel.isUnarySelector()) return false; 13450 13451 StringRef str = sel.getNameForSlot(0); 13452 while (!str.empty() && str.front() == '_') str = str.substr(1); 13453 if (str.startswith("set")) 13454 str = str.substr(3); 13455 else if (str.startswith("add")) { 13456 // Specially whitelist 'addOperationWithBlock:'. 13457 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 13458 return false; 13459 str = str.substr(3); 13460 } 13461 else 13462 return false; 13463 13464 if (str.empty()) return true; 13465 return !isLowercase(str.front()); 13466 } 13467 13468 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 13469 ObjCMessageExpr *Message) { 13470 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 13471 Message->getReceiverInterface(), 13472 NSAPI::ClassId_NSMutableArray); 13473 if (!IsMutableArray) { 13474 return None; 13475 } 13476 13477 Selector Sel = Message->getSelector(); 13478 13479 Optional<NSAPI::NSArrayMethodKind> MKOpt = 13480 S.NSAPIObj->getNSArrayMethodKind(Sel); 13481 if (!MKOpt) { 13482 return None; 13483 } 13484 13485 NSAPI::NSArrayMethodKind MK = *MKOpt; 13486 13487 switch (MK) { 13488 case NSAPI::NSMutableArr_addObject: 13489 case NSAPI::NSMutableArr_insertObjectAtIndex: 13490 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 13491 return 0; 13492 case NSAPI::NSMutableArr_replaceObjectAtIndex: 13493 return 1; 13494 13495 default: 13496 return None; 13497 } 13498 13499 return None; 13500 } 13501 13502 static 13503 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 13504 ObjCMessageExpr *Message) { 13505 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 13506 Message->getReceiverInterface(), 13507 NSAPI::ClassId_NSMutableDictionary); 13508 if (!IsMutableDictionary) { 13509 return None; 13510 } 13511 13512 Selector Sel = Message->getSelector(); 13513 13514 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13515 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13516 if (!MKOpt) { 13517 return None; 13518 } 13519 13520 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 13521 13522 switch (MK) { 13523 case NSAPI::NSMutableDict_setObjectForKey: 13524 case NSAPI::NSMutableDict_setValueForKey: 13525 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 13526 return 0; 13527 13528 default: 13529 return None; 13530 } 13531 13532 return None; 13533 } 13534 13535 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 13536 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 13537 Message->getReceiverInterface(), 13538 NSAPI::ClassId_NSMutableSet); 13539 13540 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 13541 Message->getReceiverInterface(), 13542 NSAPI::ClassId_NSMutableOrderedSet); 13543 if (!IsMutableSet && !IsMutableOrderedSet) { 13544 return None; 13545 } 13546 13547 Selector Sel = Message->getSelector(); 13548 13549 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 13550 if (!MKOpt) { 13551 return None; 13552 } 13553 13554 NSAPI::NSSetMethodKind MK = *MKOpt; 13555 13556 switch (MK) { 13557 case NSAPI::NSMutableSet_addObject: 13558 case NSAPI::NSOrderedSet_setObjectAtIndex: 13559 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 13560 case NSAPI::NSOrderedSet_insertObjectAtIndex: 13561 return 0; 13562 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 13563 return 1; 13564 } 13565 13566 return None; 13567 } 13568 13569 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 13570 if (!Message->isInstanceMessage()) { 13571 return; 13572 } 13573 13574 Optional<int> ArgOpt; 13575 13576 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 13577 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 13578 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 13579 return; 13580 } 13581 13582 int ArgIndex = *ArgOpt; 13583 13584 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 13585 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 13586 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 13587 } 13588 13589 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 13590 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13591 if (ArgRE->isObjCSelfExpr()) { 13592 Diag(Message->getSourceRange().getBegin(), 13593 diag::warn_objc_circular_container) 13594 << ArgRE->getDecl() << StringRef("'super'"); 13595 } 13596 } 13597 } else { 13598 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 13599 13600 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 13601 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 13602 } 13603 13604 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 13605 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13606 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 13607 ValueDecl *Decl = ReceiverRE->getDecl(); 13608 Diag(Message->getSourceRange().getBegin(), 13609 diag::warn_objc_circular_container) 13610 << Decl << Decl; 13611 if (!ArgRE->isObjCSelfExpr()) { 13612 Diag(Decl->getLocation(), 13613 diag::note_objc_circular_container_declared_here) 13614 << Decl; 13615 } 13616 } 13617 } 13618 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 13619 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 13620 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 13621 ObjCIvarDecl *Decl = IvarRE->getDecl(); 13622 Diag(Message->getSourceRange().getBegin(), 13623 diag::warn_objc_circular_container) 13624 << Decl << Decl; 13625 Diag(Decl->getLocation(), 13626 diag::note_objc_circular_container_declared_here) 13627 << Decl; 13628 } 13629 } 13630 } 13631 } 13632 } 13633 13634 /// Check a message send to see if it's likely to cause a retain cycle. 13635 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 13636 // Only check instance methods whose selector looks like a setter. 13637 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 13638 return; 13639 13640 // Try to find a variable that the receiver is strongly owned by. 13641 RetainCycleOwner owner; 13642 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 13643 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 13644 return; 13645 } else { 13646 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 13647 owner.Variable = getCurMethodDecl()->getSelfDecl(); 13648 owner.Loc = msg->getSuperLoc(); 13649 owner.Range = msg->getSuperLoc(); 13650 } 13651 13652 // Check whether the receiver is captured by any of the arguments. 13653 const ObjCMethodDecl *MD = msg->getMethodDecl(); 13654 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 13655 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 13656 // noescape blocks should not be retained by the method. 13657 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 13658 continue; 13659 return diagnoseRetainCycle(*this, capturer, owner); 13660 } 13661 } 13662 } 13663 13664 /// Check a property assign to see if it's likely to cause a retain cycle. 13665 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 13666 RetainCycleOwner owner; 13667 if (!findRetainCycleOwner(*this, receiver, owner)) 13668 return; 13669 13670 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 13671 diagnoseRetainCycle(*this, capturer, owner); 13672 } 13673 13674 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 13675 RetainCycleOwner Owner; 13676 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 13677 return; 13678 13679 // Because we don't have an expression for the variable, we have to set the 13680 // location explicitly here. 13681 Owner.Loc = Var->getLocation(); 13682 Owner.Range = Var->getSourceRange(); 13683 13684 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 13685 diagnoseRetainCycle(*this, Capturer, Owner); 13686 } 13687 13688 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 13689 Expr *RHS, bool isProperty) { 13690 // Check if RHS is an Objective-C object literal, which also can get 13691 // immediately zapped in a weak reference. Note that we explicitly 13692 // allow ObjCStringLiterals, since those are designed to never really die. 13693 RHS = RHS->IgnoreParenImpCasts(); 13694 13695 // This enum needs to match with the 'select' in 13696 // warn_objc_arc_literal_assign (off-by-1). 13697 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 13698 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 13699 return false; 13700 13701 S.Diag(Loc, diag::warn_arc_literal_assign) 13702 << (unsigned) Kind 13703 << (isProperty ? 0 : 1) 13704 << RHS->getSourceRange(); 13705 13706 return true; 13707 } 13708 13709 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 13710 Qualifiers::ObjCLifetime LT, 13711 Expr *RHS, bool isProperty) { 13712 // Strip off any implicit cast added to get to the one ARC-specific. 13713 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13714 if (cast->getCastKind() == CK_ARCConsumeObject) { 13715 S.Diag(Loc, diag::warn_arc_retained_assign) 13716 << (LT == Qualifiers::OCL_ExplicitNone) 13717 << (isProperty ? 0 : 1) 13718 << RHS->getSourceRange(); 13719 return true; 13720 } 13721 RHS = cast->getSubExpr(); 13722 } 13723 13724 if (LT == Qualifiers::OCL_Weak && 13725 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 13726 return true; 13727 13728 return false; 13729 } 13730 13731 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 13732 QualType LHS, Expr *RHS) { 13733 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 13734 13735 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 13736 return false; 13737 13738 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 13739 return true; 13740 13741 return false; 13742 } 13743 13744 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 13745 Expr *LHS, Expr *RHS) { 13746 QualType LHSType; 13747 // PropertyRef on LHS type need be directly obtained from 13748 // its declaration as it has a PseudoType. 13749 ObjCPropertyRefExpr *PRE 13750 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 13751 if (PRE && !PRE->isImplicitProperty()) { 13752 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13753 if (PD) 13754 LHSType = PD->getType(); 13755 } 13756 13757 if (LHSType.isNull()) 13758 LHSType = LHS->getType(); 13759 13760 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 13761 13762 if (LT == Qualifiers::OCL_Weak) { 13763 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 13764 getCurFunction()->markSafeWeakUse(LHS); 13765 } 13766 13767 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 13768 return; 13769 13770 // FIXME. Check for other life times. 13771 if (LT != Qualifiers::OCL_None) 13772 return; 13773 13774 if (PRE) { 13775 if (PRE->isImplicitProperty()) 13776 return; 13777 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13778 if (!PD) 13779 return; 13780 13781 unsigned Attributes = PD->getPropertyAttributes(); 13782 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 13783 // when 'assign' attribute was not explicitly specified 13784 // by user, ignore it and rely on property type itself 13785 // for lifetime info. 13786 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 13787 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 13788 LHSType->isObjCRetainableType()) 13789 return; 13790 13791 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13792 if (cast->getCastKind() == CK_ARCConsumeObject) { 13793 Diag(Loc, diag::warn_arc_retained_property_assign) 13794 << RHS->getSourceRange(); 13795 return; 13796 } 13797 RHS = cast->getSubExpr(); 13798 } 13799 } 13800 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 13801 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 13802 return; 13803 } 13804 } 13805 } 13806 13807 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 13808 13809 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 13810 SourceLocation StmtLoc, 13811 const NullStmt *Body) { 13812 // Do not warn if the body is a macro that expands to nothing, e.g: 13813 // 13814 // #define CALL(x) 13815 // if (condition) 13816 // CALL(0); 13817 if (Body->hasLeadingEmptyMacro()) 13818 return false; 13819 13820 // Get line numbers of statement and body. 13821 bool StmtLineInvalid; 13822 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 13823 &StmtLineInvalid); 13824 if (StmtLineInvalid) 13825 return false; 13826 13827 bool BodyLineInvalid; 13828 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 13829 &BodyLineInvalid); 13830 if (BodyLineInvalid) 13831 return false; 13832 13833 // Warn if null statement and body are on the same line. 13834 if (StmtLine != BodyLine) 13835 return false; 13836 13837 return true; 13838 } 13839 13840 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 13841 const Stmt *Body, 13842 unsigned DiagID) { 13843 // Since this is a syntactic check, don't emit diagnostic for template 13844 // instantiations, this just adds noise. 13845 if (CurrentInstantiationScope) 13846 return; 13847 13848 // The body should be a null statement. 13849 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13850 if (!NBody) 13851 return; 13852 13853 // Do the usual checks. 13854 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13855 return; 13856 13857 Diag(NBody->getSemiLoc(), DiagID); 13858 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13859 } 13860 13861 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 13862 const Stmt *PossibleBody) { 13863 assert(!CurrentInstantiationScope); // Ensured by caller 13864 13865 SourceLocation StmtLoc; 13866 const Stmt *Body; 13867 unsigned DiagID; 13868 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 13869 StmtLoc = FS->getRParenLoc(); 13870 Body = FS->getBody(); 13871 DiagID = diag::warn_empty_for_body; 13872 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 13873 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 13874 Body = WS->getBody(); 13875 DiagID = diag::warn_empty_while_body; 13876 } else 13877 return; // Neither `for' nor `while'. 13878 13879 // The body should be a null statement. 13880 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13881 if (!NBody) 13882 return; 13883 13884 // Skip expensive checks if diagnostic is disabled. 13885 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 13886 return; 13887 13888 // Do the usual checks. 13889 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13890 return; 13891 13892 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13893 // noise level low, emit diagnostics only if for/while is followed by a 13894 // CompoundStmt, e.g.: 13895 // for (int i = 0; i < n; i++); 13896 // { 13897 // a(i); 13898 // } 13899 // or if for/while is followed by a statement with more indentation 13900 // than for/while itself: 13901 // for (int i = 0; i < n; i++); 13902 // a(i); 13903 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13904 if (!ProbableTypo) { 13905 bool BodyColInvalid; 13906 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13907 PossibleBody->getBeginLoc(), &BodyColInvalid); 13908 if (BodyColInvalid) 13909 return; 13910 13911 bool StmtColInvalid; 13912 unsigned StmtCol = 13913 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13914 if (StmtColInvalid) 13915 return; 13916 13917 if (BodyCol > StmtCol) 13918 ProbableTypo = true; 13919 } 13920 13921 if (ProbableTypo) { 13922 Diag(NBody->getSemiLoc(), DiagID); 13923 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13924 } 13925 } 13926 13927 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13928 13929 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 13930 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13931 SourceLocation OpLoc) { 13932 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13933 return; 13934 13935 if (inTemplateInstantiation()) 13936 return; 13937 13938 // Strip parens and casts away. 13939 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13940 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13941 13942 // Check for a call expression 13943 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 13944 if (!CE || CE->getNumArgs() != 1) 13945 return; 13946 13947 // Check for a call to std::move 13948 if (!CE->isCallToStdMove()) 13949 return; 13950 13951 // Get argument from std::move 13952 RHSExpr = CE->getArg(0); 13953 13954 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13955 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13956 13957 // Two DeclRefExpr's, check that the decls are the same. 13958 if (LHSDeclRef && RHSDeclRef) { 13959 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13960 return; 13961 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13962 RHSDeclRef->getDecl()->getCanonicalDecl()) 13963 return; 13964 13965 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13966 << LHSExpr->getSourceRange() 13967 << RHSExpr->getSourceRange(); 13968 return; 13969 } 13970 13971 // Member variables require a different approach to check for self moves. 13972 // MemberExpr's are the same if every nested MemberExpr refers to the same 13973 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13974 // the base Expr's are CXXThisExpr's. 13975 const Expr *LHSBase = LHSExpr; 13976 const Expr *RHSBase = RHSExpr; 13977 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13978 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13979 if (!LHSME || !RHSME) 13980 return; 13981 13982 while (LHSME && RHSME) { 13983 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13984 RHSME->getMemberDecl()->getCanonicalDecl()) 13985 return; 13986 13987 LHSBase = LHSME->getBase(); 13988 RHSBase = RHSME->getBase(); 13989 LHSME = dyn_cast<MemberExpr>(LHSBase); 13990 RHSME = dyn_cast<MemberExpr>(RHSBase); 13991 } 13992 13993 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13994 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13995 if (LHSDeclRef && RHSDeclRef) { 13996 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13997 return; 13998 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13999 RHSDeclRef->getDecl()->getCanonicalDecl()) 14000 return; 14001 14002 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14003 << LHSExpr->getSourceRange() 14004 << RHSExpr->getSourceRange(); 14005 return; 14006 } 14007 14008 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14009 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14010 << LHSExpr->getSourceRange() 14011 << RHSExpr->getSourceRange(); 14012 } 14013 14014 //===--- Layout compatibility ----------------------------------------------// 14015 14016 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14017 14018 /// Check if two enumeration types are layout-compatible. 14019 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14020 // C++11 [dcl.enum] p8: 14021 // Two enumeration types are layout-compatible if they have the same 14022 // underlying type. 14023 return ED1->isComplete() && ED2->isComplete() && 14024 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14025 } 14026 14027 /// Check if two fields are layout-compatible. 14028 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14029 FieldDecl *Field2) { 14030 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14031 return false; 14032 14033 if (Field1->isBitField() != Field2->isBitField()) 14034 return false; 14035 14036 if (Field1->isBitField()) { 14037 // Make sure that the bit-fields are the same length. 14038 unsigned Bits1 = Field1->getBitWidthValue(C); 14039 unsigned Bits2 = Field2->getBitWidthValue(C); 14040 14041 if (Bits1 != Bits2) 14042 return false; 14043 } 14044 14045 return true; 14046 } 14047 14048 /// Check if two standard-layout structs are layout-compatible. 14049 /// (C++11 [class.mem] p17) 14050 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14051 RecordDecl *RD2) { 14052 // If both records are C++ classes, check that base classes match. 14053 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14054 // If one of records is a CXXRecordDecl we are in C++ mode, 14055 // thus the other one is a CXXRecordDecl, too. 14056 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14057 // Check number of base classes. 14058 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14059 return false; 14060 14061 // Check the base classes. 14062 for (CXXRecordDecl::base_class_const_iterator 14063 Base1 = D1CXX->bases_begin(), 14064 BaseEnd1 = D1CXX->bases_end(), 14065 Base2 = D2CXX->bases_begin(); 14066 Base1 != BaseEnd1; 14067 ++Base1, ++Base2) { 14068 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14069 return false; 14070 } 14071 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14072 // If only RD2 is a C++ class, it should have zero base classes. 14073 if (D2CXX->getNumBases() > 0) 14074 return false; 14075 } 14076 14077 // Check the fields. 14078 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14079 Field2End = RD2->field_end(), 14080 Field1 = RD1->field_begin(), 14081 Field1End = RD1->field_end(); 14082 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14083 if (!isLayoutCompatible(C, *Field1, *Field2)) 14084 return false; 14085 } 14086 if (Field1 != Field1End || Field2 != Field2End) 14087 return false; 14088 14089 return true; 14090 } 14091 14092 /// Check if two standard-layout unions are layout-compatible. 14093 /// (C++11 [class.mem] p18) 14094 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14095 RecordDecl *RD2) { 14096 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14097 for (auto *Field2 : RD2->fields()) 14098 UnmatchedFields.insert(Field2); 14099 14100 for (auto *Field1 : RD1->fields()) { 14101 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14102 I = UnmatchedFields.begin(), 14103 E = UnmatchedFields.end(); 14104 14105 for ( ; I != E; ++I) { 14106 if (isLayoutCompatible(C, Field1, *I)) { 14107 bool Result = UnmatchedFields.erase(*I); 14108 (void) Result; 14109 assert(Result); 14110 break; 14111 } 14112 } 14113 if (I == E) 14114 return false; 14115 } 14116 14117 return UnmatchedFields.empty(); 14118 } 14119 14120 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14121 RecordDecl *RD2) { 14122 if (RD1->isUnion() != RD2->isUnion()) 14123 return false; 14124 14125 if (RD1->isUnion()) 14126 return isLayoutCompatibleUnion(C, RD1, RD2); 14127 else 14128 return isLayoutCompatibleStruct(C, RD1, RD2); 14129 } 14130 14131 /// Check if two types are layout-compatible in C++11 sense. 14132 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14133 if (T1.isNull() || T2.isNull()) 14134 return false; 14135 14136 // C++11 [basic.types] p11: 14137 // If two types T1 and T2 are the same type, then T1 and T2 are 14138 // layout-compatible types. 14139 if (C.hasSameType(T1, T2)) 14140 return true; 14141 14142 T1 = T1.getCanonicalType().getUnqualifiedType(); 14143 T2 = T2.getCanonicalType().getUnqualifiedType(); 14144 14145 const Type::TypeClass TC1 = T1->getTypeClass(); 14146 const Type::TypeClass TC2 = T2->getTypeClass(); 14147 14148 if (TC1 != TC2) 14149 return false; 14150 14151 if (TC1 == Type::Enum) { 14152 return isLayoutCompatible(C, 14153 cast<EnumType>(T1)->getDecl(), 14154 cast<EnumType>(T2)->getDecl()); 14155 } else if (TC1 == Type::Record) { 14156 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14157 return false; 14158 14159 return isLayoutCompatible(C, 14160 cast<RecordType>(T1)->getDecl(), 14161 cast<RecordType>(T2)->getDecl()); 14162 } 14163 14164 return false; 14165 } 14166 14167 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14168 14169 /// Given a type tag expression find the type tag itself. 14170 /// 14171 /// \param TypeExpr Type tag expression, as it appears in user's code. 14172 /// 14173 /// \param VD Declaration of an identifier that appears in a type tag. 14174 /// 14175 /// \param MagicValue Type tag magic value. 14176 /// 14177 /// \param isConstantEvaluated wether the evalaution should be performed in 14178 14179 /// constant context. 14180 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14181 const ValueDecl **VD, uint64_t *MagicValue, 14182 bool isConstantEvaluated) { 14183 while(true) { 14184 if (!TypeExpr) 14185 return false; 14186 14187 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14188 14189 switch (TypeExpr->getStmtClass()) { 14190 case Stmt::UnaryOperatorClass: { 14191 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14192 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14193 TypeExpr = UO->getSubExpr(); 14194 continue; 14195 } 14196 return false; 14197 } 14198 14199 case Stmt::DeclRefExprClass: { 14200 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14201 *VD = DRE->getDecl(); 14202 return true; 14203 } 14204 14205 case Stmt::IntegerLiteralClass: { 14206 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14207 llvm::APInt MagicValueAPInt = IL->getValue(); 14208 if (MagicValueAPInt.getActiveBits() <= 64) { 14209 *MagicValue = MagicValueAPInt.getZExtValue(); 14210 return true; 14211 } else 14212 return false; 14213 } 14214 14215 case Stmt::BinaryConditionalOperatorClass: 14216 case Stmt::ConditionalOperatorClass: { 14217 const AbstractConditionalOperator *ACO = 14218 cast<AbstractConditionalOperator>(TypeExpr); 14219 bool Result; 14220 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14221 isConstantEvaluated)) { 14222 if (Result) 14223 TypeExpr = ACO->getTrueExpr(); 14224 else 14225 TypeExpr = ACO->getFalseExpr(); 14226 continue; 14227 } 14228 return false; 14229 } 14230 14231 case Stmt::BinaryOperatorClass: { 14232 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14233 if (BO->getOpcode() == BO_Comma) { 14234 TypeExpr = BO->getRHS(); 14235 continue; 14236 } 14237 return false; 14238 } 14239 14240 default: 14241 return false; 14242 } 14243 } 14244 } 14245 14246 /// Retrieve the C type corresponding to type tag TypeExpr. 14247 /// 14248 /// \param TypeExpr Expression that specifies a type tag. 14249 /// 14250 /// \param MagicValues Registered magic values. 14251 /// 14252 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14253 /// kind. 14254 /// 14255 /// \param TypeInfo Information about the corresponding C type. 14256 /// 14257 /// \param isConstantEvaluated wether the evalaution should be performed in 14258 /// constant context. 14259 /// 14260 /// \returns true if the corresponding C type was found. 14261 static bool GetMatchingCType( 14262 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14263 const ASTContext &Ctx, 14264 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14265 *MagicValues, 14266 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14267 bool isConstantEvaluated) { 14268 FoundWrongKind = false; 14269 14270 // Variable declaration that has type_tag_for_datatype attribute. 14271 const ValueDecl *VD = nullptr; 14272 14273 uint64_t MagicValue; 14274 14275 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14276 return false; 14277 14278 if (VD) { 14279 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14280 if (I->getArgumentKind() != ArgumentKind) { 14281 FoundWrongKind = true; 14282 return false; 14283 } 14284 TypeInfo.Type = I->getMatchingCType(); 14285 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14286 TypeInfo.MustBeNull = I->getMustBeNull(); 14287 return true; 14288 } 14289 return false; 14290 } 14291 14292 if (!MagicValues) 14293 return false; 14294 14295 llvm::DenseMap<Sema::TypeTagMagicValue, 14296 Sema::TypeTagData>::const_iterator I = 14297 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14298 if (I == MagicValues->end()) 14299 return false; 14300 14301 TypeInfo = I->second; 14302 return true; 14303 } 14304 14305 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14306 uint64_t MagicValue, QualType Type, 14307 bool LayoutCompatible, 14308 bool MustBeNull) { 14309 if (!TypeTagForDatatypeMagicValues) 14310 TypeTagForDatatypeMagicValues.reset( 14311 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14312 14313 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14314 (*TypeTagForDatatypeMagicValues)[Magic] = 14315 TypeTagData(Type, LayoutCompatible, MustBeNull); 14316 } 14317 14318 static bool IsSameCharType(QualType T1, QualType T2) { 14319 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14320 if (!BT1) 14321 return false; 14322 14323 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14324 if (!BT2) 14325 return false; 14326 14327 BuiltinType::Kind T1Kind = BT1->getKind(); 14328 BuiltinType::Kind T2Kind = BT2->getKind(); 14329 14330 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14331 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14332 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14333 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14334 } 14335 14336 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14337 const ArrayRef<const Expr *> ExprArgs, 14338 SourceLocation CallSiteLoc) { 14339 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14340 bool IsPointerAttr = Attr->getIsPointer(); 14341 14342 // Retrieve the argument representing the 'type_tag'. 14343 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14344 if (TypeTagIdxAST >= ExprArgs.size()) { 14345 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14346 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14347 return; 14348 } 14349 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14350 bool FoundWrongKind; 14351 TypeTagData TypeInfo; 14352 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14353 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14354 TypeInfo, isConstantEvaluated())) { 14355 if (FoundWrongKind) 14356 Diag(TypeTagExpr->getExprLoc(), 14357 diag::warn_type_tag_for_datatype_wrong_kind) 14358 << TypeTagExpr->getSourceRange(); 14359 return; 14360 } 14361 14362 // Retrieve the argument representing the 'arg_idx'. 14363 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14364 if (ArgumentIdxAST >= ExprArgs.size()) { 14365 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14366 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14367 return; 14368 } 14369 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14370 if (IsPointerAttr) { 14371 // Skip implicit cast of pointer to `void *' (as a function argument). 14372 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14373 if (ICE->getType()->isVoidPointerType() && 14374 ICE->getCastKind() == CK_BitCast) 14375 ArgumentExpr = ICE->getSubExpr(); 14376 } 14377 QualType ArgumentType = ArgumentExpr->getType(); 14378 14379 // Passing a `void*' pointer shouldn't trigger a warning. 14380 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14381 return; 14382 14383 if (TypeInfo.MustBeNull) { 14384 // Type tag with matching void type requires a null pointer. 14385 if (!ArgumentExpr->isNullPointerConstant(Context, 14386 Expr::NPC_ValueDependentIsNotNull)) { 14387 Diag(ArgumentExpr->getExprLoc(), 14388 diag::warn_type_safety_null_pointer_required) 14389 << ArgumentKind->getName() 14390 << ArgumentExpr->getSourceRange() 14391 << TypeTagExpr->getSourceRange(); 14392 } 14393 return; 14394 } 14395 14396 QualType RequiredType = TypeInfo.Type; 14397 if (IsPointerAttr) 14398 RequiredType = Context.getPointerType(RequiredType); 14399 14400 bool mismatch = false; 14401 if (!TypeInfo.LayoutCompatible) { 14402 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14403 14404 // C++11 [basic.fundamental] p1: 14405 // Plain char, signed char, and unsigned char are three distinct types. 14406 // 14407 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14408 // char' depending on the current char signedness mode. 14409 if (mismatch) 14410 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14411 RequiredType->getPointeeType())) || 14412 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14413 mismatch = false; 14414 } else 14415 if (IsPointerAttr) 14416 mismatch = !isLayoutCompatible(Context, 14417 ArgumentType->getPointeeType(), 14418 RequiredType->getPointeeType()); 14419 else 14420 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14421 14422 if (mismatch) 14423 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14424 << ArgumentType << ArgumentKind 14425 << TypeInfo.LayoutCompatible << RequiredType 14426 << ArgumentExpr->getSourceRange() 14427 << TypeTagExpr->getSourceRange(); 14428 } 14429 14430 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14431 CharUnits Alignment) { 14432 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14433 } 14434 14435 void Sema::DiagnoseMisalignedMembers() { 14436 for (MisalignedMember &m : MisalignedMembers) { 14437 const NamedDecl *ND = m.RD; 14438 if (ND->getName().empty()) { 14439 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14440 ND = TD; 14441 } 14442 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14443 << m.MD << ND << m.E->getSourceRange(); 14444 } 14445 MisalignedMembers.clear(); 14446 } 14447 14448 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14449 E = E->IgnoreParens(); 14450 if (!T->isPointerType() && !T->isIntegerType()) 14451 return; 14452 if (isa<UnaryOperator>(E) && 14453 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14454 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14455 if (isa<MemberExpr>(Op)) { 14456 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14457 if (MA != MisalignedMembers.end() && 14458 (T->isIntegerType() || 14459 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14460 Context.getTypeAlignInChars( 14461 T->getPointeeType()) <= MA->Alignment)))) 14462 MisalignedMembers.erase(MA); 14463 } 14464 } 14465 } 14466 14467 void Sema::RefersToMemberWithReducedAlignment( 14468 Expr *E, 14469 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14470 Action) { 14471 const auto *ME = dyn_cast<MemberExpr>(E); 14472 if (!ME) 14473 return; 14474 14475 // No need to check expressions with an __unaligned-qualified type. 14476 if (E->getType().getQualifiers().hasUnaligned()) 14477 return; 14478 14479 // For a chain of MemberExpr like "a.b.c.d" this list 14480 // will keep FieldDecl's like [d, c, b]. 14481 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14482 const MemberExpr *TopME = nullptr; 14483 bool AnyIsPacked = false; 14484 do { 14485 QualType BaseType = ME->getBase()->getType(); 14486 if (BaseType->isDependentType()) 14487 return; 14488 if (ME->isArrow()) 14489 BaseType = BaseType->getPointeeType(); 14490 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 14491 if (RD->isInvalidDecl()) 14492 return; 14493 14494 ValueDecl *MD = ME->getMemberDecl(); 14495 auto *FD = dyn_cast<FieldDecl>(MD); 14496 // We do not care about non-data members. 14497 if (!FD || FD->isInvalidDecl()) 14498 return; 14499 14500 AnyIsPacked = 14501 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14502 ReverseMemberChain.push_back(FD); 14503 14504 TopME = ME; 14505 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14506 } while (ME); 14507 assert(TopME && "We did not compute a topmost MemberExpr!"); 14508 14509 // Not the scope of this diagnostic. 14510 if (!AnyIsPacked) 14511 return; 14512 14513 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14514 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14515 // TODO: The innermost base of the member expression may be too complicated. 14516 // For now, just disregard these cases. This is left for future 14517 // improvement. 14518 if (!DRE && !isa<CXXThisExpr>(TopBase)) 14519 return; 14520 14521 // Alignment expected by the whole expression. 14522 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 14523 14524 // No need to do anything else with this case. 14525 if (ExpectedAlignment.isOne()) 14526 return; 14527 14528 // Synthesize offset of the whole access. 14529 CharUnits Offset; 14530 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 14531 I++) { 14532 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 14533 } 14534 14535 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 14536 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 14537 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 14538 14539 // The base expression of the innermost MemberExpr may give 14540 // stronger guarantees than the class containing the member. 14541 if (DRE && !TopME->isArrow()) { 14542 const ValueDecl *VD = DRE->getDecl(); 14543 if (!VD->getType()->isReferenceType()) 14544 CompleteObjectAlignment = 14545 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 14546 } 14547 14548 // Check if the synthesized offset fulfills the alignment. 14549 if (Offset % ExpectedAlignment != 0 || 14550 // It may fulfill the offset it but the effective alignment may still be 14551 // lower than the expected expression alignment. 14552 CompleteObjectAlignment < ExpectedAlignment) { 14553 // If this happens, we want to determine a sensible culprit of this. 14554 // Intuitively, watching the chain of member expressions from right to 14555 // left, we start with the required alignment (as required by the field 14556 // type) but some packed attribute in that chain has reduced the alignment. 14557 // It may happen that another packed structure increases it again. But if 14558 // we are here such increase has not been enough. So pointing the first 14559 // FieldDecl that either is packed or else its RecordDecl is, 14560 // seems reasonable. 14561 FieldDecl *FD = nullptr; 14562 CharUnits Alignment; 14563 for (FieldDecl *FDI : ReverseMemberChain) { 14564 if (FDI->hasAttr<PackedAttr>() || 14565 FDI->getParent()->hasAttr<PackedAttr>()) { 14566 FD = FDI; 14567 Alignment = std::min( 14568 Context.getTypeAlignInChars(FD->getType()), 14569 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 14570 break; 14571 } 14572 } 14573 assert(FD && "We did not find a packed FieldDecl!"); 14574 Action(E, FD->getParent(), FD, Alignment); 14575 } 14576 } 14577 14578 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 14579 using namespace std::placeholders; 14580 14581 RefersToMemberWithReducedAlignment( 14582 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 14583 _2, _3, _4)); 14584 } 14585