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 // __builtin_memcpy_inline size argument is a constant by definition. 1653 if (TheCall->getArg(2)->EvaluateKnownConstInt(Context).isNullValue()) 1654 break; 1655 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1656 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1657 break; 1658 } 1659 #define BUILTIN(ID, TYPE, ATTRS) 1660 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1661 case Builtin::BI##ID: \ 1662 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1663 #include "clang/Basic/Builtins.def" 1664 case Builtin::BI__annotation: 1665 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1666 return ExprError(); 1667 break; 1668 case Builtin::BI__builtin_annotation: 1669 if (SemaBuiltinAnnotation(*this, TheCall)) 1670 return ExprError(); 1671 break; 1672 case Builtin::BI__builtin_addressof: 1673 if (SemaBuiltinAddressof(*this, TheCall)) 1674 return ExprError(); 1675 break; 1676 case Builtin::BI__builtin_is_aligned: 1677 case Builtin::BI__builtin_align_up: 1678 case Builtin::BI__builtin_align_down: 1679 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1680 return ExprError(); 1681 break; 1682 case Builtin::BI__builtin_add_overflow: 1683 case Builtin::BI__builtin_sub_overflow: 1684 case Builtin::BI__builtin_mul_overflow: 1685 if (SemaBuiltinOverflow(*this, TheCall)) 1686 return ExprError(); 1687 break; 1688 case Builtin::BI__builtin_operator_new: 1689 case Builtin::BI__builtin_operator_delete: { 1690 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1691 ExprResult Res = 1692 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1693 if (Res.isInvalid()) 1694 CorrectDelayedTyposInExpr(TheCallResult.get()); 1695 return Res; 1696 } 1697 case Builtin::BI__builtin_dump_struct: { 1698 // We first want to ensure we are called with 2 arguments 1699 if (checkArgCount(*this, TheCall, 2)) 1700 return ExprError(); 1701 // Ensure that the first argument is of type 'struct XX *' 1702 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1703 const QualType PtrArgType = PtrArg->getType(); 1704 if (!PtrArgType->isPointerType() || 1705 !PtrArgType->getPointeeType()->isRecordType()) { 1706 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1707 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1708 << "structure pointer"; 1709 return ExprError(); 1710 } 1711 1712 // Ensure that the second argument is of type 'FunctionType' 1713 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1714 const QualType FnPtrArgType = FnPtrArg->getType(); 1715 if (!FnPtrArgType->isPointerType()) { 1716 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1717 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1718 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1719 return ExprError(); 1720 } 1721 1722 const auto *FuncType = 1723 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1724 1725 if (!FuncType) { 1726 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1727 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1728 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1729 return ExprError(); 1730 } 1731 1732 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1733 if (!FT->getNumParams()) { 1734 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1735 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1736 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1737 return ExprError(); 1738 } 1739 QualType PT = FT->getParamType(0); 1740 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1741 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1742 !PT->getPointeeType().isConstQualified()) { 1743 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1744 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1745 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1746 return ExprError(); 1747 } 1748 } 1749 1750 TheCall->setType(Context.IntTy); 1751 break; 1752 } 1753 case Builtin::BI__builtin_preserve_access_index: 1754 if (SemaBuiltinPreserveAI(*this, TheCall)) 1755 return ExprError(); 1756 break; 1757 case Builtin::BI__builtin_call_with_static_chain: 1758 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1759 return ExprError(); 1760 break; 1761 case Builtin::BI__exception_code: 1762 case Builtin::BI_exception_code: 1763 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1764 diag::err_seh___except_block)) 1765 return ExprError(); 1766 break; 1767 case Builtin::BI__exception_info: 1768 case Builtin::BI_exception_info: 1769 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1770 diag::err_seh___except_filter)) 1771 return ExprError(); 1772 break; 1773 case Builtin::BI__GetExceptionInfo: 1774 if (checkArgCount(*this, TheCall, 1)) 1775 return ExprError(); 1776 1777 if (CheckCXXThrowOperand( 1778 TheCall->getBeginLoc(), 1779 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1780 TheCall)) 1781 return ExprError(); 1782 1783 TheCall->setType(Context.VoidPtrTy); 1784 break; 1785 // OpenCL v2.0, s6.13.16 - Pipe functions 1786 case Builtin::BIread_pipe: 1787 case Builtin::BIwrite_pipe: 1788 // Since those two functions are declared with var args, we need a semantic 1789 // check for the argument. 1790 if (SemaBuiltinRWPipe(*this, TheCall)) 1791 return ExprError(); 1792 break; 1793 case Builtin::BIreserve_read_pipe: 1794 case Builtin::BIreserve_write_pipe: 1795 case Builtin::BIwork_group_reserve_read_pipe: 1796 case Builtin::BIwork_group_reserve_write_pipe: 1797 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1798 return ExprError(); 1799 break; 1800 case Builtin::BIsub_group_reserve_read_pipe: 1801 case Builtin::BIsub_group_reserve_write_pipe: 1802 if (checkOpenCLSubgroupExt(*this, TheCall) || 1803 SemaBuiltinReserveRWPipe(*this, TheCall)) 1804 return ExprError(); 1805 break; 1806 case Builtin::BIcommit_read_pipe: 1807 case Builtin::BIcommit_write_pipe: 1808 case Builtin::BIwork_group_commit_read_pipe: 1809 case Builtin::BIwork_group_commit_write_pipe: 1810 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1811 return ExprError(); 1812 break; 1813 case Builtin::BIsub_group_commit_read_pipe: 1814 case Builtin::BIsub_group_commit_write_pipe: 1815 if (checkOpenCLSubgroupExt(*this, TheCall) || 1816 SemaBuiltinCommitRWPipe(*this, TheCall)) 1817 return ExprError(); 1818 break; 1819 case Builtin::BIget_pipe_num_packets: 1820 case Builtin::BIget_pipe_max_packets: 1821 if (SemaBuiltinPipePackets(*this, TheCall)) 1822 return ExprError(); 1823 break; 1824 case Builtin::BIto_global: 1825 case Builtin::BIto_local: 1826 case Builtin::BIto_private: 1827 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1828 return ExprError(); 1829 break; 1830 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1831 case Builtin::BIenqueue_kernel: 1832 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1833 return ExprError(); 1834 break; 1835 case Builtin::BIget_kernel_work_group_size: 1836 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1837 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1838 return ExprError(); 1839 break; 1840 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1841 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1842 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1843 return ExprError(); 1844 break; 1845 case Builtin::BI__builtin_os_log_format: 1846 Cleanup.setExprNeedsCleanups(true); 1847 LLVM_FALLTHROUGH; 1848 case Builtin::BI__builtin_os_log_format_buffer_size: 1849 if (SemaBuiltinOSLogFormat(TheCall)) 1850 return ExprError(); 1851 break; 1852 case Builtin::BI__builtin_frame_address: 1853 case Builtin::BI__builtin_return_address: 1854 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1855 return ExprError(); 1856 1857 // -Wframe-address warning if non-zero passed to builtin 1858 // return/frame address. 1859 Expr::EvalResult Result; 1860 if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1861 Result.Val.getInt() != 0) 1862 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1863 << ((BuiltinID == Builtin::BI__builtin_return_address) 1864 ? "__builtin_return_address" 1865 : "__builtin_frame_address") 1866 << TheCall->getSourceRange(); 1867 break; 1868 } 1869 1870 // Since the target specific builtins for each arch overlap, only check those 1871 // of the arch we are compiling for. 1872 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1873 switch (Context.getTargetInfo().getTriple().getArch()) { 1874 case llvm::Triple::arm: 1875 case llvm::Triple::armeb: 1876 case llvm::Triple::thumb: 1877 case llvm::Triple::thumbeb: 1878 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall)) 1879 return ExprError(); 1880 break; 1881 case llvm::Triple::aarch64: 1882 case llvm::Triple::aarch64_32: 1883 case llvm::Triple::aarch64_be: 1884 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall)) 1885 return ExprError(); 1886 break; 1887 case llvm::Triple::bpfeb: 1888 case llvm::Triple::bpfel: 1889 if (CheckBPFBuiltinFunctionCall(BuiltinID, TheCall)) 1890 return ExprError(); 1891 break; 1892 case llvm::Triple::hexagon: 1893 if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall)) 1894 return ExprError(); 1895 break; 1896 case llvm::Triple::mips: 1897 case llvm::Triple::mipsel: 1898 case llvm::Triple::mips64: 1899 case llvm::Triple::mips64el: 1900 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall)) 1901 return ExprError(); 1902 break; 1903 case llvm::Triple::systemz: 1904 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall)) 1905 return ExprError(); 1906 break; 1907 case llvm::Triple::x86: 1908 case llvm::Triple::x86_64: 1909 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall)) 1910 return ExprError(); 1911 break; 1912 case llvm::Triple::ppc: 1913 case llvm::Triple::ppc64: 1914 case llvm::Triple::ppc64le: 1915 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall)) 1916 return ExprError(); 1917 break; 1918 default: 1919 break; 1920 } 1921 } 1922 1923 return TheCallResult; 1924 } 1925 1926 // Get the valid immediate range for the specified NEON type code. 1927 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1928 NeonTypeFlags Type(t); 1929 int IsQuad = ForceQuad ? true : Type.isQuad(); 1930 switch (Type.getEltType()) { 1931 case NeonTypeFlags::Int8: 1932 case NeonTypeFlags::Poly8: 1933 return shift ? 7 : (8 << IsQuad) - 1; 1934 case NeonTypeFlags::Int16: 1935 case NeonTypeFlags::Poly16: 1936 return shift ? 15 : (4 << IsQuad) - 1; 1937 case NeonTypeFlags::Int32: 1938 return shift ? 31 : (2 << IsQuad) - 1; 1939 case NeonTypeFlags::Int64: 1940 case NeonTypeFlags::Poly64: 1941 return shift ? 63 : (1 << IsQuad) - 1; 1942 case NeonTypeFlags::Poly128: 1943 return shift ? 127 : (1 << IsQuad) - 1; 1944 case NeonTypeFlags::Float16: 1945 assert(!shift && "cannot shift float types!"); 1946 return (4 << IsQuad) - 1; 1947 case NeonTypeFlags::Float32: 1948 assert(!shift && "cannot shift float types!"); 1949 return (2 << IsQuad) - 1; 1950 case NeonTypeFlags::Float64: 1951 assert(!shift && "cannot shift float types!"); 1952 return (1 << IsQuad) - 1; 1953 } 1954 llvm_unreachable("Invalid NeonTypeFlag!"); 1955 } 1956 1957 /// getNeonEltType - Return the QualType corresponding to the elements of 1958 /// the vector type specified by the NeonTypeFlags. This is used to check 1959 /// the pointer arguments for Neon load/store intrinsics. 1960 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1961 bool IsPolyUnsigned, bool IsInt64Long) { 1962 switch (Flags.getEltType()) { 1963 case NeonTypeFlags::Int8: 1964 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1965 case NeonTypeFlags::Int16: 1966 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1967 case NeonTypeFlags::Int32: 1968 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1969 case NeonTypeFlags::Int64: 1970 if (IsInt64Long) 1971 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 1972 else 1973 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 1974 : Context.LongLongTy; 1975 case NeonTypeFlags::Poly8: 1976 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 1977 case NeonTypeFlags::Poly16: 1978 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 1979 case NeonTypeFlags::Poly64: 1980 if (IsInt64Long) 1981 return Context.UnsignedLongTy; 1982 else 1983 return Context.UnsignedLongLongTy; 1984 case NeonTypeFlags::Poly128: 1985 break; 1986 case NeonTypeFlags::Float16: 1987 return Context.HalfTy; 1988 case NeonTypeFlags::Float32: 1989 return Context.FloatTy; 1990 case NeonTypeFlags::Float64: 1991 return Context.DoubleTy; 1992 } 1993 llvm_unreachable("Invalid NeonTypeFlag!"); 1994 } 1995 1996 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 1997 llvm::APSInt Result; 1998 uint64_t mask = 0; 1999 unsigned TV = 0; 2000 int PtrArgNum = -1; 2001 bool HasConstPtr = false; 2002 switch (BuiltinID) { 2003 #define GET_NEON_OVERLOAD_CHECK 2004 #include "clang/Basic/arm_neon.inc" 2005 #include "clang/Basic/arm_fp16.inc" 2006 #undef GET_NEON_OVERLOAD_CHECK 2007 } 2008 2009 // For NEON intrinsics which are overloaded on vector element type, validate 2010 // the immediate which specifies which variant to emit. 2011 unsigned ImmArg = TheCall->getNumArgs()-1; 2012 if (mask) { 2013 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2014 return true; 2015 2016 TV = Result.getLimitedValue(64); 2017 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2018 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2019 << TheCall->getArg(ImmArg)->getSourceRange(); 2020 } 2021 2022 if (PtrArgNum >= 0) { 2023 // Check that pointer arguments have the specified type. 2024 Expr *Arg = TheCall->getArg(PtrArgNum); 2025 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2026 Arg = ICE->getSubExpr(); 2027 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2028 QualType RHSTy = RHS.get()->getType(); 2029 2030 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 2031 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2032 Arch == llvm::Triple::aarch64_32 || 2033 Arch == llvm::Triple::aarch64_be; 2034 bool IsInt64Long = 2035 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong; 2036 QualType EltTy = 2037 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2038 if (HasConstPtr) 2039 EltTy = EltTy.withConst(); 2040 QualType LHSTy = Context.getPointerType(EltTy); 2041 AssignConvertType ConvTy; 2042 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2043 if (RHS.isInvalid()) 2044 return true; 2045 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2046 RHS.get(), AA_Assigning)) 2047 return true; 2048 } 2049 2050 // For NEON intrinsics which take an immediate value as part of the 2051 // instruction, range check them here. 2052 unsigned i = 0, l = 0, u = 0; 2053 switch (BuiltinID) { 2054 default: 2055 return false; 2056 #define GET_NEON_IMMEDIATE_CHECK 2057 #include "clang/Basic/arm_neon.inc" 2058 #include "clang/Basic/arm_fp16.inc" 2059 #undef GET_NEON_IMMEDIATE_CHECK 2060 } 2061 2062 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2063 } 2064 2065 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2066 switch (BuiltinID) { 2067 default: 2068 return false; 2069 #include "clang/Basic/arm_mve_builtin_sema.inc" 2070 } 2071 } 2072 2073 bool Sema::CheckCDEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2074 bool Err = false; 2075 switch (BuiltinID) { 2076 default: 2077 return false; 2078 #include "clang/Basic/arm_cde_builtin_sema.inc" 2079 } 2080 2081 if (Err) 2082 return true; 2083 2084 return CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ true); 2085 } 2086 2087 bool Sema::CheckARMCoprocessorImmediate(const Expr *CoprocArg, bool WantCDE) { 2088 if (isConstantEvaluated()) 2089 return false; 2090 2091 // We can't check the value of a dependent argument. 2092 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2093 return false; 2094 2095 llvm::APSInt CoprocNoAP; 2096 bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context); 2097 (void)IsICE; 2098 assert(IsICE && "Coprocossor immediate is not a constant expression"); 2099 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2100 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2101 2102 uint32_t CDECoprocMask = Context.getTargetInfo().getARMCDECoprocMask(); 2103 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2104 2105 if (IsCDECoproc != WantCDE) 2106 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2107 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2108 2109 return false; 2110 } 2111 2112 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2113 unsigned MaxWidth) { 2114 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2115 BuiltinID == ARM::BI__builtin_arm_ldaex || 2116 BuiltinID == ARM::BI__builtin_arm_strex || 2117 BuiltinID == ARM::BI__builtin_arm_stlex || 2118 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2119 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2120 BuiltinID == AArch64::BI__builtin_arm_strex || 2121 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2122 "unexpected ARM builtin"); 2123 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2124 BuiltinID == ARM::BI__builtin_arm_ldaex || 2125 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2126 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2127 2128 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2129 2130 // Ensure that we have the proper number of arguments. 2131 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2132 return true; 2133 2134 // Inspect the pointer argument of the atomic builtin. This should always be 2135 // a pointer type, whose element is an integral scalar or pointer type. 2136 // Because it is a pointer type, we don't have to worry about any implicit 2137 // casts here. 2138 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2139 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2140 if (PointerArgRes.isInvalid()) 2141 return true; 2142 PointerArg = PointerArgRes.get(); 2143 2144 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2145 if (!pointerType) { 2146 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2147 << PointerArg->getType() << PointerArg->getSourceRange(); 2148 return true; 2149 } 2150 2151 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2152 // task is to insert the appropriate casts into the AST. First work out just 2153 // what the appropriate type is. 2154 QualType ValType = pointerType->getPointeeType(); 2155 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2156 if (IsLdrex) 2157 AddrType.addConst(); 2158 2159 // Issue a warning if the cast is dodgy. 2160 CastKind CastNeeded = CK_NoOp; 2161 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2162 CastNeeded = CK_BitCast; 2163 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2164 << PointerArg->getType() << Context.getPointerType(AddrType) 2165 << AA_Passing << PointerArg->getSourceRange(); 2166 } 2167 2168 // Finally, do the cast and replace the argument with the corrected version. 2169 AddrType = Context.getPointerType(AddrType); 2170 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2171 if (PointerArgRes.isInvalid()) 2172 return true; 2173 PointerArg = PointerArgRes.get(); 2174 2175 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2176 2177 // In general, we allow ints, floats and pointers to be loaded and stored. 2178 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2179 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2180 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2181 << PointerArg->getType() << PointerArg->getSourceRange(); 2182 return true; 2183 } 2184 2185 // But ARM doesn't have instructions to deal with 128-bit versions. 2186 if (Context.getTypeSize(ValType) > MaxWidth) { 2187 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2188 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2189 << PointerArg->getType() << PointerArg->getSourceRange(); 2190 return true; 2191 } 2192 2193 switch (ValType.getObjCLifetime()) { 2194 case Qualifiers::OCL_None: 2195 case Qualifiers::OCL_ExplicitNone: 2196 // okay 2197 break; 2198 2199 case Qualifiers::OCL_Weak: 2200 case Qualifiers::OCL_Strong: 2201 case Qualifiers::OCL_Autoreleasing: 2202 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2203 << ValType << PointerArg->getSourceRange(); 2204 return true; 2205 } 2206 2207 if (IsLdrex) { 2208 TheCall->setType(ValType); 2209 return false; 2210 } 2211 2212 // Initialize the argument to be stored. 2213 ExprResult ValArg = TheCall->getArg(0); 2214 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2215 Context, ValType, /*consume*/ false); 2216 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2217 if (ValArg.isInvalid()) 2218 return true; 2219 TheCall->setArg(0, ValArg.get()); 2220 2221 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2222 // but the custom checker bypasses all default analysis. 2223 TheCall->setType(Context.IntTy); 2224 return false; 2225 } 2226 2227 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2228 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2229 BuiltinID == ARM::BI__builtin_arm_ldaex || 2230 BuiltinID == ARM::BI__builtin_arm_strex || 2231 BuiltinID == ARM::BI__builtin_arm_stlex) { 2232 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2233 } 2234 2235 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2236 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2237 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2238 } 2239 2240 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2241 BuiltinID == ARM::BI__builtin_arm_wsr64) 2242 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2243 2244 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2245 BuiltinID == ARM::BI__builtin_arm_rsrp || 2246 BuiltinID == ARM::BI__builtin_arm_wsr || 2247 BuiltinID == ARM::BI__builtin_arm_wsrp) 2248 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2249 2250 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 2251 return true; 2252 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2253 return true; 2254 if (CheckCDEBuiltinFunctionCall(BuiltinID, TheCall)) 2255 return true; 2256 2257 // For intrinsics which take an immediate value as part of the instruction, 2258 // range check them here. 2259 // FIXME: VFP Intrinsics should error if VFP not present. 2260 switch (BuiltinID) { 2261 default: return false; 2262 case ARM::BI__builtin_arm_ssat: 2263 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2264 case ARM::BI__builtin_arm_usat: 2265 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2266 case ARM::BI__builtin_arm_ssat16: 2267 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2268 case ARM::BI__builtin_arm_usat16: 2269 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2270 case ARM::BI__builtin_arm_vcvtr_f: 2271 case ARM::BI__builtin_arm_vcvtr_d: 2272 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2273 case ARM::BI__builtin_arm_dmb: 2274 case ARM::BI__builtin_arm_dsb: 2275 case ARM::BI__builtin_arm_isb: 2276 case ARM::BI__builtin_arm_dbg: 2277 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2278 case ARM::BI__builtin_arm_cdp: 2279 case ARM::BI__builtin_arm_cdp2: 2280 case ARM::BI__builtin_arm_mcr: 2281 case ARM::BI__builtin_arm_mcr2: 2282 case ARM::BI__builtin_arm_mrc: 2283 case ARM::BI__builtin_arm_mrc2: 2284 case ARM::BI__builtin_arm_mcrr: 2285 case ARM::BI__builtin_arm_mcrr2: 2286 case ARM::BI__builtin_arm_mrrc: 2287 case ARM::BI__builtin_arm_mrrc2: 2288 case ARM::BI__builtin_arm_ldc: 2289 case ARM::BI__builtin_arm_ldcl: 2290 case ARM::BI__builtin_arm_ldc2: 2291 case ARM::BI__builtin_arm_ldc2l: 2292 case ARM::BI__builtin_arm_stc: 2293 case ARM::BI__builtin_arm_stcl: 2294 case ARM::BI__builtin_arm_stc2: 2295 case ARM::BI__builtin_arm_stc2l: 2296 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2297 CheckARMCoprocessorImmediate(TheCall->getArg(0), /*WantCDE*/ false); 2298 } 2299 } 2300 2301 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, 2302 CallExpr *TheCall) { 2303 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2304 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2305 BuiltinID == AArch64::BI__builtin_arm_strex || 2306 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2307 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2308 } 2309 2310 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2311 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2312 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2313 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2314 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2315 } 2316 2317 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2318 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2319 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2320 2321 // Memory Tagging Extensions (MTE) Intrinsics 2322 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2323 BuiltinID == AArch64::BI__builtin_arm_addg || 2324 BuiltinID == AArch64::BI__builtin_arm_gmi || 2325 BuiltinID == AArch64::BI__builtin_arm_ldg || 2326 BuiltinID == AArch64::BI__builtin_arm_stg || 2327 BuiltinID == AArch64::BI__builtin_arm_subp) { 2328 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2329 } 2330 2331 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2332 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2333 BuiltinID == AArch64::BI__builtin_arm_wsr || 2334 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2335 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2336 2337 // Only check the valid encoding range. Any constant in this range would be 2338 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2339 // an exception for incorrect registers. This matches MSVC behavior. 2340 if (BuiltinID == AArch64::BI_ReadStatusReg || 2341 BuiltinID == AArch64::BI_WriteStatusReg) 2342 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2343 2344 if (BuiltinID == AArch64::BI__getReg) 2345 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2346 2347 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall)) 2348 return true; 2349 2350 // For intrinsics which take an immediate value as part of the instruction, 2351 // range check them here. 2352 unsigned i = 0, l = 0, u = 0; 2353 switch (BuiltinID) { 2354 default: return false; 2355 case AArch64::BI__builtin_arm_dmb: 2356 case AArch64::BI__builtin_arm_dsb: 2357 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2358 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2359 } 2360 2361 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2362 } 2363 2364 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2365 CallExpr *TheCall) { 2366 assert(BuiltinID == BPF::BI__builtin_preserve_field_info && 2367 "unexpected ARM builtin"); 2368 2369 if (checkArgCount(*this, TheCall, 2)) 2370 return true; 2371 2372 // The first argument needs to be a record field access. 2373 // If it is an array element access, we delay decision 2374 // to BPF backend to check whether the access is a 2375 // field access or not. 2376 Expr *Arg = TheCall->getArg(0); 2377 if (Arg->getType()->getAsPlaceholderType() || 2378 (Arg->IgnoreParens()->getObjectKind() != OK_BitField && 2379 !dyn_cast<MemberExpr>(Arg->IgnoreParens()) && 2380 !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) { 2381 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field) 2382 << 1 << Arg->getSourceRange(); 2383 return true; 2384 } 2385 2386 // The second argument needs to be a constant int 2387 llvm::APSInt Value; 2388 if (!TheCall->getArg(1)->isIntegerConstantExpr(Value, Context)) { 2389 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const) 2390 << 2 << Arg->getSourceRange(); 2391 return true; 2392 } 2393 2394 TheCall->setType(Context.UnsignedIntTy); 2395 return false; 2396 } 2397 2398 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2399 struct ArgInfo { 2400 uint8_t OpNum; 2401 bool IsSigned; 2402 uint8_t BitWidth; 2403 uint8_t Align; 2404 }; 2405 struct BuiltinInfo { 2406 unsigned BuiltinID; 2407 ArgInfo Infos[2]; 2408 }; 2409 2410 static BuiltinInfo Infos[] = { 2411 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2412 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2413 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2414 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2415 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2416 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2417 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2418 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2419 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2420 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2421 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2422 2423 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2424 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2425 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2426 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2427 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2428 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2429 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2430 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2431 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2432 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2433 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2434 2435 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2436 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2437 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2438 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2439 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2440 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2441 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2442 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2443 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2444 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2445 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2446 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2447 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2448 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2449 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2450 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2451 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2452 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2453 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2454 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2455 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2456 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2457 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2458 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2459 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2460 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2461 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2462 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2463 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2464 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2465 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2466 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2467 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2468 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2469 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2470 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2471 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2472 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2473 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2474 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2475 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2476 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2477 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2478 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2479 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2480 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2481 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2482 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2483 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2484 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2485 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2486 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2487 {{ 1, false, 6, 0 }} }, 2488 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2489 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2490 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2491 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2492 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2493 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2494 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2495 {{ 1, false, 5, 0 }} }, 2496 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2497 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2498 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2499 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2500 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2501 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2502 { 2, false, 5, 0 }} }, 2503 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2504 { 2, false, 6, 0 }} }, 2505 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2506 { 3, false, 5, 0 }} }, 2507 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2508 { 3, false, 6, 0 }} }, 2509 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2510 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2511 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2512 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2513 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2514 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2515 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2516 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2517 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2518 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2519 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2520 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2521 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2522 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2523 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2524 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2525 {{ 2, false, 4, 0 }, 2526 { 3, false, 5, 0 }} }, 2527 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2528 {{ 2, false, 4, 0 }, 2529 { 3, false, 5, 0 }} }, 2530 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2531 {{ 2, false, 4, 0 }, 2532 { 3, false, 5, 0 }} }, 2533 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2534 {{ 2, false, 4, 0 }, 2535 { 3, false, 5, 0 }} }, 2536 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2537 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2538 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2539 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2540 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2541 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2542 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2543 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2544 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2545 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2546 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2547 { 2, false, 5, 0 }} }, 2548 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2549 { 2, false, 6, 0 }} }, 2550 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2551 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2552 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2553 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2554 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2555 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2556 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2557 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2558 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2559 {{ 1, false, 4, 0 }} }, 2560 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2561 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2562 {{ 1, false, 4, 0 }} }, 2563 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2564 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2565 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2566 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2567 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2568 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2569 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2570 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2571 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2572 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2573 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2574 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2575 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2576 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2577 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2578 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2579 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2580 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2581 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2582 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2583 {{ 3, false, 1, 0 }} }, 2584 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2585 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2586 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2587 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2588 {{ 3, false, 1, 0 }} }, 2589 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2590 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2591 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2592 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2593 {{ 3, false, 1, 0 }} }, 2594 }; 2595 2596 // Use a dynamically initialized static to sort the table exactly once on 2597 // first run. 2598 static const bool SortOnce = 2599 (llvm::sort(Infos, 2600 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2601 return LHS.BuiltinID < RHS.BuiltinID; 2602 }), 2603 true); 2604 (void)SortOnce; 2605 2606 const BuiltinInfo *F = llvm::partition_point( 2607 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2608 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2609 return false; 2610 2611 bool Error = false; 2612 2613 for (const ArgInfo &A : F->Infos) { 2614 // Ignore empty ArgInfo elements. 2615 if (A.BitWidth == 0) 2616 continue; 2617 2618 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2619 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2620 if (!A.Align) { 2621 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2622 } else { 2623 unsigned M = 1 << A.Align; 2624 Min *= M; 2625 Max *= M; 2626 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2627 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2628 } 2629 } 2630 return Error; 2631 } 2632 2633 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2634 CallExpr *TheCall) { 2635 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2636 } 2637 2638 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2639 return CheckMipsBuiltinCpu(BuiltinID, TheCall) || 2640 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2641 } 2642 2643 bool Sema::CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) { 2644 const TargetInfo &TI = Context.getTargetInfo(); 2645 2646 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2647 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2648 if (!TI.hasFeature("dsp")) 2649 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2650 } 2651 2652 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2653 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2654 if (!TI.hasFeature("dspr2")) 2655 return Diag(TheCall->getBeginLoc(), 2656 diag::err_mips_builtin_requires_dspr2); 2657 } 2658 2659 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2660 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2661 if (!TI.hasFeature("msa")) 2662 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2663 } 2664 2665 return false; 2666 } 2667 2668 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2669 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2670 // ordering for DSP is unspecified. MSA is ordered by the data format used 2671 // by the underlying instruction i.e., df/m, df/n and then by size. 2672 // 2673 // FIXME: The size tests here should instead be tablegen'd along with the 2674 // definitions from include/clang/Basic/BuiltinsMips.def. 2675 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2676 // be too. 2677 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2678 unsigned i = 0, l = 0, u = 0, m = 0; 2679 switch (BuiltinID) { 2680 default: return false; 2681 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2682 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2683 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2684 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2685 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2686 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2687 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2688 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 2689 // df/m field. 2690 // These intrinsics take an unsigned 3 bit immediate. 2691 case Mips::BI__builtin_msa_bclri_b: 2692 case Mips::BI__builtin_msa_bnegi_b: 2693 case Mips::BI__builtin_msa_bseti_b: 2694 case Mips::BI__builtin_msa_sat_s_b: 2695 case Mips::BI__builtin_msa_sat_u_b: 2696 case Mips::BI__builtin_msa_slli_b: 2697 case Mips::BI__builtin_msa_srai_b: 2698 case Mips::BI__builtin_msa_srari_b: 2699 case Mips::BI__builtin_msa_srli_b: 2700 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2701 case Mips::BI__builtin_msa_binsli_b: 2702 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2703 // These intrinsics take an unsigned 4 bit immediate. 2704 case Mips::BI__builtin_msa_bclri_h: 2705 case Mips::BI__builtin_msa_bnegi_h: 2706 case Mips::BI__builtin_msa_bseti_h: 2707 case Mips::BI__builtin_msa_sat_s_h: 2708 case Mips::BI__builtin_msa_sat_u_h: 2709 case Mips::BI__builtin_msa_slli_h: 2710 case Mips::BI__builtin_msa_srai_h: 2711 case Mips::BI__builtin_msa_srari_h: 2712 case Mips::BI__builtin_msa_srli_h: 2713 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2714 case Mips::BI__builtin_msa_binsli_h: 2715 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2716 // These intrinsics take an unsigned 5 bit immediate. 2717 // The first block of intrinsics actually have an unsigned 5 bit field, 2718 // not a df/n field. 2719 case Mips::BI__builtin_msa_cfcmsa: 2720 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 2721 case Mips::BI__builtin_msa_clei_u_b: 2722 case Mips::BI__builtin_msa_clei_u_h: 2723 case Mips::BI__builtin_msa_clei_u_w: 2724 case Mips::BI__builtin_msa_clei_u_d: 2725 case Mips::BI__builtin_msa_clti_u_b: 2726 case Mips::BI__builtin_msa_clti_u_h: 2727 case Mips::BI__builtin_msa_clti_u_w: 2728 case Mips::BI__builtin_msa_clti_u_d: 2729 case Mips::BI__builtin_msa_maxi_u_b: 2730 case Mips::BI__builtin_msa_maxi_u_h: 2731 case Mips::BI__builtin_msa_maxi_u_w: 2732 case Mips::BI__builtin_msa_maxi_u_d: 2733 case Mips::BI__builtin_msa_mini_u_b: 2734 case Mips::BI__builtin_msa_mini_u_h: 2735 case Mips::BI__builtin_msa_mini_u_w: 2736 case Mips::BI__builtin_msa_mini_u_d: 2737 case Mips::BI__builtin_msa_addvi_b: 2738 case Mips::BI__builtin_msa_addvi_h: 2739 case Mips::BI__builtin_msa_addvi_w: 2740 case Mips::BI__builtin_msa_addvi_d: 2741 case Mips::BI__builtin_msa_bclri_w: 2742 case Mips::BI__builtin_msa_bnegi_w: 2743 case Mips::BI__builtin_msa_bseti_w: 2744 case Mips::BI__builtin_msa_sat_s_w: 2745 case Mips::BI__builtin_msa_sat_u_w: 2746 case Mips::BI__builtin_msa_slli_w: 2747 case Mips::BI__builtin_msa_srai_w: 2748 case Mips::BI__builtin_msa_srari_w: 2749 case Mips::BI__builtin_msa_srli_w: 2750 case Mips::BI__builtin_msa_srlri_w: 2751 case Mips::BI__builtin_msa_subvi_b: 2752 case Mips::BI__builtin_msa_subvi_h: 2753 case Mips::BI__builtin_msa_subvi_w: 2754 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2755 case Mips::BI__builtin_msa_binsli_w: 2756 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2757 // These intrinsics take an unsigned 6 bit immediate. 2758 case Mips::BI__builtin_msa_bclri_d: 2759 case Mips::BI__builtin_msa_bnegi_d: 2760 case Mips::BI__builtin_msa_bseti_d: 2761 case Mips::BI__builtin_msa_sat_s_d: 2762 case Mips::BI__builtin_msa_sat_u_d: 2763 case Mips::BI__builtin_msa_slli_d: 2764 case Mips::BI__builtin_msa_srai_d: 2765 case Mips::BI__builtin_msa_srari_d: 2766 case Mips::BI__builtin_msa_srli_d: 2767 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2768 case Mips::BI__builtin_msa_binsli_d: 2769 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2770 // These intrinsics take a signed 5 bit immediate. 2771 case Mips::BI__builtin_msa_ceqi_b: 2772 case Mips::BI__builtin_msa_ceqi_h: 2773 case Mips::BI__builtin_msa_ceqi_w: 2774 case Mips::BI__builtin_msa_ceqi_d: 2775 case Mips::BI__builtin_msa_clti_s_b: 2776 case Mips::BI__builtin_msa_clti_s_h: 2777 case Mips::BI__builtin_msa_clti_s_w: 2778 case Mips::BI__builtin_msa_clti_s_d: 2779 case Mips::BI__builtin_msa_clei_s_b: 2780 case Mips::BI__builtin_msa_clei_s_h: 2781 case Mips::BI__builtin_msa_clei_s_w: 2782 case Mips::BI__builtin_msa_clei_s_d: 2783 case Mips::BI__builtin_msa_maxi_s_b: 2784 case Mips::BI__builtin_msa_maxi_s_h: 2785 case Mips::BI__builtin_msa_maxi_s_w: 2786 case Mips::BI__builtin_msa_maxi_s_d: 2787 case Mips::BI__builtin_msa_mini_s_b: 2788 case Mips::BI__builtin_msa_mini_s_h: 2789 case Mips::BI__builtin_msa_mini_s_w: 2790 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2791 // These intrinsics take an unsigned 8 bit immediate. 2792 case Mips::BI__builtin_msa_andi_b: 2793 case Mips::BI__builtin_msa_nori_b: 2794 case Mips::BI__builtin_msa_ori_b: 2795 case Mips::BI__builtin_msa_shf_b: 2796 case Mips::BI__builtin_msa_shf_h: 2797 case Mips::BI__builtin_msa_shf_w: 2798 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2799 case Mips::BI__builtin_msa_bseli_b: 2800 case Mips::BI__builtin_msa_bmnzi_b: 2801 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2802 // df/n format 2803 // These intrinsics take an unsigned 4 bit immediate. 2804 case Mips::BI__builtin_msa_copy_s_b: 2805 case Mips::BI__builtin_msa_copy_u_b: 2806 case Mips::BI__builtin_msa_insve_b: 2807 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2808 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2809 // These intrinsics take an unsigned 3 bit immediate. 2810 case Mips::BI__builtin_msa_copy_s_h: 2811 case Mips::BI__builtin_msa_copy_u_h: 2812 case Mips::BI__builtin_msa_insve_h: 2813 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2814 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2815 // These intrinsics take an unsigned 2 bit immediate. 2816 case Mips::BI__builtin_msa_copy_s_w: 2817 case Mips::BI__builtin_msa_copy_u_w: 2818 case Mips::BI__builtin_msa_insve_w: 2819 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2820 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2821 // These intrinsics take an unsigned 1 bit immediate. 2822 case Mips::BI__builtin_msa_copy_s_d: 2823 case Mips::BI__builtin_msa_copy_u_d: 2824 case Mips::BI__builtin_msa_insve_d: 2825 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2826 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2827 // Memory offsets and immediate loads. 2828 // These intrinsics take a signed 10 bit immediate. 2829 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2830 case Mips::BI__builtin_msa_ldi_h: 2831 case Mips::BI__builtin_msa_ldi_w: 2832 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 2833 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 2834 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 2835 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 2836 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 2837 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 2838 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 2839 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 2840 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 2841 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 2842 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 2843 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 2844 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 2845 } 2846 2847 if (!m) 2848 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2849 2850 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 2851 SemaBuiltinConstantArgMultiple(TheCall, i, m); 2852 } 2853 2854 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2855 unsigned i = 0, l = 0, u = 0; 2856 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 2857 BuiltinID == PPC::BI__builtin_divdeu || 2858 BuiltinID == PPC::BI__builtin_bpermd; 2859 bool IsTarget64Bit = Context.getTargetInfo() 2860 .getTypeWidth(Context 2861 .getTargetInfo() 2862 .getIntPtrType()) == 64; 2863 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 2864 BuiltinID == PPC::BI__builtin_divweu || 2865 BuiltinID == PPC::BI__builtin_divde || 2866 BuiltinID == PPC::BI__builtin_divdeu; 2867 2868 if (Is64BitBltin && !IsTarget64Bit) 2869 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 2870 << TheCall->getSourceRange(); 2871 2872 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) || 2873 (BuiltinID == PPC::BI__builtin_bpermd && 2874 !Context.getTargetInfo().hasFeature("bpermd"))) 2875 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2876 << TheCall->getSourceRange(); 2877 2878 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 2879 if (!Context.getTargetInfo().hasFeature("vsx")) 2880 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 2881 << TheCall->getSourceRange(); 2882 return false; 2883 }; 2884 2885 switch (BuiltinID) { 2886 default: return false; 2887 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 2888 case PPC::BI__builtin_altivec_crypto_vshasigmad: 2889 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2890 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2891 case PPC::BI__builtin_altivec_dss: 2892 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 2893 case PPC::BI__builtin_tbegin: 2894 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 2895 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 2896 case PPC::BI__builtin_tabortwc: 2897 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 2898 case PPC::BI__builtin_tabortwci: 2899 case PPC::BI__builtin_tabortdci: 2900 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 2901 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 2902 case PPC::BI__builtin_altivec_dst: 2903 case PPC::BI__builtin_altivec_dstt: 2904 case PPC::BI__builtin_altivec_dstst: 2905 case PPC::BI__builtin_altivec_dststt: 2906 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 2907 case PPC::BI__builtin_vsx_xxpermdi: 2908 case PPC::BI__builtin_vsx_xxsldwi: 2909 return SemaBuiltinVSX(TheCall); 2910 case PPC::BI__builtin_unpack_vector_int128: 2911 return SemaVSXCheck(TheCall) || 2912 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2913 case PPC::BI__builtin_pack_vector_int128: 2914 return SemaVSXCheck(TheCall); 2915 } 2916 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2917 } 2918 2919 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 2920 CallExpr *TheCall) { 2921 if (BuiltinID == SystemZ::BI__builtin_tabort) { 2922 Expr *Arg = TheCall->getArg(0); 2923 llvm::APSInt AbortCode(32); 2924 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 2925 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 2926 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 2927 << Arg->getSourceRange(); 2928 } 2929 2930 // For intrinsics which take an immediate value as part of the instruction, 2931 // range check them here. 2932 unsigned i = 0, l = 0, u = 0; 2933 switch (BuiltinID) { 2934 default: return false; 2935 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 2936 case SystemZ::BI__builtin_s390_verimb: 2937 case SystemZ::BI__builtin_s390_verimh: 2938 case SystemZ::BI__builtin_s390_verimf: 2939 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 2940 case SystemZ::BI__builtin_s390_vfaeb: 2941 case SystemZ::BI__builtin_s390_vfaeh: 2942 case SystemZ::BI__builtin_s390_vfaef: 2943 case SystemZ::BI__builtin_s390_vfaebs: 2944 case SystemZ::BI__builtin_s390_vfaehs: 2945 case SystemZ::BI__builtin_s390_vfaefs: 2946 case SystemZ::BI__builtin_s390_vfaezb: 2947 case SystemZ::BI__builtin_s390_vfaezh: 2948 case SystemZ::BI__builtin_s390_vfaezf: 2949 case SystemZ::BI__builtin_s390_vfaezbs: 2950 case SystemZ::BI__builtin_s390_vfaezhs: 2951 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 2952 case SystemZ::BI__builtin_s390_vfisb: 2953 case SystemZ::BI__builtin_s390_vfidb: 2954 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 2955 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 2956 case SystemZ::BI__builtin_s390_vftcisb: 2957 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 2958 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 2959 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 2960 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 2961 case SystemZ::BI__builtin_s390_vstrcb: 2962 case SystemZ::BI__builtin_s390_vstrch: 2963 case SystemZ::BI__builtin_s390_vstrcf: 2964 case SystemZ::BI__builtin_s390_vstrczb: 2965 case SystemZ::BI__builtin_s390_vstrczh: 2966 case SystemZ::BI__builtin_s390_vstrczf: 2967 case SystemZ::BI__builtin_s390_vstrcbs: 2968 case SystemZ::BI__builtin_s390_vstrchs: 2969 case SystemZ::BI__builtin_s390_vstrcfs: 2970 case SystemZ::BI__builtin_s390_vstrczbs: 2971 case SystemZ::BI__builtin_s390_vstrczhs: 2972 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 2973 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 2974 case SystemZ::BI__builtin_s390_vfminsb: 2975 case SystemZ::BI__builtin_s390_vfmaxsb: 2976 case SystemZ::BI__builtin_s390_vfmindb: 2977 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 2978 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 2979 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 2980 } 2981 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 2982 } 2983 2984 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 2985 /// This checks that the target supports __builtin_cpu_supports and 2986 /// that the string argument is constant and valid. 2987 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) { 2988 Expr *Arg = TheCall->getArg(0); 2989 2990 // Check if the argument is a string literal. 2991 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 2992 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 2993 << Arg->getSourceRange(); 2994 2995 // Check the contents of the string. 2996 StringRef Feature = 2997 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 2998 if (!S.Context.getTargetInfo().validateCpuSupports(Feature)) 2999 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3000 << Arg->getSourceRange(); 3001 return false; 3002 } 3003 3004 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3005 /// This checks that the target supports __builtin_cpu_is and 3006 /// that the string argument is constant and valid. 3007 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) { 3008 Expr *Arg = TheCall->getArg(0); 3009 3010 // Check if the argument is a string literal. 3011 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3012 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3013 << Arg->getSourceRange(); 3014 3015 // Check the contents of the string. 3016 StringRef Feature = 3017 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3018 if (!S.Context.getTargetInfo().validateCpuIs(Feature)) 3019 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3020 << Arg->getSourceRange(); 3021 return false; 3022 } 3023 3024 // Check if the rounding mode is legal. 3025 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3026 // Indicates if this instruction has rounding control or just SAE. 3027 bool HasRC = false; 3028 3029 unsigned ArgNum = 0; 3030 switch (BuiltinID) { 3031 default: 3032 return false; 3033 case X86::BI__builtin_ia32_vcvttsd2si32: 3034 case X86::BI__builtin_ia32_vcvttsd2si64: 3035 case X86::BI__builtin_ia32_vcvttsd2usi32: 3036 case X86::BI__builtin_ia32_vcvttsd2usi64: 3037 case X86::BI__builtin_ia32_vcvttss2si32: 3038 case X86::BI__builtin_ia32_vcvttss2si64: 3039 case X86::BI__builtin_ia32_vcvttss2usi32: 3040 case X86::BI__builtin_ia32_vcvttss2usi64: 3041 ArgNum = 1; 3042 break; 3043 case X86::BI__builtin_ia32_maxpd512: 3044 case X86::BI__builtin_ia32_maxps512: 3045 case X86::BI__builtin_ia32_minpd512: 3046 case X86::BI__builtin_ia32_minps512: 3047 ArgNum = 2; 3048 break; 3049 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3050 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3051 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3052 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3053 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3054 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3055 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3056 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3057 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3058 case X86::BI__builtin_ia32_exp2pd_mask: 3059 case X86::BI__builtin_ia32_exp2ps_mask: 3060 case X86::BI__builtin_ia32_getexppd512_mask: 3061 case X86::BI__builtin_ia32_getexpps512_mask: 3062 case X86::BI__builtin_ia32_rcp28pd_mask: 3063 case X86::BI__builtin_ia32_rcp28ps_mask: 3064 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3065 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3066 case X86::BI__builtin_ia32_vcomisd: 3067 case X86::BI__builtin_ia32_vcomiss: 3068 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3069 ArgNum = 3; 3070 break; 3071 case X86::BI__builtin_ia32_cmppd512_mask: 3072 case X86::BI__builtin_ia32_cmpps512_mask: 3073 case X86::BI__builtin_ia32_cmpsd_mask: 3074 case X86::BI__builtin_ia32_cmpss_mask: 3075 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3076 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3077 case X86::BI__builtin_ia32_getexpss128_round_mask: 3078 case X86::BI__builtin_ia32_getmantpd512_mask: 3079 case X86::BI__builtin_ia32_getmantps512_mask: 3080 case X86::BI__builtin_ia32_maxsd_round_mask: 3081 case X86::BI__builtin_ia32_maxss_round_mask: 3082 case X86::BI__builtin_ia32_minsd_round_mask: 3083 case X86::BI__builtin_ia32_minss_round_mask: 3084 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3085 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3086 case X86::BI__builtin_ia32_reducepd512_mask: 3087 case X86::BI__builtin_ia32_reduceps512_mask: 3088 case X86::BI__builtin_ia32_rndscalepd_mask: 3089 case X86::BI__builtin_ia32_rndscaleps_mask: 3090 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3091 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3092 ArgNum = 4; 3093 break; 3094 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3095 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3096 case X86::BI__builtin_ia32_fixupimmps512_mask: 3097 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3098 case X86::BI__builtin_ia32_fixupimmsd_mask: 3099 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3100 case X86::BI__builtin_ia32_fixupimmss_mask: 3101 case X86::BI__builtin_ia32_fixupimmss_maskz: 3102 case X86::BI__builtin_ia32_getmantsd_round_mask: 3103 case X86::BI__builtin_ia32_getmantss_round_mask: 3104 case X86::BI__builtin_ia32_rangepd512_mask: 3105 case X86::BI__builtin_ia32_rangeps512_mask: 3106 case X86::BI__builtin_ia32_rangesd128_round_mask: 3107 case X86::BI__builtin_ia32_rangess128_round_mask: 3108 case X86::BI__builtin_ia32_reducesd_mask: 3109 case X86::BI__builtin_ia32_reducess_mask: 3110 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3111 case X86::BI__builtin_ia32_rndscaless_round_mask: 3112 ArgNum = 5; 3113 break; 3114 case X86::BI__builtin_ia32_vcvtsd2si64: 3115 case X86::BI__builtin_ia32_vcvtsd2si32: 3116 case X86::BI__builtin_ia32_vcvtsd2usi32: 3117 case X86::BI__builtin_ia32_vcvtsd2usi64: 3118 case X86::BI__builtin_ia32_vcvtss2si32: 3119 case X86::BI__builtin_ia32_vcvtss2si64: 3120 case X86::BI__builtin_ia32_vcvtss2usi32: 3121 case X86::BI__builtin_ia32_vcvtss2usi64: 3122 case X86::BI__builtin_ia32_sqrtpd512: 3123 case X86::BI__builtin_ia32_sqrtps512: 3124 ArgNum = 1; 3125 HasRC = true; 3126 break; 3127 case X86::BI__builtin_ia32_addpd512: 3128 case X86::BI__builtin_ia32_addps512: 3129 case X86::BI__builtin_ia32_divpd512: 3130 case X86::BI__builtin_ia32_divps512: 3131 case X86::BI__builtin_ia32_mulpd512: 3132 case X86::BI__builtin_ia32_mulps512: 3133 case X86::BI__builtin_ia32_subpd512: 3134 case X86::BI__builtin_ia32_subps512: 3135 case X86::BI__builtin_ia32_cvtsi2sd64: 3136 case X86::BI__builtin_ia32_cvtsi2ss32: 3137 case X86::BI__builtin_ia32_cvtsi2ss64: 3138 case X86::BI__builtin_ia32_cvtusi2sd64: 3139 case X86::BI__builtin_ia32_cvtusi2ss32: 3140 case X86::BI__builtin_ia32_cvtusi2ss64: 3141 ArgNum = 2; 3142 HasRC = true; 3143 break; 3144 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3145 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3146 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3147 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3148 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3149 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3150 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3151 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3152 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3153 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3154 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3155 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3156 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3157 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3158 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3159 ArgNum = 3; 3160 HasRC = true; 3161 break; 3162 case X86::BI__builtin_ia32_addss_round_mask: 3163 case X86::BI__builtin_ia32_addsd_round_mask: 3164 case X86::BI__builtin_ia32_divss_round_mask: 3165 case X86::BI__builtin_ia32_divsd_round_mask: 3166 case X86::BI__builtin_ia32_mulss_round_mask: 3167 case X86::BI__builtin_ia32_mulsd_round_mask: 3168 case X86::BI__builtin_ia32_subss_round_mask: 3169 case X86::BI__builtin_ia32_subsd_round_mask: 3170 case X86::BI__builtin_ia32_scalefpd512_mask: 3171 case X86::BI__builtin_ia32_scalefps512_mask: 3172 case X86::BI__builtin_ia32_scalefsd_round_mask: 3173 case X86::BI__builtin_ia32_scalefss_round_mask: 3174 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3175 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3176 case X86::BI__builtin_ia32_sqrtss_round_mask: 3177 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3178 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3179 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3180 case X86::BI__builtin_ia32_vfmaddss3_mask: 3181 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3182 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3183 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3184 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3185 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3186 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3187 case X86::BI__builtin_ia32_vfmaddps512_mask: 3188 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3189 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3190 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3191 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3192 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3193 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3194 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3195 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3196 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3197 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3198 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3199 ArgNum = 4; 3200 HasRC = true; 3201 break; 3202 } 3203 3204 llvm::APSInt Result; 3205 3206 // We can't check the value of a dependent argument. 3207 Expr *Arg = TheCall->getArg(ArgNum); 3208 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3209 return false; 3210 3211 // Check constant-ness first. 3212 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3213 return true; 3214 3215 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3216 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3217 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3218 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3219 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3220 Result == 8/*ROUND_NO_EXC*/ || 3221 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3222 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3223 return false; 3224 3225 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3226 << Arg->getSourceRange(); 3227 } 3228 3229 // Check if the gather/scatter scale is legal. 3230 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3231 CallExpr *TheCall) { 3232 unsigned ArgNum = 0; 3233 switch (BuiltinID) { 3234 default: 3235 return false; 3236 case X86::BI__builtin_ia32_gatherpfdpd: 3237 case X86::BI__builtin_ia32_gatherpfdps: 3238 case X86::BI__builtin_ia32_gatherpfqpd: 3239 case X86::BI__builtin_ia32_gatherpfqps: 3240 case X86::BI__builtin_ia32_scatterpfdpd: 3241 case X86::BI__builtin_ia32_scatterpfdps: 3242 case X86::BI__builtin_ia32_scatterpfqpd: 3243 case X86::BI__builtin_ia32_scatterpfqps: 3244 ArgNum = 3; 3245 break; 3246 case X86::BI__builtin_ia32_gatherd_pd: 3247 case X86::BI__builtin_ia32_gatherd_pd256: 3248 case X86::BI__builtin_ia32_gatherq_pd: 3249 case X86::BI__builtin_ia32_gatherq_pd256: 3250 case X86::BI__builtin_ia32_gatherd_ps: 3251 case X86::BI__builtin_ia32_gatherd_ps256: 3252 case X86::BI__builtin_ia32_gatherq_ps: 3253 case X86::BI__builtin_ia32_gatherq_ps256: 3254 case X86::BI__builtin_ia32_gatherd_q: 3255 case X86::BI__builtin_ia32_gatherd_q256: 3256 case X86::BI__builtin_ia32_gatherq_q: 3257 case X86::BI__builtin_ia32_gatherq_q256: 3258 case X86::BI__builtin_ia32_gatherd_d: 3259 case X86::BI__builtin_ia32_gatherd_d256: 3260 case X86::BI__builtin_ia32_gatherq_d: 3261 case X86::BI__builtin_ia32_gatherq_d256: 3262 case X86::BI__builtin_ia32_gather3div2df: 3263 case X86::BI__builtin_ia32_gather3div2di: 3264 case X86::BI__builtin_ia32_gather3div4df: 3265 case X86::BI__builtin_ia32_gather3div4di: 3266 case X86::BI__builtin_ia32_gather3div4sf: 3267 case X86::BI__builtin_ia32_gather3div4si: 3268 case X86::BI__builtin_ia32_gather3div8sf: 3269 case X86::BI__builtin_ia32_gather3div8si: 3270 case X86::BI__builtin_ia32_gather3siv2df: 3271 case X86::BI__builtin_ia32_gather3siv2di: 3272 case X86::BI__builtin_ia32_gather3siv4df: 3273 case X86::BI__builtin_ia32_gather3siv4di: 3274 case X86::BI__builtin_ia32_gather3siv4sf: 3275 case X86::BI__builtin_ia32_gather3siv4si: 3276 case X86::BI__builtin_ia32_gather3siv8sf: 3277 case X86::BI__builtin_ia32_gather3siv8si: 3278 case X86::BI__builtin_ia32_gathersiv8df: 3279 case X86::BI__builtin_ia32_gathersiv16sf: 3280 case X86::BI__builtin_ia32_gatherdiv8df: 3281 case X86::BI__builtin_ia32_gatherdiv16sf: 3282 case X86::BI__builtin_ia32_gathersiv8di: 3283 case X86::BI__builtin_ia32_gathersiv16si: 3284 case X86::BI__builtin_ia32_gatherdiv8di: 3285 case X86::BI__builtin_ia32_gatherdiv16si: 3286 case X86::BI__builtin_ia32_scatterdiv2df: 3287 case X86::BI__builtin_ia32_scatterdiv2di: 3288 case X86::BI__builtin_ia32_scatterdiv4df: 3289 case X86::BI__builtin_ia32_scatterdiv4di: 3290 case X86::BI__builtin_ia32_scatterdiv4sf: 3291 case X86::BI__builtin_ia32_scatterdiv4si: 3292 case X86::BI__builtin_ia32_scatterdiv8sf: 3293 case X86::BI__builtin_ia32_scatterdiv8si: 3294 case X86::BI__builtin_ia32_scattersiv2df: 3295 case X86::BI__builtin_ia32_scattersiv2di: 3296 case X86::BI__builtin_ia32_scattersiv4df: 3297 case X86::BI__builtin_ia32_scattersiv4di: 3298 case X86::BI__builtin_ia32_scattersiv4sf: 3299 case X86::BI__builtin_ia32_scattersiv4si: 3300 case X86::BI__builtin_ia32_scattersiv8sf: 3301 case X86::BI__builtin_ia32_scattersiv8si: 3302 case X86::BI__builtin_ia32_scattersiv8df: 3303 case X86::BI__builtin_ia32_scattersiv16sf: 3304 case X86::BI__builtin_ia32_scatterdiv8df: 3305 case X86::BI__builtin_ia32_scatterdiv16sf: 3306 case X86::BI__builtin_ia32_scattersiv8di: 3307 case X86::BI__builtin_ia32_scattersiv16si: 3308 case X86::BI__builtin_ia32_scatterdiv8di: 3309 case X86::BI__builtin_ia32_scatterdiv16si: 3310 ArgNum = 4; 3311 break; 3312 } 3313 3314 llvm::APSInt Result; 3315 3316 // We can't check the value of a dependent argument. 3317 Expr *Arg = TheCall->getArg(ArgNum); 3318 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3319 return false; 3320 3321 // Check constant-ness first. 3322 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3323 return true; 3324 3325 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3326 return false; 3327 3328 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3329 << Arg->getSourceRange(); 3330 } 3331 3332 static bool isX86_32Builtin(unsigned BuiltinID) { 3333 // These builtins only work on x86-32 targets. 3334 switch (BuiltinID) { 3335 case X86::BI__builtin_ia32_readeflags_u32: 3336 case X86::BI__builtin_ia32_writeeflags_u32: 3337 return true; 3338 } 3339 3340 return false; 3341 } 3342 3343 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 3344 if (BuiltinID == X86::BI__builtin_cpu_supports) 3345 return SemaBuiltinCpuSupports(*this, TheCall); 3346 3347 if (BuiltinID == X86::BI__builtin_cpu_is) 3348 return SemaBuiltinCpuIs(*this, TheCall); 3349 3350 // Check for 32-bit only builtins on a 64-bit target. 3351 const llvm::Triple &TT = Context.getTargetInfo().getTriple(); 3352 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3353 return Diag(TheCall->getCallee()->getBeginLoc(), 3354 diag::err_32_bit_builtin_64_bit_tgt); 3355 3356 // If the intrinsic has rounding or SAE make sure its valid. 3357 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3358 return true; 3359 3360 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3361 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3362 return true; 3363 3364 // For intrinsics which take an immediate value as part of the instruction, 3365 // range check them here. 3366 int i = 0, l = 0, u = 0; 3367 switch (BuiltinID) { 3368 default: 3369 return false; 3370 case X86::BI__builtin_ia32_vec_ext_v2si: 3371 case X86::BI__builtin_ia32_vec_ext_v2di: 3372 case X86::BI__builtin_ia32_vextractf128_pd256: 3373 case X86::BI__builtin_ia32_vextractf128_ps256: 3374 case X86::BI__builtin_ia32_vextractf128_si256: 3375 case X86::BI__builtin_ia32_extract128i256: 3376 case X86::BI__builtin_ia32_extractf64x4_mask: 3377 case X86::BI__builtin_ia32_extracti64x4_mask: 3378 case X86::BI__builtin_ia32_extractf32x8_mask: 3379 case X86::BI__builtin_ia32_extracti32x8_mask: 3380 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3381 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3382 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3383 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3384 i = 1; l = 0; u = 1; 3385 break; 3386 case X86::BI__builtin_ia32_vec_set_v2di: 3387 case X86::BI__builtin_ia32_vinsertf128_pd256: 3388 case X86::BI__builtin_ia32_vinsertf128_ps256: 3389 case X86::BI__builtin_ia32_vinsertf128_si256: 3390 case X86::BI__builtin_ia32_insert128i256: 3391 case X86::BI__builtin_ia32_insertf32x8: 3392 case X86::BI__builtin_ia32_inserti32x8: 3393 case X86::BI__builtin_ia32_insertf64x4: 3394 case X86::BI__builtin_ia32_inserti64x4: 3395 case X86::BI__builtin_ia32_insertf64x2_256: 3396 case X86::BI__builtin_ia32_inserti64x2_256: 3397 case X86::BI__builtin_ia32_insertf32x4_256: 3398 case X86::BI__builtin_ia32_inserti32x4_256: 3399 i = 2; l = 0; u = 1; 3400 break; 3401 case X86::BI__builtin_ia32_vpermilpd: 3402 case X86::BI__builtin_ia32_vec_ext_v4hi: 3403 case X86::BI__builtin_ia32_vec_ext_v4si: 3404 case X86::BI__builtin_ia32_vec_ext_v4sf: 3405 case X86::BI__builtin_ia32_vec_ext_v4di: 3406 case X86::BI__builtin_ia32_extractf32x4_mask: 3407 case X86::BI__builtin_ia32_extracti32x4_mask: 3408 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3409 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3410 i = 1; l = 0; u = 3; 3411 break; 3412 case X86::BI_mm_prefetch: 3413 case X86::BI__builtin_ia32_vec_ext_v8hi: 3414 case X86::BI__builtin_ia32_vec_ext_v8si: 3415 i = 1; l = 0; u = 7; 3416 break; 3417 case X86::BI__builtin_ia32_sha1rnds4: 3418 case X86::BI__builtin_ia32_blendpd: 3419 case X86::BI__builtin_ia32_shufpd: 3420 case X86::BI__builtin_ia32_vec_set_v4hi: 3421 case X86::BI__builtin_ia32_vec_set_v4si: 3422 case X86::BI__builtin_ia32_vec_set_v4di: 3423 case X86::BI__builtin_ia32_shuf_f32x4_256: 3424 case X86::BI__builtin_ia32_shuf_f64x2_256: 3425 case X86::BI__builtin_ia32_shuf_i32x4_256: 3426 case X86::BI__builtin_ia32_shuf_i64x2_256: 3427 case X86::BI__builtin_ia32_insertf64x2_512: 3428 case X86::BI__builtin_ia32_inserti64x2_512: 3429 case X86::BI__builtin_ia32_insertf32x4: 3430 case X86::BI__builtin_ia32_inserti32x4: 3431 i = 2; l = 0; u = 3; 3432 break; 3433 case X86::BI__builtin_ia32_vpermil2pd: 3434 case X86::BI__builtin_ia32_vpermil2pd256: 3435 case X86::BI__builtin_ia32_vpermil2ps: 3436 case X86::BI__builtin_ia32_vpermil2ps256: 3437 i = 3; l = 0; u = 3; 3438 break; 3439 case X86::BI__builtin_ia32_cmpb128_mask: 3440 case X86::BI__builtin_ia32_cmpw128_mask: 3441 case X86::BI__builtin_ia32_cmpd128_mask: 3442 case X86::BI__builtin_ia32_cmpq128_mask: 3443 case X86::BI__builtin_ia32_cmpb256_mask: 3444 case X86::BI__builtin_ia32_cmpw256_mask: 3445 case X86::BI__builtin_ia32_cmpd256_mask: 3446 case X86::BI__builtin_ia32_cmpq256_mask: 3447 case X86::BI__builtin_ia32_cmpb512_mask: 3448 case X86::BI__builtin_ia32_cmpw512_mask: 3449 case X86::BI__builtin_ia32_cmpd512_mask: 3450 case X86::BI__builtin_ia32_cmpq512_mask: 3451 case X86::BI__builtin_ia32_ucmpb128_mask: 3452 case X86::BI__builtin_ia32_ucmpw128_mask: 3453 case X86::BI__builtin_ia32_ucmpd128_mask: 3454 case X86::BI__builtin_ia32_ucmpq128_mask: 3455 case X86::BI__builtin_ia32_ucmpb256_mask: 3456 case X86::BI__builtin_ia32_ucmpw256_mask: 3457 case X86::BI__builtin_ia32_ucmpd256_mask: 3458 case X86::BI__builtin_ia32_ucmpq256_mask: 3459 case X86::BI__builtin_ia32_ucmpb512_mask: 3460 case X86::BI__builtin_ia32_ucmpw512_mask: 3461 case X86::BI__builtin_ia32_ucmpd512_mask: 3462 case X86::BI__builtin_ia32_ucmpq512_mask: 3463 case X86::BI__builtin_ia32_vpcomub: 3464 case X86::BI__builtin_ia32_vpcomuw: 3465 case X86::BI__builtin_ia32_vpcomud: 3466 case X86::BI__builtin_ia32_vpcomuq: 3467 case X86::BI__builtin_ia32_vpcomb: 3468 case X86::BI__builtin_ia32_vpcomw: 3469 case X86::BI__builtin_ia32_vpcomd: 3470 case X86::BI__builtin_ia32_vpcomq: 3471 case X86::BI__builtin_ia32_vec_set_v8hi: 3472 case X86::BI__builtin_ia32_vec_set_v8si: 3473 i = 2; l = 0; u = 7; 3474 break; 3475 case X86::BI__builtin_ia32_vpermilpd256: 3476 case X86::BI__builtin_ia32_roundps: 3477 case X86::BI__builtin_ia32_roundpd: 3478 case X86::BI__builtin_ia32_roundps256: 3479 case X86::BI__builtin_ia32_roundpd256: 3480 case X86::BI__builtin_ia32_getmantpd128_mask: 3481 case X86::BI__builtin_ia32_getmantpd256_mask: 3482 case X86::BI__builtin_ia32_getmantps128_mask: 3483 case X86::BI__builtin_ia32_getmantps256_mask: 3484 case X86::BI__builtin_ia32_getmantpd512_mask: 3485 case X86::BI__builtin_ia32_getmantps512_mask: 3486 case X86::BI__builtin_ia32_vec_ext_v16qi: 3487 case X86::BI__builtin_ia32_vec_ext_v16hi: 3488 i = 1; l = 0; u = 15; 3489 break; 3490 case X86::BI__builtin_ia32_pblendd128: 3491 case X86::BI__builtin_ia32_blendps: 3492 case X86::BI__builtin_ia32_blendpd256: 3493 case X86::BI__builtin_ia32_shufpd256: 3494 case X86::BI__builtin_ia32_roundss: 3495 case X86::BI__builtin_ia32_roundsd: 3496 case X86::BI__builtin_ia32_rangepd128_mask: 3497 case X86::BI__builtin_ia32_rangepd256_mask: 3498 case X86::BI__builtin_ia32_rangepd512_mask: 3499 case X86::BI__builtin_ia32_rangeps128_mask: 3500 case X86::BI__builtin_ia32_rangeps256_mask: 3501 case X86::BI__builtin_ia32_rangeps512_mask: 3502 case X86::BI__builtin_ia32_getmantsd_round_mask: 3503 case X86::BI__builtin_ia32_getmantss_round_mask: 3504 case X86::BI__builtin_ia32_vec_set_v16qi: 3505 case X86::BI__builtin_ia32_vec_set_v16hi: 3506 i = 2; l = 0; u = 15; 3507 break; 3508 case X86::BI__builtin_ia32_vec_ext_v32qi: 3509 i = 1; l = 0; u = 31; 3510 break; 3511 case X86::BI__builtin_ia32_cmpps: 3512 case X86::BI__builtin_ia32_cmpss: 3513 case X86::BI__builtin_ia32_cmppd: 3514 case X86::BI__builtin_ia32_cmpsd: 3515 case X86::BI__builtin_ia32_cmpps256: 3516 case X86::BI__builtin_ia32_cmppd256: 3517 case X86::BI__builtin_ia32_cmpps128_mask: 3518 case X86::BI__builtin_ia32_cmppd128_mask: 3519 case X86::BI__builtin_ia32_cmpps256_mask: 3520 case X86::BI__builtin_ia32_cmppd256_mask: 3521 case X86::BI__builtin_ia32_cmpps512_mask: 3522 case X86::BI__builtin_ia32_cmppd512_mask: 3523 case X86::BI__builtin_ia32_cmpsd_mask: 3524 case X86::BI__builtin_ia32_cmpss_mask: 3525 case X86::BI__builtin_ia32_vec_set_v32qi: 3526 i = 2; l = 0; u = 31; 3527 break; 3528 case X86::BI__builtin_ia32_permdf256: 3529 case X86::BI__builtin_ia32_permdi256: 3530 case X86::BI__builtin_ia32_permdf512: 3531 case X86::BI__builtin_ia32_permdi512: 3532 case X86::BI__builtin_ia32_vpermilps: 3533 case X86::BI__builtin_ia32_vpermilps256: 3534 case X86::BI__builtin_ia32_vpermilpd512: 3535 case X86::BI__builtin_ia32_vpermilps512: 3536 case X86::BI__builtin_ia32_pshufd: 3537 case X86::BI__builtin_ia32_pshufd256: 3538 case X86::BI__builtin_ia32_pshufd512: 3539 case X86::BI__builtin_ia32_pshufhw: 3540 case X86::BI__builtin_ia32_pshufhw256: 3541 case X86::BI__builtin_ia32_pshufhw512: 3542 case X86::BI__builtin_ia32_pshuflw: 3543 case X86::BI__builtin_ia32_pshuflw256: 3544 case X86::BI__builtin_ia32_pshuflw512: 3545 case X86::BI__builtin_ia32_vcvtps2ph: 3546 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3547 case X86::BI__builtin_ia32_vcvtps2ph256: 3548 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3549 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3550 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3551 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3552 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3553 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3554 case X86::BI__builtin_ia32_rndscaleps_mask: 3555 case X86::BI__builtin_ia32_rndscalepd_mask: 3556 case X86::BI__builtin_ia32_reducepd128_mask: 3557 case X86::BI__builtin_ia32_reducepd256_mask: 3558 case X86::BI__builtin_ia32_reducepd512_mask: 3559 case X86::BI__builtin_ia32_reduceps128_mask: 3560 case X86::BI__builtin_ia32_reduceps256_mask: 3561 case X86::BI__builtin_ia32_reduceps512_mask: 3562 case X86::BI__builtin_ia32_prold512: 3563 case X86::BI__builtin_ia32_prolq512: 3564 case X86::BI__builtin_ia32_prold128: 3565 case X86::BI__builtin_ia32_prold256: 3566 case X86::BI__builtin_ia32_prolq128: 3567 case X86::BI__builtin_ia32_prolq256: 3568 case X86::BI__builtin_ia32_prord512: 3569 case X86::BI__builtin_ia32_prorq512: 3570 case X86::BI__builtin_ia32_prord128: 3571 case X86::BI__builtin_ia32_prord256: 3572 case X86::BI__builtin_ia32_prorq128: 3573 case X86::BI__builtin_ia32_prorq256: 3574 case X86::BI__builtin_ia32_fpclasspd128_mask: 3575 case X86::BI__builtin_ia32_fpclasspd256_mask: 3576 case X86::BI__builtin_ia32_fpclassps128_mask: 3577 case X86::BI__builtin_ia32_fpclassps256_mask: 3578 case X86::BI__builtin_ia32_fpclassps512_mask: 3579 case X86::BI__builtin_ia32_fpclasspd512_mask: 3580 case X86::BI__builtin_ia32_fpclasssd_mask: 3581 case X86::BI__builtin_ia32_fpclassss_mask: 3582 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3583 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3584 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3585 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3586 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3587 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3588 case X86::BI__builtin_ia32_kshiftliqi: 3589 case X86::BI__builtin_ia32_kshiftlihi: 3590 case X86::BI__builtin_ia32_kshiftlisi: 3591 case X86::BI__builtin_ia32_kshiftlidi: 3592 case X86::BI__builtin_ia32_kshiftriqi: 3593 case X86::BI__builtin_ia32_kshiftrihi: 3594 case X86::BI__builtin_ia32_kshiftrisi: 3595 case X86::BI__builtin_ia32_kshiftridi: 3596 i = 1; l = 0; u = 255; 3597 break; 3598 case X86::BI__builtin_ia32_vperm2f128_pd256: 3599 case X86::BI__builtin_ia32_vperm2f128_ps256: 3600 case X86::BI__builtin_ia32_vperm2f128_si256: 3601 case X86::BI__builtin_ia32_permti256: 3602 case X86::BI__builtin_ia32_pblendw128: 3603 case X86::BI__builtin_ia32_pblendw256: 3604 case X86::BI__builtin_ia32_blendps256: 3605 case X86::BI__builtin_ia32_pblendd256: 3606 case X86::BI__builtin_ia32_palignr128: 3607 case X86::BI__builtin_ia32_palignr256: 3608 case X86::BI__builtin_ia32_palignr512: 3609 case X86::BI__builtin_ia32_alignq512: 3610 case X86::BI__builtin_ia32_alignd512: 3611 case X86::BI__builtin_ia32_alignd128: 3612 case X86::BI__builtin_ia32_alignd256: 3613 case X86::BI__builtin_ia32_alignq128: 3614 case X86::BI__builtin_ia32_alignq256: 3615 case X86::BI__builtin_ia32_vcomisd: 3616 case X86::BI__builtin_ia32_vcomiss: 3617 case X86::BI__builtin_ia32_shuf_f32x4: 3618 case X86::BI__builtin_ia32_shuf_f64x2: 3619 case X86::BI__builtin_ia32_shuf_i32x4: 3620 case X86::BI__builtin_ia32_shuf_i64x2: 3621 case X86::BI__builtin_ia32_shufpd512: 3622 case X86::BI__builtin_ia32_shufps: 3623 case X86::BI__builtin_ia32_shufps256: 3624 case X86::BI__builtin_ia32_shufps512: 3625 case X86::BI__builtin_ia32_dbpsadbw128: 3626 case X86::BI__builtin_ia32_dbpsadbw256: 3627 case X86::BI__builtin_ia32_dbpsadbw512: 3628 case X86::BI__builtin_ia32_vpshldd128: 3629 case X86::BI__builtin_ia32_vpshldd256: 3630 case X86::BI__builtin_ia32_vpshldd512: 3631 case X86::BI__builtin_ia32_vpshldq128: 3632 case X86::BI__builtin_ia32_vpshldq256: 3633 case X86::BI__builtin_ia32_vpshldq512: 3634 case X86::BI__builtin_ia32_vpshldw128: 3635 case X86::BI__builtin_ia32_vpshldw256: 3636 case X86::BI__builtin_ia32_vpshldw512: 3637 case X86::BI__builtin_ia32_vpshrdd128: 3638 case X86::BI__builtin_ia32_vpshrdd256: 3639 case X86::BI__builtin_ia32_vpshrdd512: 3640 case X86::BI__builtin_ia32_vpshrdq128: 3641 case X86::BI__builtin_ia32_vpshrdq256: 3642 case X86::BI__builtin_ia32_vpshrdq512: 3643 case X86::BI__builtin_ia32_vpshrdw128: 3644 case X86::BI__builtin_ia32_vpshrdw256: 3645 case X86::BI__builtin_ia32_vpshrdw512: 3646 i = 2; l = 0; u = 255; 3647 break; 3648 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3649 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3650 case X86::BI__builtin_ia32_fixupimmps512_mask: 3651 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3652 case X86::BI__builtin_ia32_fixupimmsd_mask: 3653 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3654 case X86::BI__builtin_ia32_fixupimmss_mask: 3655 case X86::BI__builtin_ia32_fixupimmss_maskz: 3656 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3657 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3658 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3659 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3660 case X86::BI__builtin_ia32_fixupimmps128_mask: 3661 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3662 case X86::BI__builtin_ia32_fixupimmps256_mask: 3663 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3664 case X86::BI__builtin_ia32_pternlogd512_mask: 3665 case X86::BI__builtin_ia32_pternlogd512_maskz: 3666 case X86::BI__builtin_ia32_pternlogq512_mask: 3667 case X86::BI__builtin_ia32_pternlogq512_maskz: 3668 case X86::BI__builtin_ia32_pternlogd128_mask: 3669 case X86::BI__builtin_ia32_pternlogd128_maskz: 3670 case X86::BI__builtin_ia32_pternlogd256_mask: 3671 case X86::BI__builtin_ia32_pternlogd256_maskz: 3672 case X86::BI__builtin_ia32_pternlogq128_mask: 3673 case X86::BI__builtin_ia32_pternlogq128_maskz: 3674 case X86::BI__builtin_ia32_pternlogq256_mask: 3675 case X86::BI__builtin_ia32_pternlogq256_maskz: 3676 i = 3; l = 0; u = 255; 3677 break; 3678 case X86::BI__builtin_ia32_gatherpfdpd: 3679 case X86::BI__builtin_ia32_gatherpfdps: 3680 case X86::BI__builtin_ia32_gatherpfqpd: 3681 case X86::BI__builtin_ia32_gatherpfqps: 3682 case X86::BI__builtin_ia32_scatterpfdpd: 3683 case X86::BI__builtin_ia32_scatterpfdps: 3684 case X86::BI__builtin_ia32_scatterpfqpd: 3685 case X86::BI__builtin_ia32_scatterpfqps: 3686 i = 4; l = 2; u = 3; 3687 break; 3688 case X86::BI__builtin_ia32_reducesd_mask: 3689 case X86::BI__builtin_ia32_reducess_mask: 3690 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3691 case X86::BI__builtin_ia32_rndscaless_round_mask: 3692 i = 4; l = 0; u = 255; 3693 break; 3694 } 3695 3696 // Note that we don't force a hard error on the range check here, allowing 3697 // template-generated or macro-generated dead code to potentially have out-of- 3698 // range values. These need to code generate, but don't need to necessarily 3699 // make any sense. We use a warning that defaults to an error. 3700 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3701 } 3702 3703 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3704 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3705 /// Returns true when the format fits the function and the FormatStringInfo has 3706 /// been populated. 3707 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3708 FormatStringInfo *FSI) { 3709 FSI->HasVAListArg = Format->getFirstArg() == 0; 3710 FSI->FormatIdx = Format->getFormatIdx() - 1; 3711 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3712 3713 // The way the format attribute works in GCC, the implicit this argument 3714 // of member functions is counted. However, it doesn't appear in our own 3715 // lists, so decrement format_idx in that case. 3716 if (IsCXXMember) { 3717 if(FSI->FormatIdx == 0) 3718 return false; 3719 --FSI->FormatIdx; 3720 if (FSI->FirstDataArg != 0) 3721 --FSI->FirstDataArg; 3722 } 3723 return true; 3724 } 3725 3726 /// Checks if a the given expression evaluates to null. 3727 /// 3728 /// Returns true if the value evaluates to null. 3729 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3730 // If the expression has non-null type, it doesn't evaluate to null. 3731 if (auto nullability 3732 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3733 if (*nullability == NullabilityKind::NonNull) 3734 return false; 3735 } 3736 3737 // As a special case, transparent unions initialized with zero are 3738 // considered null for the purposes of the nonnull attribute. 3739 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3740 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3741 if (const CompoundLiteralExpr *CLE = 3742 dyn_cast<CompoundLiteralExpr>(Expr)) 3743 if (const InitListExpr *ILE = 3744 dyn_cast<InitListExpr>(CLE->getInitializer())) 3745 Expr = ILE->getInit(0); 3746 } 3747 3748 bool Result; 3749 return (!Expr->isValueDependent() && 3750 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3751 !Result); 3752 } 3753 3754 static void CheckNonNullArgument(Sema &S, 3755 const Expr *ArgExpr, 3756 SourceLocation CallSiteLoc) { 3757 if (CheckNonNullExpr(S, ArgExpr)) 3758 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3759 S.PDiag(diag::warn_null_arg) 3760 << ArgExpr->getSourceRange()); 3761 } 3762 3763 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3764 FormatStringInfo FSI; 3765 if ((GetFormatStringType(Format) == FST_NSString) && 3766 getFormatStringInfo(Format, false, &FSI)) { 3767 Idx = FSI.FormatIdx; 3768 return true; 3769 } 3770 return false; 3771 } 3772 3773 /// Diagnose use of %s directive in an NSString which is being passed 3774 /// as formatting string to formatting method. 3775 static void 3776 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3777 const NamedDecl *FDecl, 3778 Expr **Args, 3779 unsigned NumArgs) { 3780 unsigned Idx = 0; 3781 bool Format = false; 3782 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 3783 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 3784 Idx = 2; 3785 Format = true; 3786 } 3787 else 3788 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3789 if (S.GetFormatNSStringIdx(I, Idx)) { 3790 Format = true; 3791 break; 3792 } 3793 } 3794 if (!Format || NumArgs <= Idx) 3795 return; 3796 const Expr *FormatExpr = Args[Idx]; 3797 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 3798 FormatExpr = CSCE->getSubExpr(); 3799 const StringLiteral *FormatString; 3800 if (const ObjCStringLiteral *OSL = 3801 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 3802 FormatString = OSL->getString(); 3803 else 3804 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 3805 if (!FormatString) 3806 return; 3807 if (S.FormatStringHasSArg(FormatString)) { 3808 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 3809 << "%s" << 1 << 1; 3810 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 3811 << FDecl->getDeclName(); 3812 } 3813 } 3814 3815 /// Determine whether the given type has a non-null nullability annotation. 3816 static bool isNonNullType(ASTContext &ctx, QualType type) { 3817 if (auto nullability = type->getNullability(ctx)) 3818 return *nullability == NullabilityKind::NonNull; 3819 3820 return false; 3821 } 3822 3823 static void CheckNonNullArguments(Sema &S, 3824 const NamedDecl *FDecl, 3825 const FunctionProtoType *Proto, 3826 ArrayRef<const Expr *> Args, 3827 SourceLocation CallSiteLoc) { 3828 assert((FDecl || Proto) && "Need a function declaration or prototype"); 3829 3830 // Already checked by by constant evaluator. 3831 if (S.isConstantEvaluated()) 3832 return; 3833 // Check the attributes attached to the method/function itself. 3834 llvm::SmallBitVector NonNullArgs; 3835 if (FDecl) { 3836 // Handle the nonnull attribute on the function/method declaration itself. 3837 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 3838 if (!NonNull->args_size()) { 3839 // Easy case: all pointer arguments are nonnull. 3840 for (const auto *Arg : Args) 3841 if (S.isValidPointerAttrType(Arg->getType())) 3842 CheckNonNullArgument(S, Arg, CallSiteLoc); 3843 return; 3844 } 3845 3846 for (const ParamIdx &Idx : NonNull->args()) { 3847 unsigned IdxAST = Idx.getASTIndex(); 3848 if (IdxAST >= Args.size()) 3849 continue; 3850 if (NonNullArgs.empty()) 3851 NonNullArgs.resize(Args.size()); 3852 NonNullArgs.set(IdxAST); 3853 } 3854 } 3855 } 3856 3857 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 3858 // Handle the nonnull attribute on the parameters of the 3859 // function/method. 3860 ArrayRef<ParmVarDecl*> parms; 3861 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 3862 parms = FD->parameters(); 3863 else 3864 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 3865 3866 unsigned ParamIndex = 0; 3867 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 3868 I != E; ++I, ++ParamIndex) { 3869 const ParmVarDecl *PVD = *I; 3870 if (PVD->hasAttr<NonNullAttr>() || 3871 isNonNullType(S.Context, PVD->getType())) { 3872 if (NonNullArgs.empty()) 3873 NonNullArgs.resize(Args.size()); 3874 3875 NonNullArgs.set(ParamIndex); 3876 } 3877 } 3878 } else { 3879 // If we have a non-function, non-method declaration but no 3880 // function prototype, try to dig out the function prototype. 3881 if (!Proto) { 3882 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 3883 QualType type = VD->getType().getNonReferenceType(); 3884 if (auto pointerType = type->getAs<PointerType>()) 3885 type = pointerType->getPointeeType(); 3886 else if (auto blockType = type->getAs<BlockPointerType>()) 3887 type = blockType->getPointeeType(); 3888 // FIXME: data member pointers? 3889 3890 // Dig out the function prototype, if there is one. 3891 Proto = type->getAs<FunctionProtoType>(); 3892 } 3893 } 3894 3895 // Fill in non-null argument information from the nullability 3896 // information on the parameter types (if we have them). 3897 if (Proto) { 3898 unsigned Index = 0; 3899 for (auto paramType : Proto->getParamTypes()) { 3900 if (isNonNullType(S.Context, paramType)) { 3901 if (NonNullArgs.empty()) 3902 NonNullArgs.resize(Args.size()); 3903 3904 NonNullArgs.set(Index); 3905 } 3906 3907 ++Index; 3908 } 3909 } 3910 } 3911 3912 // Check for non-null arguments. 3913 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 3914 ArgIndex != ArgIndexEnd; ++ArgIndex) { 3915 if (NonNullArgs[ArgIndex]) 3916 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 3917 } 3918 } 3919 3920 /// Handles the checks for format strings, non-POD arguments to vararg 3921 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 3922 /// attributes. 3923 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 3924 const Expr *ThisArg, ArrayRef<const Expr *> Args, 3925 bool IsMemberFunction, SourceLocation Loc, 3926 SourceRange Range, VariadicCallType CallType) { 3927 // FIXME: We should check as much as we can in the template definition. 3928 if (CurContext->isDependentContext()) 3929 return; 3930 3931 // Printf and scanf checking. 3932 llvm::SmallBitVector CheckedVarArgs; 3933 if (FDecl) { 3934 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 3935 // Only create vector if there are format attributes. 3936 CheckedVarArgs.resize(Args.size()); 3937 3938 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 3939 CheckedVarArgs); 3940 } 3941 } 3942 3943 // Refuse POD arguments that weren't caught by the format string 3944 // checks above. 3945 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 3946 if (CallType != VariadicDoesNotApply && 3947 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 3948 unsigned NumParams = Proto ? Proto->getNumParams() 3949 : FDecl && isa<FunctionDecl>(FDecl) 3950 ? cast<FunctionDecl>(FDecl)->getNumParams() 3951 : FDecl && isa<ObjCMethodDecl>(FDecl) 3952 ? cast<ObjCMethodDecl>(FDecl)->param_size() 3953 : 0; 3954 3955 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 3956 // Args[ArgIdx] can be null in malformed code. 3957 if (const Expr *Arg = Args[ArgIdx]) { 3958 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 3959 checkVariadicArgument(Arg, CallType); 3960 } 3961 } 3962 } 3963 3964 if (FDecl || Proto) { 3965 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 3966 3967 // Type safety checking. 3968 if (FDecl) { 3969 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 3970 CheckArgumentWithTypeTag(I, Args, Loc); 3971 } 3972 } 3973 3974 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 3975 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 3976 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 3977 if (!Arg->isValueDependent()) { 3978 Expr::EvalResult Align; 3979 if (Arg->EvaluateAsInt(Align, Context)) { 3980 const llvm::APSInt &I = Align.Val.getInt(); 3981 if (!I.isPowerOf2()) 3982 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 3983 << Arg->getSourceRange(); 3984 3985 if (I > Sema::MaximumAlignment) 3986 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 3987 << Arg->getSourceRange() << Sema::MaximumAlignment; 3988 } 3989 } 3990 } 3991 3992 if (FD) 3993 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 3994 } 3995 3996 /// CheckConstructorCall - Check a constructor call for correctness and safety 3997 /// properties not enforced by the C type system. 3998 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 3999 ArrayRef<const Expr *> Args, 4000 const FunctionProtoType *Proto, 4001 SourceLocation Loc) { 4002 VariadicCallType CallType = 4003 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4004 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4005 Loc, SourceRange(), CallType); 4006 } 4007 4008 /// CheckFunctionCall - Check a direct function call for various correctness 4009 /// and safety properties not strictly enforced by the C type system. 4010 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4011 const FunctionProtoType *Proto) { 4012 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4013 isa<CXXMethodDecl>(FDecl); 4014 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4015 IsMemberOperatorCall; 4016 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4017 TheCall->getCallee()); 4018 Expr** Args = TheCall->getArgs(); 4019 unsigned NumArgs = TheCall->getNumArgs(); 4020 4021 Expr *ImplicitThis = nullptr; 4022 if (IsMemberOperatorCall) { 4023 // If this is a call to a member operator, hide the first argument 4024 // from checkCall. 4025 // FIXME: Our choice of AST representation here is less than ideal. 4026 ImplicitThis = Args[0]; 4027 ++Args; 4028 --NumArgs; 4029 } else if (IsMemberFunction) 4030 ImplicitThis = 4031 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4032 4033 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4034 IsMemberFunction, TheCall->getRParenLoc(), 4035 TheCall->getCallee()->getSourceRange(), CallType); 4036 4037 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4038 // None of the checks below are needed for functions that don't have 4039 // simple names (e.g., C++ conversion functions). 4040 if (!FnInfo) 4041 return false; 4042 4043 CheckAbsoluteValueFunction(TheCall, FDecl); 4044 CheckMaxUnsignedZero(TheCall, FDecl); 4045 4046 if (getLangOpts().ObjC) 4047 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4048 4049 unsigned CMId = FDecl->getMemoryFunctionKind(); 4050 if (CMId == 0) 4051 return false; 4052 4053 // Handle memory setting and copying functions. 4054 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4055 CheckStrlcpycatArguments(TheCall, FnInfo); 4056 else if (CMId == Builtin::BIstrncat) 4057 CheckStrncatArguments(TheCall, FnInfo); 4058 else 4059 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4060 4061 return false; 4062 } 4063 4064 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4065 ArrayRef<const Expr *> Args) { 4066 VariadicCallType CallType = 4067 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4068 4069 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4070 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4071 CallType); 4072 4073 return false; 4074 } 4075 4076 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4077 const FunctionProtoType *Proto) { 4078 QualType Ty; 4079 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4080 Ty = V->getType().getNonReferenceType(); 4081 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4082 Ty = F->getType().getNonReferenceType(); 4083 else 4084 return false; 4085 4086 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4087 !Ty->isFunctionProtoType()) 4088 return false; 4089 4090 VariadicCallType CallType; 4091 if (!Proto || !Proto->isVariadic()) { 4092 CallType = VariadicDoesNotApply; 4093 } else if (Ty->isBlockPointerType()) { 4094 CallType = VariadicBlock; 4095 } else { // Ty->isFunctionPointerType() 4096 CallType = VariadicFunction; 4097 } 4098 4099 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4100 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4101 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4102 TheCall->getCallee()->getSourceRange(), CallType); 4103 4104 return false; 4105 } 4106 4107 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4108 /// such as function pointers returned from functions. 4109 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4110 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4111 TheCall->getCallee()); 4112 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4113 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4114 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4115 TheCall->getCallee()->getSourceRange(), CallType); 4116 4117 return false; 4118 } 4119 4120 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4121 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4122 return false; 4123 4124 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4125 switch (Op) { 4126 case AtomicExpr::AO__c11_atomic_init: 4127 case AtomicExpr::AO__opencl_atomic_init: 4128 llvm_unreachable("There is no ordering argument for an init"); 4129 4130 case AtomicExpr::AO__c11_atomic_load: 4131 case AtomicExpr::AO__opencl_atomic_load: 4132 case AtomicExpr::AO__atomic_load_n: 4133 case AtomicExpr::AO__atomic_load: 4134 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4135 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4136 4137 case AtomicExpr::AO__c11_atomic_store: 4138 case AtomicExpr::AO__opencl_atomic_store: 4139 case AtomicExpr::AO__atomic_store: 4140 case AtomicExpr::AO__atomic_store_n: 4141 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4142 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4143 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4144 4145 default: 4146 return true; 4147 } 4148 } 4149 4150 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4151 AtomicExpr::AtomicOp Op) { 4152 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4153 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4154 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4155 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4156 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4157 Op); 4158 } 4159 4160 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4161 SourceLocation RParenLoc, MultiExprArg Args, 4162 AtomicExpr::AtomicOp Op, 4163 AtomicArgumentOrder ArgOrder) { 4164 // All the non-OpenCL operations take one of the following forms. 4165 // The OpenCL operations take the __c11 forms with one extra argument for 4166 // synchronization scope. 4167 enum { 4168 // C __c11_atomic_init(A *, C) 4169 Init, 4170 4171 // C __c11_atomic_load(A *, int) 4172 Load, 4173 4174 // void __atomic_load(A *, CP, int) 4175 LoadCopy, 4176 4177 // void __atomic_store(A *, CP, int) 4178 Copy, 4179 4180 // C __c11_atomic_add(A *, M, int) 4181 Arithmetic, 4182 4183 // C __atomic_exchange_n(A *, CP, int) 4184 Xchg, 4185 4186 // void __atomic_exchange(A *, C *, CP, int) 4187 GNUXchg, 4188 4189 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4190 C11CmpXchg, 4191 4192 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4193 GNUCmpXchg 4194 } Form = Init; 4195 4196 const unsigned NumForm = GNUCmpXchg + 1; 4197 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4198 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4199 // where: 4200 // C is an appropriate type, 4201 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4202 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4203 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4204 // the int parameters are for orderings. 4205 4206 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4207 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4208 "need to update code for modified forms"); 4209 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4210 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4211 AtomicExpr::AO__atomic_load, 4212 "need to update code for modified C11 atomics"); 4213 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4214 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4215 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4216 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4217 IsOpenCL; 4218 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4219 Op == AtomicExpr::AO__atomic_store_n || 4220 Op == AtomicExpr::AO__atomic_exchange_n || 4221 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4222 bool IsAddSub = false; 4223 4224 switch (Op) { 4225 case AtomicExpr::AO__c11_atomic_init: 4226 case AtomicExpr::AO__opencl_atomic_init: 4227 Form = Init; 4228 break; 4229 4230 case AtomicExpr::AO__c11_atomic_load: 4231 case AtomicExpr::AO__opencl_atomic_load: 4232 case AtomicExpr::AO__atomic_load_n: 4233 Form = Load; 4234 break; 4235 4236 case AtomicExpr::AO__atomic_load: 4237 Form = LoadCopy; 4238 break; 4239 4240 case AtomicExpr::AO__c11_atomic_store: 4241 case AtomicExpr::AO__opencl_atomic_store: 4242 case AtomicExpr::AO__atomic_store: 4243 case AtomicExpr::AO__atomic_store_n: 4244 Form = Copy; 4245 break; 4246 4247 case AtomicExpr::AO__c11_atomic_fetch_add: 4248 case AtomicExpr::AO__c11_atomic_fetch_sub: 4249 case AtomicExpr::AO__opencl_atomic_fetch_add: 4250 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4251 case AtomicExpr::AO__atomic_fetch_add: 4252 case AtomicExpr::AO__atomic_fetch_sub: 4253 case AtomicExpr::AO__atomic_add_fetch: 4254 case AtomicExpr::AO__atomic_sub_fetch: 4255 IsAddSub = true; 4256 LLVM_FALLTHROUGH; 4257 case AtomicExpr::AO__c11_atomic_fetch_and: 4258 case AtomicExpr::AO__c11_atomic_fetch_or: 4259 case AtomicExpr::AO__c11_atomic_fetch_xor: 4260 case AtomicExpr::AO__opencl_atomic_fetch_and: 4261 case AtomicExpr::AO__opencl_atomic_fetch_or: 4262 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4263 case AtomicExpr::AO__atomic_fetch_and: 4264 case AtomicExpr::AO__atomic_fetch_or: 4265 case AtomicExpr::AO__atomic_fetch_xor: 4266 case AtomicExpr::AO__atomic_fetch_nand: 4267 case AtomicExpr::AO__atomic_and_fetch: 4268 case AtomicExpr::AO__atomic_or_fetch: 4269 case AtomicExpr::AO__atomic_xor_fetch: 4270 case AtomicExpr::AO__atomic_nand_fetch: 4271 case AtomicExpr::AO__c11_atomic_fetch_min: 4272 case AtomicExpr::AO__c11_atomic_fetch_max: 4273 case AtomicExpr::AO__opencl_atomic_fetch_min: 4274 case AtomicExpr::AO__opencl_atomic_fetch_max: 4275 case AtomicExpr::AO__atomic_min_fetch: 4276 case AtomicExpr::AO__atomic_max_fetch: 4277 case AtomicExpr::AO__atomic_fetch_min: 4278 case AtomicExpr::AO__atomic_fetch_max: 4279 Form = Arithmetic; 4280 break; 4281 4282 case AtomicExpr::AO__c11_atomic_exchange: 4283 case AtomicExpr::AO__opencl_atomic_exchange: 4284 case AtomicExpr::AO__atomic_exchange_n: 4285 Form = Xchg; 4286 break; 4287 4288 case AtomicExpr::AO__atomic_exchange: 4289 Form = GNUXchg; 4290 break; 4291 4292 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4293 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4294 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4295 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4296 Form = C11CmpXchg; 4297 break; 4298 4299 case AtomicExpr::AO__atomic_compare_exchange: 4300 case AtomicExpr::AO__atomic_compare_exchange_n: 4301 Form = GNUCmpXchg; 4302 break; 4303 } 4304 4305 unsigned AdjustedNumArgs = NumArgs[Form]; 4306 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4307 ++AdjustedNumArgs; 4308 // Check we have the right number of arguments. 4309 if (Args.size() < AdjustedNumArgs) { 4310 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4311 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4312 << ExprRange; 4313 return ExprError(); 4314 } else if (Args.size() > AdjustedNumArgs) { 4315 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4316 diag::err_typecheck_call_too_many_args) 4317 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4318 << ExprRange; 4319 return ExprError(); 4320 } 4321 4322 // Inspect the first argument of the atomic operation. 4323 Expr *Ptr = Args[0]; 4324 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4325 if (ConvertedPtr.isInvalid()) 4326 return ExprError(); 4327 4328 Ptr = ConvertedPtr.get(); 4329 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4330 if (!pointerType) { 4331 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4332 << Ptr->getType() << Ptr->getSourceRange(); 4333 return ExprError(); 4334 } 4335 4336 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4337 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4338 QualType ValType = AtomTy; // 'C' 4339 if (IsC11) { 4340 if (!AtomTy->isAtomicType()) { 4341 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4342 << Ptr->getType() << Ptr->getSourceRange(); 4343 return ExprError(); 4344 } 4345 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4346 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4347 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4348 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4349 << Ptr->getSourceRange(); 4350 return ExprError(); 4351 } 4352 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4353 } else if (Form != Load && Form != LoadCopy) { 4354 if (ValType.isConstQualified()) { 4355 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4356 << Ptr->getType() << Ptr->getSourceRange(); 4357 return ExprError(); 4358 } 4359 } 4360 4361 // For an arithmetic operation, the implied arithmetic must be well-formed. 4362 if (Form == Arithmetic) { 4363 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4364 if (IsAddSub && !ValType->isIntegerType() 4365 && !ValType->isPointerType()) { 4366 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4367 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4368 return ExprError(); 4369 } 4370 if (!IsAddSub && !ValType->isIntegerType()) { 4371 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4372 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4373 return ExprError(); 4374 } 4375 if (IsC11 && ValType->isPointerType() && 4376 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4377 diag::err_incomplete_type)) { 4378 return ExprError(); 4379 } 4380 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4381 // For __atomic_*_n operations, the value type must be a scalar integral or 4382 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4383 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4384 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4385 return ExprError(); 4386 } 4387 4388 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4389 !AtomTy->isScalarType()) { 4390 // For GNU atomics, require a trivially-copyable type. This is not part of 4391 // the GNU atomics specification, but we enforce it for sanity. 4392 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4393 << Ptr->getType() << Ptr->getSourceRange(); 4394 return ExprError(); 4395 } 4396 4397 switch (ValType.getObjCLifetime()) { 4398 case Qualifiers::OCL_None: 4399 case Qualifiers::OCL_ExplicitNone: 4400 // okay 4401 break; 4402 4403 case Qualifiers::OCL_Weak: 4404 case Qualifiers::OCL_Strong: 4405 case Qualifiers::OCL_Autoreleasing: 4406 // FIXME: Can this happen? By this point, ValType should be known 4407 // to be trivially copyable. 4408 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4409 << ValType << Ptr->getSourceRange(); 4410 return ExprError(); 4411 } 4412 4413 // All atomic operations have an overload which takes a pointer to a volatile 4414 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4415 // into the result or the other operands. Similarly atomic_load takes a 4416 // pointer to a const 'A'. 4417 ValType.removeLocalVolatile(); 4418 ValType.removeLocalConst(); 4419 QualType ResultType = ValType; 4420 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4421 Form == Init) 4422 ResultType = Context.VoidTy; 4423 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4424 ResultType = Context.BoolTy; 4425 4426 // The type of a parameter passed 'by value'. In the GNU atomics, such 4427 // arguments are actually passed as pointers. 4428 QualType ByValType = ValType; // 'CP' 4429 bool IsPassedByAddress = false; 4430 if (!IsC11 && !IsN) { 4431 ByValType = Ptr->getType(); 4432 IsPassedByAddress = true; 4433 } 4434 4435 SmallVector<Expr *, 5> APIOrderedArgs; 4436 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4437 APIOrderedArgs.push_back(Args[0]); 4438 switch (Form) { 4439 case Init: 4440 case Load: 4441 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4442 break; 4443 case LoadCopy: 4444 case Copy: 4445 case Arithmetic: 4446 case Xchg: 4447 APIOrderedArgs.push_back(Args[2]); // Val1 4448 APIOrderedArgs.push_back(Args[1]); // Order 4449 break; 4450 case GNUXchg: 4451 APIOrderedArgs.push_back(Args[2]); // Val1 4452 APIOrderedArgs.push_back(Args[3]); // Val2 4453 APIOrderedArgs.push_back(Args[1]); // Order 4454 break; 4455 case C11CmpXchg: 4456 APIOrderedArgs.push_back(Args[2]); // Val1 4457 APIOrderedArgs.push_back(Args[4]); // Val2 4458 APIOrderedArgs.push_back(Args[1]); // Order 4459 APIOrderedArgs.push_back(Args[3]); // OrderFail 4460 break; 4461 case GNUCmpXchg: 4462 APIOrderedArgs.push_back(Args[2]); // Val1 4463 APIOrderedArgs.push_back(Args[4]); // Val2 4464 APIOrderedArgs.push_back(Args[5]); // Weak 4465 APIOrderedArgs.push_back(Args[1]); // Order 4466 APIOrderedArgs.push_back(Args[3]); // OrderFail 4467 break; 4468 } 4469 } else 4470 APIOrderedArgs.append(Args.begin(), Args.end()); 4471 4472 // The first argument's non-CV pointer type is used to deduce the type of 4473 // subsequent arguments, except for: 4474 // - weak flag (always converted to bool) 4475 // - memory order (always converted to int) 4476 // - scope (always converted to int) 4477 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4478 QualType Ty; 4479 if (i < NumVals[Form] + 1) { 4480 switch (i) { 4481 case 0: 4482 // The first argument is always a pointer. It has a fixed type. 4483 // It is always dereferenced, a nullptr is undefined. 4484 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4485 // Nothing else to do: we already know all we want about this pointer. 4486 continue; 4487 case 1: 4488 // The second argument is the non-atomic operand. For arithmetic, this 4489 // is always passed by value, and for a compare_exchange it is always 4490 // passed by address. For the rest, GNU uses by-address and C11 uses 4491 // by-value. 4492 assert(Form != Load); 4493 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4494 Ty = ValType; 4495 else if (Form == Copy || Form == Xchg) { 4496 if (IsPassedByAddress) { 4497 // The value pointer is always dereferenced, a nullptr is undefined. 4498 CheckNonNullArgument(*this, APIOrderedArgs[i], 4499 ExprRange.getBegin()); 4500 } 4501 Ty = ByValType; 4502 } else if (Form == Arithmetic) 4503 Ty = Context.getPointerDiffType(); 4504 else { 4505 Expr *ValArg = APIOrderedArgs[i]; 4506 // The value pointer is always dereferenced, a nullptr is undefined. 4507 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4508 LangAS AS = LangAS::Default; 4509 // Keep address space of non-atomic pointer type. 4510 if (const PointerType *PtrTy = 4511 ValArg->getType()->getAs<PointerType>()) { 4512 AS = PtrTy->getPointeeType().getAddressSpace(); 4513 } 4514 Ty = Context.getPointerType( 4515 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4516 } 4517 break; 4518 case 2: 4519 // The third argument to compare_exchange / GNU exchange is the desired 4520 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4521 if (IsPassedByAddress) 4522 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4523 Ty = ByValType; 4524 break; 4525 case 3: 4526 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4527 Ty = Context.BoolTy; 4528 break; 4529 } 4530 } else { 4531 // The order(s) and scope are always converted to int. 4532 Ty = Context.IntTy; 4533 } 4534 4535 InitializedEntity Entity = 4536 InitializedEntity::InitializeParameter(Context, Ty, false); 4537 ExprResult Arg = APIOrderedArgs[i]; 4538 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4539 if (Arg.isInvalid()) 4540 return true; 4541 APIOrderedArgs[i] = Arg.get(); 4542 } 4543 4544 // Permute the arguments into a 'consistent' order. 4545 SmallVector<Expr*, 5> SubExprs; 4546 SubExprs.push_back(Ptr); 4547 switch (Form) { 4548 case Init: 4549 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4550 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4551 break; 4552 case Load: 4553 SubExprs.push_back(APIOrderedArgs[1]); // Order 4554 break; 4555 case LoadCopy: 4556 case Copy: 4557 case Arithmetic: 4558 case Xchg: 4559 SubExprs.push_back(APIOrderedArgs[2]); // Order 4560 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4561 break; 4562 case GNUXchg: 4563 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4564 SubExprs.push_back(APIOrderedArgs[3]); // Order 4565 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4566 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4567 break; 4568 case C11CmpXchg: 4569 SubExprs.push_back(APIOrderedArgs[3]); // Order 4570 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4571 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 4572 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4573 break; 4574 case GNUCmpXchg: 4575 SubExprs.push_back(APIOrderedArgs[4]); // Order 4576 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4577 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 4578 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4579 SubExprs.push_back(APIOrderedArgs[3]); // Weak 4580 break; 4581 } 4582 4583 if (SubExprs.size() >= 2 && Form != Init) { 4584 llvm::APSInt Result(32); 4585 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4586 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4587 Diag(SubExprs[1]->getBeginLoc(), 4588 diag::warn_atomic_op_has_invalid_memory_order) 4589 << SubExprs[1]->getSourceRange(); 4590 } 4591 4592 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4593 auto *Scope = Args[Args.size() - 1]; 4594 llvm::APSInt Result(32); 4595 if (Scope->isIntegerConstantExpr(Result, Context) && 4596 !ScopeModel->isValid(Result.getZExtValue())) { 4597 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4598 << Scope->getSourceRange(); 4599 } 4600 SubExprs.push_back(Scope); 4601 } 4602 4603 AtomicExpr *AE = new (Context) 4604 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 4605 4606 if ((Op == AtomicExpr::AO__c11_atomic_load || 4607 Op == AtomicExpr::AO__c11_atomic_store || 4608 Op == AtomicExpr::AO__opencl_atomic_load || 4609 Op == AtomicExpr::AO__opencl_atomic_store ) && 4610 Context.AtomicUsesUnsupportedLibcall(AE)) 4611 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4612 << ((Op == AtomicExpr::AO__c11_atomic_load || 4613 Op == AtomicExpr::AO__opencl_atomic_load) 4614 ? 0 4615 : 1); 4616 4617 return AE; 4618 } 4619 4620 /// checkBuiltinArgument - Given a call to a builtin function, perform 4621 /// normal type-checking on the given argument, updating the call in 4622 /// place. This is useful when a builtin function requires custom 4623 /// type-checking for some of its arguments but not necessarily all of 4624 /// them. 4625 /// 4626 /// Returns true on error. 4627 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4628 FunctionDecl *Fn = E->getDirectCallee(); 4629 assert(Fn && "builtin call without direct callee!"); 4630 4631 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4632 InitializedEntity Entity = 4633 InitializedEntity::InitializeParameter(S.Context, Param); 4634 4635 ExprResult Arg = E->getArg(0); 4636 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4637 if (Arg.isInvalid()) 4638 return true; 4639 4640 E->setArg(ArgIndex, Arg.get()); 4641 return false; 4642 } 4643 4644 /// We have a call to a function like __sync_fetch_and_add, which is an 4645 /// overloaded function based on the pointer type of its first argument. 4646 /// The main BuildCallExpr routines have already promoted the types of 4647 /// arguments because all of these calls are prototyped as void(...). 4648 /// 4649 /// This function goes through and does final semantic checking for these 4650 /// builtins, as well as generating any warnings. 4651 ExprResult 4652 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4653 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4654 Expr *Callee = TheCall->getCallee(); 4655 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4656 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4657 4658 // Ensure that we have at least one argument to do type inference from. 4659 if (TheCall->getNumArgs() < 1) { 4660 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4661 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4662 return ExprError(); 4663 } 4664 4665 // Inspect the first argument of the atomic builtin. This should always be 4666 // a pointer type, whose element is an integral scalar or pointer type. 4667 // Because it is a pointer type, we don't have to worry about any implicit 4668 // casts here. 4669 // FIXME: We don't allow floating point scalars as input. 4670 Expr *FirstArg = TheCall->getArg(0); 4671 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4672 if (FirstArgResult.isInvalid()) 4673 return ExprError(); 4674 FirstArg = FirstArgResult.get(); 4675 TheCall->setArg(0, FirstArg); 4676 4677 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4678 if (!pointerType) { 4679 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4680 << FirstArg->getType() << FirstArg->getSourceRange(); 4681 return ExprError(); 4682 } 4683 4684 QualType ValType = pointerType->getPointeeType(); 4685 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4686 !ValType->isBlockPointerType()) { 4687 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4688 << FirstArg->getType() << FirstArg->getSourceRange(); 4689 return ExprError(); 4690 } 4691 4692 if (ValType.isConstQualified()) { 4693 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4694 << FirstArg->getType() << FirstArg->getSourceRange(); 4695 return ExprError(); 4696 } 4697 4698 switch (ValType.getObjCLifetime()) { 4699 case Qualifiers::OCL_None: 4700 case Qualifiers::OCL_ExplicitNone: 4701 // okay 4702 break; 4703 4704 case Qualifiers::OCL_Weak: 4705 case Qualifiers::OCL_Strong: 4706 case Qualifiers::OCL_Autoreleasing: 4707 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4708 << ValType << FirstArg->getSourceRange(); 4709 return ExprError(); 4710 } 4711 4712 // Strip any qualifiers off ValType. 4713 ValType = ValType.getUnqualifiedType(); 4714 4715 // The majority of builtins return a value, but a few have special return 4716 // types, so allow them to override appropriately below. 4717 QualType ResultType = ValType; 4718 4719 // We need to figure out which concrete builtin this maps onto. For example, 4720 // __sync_fetch_and_add with a 2 byte object turns into 4721 // __sync_fetch_and_add_2. 4722 #define BUILTIN_ROW(x) \ 4723 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4724 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4725 4726 static const unsigned BuiltinIndices[][5] = { 4727 BUILTIN_ROW(__sync_fetch_and_add), 4728 BUILTIN_ROW(__sync_fetch_and_sub), 4729 BUILTIN_ROW(__sync_fetch_and_or), 4730 BUILTIN_ROW(__sync_fetch_and_and), 4731 BUILTIN_ROW(__sync_fetch_and_xor), 4732 BUILTIN_ROW(__sync_fetch_and_nand), 4733 4734 BUILTIN_ROW(__sync_add_and_fetch), 4735 BUILTIN_ROW(__sync_sub_and_fetch), 4736 BUILTIN_ROW(__sync_and_and_fetch), 4737 BUILTIN_ROW(__sync_or_and_fetch), 4738 BUILTIN_ROW(__sync_xor_and_fetch), 4739 BUILTIN_ROW(__sync_nand_and_fetch), 4740 4741 BUILTIN_ROW(__sync_val_compare_and_swap), 4742 BUILTIN_ROW(__sync_bool_compare_and_swap), 4743 BUILTIN_ROW(__sync_lock_test_and_set), 4744 BUILTIN_ROW(__sync_lock_release), 4745 BUILTIN_ROW(__sync_swap) 4746 }; 4747 #undef BUILTIN_ROW 4748 4749 // Determine the index of the size. 4750 unsigned SizeIndex; 4751 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4752 case 1: SizeIndex = 0; break; 4753 case 2: SizeIndex = 1; break; 4754 case 4: SizeIndex = 2; break; 4755 case 8: SizeIndex = 3; break; 4756 case 16: SizeIndex = 4; break; 4757 default: 4758 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4759 << FirstArg->getType() << FirstArg->getSourceRange(); 4760 return ExprError(); 4761 } 4762 4763 // Each of these builtins has one pointer argument, followed by some number of 4764 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4765 // that we ignore. Find out which row of BuiltinIndices to read from as well 4766 // as the number of fixed args. 4767 unsigned BuiltinID = FDecl->getBuiltinID(); 4768 unsigned BuiltinIndex, NumFixed = 1; 4769 bool WarnAboutSemanticsChange = false; 4770 switch (BuiltinID) { 4771 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4772 case Builtin::BI__sync_fetch_and_add: 4773 case Builtin::BI__sync_fetch_and_add_1: 4774 case Builtin::BI__sync_fetch_and_add_2: 4775 case Builtin::BI__sync_fetch_and_add_4: 4776 case Builtin::BI__sync_fetch_and_add_8: 4777 case Builtin::BI__sync_fetch_and_add_16: 4778 BuiltinIndex = 0; 4779 break; 4780 4781 case Builtin::BI__sync_fetch_and_sub: 4782 case Builtin::BI__sync_fetch_and_sub_1: 4783 case Builtin::BI__sync_fetch_and_sub_2: 4784 case Builtin::BI__sync_fetch_and_sub_4: 4785 case Builtin::BI__sync_fetch_and_sub_8: 4786 case Builtin::BI__sync_fetch_and_sub_16: 4787 BuiltinIndex = 1; 4788 break; 4789 4790 case Builtin::BI__sync_fetch_and_or: 4791 case Builtin::BI__sync_fetch_and_or_1: 4792 case Builtin::BI__sync_fetch_and_or_2: 4793 case Builtin::BI__sync_fetch_and_or_4: 4794 case Builtin::BI__sync_fetch_and_or_8: 4795 case Builtin::BI__sync_fetch_and_or_16: 4796 BuiltinIndex = 2; 4797 break; 4798 4799 case Builtin::BI__sync_fetch_and_and: 4800 case Builtin::BI__sync_fetch_and_and_1: 4801 case Builtin::BI__sync_fetch_and_and_2: 4802 case Builtin::BI__sync_fetch_and_and_4: 4803 case Builtin::BI__sync_fetch_and_and_8: 4804 case Builtin::BI__sync_fetch_and_and_16: 4805 BuiltinIndex = 3; 4806 break; 4807 4808 case Builtin::BI__sync_fetch_and_xor: 4809 case Builtin::BI__sync_fetch_and_xor_1: 4810 case Builtin::BI__sync_fetch_and_xor_2: 4811 case Builtin::BI__sync_fetch_and_xor_4: 4812 case Builtin::BI__sync_fetch_and_xor_8: 4813 case Builtin::BI__sync_fetch_and_xor_16: 4814 BuiltinIndex = 4; 4815 break; 4816 4817 case Builtin::BI__sync_fetch_and_nand: 4818 case Builtin::BI__sync_fetch_and_nand_1: 4819 case Builtin::BI__sync_fetch_and_nand_2: 4820 case Builtin::BI__sync_fetch_and_nand_4: 4821 case Builtin::BI__sync_fetch_and_nand_8: 4822 case Builtin::BI__sync_fetch_and_nand_16: 4823 BuiltinIndex = 5; 4824 WarnAboutSemanticsChange = true; 4825 break; 4826 4827 case Builtin::BI__sync_add_and_fetch: 4828 case Builtin::BI__sync_add_and_fetch_1: 4829 case Builtin::BI__sync_add_and_fetch_2: 4830 case Builtin::BI__sync_add_and_fetch_4: 4831 case Builtin::BI__sync_add_and_fetch_8: 4832 case Builtin::BI__sync_add_and_fetch_16: 4833 BuiltinIndex = 6; 4834 break; 4835 4836 case Builtin::BI__sync_sub_and_fetch: 4837 case Builtin::BI__sync_sub_and_fetch_1: 4838 case Builtin::BI__sync_sub_and_fetch_2: 4839 case Builtin::BI__sync_sub_and_fetch_4: 4840 case Builtin::BI__sync_sub_and_fetch_8: 4841 case Builtin::BI__sync_sub_and_fetch_16: 4842 BuiltinIndex = 7; 4843 break; 4844 4845 case Builtin::BI__sync_and_and_fetch: 4846 case Builtin::BI__sync_and_and_fetch_1: 4847 case Builtin::BI__sync_and_and_fetch_2: 4848 case Builtin::BI__sync_and_and_fetch_4: 4849 case Builtin::BI__sync_and_and_fetch_8: 4850 case Builtin::BI__sync_and_and_fetch_16: 4851 BuiltinIndex = 8; 4852 break; 4853 4854 case Builtin::BI__sync_or_and_fetch: 4855 case Builtin::BI__sync_or_and_fetch_1: 4856 case Builtin::BI__sync_or_and_fetch_2: 4857 case Builtin::BI__sync_or_and_fetch_4: 4858 case Builtin::BI__sync_or_and_fetch_8: 4859 case Builtin::BI__sync_or_and_fetch_16: 4860 BuiltinIndex = 9; 4861 break; 4862 4863 case Builtin::BI__sync_xor_and_fetch: 4864 case Builtin::BI__sync_xor_and_fetch_1: 4865 case Builtin::BI__sync_xor_and_fetch_2: 4866 case Builtin::BI__sync_xor_and_fetch_4: 4867 case Builtin::BI__sync_xor_and_fetch_8: 4868 case Builtin::BI__sync_xor_and_fetch_16: 4869 BuiltinIndex = 10; 4870 break; 4871 4872 case Builtin::BI__sync_nand_and_fetch: 4873 case Builtin::BI__sync_nand_and_fetch_1: 4874 case Builtin::BI__sync_nand_and_fetch_2: 4875 case Builtin::BI__sync_nand_and_fetch_4: 4876 case Builtin::BI__sync_nand_and_fetch_8: 4877 case Builtin::BI__sync_nand_and_fetch_16: 4878 BuiltinIndex = 11; 4879 WarnAboutSemanticsChange = true; 4880 break; 4881 4882 case Builtin::BI__sync_val_compare_and_swap: 4883 case Builtin::BI__sync_val_compare_and_swap_1: 4884 case Builtin::BI__sync_val_compare_and_swap_2: 4885 case Builtin::BI__sync_val_compare_and_swap_4: 4886 case Builtin::BI__sync_val_compare_and_swap_8: 4887 case Builtin::BI__sync_val_compare_and_swap_16: 4888 BuiltinIndex = 12; 4889 NumFixed = 2; 4890 break; 4891 4892 case Builtin::BI__sync_bool_compare_and_swap: 4893 case Builtin::BI__sync_bool_compare_and_swap_1: 4894 case Builtin::BI__sync_bool_compare_and_swap_2: 4895 case Builtin::BI__sync_bool_compare_and_swap_4: 4896 case Builtin::BI__sync_bool_compare_and_swap_8: 4897 case Builtin::BI__sync_bool_compare_and_swap_16: 4898 BuiltinIndex = 13; 4899 NumFixed = 2; 4900 ResultType = Context.BoolTy; 4901 break; 4902 4903 case Builtin::BI__sync_lock_test_and_set: 4904 case Builtin::BI__sync_lock_test_and_set_1: 4905 case Builtin::BI__sync_lock_test_and_set_2: 4906 case Builtin::BI__sync_lock_test_and_set_4: 4907 case Builtin::BI__sync_lock_test_and_set_8: 4908 case Builtin::BI__sync_lock_test_and_set_16: 4909 BuiltinIndex = 14; 4910 break; 4911 4912 case Builtin::BI__sync_lock_release: 4913 case Builtin::BI__sync_lock_release_1: 4914 case Builtin::BI__sync_lock_release_2: 4915 case Builtin::BI__sync_lock_release_4: 4916 case Builtin::BI__sync_lock_release_8: 4917 case Builtin::BI__sync_lock_release_16: 4918 BuiltinIndex = 15; 4919 NumFixed = 0; 4920 ResultType = Context.VoidTy; 4921 break; 4922 4923 case Builtin::BI__sync_swap: 4924 case Builtin::BI__sync_swap_1: 4925 case Builtin::BI__sync_swap_2: 4926 case Builtin::BI__sync_swap_4: 4927 case Builtin::BI__sync_swap_8: 4928 case Builtin::BI__sync_swap_16: 4929 BuiltinIndex = 16; 4930 break; 4931 } 4932 4933 // Now that we know how many fixed arguments we expect, first check that we 4934 // have at least that many. 4935 if (TheCall->getNumArgs() < 1+NumFixed) { 4936 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4937 << 0 << 1 + NumFixed << TheCall->getNumArgs() 4938 << Callee->getSourceRange(); 4939 return ExprError(); 4940 } 4941 4942 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 4943 << Callee->getSourceRange(); 4944 4945 if (WarnAboutSemanticsChange) { 4946 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 4947 << Callee->getSourceRange(); 4948 } 4949 4950 // Get the decl for the concrete builtin from this, we can tell what the 4951 // concrete integer type we should convert to is. 4952 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 4953 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 4954 FunctionDecl *NewBuiltinDecl; 4955 if (NewBuiltinID == BuiltinID) 4956 NewBuiltinDecl = FDecl; 4957 else { 4958 // Perform builtin lookup to avoid redeclaring it. 4959 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 4960 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 4961 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 4962 assert(Res.getFoundDecl()); 4963 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 4964 if (!NewBuiltinDecl) 4965 return ExprError(); 4966 } 4967 4968 // The first argument --- the pointer --- has a fixed type; we 4969 // deduce the types of the rest of the arguments accordingly. Walk 4970 // the remaining arguments, converting them to the deduced value type. 4971 for (unsigned i = 0; i != NumFixed; ++i) { 4972 ExprResult Arg = TheCall->getArg(i+1); 4973 4974 // GCC does an implicit conversion to the pointer or integer ValType. This 4975 // can fail in some cases (1i -> int**), check for this error case now. 4976 // Initialize the argument. 4977 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 4978 ValType, /*consume*/ false); 4979 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4980 if (Arg.isInvalid()) 4981 return ExprError(); 4982 4983 // Okay, we have something that *can* be converted to the right type. Check 4984 // to see if there is a potentially weird extension going on here. This can 4985 // happen when you do an atomic operation on something like an char* and 4986 // pass in 42. The 42 gets converted to char. This is even more strange 4987 // for things like 45.123 -> char, etc. 4988 // FIXME: Do this check. 4989 TheCall->setArg(i+1, Arg.get()); 4990 } 4991 4992 // Create a new DeclRefExpr to refer to the new decl. 4993 DeclRefExpr *NewDRE = DeclRefExpr::Create( 4994 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 4995 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 4996 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 4997 4998 // Set the callee in the CallExpr. 4999 // FIXME: This loses syntactic information. 5000 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5001 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5002 CK_BuiltinFnToFnPtr); 5003 TheCall->setCallee(PromotedCall.get()); 5004 5005 // Change the result type of the call to match the original value type. This 5006 // is arbitrary, but the codegen for these builtins ins design to handle it 5007 // gracefully. 5008 TheCall->setType(ResultType); 5009 5010 return TheCallResult; 5011 } 5012 5013 /// SemaBuiltinNontemporalOverloaded - We have a call to 5014 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5015 /// overloaded function based on the pointer type of its last argument. 5016 /// 5017 /// This function goes through and does final semantic checking for these 5018 /// builtins. 5019 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5020 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5021 DeclRefExpr *DRE = 5022 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5023 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5024 unsigned BuiltinID = FDecl->getBuiltinID(); 5025 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5026 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5027 "Unexpected nontemporal load/store builtin!"); 5028 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5029 unsigned numArgs = isStore ? 2 : 1; 5030 5031 // Ensure that we have the proper number of arguments. 5032 if (checkArgCount(*this, TheCall, numArgs)) 5033 return ExprError(); 5034 5035 // Inspect the last argument of the nontemporal builtin. This should always 5036 // be a pointer type, from which we imply the type of the memory access. 5037 // Because it is a pointer type, we don't have to worry about any implicit 5038 // casts here. 5039 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5040 ExprResult PointerArgResult = 5041 DefaultFunctionArrayLvalueConversion(PointerArg); 5042 5043 if (PointerArgResult.isInvalid()) 5044 return ExprError(); 5045 PointerArg = PointerArgResult.get(); 5046 TheCall->setArg(numArgs - 1, PointerArg); 5047 5048 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5049 if (!pointerType) { 5050 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5051 << PointerArg->getType() << PointerArg->getSourceRange(); 5052 return ExprError(); 5053 } 5054 5055 QualType ValType = pointerType->getPointeeType(); 5056 5057 // Strip any qualifiers off ValType. 5058 ValType = ValType.getUnqualifiedType(); 5059 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5060 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5061 !ValType->isVectorType()) { 5062 Diag(DRE->getBeginLoc(), 5063 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5064 << PointerArg->getType() << PointerArg->getSourceRange(); 5065 return ExprError(); 5066 } 5067 5068 if (!isStore) { 5069 TheCall->setType(ValType); 5070 return TheCallResult; 5071 } 5072 5073 ExprResult ValArg = TheCall->getArg(0); 5074 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5075 Context, ValType, /*consume*/ false); 5076 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5077 if (ValArg.isInvalid()) 5078 return ExprError(); 5079 5080 TheCall->setArg(0, ValArg.get()); 5081 TheCall->setType(Context.VoidTy); 5082 return TheCallResult; 5083 } 5084 5085 /// CheckObjCString - Checks that the argument to the builtin 5086 /// CFString constructor is correct 5087 /// Note: It might also make sense to do the UTF-16 conversion here (would 5088 /// simplify the backend). 5089 bool Sema::CheckObjCString(Expr *Arg) { 5090 Arg = Arg->IgnoreParenCasts(); 5091 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5092 5093 if (!Literal || !Literal->isAscii()) { 5094 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5095 << Arg->getSourceRange(); 5096 return true; 5097 } 5098 5099 if (Literal->containsNonAsciiOrNull()) { 5100 StringRef String = Literal->getString(); 5101 unsigned NumBytes = String.size(); 5102 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5103 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5104 llvm::UTF16 *ToPtr = &ToBuf[0]; 5105 5106 llvm::ConversionResult Result = 5107 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5108 ToPtr + NumBytes, llvm::strictConversion); 5109 // Check for conversion failure. 5110 if (Result != llvm::conversionOK) 5111 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5112 << Arg->getSourceRange(); 5113 } 5114 return false; 5115 } 5116 5117 /// CheckObjCString - Checks that the format string argument to the os_log() 5118 /// and os_trace() functions is correct, and converts it to const char *. 5119 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5120 Arg = Arg->IgnoreParenCasts(); 5121 auto *Literal = dyn_cast<StringLiteral>(Arg); 5122 if (!Literal) { 5123 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5124 Literal = ObjcLiteral->getString(); 5125 } 5126 } 5127 5128 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5129 return ExprError( 5130 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5131 << Arg->getSourceRange()); 5132 } 5133 5134 ExprResult Result(Literal); 5135 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5136 InitializedEntity Entity = 5137 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5138 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5139 return Result; 5140 } 5141 5142 /// Check that the user is calling the appropriate va_start builtin for the 5143 /// target and calling convention. 5144 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5145 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5146 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5147 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5148 TT.getArch() == llvm::Triple::aarch64_32); 5149 bool IsWindows = TT.isOSWindows(); 5150 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5151 if (IsX64 || IsAArch64) { 5152 CallingConv CC = CC_C; 5153 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5154 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5155 if (IsMSVAStart) { 5156 // Don't allow this in System V ABI functions. 5157 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5158 return S.Diag(Fn->getBeginLoc(), 5159 diag::err_ms_va_start_used_in_sysv_function); 5160 } else { 5161 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5162 // On x64 Windows, don't allow this in System V ABI functions. 5163 // (Yes, that means there's no corresponding way to support variadic 5164 // System V ABI functions on Windows.) 5165 if ((IsWindows && CC == CC_X86_64SysV) || 5166 (!IsWindows && CC == CC_Win64)) 5167 return S.Diag(Fn->getBeginLoc(), 5168 diag::err_va_start_used_in_wrong_abi_function) 5169 << !IsWindows; 5170 } 5171 return false; 5172 } 5173 5174 if (IsMSVAStart) 5175 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5176 return false; 5177 } 5178 5179 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5180 ParmVarDecl **LastParam = nullptr) { 5181 // Determine whether the current function, block, or obj-c method is variadic 5182 // and get its parameter list. 5183 bool IsVariadic = false; 5184 ArrayRef<ParmVarDecl *> Params; 5185 DeclContext *Caller = S.CurContext; 5186 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5187 IsVariadic = Block->isVariadic(); 5188 Params = Block->parameters(); 5189 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5190 IsVariadic = FD->isVariadic(); 5191 Params = FD->parameters(); 5192 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5193 IsVariadic = MD->isVariadic(); 5194 // FIXME: This isn't correct for methods (results in bogus warning). 5195 Params = MD->parameters(); 5196 } else if (isa<CapturedDecl>(Caller)) { 5197 // We don't support va_start in a CapturedDecl. 5198 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5199 return true; 5200 } else { 5201 // This must be some other declcontext that parses exprs. 5202 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5203 return true; 5204 } 5205 5206 if (!IsVariadic) { 5207 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5208 return true; 5209 } 5210 5211 if (LastParam) 5212 *LastParam = Params.empty() ? nullptr : Params.back(); 5213 5214 return false; 5215 } 5216 5217 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5218 /// for validity. Emit an error and return true on failure; return false 5219 /// on success. 5220 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5221 Expr *Fn = TheCall->getCallee(); 5222 5223 if (checkVAStartABI(*this, BuiltinID, Fn)) 5224 return true; 5225 5226 if (TheCall->getNumArgs() > 2) { 5227 Diag(TheCall->getArg(2)->getBeginLoc(), 5228 diag::err_typecheck_call_too_many_args) 5229 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5230 << Fn->getSourceRange() 5231 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5232 (*(TheCall->arg_end() - 1))->getEndLoc()); 5233 return true; 5234 } 5235 5236 if (TheCall->getNumArgs() < 2) { 5237 return Diag(TheCall->getEndLoc(), 5238 diag::err_typecheck_call_too_few_args_at_least) 5239 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5240 } 5241 5242 // Type-check the first argument normally. 5243 if (checkBuiltinArgument(*this, TheCall, 0)) 5244 return true; 5245 5246 // Check that the current function is variadic, and get its last parameter. 5247 ParmVarDecl *LastParam; 5248 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5249 return true; 5250 5251 // Verify that the second argument to the builtin is the last argument of the 5252 // current function or method. 5253 bool SecondArgIsLastNamedArgument = false; 5254 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5255 5256 // These are valid if SecondArgIsLastNamedArgument is false after the next 5257 // block. 5258 QualType Type; 5259 SourceLocation ParamLoc; 5260 bool IsCRegister = false; 5261 5262 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5263 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5264 SecondArgIsLastNamedArgument = PV == LastParam; 5265 5266 Type = PV->getType(); 5267 ParamLoc = PV->getLocation(); 5268 IsCRegister = 5269 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5270 } 5271 } 5272 5273 if (!SecondArgIsLastNamedArgument) 5274 Diag(TheCall->getArg(1)->getBeginLoc(), 5275 diag::warn_second_arg_of_va_start_not_last_named_param); 5276 else if (IsCRegister || Type->isReferenceType() || 5277 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5278 // Promotable integers are UB, but enumerations need a bit of 5279 // extra checking to see what their promotable type actually is. 5280 if (!Type->isPromotableIntegerType()) 5281 return false; 5282 if (!Type->isEnumeralType()) 5283 return true; 5284 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5285 return !(ED && 5286 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5287 }()) { 5288 unsigned Reason = 0; 5289 if (Type->isReferenceType()) Reason = 1; 5290 else if (IsCRegister) Reason = 2; 5291 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5292 Diag(ParamLoc, diag::note_parameter_type) << Type; 5293 } 5294 5295 TheCall->setType(Context.VoidTy); 5296 return false; 5297 } 5298 5299 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5300 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5301 // const char *named_addr); 5302 5303 Expr *Func = Call->getCallee(); 5304 5305 if (Call->getNumArgs() < 3) 5306 return Diag(Call->getEndLoc(), 5307 diag::err_typecheck_call_too_few_args_at_least) 5308 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5309 5310 // Type-check the first argument normally. 5311 if (checkBuiltinArgument(*this, Call, 0)) 5312 return true; 5313 5314 // Check that the current function is variadic. 5315 if (checkVAStartIsInVariadicFunction(*this, Func)) 5316 return true; 5317 5318 // __va_start on Windows does not validate the parameter qualifiers 5319 5320 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5321 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5322 5323 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5324 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5325 5326 const QualType &ConstCharPtrTy = 5327 Context.getPointerType(Context.CharTy.withConst()); 5328 if (!Arg1Ty->isPointerType() || 5329 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5330 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5331 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5332 << 0 /* qualifier difference */ 5333 << 3 /* parameter mismatch */ 5334 << 2 << Arg1->getType() << ConstCharPtrTy; 5335 5336 const QualType SizeTy = Context.getSizeType(); 5337 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5338 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5339 << Arg2->getType() << SizeTy << 1 /* different class */ 5340 << 0 /* qualifier difference */ 5341 << 3 /* parameter mismatch */ 5342 << 3 << Arg2->getType() << SizeTy; 5343 5344 return false; 5345 } 5346 5347 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5348 /// friends. This is declared to take (...), so we have to check everything. 5349 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5350 if (TheCall->getNumArgs() < 2) 5351 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5352 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5353 if (TheCall->getNumArgs() > 2) 5354 return Diag(TheCall->getArg(2)->getBeginLoc(), 5355 diag::err_typecheck_call_too_many_args) 5356 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5357 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5358 (*(TheCall->arg_end() - 1))->getEndLoc()); 5359 5360 ExprResult OrigArg0 = TheCall->getArg(0); 5361 ExprResult OrigArg1 = TheCall->getArg(1); 5362 5363 // Do standard promotions between the two arguments, returning their common 5364 // type. 5365 QualType Res = UsualArithmeticConversions( 5366 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5367 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5368 return true; 5369 5370 // Make sure any conversions are pushed back into the call; this is 5371 // type safe since unordered compare builtins are declared as "_Bool 5372 // foo(...)". 5373 TheCall->setArg(0, OrigArg0.get()); 5374 TheCall->setArg(1, OrigArg1.get()); 5375 5376 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5377 return false; 5378 5379 // If the common type isn't a real floating type, then the arguments were 5380 // invalid for this operation. 5381 if (Res.isNull() || !Res->isRealFloatingType()) 5382 return Diag(OrigArg0.get()->getBeginLoc(), 5383 diag::err_typecheck_call_invalid_ordered_compare) 5384 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5385 << SourceRange(OrigArg0.get()->getBeginLoc(), 5386 OrigArg1.get()->getEndLoc()); 5387 5388 return false; 5389 } 5390 5391 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5392 /// __builtin_isnan and friends. This is declared to take (...), so we have 5393 /// to check everything. We expect the last argument to be a floating point 5394 /// value. 5395 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5396 if (TheCall->getNumArgs() < NumArgs) 5397 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5398 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5399 if (TheCall->getNumArgs() > NumArgs) 5400 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5401 diag::err_typecheck_call_too_many_args) 5402 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5403 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5404 (*(TheCall->arg_end() - 1))->getEndLoc()); 5405 5406 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5407 // on all preceding parameters just being int. Try all of those. 5408 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5409 Expr *Arg = TheCall->getArg(i); 5410 5411 if (Arg->isTypeDependent()) 5412 return false; 5413 5414 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5415 5416 if (Res.isInvalid()) 5417 return true; 5418 TheCall->setArg(i, Res.get()); 5419 } 5420 5421 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5422 5423 if (OrigArg->isTypeDependent()) 5424 return false; 5425 5426 // Usual Unary Conversions will convert half to float, which we want for 5427 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5428 // type how it is, but do normal L->Rvalue conversions. 5429 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5430 OrigArg = UsualUnaryConversions(OrigArg).get(); 5431 else 5432 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5433 TheCall->setArg(NumArgs - 1, OrigArg); 5434 5435 // This operation requires a non-_Complex floating-point number. 5436 if (!OrigArg->getType()->isRealFloatingType()) 5437 return Diag(OrigArg->getBeginLoc(), 5438 diag::err_typecheck_call_invalid_unary_fp) 5439 << OrigArg->getType() << OrigArg->getSourceRange(); 5440 5441 return false; 5442 } 5443 5444 // Customized Sema Checking for VSX builtins that have the following signature: 5445 // vector [...] builtinName(vector [...], vector [...], const int); 5446 // Which takes the same type of vectors (any legal vector type) for the first 5447 // two arguments and takes compile time constant for the third argument. 5448 // Example builtins are : 5449 // vector double vec_xxpermdi(vector double, vector double, int); 5450 // vector short vec_xxsldwi(vector short, vector short, int); 5451 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5452 unsigned ExpectedNumArgs = 3; 5453 if (TheCall->getNumArgs() < ExpectedNumArgs) 5454 return Diag(TheCall->getEndLoc(), 5455 diag::err_typecheck_call_too_few_args_at_least) 5456 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5457 << TheCall->getSourceRange(); 5458 5459 if (TheCall->getNumArgs() > ExpectedNumArgs) 5460 return Diag(TheCall->getEndLoc(), 5461 diag::err_typecheck_call_too_many_args_at_most) 5462 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5463 << TheCall->getSourceRange(); 5464 5465 // Check the third argument is a compile time constant 5466 llvm::APSInt Value; 5467 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5468 return Diag(TheCall->getBeginLoc(), 5469 diag::err_vsx_builtin_nonconstant_argument) 5470 << 3 /* argument index */ << TheCall->getDirectCallee() 5471 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5472 TheCall->getArg(2)->getEndLoc()); 5473 5474 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5475 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5476 5477 // Check the type of argument 1 and argument 2 are vectors. 5478 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5479 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5480 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5481 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5482 << TheCall->getDirectCallee() 5483 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5484 TheCall->getArg(1)->getEndLoc()); 5485 } 5486 5487 // Check the first two arguments are the same type. 5488 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5489 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5490 << TheCall->getDirectCallee() 5491 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5492 TheCall->getArg(1)->getEndLoc()); 5493 } 5494 5495 // When default clang type checking is turned off and the customized type 5496 // checking is used, the returning type of the function must be explicitly 5497 // set. Otherwise it is _Bool by default. 5498 TheCall->setType(Arg1Ty); 5499 5500 return false; 5501 } 5502 5503 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5504 // This is declared to take (...), so we have to check everything. 5505 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5506 if (TheCall->getNumArgs() < 2) 5507 return ExprError(Diag(TheCall->getEndLoc(), 5508 diag::err_typecheck_call_too_few_args_at_least) 5509 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5510 << TheCall->getSourceRange()); 5511 5512 // Determine which of the following types of shufflevector we're checking: 5513 // 1) unary, vector mask: (lhs, mask) 5514 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5515 QualType resType = TheCall->getArg(0)->getType(); 5516 unsigned numElements = 0; 5517 5518 if (!TheCall->getArg(0)->isTypeDependent() && 5519 !TheCall->getArg(1)->isTypeDependent()) { 5520 QualType LHSType = TheCall->getArg(0)->getType(); 5521 QualType RHSType = TheCall->getArg(1)->getType(); 5522 5523 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5524 return ExprError( 5525 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5526 << TheCall->getDirectCallee() 5527 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5528 TheCall->getArg(1)->getEndLoc())); 5529 5530 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5531 unsigned numResElements = TheCall->getNumArgs() - 2; 5532 5533 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5534 // with mask. If so, verify that RHS is an integer vector type with the 5535 // same number of elts as lhs. 5536 if (TheCall->getNumArgs() == 2) { 5537 if (!RHSType->hasIntegerRepresentation() || 5538 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5539 return ExprError(Diag(TheCall->getBeginLoc(), 5540 diag::err_vec_builtin_incompatible_vector) 5541 << TheCall->getDirectCallee() 5542 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5543 TheCall->getArg(1)->getEndLoc())); 5544 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5545 return ExprError(Diag(TheCall->getBeginLoc(), 5546 diag::err_vec_builtin_incompatible_vector) 5547 << TheCall->getDirectCallee() 5548 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5549 TheCall->getArg(1)->getEndLoc())); 5550 } else if (numElements != numResElements) { 5551 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5552 resType = Context.getVectorType(eltType, numResElements, 5553 VectorType::GenericVector); 5554 } 5555 } 5556 5557 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5558 if (TheCall->getArg(i)->isTypeDependent() || 5559 TheCall->getArg(i)->isValueDependent()) 5560 continue; 5561 5562 llvm::APSInt Result(32); 5563 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5564 return ExprError(Diag(TheCall->getBeginLoc(), 5565 diag::err_shufflevector_nonconstant_argument) 5566 << TheCall->getArg(i)->getSourceRange()); 5567 5568 // Allow -1 which will be translated to undef in the IR. 5569 if (Result.isSigned() && Result.isAllOnesValue()) 5570 continue; 5571 5572 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5573 return ExprError(Diag(TheCall->getBeginLoc(), 5574 diag::err_shufflevector_argument_too_large) 5575 << TheCall->getArg(i)->getSourceRange()); 5576 } 5577 5578 SmallVector<Expr*, 32> exprs; 5579 5580 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5581 exprs.push_back(TheCall->getArg(i)); 5582 TheCall->setArg(i, nullptr); 5583 } 5584 5585 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5586 TheCall->getCallee()->getBeginLoc(), 5587 TheCall->getRParenLoc()); 5588 } 5589 5590 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5591 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5592 SourceLocation BuiltinLoc, 5593 SourceLocation RParenLoc) { 5594 ExprValueKind VK = VK_RValue; 5595 ExprObjectKind OK = OK_Ordinary; 5596 QualType DstTy = TInfo->getType(); 5597 QualType SrcTy = E->getType(); 5598 5599 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5600 return ExprError(Diag(BuiltinLoc, 5601 diag::err_convertvector_non_vector) 5602 << E->getSourceRange()); 5603 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5604 return ExprError(Diag(BuiltinLoc, 5605 diag::err_convertvector_non_vector_type)); 5606 5607 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5608 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 5609 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 5610 if (SrcElts != DstElts) 5611 return ExprError(Diag(BuiltinLoc, 5612 diag::err_convertvector_incompatible_vector) 5613 << E->getSourceRange()); 5614 } 5615 5616 return new (Context) 5617 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5618 } 5619 5620 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5621 // This is declared to take (const void*, ...) and can take two 5622 // optional constant int args. 5623 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5624 unsigned NumArgs = TheCall->getNumArgs(); 5625 5626 if (NumArgs > 3) 5627 return Diag(TheCall->getEndLoc(), 5628 diag::err_typecheck_call_too_many_args_at_most) 5629 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5630 5631 // Argument 0 is checked for us and the remaining arguments must be 5632 // constant integers. 5633 for (unsigned i = 1; i != NumArgs; ++i) 5634 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5635 return true; 5636 5637 return false; 5638 } 5639 5640 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5641 // __assume does not evaluate its arguments, and should warn if its argument 5642 // has side effects. 5643 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5644 Expr *Arg = TheCall->getArg(0); 5645 if (Arg->isInstantiationDependent()) return false; 5646 5647 if (Arg->HasSideEffects(Context)) 5648 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5649 << Arg->getSourceRange() 5650 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5651 5652 return false; 5653 } 5654 5655 /// Handle __builtin_alloca_with_align. This is declared 5656 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5657 /// than 8. 5658 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5659 // The alignment must be a constant integer. 5660 Expr *Arg = TheCall->getArg(1); 5661 5662 // We can't check the value of a dependent argument. 5663 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5664 if (const auto *UE = 5665 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5666 if (UE->getKind() == UETT_AlignOf || 5667 UE->getKind() == UETT_PreferredAlignOf) 5668 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5669 << Arg->getSourceRange(); 5670 5671 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5672 5673 if (!Result.isPowerOf2()) 5674 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5675 << Arg->getSourceRange(); 5676 5677 if (Result < Context.getCharWidth()) 5678 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5679 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5680 5681 if (Result > std::numeric_limits<int32_t>::max()) 5682 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5683 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5684 } 5685 5686 return false; 5687 } 5688 5689 /// Handle __builtin_assume_aligned. This is declared 5690 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5691 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5692 unsigned NumArgs = TheCall->getNumArgs(); 5693 5694 if (NumArgs > 3) 5695 return Diag(TheCall->getEndLoc(), 5696 diag::err_typecheck_call_too_many_args_at_most) 5697 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5698 5699 // The alignment must be a constant integer. 5700 Expr *Arg = TheCall->getArg(1); 5701 5702 // We can't check the value of a dependent argument. 5703 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5704 llvm::APSInt Result; 5705 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5706 return true; 5707 5708 if (!Result.isPowerOf2()) 5709 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5710 << Arg->getSourceRange(); 5711 5712 if (Result > Sema::MaximumAlignment) 5713 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 5714 << Arg->getSourceRange() << Sema::MaximumAlignment; 5715 } 5716 5717 if (NumArgs > 2) { 5718 ExprResult Arg(TheCall->getArg(2)); 5719 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5720 Context.getSizeType(), false); 5721 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5722 if (Arg.isInvalid()) return true; 5723 TheCall->setArg(2, Arg.get()); 5724 } 5725 5726 return false; 5727 } 5728 5729 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5730 unsigned BuiltinID = 5731 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5732 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5733 5734 unsigned NumArgs = TheCall->getNumArgs(); 5735 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5736 if (NumArgs < NumRequiredArgs) { 5737 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5738 << 0 /* function call */ << NumRequiredArgs << NumArgs 5739 << TheCall->getSourceRange(); 5740 } 5741 if (NumArgs >= NumRequiredArgs + 0x100) { 5742 return Diag(TheCall->getEndLoc(), 5743 diag::err_typecheck_call_too_many_args_at_most) 5744 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5745 << TheCall->getSourceRange(); 5746 } 5747 unsigned i = 0; 5748 5749 // For formatting call, check buffer arg. 5750 if (!IsSizeCall) { 5751 ExprResult Arg(TheCall->getArg(i)); 5752 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5753 Context, Context.VoidPtrTy, false); 5754 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5755 if (Arg.isInvalid()) 5756 return true; 5757 TheCall->setArg(i, Arg.get()); 5758 i++; 5759 } 5760 5761 // Check string literal arg. 5762 unsigned FormatIdx = i; 5763 { 5764 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5765 if (Arg.isInvalid()) 5766 return true; 5767 TheCall->setArg(i, Arg.get()); 5768 i++; 5769 } 5770 5771 // Make sure variadic args are scalar. 5772 unsigned FirstDataArg = i; 5773 while (i < NumArgs) { 5774 ExprResult Arg = DefaultVariadicArgumentPromotion( 5775 TheCall->getArg(i), VariadicFunction, nullptr); 5776 if (Arg.isInvalid()) 5777 return true; 5778 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 5779 if (ArgSize.getQuantity() >= 0x100) { 5780 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 5781 << i << (int)ArgSize.getQuantity() << 0xff 5782 << TheCall->getSourceRange(); 5783 } 5784 TheCall->setArg(i, Arg.get()); 5785 i++; 5786 } 5787 5788 // Check formatting specifiers. NOTE: We're only doing this for the non-size 5789 // call to avoid duplicate diagnostics. 5790 if (!IsSizeCall) { 5791 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 5792 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 5793 bool Success = CheckFormatArguments( 5794 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 5795 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 5796 CheckedVarArgs); 5797 if (!Success) 5798 return true; 5799 } 5800 5801 if (IsSizeCall) { 5802 TheCall->setType(Context.getSizeType()); 5803 } else { 5804 TheCall->setType(Context.VoidPtrTy); 5805 } 5806 return false; 5807 } 5808 5809 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 5810 /// TheCall is a constant expression. 5811 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 5812 llvm::APSInt &Result) { 5813 Expr *Arg = TheCall->getArg(ArgNum); 5814 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5815 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5816 5817 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 5818 5819 if (!Arg->isIntegerConstantExpr(Result, Context)) 5820 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 5821 << FDecl->getDeclName() << Arg->getSourceRange(); 5822 5823 return false; 5824 } 5825 5826 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 5827 /// TheCall is a constant expression in the range [Low, High]. 5828 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 5829 int Low, int High, bool RangeIsError) { 5830 if (isConstantEvaluated()) 5831 return false; 5832 llvm::APSInt Result; 5833 5834 // We can't check the value of a dependent argument. 5835 Expr *Arg = TheCall->getArg(ArgNum); 5836 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5837 return false; 5838 5839 // Check constant-ness first. 5840 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5841 return true; 5842 5843 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 5844 if (RangeIsError) 5845 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 5846 << Result.toString(10) << Low << High << Arg->getSourceRange(); 5847 else 5848 // Defer the warning until we know if the code will be emitted so that 5849 // dead code can ignore this. 5850 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 5851 PDiag(diag::warn_argument_invalid_range) 5852 << Result.toString(10) << Low << High 5853 << Arg->getSourceRange()); 5854 } 5855 5856 return false; 5857 } 5858 5859 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 5860 /// TheCall is a constant expression is a multiple of Num.. 5861 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 5862 unsigned Num) { 5863 llvm::APSInt Result; 5864 5865 // We can't check the value of a dependent argument. 5866 Expr *Arg = TheCall->getArg(ArgNum); 5867 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5868 return false; 5869 5870 // Check constant-ness first. 5871 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5872 return true; 5873 5874 if (Result.getSExtValue() % Num != 0) 5875 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 5876 << Num << Arg->getSourceRange(); 5877 5878 return false; 5879 } 5880 5881 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 5882 /// constant expression representing a power of 2. 5883 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 5884 llvm::APSInt Result; 5885 5886 // We can't check the value of a dependent argument. 5887 Expr *Arg = TheCall->getArg(ArgNum); 5888 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5889 return false; 5890 5891 // Check constant-ness first. 5892 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5893 return true; 5894 5895 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 5896 // and only if x is a power of 2. 5897 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 5898 return false; 5899 5900 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 5901 << Arg->getSourceRange(); 5902 } 5903 5904 static bool IsShiftedByte(llvm::APSInt Value) { 5905 if (Value.isNegative()) 5906 return false; 5907 5908 // Check if it's a shifted byte, by shifting it down 5909 while (true) { 5910 // If the value fits in the bottom byte, the check passes. 5911 if (Value < 0x100) 5912 return true; 5913 5914 // Otherwise, if the value has _any_ bits in the bottom byte, the check 5915 // fails. 5916 if ((Value & 0xFF) != 0) 5917 return false; 5918 5919 // If the bottom 8 bits are all 0, but something above that is nonzero, 5920 // then shifting the value right by 8 bits won't affect whether it's a 5921 // shifted byte or not. So do that, and go round again. 5922 Value >>= 8; 5923 } 5924 } 5925 5926 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 5927 /// a constant expression representing an arbitrary byte value shifted left by 5928 /// a multiple of 8 bits. 5929 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 5930 unsigned ArgBits) { 5931 llvm::APSInt Result; 5932 5933 // We can't check the value of a dependent argument. 5934 Expr *Arg = TheCall->getArg(ArgNum); 5935 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5936 return false; 5937 5938 // Check constant-ness first. 5939 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5940 return true; 5941 5942 // Truncate to the given size. 5943 Result = Result.getLoBits(ArgBits); 5944 Result.setIsUnsigned(true); 5945 5946 if (IsShiftedByte(Result)) 5947 return false; 5948 5949 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 5950 << Arg->getSourceRange(); 5951 } 5952 5953 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 5954 /// TheCall is a constant expression representing either a shifted byte value, 5955 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 5956 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 5957 /// Arm MVE intrinsics. 5958 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 5959 int ArgNum, 5960 unsigned ArgBits) { 5961 llvm::APSInt Result; 5962 5963 // We can't check the value of a dependent argument. 5964 Expr *Arg = TheCall->getArg(ArgNum); 5965 if (Arg->isTypeDependent() || Arg->isValueDependent()) 5966 return false; 5967 5968 // Check constant-ness first. 5969 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 5970 return true; 5971 5972 // Truncate to the given size. 5973 Result = Result.getLoBits(ArgBits); 5974 Result.setIsUnsigned(true); 5975 5976 // Check to see if it's in either of the required forms. 5977 if (IsShiftedByte(Result) || 5978 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 5979 return false; 5980 5981 return Diag(TheCall->getBeginLoc(), 5982 diag::err_argument_not_shifted_byte_or_xxff) 5983 << Arg->getSourceRange(); 5984 } 5985 5986 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 5987 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 5988 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 5989 if (checkArgCount(*this, TheCall, 2)) 5990 return true; 5991 Expr *Arg0 = TheCall->getArg(0); 5992 Expr *Arg1 = TheCall->getArg(1); 5993 5994 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 5995 if (FirstArg.isInvalid()) 5996 return true; 5997 QualType FirstArgType = FirstArg.get()->getType(); 5998 if (!FirstArgType->isAnyPointerType()) 5999 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6000 << "first" << FirstArgType << Arg0->getSourceRange(); 6001 TheCall->setArg(0, FirstArg.get()); 6002 6003 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6004 if (SecArg.isInvalid()) 6005 return true; 6006 QualType SecArgType = SecArg.get()->getType(); 6007 if (!SecArgType->isIntegerType()) 6008 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6009 << "second" << SecArgType << Arg1->getSourceRange(); 6010 6011 // Derive the return type from the pointer argument. 6012 TheCall->setType(FirstArgType); 6013 return false; 6014 } 6015 6016 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6017 if (checkArgCount(*this, TheCall, 2)) 6018 return true; 6019 6020 Expr *Arg0 = TheCall->getArg(0); 6021 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6022 if (FirstArg.isInvalid()) 6023 return true; 6024 QualType FirstArgType = FirstArg.get()->getType(); 6025 if (!FirstArgType->isAnyPointerType()) 6026 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6027 << "first" << FirstArgType << Arg0->getSourceRange(); 6028 TheCall->setArg(0, FirstArg.get()); 6029 6030 // Derive the return type from the pointer argument. 6031 TheCall->setType(FirstArgType); 6032 6033 // Second arg must be an constant in range [0,15] 6034 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6035 } 6036 6037 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6038 if (checkArgCount(*this, TheCall, 2)) 6039 return true; 6040 Expr *Arg0 = TheCall->getArg(0); 6041 Expr *Arg1 = TheCall->getArg(1); 6042 6043 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6044 if (FirstArg.isInvalid()) 6045 return true; 6046 QualType FirstArgType = FirstArg.get()->getType(); 6047 if (!FirstArgType->isAnyPointerType()) 6048 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6049 << "first" << FirstArgType << Arg0->getSourceRange(); 6050 6051 QualType SecArgType = Arg1->getType(); 6052 if (!SecArgType->isIntegerType()) 6053 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6054 << "second" << SecArgType << Arg1->getSourceRange(); 6055 TheCall->setType(Context.IntTy); 6056 return false; 6057 } 6058 6059 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6060 BuiltinID == AArch64::BI__builtin_arm_stg) { 6061 if (checkArgCount(*this, TheCall, 1)) 6062 return true; 6063 Expr *Arg0 = TheCall->getArg(0); 6064 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6065 if (FirstArg.isInvalid()) 6066 return true; 6067 6068 QualType FirstArgType = FirstArg.get()->getType(); 6069 if (!FirstArgType->isAnyPointerType()) 6070 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6071 << "first" << FirstArgType << Arg0->getSourceRange(); 6072 TheCall->setArg(0, FirstArg.get()); 6073 6074 // Derive the return type from the pointer argument. 6075 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6076 TheCall->setType(FirstArgType); 6077 return false; 6078 } 6079 6080 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6081 Expr *ArgA = TheCall->getArg(0); 6082 Expr *ArgB = TheCall->getArg(1); 6083 6084 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6085 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6086 6087 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6088 return true; 6089 6090 QualType ArgTypeA = ArgExprA.get()->getType(); 6091 QualType ArgTypeB = ArgExprB.get()->getType(); 6092 6093 auto isNull = [&] (Expr *E) -> bool { 6094 return E->isNullPointerConstant( 6095 Context, Expr::NPC_ValueDependentIsNotNull); }; 6096 6097 // argument should be either a pointer or null 6098 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6099 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6100 << "first" << ArgTypeA << ArgA->getSourceRange(); 6101 6102 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6103 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6104 << "second" << ArgTypeB << ArgB->getSourceRange(); 6105 6106 // Ensure Pointee types are compatible 6107 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6108 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6109 QualType pointeeA = ArgTypeA->getPointeeType(); 6110 QualType pointeeB = ArgTypeB->getPointeeType(); 6111 if (!Context.typesAreCompatible( 6112 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6113 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6114 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6115 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6116 << ArgB->getSourceRange(); 6117 } 6118 } 6119 6120 // at least one argument should be pointer type 6121 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6122 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6123 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6124 6125 if (isNull(ArgA)) // adopt type of the other pointer 6126 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6127 6128 if (isNull(ArgB)) 6129 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6130 6131 TheCall->setArg(0, ArgExprA.get()); 6132 TheCall->setArg(1, ArgExprB.get()); 6133 TheCall->setType(Context.LongLongTy); 6134 return false; 6135 } 6136 assert(false && "Unhandled ARM MTE intrinsic"); 6137 return true; 6138 } 6139 6140 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6141 /// TheCall is an ARM/AArch64 special register string literal. 6142 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6143 int ArgNum, unsigned ExpectedFieldNum, 6144 bool AllowName) { 6145 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6146 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6147 BuiltinID == ARM::BI__builtin_arm_rsr || 6148 BuiltinID == ARM::BI__builtin_arm_rsrp || 6149 BuiltinID == ARM::BI__builtin_arm_wsr || 6150 BuiltinID == ARM::BI__builtin_arm_wsrp; 6151 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6152 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6153 BuiltinID == AArch64::BI__builtin_arm_rsr || 6154 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6155 BuiltinID == AArch64::BI__builtin_arm_wsr || 6156 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6157 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6158 6159 // We can't check the value of a dependent argument. 6160 Expr *Arg = TheCall->getArg(ArgNum); 6161 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6162 return false; 6163 6164 // Check if the argument is a string literal. 6165 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6166 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6167 << Arg->getSourceRange(); 6168 6169 // Check the type of special register given. 6170 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6171 SmallVector<StringRef, 6> Fields; 6172 Reg.split(Fields, ":"); 6173 6174 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6175 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6176 << Arg->getSourceRange(); 6177 6178 // If the string is the name of a register then we cannot check that it is 6179 // valid here but if the string is of one the forms described in ACLE then we 6180 // can check that the supplied fields are integers and within the valid 6181 // ranges. 6182 if (Fields.size() > 1) { 6183 bool FiveFields = Fields.size() == 5; 6184 6185 bool ValidString = true; 6186 if (IsARMBuiltin) { 6187 ValidString &= Fields[0].startswith_lower("cp") || 6188 Fields[0].startswith_lower("p"); 6189 if (ValidString) 6190 Fields[0] = 6191 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6192 6193 ValidString &= Fields[2].startswith_lower("c"); 6194 if (ValidString) 6195 Fields[2] = Fields[2].drop_front(1); 6196 6197 if (FiveFields) { 6198 ValidString &= Fields[3].startswith_lower("c"); 6199 if (ValidString) 6200 Fields[3] = Fields[3].drop_front(1); 6201 } 6202 } 6203 6204 SmallVector<int, 5> Ranges; 6205 if (FiveFields) 6206 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6207 else 6208 Ranges.append({15, 7, 15}); 6209 6210 for (unsigned i=0; i<Fields.size(); ++i) { 6211 int IntField; 6212 ValidString &= !Fields[i].getAsInteger(10, IntField); 6213 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6214 } 6215 6216 if (!ValidString) 6217 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6218 << Arg->getSourceRange(); 6219 } else if (IsAArch64Builtin && Fields.size() == 1) { 6220 // If the register name is one of those that appear in the condition below 6221 // and the special register builtin being used is one of the write builtins, 6222 // then we require that the argument provided for writing to the register 6223 // is an integer constant expression. This is because it will be lowered to 6224 // an MSR (immediate) instruction, so we need to know the immediate at 6225 // compile time. 6226 if (TheCall->getNumArgs() != 2) 6227 return false; 6228 6229 std::string RegLower = Reg.lower(); 6230 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6231 RegLower != "pan" && RegLower != "uao") 6232 return false; 6233 6234 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6235 } 6236 6237 return false; 6238 } 6239 6240 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6241 /// This checks that the target supports __builtin_longjmp and 6242 /// that val is a constant 1. 6243 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6244 if (!Context.getTargetInfo().hasSjLjLowering()) 6245 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6246 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6247 6248 Expr *Arg = TheCall->getArg(1); 6249 llvm::APSInt Result; 6250 6251 // TODO: This is less than ideal. Overload this to take a value. 6252 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6253 return true; 6254 6255 if (Result != 1) 6256 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6257 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6258 6259 return false; 6260 } 6261 6262 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6263 /// This checks that the target supports __builtin_setjmp. 6264 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6265 if (!Context.getTargetInfo().hasSjLjLowering()) 6266 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6267 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6268 return false; 6269 } 6270 6271 namespace { 6272 6273 class UncoveredArgHandler { 6274 enum { Unknown = -1, AllCovered = -2 }; 6275 6276 signed FirstUncoveredArg = Unknown; 6277 SmallVector<const Expr *, 4> DiagnosticExprs; 6278 6279 public: 6280 UncoveredArgHandler() = default; 6281 6282 bool hasUncoveredArg() const { 6283 return (FirstUncoveredArg >= 0); 6284 } 6285 6286 unsigned getUncoveredArg() const { 6287 assert(hasUncoveredArg() && "no uncovered argument"); 6288 return FirstUncoveredArg; 6289 } 6290 6291 void setAllCovered() { 6292 // A string has been found with all arguments covered, so clear out 6293 // the diagnostics. 6294 DiagnosticExprs.clear(); 6295 FirstUncoveredArg = AllCovered; 6296 } 6297 6298 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6299 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6300 6301 // Don't update if a previous string covers all arguments. 6302 if (FirstUncoveredArg == AllCovered) 6303 return; 6304 6305 // UncoveredArgHandler tracks the highest uncovered argument index 6306 // and with it all the strings that match this index. 6307 if (NewFirstUncoveredArg == FirstUncoveredArg) 6308 DiagnosticExprs.push_back(StrExpr); 6309 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6310 DiagnosticExprs.clear(); 6311 DiagnosticExprs.push_back(StrExpr); 6312 FirstUncoveredArg = NewFirstUncoveredArg; 6313 } 6314 } 6315 6316 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6317 }; 6318 6319 enum StringLiteralCheckType { 6320 SLCT_NotALiteral, 6321 SLCT_UncheckedLiteral, 6322 SLCT_CheckedLiteral 6323 }; 6324 6325 } // namespace 6326 6327 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6328 BinaryOperatorKind BinOpKind, 6329 bool AddendIsRight) { 6330 unsigned BitWidth = Offset.getBitWidth(); 6331 unsigned AddendBitWidth = Addend.getBitWidth(); 6332 // There might be negative interim results. 6333 if (Addend.isUnsigned()) { 6334 Addend = Addend.zext(++AddendBitWidth); 6335 Addend.setIsSigned(true); 6336 } 6337 // Adjust the bit width of the APSInts. 6338 if (AddendBitWidth > BitWidth) { 6339 Offset = Offset.sext(AddendBitWidth); 6340 BitWidth = AddendBitWidth; 6341 } else if (BitWidth > AddendBitWidth) { 6342 Addend = Addend.sext(BitWidth); 6343 } 6344 6345 bool Ov = false; 6346 llvm::APSInt ResOffset = Offset; 6347 if (BinOpKind == BO_Add) 6348 ResOffset = Offset.sadd_ov(Addend, Ov); 6349 else { 6350 assert(AddendIsRight && BinOpKind == BO_Sub && 6351 "operator must be add or sub with addend on the right"); 6352 ResOffset = Offset.ssub_ov(Addend, Ov); 6353 } 6354 6355 // We add an offset to a pointer here so we should support an offset as big as 6356 // possible. 6357 if (Ov) { 6358 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6359 "index (intermediate) result too big"); 6360 Offset = Offset.sext(2 * BitWidth); 6361 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6362 return; 6363 } 6364 6365 Offset = ResOffset; 6366 } 6367 6368 namespace { 6369 6370 // This is a wrapper class around StringLiteral to support offsetted string 6371 // literals as format strings. It takes the offset into account when returning 6372 // the string and its length or the source locations to display notes correctly. 6373 class FormatStringLiteral { 6374 const StringLiteral *FExpr; 6375 int64_t Offset; 6376 6377 public: 6378 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6379 : FExpr(fexpr), Offset(Offset) {} 6380 6381 StringRef getString() const { 6382 return FExpr->getString().drop_front(Offset); 6383 } 6384 6385 unsigned getByteLength() const { 6386 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6387 } 6388 6389 unsigned getLength() const { return FExpr->getLength() - Offset; } 6390 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6391 6392 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6393 6394 QualType getType() const { return FExpr->getType(); } 6395 6396 bool isAscii() const { return FExpr->isAscii(); } 6397 bool isWide() const { return FExpr->isWide(); } 6398 bool isUTF8() const { return FExpr->isUTF8(); } 6399 bool isUTF16() const { return FExpr->isUTF16(); } 6400 bool isUTF32() const { return FExpr->isUTF32(); } 6401 bool isPascal() const { return FExpr->isPascal(); } 6402 6403 SourceLocation getLocationOfByte( 6404 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6405 const TargetInfo &Target, unsigned *StartToken = nullptr, 6406 unsigned *StartTokenByteOffset = nullptr) const { 6407 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6408 StartToken, StartTokenByteOffset); 6409 } 6410 6411 SourceLocation getBeginLoc() const LLVM_READONLY { 6412 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6413 } 6414 6415 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6416 }; 6417 6418 } // namespace 6419 6420 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6421 const Expr *OrigFormatExpr, 6422 ArrayRef<const Expr *> Args, 6423 bool HasVAListArg, unsigned format_idx, 6424 unsigned firstDataArg, 6425 Sema::FormatStringType Type, 6426 bool inFunctionCall, 6427 Sema::VariadicCallType CallType, 6428 llvm::SmallBitVector &CheckedVarArgs, 6429 UncoveredArgHandler &UncoveredArg, 6430 bool IgnoreStringsWithoutSpecifiers); 6431 6432 // Determine if an expression is a string literal or constant string. 6433 // If this function returns false on the arguments to a function expecting a 6434 // format string, we will usually need to emit a warning. 6435 // True string literals are then checked by CheckFormatString. 6436 static StringLiteralCheckType 6437 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6438 bool HasVAListArg, unsigned format_idx, 6439 unsigned firstDataArg, Sema::FormatStringType Type, 6440 Sema::VariadicCallType CallType, bool InFunctionCall, 6441 llvm::SmallBitVector &CheckedVarArgs, 6442 UncoveredArgHandler &UncoveredArg, 6443 llvm::APSInt Offset, 6444 bool IgnoreStringsWithoutSpecifiers = false) { 6445 if (S.isConstantEvaluated()) 6446 return SLCT_NotALiteral; 6447 tryAgain: 6448 assert(Offset.isSigned() && "invalid offset"); 6449 6450 if (E->isTypeDependent() || E->isValueDependent()) 6451 return SLCT_NotALiteral; 6452 6453 E = E->IgnoreParenCasts(); 6454 6455 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6456 // Technically -Wformat-nonliteral does not warn about this case. 6457 // The behavior of printf and friends in this case is implementation 6458 // dependent. Ideally if the format string cannot be null then 6459 // it should have a 'nonnull' attribute in the function prototype. 6460 return SLCT_UncheckedLiteral; 6461 6462 switch (E->getStmtClass()) { 6463 case Stmt::BinaryConditionalOperatorClass: 6464 case Stmt::ConditionalOperatorClass: { 6465 // The expression is a literal if both sub-expressions were, and it was 6466 // completely checked only if both sub-expressions were checked. 6467 const AbstractConditionalOperator *C = 6468 cast<AbstractConditionalOperator>(E); 6469 6470 // Determine whether it is necessary to check both sub-expressions, for 6471 // example, because the condition expression is a constant that can be 6472 // evaluated at compile time. 6473 bool CheckLeft = true, CheckRight = true; 6474 6475 bool Cond; 6476 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6477 S.isConstantEvaluated())) { 6478 if (Cond) 6479 CheckRight = false; 6480 else 6481 CheckLeft = false; 6482 } 6483 6484 // We need to maintain the offsets for the right and the left hand side 6485 // separately to check if every possible indexed expression is a valid 6486 // string literal. They might have different offsets for different string 6487 // literals in the end. 6488 StringLiteralCheckType Left; 6489 if (!CheckLeft) 6490 Left = SLCT_UncheckedLiteral; 6491 else { 6492 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6493 HasVAListArg, format_idx, firstDataArg, 6494 Type, CallType, InFunctionCall, 6495 CheckedVarArgs, UncoveredArg, Offset, 6496 IgnoreStringsWithoutSpecifiers); 6497 if (Left == SLCT_NotALiteral || !CheckRight) { 6498 return Left; 6499 } 6500 } 6501 6502 StringLiteralCheckType Right = checkFormatStringExpr( 6503 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6504 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6505 IgnoreStringsWithoutSpecifiers); 6506 6507 return (CheckLeft && Left < Right) ? Left : Right; 6508 } 6509 6510 case Stmt::ImplicitCastExprClass: 6511 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6512 goto tryAgain; 6513 6514 case Stmt::OpaqueValueExprClass: 6515 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6516 E = src; 6517 goto tryAgain; 6518 } 6519 return SLCT_NotALiteral; 6520 6521 case Stmt::PredefinedExprClass: 6522 // While __func__, etc., are technically not string literals, they 6523 // cannot contain format specifiers and thus are not a security 6524 // liability. 6525 return SLCT_UncheckedLiteral; 6526 6527 case Stmt::DeclRefExprClass: { 6528 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6529 6530 // As an exception, do not flag errors for variables binding to 6531 // const string literals. 6532 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6533 bool isConstant = false; 6534 QualType T = DR->getType(); 6535 6536 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6537 isConstant = AT->getElementType().isConstant(S.Context); 6538 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6539 isConstant = T.isConstant(S.Context) && 6540 PT->getPointeeType().isConstant(S.Context); 6541 } else if (T->isObjCObjectPointerType()) { 6542 // In ObjC, there is usually no "const ObjectPointer" type, 6543 // so don't check if the pointee type is constant. 6544 isConstant = T.isConstant(S.Context); 6545 } 6546 6547 if (isConstant) { 6548 if (const Expr *Init = VD->getAnyInitializer()) { 6549 // Look through initializers like const char c[] = { "foo" } 6550 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6551 if (InitList->isStringLiteralInit()) 6552 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6553 } 6554 return checkFormatStringExpr(S, Init, Args, 6555 HasVAListArg, format_idx, 6556 firstDataArg, Type, CallType, 6557 /*InFunctionCall*/ false, CheckedVarArgs, 6558 UncoveredArg, Offset); 6559 } 6560 } 6561 6562 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6563 // special check to see if the format string is a function parameter 6564 // of the function calling the printf function. If the function 6565 // has an attribute indicating it is a printf-like function, then we 6566 // should suppress warnings concerning non-literals being used in a call 6567 // to a vprintf function. For example: 6568 // 6569 // void 6570 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6571 // va_list ap; 6572 // va_start(ap, fmt); 6573 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6574 // ... 6575 // } 6576 if (HasVAListArg) { 6577 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6578 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6579 int PVIndex = PV->getFunctionScopeIndex() + 1; 6580 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6581 // adjust for implicit parameter 6582 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6583 if (MD->isInstance()) 6584 ++PVIndex; 6585 // We also check if the formats are compatible. 6586 // We can't pass a 'scanf' string to a 'printf' function. 6587 if (PVIndex == PVFormat->getFormatIdx() && 6588 Type == S.GetFormatStringType(PVFormat)) 6589 return SLCT_UncheckedLiteral; 6590 } 6591 } 6592 } 6593 } 6594 } 6595 6596 return SLCT_NotALiteral; 6597 } 6598 6599 case Stmt::CallExprClass: 6600 case Stmt::CXXMemberCallExprClass: { 6601 const CallExpr *CE = cast<CallExpr>(E); 6602 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6603 bool IsFirst = true; 6604 StringLiteralCheckType CommonResult; 6605 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6606 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6607 StringLiteralCheckType Result = checkFormatStringExpr( 6608 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6609 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6610 IgnoreStringsWithoutSpecifiers); 6611 if (IsFirst) { 6612 CommonResult = Result; 6613 IsFirst = false; 6614 } 6615 } 6616 if (!IsFirst) 6617 return CommonResult; 6618 6619 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6620 unsigned BuiltinID = FD->getBuiltinID(); 6621 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6622 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6623 const Expr *Arg = CE->getArg(0); 6624 return checkFormatStringExpr(S, Arg, Args, 6625 HasVAListArg, format_idx, 6626 firstDataArg, Type, CallType, 6627 InFunctionCall, CheckedVarArgs, 6628 UncoveredArg, Offset, 6629 IgnoreStringsWithoutSpecifiers); 6630 } 6631 } 6632 } 6633 6634 return SLCT_NotALiteral; 6635 } 6636 case Stmt::ObjCMessageExprClass: { 6637 const auto *ME = cast<ObjCMessageExpr>(E); 6638 if (const auto *MD = ME->getMethodDecl()) { 6639 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 6640 // As a special case heuristic, if we're using the method -[NSBundle 6641 // localizedStringForKey:value:table:], ignore any key strings that lack 6642 // format specifiers. The idea is that if the key doesn't have any 6643 // format specifiers then its probably just a key to map to the 6644 // localized strings. If it does have format specifiers though, then its 6645 // likely that the text of the key is the format string in the 6646 // programmer's language, and should be checked. 6647 const ObjCInterfaceDecl *IFace; 6648 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 6649 IFace->getIdentifier()->isStr("NSBundle") && 6650 MD->getSelector().isKeywordSelector( 6651 {"localizedStringForKey", "value", "table"})) { 6652 IgnoreStringsWithoutSpecifiers = true; 6653 } 6654 6655 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6656 return checkFormatStringExpr( 6657 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6658 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6659 IgnoreStringsWithoutSpecifiers); 6660 } 6661 } 6662 6663 return SLCT_NotALiteral; 6664 } 6665 case Stmt::ObjCStringLiteralClass: 6666 case Stmt::StringLiteralClass: { 6667 const StringLiteral *StrE = nullptr; 6668 6669 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6670 StrE = ObjCFExpr->getString(); 6671 else 6672 StrE = cast<StringLiteral>(E); 6673 6674 if (StrE) { 6675 if (Offset.isNegative() || Offset > StrE->getLength()) { 6676 // TODO: It would be better to have an explicit warning for out of 6677 // bounds literals. 6678 return SLCT_NotALiteral; 6679 } 6680 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6681 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6682 firstDataArg, Type, InFunctionCall, CallType, 6683 CheckedVarArgs, UncoveredArg, 6684 IgnoreStringsWithoutSpecifiers); 6685 return SLCT_CheckedLiteral; 6686 } 6687 6688 return SLCT_NotALiteral; 6689 } 6690 case Stmt::BinaryOperatorClass: { 6691 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6692 6693 // A string literal + an int offset is still a string literal. 6694 if (BinOp->isAdditiveOp()) { 6695 Expr::EvalResult LResult, RResult; 6696 6697 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 6698 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6699 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 6700 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6701 6702 if (LIsInt != RIsInt) { 6703 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6704 6705 if (LIsInt) { 6706 if (BinOpKind == BO_Add) { 6707 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6708 E = BinOp->getRHS(); 6709 goto tryAgain; 6710 } 6711 } else { 6712 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6713 E = BinOp->getLHS(); 6714 goto tryAgain; 6715 } 6716 } 6717 } 6718 6719 return SLCT_NotALiteral; 6720 } 6721 case Stmt::UnaryOperatorClass: { 6722 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6723 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6724 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6725 Expr::EvalResult IndexResult; 6726 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 6727 Expr::SE_NoSideEffects, 6728 S.isConstantEvaluated())) { 6729 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6730 /*RHS is int*/ true); 6731 E = ASE->getBase(); 6732 goto tryAgain; 6733 } 6734 } 6735 6736 return SLCT_NotALiteral; 6737 } 6738 6739 default: 6740 return SLCT_NotALiteral; 6741 } 6742 } 6743 6744 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6745 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6746 .Case("scanf", FST_Scanf) 6747 .Cases("printf", "printf0", FST_Printf) 6748 .Cases("NSString", "CFString", FST_NSString) 6749 .Case("strftime", FST_Strftime) 6750 .Case("strfmon", FST_Strfmon) 6751 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6752 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6753 .Case("os_trace", FST_OSLog) 6754 .Case("os_log", FST_OSLog) 6755 .Default(FST_Unknown); 6756 } 6757 6758 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6759 /// functions) for correct use of format strings. 6760 /// Returns true if a format string has been fully checked. 6761 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6762 ArrayRef<const Expr *> Args, 6763 bool IsCXXMember, 6764 VariadicCallType CallType, 6765 SourceLocation Loc, SourceRange Range, 6766 llvm::SmallBitVector &CheckedVarArgs) { 6767 FormatStringInfo FSI; 6768 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6769 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6770 FSI.FirstDataArg, GetFormatStringType(Format), 6771 CallType, Loc, Range, CheckedVarArgs); 6772 return false; 6773 } 6774 6775 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6776 bool HasVAListArg, unsigned format_idx, 6777 unsigned firstDataArg, FormatStringType Type, 6778 VariadicCallType CallType, 6779 SourceLocation Loc, SourceRange Range, 6780 llvm::SmallBitVector &CheckedVarArgs) { 6781 // CHECK: printf/scanf-like function is called with no format string. 6782 if (format_idx >= Args.size()) { 6783 Diag(Loc, diag::warn_missing_format_string) << Range; 6784 return false; 6785 } 6786 6787 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 6788 6789 // CHECK: format string is not a string literal. 6790 // 6791 // Dynamically generated format strings are difficult to 6792 // automatically vet at compile time. Requiring that format strings 6793 // are string literals: (1) permits the checking of format strings by 6794 // the compiler and thereby (2) can practically remove the source of 6795 // many format string exploits. 6796 6797 // Format string can be either ObjC string (e.g. @"%d") or 6798 // C string (e.g. "%d") 6799 // ObjC string uses the same format specifiers as C string, so we can use 6800 // the same format string checking logic for both ObjC and C strings. 6801 UncoveredArgHandler UncoveredArg; 6802 StringLiteralCheckType CT = 6803 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 6804 format_idx, firstDataArg, Type, CallType, 6805 /*IsFunctionCall*/ true, CheckedVarArgs, 6806 UncoveredArg, 6807 /*no string offset*/ llvm::APSInt(64, false) = 0); 6808 6809 // Generate a diagnostic where an uncovered argument is detected. 6810 if (UncoveredArg.hasUncoveredArg()) { 6811 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 6812 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 6813 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 6814 } 6815 6816 if (CT != SLCT_NotALiteral) 6817 // Literal format string found, check done! 6818 return CT == SLCT_CheckedLiteral; 6819 6820 // Strftime is particular as it always uses a single 'time' argument, 6821 // so it is safe to pass a non-literal string. 6822 if (Type == FST_Strftime) 6823 return false; 6824 6825 // Do not emit diag when the string param is a macro expansion and the 6826 // format is either NSString or CFString. This is a hack to prevent 6827 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 6828 // which are usually used in place of NS and CF string literals. 6829 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 6830 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 6831 return false; 6832 6833 // If there are no arguments specified, warn with -Wformat-security, otherwise 6834 // warn only with -Wformat-nonliteral. 6835 if (Args.size() == firstDataArg) { 6836 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 6837 << OrigFormatExpr->getSourceRange(); 6838 switch (Type) { 6839 default: 6840 break; 6841 case FST_Kprintf: 6842 case FST_FreeBSDKPrintf: 6843 case FST_Printf: 6844 Diag(FormatLoc, diag::note_format_security_fixit) 6845 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 6846 break; 6847 case FST_NSString: 6848 Diag(FormatLoc, diag::note_format_security_fixit) 6849 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 6850 break; 6851 } 6852 } else { 6853 Diag(FormatLoc, diag::warn_format_nonliteral) 6854 << OrigFormatExpr->getSourceRange(); 6855 } 6856 return false; 6857 } 6858 6859 namespace { 6860 6861 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 6862 protected: 6863 Sema &S; 6864 const FormatStringLiteral *FExpr; 6865 const Expr *OrigFormatExpr; 6866 const Sema::FormatStringType FSType; 6867 const unsigned FirstDataArg; 6868 const unsigned NumDataArgs; 6869 const char *Beg; // Start of format string. 6870 const bool HasVAListArg; 6871 ArrayRef<const Expr *> Args; 6872 unsigned FormatIdx; 6873 llvm::SmallBitVector CoveredArgs; 6874 bool usesPositionalArgs = false; 6875 bool atFirstArg = true; 6876 bool inFunctionCall; 6877 Sema::VariadicCallType CallType; 6878 llvm::SmallBitVector &CheckedVarArgs; 6879 UncoveredArgHandler &UncoveredArg; 6880 6881 public: 6882 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 6883 const Expr *origFormatExpr, 6884 const Sema::FormatStringType type, unsigned firstDataArg, 6885 unsigned numDataArgs, const char *beg, bool hasVAListArg, 6886 ArrayRef<const Expr *> Args, unsigned formatIdx, 6887 bool inFunctionCall, Sema::VariadicCallType callType, 6888 llvm::SmallBitVector &CheckedVarArgs, 6889 UncoveredArgHandler &UncoveredArg) 6890 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 6891 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 6892 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 6893 inFunctionCall(inFunctionCall), CallType(callType), 6894 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 6895 CoveredArgs.resize(numDataArgs); 6896 CoveredArgs.reset(); 6897 } 6898 6899 void DoneProcessing(); 6900 6901 void HandleIncompleteSpecifier(const char *startSpecifier, 6902 unsigned specifierLen) override; 6903 6904 void HandleInvalidLengthModifier( 6905 const analyze_format_string::FormatSpecifier &FS, 6906 const analyze_format_string::ConversionSpecifier &CS, 6907 const char *startSpecifier, unsigned specifierLen, 6908 unsigned DiagID); 6909 6910 void HandleNonStandardLengthModifier( 6911 const analyze_format_string::FormatSpecifier &FS, 6912 const char *startSpecifier, unsigned specifierLen); 6913 6914 void HandleNonStandardConversionSpecifier( 6915 const analyze_format_string::ConversionSpecifier &CS, 6916 const char *startSpecifier, unsigned specifierLen); 6917 6918 void HandlePosition(const char *startPos, unsigned posLen) override; 6919 6920 void HandleInvalidPosition(const char *startSpecifier, 6921 unsigned specifierLen, 6922 analyze_format_string::PositionContext p) override; 6923 6924 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 6925 6926 void HandleNullChar(const char *nullCharacter) override; 6927 6928 template <typename Range> 6929 static void 6930 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 6931 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 6932 bool IsStringLocation, Range StringRange, 6933 ArrayRef<FixItHint> Fixit = None); 6934 6935 protected: 6936 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 6937 const char *startSpec, 6938 unsigned specifierLen, 6939 const char *csStart, unsigned csLen); 6940 6941 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 6942 const char *startSpec, 6943 unsigned specifierLen); 6944 6945 SourceRange getFormatStringRange(); 6946 CharSourceRange getSpecifierRange(const char *startSpecifier, 6947 unsigned specifierLen); 6948 SourceLocation getLocationOfByte(const char *x); 6949 6950 const Expr *getDataArg(unsigned i) const; 6951 6952 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 6953 const analyze_format_string::ConversionSpecifier &CS, 6954 const char *startSpecifier, unsigned specifierLen, 6955 unsigned argIndex); 6956 6957 template <typename Range> 6958 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 6959 bool IsStringLocation, Range StringRange, 6960 ArrayRef<FixItHint> Fixit = None); 6961 }; 6962 6963 } // namespace 6964 6965 SourceRange CheckFormatHandler::getFormatStringRange() { 6966 return OrigFormatExpr->getSourceRange(); 6967 } 6968 6969 CharSourceRange CheckFormatHandler:: 6970 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 6971 SourceLocation Start = getLocationOfByte(startSpecifier); 6972 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 6973 6974 // Advance the end SourceLocation by one due to half-open ranges. 6975 End = End.getLocWithOffset(1); 6976 6977 return CharSourceRange::getCharRange(Start, End); 6978 } 6979 6980 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 6981 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 6982 S.getLangOpts(), S.Context.getTargetInfo()); 6983 } 6984 6985 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 6986 unsigned specifierLen){ 6987 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 6988 getLocationOfByte(startSpecifier), 6989 /*IsStringLocation*/true, 6990 getSpecifierRange(startSpecifier, specifierLen)); 6991 } 6992 6993 void CheckFormatHandler::HandleInvalidLengthModifier( 6994 const analyze_format_string::FormatSpecifier &FS, 6995 const analyze_format_string::ConversionSpecifier &CS, 6996 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 6997 using namespace analyze_format_string; 6998 6999 const LengthModifier &LM = FS.getLengthModifier(); 7000 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7001 7002 // See if we know how to fix this length modifier. 7003 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7004 if (FixedLM) { 7005 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7006 getLocationOfByte(LM.getStart()), 7007 /*IsStringLocation*/true, 7008 getSpecifierRange(startSpecifier, specifierLen)); 7009 7010 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7011 << FixedLM->toString() 7012 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7013 7014 } else { 7015 FixItHint Hint; 7016 if (DiagID == diag::warn_format_nonsensical_length) 7017 Hint = FixItHint::CreateRemoval(LMRange); 7018 7019 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7020 getLocationOfByte(LM.getStart()), 7021 /*IsStringLocation*/true, 7022 getSpecifierRange(startSpecifier, specifierLen), 7023 Hint); 7024 } 7025 } 7026 7027 void CheckFormatHandler::HandleNonStandardLengthModifier( 7028 const analyze_format_string::FormatSpecifier &FS, 7029 const char *startSpecifier, unsigned specifierLen) { 7030 using namespace analyze_format_string; 7031 7032 const LengthModifier &LM = FS.getLengthModifier(); 7033 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7034 7035 // See if we know how to fix this length modifier. 7036 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7037 if (FixedLM) { 7038 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7039 << LM.toString() << 0, 7040 getLocationOfByte(LM.getStart()), 7041 /*IsStringLocation*/true, 7042 getSpecifierRange(startSpecifier, specifierLen)); 7043 7044 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7045 << FixedLM->toString() 7046 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7047 7048 } else { 7049 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7050 << LM.toString() << 0, 7051 getLocationOfByte(LM.getStart()), 7052 /*IsStringLocation*/true, 7053 getSpecifierRange(startSpecifier, specifierLen)); 7054 } 7055 } 7056 7057 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7058 const analyze_format_string::ConversionSpecifier &CS, 7059 const char *startSpecifier, unsigned specifierLen) { 7060 using namespace analyze_format_string; 7061 7062 // See if we know how to fix this conversion specifier. 7063 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7064 if (FixedCS) { 7065 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7066 << CS.toString() << /*conversion specifier*/1, 7067 getLocationOfByte(CS.getStart()), 7068 /*IsStringLocation*/true, 7069 getSpecifierRange(startSpecifier, specifierLen)); 7070 7071 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7072 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7073 << FixedCS->toString() 7074 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7075 } else { 7076 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7077 << CS.toString() << /*conversion specifier*/1, 7078 getLocationOfByte(CS.getStart()), 7079 /*IsStringLocation*/true, 7080 getSpecifierRange(startSpecifier, specifierLen)); 7081 } 7082 } 7083 7084 void CheckFormatHandler::HandlePosition(const char *startPos, 7085 unsigned posLen) { 7086 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7087 getLocationOfByte(startPos), 7088 /*IsStringLocation*/true, 7089 getSpecifierRange(startPos, posLen)); 7090 } 7091 7092 void 7093 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7094 analyze_format_string::PositionContext p) { 7095 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7096 << (unsigned) p, 7097 getLocationOfByte(startPos), /*IsStringLocation*/true, 7098 getSpecifierRange(startPos, posLen)); 7099 } 7100 7101 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7102 unsigned posLen) { 7103 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7104 getLocationOfByte(startPos), 7105 /*IsStringLocation*/true, 7106 getSpecifierRange(startPos, posLen)); 7107 } 7108 7109 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7110 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7111 // The presence of a null character is likely an error. 7112 EmitFormatDiagnostic( 7113 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7114 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7115 getFormatStringRange()); 7116 } 7117 } 7118 7119 // Note that this may return NULL if there was an error parsing or building 7120 // one of the argument expressions. 7121 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7122 return Args[FirstDataArg + i]; 7123 } 7124 7125 void CheckFormatHandler::DoneProcessing() { 7126 // Does the number of data arguments exceed the number of 7127 // format conversions in the format string? 7128 if (!HasVAListArg) { 7129 // Find any arguments that weren't covered. 7130 CoveredArgs.flip(); 7131 signed notCoveredArg = CoveredArgs.find_first(); 7132 if (notCoveredArg >= 0) { 7133 assert((unsigned)notCoveredArg < NumDataArgs); 7134 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7135 } else { 7136 UncoveredArg.setAllCovered(); 7137 } 7138 } 7139 } 7140 7141 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7142 const Expr *ArgExpr) { 7143 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7144 "Invalid state"); 7145 7146 if (!ArgExpr) 7147 return; 7148 7149 SourceLocation Loc = ArgExpr->getBeginLoc(); 7150 7151 if (S.getSourceManager().isInSystemMacro(Loc)) 7152 return; 7153 7154 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7155 for (auto E : DiagnosticExprs) 7156 PDiag << E->getSourceRange(); 7157 7158 CheckFormatHandler::EmitFormatDiagnostic( 7159 S, IsFunctionCall, DiagnosticExprs[0], 7160 PDiag, Loc, /*IsStringLocation*/false, 7161 DiagnosticExprs[0]->getSourceRange()); 7162 } 7163 7164 bool 7165 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7166 SourceLocation Loc, 7167 const char *startSpec, 7168 unsigned specifierLen, 7169 const char *csStart, 7170 unsigned csLen) { 7171 bool keepGoing = true; 7172 if (argIndex < NumDataArgs) { 7173 // Consider the argument coverered, even though the specifier doesn't 7174 // make sense. 7175 CoveredArgs.set(argIndex); 7176 } 7177 else { 7178 // If argIndex exceeds the number of data arguments we 7179 // don't issue a warning because that is just a cascade of warnings (and 7180 // they may have intended '%%' anyway). We don't want to continue processing 7181 // the format string after this point, however, as we will like just get 7182 // gibberish when trying to match arguments. 7183 keepGoing = false; 7184 } 7185 7186 StringRef Specifier(csStart, csLen); 7187 7188 // If the specifier in non-printable, it could be the first byte of a UTF-8 7189 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7190 // hex value. 7191 std::string CodePointStr; 7192 if (!llvm::sys::locale::isPrint(*csStart)) { 7193 llvm::UTF32 CodePoint; 7194 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7195 const llvm::UTF8 *E = 7196 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7197 llvm::ConversionResult Result = 7198 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7199 7200 if (Result != llvm::conversionOK) { 7201 unsigned char FirstChar = *csStart; 7202 CodePoint = (llvm::UTF32)FirstChar; 7203 } 7204 7205 llvm::raw_string_ostream OS(CodePointStr); 7206 if (CodePoint < 256) 7207 OS << "\\x" << llvm::format("%02x", CodePoint); 7208 else if (CodePoint <= 0xFFFF) 7209 OS << "\\u" << llvm::format("%04x", CodePoint); 7210 else 7211 OS << "\\U" << llvm::format("%08x", CodePoint); 7212 OS.flush(); 7213 Specifier = CodePointStr; 7214 } 7215 7216 EmitFormatDiagnostic( 7217 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7218 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7219 7220 return keepGoing; 7221 } 7222 7223 void 7224 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7225 const char *startSpec, 7226 unsigned specifierLen) { 7227 EmitFormatDiagnostic( 7228 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7229 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7230 } 7231 7232 bool 7233 CheckFormatHandler::CheckNumArgs( 7234 const analyze_format_string::FormatSpecifier &FS, 7235 const analyze_format_string::ConversionSpecifier &CS, 7236 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7237 7238 if (argIndex >= NumDataArgs) { 7239 PartialDiagnostic PDiag = FS.usesPositionalArg() 7240 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7241 << (argIndex+1) << NumDataArgs) 7242 : S.PDiag(diag::warn_printf_insufficient_data_args); 7243 EmitFormatDiagnostic( 7244 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7245 getSpecifierRange(startSpecifier, specifierLen)); 7246 7247 // Since more arguments than conversion tokens are given, by extension 7248 // all arguments are covered, so mark this as so. 7249 UncoveredArg.setAllCovered(); 7250 return false; 7251 } 7252 return true; 7253 } 7254 7255 template<typename Range> 7256 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7257 SourceLocation Loc, 7258 bool IsStringLocation, 7259 Range StringRange, 7260 ArrayRef<FixItHint> FixIt) { 7261 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7262 Loc, IsStringLocation, StringRange, FixIt); 7263 } 7264 7265 /// If the format string is not within the function call, emit a note 7266 /// so that the function call and string are in diagnostic messages. 7267 /// 7268 /// \param InFunctionCall if true, the format string is within the function 7269 /// call and only one diagnostic message will be produced. Otherwise, an 7270 /// extra note will be emitted pointing to location of the format string. 7271 /// 7272 /// \param ArgumentExpr the expression that is passed as the format string 7273 /// argument in the function call. Used for getting locations when two 7274 /// diagnostics are emitted. 7275 /// 7276 /// \param PDiag the callee should already have provided any strings for the 7277 /// diagnostic message. This function only adds locations and fixits 7278 /// to diagnostics. 7279 /// 7280 /// \param Loc primary location for diagnostic. If two diagnostics are 7281 /// required, one will be at Loc and a new SourceLocation will be created for 7282 /// the other one. 7283 /// 7284 /// \param IsStringLocation if true, Loc points to the format string should be 7285 /// used for the note. Otherwise, Loc points to the argument list and will 7286 /// be used with PDiag. 7287 /// 7288 /// \param StringRange some or all of the string to highlight. This is 7289 /// templated so it can accept either a CharSourceRange or a SourceRange. 7290 /// 7291 /// \param FixIt optional fix it hint for the format string. 7292 template <typename Range> 7293 void CheckFormatHandler::EmitFormatDiagnostic( 7294 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7295 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7296 Range StringRange, ArrayRef<FixItHint> FixIt) { 7297 if (InFunctionCall) { 7298 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7299 D << StringRange; 7300 D << FixIt; 7301 } else { 7302 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7303 << ArgumentExpr->getSourceRange(); 7304 7305 const Sema::SemaDiagnosticBuilder &Note = 7306 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7307 diag::note_format_string_defined); 7308 7309 Note << StringRange; 7310 Note << FixIt; 7311 } 7312 } 7313 7314 //===--- CHECK: Printf format string checking ------------------------------===// 7315 7316 namespace { 7317 7318 class CheckPrintfHandler : public CheckFormatHandler { 7319 public: 7320 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7321 const Expr *origFormatExpr, 7322 const Sema::FormatStringType type, unsigned firstDataArg, 7323 unsigned numDataArgs, bool isObjC, const char *beg, 7324 bool hasVAListArg, ArrayRef<const Expr *> Args, 7325 unsigned formatIdx, bool inFunctionCall, 7326 Sema::VariadicCallType CallType, 7327 llvm::SmallBitVector &CheckedVarArgs, 7328 UncoveredArgHandler &UncoveredArg) 7329 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7330 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7331 inFunctionCall, CallType, CheckedVarArgs, 7332 UncoveredArg) {} 7333 7334 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7335 7336 /// Returns true if '%@' specifiers are allowed in the format string. 7337 bool allowsObjCArg() const { 7338 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7339 FSType == Sema::FST_OSTrace; 7340 } 7341 7342 bool HandleInvalidPrintfConversionSpecifier( 7343 const analyze_printf::PrintfSpecifier &FS, 7344 const char *startSpecifier, 7345 unsigned specifierLen) override; 7346 7347 void handleInvalidMaskType(StringRef MaskType) override; 7348 7349 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7350 const char *startSpecifier, 7351 unsigned specifierLen) override; 7352 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7353 const char *StartSpecifier, 7354 unsigned SpecifierLen, 7355 const Expr *E); 7356 7357 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7358 const char *startSpecifier, unsigned specifierLen); 7359 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7360 const analyze_printf::OptionalAmount &Amt, 7361 unsigned type, 7362 const char *startSpecifier, unsigned specifierLen); 7363 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7364 const analyze_printf::OptionalFlag &flag, 7365 const char *startSpecifier, unsigned specifierLen); 7366 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7367 const analyze_printf::OptionalFlag &ignoredFlag, 7368 const analyze_printf::OptionalFlag &flag, 7369 const char *startSpecifier, unsigned specifierLen); 7370 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7371 const Expr *E); 7372 7373 void HandleEmptyObjCModifierFlag(const char *startFlag, 7374 unsigned flagLen) override; 7375 7376 void HandleInvalidObjCModifierFlag(const char *startFlag, 7377 unsigned flagLen) override; 7378 7379 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7380 const char *flagsEnd, 7381 const char *conversionPosition) 7382 override; 7383 }; 7384 7385 } // namespace 7386 7387 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7388 const analyze_printf::PrintfSpecifier &FS, 7389 const char *startSpecifier, 7390 unsigned specifierLen) { 7391 const analyze_printf::PrintfConversionSpecifier &CS = 7392 FS.getConversionSpecifier(); 7393 7394 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7395 getLocationOfByte(CS.getStart()), 7396 startSpecifier, specifierLen, 7397 CS.getStart(), CS.getLength()); 7398 } 7399 7400 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7401 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7402 } 7403 7404 bool CheckPrintfHandler::HandleAmount( 7405 const analyze_format_string::OptionalAmount &Amt, 7406 unsigned k, const char *startSpecifier, 7407 unsigned specifierLen) { 7408 if (Amt.hasDataArgument()) { 7409 if (!HasVAListArg) { 7410 unsigned argIndex = Amt.getArgIndex(); 7411 if (argIndex >= NumDataArgs) { 7412 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7413 << k, 7414 getLocationOfByte(Amt.getStart()), 7415 /*IsStringLocation*/true, 7416 getSpecifierRange(startSpecifier, specifierLen)); 7417 // Don't do any more checking. We will just emit 7418 // spurious errors. 7419 return false; 7420 } 7421 7422 // Type check the data argument. It should be an 'int'. 7423 // Although not in conformance with C99, we also allow the argument to be 7424 // an 'unsigned int' as that is a reasonably safe case. GCC also 7425 // doesn't emit a warning for that case. 7426 CoveredArgs.set(argIndex); 7427 const Expr *Arg = getDataArg(argIndex); 7428 if (!Arg) 7429 return false; 7430 7431 QualType T = Arg->getType(); 7432 7433 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7434 assert(AT.isValid()); 7435 7436 if (!AT.matchesType(S.Context, T)) { 7437 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7438 << k << AT.getRepresentativeTypeName(S.Context) 7439 << T << Arg->getSourceRange(), 7440 getLocationOfByte(Amt.getStart()), 7441 /*IsStringLocation*/true, 7442 getSpecifierRange(startSpecifier, specifierLen)); 7443 // Don't do any more checking. We will just emit 7444 // spurious errors. 7445 return false; 7446 } 7447 } 7448 } 7449 return true; 7450 } 7451 7452 void CheckPrintfHandler::HandleInvalidAmount( 7453 const analyze_printf::PrintfSpecifier &FS, 7454 const analyze_printf::OptionalAmount &Amt, 7455 unsigned type, 7456 const char *startSpecifier, 7457 unsigned specifierLen) { 7458 const analyze_printf::PrintfConversionSpecifier &CS = 7459 FS.getConversionSpecifier(); 7460 7461 FixItHint fixit = 7462 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7463 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7464 Amt.getConstantLength())) 7465 : FixItHint(); 7466 7467 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7468 << type << CS.toString(), 7469 getLocationOfByte(Amt.getStart()), 7470 /*IsStringLocation*/true, 7471 getSpecifierRange(startSpecifier, specifierLen), 7472 fixit); 7473 } 7474 7475 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7476 const analyze_printf::OptionalFlag &flag, 7477 const char *startSpecifier, 7478 unsigned specifierLen) { 7479 // Warn about pointless flag with a fixit removal. 7480 const analyze_printf::PrintfConversionSpecifier &CS = 7481 FS.getConversionSpecifier(); 7482 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7483 << flag.toString() << CS.toString(), 7484 getLocationOfByte(flag.getPosition()), 7485 /*IsStringLocation*/true, 7486 getSpecifierRange(startSpecifier, specifierLen), 7487 FixItHint::CreateRemoval( 7488 getSpecifierRange(flag.getPosition(), 1))); 7489 } 7490 7491 void CheckPrintfHandler::HandleIgnoredFlag( 7492 const analyze_printf::PrintfSpecifier &FS, 7493 const analyze_printf::OptionalFlag &ignoredFlag, 7494 const analyze_printf::OptionalFlag &flag, 7495 const char *startSpecifier, 7496 unsigned specifierLen) { 7497 // Warn about ignored flag with a fixit removal. 7498 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7499 << ignoredFlag.toString() << flag.toString(), 7500 getLocationOfByte(ignoredFlag.getPosition()), 7501 /*IsStringLocation*/true, 7502 getSpecifierRange(startSpecifier, specifierLen), 7503 FixItHint::CreateRemoval( 7504 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7505 } 7506 7507 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7508 unsigned flagLen) { 7509 // Warn about an empty flag. 7510 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7511 getLocationOfByte(startFlag), 7512 /*IsStringLocation*/true, 7513 getSpecifierRange(startFlag, flagLen)); 7514 } 7515 7516 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7517 unsigned flagLen) { 7518 // Warn about an invalid flag. 7519 auto Range = getSpecifierRange(startFlag, flagLen); 7520 StringRef flag(startFlag, flagLen); 7521 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7522 getLocationOfByte(startFlag), 7523 /*IsStringLocation*/true, 7524 Range, FixItHint::CreateRemoval(Range)); 7525 } 7526 7527 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7528 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7529 // Warn about using '[...]' without a '@' conversion. 7530 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7531 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7532 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7533 getLocationOfByte(conversionPosition), 7534 /*IsStringLocation*/true, 7535 Range, FixItHint::CreateRemoval(Range)); 7536 } 7537 7538 // Determines if the specified is a C++ class or struct containing 7539 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7540 // "c_str()"). 7541 template<typename MemberKind> 7542 static llvm::SmallPtrSet<MemberKind*, 1> 7543 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7544 const RecordType *RT = Ty->getAs<RecordType>(); 7545 llvm::SmallPtrSet<MemberKind*, 1> Results; 7546 7547 if (!RT) 7548 return Results; 7549 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7550 if (!RD || !RD->getDefinition()) 7551 return Results; 7552 7553 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7554 Sema::LookupMemberName); 7555 R.suppressDiagnostics(); 7556 7557 // We just need to include all members of the right kind turned up by the 7558 // filter, at this point. 7559 if (S.LookupQualifiedName(R, RT->getDecl())) 7560 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7561 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7562 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7563 Results.insert(FK); 7564 } 7565 return Results; 7566 } 7567 7568 /// Check if we could call '.c_str()' on an object. 7569 /// 7570 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7571 /// allow the call, or if it would be ambiguous). 7572 bool Sema::hasCStrMethod(const Expr *E) { 7573 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7574 7575 MethodSet Results = 7576 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7577 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7578 MI != ME; ++MI) 7579 if ((*MI)->getMinRequiredArguments() == 0) 7580 return true; 7581 return false; 7582 } 7583 7584 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7585 // better diagnostic if so. AT is assumed to be valid. 7586 // Returns true when a c_str() conversion method is found. 7587 bool CheckPrintfHandler::checkForCStrMembers( 7588 const analyze_printf::ArgType &AT, const Expr *E) { 7589 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7590 7591 MethodSet Results = 7592 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7593 7594 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7595 MI != ME; ++MI) { 7596 const CXXMethodDecl *Method = *MI; 7597 if (Method->getMinRequiredArguments() == 0 && 7598 AT.matchesType(S.Context, Method->getReturnType())) { 7599 // FIXME: Suggest parens if the expression needs them. 7600 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7601 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7602 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7603 return true; 7604 } 7605 } 7606 7607 return false; 7608 } 7609 7610 bool 7611 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7612 &FS, 7613 const char *startSpecifier, 7614 unsigned specifierLen) { 7615 using namespace analyze_format_string; 7616 using namespace analyze_printf; 7617 7618 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7619 7620 if (FS.consumesDataArgument()) { 7621 if (atFirstArg) { 7622 atFirstArg = false; 7623 usesPositionalArgs = FS.usesPositionalArg(); 7624 } 7625 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7626 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7627 startSpecifier, specifierLen); 7628 return false; 7629 } 7630 } 7631 7632 // First check if the field width, precision, and conversion specifier 7633 // have matching data arguments. 7634 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7635 startSpecifier, specifierLen)) { 7636 return false; 7637 } 7638 7639 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7640 startSpecifier, specifierLen)) { 7641 return false; 7642 } 7643 7644 if (!CS.consumesDataArgument()) { 7645 // FIXME: Technically specifying a precision or field width here 7646 // makes no sense. Worth issuing a warning at some point. 7647 return true; 7648 } 7649 7650 // Consume the argument. 7651 unsigned argIndex = FS.getArgIndex(); 7652 if (argIndex < NumDataArgs) { 7653 // The check to see if the argIndex is valid will come later. 7654 // We set the bit here because we may exit early from this 7655 // function if we encounter some other error. 7656 CoveredArgs.set(argIndex); 7657 } 7658 7659 // FreeBSD kernel extensions. 7660 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7661 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7662 // We need at least two arguments. 7663 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7664 return false; 7665 7666 // Claim the second argument. 7667 CoveredArgs.set(argIndex + 1); 7668 7669 // Type check the first argument (int for %b, pointer for %D) 7670 const Expr *Ex = getDataArg(argIndex); 7671 const analyze_printf::ArgType &AT = 7672 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7673 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7674 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7675 EmitFormatDiagnostic( 7676 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7677 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7678 << false << Ex->getSourceRange(), 7679 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7680 getSpecifierRange(startSpecifier, specifierLen)); 7681 7682 // Type check the second argument (char * for both %b and %D) 7683 Ex = getDataArg(argIndex + 1); 7684 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7685 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7686 EmitFormatDiagnostic( 7687 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7688 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7689 << false << Ex->getSourceRange(), 7690 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7691 getSpecifierRange(startSpecifier, specifierLen)); 7692 7693 return true; 7694 } 7695 7696 // Check for using an Objective-C specific conversion specifier 7697 // in a non-ObjC literal. 7698 if (!allowsObjCArg() && CS.isObjCArg()) { 7699 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7700 specifierLen); 7701 } 7702 7703 // %P can only be used with os_log. 7704 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7705 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7706 specifierLen); 7707 } 7708 7709 // %n is not allowed with os_log. 7710 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7711 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7712 getLocationOfByte(CS.getStart()), 7713 /*IsStringLocation*/ false, 7714 getSpecifierRange(startSpecifier, specifierLen)); 7715 7716 return true; 7717 } 7718 7719 // Only scalars are allowed for os_trace. 7720 if (FSType == Sema::FST_OSTrace && 7721 (CS.getKind() == ConversionSpecifier::PArg || 7722 CS.getKind() == ConversionSpecifier::sArg || 7723 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7724 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7725 specifierLen); 7726 } 7727 7728 // Check for use of public/private annotation outside of os_log(). 7729 if (FSType != Sema::FST_OSLog) { 7730 if (FS.isPublic().isSet()) { 7731 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7732 << "public", 7733 getLocationOfByte(FS.isPublic().getPosition()), 7734 /*IsStringLocation*/ false, 7735 getSpecifierRange(startSpecifier, specifierLen)); 7736 } 7737 if (FS.isPrivate().isSet()) { 7738 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7739 << "private", 7740 getLocationOfByte(FS.isPrivate().getPosition()), 7741 /*IsStringLocation*/ false, 7742 getSpecifierRange(startSpecifier, specifierLen)); 7743 } 7744 } 7745 7746 // Check for invalid use of field width 7747 if (!FS.hasValidFieldWidth()) { 7748 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7749 startSpecifier, specifierLen); 7750 } 7751 7752 // Check for invalid use of precision 7753 if (!FS.hasValidPrecision()) { 7754 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7755 startSpecifier, specifierLen); 7756 } 7757 7758 // Precision is mandatory for %P specifier. 7759 if (CS.getKind() == ConversionSpecifier::PArg && 7760 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7761 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7762 getLocationOfByte(startSpecifier), 7763 /*IsStringLocation*/ false, 7764 getSpecifierRange(startSpecifier, specifierLen)); 7765 } 7766 7767 // Check each flag does not conflict with any other component. 7768 if (!FS.hasValidThousandsGroupingPrefix()) 7769 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7770 if (!FS.hasValidLeadingZeros()) 7771 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7772 if (!FS.hasValidPlusPrefix()) 7773 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7774 if (!FS.hasValidSpacePrefix()) 7775 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7776 if (!FS.hasValidAlternativeForm()) 7777 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7778 if (!FS.hasValidLeftJustified()) 7779 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 7780 7781 // Check that flags are not ignored by another flag 7782 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 7783 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 7784 startSpecifier, specifierLen); 7785 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 7786 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 7787 startSpecifier, specifierLen); 7788 7789 // Check the length modifier is valid with the given conversion specifier. 7790 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 7791 S.getLangOpts())) 7792 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7793 diag::warn_format_nonsensical_length); 7794 else if (!FS.hasStandardLengthModifier()) 7795 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 7796 else if (!FS.hasStandardLengthConversionCombination()) 7797 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 7798 diag::warn_format_non_standard_conversion_spec); 7799 7800 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 7801 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 7802 7803 // The remaining checks depend on the data arguments. 7804 if (HasVAListArg) 7805 return true; 7806 7807 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 7808 return false; 7809 7810 const Expr *Arg = getDataArg(argIndex); 7811 if (!Arg) 7812 return true; 7813 7814 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 7815 } 7816 7817 static bool requiresParensToAddCast(const Expr *E) { 7818 // FIXME: We should have a general way to reason about operator 7819 // precedence and whether parens are actually needed here. 7820 // Take care of a few common cases where they aren't. 7821 const Expr *Inside = E->IgnoreImpCasts(); 7822 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 7823 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 7824 7825 switch (Inside->getStmtClass()) { 7826 case Stmt::ArraySubscriptExprClass: 7827 case Stmt::CallExprClass: 7828 case Stmt::CharacterLiteralClass: 7829 case Stmt::CXXBoolLiteralExprClass: 7830 case Stmt::DeclRefExprClass: 7831 case Stmt::FloatingLiteralClass: 7832 case Stmt::IntegerLiteralClass: 7833 case Stmt::MemberExprClass: 7834 case Stmt::ObjCArrayLiteralClass: 7835 case Stmt::ObjCBoolLiteralExprClass: 7836 case Stmt::ObjCBoxedExprClass: 7837 case Stmt::ObjCDictionaryLiteralClass: 7838 case Stmt::ObjCEncodeExprClass: 7839 case Stmt::ObjCIvarRefExprClass: 7840 case Stmt::ObjCMessageExprClass: 7841 case Stmt::ObjCPropertyRefExprClass: 7842 case Stmt::ObjCStringLiteralClass: 7843 case Stmt::ObjCSubscriptRefExprClass: 7844 case Stmt::ParenExprClass: 7845 case Stmt::StringLiteralClass: 7846 case Stmt::UnaryOperatorClass: 7847 return false; 7848 default: 7849 return true; 7850 } 7851 } 7852 7853 static std::pair<QualType, StringRef> 7854 shouldNotPrintDirectly(const ASTContext &Context, 7855 QualType IntendedTy, 7856 const Expr *E) { 7857 // Use a 'while' to peel off layers of typedefs. 7858 QualType TyTy = IntendedTy; 7859 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 7860 StringRef Name = UserTy->getDecl()->getName(); 7861 QualType CastTy = llvm::StringSwitch<QualType>(Name) 7862 .Case("CFIndex", Context.getNSIntegerType()) 7863 .Case("NSInteger", Context.getNSIntegerType()) 7864 .Case("NSUInteger", Context.getNSUIntegerType()) 7865 .Case("SInt32", Context.IntTy) 7866 .Case("UInt32", Context.UnsignedIntTy) 7867 .Default(QualType()); 7868 7869 if (!CastTy.isNull()) 7870 return std::make_pair(CastTy, Name); 7871 7872 TyTy = UserTy->desugar(); 7873 } 7874 7875 // Strip parens if necessary. 7876 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 7877 return shouldNotPrintDirectly(Context, 7878 PE->getSubExpr()->getType(), 7879 PE->getSubExpr()); 7880 7881 // If this is a conditional expression, then its result type is constructed 7882 // via usual arithmetic conversions and thus there might be no necessary 7883 // typedef sugar there. Recurse to operands to check for NSInteger & 7884 // Co. usage condition. 7885 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 7886 QualType TrueTy, FalseTy; 7887 StringRef TrueName, FalseName; 7888 7889 std::tie(TrueTy, TrueName) = 7890 shouldNotPrintDirectly(Context, 7891 CO->getTrueExpr()->getType(), 7892 CO->getTrueExpr()); 7893 std::tie(FalseTy, FalseName) = 7894 shouldNotPrintDirectly(Context, 7895 CO->getFalseExpr()->getType(), 7896 CO->getFalseExpr()); 7897 7898 if (TrueTy == FalseTy) 7899 return std::make_pair(TrueTy, TrueName); 7900 else if (TrueTy.isNull()) 7901 return std::make_pair(FalseTy, FalseName); 7902 else if (FalseTy.isNull()) 7903 return std::make_pair(TrueTy, TrueName); 7904 } 7905 7906 return std::make_pair(QualType(), StringRef()); 7907 } 7908 7909 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 7910 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 7911 /// type do not count. 7912 static bool 7913 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 7914 QualType From = ICE->getSubExpr()->getType(); 7915 QualType To = ICE->getType(); 7916 // It's an integer promotion if the destination type is the promoted 7917 // source type. 7918 if (ICE->getCastKind() == CK_IntegralCast && 7919 From->isPromotableIntegerType() && 7920 S.Context.getPromotedIntegerType(From) == To) 7921 return true; 7922 // Look through vector types, since we do default argument promotion for 7923 // those in OpenCL. 7924 if (const auto *VecTy = From->getAs<ExtVectorType>()) 7925 From = VecTy->getElementType(); 7926 if (const auto *VecTy = To->getAs<ExtVectorType>()) 7927 To = VecTy->getElementType(); 7928 // It's a floating promotion if the source type is a lower rank. 7929 return ICE->getCastKind() == CK_FloatingCast && 7930 S.Context.getFloatingTypeOrder(From, To) < 0; 7931 } 7932 7933 bool 7934 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7935 const char *StartSpecifier, 7936 unsigned SpecifierLen, 7937 const Expr *E) { 7938 using namespace analyze_format_string; 7939 using namespace analyze_printf; 7940 7941 // Now type check the data expression that matches the 7942 // format specifier. 7943 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 7944 if (!AT.isValid()) 7945 return true; 7946 7947 QualType ExprTy = E->getType(); 7948 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 7949 ExprTy = TET->getUnderlyingExpr()->getType(); 7950 } 7951 7952 // Diagnose attempts to print a boolean value as a character. Unlike other 7953 // -Wformat diagnostics, this is fine from a type perspective, but it still 7954 // doesn't make sense. 7955 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 7956 E->isKnownToHaveBooleanValue()) { 7957 const CharSourceRange &CSR = 7958 getSpecifierRange(StartSpecifier, SpecifierLen); 7959 SmallString<4> FSString; 7960 llvm::raw_svector_ostream os(FSString); 7961 FS.toString(os); 7962 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 7963 << FSString, 7964 E->getExprLoc(), false, CSR); 7965 return true; 7966 } 7967 7968 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 7969 if (Match == analyze_printf::ArgType::Match) 7970 return true; 7971 7972 // Look through argument promotions for our error message's reported type. 7973 // This includes the integral and floating promotions, but excludes array 7974 // and function pointer decay (seeing that an argument intended to be a 7975 // string has type 'char [6]' is probably more confusing than 'char *') and 7976 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 7977 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 7978 if (isArithmeticArgumentPromotion(S, ICE)) { 7979 E = ICE->getSubExpr(); 7980 ExprTy = E->getType(); 7981 7982 // Check if we didn't match because of an implicit cast from a 'char' 7983 // or 'short' to an 'int'. This is done because printf is a varargs 7984 // function. 7985 if (ICE->getType() == S.Context.IntTy || 7986 ICE->getType() == S.Context.UnsignedIntTy) { 7987 // All further checking is done on the subexpression 7988 const analyze_printf::ArgType::MatchKind ImplicitMatch = 7989 AT.matchesType(S.Context, ExprTy); 7990 if (ImplicitMatch == analyze_printf::ArgType::Match) 7991 return true; 7992 if (ImplicitMatch == ArgType::NoMatchPedantic || 7993 ImplicitMatch == ArgType::NoMatchTypeConfusion) 7994 Match = ImplicitMatch; 7995 } 7996 } 7997 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 7998 // Special case for 'a', which has type 'int' in C. 7999 // Note, however, that we do /not/ want to treat multibyte constants like 8000 // 'MooV' as characters! This form is deprecated but still exists. 8001 if (ExprTy == S.Context.IntTy) 8002 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8003 ExprTy = S.Context.CharTy; 8004 } 8005 8006 // Look through enums to their underlying type. 8007 bool IsEnum = false; 8008 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8009 ExprTy = EnumTy->getDecl()->getIntegerType(); 8010 IsEnum = true; 8011 } 8012 8013 // %C in an Objective-C context prints a unichar, not a wchar_t. 8014 // If the argument is an integer of some kind, believe the %C and suggest 8015 // a cast instead of changing the conversion specifier. 8016 QualType IntendedTy = ExprTy; 8017 if (isObjCContext() && 8018 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8019 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8020 !ExprTy->isCharType()) { 8021 // 'unichar' is defined as a typedef of unsigned short, but we should 8022 // prefer using the typedef if it is visible. 8023 IntendedTy = S.Context.UnsignedShortTy; 8024 8025 // While we are here, check if the value is an IntegerLiteral that happens 8026 // to be within the valid range. 8027 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8028 const llvm::APInt &V = IL->getValue(); 8029 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8030 return true; 8031 } 8032 8033 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8034 Sema::LookupOrdinaryName); 8035 if (S.LookupName(Result, S.getCurScope())) { 8036 NamedDecl *ND = Result.getFoundDecl(); 8037 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8038 if (TD->getUnderlyingType() == IntendedTy) 8039 IntendedTy = S.Context.getTypedefType(TD); 8040 } 8041 } 8042 } 8043 8044 // Special-case some of Darwin's platform-independence types by suggesting 8045 // casts to primitive types that are known to be large enough. 8046 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8047 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8048 QualType CastTy; 8049 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8050 if (!CastTy.isNull()) { 8051 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8052 // (long in ASTContext). Only complain to pedants. 8053 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8054 (AT.isSizeT() || AT.isPtrdiffT()) && 8055 AT.matchesType(S.Context, CastTy)) 8056 Match = ArgType::NoMatchPedantic; 8057 IntendedTy = CastTy; 8058 ShouldNotPrintDirectly = true; 8059 } 8060 } 8061 8062 // We may be able to offer a FixItHint if it is a supported type. 8063 PrintfSpecifier fixedFS = FS; 8064 bool Success = 8065 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8066 8067 if (Success) { 8068 // Get the fix string from the fixed format specifier 8069 SmallString<16> buf; 8070 llvm::raw_svector_ostream os(buf); 8071 fixedFS.toString(os); 8072 8073 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8074 8075 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8076 unsigned Diag; 8077 switch (Match) { 8078 case ArgType::Match: llvm_unreachable("expected non-matching"); 8079 case ArgType::NoMatchPedantic: 8080 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8081 break; 8082 case ArgType::NoMatchTypeConfusion: 8083 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8084 break; 8085 case ArgType::NoMatch: 8086 Diag = diag::warn_format_conversion_argument_type_mismatch; 8087 break; 8088 } 8089 8090 // In this case, the specifier is wrong and should be changed to match 8091 // the argument. 8092 EmitFormatDiagnostic(S.PDiag(Diag) 8093 << AT.getRepresentativeTypeName(S.Context) 8094 << IntendedTy << IsEnum << E->getSourceRange(), 8095 E->getBeginLoc(), 8096 /*IsStringLocation*/ false, SpecRange, 8097 FixItHint::CreateReplacement(SpecRange, os.str())); 8098 } else { 8099 // The canonical type for formatting this value is different from the 8100 // actual type of the expression. (This occurs, for example, with Darwin's 8101 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8102 // should be printed as 'long' for 64-bit compatibility.) 8103 // Rather than emitting a normal format/argument mismatch, we want to 8104 // add a cast to the recommended type (and correct the format string 8105 // if necessary). 8106 SmallString<16> CastBuf; 8107 llvm::raw_svector_ostream CastFix(CastBuf); 8108 CastFix << "("; 8109 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8110 CastFix << ")"; 8111 8112 SmallVector<FixItHint,4> Hints; 8113 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8114 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8115 8116 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8117 // If there's already a cast present, just replace it. 8118 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8119 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8120 8121 } else if (!requiresParensToAddCast(E)) { 8122 // If the expression has high enough precedence, 8123 // just write the C-style cast. 8124 Hints.push_back( 8125 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8126 } else { 8127 // Otherwise, add parens around the expression as well as the cast. 8128 CastFix << "("; 8129 Hints.push_back( 8130 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8131 8132 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8133 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8134 } 8135 8136 if (ShouldNotPrintDirectly) { 8137 // The expression has a type that should not be printed directly. 8138 // We extract the name from the typedef because we don't want to show 8139 // the underlying type in the diagnostic. 8140 StringRef Name; 8141 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8142 Name = TypedefTy->getDecl()->getName(); 8143 else 8144 Name = CastTyName; 8145 unsigned Diag = Match == ArgType::NoMatchPedantic 8146 ? diag::warn_format_argument_needs_cast_pedantic 8147 : diag::warn_format_argument_needs_cast; 8148 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8149 << E->getSourceRange(), 8150 E->getBeginLoc(), /*IsStringLocation=*/false, 8151 SpecRange, Hints); 8152 } else { 8153 // In this case, the expression could be printed using a different 8154 // specifier, but we've decided that the specifier is probably correct 8155 // and we should cast instead. Just use the normal warning message. 8156 EmitFormatDiagnostic( 8157 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8158 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8159 << E->getSourceRange(), 8160 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8161 } 8162 } 8163 } else { 8164 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8165 SpecifierLen); 8166 // Since the warning for passing non-POD types to variadic functions 8167 // was deferred until now, we emit a warning for non-POD 8168 // arguments here. 8169 switch (S.isValidVarArgType(ExprTy)) { 8170 case Sema::VAK_Valid: 8171 case Sema::VAK_ValidInCXX11: { 8172 unsigned Diag; 8173 switch (Match) { 8174 case ArgType::Match: llvm_unreachable("expected non-matching"); 8175 case ArgType::NoMatchPedantic: 8176 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8177 break; 8178 case ArgType::NoMatchTypeConfusion: 8179 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8180 break; 8181 case ArgType::NoMatch: 8182 Diag = diag::warn_format_conversion_argument_type_mismatch; 8183 break; 8184 } 8185 8186 EmitFormatDiagnostic( 8187 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8188 << IsEnum << CSR << E->getSourceRange(), 8189 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8190 break; 8191 } 8192 case Sema::VAK_Undefined: 8193 case Sema::VAK_MSVCUndefined: 8194 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8195 << S.getLangOpts().CPlusPlus11 << ExprTy 8196 << CallType 8197 << AT.getRepresentativeTypeName(S.Context) << CSR 8198 << E->getSourceRange(), 8199 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8200 checkForCStrMembers(AT, E); 8201 break; 8202 8203 case Sema::VAK_Invalid: 8204 if (ExprTy->isObjCObjectType()) 8205 EmitFormatDiagnostic( 8206 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8207 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8208 << AT.getRepresentativeTypeName(S.Context) << CSR 8209 << E->getSourceRange(), 8210 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8211 else 8212 // FIXME: If this is an initializer list, suggest removing the braces 8213 // or inserting a cast to the target type. 8214 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8215 << isa<InitListExpr>(E) << ExprTy << CallType 8216 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8217 break; 8218 } 8219 8220 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8221 "format string specifier index out of range"); 8222 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8223 } 8224 8225 return true; 8226 } 8227 8228 //===--- CHECK: Scanf format string checking ------------------------------===// 8229 8230 namespace { 8231 8232 class CheckScanfHandler : public CheckFormatHandler { 8233 public: 8234 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8235 const Expr *origFormatExpr, Sema::FormatStringType type, 8236 unsigned firstDataArg, unsigned numDataArgs, 8237 const char *beg, bool hasVAListArg, 8238 ArrayRef<const Expr *> Args, unsigned formatIdx, 8239 bool inFunctionCall, Sema::VariadicCallType CallType, 8240 llvm::SmallBitVector &CheckedVarArgs, 8241 UncoveredArgHandler &UncoveredArg) 8242 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8243 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8244 inFunctionCall, CallType, CheckedVarArgs, 8245 UncoveredArg) {} 8246 8247 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8248 const char *startSpecifier, 8249 unsigned specifierLen) override; 8250 8251 bool HandleInvalidScanfConversionSpecifier( 8252 const analyze_scanf::ScanfSpecifier &FS, 8253 const char *startSpecifier, 8254 unsigned specifierLen) override; 8255 8256 void HandleIncompleteScanList(const char *start, const char *end) override; 8257 }; 8258 8259 } // namespace 8260 8261 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8262 const char *end) { 8263 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8264 getLocationOfByte(end), /*IsStringLocation*/true, 8265 getSpecifierRange(start, end - start)); 8266 } 8267 8268 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8269 const analyze_scanf::ScanfSpecifier &FS, 8270 const char *startSpecifier, 8271 unsigned specifierLen) { 8272 const analyze_scanf::ScanfConversionSpecifier &CS = 8273 FS.getConversionSpecifier(); 8274 8275 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8276 getLocationOfByte(CS.getStart()), 8277 startSpecifier, specifierLen, 8278 CS.getStart(), CS.getLength()); 8279 } 8280 8281 bool CheckScanfHandler::HandleScanfSpecifier( 8282 const analyze_scanf::ScanfSpecifier &FS, 8283 const char *startSpecifier, 8284 unsigned specifierLen) { 8285 using namespace analyze_scanf; 8286 using namespace analyze_format_string; 8287 8288 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8289 8290 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8291 // be used to decide if we are using positional arguments consistently. 8292 if (FS.consumesDataArgument()) { 8293 if (atFirstArg) { 8294 atFirstArg = false; 8295 usesPositionalArgs = FS.usesPositionalArg(); 8296 } 8297 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8298 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8299 startSpecifier, specifierLen); 8300 return false; 8301 } 8302 } 8303 8304 // Check if the field with is non-zero. 8305 const OptionalAmount &Amt = FS.getFieldWidth(); 8306 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8307 if (Amt.getConstantAmount() == 0) { 8308 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8309 Amt.getConstantLength()); 8310 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8311 getLocationOfByte(Amt.getStart()), 8312 /*IsStringLocation*/true, R, 8313 FixItHint::CreateRemoval(R)); 8314 } 8315 } 8316 8317 if (!FS.consumesDataArgument()) { 8318 // FIXME: Technically specifying a precision or field width here 8319 // makes no sense. Worth issuing a warning at some point. 8320 return true; 8321 } 8322 8323 // Consume the argument. 8324 unsigned argIndex = FS.getArgIndex(); 8325 if (argIndex < NumDataArgs) { 8326 // The check to see if the argIndex is valid will come later. 8327 // We set the bit here because we may exit early from this 8328 // function if we encounter some other error. 8329 CoveredArgs.set(argIndex); 8330 } 8331 8332 // Check the length modifier is valid with the given conversion specifier. 8333 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8334 S.getLangOpts())) 8335 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8336 diag::warn_format_nonsensical_length); 8337 else if (!FS.hasStandardLengthModifier()) 8338 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8339 else if (!FS.hasStandardLengthConversionCombination()) 8340 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8341 diag::warn_format_non_standard_conversion_spec); 8342 8343 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8344 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8345 8346 // The remaining checks depend on the data arguments. 8347 if (HasVAListArg) 8348 return true; 8349 8350 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8351 return false; 8352 8353 // Check that the argument type matches the format specifier. 8354 const Expr *Ex = getDataArg(argIndex); 8355 if (!Ex) 8356 return true; 8357 8358 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8359 8360 if (!AT.isValid()) { 8361 return true; 8362 } 8363 8364 analyze_format_string::ArgType::MatchKind Match = 8365 AT.matchesType(S.Context, Ex->getType()); 8366 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8367 if (Match == analyze_format_string::ArgType::Match) 8368 return true; 8369 8370 ScanfSpecifier fixedFS = FS; 8371 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8372 S.getLangOpts(), S.Context); 8373 8374 unsigned Diag = 8375 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8376 : diag::warn_format_conversion_argument_type_mismatch; 8377 8378 if (Success) { 8379 // Get the fix string from the fixed format specifier. 8380 SmallString<128> buf; 8381 llvm::raw_svector_ostream os(buf); 8382 fixedFS.toString(os); 8383 8384 EmitFormatDiagnostic( 8385 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8386 << Ex->getType() << false << Ex->getSourceRange(), 8387 Ex->getBeginLoc(), 8388 /*IsStringLocation*/ false, 8389 getSpecifierRange(startSpecifier, specifierLen), 8390 FixItHint::CreateReplacement( 8391 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8392 } else { 8393 EmitFormatDiagnostic(S.PDiag(Diag) 8394 << AT.getRepresentativeTypeName(S.Context) 8395 << Ex->getType() << false << Ex->getSourceRange(), 8396 Ex->getBeginLoc(), 8397 /*IsStringLocation*/ false, 8398 getSpecifierRange(startSpecifier, specifierLen)); 8399 } 8400 8401 return true; 8402 } 8403 8404 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8405 const Expr *OrigFormatExpr, 8406 ArrayRef<const Expr *> Args, 8407 bool HasVAListArg, unsigned format_idx, 8408 unsigned firstDataArg, 8409 Sema::FormatStringType Type, 8410 bool inFunctionCall, 8411 Sema::VariadicCallType CallType, 8412 llvm::SmallBitVector &CheckedVarArgs, 8413 UncoveredArgHandler &UncoveredArg, 8414 bool IgnoreStringsWithoutSpecifiers) { 8415 // CHECK: is the format string a wide literal? 8416 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8417 CheckFormatHandler::EmitFormatDiagnostic( 8418 S, inFunctionCall, Args[format_idx], 8419 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8420 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8421 return; 8422 } 8423 8424 // Str - The format string. NOTE: this is NOT null-terminated! 8425 StringRef StrRef = FExpr->getString(); 8426 const char *Str = StrRef.data(); 8427 // Account for cases where the string literal is truncated in a declaration. 8428 const ConstantArrayType *T = 8429 S.Context.getAsConstantArrayType(FExpr->getType()); 8430 assert(T && "String literal not of constant array type!"); 8431 size_t TypeSize = T->getSize().getZExtValue(); 8432 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8433 const unsigned numDataArgs = Args.size() - firstDataArg; 8434 8435 if (IgnoreStringsWithoutSpecifiers && 8436 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8437 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8438 return; 8439 8440 // Emit a warning if the string literal is truncated and does not contain an 8441 // embedded null character. 8442 if (TypeSize <= StrRef.size() && 8443 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8444 CheckFormatHandler::EmitFormatDiagnostic( 8445 S, inFunctionCall, Args[format_idx], 8446 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8447 FExpr->getBeginLoc(), 8448 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8449 return; 8450 } 8451 8452 // CHECK: empty format string? 8453 if (StrLen == 0 && numDataArgs > 0) { 8454 CheckFormatHandler::EmitFormatDiagnostic( 8455 S, inFunctionCall, Args[format_idx], 8456 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8457 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8458 return; 8459 } 8460 8461 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8462 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8463 Type == Sema::FST_OSTrace) { 8464 CheckPrintfHandler H( 8465 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8466 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8467 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8468 CheckedVarArgs, UncoveredArg); 8469 8470 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8471 S.getLangOpts(), 8472 S.Context.getTargetInfo(), 8473 Type == Sema::FST_FreeBSDKPrintf)) 8474 H.DoneProcessing(); 8475 } else if (Type == Sema::FST_Scanf) { 8476 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8477 numDataArgs, Str, HasVAListArg, Args, format_idx, 8478 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8479 8480 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8481 S.getLangOpts(), 8482 S.Context.getTargetInfo())) 8483 H.DoneProcessing(); 8484 } // TODO: handle other formats 8485 } 8486 8487 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8488 // Str - The format string. NOTE: this is NOT null-terminated! 8489 StringRef StrRef = FExpr->getString(); 8490 const char *Str = StrRef.data(); 8491 // Account for cases where the string literal is truncated in a declaration. 8492 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8493 assert(T && "String literal not of constant array type!"); 8494 size_t TypeSize = T->getSize().getZExtValue(); 8495 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8496 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8497 getLangOpts(), 8498 Context.getTargetInfo()); 8499 } 8500 8501 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8502 8503 // Returns the related absolute value function that is larger, of 0 if one 8504 // does not exist. 8505 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8506 switch (AbsFunction) { 8507 default: 8508 return 0; 8509 8510 case Builtin::BI__builtin_abs: 8511 return Builtin::BI__builtin_labs; 8512 case Builtin::BI__builtin_labs: 8513 return Builtin::BI__builtin_llabs; 8514 case Builtin::BI__builtin_llabs: 8515 return 0; 8516 8517 case Builtin::BI__builtin_fabsf: 8518 return Builtin::BI__builtin_fabs; 8519 case Builtin::BI__builtin_fabs: 8520 return Builtin::BI__builtin_fabsl; 8521 case Builtin::BI__builtin_fabsl: 8522 return 0; 8523 8524 case Builtin::BI__builtin_cabsf: 8525 return Builtin::BI__builtin_cabs; 8526 case Builtin::BI__builtin_cabs: 8527 return Builtin::BI__builtin_cabsl; 8528 case Builtin::BI__builtin_cabsl: 8529 return 0; 8530 8531 case Builtin::BIabs: 8532 return Builtin::BIlabs; 8533 case Builtin::BIlabs: 8534 return Builtin::BIllabs; 8535 case Builtin::BIllabs: 8536 return 0; 8537 8538 case Builtin::BIfabsf: 8539 return Builtin::BIfabs; 8540 case Builtin::BIfabs: 8541 return Builtin::BIfabsl; 8542 case Builtin::BIfabsl: 8543 return 0; 8544 8545 case Builtin::BIcabsf: 8546 return Builtin::BIcabs; 8547 case Builtin::BIcabs: 8548 return Builtin::BIcabsl; 8549 case Builtin::BIcabsl: 8550 return 0; 8551 } 8552 } 8553 8554 // Returns the argument type of the absolute value function. 8555 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8556 unsigned AbsType) { 8557 if (AbsType == 0) 8558 return QualType(); 8559 8560 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8561 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8562 if (Error != ASTContext::GE_None) 8563 return QualType(); 8564 8565 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8566 if (!FT) 8567 return QualType(); 8568 8569 if (FT->getNumParams() != 1) 8570 return QualType(); 8571 8572 return FT->getParamType(0); 8573 } 8574 8575 // Returns the best absolute value function, or zero, based on type and 8576 // current absolute value function. 8577 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8578 unsigned AbsFunctionKind) { 8579 unsigned BestKind = 0; 8580 uint64_t ArgSize = Context.getTypeSize(ArgType); 8581 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8582 Kind = getLargerAbsoluteValueFunction(Kind)) { 8583 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8584 if (Context.getTypeSize(ParamType) >= ArgSize) { 8585 if (BestKind == 0) 8586 BestKind = Kind; 8587 else if (Context.hasSameType(ParamType, ArgType)) { 8588 BestKind = Kind; 8589 break; 8590 } 8591 } 8592 } 8593 return BestKind; 8594 } 8595 8596 enum AbsoluteValueKind { 8597 AVK_Integer, 8598 AVK_Floating, 8599 AVK_Complex 8600 }; 8601 8602 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8603 if (T->isIntegralOrEnumerationType()) 8604 return AVK_Integer; 8605 if (T->isRealFloatingType()) 8606 return AVK_Floating; 8607 if (T->isAnyComplexType()) 8608 return AVK_Complex; 8609 8610 llvm_unreachable("Type not integer, floating, or complex"); 8611 } 8612 8613 // Changes the absolute value function to a different type. Preserves whether 8614 // the function is a builtin. 8615 static unsigned changeAbsFunction(unsigned AbsKind, 8616 AbsoluteValueKind ValueKind) { 8617 switch (ValueKind) { 8618 case AVK_Integer: 8619 switch (AbsKind) { 8620 default: 8621 return 0; 8622 case Builtin::BI__builtin_fabsf: 8623 case Builtin::BI__builtin_fabs: 8624 case Builtin::BI__builtin_fabsl: 8625 case Builtin::BI__builtin_cabsf: 8626 case Builtin::BI__builtin_cabs: 8627 case Builtin::BI__builtin_cabsl: 8628 return Builtin::BI__builtin_abs; 8629 case Builtin::BIfabsf: 8630 case Builtin::BIfabs: 8631 case Builtin::BIfabsl: 8632 case Builtin::BIcabsf: 8633 case Builtin::BIcabs: 8634 case Builtin::BIcabsl: 8635 return Builtin::BIabs; 8636 } 8637 case AVK_Floating: 8638 switch (AbsKind) { 8639 default: 8640 return 0; 8641 case Builtin::BI__builtin_abs: 8642 case Builtin::BI__builtin_labs: 8643 case Builtin::BI__builtin_llabs: 8644 case Builtin::BI__builtin_cabsf: 8645 case Builtin::BI__builtin_cabs: 8646 case Builtin::BI__builtin_cabsl: 8647 return Builtin::BI__builtin_fabsf; 8648 case Builtin::BIabs: 8649 case Builtin::BIlabs: 8650 case Builtin::BIllabs: 8651 case Builtin::BIcabsf: 8652 case Builtin::BIcabs: 8653 case Builtin::BIcabsl: 8654 return Builtin::BIfabsf; 8655 } 8656 case AVK_Complex: 8657 switch (AbsKind) { 8658 default: 8659 return 0; 8660 case Builtin::BI__builtin_abs: 8661 case Builtin::BI__builtin_labs: 8662 case Builtin::BI__builtin_llabs: 8663 case Builtin::BI__builtin_fabsf: 8664 case Builtin::BI__builtin_fabs: 8665 case Builtin::BI__builtin_fabsl: 8666 return Builtin::BI__builtin_cabsf; 8667 case Builtin::BIabs: 8668 case Builtin::BIlabs: 8669 case Builtin::BIllabs: 8670 case Builtin::BIfabsf: 8671 case Builtin::BIfabs: 8672 case Builtin::BIfabsl: 8673 return Builtin::BIcabsf; 8674 } 8675 } 8676 llvm_unreachable("Unable to convert function"); 8677 } 8678 8679 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8680 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8681 if (!FnInfo) 8682 return 0; 8683 8684 switch (FDecl->getBuiltinID()) { 8685 default: 8686 return 0; 8687 case Builtin::BI__builtin_abs: 8688 case Builtin::BI__builtin_fabs: 8689 case Builtin::BI__builtin_fabsf: 8690 case Builtin::BI__builtin_fabsl: 8691 case Builtin::BI__builtin_labs: 8692 case Builtin::BI__builtin_llabs: 8693 case Builtin::BI__builtin_cabs: 8694 case Builtin::BI__builtin_cabsf: 8695 case Builtin::BI__builtin_cabsl: 8696 case Builtin::BIabs: 8697 case Builtin::BIlabs: 8698 case Builtin::BIllabs: 8699 case Builtin::BIfabs: 8700 case Builtin::BIfabsf: 8701 case Builtin::BIfabsl: 8702 case Builtin::BIcabs: 8703 case Builtin::BIcabsf: 8704 case Builtin::BIcabsl: 8705 return FDecl->getBuiltinID(); 8706 } 8707 llvm_unreachable("Unknown Builtin type"); 8708 } 8709 8710 // If the replacement is valid, emit a note with replacement function. 8711 // Additionally, suggest including the proper header if not already included. 8712 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8713 unsigned AbsKind, QualType ArgType) { 8714 bool EmitHeaderHint = true; 8715 const char *HeaderName = nullptr; 8716 const char *FunctionName = nullptr; 8717 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8718 FunctionName = "std::abs"; 8719 if (ArgType->isIntegralOrEnumerationType()) { 8720 HeaderName = "cstdlib"; 8721 } else if (ArgType->isRealFloatingType()) { 8722 HeaderName = "cmath"; 8723 } else { 8724 llvm_unreachable("Invalid Type"); 8725 } 8726 8727 // Lookup all std::abs 8728 if (NamespaceDecl *Std = S.getStdNamespace()) { 8729 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8730 R.suppressDiagnostics(); 8731 S.LookupQualifiedName(R, Std); 8732 8733 for (const auto *I : R) { 8734 const FunctionDecl *FDecl = nullptr; 8735 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8736 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8737 } else { 8738 FDecl = dyn_cast<FunctionDecl>(I); 8739 } 8740 if (!FDecl) 8741 continue; 8742 8743 // Found std::abs(), check that they are the right ones. 8744 if (FDecl->getNumParams() != 1) 8745 continue; 8746 8747 // Check that the parameter type can handle the argument. 8748 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8749 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8750 S.Context.getTypeSize(ArgType) <= 8751 S.Context.getTypeSize(ParamType)) { 8752 // Found a function, don't need the header hint. 8753 EmitHeaderHint = false; 8754 break; 8755 } 8756 } 8757 } 8758 } else { 8759 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8760 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8761 8762 if (HeaderName) { 8763 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8764 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8765 R.suppressDiagnostics(); 8766 S.LookupName(R, S.getCurScope()); 8767 8768 if (R.isSingleResult()) { 8769 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8770 if (FD && FD->getBuiltinID() == AbsKind) { 8771 EmitHeaderHint = false; 8772 } else { 8773 return; 8774 } 8775 } else if (!R.empty()) { 8776 return; 8777 } 8778 } 8779 } 8780 8781 S.Diag(Loc, diag::note_replace_abs_function) 8782 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 8783 8784 if (!HeaderName) 8785 return; 8786 8787 if (!EmitHeaderHint) 8788 return; 8789 8790 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 8791 << FunctionName; 8792 } 8793 8794 template <std::size_t StrLen> 8795 static bool IsStdFunction(const FunctionDecl *FDecl, 8796 const char (&Str)[StrLen]) { 8797 if (!FDecl) 8798 return false; 8799 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 8800 return false; 8801 if (!FDecl->isInStdNamespace()) 8802 return false; 8803 8804 return true; 8805 } 8806 8807 // Warn when using the wrong abs() function. 8808 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 8809 const FunctionDecl *FDecl) { 8810 if (Call->getNumArgs() != 1) 8811 return; 8812 8813 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 8814 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 8815 if (AbsKind == 0 && !IsStdAbs) 8816 return; 8817 8818 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 8819 QualType ParamType = Call->getArg(0)->getType(); 8820 8821 // Unsigned types cannot be negative. Suggest removing the absolute value 8822 // function call. 8823 if (ArgType->isUnsignedIntegerType()) { 8824 const char *FunctionName = 8825 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 8826 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 8827 Diag(Call->getExprLoc(), diag::note_remove_abs) 8828 << FunctionName 8829 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 8830 return; 8831 } 8832 8833 // Taking the absolute value of a pointer is very suspicious, they probably 8834 // wanted to index into an array, dereference a pointer, call a function, etc. 8835 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 8836 unsigned DiagType = 0; 8837 if (ArgType->isFunctionType()) 8838 DiagType = 1; 8839 else if (ArgType->isArrayType()) 8840 DiagType = 2; 8841 8842 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 8843 return; 8844 } 8845 8846 // std::abs has overloads which prevent most of the absolute value problems 8847 // from occurring. 8848 if (IsStdAbs) 8849 return; 8850 8851 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 8852 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 8853 8854 // The argument and parameter are the same kind. Check if they are the right 8855 // size. 8856 if (ArgValueKind == ParamValueKind) { 8857 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 8858 return; 8859 8860 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 8861 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 8862 << FDecl << ArgType << ParamType; 8863 8864 if (NewAbsKind == 0) 8865 return; 8866 8867 emitReplacement(*this, Call->getExprLoc(), 8868 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8869 return; 8870 } 8871 8872 // ArgValueKind != ParamValueKind 8873 // The wrong type of absolute value function was used. Attempt to find the 8874 // proper one. 8875 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 8876 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 8877 if (NewAbsKind == 0) 8878 return; 8879 8880 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 8881 << FDecl << ParamValueKind << ArgValueKind; 8882 8883 emitReplacement(*this, Call->getExprLoc(), 8884 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 8885 } 8886 8887 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 8888 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 8889 const FunctionDecl *FDecl) { 8890 if (!Call || !FDecl) return; 8891 8892 // Ignore template specializations and macros. 8893 if (inTemplateInstantiation()) return; 8894 if (Call->getExprLoc().isMacroID()) return; 8895 8896 // Only care about the one template argument, two function parameter std::max 8897 if (Call->getNumArgs() != 2) return; 8898 if (!IsStdFunction(FDecl, "max")) return; 8899 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 8900 if (!ArgList) return; 8901 if (ArgList->size() != 1) return; 8902 8903 // Check that template type argument is unsigned integer. 8904 const auto& TA = ArgList->get(0); 8905 if (TA.getKind() != TemplateArgument::Type) return; 8906 QualType ArgType = TA.getAsType(); 8907 if (!ArgType->isUnsignedIntegerType()) return; 8908 8909 // See if either argument is a literal zero. 8910 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 8911 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 8912 if (!MTE) return false; 8913 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 8914 if (!Num) return false; 8915 if (Num->getValue() != 0) return false; 8916 return true; 8917 }; 8918 8919 const Expr *FirstArg = Call->getArg(0); 8920 const Expr *SecondArg = Call->getArg(1); 8921 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 8922 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 8923 8924 // Only warn when exactly one argument is zero. 8925 if (IsFirstArgZero == IsSecondArgZero) return; 8926 8927 SourceRange FirstRange = FirstArg->getSourceRange(); 8928 SourceRange SecondRange = SecondArg->getSourceRange(); 8929 8930 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 8931 8932 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 8933 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 8934 8935 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 8936 SourceRange RemovalRange; 8937 if (IsFirstArgZero) { 8938 RemovalRange = SourceRange(FirstRange.getBegin(), 8939 SecondRange.getBegin().getLocWithOffset(-1)); 8940 } else { 8941 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 8942 SecondRange.getEnd()); 8943 } 8944 8945 Diag(Call->getExprLoc(), diag::note_remove_max_call) 8946 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 8947 << FixItHint::CreateRemoval(RemovalRange); 8948 } 8949 8950 //===--- CHECK: Standard memory functions ---------------------------------===// 8951 8952 /// Takes the expression passed to the size_t parameter of functions 8953 /// such as memcmp, strncat, etc and warns if it's a comparison. 8954 /// 8955 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 8956 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 8957 IdentifierInfo *FnName, 8958 SourceLocation FnLoc, 8959 SourceLocation RParenLoc) { 8960 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 8961 if (!Size) 8962 return false; 8963 8964 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 8965 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 8966 return false; 8967 8968 SourceRange SizeRange = Size->getSourceRange(); 8969 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 8970 << SizeRange << FnName; 8971 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 8972 << FnName 8973 << FixItHint::CreateInsertion( 8974 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 8975 << FixItHint::CreateRemoval(RParenLoc); 8976 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 8977 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 8978 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 8979 ")"); 8980 8981 return true; 8982 } 8983 8984 /// Determine whether the given type is or contains a dynamic class type 8985 /// (e.g., whether it has a vtable). 8986 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 8987 bool &IsContained) { 8988 // Look through array types while ignoring qualifiers. 8989 const Type *Ty = T->getBaseElementTypeUnsafe(); 8990 IsContained = false; 8991 8992 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 8993 RD = RD ? RD->getDefinition() : nullptr; 8994 if (!RD || RD->isInvalidDecl()) 8995 return nullptr; 8996 8997 if (RD->isDynamicClass()) 8998 return RD; 8999 9000 // Check all the fields. If any bases were dynamic, the class is dynamic. 9001 // It's impossible for a class to transitively contain itself by value, so 9002 // infinite recursion is impossible. 9003 for (auto *FD : RD->fields()) { 9004 bool SubContained; 9005 if (const CXXRecordDecl *ContainedRD = 9006 getContainedDynamicClass(FD->getType(), SubContained)) { 9007 IsContained = true; 9008 return ContainedRD; 9009 } 9010 } 9011 9012 return nullptr; 9013 } 9014 9015 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9016 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9017 if (Unary->getKind() == UETT_SizeOf) 9018 return Unary; 9019 return nullptr; 9020 } 9021 9022 /// If E is a sizeof expression, returns its argument expression, 9023 /// otherwise returns NULL. 9024 static const Expr *getSizeOfExprArg(const Expr *E) { 9025 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9026 if (!SizeOf->isArgumentType()) 9027 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9028 return nullptr; 9029 } 9030 9031 /// If E is a sizeof expression, returns its argument type. 9032 static QualType getSizeOfArgType(const Expr *E) { 9033 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9034 return SizeOf->getTypeOfArgument(); 9035 return QualType(); 9036 } 9037 9038 namespace { 9039 9040 struct SearchNonTrivialToInitializeField 9041 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9042 using Super = 9043 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9044 9045 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9046 9047 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9048 SourceLocation SL) { 9049 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9050 asDerived().visitArray(PDIK, AT, SL); 9051 return; 9052 } 9053 9054 Super::visitWithKind(PDIK, FT, SL); 9055 } 9056 9057 void visitARCStrong(QualType FT, SourceLocation SL) { 9058 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9059 } 9060 void visitARCWeak(QualType FT, SourceLocation SL) { 9061 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9062 } 9063 void visitStruct(QualType FT, SourceLocation SL) { 9064 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9065 visit(FD->getType(), FD->getLocation()); 9066 } 9067 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9068 const ArrayType *AT, SourceLocation SL) { 9069 visit(getContext().getBaseElementType(AT), SL); 9070 } 9071 void visitTrivial(QualType FT, SourceLocation SL) {} 9072 9073 static void diag(QualType RT, const Expr *E, Sema &S) { 9074 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9075 } 9076 9077 ASTContext &getContext() { return S.getASTContext(); } 9078 9079 const Expr *E; 9080 Sema &S; 9081 }; 9082 9083 struct SearchNonTrivialToCopyField 9084 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9085 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9086 9087 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9088 9089 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9090 SourceLocation SL) { 9091 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9092 asDerived().visitArray(PCK, AT, SL); 9093 return; 9094 } 9095 9096 Super::visitWithKind(PCK, FT, SL); 9097 } 9098 9099 void visitARCStrong(QualType FT, SourceLocation SL) { 9100 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9101 } 9102 void visitARCWeak(QualType FT, SourceLocation SL) { 9103 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9104 } 9105 void visitStruct(QualType FT, SourceLocation SL) { 9106 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9107 visit(FD->getType(), FD->getLocation()); 9108 } 9109 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9110 SourceLocation SL) { 9111 visit(getContext().getBaseElementType(AT), SL); 9112 } 9113 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9114 SourceLocation SL) {} 9115 void visitTrivial(QualType FT, SourceLocation SL) {} 9116 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9117 9118 static void diag(QualType RT, const Expr *E, Sema &S) { 9119 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9120 } 9121 9122 ASTContext &getContext() { return S.getASTContext(); } 9123 9124 const Expr *E; 9125 Sema &S; 9126 }; 9127 9128 } 9129 9130 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9131 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9132 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9133 9134 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9135 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9136 return false; 9137 9138 return doesExprLikelyComputeSize(BO->getLHS()) || 9139 doesExprLikelyComputeSize(BO->getRHS()); 9140 } 9141 9142 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9143 } 9144 9145 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9146 /// 9147 /// \code 9148 /// #define MACRO 0 9149 /// foo(MACRO); 9150 /// foo(0); 9151 /// \endcode 9152 /// 9153 /// This should return true for the first call to foo, but not for the second 9154 /// (regardless of whether foo is a macro or function). 9155 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9156 SourceLocation CallLoc, 9157 SourceLocation ArgLoc) { 9158 if (!CallLoc.isMacroID()) 9159 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9160 9161 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9162 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9163 } 9164 9165 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9166 /// last two arguments transposed. 9167 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9168 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9169 return; 9170 9171 const Expr *SizeArg = 9172 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9173 9174 auto isLiteralZero = [](const Expr *E) { 9175 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9176 }; 9177 9178 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9179 SourceLocation CallLoc = Call->getRParenLoc(); 9180 SourceManager &SM = S.getSourceManager(); 9181 if (isLiteralZero(SizeArg) && 9182 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9183 9184 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9185 9186 // Some platforms #define bzero to __builtin_memset. See if this is the 9187 // case, and if so, emit a better diagnostic. 9188 if (BId == Builtin::BIbzero || 9189 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9190 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9191 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9192 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9193 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9194 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9195 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9196 } 9197 return; 9198 } 9199 9200 // If the second argument to a memset is a sizeof expression and the third 9201 // isn't, this is also likely an error. This should catch 9202 // 'memset(buf, sizeof(buf), 0xff)'. 9203 if (BId == Builtin::BImemset && 9204 doesExprLikelyComputeSize(Call->getArg(1)) && 9205 !doesExprLikelyComputeSize(Call->getArg(2))) { 9206 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9207 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9208 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9209 return; 9210 } 9211 } 9212 9213 /// Check for dangerous or invalid arguments to memset(). 9214 /// 9215 /// This issues warnings on known problematic, dangerous or unspecified 9216 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9217 /// function calls. 9218 /// 9219 /// \param Call The call expression to diagnose. 9220 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9221 unsigned BId, 9222 IdentifierInfo *FnName) { 9223 assert(BId != 0); 9224 9225 // It is possible to have a non-standard definition of memset. Validate 9226 // we have enough arguments, and if not, abort further checking. 9227 unsigned ExpectedNumArgs = 9228 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9229 if (Call->getNumArgs() < ExpectedNumArgs) 9230 return; 9231 9232 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9233 BId == Builtin::BIstrndup ? 1 : 2); 9234 unsigned LenArg = 9235 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9236 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9237 9238 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9239 Call->getBeginLoc(), Call->getRParenLoc())) 9240 return; 9241 9242 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9243 CheckMemaccessSize(*this, BId, Call); 9244 9245 // We have special checking when the length is a sizeof expression. 9246 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9247 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9248 llvm::FoldingSetNodeID SizeOfArgID; 9249 9250 // Although widely used, 'bzero' is not a standard function. Be more strict 9251 // with the argument types before allowing diagnostics and only allow the 9252 // form bzero(ptr, sizeof(...)). 9253 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9254 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9255 return; 9256 9257 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9258 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9259 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9260 9261 QualType DestTy = Dest->getType(); 9262 QualType PointeeTy; 9263 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9264 PointeeTy = DestPtrTy->getPointeeType(); 9265 9266 // Never warn about void type pointers. This can be used to suppress 9267 // false positives. 9268 if (PointeeTy->isVoidType()) 9269 continue; 9270 9271 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9272 // actually comparing the expressions for equality. Because computing the 9273 // expression IDs can be expensive, we only do this if the diagnostic is 9274 // enabled. 9275 if (SizeOfArg && 9276 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9277 SizeOfArg->getExprLoc())) { 9278 // We only compute IDs for expressions if the warning is enabled, and 9279 // cache the sizeof arg's ID. 9280 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9281 SizeOfArg->Profile(SizeOfArgID, Context, true); 9282 llvm::FoldingSetNodeID DestID; 9283 Dest->Profile(DestID, Context, true); 9284 if (DestID == SizeOfArgID) { 9285 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9286 // over sizeof(src) as well. 9287 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9288 StringRef ReadableName = FnName->getName(); 9289 9290 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9291 if (UnaryOp->getOpcode() == UO_AddrOf) 9292 ActionIdx = 1; // If its an address-of operator, just remove it. 9293 if (!PointeeTy->isIncompleteType() && 9294 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9295 ActionIdx = 2; // If the pointee's size is sizeof(char), 9296 // suggest an explicit length. 9297 9298 // If the function is defined as a builtin macro, do not show macro 9299 // expansion. 9300 SourceLocation SL = SizeOfArg->getExprLoc(); 9301 SourceRange DSR = Dest->getSourceRange(); 9302 SourceRange SSR = SizeOfArg->getSourceRange(); 9303 SourceManager &SM = getSourceManager(); 9304 9305 if (SM.isMacroArgExpansion(SL)) { 9306 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9307 SL = SM.getSpellingLoc(SL); 9308 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9309 SM.getSpellingLoc(DSR.getEnd())); 9310 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9311 SM.getSpellingLoc(SSR.getEnd())); 9312 } 9313 9314 DiagRuntimeBehavior(SL, SizeOfArg, 9315 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9316 << ReadableName 9317 << PointeeTy 9318 << DestTy 9319 << DSR 9320 << SSR); 9321 DiagRuntimeBehavior(SL, SizeOfArg, 9322 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9323 << ActionIdx 9324 << SSR); 9325 9326 break; 9327 } 9328 } 9329 9330 // Also check for cases where the sizeof argument is the exact same 9331 // type as the memory argument, and where it points to a user-defined 9332 // record type. 9333 if (SizeOfArgTy != QualType()) { 9334 if (PointeeTy->isRecordType() && 9335 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9336 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9337 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9338 << FnName << SizeOfArgTy << ArgIdx 9339 << PointeeTy << Dest->getSourceRange() 9340 << LenExpr->getSourceRange()); 9341 break; 9342 } 9343 } 9344 } else if (DestTy->isArrayType()) { 9345 PointeeTy = DestTy; 9346 } 9347 9348 if (PointeeTy == QualType()) 9349 continue; 9350 9351 // Always complain about dynamic classes. 9352 bool IsContained; 9353 if (const CXXRecordDecl *ContainedRD = 9354 getContainedDynamicClass(PointeeTy, IsContained)) { 9355 9356 unsigned OperationType = 0; 9357 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9358 // "overwritten" if we're warning about the destination for any call 9359 // but memcmp; otherwise a verb appropriate to the call. 9360 if (ArgIdx != 0 || IsCmp) { 9361 if (BId == Builtin::BImemcpy) 9362 OperationType = 1; 9363 else if(BId == Builtin::BImemmove) 9364 OperationType = 2; 9365 else if (IsCmp) 9366 OperationType = 3; 9367 } 9368 9369 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9370 PDiag(diag::warn_dyn_class_memaccess) 9371 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9372 << IsContained << ContainedRD << OperationType 9373 << Call->getCallee()->getSourceRange()); 9374 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9375 BId != Builtin::BImemset) 9376 DiagRuntimeBehavior( 9377 Dest->getExprLoc(), Dest, 9378 PDiag(diag::warn_arc_object_memaccess) 9379 << ArgIdx << FnName << PointeeTy 9380 << Call->getCallee()->getSourceRange()); 9381 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9382 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9383 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9384 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9385 PDiag(diag::warn_cstruct_memaccess) 9386 << ArgIdx << FnName << PointeeTy << 0); 9387 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9388 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9389 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9390 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9391 PDiag(diag::warn_cstruct_memaccess) 9392 << ArgIdx << FnName << PointeeTy << 1); 9393 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9394 } else { 9395 continue; 9396 } 9397 } else 9398 continue; 9399 9400 DiagRuntimeBehavior( 9401 Dest->getExprLoc(), Dest, 9402 PDiag(diag::note_bad_memaccess_silence) 9403 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9404 break; 9405 } 9406 } 9407 9408 // A little helper routine: ignore addition and subtraction of integer literals. 9409 // This intentionally does not ignore all integer constant expressions because 9410 // we don't want to remove sizeof(). 9411 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9412 Ex = Ex->IgnoreParenCasts(); 9413 9414 while (true) { 9415 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9416 if (!BO || !BO->isAdditiveOp()) 9417 break; 9418 9419 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9420 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9421 9422 if (isa<IntegerLiteral>(RHS)) 9423 Ex = LHS; 9424 else if (isa<IntegerLiteral>(LHS)) 9425 Ex = RHS; 9426 else 9427 break; 9428 } 9429 9430 return Ex; 9431 } 9432 9433 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9434 ASTContext &Context) { 9435 // Only handle constant-sized or VLAs, but not flexible members. 9436 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9437 // Only issue the FIXIT for arrays of size > 1. 9438 if (CAT->getSize().getSExtValue() <= 1) 9439 return false; 9440 } else if (!Ty->isVariableArrayType()) { 9441 return false; 9442 } 9443 return true; 9444 } 9445 9446 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9447 // be the size of the source, instead of the destination. 9448 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9449 IdentifierInfo *FnName) { 9450 9451 // Don't crash if the user has the wrong number of arguments 9452 unsigned NumArgs = Call->getNumArgs(); 9453 if ((NumArgs != 3) && (NumArgs != 4)) 9454 return; 9455 9456 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9457 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9458 const Expr *CompareWithSrc = nullptr; 9459 9460 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9461 Call->getBeginLoc(), Call->getRParenLoc())) 9462 return; 9463 9464 // Look for 'strlcpy(dst, x, sizeof(x))' 9465 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9466 CompareWithSrc = Ex; 9467 else { 9468 // Look for 'strlcpy(dst, x, strlen(x))' 9469 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9470 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9471 SizeCall->getNumArgs() == 1) 9472 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9473 } 9474 } 9475 9476 if (!CompareWithSrc) 9477 return; 9478 9479 // Determine if the argument to sizeof/strlen is equal to the source 9480 // argument. In principle there's all kinds of things you could do 9481 // here, for instance creating an == expression and evaluating it with 9482 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9483 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9484 if (!SrcArgDRE) 9485 return; 9486 9487 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9488 if (!CompareWithSrcDRE || 9489 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9490 return; 9491 9492 const Expr *OriginalSizeArg = Call->getArg(2); 9493 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9494 << OriginalSizeArg->getSourceRange() << FnName; 9495 9496 // Output a FIXIT hint if the destination is an array (rather than a 9497 // pointer to an array). This could be enhanced to handle some 9498 // pointers if we know the actual size, like if DstArg is 'array+2' 9499 // we could say 'sizeof(array)-2'. 9500 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9501 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9502 return; 9503 9504 SmallString<128> sizeString; 9505 llvm::raw_svector_ostream OS(sizeString); 9506 OS << "sizeof("; 9507 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9508 OS << ")"; 9509 9510 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9511 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9512 OS.str()); 9513 } 9514 9515 /// Check if two expressions refer to the same declaration. 9516 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9517 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9518 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9519 return D1->getDecl() == D2->getDecl(); 9520 return false; 9521 } 9522 9523 static const Expr *getStrlenExprArg(const Expr *E) { 9524 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9525 const FunctionDecl *FD = CE->getDirectCallee(); 9526 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9527 return nullptr; 9528 return CE->getArg(0)->IgnoreParenCasts(); 9529 } 9530 return nullptr; 9531 } 9532 9533 // Warn on anti-patterns as the 'size' argument to strncat. 9534 // The correct size argument should look like following: 9535 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9536 void Sema::CheckStrncatArguments(const CallExpr *CE, 9537 IdentifierInfo *FnName) { 9538 // Don't crash if the user has the wrong number of arguments. 9539 if (CE->getNumArgs() < 3) 9540 return; 9541 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9542 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9543 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9544 9545 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9546 CE->getRParenLoc())) 9547 return; 9548 9549 // Identify common expressions, which are wrongly used as the size argument 9550 // to strncat and may lead to buffer overflows. 9551 unsigned PatternType = 0; 9552 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9553 // - sizeof(dst) 9554 if (referToTheSameDecl(SizeOfArg, DstArg)) 9555 PatternType = 1; 9556 // - sizeof(src) 9557 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9558 PatternType = 2; 9559 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9560 if (BE->getOpcode() == BO_Sub) { 9561 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9562 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9563 // - sizeof(dst) - strlen(dst) 9564 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9565 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9566 PatternType = 1; 9567 // - sizeof(src) - (anything) 9568 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9569 PatternType = 2; 9570 } 9571 } 9572 9573 if (PatternType == 0) 9574 return; 9575 9576 // Generate the diagnostic. 9577 SourceLocation SL = LenArg->getBeginLoc(); 9578 SourceRange SR = LenArg->getSourceRange(); 9579 SourceManager &SM = getSourceManager(); 9580 9581 // If the function is defined as a builtin macro, do not show macro expansion. 9582 if (SM.isMacroArgExpansion(SL)) { 9583 SL = SM.getSpellingLoc(SL); 9584 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9585 SM.getSpellingLoc(SR.getEnd())); 9586 } 9587 9588 // Check if the destination is an array (rather than a pointer to an array). 9589 QualType DstTy = DstArg->getType(); 9590 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9591 Context); 9592 if (!isKnownSizeArray) { 9593 if (PatternType == 1) 9594 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9595 else 9596 Diag(SL, diag::warn_strncat_src_size) << SR; 9597 return; 9598 } 9599 9600 if (PatternType == 1) 9601 Diag(SL, diag::warn_strncat_large_size) << SR; 9602 else 9603 Diag(SL, diag::warn_strncat_src_size) << SR; 9604 9605 SmallString<128> sizeString; 9606 llvm::raw_svector_ostream OS(sizeString); 9607 OS << "sizeof("; 9608 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9609 OS << ") - "; 9610 OS << "strlen("; 9611 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9612 OS << ") - 1"; 9613 9614 Diag(SL, diag::note_strncat_wrong_size) 9615 << FixItHint::CreateReplacement(SR, OS.str()); 9616 } 9617 9618 void 9619 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9620 SourceLocation ReturnLoc, 9621 bool isObjCMethod, 9622 const AttrVec *Attrs, 9623 const FunctionDecl *FD) { 9624 // Check if the return value is null but should not be. 9625 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9626 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9627 CheckNonNullExpr(*this, RetValExp)) 9628 Diag(ReturnLoc, diag::warn_null_ret) 9629 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9630 9631 // C++11 [basic.stc.dynamic.allocation]p4: 9632 // If an allocation function declared with a non-throwing 9633 // exception-specification fails to allocate storage, it shall return 9634 // a null pointer. Any other allocation function that fails to allocate 9635 // storage shall indicate failure only by throwing an exception [...] 9636 if (FD) { 9637 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9638 if (Op == OO_New || Op == OO_Array_New) { 9639 const FunctionProtoType *Proto 9640 = FD->getType()->castAs<FunctionProtoType>(); 9641 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9642 CheckNonNullExpr(*this, RetValExp)) 9643 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9644 << FD << getLangOpts().CPlusPlus11; 9645 } 9646 } 9647 } 9648 9649 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9650 9651 /// Check for comparisons of floating point operands using != and ==. 9652 /// Issue a warning if these are no self-comparisons, as they are not likely 9653 /// to do what the programmer intended. 9654 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9655 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9656 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9657 9658 // Special case: check for x == x (which is OK). 9659 // Do not emit warnings for such cases. 9660 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9661 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9662 if (DRL->getDecl() == DRR->getDecl()) 9663 return; 9664 9665 // Special case: check for comparisons against literals that can be exactly 9666 // represented by APFloat. In such cases, do not emit a warning. This 9667 // is a heuristic: often comparison against such literals are used to 9668 // detect if a value in a variable has not changed. This clearly can 9669 // lead to false negatives. 9670 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9671 if (FLL->isExact()) 9672 return; 9673 } else 9674 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9675 if (FLR->isExact()) 9676 return; 9677 9678 // Check for comparisons with builtin types. 9679 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9680 if (CL->getBuiltinCallee()) 9681 return; 9682 9683 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9684 if (CR->getBuiltinCallee()) 9685 return; 9686 9687 // Emit the diagnostic. 9688 Diag(Loc, diag::warn_floatingpoint_eq) 9689 << LHS->getSourceRange() << RHS->getSourceRange(); 9690 } 9691 9692 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9693 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9694 9695 namespace { 9696 9697 /// Structure recording the 'active' range of an integer-valued 9698 /// expression. 9699 struct IntRange { 9700 /// The number of bits active in the int. 9701 unsigned Width; 9702 9703 /// True if the int is known not to have negative values. 9704 bool NonNegative; 9705 9706 IntRange(unsigned Width, bool NonNegative) 9707 : Width(Width), NonNegative(NonNegative) {} 9708 9709 /// Returns the range of the bool type. 9710 static IntRange forBoolType() { 9711 return IntRange(1, true); 9712 } 9713 9714 /// Returns the range of an opaque value of the given integral type. 9715 static IntRange forValueOfType(ASTContext &C, QualType T) { 9716 return forValueOfCanonicalType(C, 9717 T->getCanonicalTypeInternal().getTypePtr()); 9718 } 9719 9720 /// Returns the range of an opaque value of a canonical integral type. 9721 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9722 assert(T->isCanonicalUnqualified()); 9723 9724 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9725 T = VT->getElementType().getTypePtr(); 9726 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9727 T = CT->getElementType().getTypePtr(); 9728 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9729 T = AT->getValueType().getTypePtr(); 9730 9731 if (!C.getLangOpts().CPlusPlus) { 9732 // For enum types in C code, use the underlying datatype. 9733 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9734 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9735 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9736 // For enum types in C++, use the known bit width of the enumerators. 9737 EnumDecl *Enum = ET->getDecl(); 9738 // In C++11, enums can have a fixed underlying type. Use this type to 9739 // compute the range. 9740 if (Enum->isFixed()) { 9741 return IntRange(C.getIntWidth(QualType(T, 0)), 9742 !ET->isSignedIntegerOrEnumerationType()); 9743 } 9744 9745 unsigned NumPositive = Enum->getNumPositiveBits(); 9746 unsigned NumNegative = Enum->getNumNegativeBits(); 9747 9748 if (NumNegative == 0) 9749 return IntRange(NumPositive, true/*NonNegative*/); 9750 else 9751 return IntRange(std::max(NumPositive + 1, NumNegative), 9752 false/*NonNegative*/); 9753 } 9754 9755 const BuiltinType *BT = cast<BuiltinType>(T); 9756 assert(BT->isInteger()); 9757 9758 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9759 } 9760 9761 /// Returns the "target" range of a canonical integral type, i.e. 9762 /// the range of values expressible in the type. 9763 /// 9764 /// This matches forValueOfCanonicalType except that enums have the 9765 /// full range of their type, not the range of their enumerators. 9766 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9767 assert(T->isCanonicalUnqualified()); 9768 9769 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9770 T = VT->getElementType().getTypePtr(); 9771 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9772 T = CT->getElementType().getTypePtr(); 9773 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9774 T = AT->getValueType().getTypePtr(); 9775 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9776 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 9777 9778 const BuiltinType *BT = cast<BuiltinType>(T); 9779 assert(BT->isInteger()); 9780 9781 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9782 } 9783 9784 /// Returns the supremum of two ranges: i.e. their conservative merge. 9785 static IntRange join(IntRange L, IntRange R) { 9786 return IntRange(std::max(L.Width, R.Width), 9787 L.NonNegative && R.NonNegative); 9788 } 9789 9790 /// Returns the infinum of two ranges: i.e. their aggressive merge. 9791 static IntRange meet(IntRange L, IntRange R) { 9792 return IntRange(std::min(L.Width, R.Width), 9793 L.NonNegative || R.NonNegative); 9794 } 9795 }; 9796 9797 } // namespace 9798 9799 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 9800 unsigned MaxWidth) { 9801 if (value.isSigned() && value.isNegative()) 9802 return IntRange(value.getMinSignedBits(), false); 9803 9804 if (value.getBitWidth() > MaxWidth) 9805 value = value.trunc(MaxWidth); 9806 9807 // isNonNegative() just checks the sign bit without considering 9808 // signedness. 9809 return IntRange(value.getActiveBits(), true); 9810 } 9811 9812 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 9813 unsigned MaxWidth) { 9814 if (result.isInt()) 9815 return GetValueRange(C, result.getInt(), MaxWidth); 9816 9817 if (result.isVector()) { 9818 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 9819 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 9820 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 9821 R = IntRange::join(R, El); 9822 } 9823 return R; 9824 } 9825 9826 if (result.isComplexInt()) { 9827 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 9828 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 9829 return IntRange::join(R, I); 9830 } 9831 9832 // This can happen with lossless casts to intptr_t of "based" lvalues. 9833 // Assume it might use arbitrary bits. 9834 // FIXME: The only reason we need to pass the type in here is to get 9835 // the sign right on this one case. It would be nice if APValue 9836 // preserved this. 9837 assert(result.isLValue() || result.isAddrLabelDiff()); 9838 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 9839 } 9840 9841 static QualType GetExprType(const Expr *E) { 9842 QualType Ty = E->getType(); 9843 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 9844 Ty = AtomicRHS->getValueType(); 9845 return Ty; 9846 } 9847 9848 /// Pseudo-evaluate the given integer expression, estimating the 9849 /// range of values it might take. 9850 /// 9851 /// \param MaxWidth - the width to which the value will be truncated 9852 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 9853 bool InConstantContext) { 9854 E = E->IgnoreParens(); 9855 9856 // Try a full evaluation first. 9857 Expr::EvalResult result; 9858 if (E->EvaluateAsRValue(result, C, InConstantContext)) 9859 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 9860 9861 // I think we only want to look through implicit casts here; if the 9862 // user has an explicit widening cast, we should treat the value as 9863 // being of the new, wider type. 9864 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 9865 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 9866 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 9867 9868 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 9869 9870 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 9871 CE->getCastKind() == CK_BooleanToSignedIntegral; 9872 9873 // Assume that non-integer casts can span the full range of the type. 9874 if (!isIntegerCast) 9875 return OutputTypeRange; 9876 9877 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 9878 std::min(MaxWidth, OutputTypeRange.Width), 9879 InConstantContext); 9880 9881 // Bail out if the subexpr's range is as wide as the cast type. 9882 if (SubRange.Width >= OutputTypeRange.Width) 9883 return OutputTypeRange; 9884 9885 // Otherwise, we take the smaller width, and we're non-negative if 9886 // either the output type or the subexpr is. 9887 return IntRange(SubRange.Width, 9888 SubRange.NonNegative || OutputTypeRange.NonNegative); 9889 } 9890 9891 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 9892 // If we can fold the condition, just take that operand. 9893 bool CondResult; 9894 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 9895 return GetExprRange(C, 9896 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 9897 MaxWidth, InConstantContext); 9898 9899 // Otherwise, conservatively merge. 9900 IntRange L = 9901 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 9902 IntRange R = 9903 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 9904 return IntRange::join(L, R); 9905 } 9906 9907 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 9908 switch (BO->getOpcode()) { 9909 case BO_Cmp: 9910 llvm_unreachable("builtin <=> should have class type"); 9911 9912 // Boolean-valued operations are single-bit and positive. 9913 case BO_LAnd: 9914 case BO_LOr: 9915 case BO_LT: 9916 case BO_GT: 9917 case BO_LE: 9918 case BO_GE: 9919 case BO_EQ: 9920 case BO_NE: 9921 return IntRange::forBoolType(); 9922 9923 // The type of the assignments is the type of the LHS, so the RHS 9924 // is not necessarily the same type. 9925 case BO_MulAssign: 9926 case BO_DivAssign: 9927 case BO_RemAssign: 9928 case BO_AddAssign: 9929 case BO_SubAssign: 9930 case BO_XorAssign: 9931 case BO_OrAssign: 9932 // TODO: bitfields? 9933 return IntRange::forValueOfType(C, GetExprType(E)); 9934 9935 // Simple assignments just pass through the RHS, which will have 9936 // been coerced to the LHS type. 9937 case BO_Assign: 9938 // TODO: bitfields? 9939 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 9940 9941 // Operations with opaque sources are black-listed. 9942 case BO_PtrMemD: 9943 case BO_PtrMemI: 9944 return IntRange::forValueOfType(C, GetExprType(E)); 9945 9946 // Bitwise-and uses the *infinum* of the two source ranges. 9947 case BO_And: 9948 case BO_AndAssign: 9949 return IntRange::meet( 9950 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 9951 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 9952 9953 // Left shift gets black-listed based on a judgement call. 9954 case BO_Shl: 9955 // ...except that we want to treat '1 << (blah)' as logically 9956 // positive. It's an important idiom. 9957 if (IntegerLiteral *I 9958 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 9959 if (I->getValue() == 1) { 9960 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 9961 return IntRange(R.Width, /*NonNegative*/ true); 9962 } 9963 } 9964 LLVM_FALLTHROUGH; 9965 9966 case BO_ShlAssign: 9967 return IntRange::forValueOfType(C, GetExprType(E)); 9968 9969 // Right shift by a constant can narrow its left argument. 9970 case BO_Shr: 9971 case BO_ShrAssign: { 9972 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 9973 9974 // If the shift amount is a positive constant, drop the width by 9975 // that much. 9976 llvm::APSInt shift; 9977 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 9978 shift.isNonNegative()) { 9979 unsigned zext = shift.getZExtValue(); 9980 if (zext >= L.Width) 9981 L.Width = (L.NonNegative ? 0 : 1); 9982 else 9983 L.Width -= zext; 9984 } 9985 9986 return L; 9987 } 9988 9989 // Comma acts as its right operand. 9990 case BO_Comma: 9991 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 9992 9993 // Black-list pointer subtractions. 9994 case BO_Sub: 9995 if (BO->getLHS()->getType()->isPointerType()) 9996 return IntRange::forValueOfType(C, GetExprType(E)); 9997 break; 9998 9999 // The width of a division result is mostly determined by the size 10000 // of the LHS. 10001 case BO_Div: { 10002 // Don't 'pre-truncate' the operands. 10003 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10004 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10005 10006 // If the divisor is constant, use that. 10007 llvm::APSInt divisor; 10008 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 10009 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 10010 if (log2 >= L.Width) 10011 L.Width = (L.NonNegative ? 0 : 1); 10012 else 10013 L.Width = std::min(L.Width - log2, MaxWidth); 10014 return L; 10015 } 10016 10017 // Otherwise, just use the LHS's width. 10018 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10019 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10020 } 10021 10022 // The result of a remainder can't be larger than the result of 10023 // either side. 10024 case BO_Rem: { 10025 // Don't 'pre-truncate' the operands. 10026 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10027 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10028 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10029 10030 IntRange meet = IntRange::meet(L, R); 10031 meet.Width = std::min(meet.Width, MaxWidth); 10032 return meet; 10033 } 10034 10035 // The default behavior is okay for these. 10036 case BO_Mul: 10037 case BO_Add: 10038 case BO_Xor: 10039 case BO_Or: 10040 break; 10041 } 10042 10043 // The default case is to treat the operation as if it were closed 10044 // on the narrowest type that encompasses both operands. 10045 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10046 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10047 return IntRange::join(L, R); 10048 } 10049 10050 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10051 switch (UO->getOpcode()) { 10052 // Boolean-valued operations are white-listed. 10053 case UO_LNot: 10054 return IntRange::forBoolType(); 10055 10056 // Operations with opaque sources are black-listed. 10057 case UO_Deref: 10058 case UO_AddrOf: // should be impossible 10059 return IntRange::forValueOfType(C, GetExprType(E)); 10060 10061 default: 10062 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10063 } 10064 } 10065 10066 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10067 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10068 10069 if (const auto *BitField = E->getSourceBitField()) 10070 return IntRange(BitField->getBitWidthValue(C), 10071 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10072 10073 return IntRange::forValueOfType(C, GetExprType(E)); 10074 } 10075 10076 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10077 bool InConstantContext) { 10078 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10079 } 10080 10081 /// Checks whether the given value, which currently has the given 10082 /// source semantics, has the same value when coerced through the 10083 /// target semantics. 10084 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10085 const llvm::fltSemantics &Src, 10086 const llvm::fltSemantics &Tgt) { 10087 llvm::APFloat truncated = value; 10088 10089 bool ignored; 10090 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10091 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10092 10093 return truncated.bitwiseIsEqual(value); 10094 } 10095 10096 /// Checks whether the given value, which currently has the given 10097 /// source semantics, has the same value when coerced through the 10098 /// target semantics. 10099 /// 10100 /// The value might be a vector of floats (or a complex number). 10101 static bool IsSameFloatAfterCast(const APValue &value, 10102 const llvm::fltSemantics &Src, 10103 const llvm::fltSemantics &Tgt) { 10104 if (value.isFloat()) 10105 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10106 10107 if (value.isVector()) { 10108 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10109 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10110 return false; 10111 return true; 10112 } 10113 10114 assert(value.isComplexFloat()); 10115 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10116 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10117 } 10118 10119 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10120 bool IsListInit = false); 10121 10122 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10123 // Suppress cases where we are comparing against an enum constant. 10124 if (const DeclRefExpr *DR = 10125 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10126 if (isa<EnumConstantDecl>(DR->getDecl())) 10127 return true; 10128 10129 // Suppress cases where the value is expanded from a macro, unless that macro 10130 // is how a language represents a boolean literal. This is the case in both C 10131 // and Objective-C. 10132 SourceLocation BeginLoc = E->getBeginLoc(); 10133 if (BeginLoc.isMacroID()) { 10134 StringRef MacroName = Lexer::getImmediateMacroName( 10135 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10136 return MacroName != "YES" && MacroName != "NO" && 10137 MacroName != "true" && MacroName != "false"; 10138 } 10139 10140 return false; 10141 } 10142 10143 static bool isKnownToHaveUnsignedValue(Expr *E) { 10144 return E->getType()->isIntegerType() && 10145 (!E->getType()->isSignedIntegerType() || 10146 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10147 } 10148 10149 namespace { 10150 /// The promoted range of values of a type. In general this has the 10151 /// following structure: 10152 /// 10153 /// |-----------| . . . |-----------| 10154 /// ^ ^ ^ ^ 10155 /// Min HoleMin HoleMax Max 10156 /// 10157 /// ... where there is only a hole if a signed type is promoted to unsigned 10158 /// (in which case Min and Max are the smallest and largest representable 10159 /// values). 10160 struct PromotedRange { 10161 // Min, or HoleMax if there is a hole. 10162 llvm::APSInt PromotedMin; 10163 // Max, or HoleMin if there is a hole. 10164 llvm::APSInt PromotedMax; 10165 10166 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10167 if (R.Width == 0) 10168 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10169 else if (R.Width >= BitWidth && !Unsigned) { 10170 // Promotion made the type *narrower*. This happens when promoting 10171 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10172 // Treat all values of 'signed int' as being in range for now. 10173 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10174 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10175 } else { 10176 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10177 .extOrTrunc(BitWidth); 10178 PromotedMin.setIsUnsigned(Unsigned); 10179 10180 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10181 .extOrTrunc(BitWidth); 10182 PromotedMax.setIsUnsigned(Unsigned); 10183 } 10184 } 10185 10186 // Determine whether this range is contiguous (has no hole). 10187 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10188 10189 // Where a constant value is within the range. 10190 enum ComparisonResult { 10191 LT = 0x1, 10192 LE = 0x2, 10193 GT = 0x4, 10194 GE = 0x8, 10195 EQ = 0x10, 10196 NE = 0x20, 10197 InRangeFlag = 0x40, 10198 10199 Less = LE | LT | NE, 10200 Min = LE | InRangeFlag, 10201 InRange = InRangeFlag, 10202 Max = GE | InRangeFlag, 10203 Greater = GE | GT | NE, 10204 10205 OnlyValue = LE | GE | EQ | InRangeFlag, 10206 InHole = NE 10207 }; 10208 10209 ComparisonResult compare(const llvm::APSInt &Value) const { 10210 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10211 Value.isUnsigned() == PromotedMin.isUnsigned()); 10212 if (!isContiguous()) { 10213 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10214 if (Value.isMinValue()) return Min; 10215 if (Value.isMaxValue()) return Max; 10216 if (Value >= PromotedMin) return InRange; 10217 if (Value <= PromotedMax) return InRange; 10218 return InHole; 10219 } 10220 10221 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10222 case -1: return Less; 10223 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10224 case 1: 10225 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10226 case -1: return InRange; 10227 case 0: return Max; 10228 case 1: return Greater; 10229 } 10230 } 10231 10232 llvm_unreachable("impossible compare result"); 10233 } 10234 10235 static llvm::Optional<StringRef> 10236 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10237 if (Op == BO_Cmp) { 10238 ComparisonResult LTFlag = LT, GTFlag = GT; 10239 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10240 10241 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10242 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10243 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10244 return llvm::None; 10245 } 10246 10247 ComparisonResult TrueFlag, FalseFlag; 10248 if (Op == BO_EQ) { 10249 TrueFlag = EQ; 10250 FalseFlag = NE; 10251 } else if (Op == BO_NE) { 10252 TrueFlag = NE; 10253 FalseFlag = EQ; 10254 } else { 10255 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10256 TrueFlag = LT; 10257 FalseFlag = GE; 10258 } else { 10259 TrueFlag = GT; 10260 FalseFlag = LE; 10261 } 10262 if (Op == BO_GE || Op == BO_LE) 10263 std::swap(TrueFlag, FalseFlag); 10264 } 10265 if (R & TrueFlag) 10266 return StringRef("true"); 10267 if (R & FalseFlag) 10268 return StringRef("false"); 10269 return llvm::None; 10270 } 10271 }; 10272 } 10273 10274 static bool HasEnumType(Expr *E) { 10275 // Strip off implicit integral promotions. 10276 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10277 if (ICE->getCastKind() != CK_IntegralCast && 10278 ICE->getCastKind() != CK_NoOp) 10279 break; 10280 E = ICE->getSubExpr(); 10281 } 10282 10283 return E->getType()->isEnumeralType(); 10284 } 10285 10286 static int classifyConstantValue(Expr *Constant) { 10287 // The values of this enumeration are used in the diagnostics 10288 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10289 enum ConstantValueKind { 10290 Miscellaneous = 0, 10291 LiteralTrue, 10292 LiteralFalse 10293 }; 10294 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10295 return BL->getValue() ? ConstantValueKind::LiteralTrue 10296 : ConstantValueKind::LiteralFalse; 10297 return ConstantValueKind::Miscellaneous; 10298 } 10299 10300 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10301 Expr *Constant, Expr *Other, 10302 const llvm::APSInt &Value, 10303 bool RhsConstant) { 10304 if (S.inTemplateInstantiation()) 10305 return false; 10306 10307 Expr *OriginalOther = Other; 10308 10309 Constant = Constant->IgnoreParenImpCasts(); 10310 Other = Other->IgnoreParenImpCasts(); 10311 10312 // Suppress warnings on tautological comparisons between values of the same 10313 // enumeration type. There are only two ways we could warn on this: 10314 // - If the constant is outside the range of representable values of 10315 // the enumeration. In such a case, we should warn about the cast 10316 // to enumeration type, not about the comparison. 10317 // - If the constant is the maximum / minimum in-range value. For an 10318 // enumeratin type, such comparisons can be meaningful and useful. 10319 if (Constant->getType()->isEnumeralType() && 10320 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10321 return false; 10322 10323 // TODO: Investigate using GetExprRange() to get tighter bounds 10324 // on the bit ranges. 10325 QualType OtherT = Other->getType(); 10326 if (const auto *AT = OtherT->getAs<AtomicType>()) 10327 OtherT = AT->getValueType(); 10328 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10329 10330 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10331 // (Namely, macOS). 10332 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10333 S.NSAPIObj->isObjCBOOLType(OtherT) && 10334 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10335 10336 // Whether we're treating Other as being a bool because of the form of 10337 // expression despite it having another type (typically 'int' in C). 10338 bool OtherIsBooleanDespiteType = 10339 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10340 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10341 OtherRange = IntRange::forBoolType(); 10342 10343 // Determine the promoted range of the other type and see if a comparison of 10344 // the constant against that range is tautological. 10345 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10346 Value.isUnsigned()); 10347 auto Cmp = OtherPromotedRange.compare(Value); 10348 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10349 if (!Result) 10350 return false; 10351 10352 // Suppress the diagnostic for an in-range comparison if the constant comes 10353 // from a macro or enumerator. We don't want to diagnose 10354 // 10355 // some_long_value <= INT_MAX 10356 // 10357 // when sizeof(int) == sizeof(long). 10358 bool InRange = Cmp & PromotedRange::InRangeFlag; 10359 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10360 return false; 10361 10362 // If this is a comparison to an enum constant, include that 10363 // constant in the diagnostic. 10364 const EnumConstantDecl *ED = nullptr; 10365 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10366 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10367 10368 // Should be enough for uint128 (39 decimal digits) 10369 SmallString<64> PrettySourceValue; 10370 llvm::raw_svector_ostream OS(PrettySourceValue); 10371 if (ED) { 10372 OS << '\'' << *ED << "' (" << Value << ")"; 10373 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10374 Constant->IgnoreParenImpCasts())) { 10375 OS << (BL->getValue() ? "YES" : "NO"); 10376 } else { 10377 OS << Value; 10378 } 10379 10380 if (IsObjCSignedCharBool) { 10381 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10382 S.PDiag(diag::warn_tautological_compare_objc_bool) 10383 << OS.str() << *Result); 10384 return true; 10385 } 10386 10387 // FIXME: We use a somewhat different formatting for the in-range cases and 10388 // cases involving boolean values for historical reasons. We should pick a 10389 // consistent way of presenting these diagnostics. 10390 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10391 10392 S.DiagRuntimeBehavior( 10393 E->getOperatorLoc(), E, 10394 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10395 : diag::warn_tautological_bool_compare) 10396 << OS.str() << classifyConstantValue(Constant) << OtherT 10397 << OtherIsBooleanDespiteType << *Result 10398 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10399 } else { 10400 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10401 ? (HasEnumType(OriginalOther) 10402 ? diag::warn_unsigned_enum_always_true_comparison 10403 : diag::warn_unsigned_always_true_comparison) 10404 : diag::warn_tautological_constant_compare; 10405 10406 S.Diag(E->getOperatorLoc(), Diag) 10407 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10408 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10409 } 10410 10411 return true; 10412 } 10413 10414 /// Analyze the operands of the given comparison. Implements the 10415 /// fallback case from AnalyzeComparison. 10416 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10417 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10418 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10419 } 10420 10421 /// Implements -Wsign-compare. 10422 /// 10423 /// \param E the binary operator to check for warnings 10424 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10425 // The type the comparison is being performed in. 10426 QualType T = E->getLHS()->getType(); 10427 10428 // Only analyze comparison operators where both sides have been converted to 10429 // the same type. 10430 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10431 return AnalyzeImpConvsInComparison(S, E); 10432 10433 // Don't analyze value-dependent comparisons directly. 10434 if (E->isValueDependent()) 10435 return AnalyzeImpConvsInComparison(S, E); 10436 10437 Expr *LHS = E->getLHS(); 10438 Expr *RHS = E->getRHS(); 10439 10440 if (T->isIntegralType(S.Context)) { 10441 llvm::APSInt RHSValue; 10442 llvm::APSInt LHSValue; 10443 10444 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10445 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10446 10447 // We don't care about expressions whose result is a constant. 10448 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10449 return AnalyzeImpConvsInComparison(S, E); 10450 10451 // We only care about expressions where just one side is literal 10452 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10453 // Is the constant on the RHS or LHS? 10454 const bool RhsConstant = IsRHSIntegralLiteral; 10455 Expr *Const = RhsConstant ? RHS : LHS; 10456 Expr *Other = RhsConstant ? LHS : RHS; 10457 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10458 10459 // Check whether an integer constant comparison results in a value 10460 // of 'true' or 'false'. 10461 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10462 return AnalyzeImpConvsInComparison(S, E); 10463 } 10464 } 10465 10466 if (!T->hasUnsignedIntegerRepresentation()) { 10467 // We don't do anything special if this isn't an unsigned integral 10468 // comparison: we're only interested in integral comparisons, and 10469 // signed comparisons only happen in cases we don't care to warn about. 10470 return AnalyzeImpConvsInComparison(S, E); 10471 } 10472 10473 LHS = LHS->IgnoreParenImpCasts(); 10474 RHS = RHS->IgnoreParenImpCasts(); 10475 10476 if (!S.getLangOpts().CPlusPlus) { 10477 // Avoid warning about comparison of integers with different signs when 10478 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10479 // the type of `E`. 10480 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10481 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10482 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10483 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10484 } 10485 10486 // Check to see if one of the (unmodified) operands is of different 10487 // signedness. 10488 Expr *signedOperand, *unsignedOperand; 10489 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10490 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10491 "unsigned comparison between two signed integer expressions?"); 10492 signedOperand = LHS; 10493 unsignedOperand = RHS; 10494 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10495 signedOperand = RHS; 10496 unsignedOperand = LHS; 10497 } else { 10498 return AnalyzeImpConvsInComparison(S, E); 10499 } 10500 10501 // Otherwise, calculate the effective range of the signed operand. 10502 IntRange signedRange = 10503 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10504 10505 // Go ahead and analyze implicit conversions in the operands. Note 10506 // that we skip the implicit conversions on both sides. 10507 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10508 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10509 10510 // If the signed range is non-negative, -Wsign-compare won't fire. 10511 if (signedRange.NonNegative) 10512 return; 10513 10514 // For (in)equality comparisons, if the unsigned operand is a 10515 // constant which cannot collide with a overflowed signed operand, 10516 // then reinterpreting the signed operand as unsigned will not 10517 // change the result of the comparison. 10518 if (E->isEqualityOp()) { 10519 unsigned comparisonWidth = S.Context.getIntWidth(T); 10520 IntRange unsignedRange = 10521 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10522 10523 // We should never be unable to prove that the unsigned operand is 10524 // non-negative. 10525 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10526 10527 if (unsignedRange.Width < comparisonWidth) 10528 return; 10529 } 10530 10531 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10532 S.PDiag(diag::warn_mixed_sign_comparison) 10533 << LHS->getType() << RHS->getType() 10534 << LHS->getSourceRange() << RHS->getSourceRange()); 10535 } 10536 10537 /// Analyzes an attempt to assign the given value to a bitfield. 10538 /// 10539 /// Returns true if there was something fishy about the attempt. 10540 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10541 SourceLocation InitLoc) { 10542 assert(Bitfield->isBitField()); 10543 if (Bitfield->isInvalidDecl()) 10544 return false; 10545 10546 // White-list bool bitfields. 10547 QualType BitfieldType = Bitfield->getType(); 10548 if (BitfieldType->isBooleanType()) 10549 return false; 10550 10551 if (BitfieldType->isEnumeralType()) { 10552 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10553 // If the underlying enum type was not explicitly specified as an unsigned 10554 // type and the enum contain only positive values, MSVC++ will cause an 10555 // inconsistency by storing this as a signed type. 10556 if (S.getLangOpts().CPlusPlus11 && 10557 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10558 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10559 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10560 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10561 << BitfieldEnumDecl->getNameAsString(); 10562 } 10563 } 10564 10565 if (Bitfield->getType()->isBooleanType()) 10566 return false; 10567 10568 // Ignore value- or type-dependent expressions. 10569 if (Bitfield->getBitWidth()->isValueDependent() || 10570 Bitfield->getBitWidth()->isTypeDependent() || 10571 Init->isValueDependent() || 10572 Init->isTypeDependent()) 10573 return false; 10574 10575 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10576 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10577 10578 Expr::EvalResult Result; 10579 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10580 Expr::SE_AllowSideEffects)) { 10581 // The RHS is not constant. If the RHS has an enum type, make sure the 10582 // bitfield is wide enough to hold all the values of the enum without 10583 // truncation. 10584 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10585 EnumDecl *ED = EnumTy->getDecl(); 10586 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10587 10588 // Enum types are implicitly signed on Windows, so check if there are any 10589 // negative enumerators to see if the enum was intended to be signed or 10590 // not. 10591 bool SignedEnum = ED->getNumNegativeBits() > 0; 10592 10593 // Check for surprising sign changes when assigning enum values to a 10594 // bitfield of different signedness. If the bitfield is signed and we 10595 // have exactly the right number of bits to store this unsigned enum, 10596 // suggest changing the enum to an unsigned type. This typically happens 10597 // on Windows where unfixed enums always use an underlying type of 'int'. 10598 unsigned DiagID = 0; 10599 if (SignedEnum && !SignedBitfield) { 10600 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10601 } else if (SignedBitfield && !SignedEnum && 10602 ED->getNumPositiveBits() == FieldWidth) { 10603 DiagID = diag::warn_signed_bitfield_enum_conversion; 10604 } 10605 10606 if (DiagID) { 10607 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10608 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10609 SourceRange TypeRange = 10610 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10611 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10612 << SignedEnum << TypeRange; 10613 } 10614 10615 // Compute the required bitwidth. If the enum has negative values, we need 10616 // one more bit than the normal number of positive bits to represent the 10617 // sign bit. 10618 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10619 ED->getNumNegativeBits()) 10620 : ED->getNumPositiveBits(); 10621 10622 // Check the bitwidth. 10623 if (BitsNeeded > FieldWidth) { 10624 Expr *WidthExpr = Bitfield->getBitWidth(); 10625 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10626 << Bitfield << ED; 10627 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10628 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10629 } 10630 } 10631 10632 return false; 10633 } 10634 10635 llvm::APSInt Value = Result.Val.getInt(); 10636 10637 unsigned OriginalWidth = Value.getBitWidth(); 10638 10639 if (!Value.isSigned() || Value.isNegative()) 10640 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10641 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10642 OriginalWidth = Value.getMinSignedBits(); 10643 10644 if (OriginalWidth <= FieldWidth) 10645 return false; 10646 10647 // Compute the value which the bitfield will contain. 10648 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10649 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10650 10651 // Check whether the stored value is equal to the original value. 10652 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10653 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10654 return false; 10655 10656 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10657 // therefore don't strictly fit into a signed bitfield of width 1. 10658 if (FieldWidth == 1 && Value == 1) 10659 return false; 10660 10661 std::string PrettyValue = Value.toString(10); 10662 std::string PrettyTrunc = TruncatedValue.toString(10); 10663 10664 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10665 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10666 << Init->getSourceRange(); 10667 10668 return true; 10669 } 10670 10671 /// Analyze the given simple or compound assignment for warning-worthy 10672 /// operations. 10673 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10674 // Just recurse on the LHS. 10675 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10676 10677 // We want to recurse on the RHS as normal unless we're assigning to 10678 // a bitfield. 10679 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10680 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10681 E->getOperatorLoc())) { 10682 // Recurse, ignoring any implicit conversions on the RHS. 10683 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10684 E->getOperatorLoc()); 10685 } 10686 } 10687 10688 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10689 10690 // Diagnose implicitly sequentially-consistent atomic assignment. 10691 if (E->getLHS()->getType()->isAtomicType()) 10692 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10693 } 10694 10695 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10696 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10697 SourceLocation CContext, unsigned diag, 10698 bool pruneControlFlow = false) { 10699 if (pruneControlFlow) { 10700 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10701 S.PDiag(diag) 10702 << SourceType << T << E->getSourceRange() 10703 << SourceRange(CContext)); 10704 return; 10705 } 10706 S.Diag(E->getExprLoc(), diag) 10707 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10708 } 10709 10710 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10711 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10712 SourceLocation CContext, 10713 unsigned diag, bool pruneControlFlow = false) { 10714 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10715 } 10716 10717 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 10718 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 10719 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 10720 } 10721 10722 static void adornObjCBoolConversionDiagWithTernaryFixit( 10723 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 10724 Expr *Ignored = SourceExpr->IgnoreImplicit(); 10725 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 10726 Ignored = OVE->getSourceExpr(); 10727 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 10728 isa<BinaryOperator>(Ignored) || 10729 isa<CXXOperatorCallExpr>(Ignored); 10730 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 10731 if (NeedsParens) 10732 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 10733 << FixItHint::CreateInsertion(EndLoc, ")"); 10734 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 10735 } 10736 10737 /// Diagnose an implicit cast from a floating point value to an integer value. 10738 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10739 SourceLocation CContext) { 10740 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10741 const bool PruneWarnings = S.inTemplateInstantiation(); 10742 10743 Expr *InnerE = E->IgnoreParenImpCasts(); 10744 // We also want to warn on, e.g., "int i = -1.234" 10745 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10746 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10747 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10748 10749 const bool IsLiteral = 10750 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10751 10752 llvm::APFloat Value(0.0); 10753 bool IsConstant = 10754 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10755 if (!IsConstant) { 10756 if (isObjCSignedCharBool(S, T)) { 10757 return adornObjCBoolConversionDiagWithTernaryFixit( 10758 S, E, 10759 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 10760 << E->getType()); 10761 } 10762 10763 return DiagnoseImpCast(S, E, T, CContext, 10764 diag::warn_impcast_float_integer, PruneWarnings); 10765 } 10766 10767 bool isExact = false; 10768 10769 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10770 T->hasUnsignedIntegerRepresentation()); 10771 llvm::APFloat::opStatus Result = Value.convertToInteger( 10772 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 10773 10774 // FIXME: Force the precision of the source value down so we don't print 10775 // digits which are usually useless (we don't really care here if we 10776 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 10777 // would automatically print the shortest representation, but it's a bit 10778 // tricky to implement. 10779 SmallString<16> PrettySourceValue; 10780 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 10781 precision = (precision * 59 + 195) / 196; 10782 Value.toString(PrettySourceValue, precision); 10783 10784 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 10785 return adornObjCBoolConversionDiagWithTernaryFixit( 10786 S, E, 10787 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 10788 << PrettySourceValue); 10789 } 10790 10791 if (Result == llvm::APFloat::opOK && isExact) { 10792 if (IsLiteral) return; 10793 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 10794 PruneWarnings); 10795 } 10796 10797 // Conversion of a floating-point value to a non-bool integer where the 10798 // integral part cannot be represented by the integer type is undefined. 10799 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 10800 return DiagnoseImpCast( 10801 S, E, T, CContext, 10802 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 10803 : diag::warn_impcast_float_to_integer_out_of_range, 10804 PruneWarnings); 10805 10806 unsigned DiagID = 0; 10807 if (IsLiteral) { 10808 // Warn on floating point literal to integer. 10809 DiagID = diag::warn_impcast_literal_float_to_integer; 10810 } else if (IntegerValue == 0) { 10811 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 10812 return DiagnoseImpCast(S, E, T, CContext, 10813 diag::warn_impcast_float_integer, PruneWarnings); 10814 } 10815 // Warn on non-zero to zero conversion. 10816 DiagID = diag::warn_impcast_float_to_integer_zero; 10817 } else { 10818 if (IntegerValue.isUnsigned()) { 10819 if (!IntegerValue.isMaxValue()) { 10820 return DiagnoseImpCast(S, E, T, CContext, 10821 diag::warn_impcast_float_integer, PruneWarnings); 10822 } 10823 } else { // IntegerValue.isSigned() 10824 if (!IntegerValue.isMaxSignedValue() && 10825 !IntegerValue.isMinSignedValue()) { 10826 return DiagnoseImpCast(S, E, T, CContext, 10827 diag::warn_impcast_float_integer, PruneWarnings); 10828 } 10829 } 10830 // Warn on evaluatable floating point expression to integer conversion. 10831 DiagID = diag::warn_impcast_float_to_integer; 10832 } 10833 10834 SmallString<16> PrettyTargetValue; 10835 if (IsBool) 10836 PrettyTargetValue = Value.isZero() ? "false" : "true"; 10837 else 10838 IntegerValue.toString(PrettyTargetValue); 10839 10840 if (PruneWarnings) { 10841 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10842 S.PDiag(DiagID) 10843 << E->getType() << T.getUnqualifiedType() 10844 << PrettySourceValue << PrettyTargetValue 10845 << E->getSourceRange() << SourceRange(CContext)); 10846 } else { 10847 S.Diag(E->getExprLoc(), DiagID) 10848 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 10849 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 10850 } 10851 } 10852 10853 /// Analyze the given compound assignment for the possible losing of 10854 /// floating-point precision. 10855 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 10856 assert(isa<CompoundAssignOperator>(E) && 10857 "Must be compound assignment operation"); 10858 // Recurse on the LHS and RHS in here 10859 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10860 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10861 10862 if (E->getLHS()->getType()->isAtomicType()) 10863 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 10864 10865 // Now check the outermost expression 10866 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 10867 const auto *RBT = cast<CompoundAssignOperator>(E) 10868 ->getComputationResultType() 10869 ->getAs<BuiltinType>(); 10870 10871 // The below checks assume source is floating point. 10872 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 10873 10874 // If source is floating point but target is an integer. 10875 if (ResultBT->isInteger()) 10876 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 10877 E->getExprLoc(), diag::warn_impcast_float_integer); 10878 10879 if (!ResultBT->isFloatingPoint()) 10880 return; 10881 10882 // If both source and target are floating points, warn about losing precision. 10883 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 10884 QualType(ResultBT, 0), QualType(RBT, 0)); 10885 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 10886 // warn about dropping FP rank. 10887 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 10888 diag::warn_impcast_float_result_precision); 10889 } 10890 10891 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 10892 IntRange Range) { 10893 if (!Range.Width) return "0"; 10894 10895 llvm::APSInt ValueInRange = Value; 10896 ValueInRange.setIsSigned(!Range.NonNegative); 10897 ValueInRange = ValueInRange.trunc(Range.Width); 10898 return ValueInRange.toString(10); 10899 } 10900 10901 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 10902 if (!isa<ImplicitCastExpr>(Ex)) 10903 return false; 10904 10905 Expr *InnerE = Ex->IgnoreParenImpCasts(); 10906 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 10907 const Type *Source = 10908 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 10909 if (Target->isDependentType()) 10910 return false; 10911 10912 const BuiltinType *FloatCandidateBT = 10913 dyn_cast<BuiltinType>(ToBool ? Source : Target); 10914 const Type *BoolCandidateType = ToBool ? Target : Source; 10915 10916 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 10917 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 10918 } 10919 10920 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 10921 SourceLocation CC) { 10922 unsigned NumArgs = TheCall->getNumArgs(); 10923 for (unsigned i = 0; i < NumArgs; ++i) { 10924 Expr *CurrA = TheCall->getArg(i); 10925 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 10926 continue; 10927 10928 bool IsSwapped = ((i > 0) && 10929 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 10930 IsSwapped |= ((i < (NumArgs - 1)) && 10931 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 10932 if (IsSwapped) { 10933 // Warn on this floating-point to bool conversion. 10934 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 10935 CurrA->getType(), CC, 10936 diag::warn_impcast_floating_point_to_bool); 10937 } 10938 } 10939 } 10940 10941 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 10942 SourceLocation CC) { 10943 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 10944 E->getExprLoc())) 10945 return; 10946 10947 // Don't warn on functions which have return type nullptr_t. 10948 if (isa<CallExpr>(E)) 10949 return; 10950 10951 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 10952 const Expr::NullPointerConstantKind NullKind = 10953 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 10954 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 10955 return; 10956 10957 // Return if target type is a safe conversion. 10958 if (T->isAnyPointerType() || T->isBlockPointerType() || 10959 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 10960 return; 10961 10962 SourceLocation Loc = E->getSourceRange().getBegin(); 10963 10964 // Venture through the macro stacks to get to the source of macro arguments. 10965 // The new location is a better location than the complete location that was 10966 // passed in. 10967 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 10968 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 10969 10970 // __null is usually wrapped in a macro. Go up a macro if that is the case. 10971 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 10972 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 10973 Loc, S.SourceMgr, S.getLangOpts()); 10974 if (MacroName == "NULL") 10975 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 10976 } 10977 10978 // Only warn if the null and context location are in the same macro expansion. 10979 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 10980 return; 10981 10982 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 10983 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 10984 << FixItHint::CreateReplacement(Loc, 10985 S.getFixItZeroLiteralForType(T, Loc)); 10986 } 10987 10988 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 10989 ObjCArrayLiteral *ArrayLiteral); 10990 10991 static void 10992 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 10993 ObjCDictionaryLiteral *DictionaryLiteral); 10994 10995 /// Check a single element within a collection literal against the 10996 /// target element type. 10997 static void checkObjCCollectionLiteralElement(Sema &S, 10998 QualType TargetElementType, 10999 Expr *Element, 11000 unsigned ElementKind) { 11001 // Skip a bitcast to 'id' or qualified 'id'. 11002 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11003 if (ICE->getCastKind() == CK_BitCast && 11004 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11005 Element = ICE->getSubExpr(); 11006 } 11007 11008 QualType ElementType = Element->getType(); 11009 ExprResult ElementResult(Element); 11010 if (ElementType->getAs<ObjCObjectPointerType>() && 11011 S.CheckSingleAssignmentConstraints(TargetElementType, 11012 ElementResult, 11013 false, false) 11014 != Sema::Compatible) { 11015 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11016 << ElementType << ElementKind << TargetElementType 11017 << Element->getSourceRange(); 11018 } 11019 11020 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11021 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11022 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11023 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11024 } 11025 11026 /// Check an Objective-C array literal being converted to the given 11027 /// target type. 11028 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11029 ObjCArrayLiteral *ArrayLiteral) { 11030 if (!S.NSArrayDecl) 11031 return; 11032 11033 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11034 if (!TargetObjCPtr) 11035 return; 11036 11037 if (TargetObjCPtr->isUnspecialized() || 11038 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11039 != S.NSArrayDecl->getCanonicalDecl()) 11040 return; 11041 11042 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11043 if (TypeArgs.size() != 1) 11044 return; 11045 11046 QualType TargetElementType = TypeArgs[0]; 11047 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11048 checkObjCCollectionLiteralElement(S, TargetElementType, 11049 ArrayLiteral->getElement(I), 11050 0); 11051 } 11052 } 11053 11054 /// Check an Objective-C dictionary literal being converted to the given 11055 /// target type. 11056 static void 11057 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11058 ObjCDictionaryLiteral *DictionaryLiteral) { 11059 if (!S.NSDictionaryDecl) 11060 return; 11061 11062 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11063 if (!TargetObjCPtr) 11064 return; 11065 11066 if (TargetObjCPtr->isUnspecialized() || 11067 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11068 != S.NSDictionaryDecl->getCanonicalDecl()) 11069 return; 11070 11071 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11072 if (TypeArgs.size() != 2) 11073 return; 11074 11075 QualType TargetKeyType = TypeArgs[0]; 11076 QualType TargetObjectType = TypeArgs[1]; 11077 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11078 auto Element = DictionaryLiteral->getKeyValueElement(I); 11079 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11080 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11081 } 11082 } 11083 11084 // Helper function to filter out cases for constant width constant conversion. 11085 // Don't warn on char array initialization or for non-decimal values. 11086 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11087 SourceLocation CC) { 11088 // If initializing from a constant, and the constant starts with '0', 11089 // then it is a binary, octal, or hexadecimal. Allow these constants 11090 // to fill all the bits, even if there is a sign change. 11091 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11092 const char FirstLiteralCharacter = 11093 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11094 if (FirstLiteralCharacter == '0') 11095 return false; 11096 } 11097 11098 // If the CC location points to a '{', and the type is char, then assume 11099 // assume it is an array initialization. 11100 if (CC.isValid() && T->isCharType()) { 11101 const char FirstContextCharacter = 11102 S.getSourceManager().getCharacterData(CC)[0]; 11103 if (FirstContextCharacter == '{') 11104 return false; 11105 } 11106 11107 return true; 11108 } 11109 11110 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11111 const auto *IL = dyn_cast<IntegerLiteral>(E); 11112 if (!IL) { 11113 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11114 if (UO->getOpcode() == UO_Minus) 11115 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11116 } 11117 } 11118 11119 return IL; 11120 } 11121 11122 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11123 E = E->IgnoreParenImpCasts(); 11124 SourceLocation ExprLoc = E->getExprLoc(); 11125 11126 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11127 BinaryOperator::Opcode Opc = BO->getOpcode(); 11128 Expr::EvalResult Result; 11129 // Do not diagnose unsigned shifts. 11130 if (Opc == BO_Shl) { 11131 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11132 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11133 if (LHS && LHS->getValue() == 0) 11134 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11135 else if (!E->isValueDependent() && LHS && RHS && 11136 RHS->getValue().isNonNegative() && 11137 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11138 S.Diag(ExprLoc, diag::warn_left_shift_always) 11139 << (Result.Val.getInt() != 0); 11140 else if (E->getType()->isSignedIntegerType()) 11141 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11142 } 11143 } 11144 11145 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11146 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11147 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11148 if (!LHS || !RHS) 11149 return; 11150 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11151 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11152 // Do not diagnose common idioms. 11153 return; 11154 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11155 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11156 } 11157 } 11158 11159 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11160 SourceLocation CC, 11161 bool *ICContext = nullptr, 11162 bool IsListInit = false) { 11163 if (E->isTypeDependent() || E->isValueDependent()) return; 11164 11165 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11166 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11167 if (Source == Target) return; 11168 if (Target->isDependentType()) return; 11169 11170 // If the conversion context location is invalid don't complain. We also 11171 // don't want to emit a warning if the issue occurs from the expansion of 11172 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11173 // delay this check as long as possible. Once we detect we are in that 11174 // scenario, we just return. 11175 if (CC.isInvalid()) 11176 return; 11177 11178 if (Source->isAtomicType()) 11179 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11180 11181 // Diagnose implicit casts to bool. 11182 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11183 if (isa<StringLiteral>(E)) 11184 // Warn on string literal to bool. Checks for string literals in logical 11185 // and expressions, for instance, assert(0 && "error here"), are 11186 // prevented by a check in AnalyzeImplicitConversions(). 11187 return DiagnoseImpCast(S, E, T, CC, 11188 diag::warn_impcast_string_literal_to_bool); 11189 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11190 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11191 // This covers the literal expressions that evaluate to Objective-C 11192 // objects. 11193 return DiagnoseImpCast(S, E, T, CC, 11194 diag::warn_impcast_objective_c_literal_to_bool); 11195 } 11196 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11197 // Warn on pointer to bool conversion that is always true. 11198 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11199 SourceRange(CC)); 11200 } 11201 } 11202 11203 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11204 // is a typedef for signed char (macOS), then that constant value has to be 1 11205 // or 0. 11206 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11207 Expr::EvalResult Result; 11208 if (E->EvaluateAsInt(Result, S.getASTContext(), 11209 Expr::SE_AllowSideEffects)) { 11210 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11211 adornObjCBoolConversionDiagWithTernaryFixit( 11212 S, E, 11213 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11214 << Result.Val.getInt().toString(10)); 11215 } 11216 return; 11217 } 11218 } 11219 11220 // Check implicit casts from Objective-C collection literals to specialized 11221 // collection types, e.g., NSArray<NSString *> *. 11222 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11223 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11224 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11225 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11226 11227 // Strip vector types. 11228 if (isa<VectorType>(Source)) { 11229 if (!isa<VectorType>(Target)) { 11230 if (S.SourceMgr.isInSystemMacro(CC)) 11231 return; 11232 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11233 } 11234 11235 // If the vector cast is cast between two vectors of the same size, it is 11236 // a bitcast, not a conversion. 11237 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11238 return; 11239 11240 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11241 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11242 } 11243 if (auto VecTy = dyn_cast<VectorType>(Target)) 11244 Target = VecTy->getElementType().getTypePtr(); 11245 11246 // Strip complex types. 11247 if (isa<ComplexType>(Source)) { 11248 if (!isa<ComplexType>(Target)) { 11249 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11250 return; 11251 11252 return DiagnoseImpCast(S, E, T, CC, 11253 S.getLangOpts().CPlusPlus 11254 ? diag::err_impcast_complex_scalar 11255 : diag::warn_impcast_complex_scalar); 11256 } 11257 11258 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11259 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11260 } 11261 11262 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11263 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11264 11265 // If the source is floating point... 11266 if (SourceBT && SourceBT->isFloatingPoint()) { 11267 // ...and the target is floating point... 11268 if (TargetBT && TargetBT->isFloatingPoint()) { 11269 // ...then warn if we're dropping FP rank. 11270 11271 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11272 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11273 if (Order > 0) { 11274 // Don't warn about float constants that are precisely 11275 // representable in the target type. 11276 Expr::EvalResult result; 11277 if (E->EvaluateAsRValue(result, S.Context)) { 11278 // Value might be a float, a float vector, or a float complex. 11279 if (IsSameFloatAfterCast(result.Val, 11280 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11281 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11282 return; 11283 } 11284 11285 if (S.SourceMgr.isInSystemMacro(CC)) 11286 return; 11287 11288 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11289 } 11290 // ... or possibly if we're increasing rank, too 11291 else if (Order < 0) { 11292 if (S.SourceMgr.isInSystemMacro(CC)) 11293 return; 11294 11295 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11296 } 11297 return; 11298 } 11299 11300 // If the target is integral, always warn. 11301 if (TargetBT && TargetBT->isInteger()) { 11302 if (S.SourceMgr.isInSystemMacro(CC)) 11303 return; 11304 11305 DiagnoseFloatingImpCast(S, E, T, CC); 11306 } 11307 11308 // Detect the case where a call result is converted from floating-point to 11309 // to bool, and the final argument to the call is converted from bool, to 11310 // discover this typo: 11311 // 11312 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11313 // 11314 // FIXME: This is an incredibly special case; is there some more general 11315 // way to detect this class of misplaced-parentheses bug? 11316 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11317 // Check last argument of function call to see if it is an 11318 // implicit cast from a type matching the type the result 11319 // is being cast to. 11320 CallExpr *CEx = cast<CallExpr>(E); 11321 if (unsigned NumArgs = CEx->getNumArgs()) { 11322 Expr *LastA = CEx->getArg(NumArgs - 1); 11323 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11324 if (isa<ImplicitCastExpr>(LastA) && 11325 InnerE->getType()->isBooleanType()) { 11326 // Warn on this floating-point to bool conversion 11327 DiagnoseImpCast(S, E, T, CC, 11328 diag::warn_impcast_floating_point_to_bool); 11329 } 11330 } 11331 } 11332 return; 11333 } 11334 11335 // Valid casts involving fixed point types should be accounted for here. 11336 if (Source->isFixedPointType()) { 11337 if (Target->isUnsaturatedFixedPointType()) { 11338 Expr::EvalResult Result; 11339 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11340 S.isConstantEvaluated())) { 11341 APFixedPoint Value = Result.Val.getFixedPoint(); 11342 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11343 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11344 if (Value > MaxVal || Value < MinVal) { 11345 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11346 S.PDiag(diag::warn_impcast_fixed_point_range) 11347 << Value.toString() << T 11348 << E->getSourceRange() 11349 << clang::SourceRange(CC)); 11350 return; 11351 } 11352 } 11353 } else if (Target->isIntegerType()) { 11354 Expr::EvalResult Result; 11355 if (!S.isConstantEvaluated() && 11356 E->EvaluateAsFixedPoint(Result, S.Context, 11357 Expr::SE_AllowSideEffects)) { 11358 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11359 11360 bool Overflowed; 11361 llvm::APSInt IntResult = FXResult.convertToInt( 11362 S.Context.getIntWidth(T), 11363 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11364 11365 if (Overflowed) { 11366 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11367 S.PDiag(diag::warn_impcast_fixed_point_range) 11368 << FXResult.toString() << T 11369 << E->getSourceRange() 11370 << clang::SourceRange(CC)); 11371 return; 11372 } 11373 } 11374 } 11375 } else if (Target->isUnsaturatedFixedPointType()) { 11376 if (Source->isIntegerType()) { 11377 Expr::EvalResult Result; 11378 if (!S.isConstantEvaluated() && 11379 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11380 llvm::APSInt Value = Result.Val.getInt(); 11381 11382 bool Overflowed; 11383 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11384 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11385 11386 if (Overflowed) { 11387 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11388 S.PDiag(diag::warn_impcast_fixed_point_range) 11389 << Value.toString(/*Radix=*/10) << T 11390 << E->getSourceRange() 11391 << clang::SourceRange(CC)); 11392 return; 11393 } 11394 } 11395 } 11396 } 11397 11398 // If we are casting an integer type to a floating point type without 11399 // initialization-list syntax, we might lose accuracy if the floating 11400 // point type has a narrower significand than the integer type. 11401 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11402 TargetBT->isFloatingType() && !IsListInit) { 11403 // Determine the number of precision bits in the source integer type. 11404 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11405 unsigned int SourcePrecision = SourceRange.Width; 11406 11407 // Determine the number of precision bits in the 11408 // target floating point type. 11409 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11410 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11411 11412 if (SourcePrecision > 0 && TargetPrecision > 0 && 11413 SourcePrecision > TargetPrecision) { 11414 11415 llvm::APSInt SourceInt; 11416 if (E->isIntegerConstantExpr(SourceInt, S.Context)) { 11417 // If the source integer is a constant, convert it to the target 11418 // floating point type. Issue a warning if the value changes 11419 // during the whole conversion. 11420 llvm::APFloat TargetFloatValue( 11421 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11422 llvm::APFloat::opStatus ConversionStatus = 11423 TargetFloatValue.convertFromAPInt( 11424 SourceInt, SourceBT->isSignedInteger(), 11425 llvm::APFloat::rmNearestTiesToEven); 11426 11427 if (ConversionStatus != llvm::APFloat::opOK) { 11428 std::string PrettySourceValue = SourceInt.toString(10); 11429 SmallString<32> PrettyTargetValue; 11430 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11431 11432 S.DiagRuntimeBehavior( 11433 E->getExprLoc(), E, 11434 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11435 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11436 << E->getSourceRange() << clang::SourceRange(CC)); 11437 } 11438 } else { 11439 // Otherwise, the implicit conversion may lose precision. 11440 DiagnoseImpCast(S, E, T, CC, 11441 diag::warn_impcast_integer_float_precision); 11442 } 11443 } 11444 } 11445 11446 DiagnoseNullConversion(S, E, T, CC); 11447 11448 S.DiscardMisalignedMemberAddress(Target, E); 11449 11450 if (Target->isBooleanType()) 11451 DiagnoseIntInBoolContext(S, E); 11452 11453 if (!Source->isIntegerType() || !Target->isIntegerType()) 11454 return; 11455 11456 // TODO: remove this early return once the false positives for constant->bool 11457 // in templates, macros, etc, are reduced or removed. 11458 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11459 return; 11460 11461 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11462 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11463 return adornObjCBoolConversionDiagWithTernaryFixit( 11464 S, E, 11465 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11466 << E->getType()); 11467 } 11468 11469 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11470 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11471 11472 if (SourceRange.Width > TargetRange.Width) { 11473 // If the source is a constant, use a default-on diagnostic. 11474 // TODO: this should happen for bitfield stores, too. 11475 Expr::EvalResult Result; 11476 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11477 S.isConstantEvaluated())) { 11478 llvm::APSInt Value(32); 11479 Value = Result.Val.getInt(); 11480 11481 if (S.SourceMgr.isInSystemMacro(CC)) 11482 return; 11483 11484 std::string PrettySourceValue = Value.toString(10); 11485 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11486 11487 S.DiagRuntimeBehavior( 11488 E->getExprLoc(), E, 11489 S.PDiag(diag::warn_impcast_integer_precision_constant) 11490 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11491 << E->getSourceRange() << clang::SourceRange(CC)); 11492 return; 11493 } 11494 11495 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11496 if (S.SourceMgr.isInSystemMacro(CC)) 11497 return; 11498 11499 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11500 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11501 /* pruneControlFlow */ true); 11502 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11503 } 11504 11505 if (TargetRange.Width > SourceRange.Width) { 11506 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11507 if (UO->getOpcode() == UO_Minus) 11508 if (Source->isUnsignedIntegerType()) { 11509 if (Target->isUnsignedIntegerType()) 11510 return DiagnoseImpCast(S, E, T, CC, 11511 diag::warn_impcast_high_order_zero_bits); 11512 if (Target->isSignedIntegerType()) 11513 return DiagnoseImpCast(S, E, T, CC, 11514 diag::warn_impcast_nonnegative_result); 11515 } 11516 } 11517 11518 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11519 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11520 // Warn when doing a signed to signed conversion, warn if the positive 11521 // source value is exactly the width of the target type, which will 11522 // cause a negative value to be stored. 11523 11524 Expr::EvalResult Result; 11525 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11526 !S.SourceMgr.isInSystemMacro(CC)) { 11527 llvm::APSInt Value = Result.Val.getInt(); 11528 if (isSameWidthConstantConversion(S, E, T, CC)) { 11529 std::string PrettySourceValue = Value.toString(10); 11530 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11531 11532 S.DiagRuntimeBehavior( 11533 E->getExprLoc(), E, 11534 S.PDiag(diag::warn_impcast_integer_precision_constant) 11535 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11536 << E->getSourceRange() << clang::SourceRange(CC)); 11537 return; 11538 } 11539 } 11540 11541 // Fall through for non-constants to give a sign conversion warning. 11542 } 11543 11544 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11545 (!TargetRange.NonNegative && SourceRange.NonNegative && 11546 SourceRange.Width == TargetRange.Width)) { 11547 if (S.SourceMgr.isInSystemMacro(CC)) 11548 return; 11549 11550 unsigned DiagID = diag::warn_impcast_integer_sign; 11551 11552 // Traditionally, gcc has warned about this under -Wsign-compare. 11553 // We also want to warn about it in -Wconversion. 11554 // So if -Wconversion is off, use a completely identical diagnostic 11555 // in the sign-compare group. 11556 // The conditional-checking code will 11557 if (ICContext) { 11558 DiagID = diag::warn_impcast_integer_sign_conditional; 11559 *ICContext = true; 11560 } 11561 11562 return DiagnoseImpCast(S, E, T, CC, DiagID); 11563 } 11564 11565 // Diagnose conversions between different enumeration types. 11566 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11567 // type, to give us better diagnostics. 11568 QualType SourceType = E->getType(); 11569 if (!S.getLangOpts().CPlusPlus) { 11570 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11571 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11572 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11573 SourceType = S.Context.getTypeDeclType(Enum); 11574 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11575 } 11576 } 11577 11578 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11579 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11580 if (SourceEnum->getDecl()->hasNameForLinkage() && 11581 TargetEnum->getDecl()->hasNameForLinkage() && 11582 SourceEnum != TargetEnum) { 11583 if (S.SourceMgr.isInSystemMacro(CC)) 11584 return; 11585 11586 return DiagnoseImpCast(S, E, SourceType, T, CC, 11587 diag::warn_impcast_different_enum_types); 11588 } 11589 } 11590 11591 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11592 SourceLocation CC, QualType T); 11593 11594 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11595 SourceLocation CC, bool &ICContext) { 11596 E = E->IgnoreParenImpCasts(); 11597 11598 if (isa<ConditionalOperator>(E)) 11599 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11600 11601 AnalyzeImplicitConversions(S, E, CC); 11602 if (E->getType() != T) 11603 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11604 } 11605 11606 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11607 SourceLocation CC, QualType T) { 11608 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11609 11610 bool Suspicious = false; 11611 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11612 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11613 11614 if (T->isBooleanType()) 11615 DiagnoseIntInBoolContext(S, E); 11616 11617 // If -Wconversion would have warned about either of the candidates 11618 // for a signedness conversion to the context type... 11619 if (!Suspicious) return; 11620 11621 // ...but it's currently ignored... 11622 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11623 return; 11624 11625 // ...then check whether it would have warned about either of the 11626 // candidates for a signedness conversion to the condition type. 11627 if (E->getType() == T) return; 11628 11629 Suspicious = false; 11630 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11631 E->getType(), CC, &Suspicious); 11632 if (!Suspicious) 11633 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11634 E->getType(), CC, &Suspicious); 11635 } 11636 11637 /// Check conversion of given expression to boolean. 11638 /// Input argument E is a logical expression. 11639 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11640 if (S.getLangOpts().Bool) 11641 return; 11642 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11643 return; 11644 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11645 } 11646 11647 /// AnalyzeImplicitConversions - Find and report any interesting 11648 /// implicit conversions in the given expression. There are a couple 11649 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 11650 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 11651 bool IsListInit/*= false*/) { 11652 QualType T = OrigE->getType(); 11653 Expr *E = OrigE->IgnoreParenImpCasts(); 11654 11655 // Propagate whether we are in a C++ list initialization expression. 11656 // If so, we do not issue warnings for implicit int-float conversion 11657 // precision loss, because C++11 narrowing already handles it. 11658 IsListInit = 11659 IsListInit || (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 11660 11661 if (E->isTypeDependent() || E->isValueDependent()) 11662 return; 11663 11664 Expr *SourceExpr = E; 11665 // Examine, but don't traverse into the source expression of an 11666 // OpaqueValueExpr, since it may have multiple parents and we don't want to 11667 // emit duplicate diagnostics. Its fine to examine the form or attempt to 11668 // evaluate it in the context of checking the specific conversion to T though. 11669 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11670 if (auto *Src = OVE->getSourceExpr()) 11671 SourceExpr = Src; 11672 11673 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 11674 if (UO->getOpcode() == UO_Not && 11675 UO->getSubExpr()->isKnownToHaveBooleanValue()) 11676 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 11677 << OrigE->getSourceRange() << T->isBooleanType() 11678 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 11679 11680 // For conditional operators, we analyze the arguments as if they 11681 // were being fed directly into the output. 11682 if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) { 11683 CheckConditionalOperator(S, CO, CC, T); 11684 return; 11685 } 11686 11687 // Check implicit argument conversions for function calls. 11688 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 11689 CheckImplicitArgumentConversions(S, Call, CC); 11690 11691 // Go ahead and check any implicit conversions we might have skipped. 11692 // The non-canonical typecheck is just an optimization; 11693 // CheckImplicitConversion will filter out dead implicit conversions. 11694 if (SourceExpr->getType() != T) 11695 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 11696 11697 // Now continue drilling into this expression. 11698 11699 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11700 // The bound subexpressions in a PseudoObjectExpr are not reachable 11701 // as transitive children. 11702 // FIXME: Use a more uniform representation for this. 11703 for (auto *SE : POE->semantics()) 11704 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11705 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC, IsListInit); 11706 } 11707 11708 // Skip past explicit casts. 11709 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11710 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11711 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11712 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11713 return AnalyzeImplicitConversions(S, E, CC, IsListInit); 11714 } 11715 11716 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11717 // Do a somewhat different check with comparison operators. 11718 if (BO->isComparisonOp()) 11719 return AnalyzeComparison(S, BO); 11720 11721 // And with simple assignments. 11722 if (BO->getOpcode() == BO_Assign) 11723 return AnalyzeAssignment(S, BO); 11724 // And with compound assignments. 11725 if (BO->isAssignmentOp()) 11726 return AnalyzeCompoundAssignment(S, BO); 11727 } 11728 11729 // These break the otherwise-useful invariant below. Fortunately, 11730 // we don't really need to recurse into them, because any internal 11731 // expressions should have been analyzed already when they were 11732 // built into statements. 11733 if (isa<StmtExpr>(E)) return; 11734 11735 // Don't descend into unevaluated contexts. 11736 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11737 11738 // Now just recurse over the expression's children. 11739 CC = E->getExprLoc(); 11740 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11741 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11742 for (Stmt *SubStmt : E->children()) { 11743 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11744 if (!ChildExpr) 11745 continue; 11746 11747 if (IsLogicalAndOperator && 11748 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11749 // Ignore checking string literals that are in logical and operators. 11750 // This is a common pattern for asserts. 11751 continue; 11752 AnalyzeImplicitConversions(S, ChildExpr, CC, IsListInit); 11753 } 11754 11755 if (BO && BO->isLogicalOp()) { 11756 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11757 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11758 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11759 11760 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 11761 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11762 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11763 } 11764 11765 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 11766 if (U->getOpcode() == UO_LNot) { 11767 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 11768 } else if (U->getOpcode() != UO_AddrOf) { 11769 if (U->getSubExpr()->getType()->isAtomicType()) 11770 S.Diag(U->getSubExpr()->getBeginLoc(), 11771 diag::warn_atomic_implicit_seq_cst); 11772 } 11773 } 11774 } 11775 11776 /// Diagnose integer type and any valid implicit conversion to it. 11777 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 11778 // Taking into account implicit conversions, 11779 // allow any integer. 11780 if (!E->getType()->isIntegerType()) { 11781 S.Diag(E->getBeginLoc(), 11782 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 11783 return true; 11784 } 11785 // Potentially emit standard warnings for implicit conversions if enabled 11786 // using -Wconversion. 11787 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 11788 return false; 11789 } 11790 11791 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 11792 // Returns true when emitting a warning about taking the address of a reference. 11793 static bool CheckForReference(Sema &SemaRef, const Expr *E, 11794 const PartialDiagnostic &PD) { 11795 E = E->IgnoreParenImpCasts(); 11796 11797 const FunctionDecl *FD = nullptr; 11798 11799 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11800 if (!DRE->getDecl()->getType()->isReferenceType()) 11801 return false; 11802 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11803 if (!M->getMemberDecl()->getType()->isReferenceType()) 11804 return false; 11805 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 11806 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 11807 return false; 11808 FD = Call->getDirectCallee(); 11809 } else { 11810 return false; 11811 } 11812 11813 SemaRef.Diag(E->getExprLoc(), PD); 11814 11815 // If possible, point to location of function. 11816 if (FD) { 11817 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 11818 } 11819 11820 return true; 11821 } 11822 11823 // Returns true if the SourceLocation is expanded from any macro body. 11824 // Returns false if the SourceLocation is invalid, is from not in a macro 11825 // expansion, or is from expanded from a top-level macro argument. 11826 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 11827 if (Loc.isInvalid()) 11828 return false; 11829 11830 while (Loc.isMacroID()) { 11831 if (SM.isMacroBodyExpansion(Loc)) 11832 return true; 11833 Loc = SM.getImmediateMacroCallerLoc(Loc); 11834 } 11835 11836 return false; 11837 } 11838 11839 /// Diagnose pointers that are always non-null. 11840 /// \param E the expression containing the pointer 11841 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 11842 /// compared to a null pointer 11843 /// \param IsEqual True when the comparison is equal to a null pointer 11844 /// \param Range Extra SourceRange to highlight in the diagnostic 11845 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 11846 Expr::NullPointerConstantKind NullKind, 11847 bool IsEqual, SourceRange Range) { 11848 if (!E) 11849 return; 11850 11851 // Don't warn inside macros. 11852 if (E->getExprLoc().isMacroID()) { 11853 const SourceManager &SM = getSourceManager(); 11854 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 11855 IsInAnyMacroBody(SM, Range.getBegin())) 11856 return; 11857 } 11858 E = E->IgnoreImpCasts(); 11859 11860 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 11861 11862 if (isa<CXXThisExpr>(E)) { 11863 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 11864 : diag::warn_this_bool_conversion; 11865 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 11866 return; 11867 } 11868 11869 bool IsAddressOf = false; 11870 11871 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 11872 if (UO->getOpcode() != UO_AddrOf) 11873 return; 11874 IsAddressOf = true; 11875 E = UO->getSubExpr(); 11876 } 11877 11878 if (IsAddressOf) { 11879 unsigned DiagID = IsCompare 11880 ? diag::warn_address_of_reference_null_compare 11881 : diag::warn_address_of_reference_bool_conversion; 11882 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 11883 << IsEqual; 11884 if (CheckForReference(*this, E, PD)) { 11885 return; 11886 } 11887 } 11888 11889 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 11890 bool IsParam = isa<NonNullAttr>(NonnullAttr); 11891 std::string Str; 11892 llvm::raw_string_ostream S(Str); 11893 E->printPretty(S, nullptr, getPrintingPolicy()); 11894 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 11895 : diag::warn_cast_nonnull_to_bool; 11896 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 11897 << E->getSourceRange() << Range << IsEqual; 11898 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 11899 }; 11900 11901 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 11902 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 11903 if (auto *Callee = Call->getDirectCallee()) { 11904 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 11905 ComplainAboutNonnullParamOrCall(A); 11906 return; 11907 } 11908 } 11909 } 11910 11911 // Expect to find a single Decl. Skip anything more complicated. 11912 ValueDecl *D = nullptr; 11913 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 11914 D = R->getDecl(); 11915 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 11916 D = M->getMemberDecl(); 11917 } 11918 11919 // Weak Decls can be null. 11920 if (!D || D->isWeak()) 11921 return; 11922 11923 // Check for parameter decl with nonnull attribute 11924 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 11925 if (getCurFunction() && 11926 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 11927 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 11928 ComplainAboutNonnullParamOrCall(A); 11929 return; 11930 } 11931 11932 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 11933 // Skip function template not specialized yet. 11934 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 11935 return; 11936 auto ParamIter = llvm::find(FD->parameters(), PV); 11937 assert(ParamIter != FD->param_end()); 11938 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 11939 11940 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 11941 if (!NonNull->args_size()) { 11942 ComplainAboutNonnullParamOrCall(NonNull); 11943 return; 11944 } 11945 11946 for (const ParamIdx &ArgNo : NonNull->args()) { 11947 if (ArgNo.getASTIndex() == ParamNo) { 11948 ComplainAboutNonnullParamOrCall(NonNull); 11949 return; 11950 } 11951 } 11952 } 11953 } 11954 } 11955 } 11956 11957 QualType T = D->getType(); 11958 const bool IsArray = T->isArrayType(); 11959 const bool IsFunction = T->isFunctionType(); 11960 11961 // Address of function is used to silence the function warning. 11962 if (IsAddressOf && IsFunction) { 11963 return; 11964 } 11965 11966 // Found nothing. 11967 if (!IsAddressOf && !IsFunction && !IsArray) 11968 return; 11969 11970 // Pretty print the expression for the diagnostic. 11971 std::string Str; 11972 llvm::raw_string_ostream S(Str); 11973 E->printPretty(S, nullptr, getPrintingPolicy()); 11974 11975 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 11976 : diag::warn_impcast_pointer_to_bool; 11977 enum { 11978 AddressOf, 11979 FunctionPointer, 11980 ArrayPointer 11981 } DiagType; 11982 if (IsAddressOf) 11983 DiagType = AddressOf; 11984 else if (IsFunction) 11985 DiagType = FunctionPointer; 11986 else if (IsArray) 11987 DiagType = ArrayPointer; 11988 else 11989 llvm_unreachable("Could not determine diagnostic."); 11990 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 11991 << Range << IsEqual; 11992 11993 if (!IsFunction) 11994 return; 11995 11996 // Suggest '&' to silence the function warning. 11997 Diag(E->getExprLoc(), diag::note_function_warning_silence) 11998 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 11999 12000 // Check to see if '()' fixit should be emitted. 12001 QualType ReturnType; 12002 UnresolvedSet<4> NonTemplateOverloads; 12003 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12004 if (ReturnType.isNull()) 12005 return; 12006 12007 if (IsCompare) { 12008 // There are two cases here. If there is null constant, the only suggest 12009 // for a pointer return type. If the null is 0, then suggest if the return 12010 // type is a pointer or an integer type. 12011 if (!ReturnType->isPointerType()) { 12012 if (NullKind == Expr::NPCK_ZeroExpression || 12013 NullKind == Expr::NPCK_ZeroLiteral) { 12014 if (!ReturnType->isIntegerType()) 12015 return; 12016 } else { 12017 return; 12018 } 12019 } 12020 } else { // !IsCompare 12021 // For function to bool, only suggest if the function pointer has bool 12022 // return type. 12023 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12024 return; 12025 } 12026 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12027 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12028 } 12029 12030 /// Diagnoses "dangerous" implicit conversions within the given 12031 /// expression (which is a full expression). Implements -Wconversion 12032 /// and -Wsign-compare. 12033 /// 12034 /// \param CC the "context" location of the implicit conversion, i.e. 12035 /// the most location of the syntactic entity requiring the implicit 12036 /// conversion 12037 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12038 // Don't diagnose in unevaluated contexts. 12039 if (isUnevaluatedContext()) 12040 return; 12041 12042 // Don't diagnose for value- or type-dependent expressions. 12043 if (E->isTypeDependent() || E->isValueDependent()) 12044 return; 12045 12046 // Check for array bounds violations in cases where the check isn't triggered 12047 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12048 // ArraySubscriptExpr is on the RHS of a variable initialization. 12049 CheckArrayAccess(E); 12050 12051 // This is not the right CC for (e.g.) a variable initialization. 12052 AnalyzeImplicitConversions(*this, E, CC); 12053 } 12054 12055 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12056 /// Input argument E is a logical expression. 12057 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12058 ::CheckBoolLikeConversion(*this, E, CC); 12059 } 12060 12061 /// Diagnose when expression is an integer constant expression and its evaluation 12062 /// results in integer overflow 12063 void Sema::CheckForIntOverflow (Expr *E) { 12064 // Use a work list to deal with nested struct initializers. 12065 SmallVector<Expr *, 2> Exprs(1, E); 12066 12067 do { 12068 Expr *OriginalE = Exprs.pop_back_val(); 12069 Expr *E = OriginalE->IgnoreParenCasts(); 12070 12071 if (isa<BinaryOperator>(E)) { 12072 E->EvaluateForOverflow(Context); 12073 continue; 12074 } 12075 12076 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12077 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12078 else if (isa<ObjCBoxedExpr>(OriginalE)) 12079 E->EvaluateForOverflow(Context); 12080 else if (auto Call = dyn_cast<CallExpr>(E)) 12081 Exprs.append(Call->arg_begin(), Call->arg_end()); 12082 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12083 Exprs.append(Message->arg_begin(), Message->arg_end()); 12084 } while (!Exprs.empty()); 12085 } 12086 12087 namespace { 12088 12089 /// Visitor for expressions which looks for unsequenced operations on the 12090 /// same object. 12091 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12092 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12093 12094 /// A tree of sequenced regions within an expression. Two regions are 12095 /// unsequenced if one is an ancestor or a descendent of the other. When we 12096 /// finish processing an expression with sequencing, such as a comma 12097 /// expression, we fold its tree nodes into its parent, since they are 12098 /// unsequenced with respect to nodes we will visit later. 12099 class SequenceTree { 12100 struct Value { 12101 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12102 unsigned Parent : 31; 12103 unsigned Merged : 1; 12104 }; 12105 SmallVector<Value, 8> Values; 12106 12107 public: 12108 /// A region within an expression which may be sequenced with respect 12109 /// to some other region. 12110 class Seq { 12111 friend class SequenceTree; 12112 12113 unsigned Index; 12114 12115 explicit Seq(unsigned N) : Index(N) {} 12116 12117 public: 12118 Seq() : Index(0) {} 12119 }; 12120 12121 SequenceTree() { Values.push_back(Value(0)); } 12122 Seq root() const { return Seq(0); } 12123 12124 /// Create a new sequence of operations, which is an unsequenced 12125 /// subset of \p Parent. This sequence of operations is sequenced with 12126 /// respect to other children of \p Parent. 12127 Seq allocate(Seq Parent) { 12128 Values.push_back(Value(Parent.Index)); 12129 return Seq(Values.size() - 1); 12130 } 12131 12132 /// Merge a sequence of operations into its parent. 12133 void merge(Seq S) { 12134 Values[S.Index].Merged = true; 12135 } 12136 12137 /// Determine whether two operations are unsequenced. This operation 12138 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12139 /// should have been merged into its parent as appropriate. 12140 bool isUnsequenced(Seq Cur, Seq Old) { 12141 unsigned C = representative(Cur.Index); 12142 unsigned Target = representative(Old.Index); 12143 while (C >= Target) { 12144 if (C == Target) 12145 return true; 12146 C = Values[C].Parent; 12147 } 12148 return false; 12149 } 12150 12151 private: 12152 /// Pick a representative for a sequence. 12153 unsigned representative(unsigned K) { 12154 if (Values[K].Merged) 12155 // Perform path compression as we go. 12156 return Values[K].Parent = representative(Values[K].Parent); 12157 return K; 12158 } 12159 }; 12160 12161 /// An object for which we can track unsequenced uses. 12162 using Object = const NamedDecl *; 12163 12164 /// Different flavors of object usage which we track. We only track the 12165 /// least-sequenced usage of each kind. 12166 enum UsageKind { 12167 /// A read of an object. Multiple unsequenced reads are OK. 12168 UK_Use, 12169 12170 /// A modification of an object which is sequenced before the value 12171 /// computation of the expression, such as ++n in C++. 12172 UK_ModAsValue, 12173 12174 /// A modification of an object which is not sequenced before the value 12175 /// computation of the expression, such as n++. 12176 UK_ModAsSideEffect, 12177 12178 UK_Count = UK_ModAsSideEffect + 1 12179 }; 12180 12181 /// Bundle together a sequencing region and the expression corresponding 12182 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12183 struct Usage { 12184 const Expr *UsageExpr; 12185 SequenceTree::Seq Seq; 12186 12187 Usage() : UsageExpr(nullptr), Seq() {} 12188 }; 12189 12190 struct UsageInfo { 12191 Usage Uses[UK_Count]; 12192 12193 /// Have we issued a diagnostic for this object already? 12194 bool Diagnosed; 12195 12196 UsageInfo() : Uses(), Diagnosed(false) {} 12197 }; 12198 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12199 12200 Sema &SemaRef; 12201 12202 /// Sequenced regions within the expression. 12203 SequenceTree Tree; 12204 12205 /// Declaration modifications and references which we have seen. 12206 UsageInfoMap UsageMap; 12207 12208 /// The region we are currently within. 12209 SequenceTree::Seq Region; 12210 12211 /// Filled in with declarations which were modified as a side-effect 12212 /// (that is, post-increment operations). 12213 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12214 12215 /// Expressions to check later. We defer checking these to reduce 12216 /// stack usage. 12217 SmallVectorImpl<const Expr *> &WorkList; 12218 12219 /// RAII object wrapping the visitation of a sequenced subexpression of an 12220 /// expression. At the end of this process, the side-effects of the evaluation 12221 /// become sequenced with respect to the value computation of the result, so 12222 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12223 /// UK_ModAsValue. 12224 struct SequencedSubexpression { 12225 SequencedSubexpression(SequenceChecker &Self) 12226 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12227 Self.ModAsSideEffect = &ModAsSideEffect; 12228 } 12229 12230 ~SequencedSubexpression() { 12231 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12232 // Add a new usage with usage kind UK_ModAsValue, and then restore 12233 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12234 // the previous one was empty). 12235 UsageInfo &UI = Self.UsageMap[M.first]; 12236 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12237 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12238 SideEffectUsage = M.second; 12239 } 12240 Self.ModAsSideEffect = OldModAsSideEffect; 12241 } 12242 12243 SequenceChecker &Self; 12244 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12245 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12246 }; 12247 12248 /// RAII object wrapping the visitation of a subexpression which we might 12249 /// choose to evaluate as a constant. If any subexpression is evaluated and 12250 /// found to be non-constant, this allows us to suppress the evaluation of 12251 /// the outer expression. 12252 class EvaluationTracker { 12253 public: 12254 EvaluationTracker(SequenceChecker &Self) 12255 : Self(Self), Prev(Self.EvalTracker) { 12256 Self.EvalTracker = this; 12257 } 12258 12259 ~EvaluationTracker() { 12260 Self.EvalTracker = Prev; 12261 if (Prev) 12262 Prev->EvalOK &= EvalOK; 12263 } 12264 12265 bool evaluate(const Expr *E, bool &Result) { 12266 if (!EvalOK || E->isValueDependent()) 12267 return false; 12268 EvalOK = E->EvaluateAsBooleanCondition( 12269 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12270 return EvalOK; 12271 } 12272 12273 private: 12274 SequenceChecker &Self; 12275 EvaluationTracker *Prev; 12276 bool EvalOK = true; 12277 } *EvalTracker = nullptr; 12278 12279 /// Find the object which is produced by the specified expression, 12280 /// if any. 12281 Object getObject(const Expr *E, bool Mod) const { 12282 E = E->IgnoreParenCasts(); 12283 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12284 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12285 return getObject(UO->getSubExpr(), Mod); 12286 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12287 if (BO->getOpcode() == BO_Comma) 12288 return getObject(BO->getRHS(), Mod); 12289 if (Mod && BO->isAssignmentOp()) 12290 return getObject(BO->getLHS(), Mod); 12291 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12292 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12293 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12294 return ME->getMemberDecl(); 12295 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12296 // FIXME: If this is a reference, map through to its value. 12297 return DRE->getDecl(); 12298 return nullptr; 12299 } 12300 12301 /// Note that an object \p O was modified or used by an expression 12302 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12303 /// the object \p O as obtained via the \p UsageMap. 12304 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12305 // Get the old usage for the given object and usage kind. 12306 Usage &U = UI.Uses[UK]; 12307 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12308 // If we have a modification as side effect and are in a sequenced 12309 // subexpression, save the old Usage so that we can restore it later 12310 // in SequencedSubexpression::~SequencedSubexpression. 12311 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12312 ModAsSideEffect->push_back(std::make_pair(O, U)); 12313 // Then record the new usage with the current sequencing region. 12314 U.UsageExpr = UsageExpr; 12315 U.Seq = Region; 12316 } 12317 } 12318 12319 /// Check whether a modification or use of an object \p O in an expression 12320 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12321 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12322 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12323 /// usage and false we are checking for a mod-use unsequenced usage. 12324 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12325 UsageKind OtherKind, bool IsModMod) { 12326 if (UI.Diagnosed) 12327 return; 12328 12329 const Usage &U = UI.Uses[OtherKind]; 12330 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12331 return; 12332 12333 const Expr *Mod = U.UsageExpr; 12334 const Expr *ModOrUse = UsageExpr; 12335 if (OtherKind == UK_Use) 12336 std::swap(Mod, ModOrUse); 12337 12338 SemaRef.DiagRuntimeBehavior( 12339 Mod->getExprLoc(), {Mod, ModOrUse}, 12340 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12341 : diag::warn_unsequenced_mod_use) 12342 << O << SourceRange(ModOrUse->getExprLoc())); 12343 UI.Diagnosed = true; 12344 } 12345 12346 // A note on note{Pre, Post}{Use, Mod}: 12347 // 12348 // (It helps to follow the algorithm with an expression such as 12349 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12350 // operations before C++17 and both are well-defined in C++17). 12351 // 12352 // When visiting a node which uses/modify an object we first call notePreUse 12353 // or notePreMod before visiting its sub-expression(s). At this point the 12354 // children of the current node have not yet been visited and so the eventual 12355 // uses/modifications resulting from the children of the current node have not 12356 // been recorded yet. 12357 // 12358 // We then visit the children of the current node. After that notePostUse or 12359 // notePostMod is called. These will 1) detect an unsequenced modification 12360 // as side effect (as in "k++ + k") and 2) add a new usage with the 12361 // appropriate usage kind. 12362 // 12363 // We also have to be careful that some operation sequences modification as 12364 // side effect as well (for example: || or ,). To account for this we wrap 12365 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12366 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12367 // which record usages which are modifications as side effect, and then 12368 // downgrade them (or more accurately restore the previous usage which was a 12369 // modification as side effect) when exiting the scope of the sequenced 12370 // subexpression. 12371 12372 void notePreUse(Object O, const Expr *UseExpr) { 12373 UsageInfo &UI = UsageMap[O]; 12374 // Uses conflict with other modifications. 12375 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12376 } 12377 12378 void notePostUse(Object O, const Expr *UseExpr) { 12379 UsageInfo &UI = UsageMap[O]; 12380 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12381 /*IsModMod=*/false); 12382 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12383 } 12384 12385 void notePreMod(Object O, const Expr *ModExpr) { 12386 UsageInfo &UI = UsageMap[O]; 12387 // Modifications conflict with other modifications and with uses. 12388 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12389 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12390 } 12391 12392 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12393 UsageInfo &UI = UsageMap[O]; 12394 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12395 /*IsModMod=*/true); 12396 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12397 } 12398 12399 public: 12400 SequenceChecker(Sema &S, const Expr *E, 12401 SmallVectorImpl<const Expr *> &WorkList) 12402 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12403 Visit(E); 12404 // Silence a -Wunused-private-field since WorkList is now unused. 12405 // TODO: Evaluate if it can be used, and if not remove it. 12406 (void)this->WorkList; 12407 } 12408 12409 void VisitStmt(const Stmt *S) { 12410 // Skip all statements which aren't expressions for now. 12411 } 12412 12413 void VisitExpr(const Expr *E) { 12414 // By default, just recurse to evaluated subexpressions. 12415 Base::VisitStmt(E); 12416 } 12417 12418 void VisitCastExpr(const CastExpr *E) { 12419 Object O = Object(); 12420 if (E->getCastKind() == CK_LValueToRValue) 12421 O = getObject(E->getSubExpr(), false); 12422 12423 if (O) 12424 notePreUse(O, E); 12425 VisitExpr(E); 12426 if (O) 12427 notePostUse(O, E); 12428 } 12429 12430 void VisitSequencedExpressions(const Expr *SequencedBefore, 12431 const Expr *SequencedAfter) { 12432 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12433 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12434 SequenceTree::Seq OldRegion = Region; 12435 12436 { 12437 SequencedSubexpression SeqBefore(*this); 12438 Region = BeforeRegion; 12439 Visit(SequencedBefore); 12440 } 12441 12442 Region = AfterRegion; 12443 Visit(SequencedAfter); 12444 12445 Region = OldRegion; 12446 12447 Tree.merge(BeforeRegion); 12448 Tree.merge(AfterRegion); 12449 } 12450 12451 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12452 // C++17 [expr.sub]p1: 12453 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12454 // expression E1 is sequenced before the expression E2. 12455 if (SemaRef.getLangOpts().CPlusPlus17) 12456 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12457 else { 12458 Visit(ASE->getLHS()); 12459 Visit(ASE->getRHS()); 12460 } 12461 } 12462 12463 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12464 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12465 void VisitBinPtrMem(const BinaryOperator *BO) { 12466 // C++17 [expr.mptr.oper]p4: 12467 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12468 // the expression E1 is sequenced before the expression E2. 12469 if (SemaRef.getLangOpts().CPlusPlus17) 12470 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12471 else { 12472 Visit(BO->getLHS()); 12473 Visit(BO->getRHS()); 12474 } 12475 } 12476 12477 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12478 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12479 void VisitBinShlShr(const BinaryOperator *BO) { 12480 // C++17 [expr.shift]p4: 12481 // The expression E1 is sequenced before the expression E2. 12482 if (SemaRef.getLangOpts().CPlusPlus17) 12483 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12484 else { 12485 Visit(BO->getLHS()); 12486 Visit(BO->getRHS()); 12487 } 12488 } 12489 12490 void VisitBinComma(const BinaryOperator *BO) { 12491 // C++11 [expr.comma]p1: 12492 // Every value computation and side effect associated with the left 12493 // expression is sequenced before every value computation and side 12494 // effect associated with the right expression. 12495 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12496 } 12497 12498 void VisitBinAssign(const BinaryOperator *BO) { 12499 SequenceTree::Seq RHSRegion; 12500 SequenceTree::Seq LHSRegion; 12501 if (SemaRef.getLangOpts().CPlusPlus17) { 12502 RHSRegion = Tree.allocate(Region); 12503 LHSRegion = Tree.allocate(Region); 12504 } else { 12505 RHSRegion = Region; 12506 LHSRegion = Region; 12507 } 12508 SequenceTree::Seq OldRegion = Region; 12509 12510 // C++11 [expr.ass]p1: 12511 // [...] the assignment is sequenced after the value computation 12512 // of the right and left operands, [...] 12513 // 12514 // so check it before inspecting the operands and update the 12515 // map afterwards. 12516 Object O = getObject(BO->getLHS(), /*Mod=*/true); 12517 if (O) 12518 notePreMod(O, BO); 12519 12520 if (SemaRef.getLangOpts().CPlusPlus17) { 12521 // C++17 [expr.ass]p1: 12522 // [...] The right operand is sequenced before the left operand. [...] 12523 { 12524 SequencedSubexpression SeqBefore(*this); 12525 Region = RHSRegion; 12526 Visit(BO->getRHS()); 12527 } 12528 12529 Region = LHSRegion; 12530 Visit(BO->getLHS()); 12531 12532 if (O && isa<CompoundAssignOperator>(BO)) 12533 notePostUse(O, BO); 12534 12535 } else { 12536 // C++11 does not specify any sequencing between the LHS and RHS. 12537 Region = LHSRegion; 12538 Visit(BO->getLHS()); 12539 12540 if (O && isa<CompoundAssignOperator>(BO)) 12541 notePostUse(O, BO); 12542 12543 Region = RHSRegion; 12544 Visit(BO->getRHS()); 12545 } 12546 12547 // C++11 [expr.ass]p1: 12548 // the assignment is sequenced [...] before the value computation of the 12549 // assignment expression. 12550 // C11 6.5.16/3 has no such rule. 12551 Region = OldRegion; 12552 if (O) 12553 notePostMod(O, BO, 12554 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12555 : UK_ModAsSideEffect); 12556 if (SemaRef.getLangOpts().CPlusPlus17) { 12557 Tree.merge(RHSRegion); 12558 Tree.merge(LHSRegion); 12559 } 12560 } 12561 12562 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 12563 VisitBinAssign(CAO); 12564 } 12565 12566 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12567 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12568 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 12569 Object O = getObject(UO->getSubExpr(), true); 12570 if (!O) 12571 return VisitExpr(UO); 12572 12573 notePreMod(O, UO); 12574 Visit(UO->getSubExpr()); 12575 // C++11 [expr.pre.incr]p1: 12576 // the expression ++x is equivalent to x+=1 12577 notePostMod(O, UO, 12578 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12579 : UK_ModAsSideEffect); 12580 } 12581 12582 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12583 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12584 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 12585 Object O = getObject(UO->getSubExpr(), true); 12586 if (!O) 12587 return VisitExpr(UO); 12588 12589 notePreMod(O, UO); 12590 Visit(UO->getSubExpr()); 12591 notePostMod(O, UO, UK_ModAsSideEffect); 12592 } 12593 12594 void VisitBinLOr(const BinaryOperator *BO) { 12595 // C++11 [expr.log.or]p2: 12596 // If the second expression is evaluated, every value computation and 12597 // side effect associated with the first expression is sequenced before 12598 // every value computation and side effect associated with the 12599 // second expression. 12600 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12601 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12602 SequenceTree::Seq OldRegion = Region; 12603 12604 EvaluationTracker Eval(*this); 12605 { 12606 SequencedSubexpression Sequenced(*this); 12607 Region = LHSRegion; 12608 Visit(BO->getLHS()); 12609 } 12610 12611 // C++11 [expr.log.or]p1: 12612 // [...] the second operand is not evaluated if the first operand 12613 // evaluates to true. 12614 bool EvalResult = false; 12615 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12616 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 12617 if (ShouldVisitRHS) { 12618 Region = RHSRegion; 12619 Visit(BO->getRHS()); 12620 } 12621 12622 Region = OldRegion; 12623 Tree.merge(LHSRegion); 12624 Tree.merge(RHSRegion); 12625 } 12626 12627 void VisitBinLAnd(const BinaryOperator *BO) { 12628 // C++11 [expr.log.and]p2: 12629 // If the second expression is evaluated, every value computation and 12630 // side effect associated with the first expression is sequenced before 12631 // every value computation and side effect associated with the 12632 // second expression. 12633 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12634 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12635 SequenceTree::Seq OldRegion = Region; 12636 12637 EvaluationTracker Eval(*this); 12638 { 12639 SequencedSubexpression Sequenced(*this); 12640 Region = LHSRegion; 12641 Visit(BO->getLHS()); 12642 } 12643 12644 // C++11 [expr.log.and]p1: 12645 // [...] the second operand is not evaluated if the first operand is false. 12646 bool EvalResult = false; 12647 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12648 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 12649 if (ShouldVisitRHS) { 12650 Region = RHSRegion; 12651 Visit(BO->getRHS()); 12652 } 12653 12654 Region = OldRegion; 12655 Tree.merge(LHSRegion); 12656 Tree.merge(RHSRegion); 12657 } 12658 12659 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 12660 // C++11 [expr.cond]p1: 12661 // [...] Every value computation and side effect associated with the first 12662 // expression is sequenced before every value computation and side effect 12663 // associated with the second or third expression. 12664 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 12665 12666 // No sequencing is specified between the true and false expression. 12667 // However since exactly one of both is going to be evaluated we can 12668 // consider them to be sequenced. This is needed to avoid warning on 12669 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 12670 // both the true and false expressions because we can't evaluate x. 12671 // This will still allow us to detect an expression like (pre C++17) 12672 // "(x ? y += 1 : y += 2) = y". 12673 // 12674 // We don't wrap the visitation of the true and false expression with 12675 // SequencedSubexpression because we don't want to downgrade modifications 12676 // as side effect in the true and false expressions after the visition 12677 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 12678 // not warn between the two "y++", but we should warn between the "y++" 12679 // and the "y". 12680 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 12681 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 12682 SequenceTree::Seq OldRegion = Region; 12683 12684 EvaluationTracker Eval(*this); 12685 { 12686 SequencedSubexpression Sequenced(*this); 12687 Region = ConditionRegion; 12688 Visit(CO->getCond()); 12689 } 12690 12691 // C++11 [expr.cond]p1: 12692 // [...] The first expression is contextually converted to bool (Clause 4). 12693 // It is evaluated and if it is true, the result of the conditional 12694 // expression is the value of the second expression, otherwise that of the 12695 // third expression. Only one of the second and third expressions is 12696 // evaluated. [...] 12697 bool EvalResult = false; 12698 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 12699 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 12700 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 12701 if (ShouldVisitTrueExpr) { 12702 Region = TrueRegion; 12703 Visit(CO->getTrueExpr()); 12704 } 12705 if (ShouldVisitFalseExpr) { 12706 Region = FalseRegion; 12707 Visit(CO->getFalseExpr()); 12708 } 12709 12710 Region = OldRegion; 12711 Tree.merge(ConditionRegion); 12712 Tree.merge(TrueRegion); 12713 Tree.merge(FalseRegion); 12714 } 12715 12716 void VisitCallExpr(const CallExpr *CE) { 12717 // C++11 [intro.execution]p15: 12718 // When calling a function [...], every value computation and side effect 12719 // associated with any argument expression, or with the postfix expression 12720 // designating the called function, is sequenced before execution of every 12721 // expression or statement in the body of the function [and thus before 12722 // the value computation of its result]. 12723 SequencedSubexpression Sequenced(*this); 12724 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), 12725 [&] { Base::VisitCallExpr(CE); }); 12726 12727 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12728 } 12729 12730 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 12731 // This is a call, so all subexpressions are sequenced before the result. 12732 SequencedSubexpression Sequenced(*this); 12733 12734 if (!CCE->isListInitialization()) 12735 return VisitExpr(CCE); 12736 12737 // In C++11, list initializations are sequenced. 12738 SmallVector<SequenceTree::Seq, 32> Elts; 12739 SequenceTree::Seq Parent = Region; 12740 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 12741 E = CCE->arg_end(); 12742 I != E; ++I) { 12743 Region = Tree.allocate(Parent); 12744 Elts.push_back(Region); 12745 Visit(*I); 12746 } 12747 12748 // Forget that the initializers are sequenced. 12749 Region = Parent; 12750 for (unsigned I = 0; I < Elts.size(); ++I) 12751 Tree.merge(Elts[I]); 12752 } 12753 12754 void VisitInitListExpr(const InitListExpr *ILE) { 12755 if (!SemaRef.getLangOpts().CPlusPlus11) 12756 return VisitExpr(ILE); 12757 12758 // In C++11, list initializations are sequenced. 12759 SmallVector<SequenceTree::Seq, 32> Elts; 12760 SequenceTree::Seq Parent = Region; 12761 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 12762 const Expr *E = ILE->getInit(I); 12763 if (!E) 12764 continue; 12765 Region = Tree.allocate(Parent); 12766 Elts.push_back(Region); 12767 Visit(E); 12768 } 12769 12770 // Forget that the initializers are sequenced. 12771 Region = Parent; 12772 for (unsigned I = 0; I < Elts.size(); ++I) 12773 Tree.merge(Elts[I]); 12774 } 12775 }; 12776 12777 } // namespace 12778 12779 void Sema::CheckUnsequencedOperations(const Expr *E) { 12780 SmallVector<const Expr *, 8> WorkList; 12781 WorkList.push_back(E); 12782 while (!WorkList.empty()) { 12783 const Expr *Item = WorkList.pop_back_val(); 12784 SequenceChecker(*this, Item, WorkList); 12785 } 12786 } 12787 12788 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 12789 bool IsConstexpr) { 12790 llvm::SaveAndRestore<bool> ConstantContext( 12791 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 12792 CheckImplicitConversions(E, CheckLoc); 12793 if (!E->isInstantiationDependent()) 12794 CheckUnsequencedOperations(E); 12795 if (!IsConstexpr && !E->isValueDependent()) 12796 CheckForIntOverflow(E); 12797 DiagnoseMisalignedMembers(); 12798 } 12799 12800 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 12801 FieldDecl *BitField, 12802 Expr *Init) { 12803 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 12804 } 12805 12806 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 12807 SourceLocation Loc) { 12808 if (!PType->isVariablyModifiedType()) 12809 return; 12810 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 12811 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 12812 return; 12813 } 12814 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 12815 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 12816 return; 12817 } 12818 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 12819 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 12820 return; 12821 } 12822 12823 const ArrayType *AT = S.Context.getAsArrayType(PType); 12824 if (!AT) 12825 return; 12826 12827 if (AT->getSizeModifier() != ArrayType::Star) { 12828 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 12829 return; 12830 } 12831 12832 S.Diag(Loc, diag::err_array_star_in_function_definition); 12833 } 12834 12835 /// CheckParmsForFunctionDef - Check that the parameters of the given 12836 /// function are appropriate for the definition of a function. This 12837 /// takes care of any checks that cannot be performed on the 12838 /// declaration itself, e.g., that the types of each of the function 12839 /// parameters are complete. 12840 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 12841 bool CheckParameterNames) { 12842 bool HasInvalidParm = false; 12843 for (ParmVarDecl *Param : Parameters) { 12844 // C99 6.7.5.3p4: the parameters in a parameter type list in a 12845 // function declarator that is part of a function definition of 12846 // that function shall not have incomplete type. 12847 // 12848 // This is also C++ [dcl.fct]p6. 12849 if (!Param->isInvalidDecl() && 12850 RequireCompleteType(Param->getLocation(), Param->getType(), 12851 diag::err_typecheck_decl_incomplete_type)) { 12852 Param->setInvalidDecl(); 12853 HasInvalidParm = true; 12854 } 12855 12856 // C99 6.9.1p5: If the declarator includes a parameter type list, the 12857 // declaration of each parameter shall include an identifier. 12858 if (CheckParameterNames && 12859 Param->getIdentifier() == nullptr && 12860 !Param->isImplicit() && 12861 !getLangOpts().CPlusPlus) 12862 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 12863 12864 // C99 6.7.5.3p12: 12865 // If the function declarator is not part of a definition of that 12866 // function, parameters may have incomplete type and may use the [*] 12867 // notation in their sequences of declarator specifiers to specify 12868 // variable length array types. 12869 QualType PType = Param->getOriginalType(); 12870 // FIXME: This diagnostic should point the '[*]' if source-location 12871 // information is added for it. 12872 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 12873 12874 // If the parameter is a c++ class type and it has to be destructed in the 12875 // callee function, declare the destructor so that it can be called by the 12876 // callee function. Do not perform any direct access check on the dtor here. 12877 if (!Param->isInvalidDecl()) { 12878 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 12879 if (!ClassDecl->isInvalidDecl() && 12880 !ClassDecl->hasIrrelevantDestructor() && 12881 !ClassDecl->isDependentContext() && 12882 ClassDecl->isParamDestroyedInCallee()) { 12883 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 12884 MarkFunctionReferenced(Param->getLocation(), Destructor); 12885 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 12886 } 12887 } 12888 } 12889 12890 // Parameters with the pass_object_size attribute only need to be marked 12891 // constant at function definitions. Because we lack information about 12892 // whether we're on a declaration or definition when we're instantiating the 12893 // attribute, we need to check for constness here. 12894 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 12895 if (!Param->getType().isConstQualified()) 12896 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 12897 << Attr->getSpelling() << 1; 12898 12899 // Check for parameter names shadowing fields from the class. 12900 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 12901 // The owning context for the parameter should be the function, but we 12902 // want to see if this function's declaration context is a record. 12903 DeclContext *DC = Param->getDeclContext(); 12904 if (DC && DC->isFunctionOrMethod()) { 12905 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 12906 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 12907 RD, /*DeclIsField*/ false); 12908 } 12909 } 12910 } 12911 12912 return HasInvalidParm; 12913 } 12914 12915 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr 12916 /// or MemberExpr. 12917 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, 12918 ASTContext &Context) { 12919 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 12920 return Context.getDeclAlign(DRE->getDecl()); 12921 12922 if (const auto *ME = dyn_cast<MemberExpr>(E)) 12923 return Context.getDeclAlign(ME->getMemberDecl()); 12924 12925 return TypeAlign; 12926 } 12927 12928 /// CheckCastAlign - Implements -Wcast-align, which warns when a 12929 /// pointer cast increases the alignment requirements. 12930 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 12931 // This is actually a lot of work to potentially be doing on every 12932 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 12933 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 12934 return; 12935 12936 // Ignore dependent types. 12937 if (T->isDependentType() || Op->getType()->isDependentType()) 12938 return; 12939 12940 // Require that the destination be a pointer type. 12941 const PointerType *DestPtr = T->getAs<PointerType>(); 12942 if (!DestPtr) return; 12943 12944 // If the destination has alignment 1, we're done. 12945 QualType DestPointee = DestPtr->getPointeeType(); 12946 if (DestPointee->isIncompleteType()) return; 12947 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 12948 if (DestAlign.isOne()) return; 12949 12950 // Require that the source be a pointer type. 12951 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 12952 if (!SrcPtr) return; 12953 QualType SrcPointee = SrcPtr->getPointeeType(); 12954 12955 // Whitelist casts from cv void*. We already implicitly 12956 // whitelisted casts to cv void*, since they have alignment 1. 12957 // Also whitelist casts involving incomplete types, which implicitly 12958 // includes 'void'. 12959 if (SrcPointee->isIncompleteType()) return; 12960 12961 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee); 12962 12963 if (auto *CE = dyn_cast<CastExpr>(Op)) { 12964 if (CE->getCastKind() == CK_ArrayToPointerDecay) 12965 SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context); 12966 } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) { 12967 if (UO->getOpcode() == UO_AddrOf) 12968 SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context); 12969 } 12970 12971 if (SrcAlign >= DestAlign) return; 12972 12973 Diag(TRange.getBegin(), diag::warn_cast_align) 12974 << Op->getType() << T 12975 << static_cast<unsigned>(SrcAlign.getQuantity()) 12976 << static_cast<unsigned>(DestAlign.getQuantity()) 12977 << TRange << Op->getSourceRange(); 12978 } 12979 12980 /// Check whether this array fits the idiom of a size-one tail padded 12981 /// array member of a struct. 12982 /// 12983 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 12984 /// commonly used to emulate flexible arrays in C89 code. 12985 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 12986 const NamedDecl *ND) { 12987 if (Size != 1 || !ND) return false; 12988 12989 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 12990 if (!FD) return false; 12991 12992 // Don't consider sizes resulting from macro expansions or template argument 12993 // substitution to form C89 tail-padded arrays. 12994 12995 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 12996 while (TInfo) { 12997 TypeLoc TL = TInfo->getTypeLoc(); 12998 // Look through typedefs. 12999 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13000 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13001 TInfo = TDL->getTypeSourceInfo(); 13002 continue; 13003 } 13004 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13005 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13006 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13007 return false; 13008 } 13009 break; 13010 } 13011 13012 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13013 if (!RD) return false; 13014 if (RD->isUnion()) return false; 13015 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13016 if (!CRD->isStandardLayout()) return false; 13017 } 13018 13019 // See if this is the last field decl in the record. 13020 const Decl *D = FD; 13021 while ((D = D->getNextDeclInContext())) 13022 if (isa<FieldDecl>(D)) 13023 return false; 13024 return true; 13025 } 13026 13027 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13028 const ArraySubscriptExpr *ASE, 13029 bool AllowOnePastEnd, bool IndexNegated) { 13030 // Already diagnosed by the constant evaluator. 13031 if (isConstantEvaluated()) 13032 return; 13033 13034 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13035 if (IndexExpr->isValueDependent()) 13036 return; 13037 13038 const Type *EffectiveType = 13039 BaseExpr->getType()->getPointeeOrArrayElementType(); 13040 BaseExpr = BaseExpr->IgnoreParenCasts(); 13041 const ConstantArrayType *ArrayTy = 13042 Context.getAsConstantArrayType(BaseExpr->getType()); 13043 13044 if (!ArrayTy) 13045 return; 13046 13047 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13048 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13049 return; 13050 13051 Expr::EvalResult Result; 13052 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13053 return; 13054 13055 llvm::APSInt index = Result.Val.getInt(); 13056 if (IndexNegated) 13057 index = -index; 13058 13059 const NamedDecl *ND = nullptr; 13060 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13061 ND = DRE->getDecl(); 13062 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13063 ND = ME->getMemberDecl(); 13064 13065 if (index.isUnsigned() || !index.isNegative()) { 13066 // It is possible that the type of the base expression after 13067 // IgnoreParenCasts is incomplete, even though the type of the base 13068 // expression before IgnoreParenCasts is complete (see PR39746 for an 13069 // example). In this case we have no information about whether the array 13070 // access exceeds the array bounds. However we can still diagnose an array 13071 // access which precedes the array bounds. 13072 if (BaseType->isIncompleteType()) 13073 return; 13074 13075 llvm::APInt size = ArrayTy->getSize(); 13076 if (!size.isStrictlyPositive()) 13077 return; 13078 13079 if (BaseType != EffectiveType) { 13080 // Make sure we're comparing apples to apples when comparing index to size 13081 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13082 uint64_t array_typesize = Context.getTypeSize(BaseType); 13083 // Handle ptrarith_typesize being zero, such as when casting to void* 13084 if (!ptrarith_typesize) ptrarith_typesize = 1; 13085 if (ptrarith_typesize != array_typesize) { 13086 // There's a cast to a different size type involved 13087 uint64_t ratio = array_typesize / ptrarith_typesize; 13088 // TODO: Be smarter about handling cases where array_typesize is not a 13089 // multiple of ptrarith_typesize 13090 if (ptrarith_typesize * ratio == array_typesize) 13091 size *= llvm::APInt(size.getBitWidth(), ratio); 13092 } 13093 } 13094 13095 if (size.getBitWidth() > index.getBitWidth()) 13096 index = index.zext(size.getBitWidth()); 13097 else if (size.getBitWidth() < index.getBitWidth()) 13098 size = size.zext(index.getBitWidth()); 13099 13100 // For array subscripting the index must be less than size, but for pointer 13101 // arithmetic also allow the index (offset) to be equal to size since 13102 // computing the next address after the end of the array is legal and 13103 // commonly done e.g. in C++ iterators and range-based for loops. 13104 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13105 return; 13106 13107 // Also don't warn for arrays of size 1 which are members of some 13108 // structure. These are often used to approximate flexible arrays in C89 13109 // code. 13110 if (IsTailPaddedMemberArray(*this, size, ND)) 13111 return; 13112 13113 // Suppress the warning if the subscript expression (as identified by the 13114 // ']' location) and the index expression are both from macro expansions 13115 // within a system header. 13116 if (ASE) { 13117 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13118 ASE->getRBracketLoc()); 13119 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13120 SourceLocation IndexLoc = 13121 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13122 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13123 return; 13124 } 13125 } 13126 13127 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13128 if (ASE) 13129 DiagID = diag::warn_array_index_exceeds_bounds; 13130 13131 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13132 PDiag(DiagID) << index.toString(10, true) 13133 << size.toString(10, true) 13134 << (unsigned)size.getLimitedValue(~0U) 13135 << IndexExpr->getSourceRange()); 13136 } else { 13137 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13138 if (!ASE) { 13139 DiagID = diag::warn_ptr_arith_precedes_bounds; 13140 if (index.isNegative()) index = -index; 13141 } 13142 13143 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13144 PDiag(DiagID) << index.toString(10, true) 13145 << IndexExpr->getSourceRange()); 13146 } 13147 13148 if (!ND) { 13149 // Try harder to find a NamedDecl to point at in the note. 13150 while (const ArraySubscriptExpr *ASE = 13151 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13152 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13153 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13154 ND = DRE->getDecl(); 13155 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13156 ND = ME->getMemberDecl(); 13157 } 13158 13159 if (ND) 13160 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13161 PDiag(diag::note_array_declared_here) 13162 << ND->getDeclName()); 13163 } 13164 13165 void Sema::CheckArrayAccess(const Expr *expr) { 13166 int AllowOnePastEnd = 0; 13167 while (expr) { 13168 expr = expr->IgnoreParenImpCasts(); 13169 switch (expr->getStmtClass()) { 13170 case Stmt::ArraySubscriptExprClass: { 13171 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13172 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13173 AllowOnePastEnd > 0); 13174 expr = ASE->getBase(); 13175 break; 13176 } 13177 case Stmt::MemberExprClass: { 13178 expr = cast<MemberExpr>(expr)->getBase(); 13179 break; 13180 } 13181 case Stmt::OMPArraySectionExprClass: { 13182 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13183 if (ASE->getLowerBound()) 13184 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13185 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13186 return; 13187 } 13188 case Stmt::UnaryOperatorClass: { 13189 // Only unwrap the * and & unary operators 13190 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13191 expr = UO->getSubExpr(); 13192 switch (UO->getOpcode()) { 13193 case UO_AddrOf: 13194 AllowOnePastEnd++; 13195 break; 13196 case UO_Deref: 13197 AllowOnePastEnd--; 13198 break; 13199 default: 13200 return; 13201 } 13202 break; 13203 } 13204 case Stmt::ConditionalOperatorClass: { 13205 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13206 if (const Expr *lhs = cond->getLHS()) 13207 CheckArrayAccess(lhs); 13208 if (const Expr *rhs = cond->getRHS()) 13209 CheckArrayAccess(rhs); 13210 return; 13211 } 13212 case Stmt::CXXOperatorCallExprClass: { 13213 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13214 for (const auto *Arg : OCE->arguments()) 13215 CheckArrayAccess(Arg); 13216 return; 13217 } 13218 default: 13219 return; 13220 } 13221 } 13222 } 13223 13224 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13225 13226 namespace { 13227 13228 struct RetainCycleOwner { 13229 VarDecl *Variable = nullptr; 13230 SourceRange Range; 13231 SourceLocation Loc; 13232 bool Indirect = false; 13233 13234 RetainCycleOwner() = default; 13235 13236 void setLocsFrom(Expr *e) { 13237 Loc = e->getExprLoc(); 13238 Range = e->getSourceRange(); 13239 } 13240 }; 13241 13242 } // namespace 13243 13244 /// Consider whether capturing the given variable can possibly lead to 13245 /// a retain cycle. 13246 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 13247 // In ARC, it's captured strongly iff the variable has __strong 13248 // lifetime. In MRR, it's captured strongly if the variable is 13249 // __block and has an appropriate type. 13250 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13251 return false; 13252 13253 owner.Variable = var; 13254 if (ref) 13255 owner.setLocsFrom(ref); 13256 return true; 13257 } 13258 13259 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13260 while (true) { 13261 e = e->IgnoreParens(); 13262 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13263 switch (cast->getCastKind()) { 13264 case CK_BitCast: 13265 case CK_LValueBitCast: 13266 case CK_LValueToRValue: 13267 case CK_ARCReclaimReturnedObject: 13268 e = cast->getSubExpr(); 13269 continue; 13270 13271 default: 13272 return false; 13273 } 13274 } 13275 13276 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13277 ObjCIvarDecl *ivar = ref->getDecl(); 13278 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13279 return false; 13280 13281 // Try to find a retain cycle in the base. 13282 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13283 return false; 13284 13285 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13286 owner.Indirect = true; 13287 return true; 13288 } 13289 13290 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13291 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13292 if (!var) return false; 13293 return considerVariable(var, ref, owner); 13294 } 13295 13296 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13297 if (member->isArrow()) return false; 13298 13299 // Don't count this as an indirect ownership. 13300 e = member->getBase(); 13301 continue; 13302 } 13303 13304 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13305 // Only pay attention to pseudo-objects on property references. 13306 ObjCPropertyRefExpr *pre 13307 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13308 ->IgnoreParens()); 13309 if (!pre) return false; 13310 if (pre->isImplicitProperty()) return false; 13311 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13312 if (!property->isRetaining() && 13313 !(property->getPropertyIvarDecl() && 13314 property->getPropertyIvarDecl()->getType() 13315 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13316 return false; 13317 13318 owner.Indirect = true; 13319 if (pre->isSuperReceiver()) { 13320 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13321 if (!owner.Variable) 13322 return false; 13323 owner.Loc = pre->getLocation(); 13324 owner.Range = pre->getSourceRange(); 13325 return true; 13326 } 13327 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13328 ->getSourceExpr()); 13329 continue; 13330 } 13331 13332 // Array ivars? 13333 13334 return false; 13335 } 13336 } 13337 13338 namespace { 13339 13340 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 13341 ASTContext &Context; 13342 VarDecl *Variable; 13343 Expr *Capturer = nullptr; 13344 bool VarWillBeReased = false; 13345 13346 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 13347 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 13348 Context(Context), Variable(variable) {} 13349 13350 void VisitDeclRefExpr(DeclRefExpr *ref) { 13351 if (ref->getDecl() == Variable && !Capturer) 13352 Capturer = ref; 13353 } 13354 13355 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 13356 if (Capturer) return; 13357 Visit(ref->getBase()); 13358 if (Capturer && ref->isFreeIvar()) 13359 Capturer = ref; 13360 } 13361 13362 void VisitBlockExpr(BlockExpr *block) { 13363 // Look inside nested blocks 13364 if (block->getBlockDecl()->capturesVariable(Variable)) 13365 Visit(block->getBlockDecl()->getBody()); 13366 } 13367 13368 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 13369 if (Capturer) return; 13370 if (OVE->getSourceExpr()) 13371 Visit(OVE->getSourceExpr()); 13372 } 13373 13374 void VisitBinaryOperator(BinaryOperator *BinOp) { 13375 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 13376 return; 13377 Expr *LHS = BinOp->getLHS(); 13378 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 13379 if (DRE->getDecl() != Variable) 13380 return; 13381 if (Expr *RHS = BinOp->getRHS()) { 13382 RHS = RHS->IgnoreParenCasts(); 13383 llvm::APSInt Value; 13384 VarWillBeReased = 13385 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 13386 } 13387 } 13388 } 13389 }; 13390 13391 } // namespace 13392 13393 /// Check whether the given argument is a block which captures a 13394 /// variable. 13395 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 13396 assert(owner.Variable && owner.Loc.isValid()); 13397 13398 e = e->IgnoreParenCasts(); 13399 13400 // Look through [^{...} copy] and Block_copy(^{...}). 13401 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 13402 Selector Cmd = ME->getSelector(); 13403 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 13404 e = ME->getInstanceReceiver(); 13405 if (!e) 13406 return nullptr; 13407 e = e->IgnoreParenCasts(); 13408 } 13409 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 13410 if (CE->getNumArgs() == 1) { 13411 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 13412 if (Fn) { 13413 const IdentifierInfo *FnI = Fn->getIdentifier(); 13414 if (FnI && FnI->isStr("_Block_copy")) { 13415 e = CE->getArg(0)->IgnoreParenCasts(); 13416 } 13417 } 13418 } 13419 } 13420 13421 BlockExpr *block = dyn_cast<BlockExpr>(e); 13422 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 13423 return nullptr; 13424 13425 FindCaptureVisitor visitor(S.Context, owner.Variable); 13426 visitor.Visit(block->getBlockDecl()->getBody()); 13427 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 13428 } 13429 13430 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 13431 RetainCycleOwner &owner) { 13432 assert(capturer); 13433 assert(owner.Variable && owner.Loc.isValid()); 13434 13435 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 13436 << owner.Variable << capturer->getSourceRange(); 13437 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 13438 << owner.Indirect << owner.Range; 13439 } 13440 13441 /// Check for a keyword selector that starts with the word 'add' or 13442 /// 'set'. 13443 static bool isSetterLikeSelector(Selector sel) { 13444 if (sel.isUnarySelector()) return false; 13445 13446 StringRef str = sel.getNameForSlot(0); 13447 while (!str.empty() && str.front() == '_') str = str.substr(1); 13448 if (str.startswith("set")) 13449 str = str.substr(3); 13450 else if (str.startswith("add")) { 13451 // Specially whitelist 'addOperationWithBlock:'. 13452 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 13453 return false; 13454 str = str.substr(3); 13455 } 13456 else 13457 return false; 13458 13459 if (str.empty()) return true; 13460 return !isLowercase(str.front()); 13461 } 13462 13463 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 13464 ObjCMessageExpr *Message) { 13465 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 13466 Message->getReceiverInterface(), 13467 NSAPI::ClassId_NSMutableArray); 13468 if (!IsMutableArray) { 13469 return None; 13470 } 13471 13472 Selector Sel = Message->getSelector(); 13473 13474 Optional<NSAPI::NSArrayMethodKind> MKOpt = 13475 S.NSAPIObj->getNSArrayMethodKind(Sel); 13476 if (!MKOpt) { 13477 return None; 13478 } 13479 13480 NSAPI::NSArrayMethodKind MK = *MKOpt; 13481 13482 switch (MK) { 13483 case NSAPI::NSMutableArr_addObject: 13484 case NSAPI::NSMutableArr_insertObjectAtIndex: 13485 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 13486 return 0; 13487 case NSAPI::NSMutableArr_replaceObjectAtIndex: 13488 return 1; 13489 13490 default: 13491 return None; 13492 } 13493 13494 return None; 13495 } 13496 13497 static 13498 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 13499 ObjCMessageExpr *Message) { 13500 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 13501 Message->getReceiverInterface(), 13502 NSAPI::ClassId_NSMutableDictionary); 13503 if (!IsMutableDictionary) { 13504 return None; 13505 } 13506 13507 Selector Sel = Message->getSelector(); 13508 13509 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13510 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13511 if (!MKOpt) { 13512 return None; 13513 } 13514 13515 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 13516 13517 switch (MK) { 13518 case NSAPI::NSMutableDict_setObjectForKey: 13519 case NSAPI::NSMutableDict_setValueForKey: 13520 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 13521 return 0; 13522 13523 default: 13524 return None; 13525 } 13526 13527 return None; 13528 } 13529 13530 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 13531 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 13532 Message->getReceiverInterface(), 13533 NSAPI::ClassId_NSMutableSet); 13534 13535 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 13536 Message->getReceiverInterface(), 13537 NSAPI::ClassId_NSMutableOrderedSet); 13538 if (!IsMutableSet && !IsMutableOrderedSet) { 13539 return None; 13540 } 13541 13542 Selector Sel = Message->getSelector(); 13543 13544 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 13545 if (!MKOpt) { 13546 return None; 13547 } 13548 13549 NSAPI::NSSetMethodKind MK = *MKOpt; 13550 13551 switch (MK) { 13552 case NSAPI::NSMutableSet_addObject: 13553 case NSAPI::NSOrderedSet_setObjectAtIndex: 13554 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 13555 case NSAPI::NSOrderedSet_insertObjectAtIndex: 13556 return 0; 13557 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 13558 return 1; 13559 } 13560 13561 return None; 13562 } 13563 13564 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 13565 if (!Message->isInstanceMessage()) { 13566 return; 13567 } 13568 13569 Optional<int> ArgOpt; 13570 13571 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 13572 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 13573 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 13574 return; 13575 } 13576 13577 int ArgIndex = *ArgOpt; 13578 13579 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 13580 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 13581 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 13582 } 13583 13584 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 13585 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13586 if (ArgRE->isObjCSelfExpr()) { 13587 Diag(Message->getSourceRange().getBegin(), 13588 diag::warn_objc_circular_container) 13589 << ArgRE->getDecl() << StringRef("'super'"); 13590 } 13591 } 13592 } else { 13593 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 13594 13595 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 13596 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 13597 } 13598 13599 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 13600 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 13601 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 13602 ValueDecl *Decl = ReceiverRE->getDecl(); 13603 Diag(Message->getSourceRange().getBegin(), 13604 diag::warn_objc_circular_container) 13605 << Decl << Decl; 13606 if (!ArgRE->isObjCSelfExpr()) { 13607 Diag(Decl->getLocation(), 13608 diag::note_objc_circular_container_declared_here) 13609 << Decl; 13610 } 13611 } 13612 } 13613 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 13614 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 13615 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 13616 ObjCIvarDecl *Decl = IvarRE->getDecl(); 13617 Diag(Message->getSourceRange().getBegin(), 13618 diag::warn_objc_circular_container) 13619 << Decl << Decl; 13620 Diag(Decl->getLocation(), 13621 diag::note_objc_circular_container_declared_here) 13622 << Decl; 13623 } 13624 } 13625 } 13626 } 13627 } 13628 13629 /// Check a message send to see if it's likely to cause a retain cycle. 13630 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 13631 // Only check instance methods whose selector looks like a setter. 13632 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 13633 return; 13634 13635 // Try to find a variable that the receiver is strongly owned by. 13636 RetainCycleOwner owner; 13637 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 13638 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 13639 return; 13640 } else { 13641 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 13642 owner.Variable = getCurMethodDecl()->getSelfDecl(); 13643 owner.Loc = msg->getSuperLoc(); 13644 owner.Range = msg->getSuperLoc(); 13645 } 13646 13647 // Check whether the receiver is captured by any of the arguments. 13648 const ObjCMethodDecl *MD = msg->getMethodDecl(); 13649 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 13650 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 13651 // noescape blocks should not be retained by the method. 13652 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 13653 continue; 13654 return diagnoseRetainCycle(*this, capturer, owner); 13655 } 13656 } 13657 } 13658 13659 /// Check a property assign to see if it's likely to cause a retain cycle. 13660 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 13661 RetainCycleOwner owner; 13662 if (!findRetainCycleOwner(*this, receiver, owner)) 13663 return; 13664 13665 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 13666 diagnoseRetainCycle(*this, capturer, owner); 13667 } 13668 13669 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 13670 RetainCycleOwner Owner; 13671 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 13672 return; 13673 13674 // Because we don't have an expression for the variable, we have to set the 13675 // location explicitly here. 13676 Owner.Loc = Var->getLocation(); 13677 Owner.Range = Var->getSourceRange(); 13678 13679 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 13680 diagnoseRetainCycle(*this, Capturer, Owner); 13681 } 13682 13683 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 13684 Expr *RHS, bool isProperty) { 13685 // Check if RHS is an Objective-C object literal, which also can get 13686 // immediately zapped in a weak reference. Note that we explicitly 13687 // allow ObjCStringLiterals, since those are designed to never really die. 13688 RHS = RHS->IgnoreParenImpCasts(); 13689 13690 // This enum needs to match with the 'select' in 13691 // warn_objc_arc_literal_assign (off-by-1). 13692 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 13693 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 13694 return false; 13695 13696 S.Diag(Loc, diag::warn_arc_literal_assign) 13697 << (unsigned) Kind 13698 << (isProperty ? 0 : 1) 13699 << RHS->getSourceRange(); 13700 13701 return true; 13702 } 13703 13704 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 13705 Qualifiers::ObjCLifetime LT, 13706 Expr *RHS, bool isProperty) { 13707 // Strip off any implicit cast added to get to the one ARC-specific. 13708 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13709 if (cast->getCastKind() == CK_ARCConsumeObject) { 13710 S.Diag(Loc, diag::warn_arc_retained_assign) 13711 << (LT == Qualifiers::OCL_ExplicitNone) 13712 << (isProperty ? 0 : 1) 13713 << RHS->getSourceRange(); 13714 return true; 13715 } 13716 RHS = cast->getSubExpr(); 13717 } 13718 13719 if (LT == Qualifiers::OCL_Weak && 13720 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 13721 return true; 13722 13723 return false; 13724 } 13725 13726 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 13727 QualType LHS, Expr *RHS) { 13728 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 13729 13730 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 13731 return false; 13732 13733 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 13734 return true; 13735 13736 return false; 13737 } 13738 13739 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 13740 Expr *LHS, Expr *RHS) { 13741 QualType LHSType; 13742 // PropertyRef on LHS type need be directly obtained from 13743 // its declaration as it has a PseudoType. 13744 ObjCPropertyRefExpr *PRE 13745 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 13746 if (PRE && !PRE->isImplicitProperty()) { 13747 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13748 if (PD) 13749 LHSType = PD->getType(); 13750 } 13751 13752 if (LHSType.isNull()) 13753 LHSType = LHS->getType(); 13754 13755 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 13756 13757 if (LT == Qualifiers::OCL_Weak) { 13758 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 13759 getCurFunction()->markSafeWeakUse(LHS); 13760 } 13761 13762 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 13763 return; 13764 13765 // FIXME. Check for other life times. 13766 if (LT != Qualifiers::OCL_None) 13767 return; 13768 13769 if (PRE) { 13770 if (PRE->isImplicitProperty()) 13771 return; 13772 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 13773 if (!PD) 13774 return; 13775 13776 unsigned Attributes = PD->getPropertyAttributes(); 13777 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) { 13778 // when 'assign' attribute was not explicitly specified 13779 // by user, ignore it and rely on property type itself 13780 // for lifetime info. 13781 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 13782 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) && 13783 LHSType->isObjCRetainableType()) 13784 return; 13785 13786 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 13787 if (cast->getCastKind() == CK_ARCConsumeObject) { 13788 Diag(Loc, diag::warn_arc_retained_property_assign) 13789 << RHS->getSourceRange(); 13790 return; 13791 } 13792 RHS = cast->getSubExpr(); 13793 } 13794 } 13795 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) { 13796 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 13797 return; 13798 } 13799 } 13800 } 13801 13802 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 13803 13804 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 13805 SourceLocation StmtLoc, 13806 const NullStmt *Body) { 13807 // Do not warn if the body is a macro that expands to nothing, e.g: 13808 // 13809 // #define CALL(x) 13810 // if (condition) 13811 // CALL(0); 13812 if (Body->hasLeadingEmptyMacro()) 13813 return false; 13814 13815 // Get line numbers of statement and body. 13816 bool StmtLineInvalid; 13817 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 13818 &StmtLineInvalid); 13819 if (StmtLineInvalid) 13820 return false; 13821 13822 bool BodyLineInvalid; 13823 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 13824 &BodyLineInvalid); 13825 if (BodyLineInvalid) 13826 return false; 13827 13828 // Warn if null statement and body are on the same line. 13829 if (StmtLine != BodyLine) 13830 return false; 13831 13832 return true; 13833 } 13834 13835 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 13836 const Stmt *Body, 13837 unsigned DiagID) { 13838 // Since this is a syntactic check, don't emit diagnostic for template 13839 // instantiations, this just adds noise. 13840 if (CurrentInstantiationScope) 13841 return; 13842 13843 // The body should be a null statement. 13844 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13845 if (!NBody) 13846 return; 13847 13848 // Do the usual checks. 13849 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13850 return; 13851 13852 Diag(NBody->getSemiLoc(), DiagID); 13853 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13854 } 13855 13856 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 13857 const Stmt *PossibleBody) { 13858 assert(!CurrentInstantiationScope); // Ensured by caller 13859 13860 SourceLocation StmtLoc; 13861 const Stmt *Body; 13862 unsigned DiagID; 13863 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 13864 StmtLoc = FS->getRParenLoc(); 13865 Body = FS->getBody(); 13866 DiagID = diag::warn_empty_for_body; 13867 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 13868 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 13869 Body = WS->getBody(); 13870 DiagID = diag::warn_empty_while_body; 13871 } else 13872 return; // Neither `for' nor `while'. 13873 13874 // The body should be a null statement. 13875 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 13876 if (!NBody) 13877 return; 13878 13879 // Skip expensive checks if diagnostic is disabled. 13880 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 13881 return; 13882 13883 // Do the usual checks. 13884 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 13885 return; 13886 13887 // `for(...);' and `while(...);' are popular idioms, so in order to keep 13888 // noise level low, emit diagnostics only if for/while is followed by a 13889 // CompoundStmt, e.g.: 13890 // for (int i = 0; i < n; i++); 13891 // { 13892 // a(i); 13893 // } 13894 // or if for/while is followed by a statement with more indentation 13895 // than for/while itself: 13896 // for (int i = 0; i < n; i++); 13897 // a(i); 13898 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 13899 if (!ProbableTypo) { 13900 bool BodyColInvalid; 13901 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 13902 PossibleBody->getBeginLoc(), &BodyColInvalid); 13903 if (BodyColInvalid) 13904 return; 13905 13906 bool StmtColInvalid; 13907 unsigned StmtCol = 13908 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 13909 if (StmtColInvalid) 13910 return; 13911 13912 if (BodyCol > StmtCol) 13913 ProbableTypo = true; 13914 } 13915 13916 if (ProbableTypo) { 13917 Diag(NBody->getSemiLoc(), DiagID); 13918 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 13919 } 13920 } 13921 13922 //===--- CHECK: Warn on self move with std::move. -------------------------===// 13923 13924 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 13925 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 13926 SourceLocation OpLoc) { 13927 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 13928 return; 13929 13930 if (inTemplateInstantiation()) 13931 return; 13932 13933 // Strip parens and casts away. 13934 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 13935 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 13936 13937 // Check for a call expression 13938 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 13939 if (!CE || CE->getNumArgs() != 1) 13940 return; 13941 13942 // Check for a call to std::move 13943 if (!CE->isCallToStdMove()) 13944 return; 13945 13946 // Get argument from std::move 13947 RHSExpr = CE->getArg(0); 13948 13949 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 13950 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 13951 13952 // Two DeclRefExpr's, check that the decls are the same. 13953 if (LHSDeclRef && RHSDeclRef) { 13954 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13955 return; 13956 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13957 RHSDeclRef->getDecl()->getCanonicalDecl()) 13958 return; 13959 13960 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13961 << LHSExpr->getSourceRange() 13962 << RHSExpr->getSourceRange(); 13963 return; 13964 } 13965 13966 // Member variables require a different approach to check for self moves. 13967 // MemberExpr's are the same if every nested MemberExpr refers to the same 13968 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 13969 // the base Expr's are CXXThisExpr's. 13970 const Expr *LHSBase = LHSExpr; 13971 const Expr *RHSBase = RHSExpr; 13972 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 13973 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 13974 if (!LHSME || !RHSME) 13975 return; 13976 13977 while (LHSME && RHSME) { 13978 if (LHSME->getMemberDecl()->getCanonicalDecl() != 13979 RHSME->getMemberDecl()->getCanonicalDecl()) 13980 return; 13981 13982 LHSBase = LHSME->getBase(); 13983 RHSBase = RHSME->getBase(); 13984 LHSME = dyn_cast<MemberExpr>(LHSBase); 13985 RHSME = dyn_cast<MemberExpr>(RHSBase); 13986 } 13987 13988 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 13989 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 13990 if (LHSDeclRef && RHSDeclRef) { 13991 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 13992 return; 13993 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 13994 RHSDeclRef->getDecl()->getCanonicalDecl()) 13995 return; 13996 13997 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 13998 << LHSExpr->getSourceRange() 13999 << RHSExpr->getSourceRange(); 14000 return; 14001 } 14002 14003 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14004 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14005 << LHSExpr->getSourceRange() 14006 << RHSExpr->getSourceRange(); 14007 } 14008 14009 //===--- Layout compatibility ----------------------------------------------// 14010 14011 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14012 14013 /// Check if two enumeration types are layout-compatible. 14014 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14015 // C++11 [dcl.enum] p8: 14016 // Two enumeration types are layout-compatible if they have the same 14017 // underlying type. 14018 return ED1->isComplete() && ED2->isComplete() && 14019 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14020 } 14021 14022 /// Check if two fields are layout-compatible. 14023 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14024 FieldDecl *Field2) { 14025 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14026 return false; 14027 14028 if (Field1->isBitField() != Field2->isBitField()) 14029 return false; 14030 14031 if (Field1->isBitField()) { 14032 // Make sure that the bit-fields are the same length. 14033 unsigned Bits1 = Field1->getBitWidthValue(C); 14034 unsigned Bits2 = Field2->getBitWidthValue(C); 14035 14036 if (Bits1 != Bits2) 14037 return false; 14038 } 14039 14040 return true; 14041 } 14042 14043 /// Check if two standard-layout structs are layout-compatible. 14044 /// (C++11 [class.mem] p17) 14045 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14046 RecordDecl *RD2) { 14047 // If both records are C++ classes, check that base classes match. 14048 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14049 // If one of records is a CXXRecordDecl we are in C++ mode, 14050 // thus the other one is a CXXRecordDecl, too. 14051 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14052 // Check number of base classes. 14053 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14054 return false; 14055 14056 // Check the base classes. 14057 for (CXXRecordDecl::base_class_const_iterator 14058 Base1 = D1CXX->bases_begin(), 14059 BaseEnd1 = D1CXX->bases_end(), 14060 Base2 = D2CXX->bases_begin(); 14061 Base1 != BaseEnd1; 14062 ++Base1, ++Base2) { 14063 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14064 return false; 14065 } 14066 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14067 // If only RD2 is a C++ class, it should have zero base classes. 14068 if (D2CXX->getNumBases() > 0) 14069 return false; 14070 } 14071 14072 // Check the fields. 14073 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14074 Field2End = RD2->field_end(), 14075 Field1 = RD1->field_begin(), 14076 Field1End = RD1->field_end(); 14077 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14078 if (!isLayoutCompatible(C, *Field1, *Field2)) 14079 return false; 14080 } 14081 if (Field1 != Field1End || Field2 != Field2End) 14082 return false; 14083 14084 return true; 14085 } 14086 14087 /// Check if two standard-layout unions are layout-compatible. 14088 /// (C++11 [class.mem] p18) 14089 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14090 RecordDecl *RD2) { 14091 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14092 for (auto *Field2 : RD2->fields()) 14093 UnmatchedFields.insert(Field2); 14094 14095 for (auto *Field1 : RD1->fields()) { 14096 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14097 I = UnmatchedFields.begin(), 14098 E = UnmatchedFields.end(); 14099 14100 for ( ; I != E; ++I) { 14101 if (isLayoutCompatible(C, Field1, *I)) { 14102 bool Result = UnmatchedFields.erase(*I); 14103 (void) Result; 14104 assert(Result); 14105 break; 14106 } 14107 } 14108 if (I == E) 14109 return false; 14110 } 14111 14112 return UnmatchedFields.empty(); 14113 } 14114 14115 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14116 RecordDecl *RD2) { 14117 if (RD1->isUnion() != RD2->isUnion()) 14118 return false; 14119 14120 if (RD1->isUnion()) 14121 return isLayoutCompatibleUnion(C, RD1, RD2); 14122 else 14123 return isLayoutCompatibleStruct(C, RD1, RD2); 14124 } 14125 14126 /// Check if two types are layout-compatible in C++11 sense. 14127 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14128 if (T1.isNull() || T2.isNull()) 14129 return false; 14130 14131 // C++11 [basic.types] p11: 14132 // If two types T1 and T2 are the same type, then T1 and T2 are 14133 // layout-compatible types. 14134 if (C.hasSameType(T1, T2)) 14135 return true; 14136 14137 T1 = T1.getCanonicalType().getUnqualifiedType(); 14138 T2 = T2.getCanonicalType().getUnqualifiedType(); 14139 14140 const Type::TypeClass TC1 = T1->getTypeClass(); 14141 const Type::TypeClass TC2 = T2->getTypeClass(); 14142 14143 if (TC1 != TC2) 14144 return false; 14145 14146 if (TC1 == Type::Enum) { 14147 return isLayoutCompatible(C, 14148 cast<EnumType>(T1)->getDecl(), 14149 cast<EnumType>(T2)->getDecl()); 14150 } else if (TC1 == Type::Record) { 14151 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14152 return false; 14153 14154 return isLayoutCompatible(C, 14155 cast<RecordType>(T1)->getDecl(), 14156 cast<RecordType>(T2)->getDecl()); 14157 } 14158 14159 return false; 14160 } 14161 14162 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14163 14164 /// Given a type tag expression find the type tag itself. 14165 /// 14166 /// \param TypeExpr Type tag expression, as it appears in user's code. 14167 /// 14168 /// \param VD Declaration of an identifier that appears in a type tag. 14169 /// 14170 /// \param MagicValue Type tag magic value. 14171 /// 14172 /// \param isConstantEvaluated wether the evalaution should be performed in 14173 14174 /// constant context. 14175 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14176 const ValueDecl **VD, uint64_t *MagicValue, 14177 bool isConstantEvaluated) { 14178 while(true) { 14179 if (!TypeExpr) 14180 return false; 14181 14182 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14183 14184 switch (TypeExpr->getStmtClass()) { 14185 case Stmt::UnaryOperatorClass: { 14186 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14187 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14188 TypeExpr = UO->getSubExpr(); 14189 continue; 14190 } 14191 return false; 14192 } 14193 14194 case Stmt::DeclRefExprClass: { 14195 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14196 *VD = DRE->getDecl(); 14197 return true; 14198 } 14199 14200 case Stmt::IntegerLiteralClass: { 14201 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14202 llvm::APInt MagicValueAPInt = IL->getValue(); 14203 if (MagicValueAPInt.getActiveBits() <= 64) { 14204 *MagicValue = MagicValueAPInt.getZExtValue(); 14205 return true; 14206 } else 14207 return false; 14208 } 14209 14210 case Stmt::BinaryConditionalOperatorClass: 14211 case Stmt::ConditionalOperatorClass: { 14212 const AbstractConditionalOperator *ACO = 14213 cast<AbstractConditionalOperator>(TypeExpr); 14214 bool Result; 14215 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14216 isConstantEvaluated)) { 14217 if (Result) 14218 TypeExpr = ACO->getTrueExpr(); 14219 else 14220 TypeExpr = ACO->getFalseExpr(); 14221 continue; 14222 } 14223 return false; 14224 } 14225 14226 case Stmt::BinaryOperatorClass: { 14227 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14228 if (BO->getOpcode() == BO_Comma) { 14229 TypeExpr = BO->getRHS(); 14230 continue; 14231 } 14232 return false; 14233 } 14234 14235 default: 14236 return false; 14237 } 14238 } 14239 } 14240 14241 /// Retrieve the C type corresponding to type tag TypeExpr. 14242 /// 14243 /// \param TypeExpr Expression that specifies a type tag. 14244 /// 14245 /// \param MagicValues Registered magic values. 14246 /// 14247 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14248 /// kind. 14249 /// 14250 /// \param TypeInfo Information about the corresponding C type. 14251 /// 14252 /// \param isConstantEvaluated wether the evalaution should be performed in 14253 /// constant context. 14254 /// 14255 /// \returns true if the corresponding C type was found. 14256 static bool GetMatchingCType( 14257 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14258 const ASTContext &Ctx, 14259 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14260 *MagicValues, 14261 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14262 bool isConstantEvaluated) { 14263 FoundWrongKind = false; 14264 14265 // Variable declaration that has type_tag_for_datatype attribute. 14266 const ValueDecl *VD = nullptr; 14267 14268 uint64_t MagicValue; 14269 14270 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14271 return false; 14272 14273 if (VD) { 14274 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14275 if (I->getArgumentKind() != ArgumentKind) { 14276 FoundWrongKind = true; 14277 return false; 14278 } 14279 TypeInfo.Type = I->getMatchingCType(); 14280 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14281 TypeInfo.MustBeNull = I->getMustBeNull(); 14282 return true; 14283 } 14284 return false; 14285 } 14286 14287 if (!MagicValues) 14288 return false; 14289 14290 llvm::DenseMap<Sema::TypeTagMagicValue, 14291 Sema::TypeTagData>::const_iterator I = 14292 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14293 if (I == MagicValues->end()) 14294 return false; 14295 14296 TypeInfo = I->second; 14297 return true; 14298 } 14299 14300 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14301 uint64_t MagicValue, QualType Type, 14302 bool LayoutCompatible, 14303 bool MustBeNull) { 14304 if (!TypeTagForDatatypeMagicValues) 14305 TypeTagForDatatypeMagicValues.reset( 14306 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14307 14308 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14309 (*TypeTagForDatatypeMagicValues)[Magic] = 14310 TypeTagData(Type, LayoutCompatible, MustBeNull); 14311 } 14312 14313 static bool IsSameCharType(QualType T1, QualType T2) { 14314 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14315 if (!BT1) 14316 return false; 14317 14318 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14319 if (!BT2) 14320 return false; 14321 14322 BuiltinType::Kind T1Kind = BT1->getKind(); 14323 BuiltinType::Kind T2Kind = BT2->getKind(); 14324 14325 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14326 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14327 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14328 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14329 } 14330 14331 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14332 const ArrayRef<const Expr *> ExprArgs, 14333 SourceLocation CallSiteLoc) { 14334 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14335 bool IsPointerAttr = Attr->getIsPointer(); 14336 14337 // Retrieve the argument representing the 'type_tag'. 14338 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14339 if (TypeTagIdxAST >= ExprArgs.size()) { 14340 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14341 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14342 return; 14343 } 14344 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14345 bool FoundWrongKind; 14346 TypeTagData TypeInfo; 14347 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14348 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14349 TypeInfo, isConstantEvaluated())) { 14350 if (FoundWrongKind) 14351 Diag(TypeTagExpr->getExprLoc(), 14352 diag::warn_type_tag_for_datatype_wrong_kind) 14353 << TypeTagExpr->getSourceRange(); 14354 return; 14355 } 14356 14357 // Retrieve the argument representing the 'arg_idx'. 14358 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14359 if (ArgumentIdxAST >= ExprArgs.size()) { 14360 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14361 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14362 return; 14363 } 14364 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14365 if (IsPointerAttr) { 14366 // Skip implicit cast of pointer to `void *' (as a function argument). 14367 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14368 if (ICE->getType()->isVoidPointerType() && 14369 ICE->getCastKind() == CK_BitCast) 14370 ArgumentExpr = ICE->getSubExpr(); 14371 } 14372 QualType ArgumentType = ArgumentExpr->getType(); 14373 14374 // Passing a `void*' pointer shouldn't trigger a warning. 14375 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14376 return; 14377 14378 if (TypeInfo.MustBeNull) { 14379 // Type tag with matching void type requires a null pointer. 14380 if (!ArgumentExpr->isNullPointerConstant(Context, 14381 Expr::NPC_ValueDependentIsNotNull)) { 14382 Diag(ArgumentExpr->getExprLoc(), 14383 diag::warn_type_safety_null_pointer_required) 14384 << ArgumentKind->getName() 14385 << ArgumentExpr->getSourceRange() 14386 << TypeTagExpr->getSourceRange(); 14387 } 14388 return; 14389 } 14390 14391 QualType RequiredType = TypeInfo.Type; 14392 if (IsPointerAttr) 14393 RequiredType = Context.getPointerType(RequiredType); 14394 14395 bool mismatch = false; 14396 if (!TypeInfo.LayoutCompatible) { 14397 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14398 14399 // C++11 [basic.fundamental] p1: 14400 // Plain char, signed char, and unsigned char are three distinct types. 14401 // 14402 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14403 // char' depending on the current char signedness mode. 14404 if (mismatch) 14405 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14406 RequiredType->getPointeeType())) || 14407 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14408 mismatch = false; 14409 } else 14410 if (IsPointerAttr) 14411 mismatch = !isLayoutCompatible(Context, 14412 ArgumentType->getPointeeType(), 14413 RequiredType->getPointeeType()); 14414 else 14415 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14416 14417 if (mismatch) 14418 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14419 << ArgumentType << ArgumentKind 14420 << TypeInfo.LayoutCompatible << RequiredType 14421 << ArgumentExpr->getSourceRange() 14422 << TypeTagExpr->getSourceRange(); 14423 } 14424 14425 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14426 CharUnits Alignment) { 14427 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14428 } 14429 14430 void Sema::DiagnoseMisalignedMembers() { 14431 for (MisalignedMember &m : MisalignedMembers) { 14432 const NamedDecl *ND = m.RD; 14433 if (ND->getName().empty()) { 14434 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14435 ND = TD; 14436 } 14437 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14438 << m.MD << ND << m.E->getSourceRange(); 14439 } 14440 MisalignedMembers.clear(); 14441 } 14442 14443 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14444 E = E->IgnoreParens(); 14445 if (!T->isPointerType() && !T->isIntegerType()) 14446 return; 14447 if (isa<UnaryOperator>(E) && 14448 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14449 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14450 if (isa<MemberExpr>(Op)) { 14451 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14452 if (MA != MisalignedMembers.end() && 14453 (T->isIntegerType() || 14454 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14455 Context.getTypeAlignInChars( 14456 T->getPointeeType()) <= MA->Alignment)))) 14457 MisalignedMembers.erase(MA); 14458 } 14459 } 14460 } 14461 14462 void Sema::RefersToMemberWithReducedAlignment( 14463 Expr *E, 14464 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14465 Action) { 14466 const auto *ME = dyn_cast<MemberExpr>(E); 14467 if (!ME) 14468 return; 14469 14470 // No need to check expressions with an __unaligned-qualified type. 14471 if (E->getType().getQualifiers().hasUnaligned()) 14472 return; 14473 14474 // For a chain of MemberExpr like "a.b.c.d" this list 14475 // will keep FieldDecl's like [d, c, b]. 14476 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14477 const MemberExpr *TopME = nullptr; 14478 bool AnyIsPacked = false; 14479 do { 14480 QualType BaseType = ME->getBase()->getType(); 14481 if (BaseType->isDependentType()) 14482 return; 14483 if (ME->isArrow()) 14484 BaseType = BaseType->getPointeeType(); 14485 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 14486 if (RD->isInvalidDecl()) 14487 return; 14488 14489 ValueDecl *MD = ME->getMemberDecl(); 14490 auto *FD = dyn_cast<FieldDecl>(MD); 14491 // We do not care about non-data members. 14492 if (!FD || FD->isInvalidDecl()) 14493 return; 14494 14495 AnyIsPacked = 14496 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14497 ReverseMemberChain.push_back(FD); 14498 14499 TopME = ME; 14500 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14501 } while (ME); 14502 assert(TopME && "We did not compute a topmost MemberExpr!"); 14503 14504 // Not the scope of this diagnostic. 14505 if (!AnyIsPacked) 14506 return; 14507 14508 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14509 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14510 // TODO: The innermost base of the member expression may be too complicated. 14511 // For now, just disregard these cases. This is left for future 14512 // improvement. 14513 if (!DRE && !isa<CXXThisExpr>(TopBase)) 14514 return; 14515 14516 // Alignment expected by the whole expression. 14517 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 14518 14519 // No need to do anything else with this case. 14520 if (ExpectedAlignment.isOne()) 14521 return; 14522 14523 // Synthesize offset of the whole access. 14524 CharUnits Offset; 14525 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 14526 I++) { 14527 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 14528 } 14529 14530 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 14531 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 14532 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 14533 14534 // The base expression of the innermost MemberExpr may give 14535 // stronger guarantees than the class containing the member. 14536 if (DRE && !TopME->isArrow()) { 14537 const ValueDecl *VD = DRE->getDecl(); 14538 if (!VD->getType()->isReferenceType()) 14539 CompleteObjectAlignment = 14540 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 14541 } 14542 14543 // Check if the synthesized offset fulfills the alignment. 14544 if (Offset % ExpectedAlignment != 0 || 14545 // It may fulfill the offset it but the effective alignment may still be 14546 // lower than the expected expression alignment. 14547 CompleteObjectAlignment < ExpectedAlignment) { 14548 // If this happens, we want to determine a sensible culprit of this. 14549 // Intuitively, watching the chain of member expressions from right to 14550 // left, we start with the required alignment (as required by the field 14551 // type) but some packed attribute in that chain has reduced the alignment. 14552 // It may happen that another packed structure increases it again. But if 14553 // we are here such increase has not been enough. So pointing the first 14554 // FieldDecl that either is packed or else its RecordDecl is, 14555 // seems reasonable. 14556 FieldDecl *FD = nullptr; 14557 CharUnits Alignment; 14558 for (FieldDecl *FDI : ReverseMemberChain) { 14559 if (FDI->hasAttr<PackedAttr>() || 14560 FDI->getParent()->hasAttr<PackedAttr>()) { 14561 FD = FDI; 14562 Alignment = std::min( 14563 Context.getTypeAlignInChars(FD->getType()), 14564 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 14565 break; 14566 } 14567 } 14568 assert(FD && "We did not find a packed FieldDecl!"); 14569 Action(E, FD->getParent(), FD, Alignment); 14570 } 14571 } 14572 14573 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 14574 using namespace std::placeholders; 14575 14576 RefersToMemberWithReducedAlignment( 14577 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 14578 _2, _3, _4)); 14579 } 14580