1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is the desired number. 113 /// This is useful when doing custom type-checking. Returns true on error. 114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 115 unsigned argCount = call->getNumArgs(); 116 if (argCount == desiredArgCount) return false; 117 118 if (argCount < desiredArgCount) 119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 120 << 0 /*function call*/ << desiredArgCount << argCount 121 << call->getSourceRange(); 122 123 // Highlight all the excess arguments. 124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 125 call->getArg(argCount - 1)->getEndLoc()); 126 127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 128 << 0 /*function call*/ << desiredArgCount << argCount 129 << call->getArg(1)->getSourceRange(); 130 } 131 132 /// Check that the first argument to __builtin_annotation is an integer 133 /// and the second argument is a non-wide string literal. 134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 135 if (checkArgCount(S, TheCall, 2)) 136 return true; 137 138 // First argument should be an integer. 139 Expr *ValArg = TheCall->getArg(0); 140 QualType Ty = ValArg->getType(); 141 if (!Ty->isIntegerType()) { 142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 143 << ValArg->getSourceRange(); 144 return true; 145 } 146 147 // Second argument should be a constant string. 148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 150 if (!Literal || !Literal->isAscii()) { 151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 152 << StrArg->getSourceRange(); 153 return true; 154 } 155 156 TheCall->setType(Ty); 157 return false; 158 } 159 160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 161 // We need at least one argument. 162 if (TheCall->getNumArgs() < 1) { 163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 164 << 0 << 1 << TheCall->getNumArgs() 165 << TheCall->getCallee()->getSourceRange(); 166 return true; 167 } 168 169 // All arguments should be wide string literals. 170 for (Expr *Arg : TheCall->arguments()) { 171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 172 if (!Literal || !Literal->isWide()) { 173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 174 << Arg->getSourceRange(); 175 return true; 176 } 177 } 178 179 return false; 180 } 181 182 /// Check that the argument to __builtin_addressof is a glvalue, and set the 183 /// result type to the corresponding pointer type. 184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 185 if (checkArgCount(S, TheCall, 1)) 186 return true; 187 188 ExprResult Arg(TheCall->getArg(0)); 189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 190 if (ResultType.isNull()) 191 return true; 192 193 TheCall->setArg(0, Arg.get()); 194 TheCall->setType(ResultType); 195 return false; 196 } 197 198 /// Check the number of arguments and set the result type to 199 /// the argument type. 200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 201 if (checkArgCount(S, TheCall, 1)) 202 return true; 203 204 TheCall->setType(TheCall->getArg(0)->getType()); 205 return false; 206 } 207 208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 210 /// type (but not a function pointer) and that the alignment is a power-of-two. 211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 212 if (checkArgCount(S, TheCall, 2)) 213 return true; 214 215 clang::Expr *Source = TheCall->getArg(0); 216 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 217 218 auto IsValidIntegerType = [](QualType Ty) { 219 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 220 }; 221 QualType SrcTy = Source->getType(); 222 // We should also be able to use it with arrays (but not functions!). 223 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 224 SrcTy = S.Context.getDecayedType(SrcTy); 225 } 226 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 227 SrcTy->isFunctionPointerType()) { 228 // FIXME: this is not quite the right error message since we don't allow 229 // floating point types, or member pointers. 230 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 231 << SrcTy; 232 return true; 233 } 234 235 clang::Expr *AlignOp = TheCall->getArg(1); 236 if (!IsValidIntegerType(AlignOp->getType())) { 237 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 238 << AlignOp->getType(); 239 return true; 240 } 241 Expr::EvalResult AlignResult; 242 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 243 // We can't check validity of alignment if it is value dependent. 244 if (!AlignOp->isValueDependent() && 245 AlignOp->EvaluateAsInt(AlignResult, S.Context, 246 Expr::SE_AllowSideEffects)) { 247 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 248 llvm::APSInt MaxValue( 249 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 250 if (AlignValue < 1) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 252 return true; 253 } 254 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 255 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 256 << toString(MaxValue, 10); 257 return true; 258 } 259 if (!AlignValue.isPowerOf2()) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 261 return true; 262 } 263 if (AlignValue == 1) { 264 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 265 << IsBooleanAlignBuiltin; 266 } 267 } 268 269 ExprResult SrcArg = S.PerformCopyInitialization( 270 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 271 SourceLocation(), Source); 272 if (SrcArg.isInvalid()) 273 return true; 274 TheCall->setArg(0, SrcArg.get()); 275 ExprResult AlignArg = 276 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 277 S.Context, AlignOp->getType(), false), 278 SourceLocation(), AlignOp); 279 if (AlignArg.isInvalid()) 280 return true; 281 TheCall->setArg(1, AlignArg.get()); 282 // For align_up/align_down, the return type is the same as the (potentially 283 // decayed) argument type including qualifiers. For is_aligned(), the result 284 // is always bool. 285 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 286 return false; 287 } 288 289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 290 unsigned BuiltinID) { 291 if (checkArgCount(S, TheCall, 3)) 292 return true; 293 294 // First two arguments should be integers. 295 for (unsigned I = 0; I < 2; ++I) { 296 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 297 if (Arg.isInvalid()) return true; 298 TheCall->setArg(I, Arg.get()); 299 300 QualType Ty = Arg.get()->getType(); 301 if (!Ty->isIntegerType()) { 302 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 303 << Ty << Arg.get()->getSourceRange(); 304 return true; 305 } 306 } 307 308 // Third argument should be a pointer to a non-const integer. 309 // IRGen correctly handles volatile, restrict, and address spaces, and 310 // the other qualifiers aren't possible. 311 { 312 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 313 if (Arg.isInvalid()) return true; 314 TheCall->setArg(2, Arg.get()); 315 316 QualType Ty = Arg.get()->getType(); 317 const auto *PtrTy = Ty->getAs<PointerType>(); 318 if (!PtrTy || 319 !PtrTy->getPointeeType()->isIntegerType() || 320 PtrTy->getPointeeType().isConstQualified()) { 321 S.Diag(Arg.get()->getBeginLoc(), 322 diag::err_overflow_builtin_must_be_ptr_int) 323 << Ty << Arg.get()->getSourceRange(); 324 return true; 325 } 326 } 327 328 // Disallow signed ExtIntType args larger than 128 bits to mul function until 329 // we improve backend support. 330 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 331 for (unsigned I = 0; I < 3; ++I) { 332 const auto Arg = TheCall->getArg(I); 333 // Third argument will be a pointer. 334 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 335 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 336 S.getASTContext().getIntWidth(Ty) > 128) 337 return S.Diag(Arg->getBeginLoc(), 338 diag::err_overflow_builtin_ext_int_max_size) 339 << 128; 340 } 341 } 342 343 return false; 344 } 345 346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 347 if (checkArgCount(S, BuiltinCall, 2)) 348 return true; 349 350 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 351 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 352 Expr *Call = BuiltinCall->getArg(0); 353 Expr *Chain = BuiltinCall->getArg(1); 354 355 if (Call->getStmtClass() != Stmt::CallExprClass) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 auto CE = cast<CallExpr>(Call); 362 if (CE->getCallee()->getType()->isBlockPointerType()) { 363 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 364 << Call->getSourceRange(); 365 return true; 366 } 367 368 const Decl *TargetDecl = CE->getCalleeDecl(); 369 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 370 if (FD->getBuiltinID()) { 371 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 372 << Call->getSourceRange(); 373 return true; 374 } 375 376 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 377 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 378 << Call->getSourceRange(); 379 return true; 380 } 381 382 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 383 if (ChainResult.isInvalid()) 384 return true; 385 if (!ChainResult.get()->getType()->isPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 387 << Chain->getSourceRange(); 388 return true; 389 } 390 391 QualType ReturnTy = CE->getCallReturnType(S.Context); 392 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 393 QualType BuiltinTy = S.Context.getFunctionType( 394 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 395 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 396 397 Builtin = 398 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 399 400 BuiltinCall->setType(CE->getType()); 401 BuiltinCall->setValueKind(CE->getValueKind()); 402 BuiltinCall->setObjectKind(CE->getObjectKind()); 403 BuiltinCall->setCallee(Builtin); 404 BuiltinCall->setArg(1, ChainResult.get()); 405 406 return false; 407 } 408 409 namespace { 410 411 class EstimateSizeFormatHandler 412 : public analyze_format_string::FormatStringHandler { 413 size_t Size; 414 415 public: 416 EstimateSizeFormatHandler(StringRef Format) 417 : Size(std::min(Format.find(0), Format.size()) + 418 1 /* null byte always written by sprintf */) {} 419 420 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 421 const char *, unsigned SpecifierLen) override { 422 423 const size_t FieldWidth = computeFieldWidth(FS); 424 const size_t Precision = computePrecision(FS); 425 426 // The actual format. 427 switch (FS.getConversionSpecifier().getKind()) { 428 // Just a char. 429 case analyze_format_string::ConversionSpecifier::cArg: 430 case analyze_format_string::ConversionSpecifier::CArg: 431 Size += std::max(FieldWidth, (size_t)1); 432 break; 433 // Just an integer. 434 case analyze_format_string::ConversionSpecifier::dArg: 435 case analyze_format_string::ConversionSpecifier::DArg: 436 case analyze_format_string::ConversionSpecifier::iArg: 437 case analyze_format_string::ConversionSpecifier::oArg: 438 case analyze_format_string::ConversionSpecifier::OArg: 439 case analyze_format_string::ConversionSpecifier::uArg: 440 case analyze_format_string::ConversionSpecifier::UArg: 441 case analyze_format_string::ConversionSpecifier::xArg: 442 case analyze_format_string::ConversionSpecifier::XArg: 443 Size += std::max(FieldWidth, Precision); 444 break; 445 446 // %g style conversion switches between %f or %e style dynamically. 447 // %f always takes less space, so default to it. 448 case analyze_format_string::ConversionSpecifier::gArg: 449 case analyze_format_string::ConversionSpecifier::GArg: 450 451 // Floating point number in the form '[+]ddd.ddd'. 452 case analyze_format_string::ConversionSpecifier::fArg: 453 case analyze_format_string::ConversionSpecifier::FArg: 454 Size += std::max(FieldWidth, 1 /* integer part */ + 455 (Precision ? 1 + Precision 456 : 0) /* period + decimal */); 457 break; 458 459 // Floating point number in the form '[-]d.ddde[+-]dd'. 460 case analyze_format_string::ConversionSpecifier::eArg: 461 case analyze_format_string::ConversionSpecifier::EArg: 462 Size += 463 std::max(FieldWidth, 464 1 /* integer part */ + 465 (Precision ? 1 + Precision : 0) /* period + decimal */ + 466 1 /* e or E letter */ + 2 /* exponent */); 467 break; 468 469 // Floating point number in the form '[-]0xh.hhhhp±dd'. 470 case analyze_format_string::ConversionSpecifier::aArg: 471 case analyze_format_string::ConversionSpecifier::AArg: 472 Size += 473 std::max(FieldWidth, 474 2 /* 0x */ + 1 /* integer part */ + 475 (Precision ? 1 + Precision : 0) /* period + decimal */ + 476 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 477 break; 478 479 // Just a string. 480 case analyze_format_string::ConversionSpecifier::sArg: 481 case analyze_format_string::ConversionSpecifier::SArg: 482 Size += FieldWidth; 483 break; 484 485 // Just a pointer in the form '0xddd'. 486 case analyze_format_string::ConversionSpecifier::pArg: 487 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 488 break; 489 490 // A plain percent. 491 case analyze_format_string::ConversionSpecifier::PercentArg: 492 Size += 1; 493 break; 494 495 default: 496 break; 497 } 498 499 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 500 501 if (FS.hasAlternativeForm()) { 502 switch (FS.getConversionSpecifier().getKind()) { 503 default: 504 break; 505 // Force a leading '0'. 506 case analyze_format_string::ConversionSpecifier::oArg: 507 Size += 1; 508 break; 509 // Force a leading '0x'. 510 case analyze_format_string::ConversionSpecifier::xArg: 511 case analyze_format_string::ConversionSpecifier::XArg: 512 Size += 2; 513 break; 514 // Force a period '.' before decimal, even if precision is 0. 515 case analyze_format_string::ConversionSpecifier::aArg: 516 case analyze_format_string::ConversionSpecifier::AArg: 517 case analyze_format_string::ConversionSpecifier::eArg: 518 case analyze_format_string::ConversionSpecifier::EArg: 519 case analyze_format_string::ConversionSpecifier::fArg: 520 case analyze_format_string::ConversionSpecifier::FArg: 521 case analyze_format_string::ConversionSpecifier::gArg: 522 case analyze_format_string::ConversionSpecifier::GArg: 523 Size += (Precision ? 0 : 1); 524 break; 525 } 526 } 527 assert(SpecifierLen <= Size && "no underflow"); 528 Size -= SpecifierLen; 529 return true; 530 } 531 532 size_t getSizeLowerBound() const { return Size; } 533 534 private: 535 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 536 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 537 size_t FieldWidth = 0; 538 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 539 FieldWidth = FW.getConstantAmount(); 540 return FieldWidth; 541 } 542 543 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 544 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 545 size_t Precision = 0; 546 547 // See man 3 printf for default precision value based on the specifier. 548 switch (FW.getHowSpecified()) { 549 case analyze_format_string::OptionalAmount::NotSpecified: 550 switch (FS.getConversionSpecifier().getKind()) { 551 default: 552 break; 553 case analyze_format_string::ConversionSpecifier::dArg: // %d 554 case analyze_format_string::ConversionSpecifier::DArg: // %D 555 case analyze_format_string::ConversionSpecifier::iArg: // %i 556 Precision = 1; 557 break; 558 case analyze_format_string::ConversionSpecifier::oArg: // %d 559 case analyze_format_string::ConversionSpecifier::OArg: // %D 560 case analyze_format_string::ConversionSpecifier::uArg: // %d 561 case analyze_format_string::ConversionSpecifier::UArg: // %D 562 case analyze_format_string::ConversionSpecifier::xArg: // %d 563 case analyze_format_string::ConversionSpecifier::XArg: // %D 564 Precision = 1; 565 break; 566 case analyze_format_string::ConversionSpecifier::fArg: // %f 567 case analyze_format_string::ConversionSpecifier::FArg: // %F 568 case analyze_format_string::ConversionSpecifier::eArg: // %e 569 case analyze_format_string::ConversionSpecifier::EArg: // %E 570 case analyze_format_string::ConversionSpecifier::gArg: // %g 571 case analyze_format_string::ConversionSpecifier::GArg: // %G 572 Precision = 6; 573 break; 574 case analyze_format_string::ConversionSpecifier::pArg: // %d 575 Precision = 1; 576 break; 577 } 578 break; 579 case analyze_format_string::OptionalAmount::Constant: 580 Precision = FW.getConstantAmount(); 581 break; 582 default: 583 break; 584 } 585 return Precision; 586 } 587 }; 588 589 } // namespace 590 591 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 592 CallExpr *TheCall) { 593 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 594 isConstantEvaluated()) 595 return; 596 597 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 598 if (!BuiltinID) 599 return; 600 601 const TargetInfo &TI = getASTContext().getTargetInfo(); 602 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 603 604 auto ComputeExplicitObjectSizeArgument = 605 [&](unsigned Index) -> Optional<llvm::APSInt> { 606 Expr::EvalResult Result; 607 Expr *SizeArg = TheCall->getArg(Index); 608 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 609 return llvm::None; 610 return Result.Val.getInt(); 611 }; 612 613 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 614 // If the parameter has a pass_object_size attribute, then we should use its 615 // (potentially) more strict checking mode. Otherwise, conservatively assume 616 // type 0. 617 int BOSType = 0; 618 if (const auto *POS = 619 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 620 BOSType = POS->getType(); 621 622 const Expr *ObjArg = TheCall->getArg(Index); 623 uint64_t Result; 624 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 625 return llvm::None; 626 627 // Get the object size in the target's size_t width. 628 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 629 }; 630 631 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 632 Expr *ObjArg = TheCall->getArg(Index); 633 uint64_t Result; 634 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 635 return llvm::None; 636 // Add 1 for null byte. 637 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 638 }; 639 640 Optional<llvm::APSInt> SourceSize; 641 Optional<llvm::APSInt> DestinationSize; 642 unsigned DiagID = 0; 643 bool IsChkVariant = false; 644 645 switch (BuiltinID) { 646 default: 647 return; 648 case Builtin::BI__builtin_strcpy: 649 case Builtin::BIstrcpy: { 650 DiagID = diag::warn_fortify_strlen_overflow; 651 SourceSize = ComputeStrLenArgument(1); 652 DestinationSize = ComputeSizeArgument(0); 653 break; 654 } 655 656 case Builtin::BI__builtin___strcpy_chk: { 657 DiagID = diag::warn_fortify_strlen_overflow; 658 SourceSize = ComputeStrLenArgument(1); 659 DestinationSize = ComputeExplicitObjectSizeArgument(2); 660 IsChkVariant = true; 661 break; 662 } 663 664 case Builtin::BIsprintf: 665 case Builtin::BI__builtin___sprintf_chk: { 666 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 667 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 668 669 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 670 671 if (!Format->isAscii() && !Format->isUTF8()) 672 return; 673 674 StringRef FormatStrRef = Format->getString(); 675 EstimateSizeFormatHandler H(FormatStrRef); 676 const char *FormatBytes = FormatStrRef.data(); 677 const ConstantArrayType *T = 678 Context.getAsConstantArrayType(Format->getType()); 679 assert(T && "String literal not of constant array type!"); 680 size_t TypeSize = T->getSize().getZExtValue(); 681 682 // In case there's a null byte somewhere. 683 size_t StrLen = 684 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 685 if (!analyze_format_string::ParsePrintfString( 686 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 687 Context.getTargetInfo(), false)) { 688 DiagID = diag::warn_fortify_source_format_overflow; 689 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 690 .extOrTrunc(SizeTypeWidth); 691 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 692 DestinationSize = ComputeExplicitObjectSizeArgument(2); 693 IsChkVariant = true; 694 } else { 695 DestinationSize = ComputeSizeArgument(0); 696 } 697 break; 698 } 699 } 700 return; 701 } 702 case Builtin::BI__builtin___memcpy_chk: 703 case Builtin::BI__builtin___memmove_chk: 704 case Builtin::BI__builtin___memset_chk: 705 case Builtin::BI__builtin___strlcat_chk: 706 case Builtin::BI__builtin___strlcpy_chk: 707 case Builtin::BI__builtin___strncat_chk: 708 case Builtin::BI__builtin___strncpy_chk: 709 case Builtin::BI__builtin___stpncpy_chk: 710 case Builtin::BI__builtin___memccpy_chk: 711 case Builtin::BI__builtin___mempcpy_chk: { 712 DiagID = diag::warn_builtin_chk_overflow; 713 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 714 DestinationSize = 715 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 716 IsChkVariant = true; 717 break; 718 } 719 720 case Builtin::BI__builtin___snprintf_chk: 721 case Builtin::BI__builtin___vsnprintf_chk: { 722 DiagID = diag::warn_builtin_chk_overflow; 723 SourceSize = ComputeExplicitObjectSizeArgument(1); 724 DestinationSize = ComputeExplicitObjectSizeArgument(3); 725 IsChkVariant = true; 726 break; 727 } 728 729 case Builtin::BIstrncat: 730 case Builtin::BI__builtin_strncat: 731 case Builtin::BIstrncpy: 732 case Builtin::BI__builtin_strncpy: 733 case Builtin::BIstpncpy: 734 case Builtin::BI__builtin_stpncpy: { 735 // Whether these functions overflow depends on the runtime strlen of the 736 // string, not just the buffer size, so emitting the "always overflow" 737 // diagnostic isn't quite right. We should still diagnose passing a buffer 738 // size larger than the destination buffer though; this is a runtime abort 739 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 740 DiagID = diag::warn_fortify_source_size_mismatch; 741 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 742 DestinationSize = ComputeSizeArgument(0); 743 break; 744 } 745 746 case Builtin::BImemcpy: 747 case Builtin::BI__builtin_memcpy: 748 case Builtin::BImemmove: 749 case Builtin::BI__builtin_memmove: 750 case Builtin::BImemset: 751 case Builtin::BI__builtin_memset: 752 case Builtin::BImempcpy: 753 case Builtin::BI__builtin_mempcpy: { 754 DiagID = diag::warn_fortify_source_overflow; 755 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 756 DestinationSize = ComputeSizeArgument(0); 757 break; 758 } 759 case Builtin::BIsnprintf: 760 case Builtin::BI__builtin_snprintf: 761 case Builtin::BIvsnprintf: 762 case Builtin::BI__builtin_vsnprintf: { 763 DiagID = diag::warn_fortify_source_size_mismatch; 764 SourceSize = ComputeExplicitObjectSizeArgument(1); 765 DestinationSize = ComputeSizeArgument(0); 766 break; 767 } 768 } 769 770 if (!SourceSize || !DestinationSize || 771 SourceSize.getValue().ule(DestinationSize.getValue())) 772 return; 773 774 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 775 // Skim off the details of whichever builtin was called to produce a better 776 // diagnostic, as it's unlikely that the user wrote the __builtin explicitly. 777 if (IsChkVariant) { 778 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 779 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 780 } else if (FunctionName.startswith("__builtin_")) { 781 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 782 } 783 784 SmallString<16> DestinationStr; 785 SmallString<16> SourceStr; 786 DestinationSize->toString(DestinationStr, /*Radix=*/10); 787 SourceSize->toString(SourceStr, /*Radix=*/10); 788 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 789 PDiag(DiagID) 790 << FunctionName << DestinationStr << SourceStr); 791 } 792 793 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 794 Scope::ScopeFlags NeededScopeFlags, 795 unsigned DiagID) { 796 // Scopes aren't available during instantiation. Fortunately, builtin 797 // functions cannot be template args so they cannot be formed through template 798 // instantiation. Therefore checking once during the parse is sufficient. 799 if (SemaRef.inTemplateInstantiation()) 800 return false; 801 802 Scope *S = SemaRef.getCurScope(); 803 while (S && !S->isSEHExceptScope()) 804 S = S->getParent(); 805 if (!S || !(S->getFlags() & NeededScopeFlags)) { 806 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 807 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 808 << DRE->getDecl()->getIdentifier(); 809 return true; 810 } 811 812 return false; 813 } 814 815 static inline bool isBlockPointer(Expr *Arg) { 816 return Arg->getType()->isBlockPointerType(); 817 } 818 819 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 820 /// void*, which is a requirement of device side enqueue. 821 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 822 const BlockPointerType *BPT = 823 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 824 ArrayRef<QualType> Params = 825 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 826 unsigned ArgCounter = 0; 827 bool IllegalParams = false; 828 // Iterate through the block parameters until either one is found that is not 829 // a local void*, or the block is valid. 830 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 831 I != E; ++I, ++ArgCounter) { 832 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 833 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 834 LangAS::opencl_local) { 835 // Get the location of the error. If a block literal has been passed 836 // (BlockExpr) then we can point straight to the offending argument, 837 // else we just point to the variable reference. 838 SourceLocation ErrorLoc; 839 if (isa<BlockExpr>(BlockArg)) { 840 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 841 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 842 } else if (isa<DeclRefExpr>(BlockArg)) { 843 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 844 } 845 S.Diag(ErrorLoc, 846 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 847 IllegalParams = true; 848 } 849 } 850 851 return IllegalParams; 852 } 853 854 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 855 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 856 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 857 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 858 return true; 859 } 860 return false; 861 } 862 863 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 864 if (checkArgCount(S, TheCall, 2)) 865 return true; 866 867 if (checkOpenCLSubgroupExt(S, TheCall)) 868 return true; 869 870 // First argument is an ndrange_t type. 871 Expr *NDRangeArg = TheCall->getArg(0); 872 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 873 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 874 << TheCall->getDirectCallee() << "'ndrange_t'"; 875 return true; 876 } 877 878 Expr *BlockArg = TheCall->getArg(1); 879 if (!isBlockPointer(BlockArg)) { 880 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 881 << TheCall->getDirectCallee() << "block"; 882 return true; 883 } 884 return checkOpenCLBlockArgs(S, BlockArg); 885 } 886 887 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 888 /// get_kernel_work_group_size 889 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 890 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 891 if (checkArgCount(S, TheCall, 1)) 892 return true; 893 894 Expr *BlockArg = TheCall->getArg(0); 895 if (!isBlockPointer(BlockArg)) { 896 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 897 << TheCall->getDirectCallee() << "block"; 898 return true; 899 } 900 return checkOpenCLBlockArgs(S, BlockArg); 901 } 902 903 /// Diagnose integer type and any valid implicit conversion to it. 904 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 905 const QualType &IntType); 906 907 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 908 unsigned Start, unsigned End) { 909 bool IllegalParams = false; 910 for (unsigned I = Start; I <= End; ++I) 911 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 912 S.Context.getSizeType()); 913 return IllegalParams; 914 } 915 916 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 917 /// 'local void*' parameter of passed block. 918 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 919 Expr *BlockArg, 920 unsigned NumNonVarArgs) { 921 const BlockPointerType *BPT = 922 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 923 unsigned NumBlockParams = 924 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 925 unsigned TotalNumArgs = TheCall->getNumArgs(); 926 927 // For each argument passed to the block, a corresponding uint needs to 928 // be passed to describe the size of the local memory. 929 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 930 S.Diag(TheCall->getBeginLoc(), 931 diag::err_opencl_enqueue_kernel_local_size_args); 932 return true; 933 } 934 935 // Check that the sizes of the local memory are specified by integers. 936 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 937 TotalNumArgs - 1); 938 } 939 940 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 941 /// overload formats specified in Table 6.13.17.1. 942 /// int enqueue_kernel(queue_t queue, 943 /// kernel_enqueue_flags_t flags, 944 /// const ndrange_t ndrange, 945 /// void (^block)(void)) 946 /// int enqueue_kernel(queue_t queue, 947 /// kernel_enqueue_flags_t flags, 948 /// const ndrange_t ndrange, 949 /// uint num_events_in_wait_list, 950 /// clk_event_t *event_wait_list, 951 /// clk_event_t *event_ret, 952 /// void (^block)(void)) 953 /// int enqueue_kernel(queue_t queue, 954 /// kernel_enqueue_flags_t flags, 955 /// const ndrange_t ndrange, 956 /// void (^block)(local void*, ...), 957 /// uint size0, ...) 958 /// int enqueue_kernel(queue_t queue, 959 /// kernel_enqueue_flags_t flags, 960 /// const ndrange_t ndrange, 961 /// uint num_events_in_wait_list, 962 /// clk_event_t *event_wait_list, 963 /// clk_event_t *event_ret, 964 /// void (^block)(local void*, ...), 965 /// uint size0, ...) 966 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 967 unsigned NumArgs = TheCall->getNumArgs(); 968 969 if (NumArgs < 4) { 970 S.Diag(TheCall->getBeginLoc(), 971 diag::err_typecheck_call_too_few_args_at_least) 972 << 0 << 4 << NumArgs; 973 return true; 974 } 975 976 Expr *Arg0 = TheCall->getArg(0); 977 Expr *Arg1 = TheCall->getArg(1); 978 Expr *Arg2 = TheCall->getArg(2); 979 Expr *Arg3 = TheCall->getArg(3); 980 981 // First argument always needs to be a queue_t type. 982 if (!Arg0->getType()->isQueueT()) { 983 S.Diag(TheCall->getArg(0)->getBeginLoc(), 984 diag::err_opencl_builtin_expected_type) 985 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 986 return true; 987 } 988 989 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 990 if (!Arg1->getType()->isIntegerType()) { 991 S.Diag(TheCall->getArg(1)->getBeginLoc(), 992 diag::err_opencl_builtin_expected_type) 993 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 994 return true; 995 } 996 997 // Third argument is always an ndrange_t type. 998 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 999 S.Diag(TheCall->getArg(2)->getBeginLoc(), 1000 diag::err_opencl_builtin_expected_type) 1001 << TheCall->getDirectCallee() << "'ndrange_t'"; 1002 return true; 1003 } 1004 1005 // With four arguments, there is only one form that the function could be 1006 // called in: no events and no variable arguments. 1007 if (NumArgs == 4) { 1008 // check that the last argument is the right block type. 1009 if (!isBlockPointer(Arg3)) { 1010 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1011 << TheCall->getDirectCallee() << "block"; 1012 return true; 1013 } 1014 // we have a block type, check the prototype 1015 const BlockPointerType *BPT = 1016 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1017 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1018 S.Diag(Arg3->getBeginLoc(), 1019 diag::err_opencl_enqueue_kernel_blocks_no_args); 1020 return true; 1021 } 1022 return false; 1023 } 1024 // we can have block + varargs. 1025 if (isBlockPointer(Arg3)) 1026 return (checkOpenCLBlockArgs(S, Arg3) || 1027 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1028 // last two cases with either exactly 7 args or 7 args and varargs. 1029 if (NumArgs >= 7) { 1030 // check common block argument. 1031 Expr *Arg6 = TheCall->getArg(6); 1032 if (!isBlockPointer(Arg6)) { 1033 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1034 << TheCall->getDirectCallee() << "block"; 1035 return true; 1036 } 1037 if (checkOpenCLBlockArgs(S, Arg6)) 1038 return true; 1039 1040 // Forth argument has to be any integer type. 1041 if (!Arg3->getType()->isIntegerType()) { 1042 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1043 diag::err_opencl_builtin_expected_type) 1044 << TheCall->getDirectCallee() << "integer"; 1045 return true; 1046 } 1047 // check remaining common arguments. 1048 Expr *Arg4 = TheCall->getArg(4); 1049 Expr *Arg5 = TheCall->getArg(5); 1050 1051 // Fifth argument is always passed as a pointer to clk_event_t. 1052 if (!Arg4->isNullPointerConstant(S.Context, 1053 Expr::NPC_ValueDependentIsNotNull) && 1054 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1055 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1056 diag::err_opencl_builtin_expected_type) 1057 << TheCall->getDirectCallee() 1058 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1059 return true; 1060 } 1061 1062 // Sixth argument is always passed as a pointer to clk_event_t. 1063 if (!Arg5->isNullPointerConstant(S.Context, 1064 Expr::NPC_ValueDependentIsNotNull) && 1065 !(Arg5->getType()->isPointerType() && 1066 Arg5->getType()->getPointeeType()->isClkEventT())) { 1067 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1068 diag::err_opencl_builtin_expected_type) 1069 << TheCall->getDirectCallee() 1070 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1071 return true; 1072 } 1073 1074 if (NumArgs == 7) 1075 return false; 1076 1077 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1078 } 1079 1080 // None of the specific case has been detected, give generic error 1081 S.Diag(TheCall->getBeginLoc(), 1082 diag::err_opencl_enqueue_kernel_incorrect_args); 1083 return true; 1084 } 1085 1086 /// Returns OpenCL access qual. 1087 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1088 return D->getAttr<OpenCLAccessAttr>(); 1089 } 1090 1091 /// Returns true if pipe element type is different from the pointer. 1092 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1093 const Expr *Arg0 = Call->getArg(0); 1094 // First argument type should always be pipe. 1095 if (!Arg0->getType()->isPipeType()) { 1096 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1097 << Call->getDirectCallee() << Arg0->getSourceRange(); 1098 return true; 1099 } 1100 OpenCLAccessAttr *AccessQual = 1101 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1102 // Validates the access qualifier is compatible with the call. 1103 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1104 // read_only and write_only, and assumed to be read_only if no qualifier is 1105 // specified. 1106 switch (Call->getDirectCallee()->getBuiltinID()) { 1107 case Builtin::BIread_pipe: 1108 case Builtin::BIreserve_read_pipe: 1109 case Builtin::BIcommit_read_pipe: 1110 case Builtin::BIwork_group_reserve_read_pipe: 1111 case Builtin::BIsub_group_reserve_read_pipe: 1112 case Builtin::BIwork_group_commit_read_pipe: 1113 case Builtin::BIsub_group_commit_read_pipe: 1114 if (!(!AccessQual || AccessQual->isReadOnly())) { 1115 S.Diag(Arg0->getBeginLoc(), 1116 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1117 << "read_only" << Arg0->getSourceRange(); 1118 return true; 1119 } 1120 break; 1121 case Builtin::BIwrite_pipe: 1122 case Builtin::BIreserve_write_pipe: 1123 case Builtin::BIcommit_write_pipe: 1124 case Builtin::BIwork_group_reserve_write_pipe: 1125 case Builtin::BIsub_group_reserve_write_pipe: 1126 case Builtin::BIwork_group_commit_write_pipe: 1127 case Builtin::BIsub_group_commit_write_pipe: 1128 if (!(AccessQual && AccessQual->isWriteOnly())) { 1129 S.Diag(Arg0->getBeginLoc(), 1130 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1131 << "write_only" << Arg0->getSourceRange(); 1132 return true; 1133 } 1134 break; 1135 default: 1136 break; 1137 } 1138 return false; 1139 } 1140 1141 /// Returns true if pipe element type is different from the pointer. 1142 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1143 const Expr *Arg0 = Call->getArg(0); 1144 const Expr *ArgIdx = Call->getArg(Idx); 1145 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1146 const QualType EltTy = PipeTy->getElementType(); 1147 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1148 // The Idx argument should be a pointer and the type of the pointer and 1149 // the type of pipe element should also be the same. 1150 if (!ArgTy || 1151 !S.Context.hasSameType( 1152 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1153 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1154 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1155 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1156 return true; 1157 } 1158 return false; 1159 } 1160 1161 // Performs semantic analysis for the read/write_pipe call. 1162 // \param S Reference to the semantic analyzer. 1163 // \param Call A pointer to the builtin call. 1164 // \return True if a semantic error has been found, false otherwise. 1165 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1166 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1167 // functions have two forms. 1168 switch (Call->getNumArgs()) { 1169 case 2: 1170 if (checkOpenCLPipeArg(S, Call)) 1171 return true; 1172 // The call with 2 arguments should be 1173 // read/write_pipe(pipe T, T*). 1174 // Check packet type T. 1175 if (checkOpenCLPipePacketType(S, Call, 1)) 1176 return true; 1177 break; 1178 1179 case 4: { 1180 if (checkOpenCLPipeArg(S, Call)) 1181 return true; 1182 // The call with 4 arguments should be 1183 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1184 // Check reserve_id_t. 1185 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1186 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1187 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1188 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1189 return true; 1190 } 1191 1192 // Check the index. 1193 const Expr *Arg2 = Call->getArg(2); 1194 if (!Arg2->getType()->isIntegerType() && 1195 !Arg2->getType()->isUnsignedIntegerType()) { 1196 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1197 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1198 << Arg2->getType() << Arg2->getSourceRange(); 1199 return true; 1200 } 1201 1202 // Check packet type T. 1203 if (checkOpenCLPipePacketType(S, Call, 3)) 1204 return true; 1205 } break; 1206 default: 1207 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1208 << Call->getDirectCallee() << Call->getSourceRange(); 1209 return true; 1210 } 1211 1212 return false; 1213 } 1214 1215 // Performs a semantic analysis on the {work_group_/sub_group_ 1216 // /_}reserve_{read/write}_pipe 1217 // \param S Reference to the semantic analyzer. 1218 // \param Call The call to the builtin function to be analyzed. 1219 // \return True if a semantic error was found, false otherwise. 1220 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1221 if (checkArgCount(S, Call, 2)) 1222 return true; 1223 1224 if (checkOpenCLPipeArg(S, Call)) 1225 return true; 1226 1227 // Check the reserve size. 1228 if (!Call->getArg(1)->getType()->isIntegerType() && 1229 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1230 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1231 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1232 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1233 return true; 1234 } 1235 1236 // Since return type of reserve_read/write_pipe built-in function is 1237 // reserve_id_t, which is not defined in the builtin def file , we used int 1238 // as return type and need to override the return type of these functions. 1239 Call->setType(S.Context.OCLReserveIDTy); 1240 1241 return false; 1242 } 1243 1244 // Performs a semantic analysis on {work_group_/sub_group_ 1245 // /_}commit_{read/write}_pipe 1246 // \param S Reference to the semantic analyzer. 1247 // \param Call The call to the builtin function to be analyzed. 1248 // \return True if a semantic error was found, false otherwise. 1249 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1250 if (checkArgCount(S, Call, 2)) 1251 return true; 1252 1253 if (checkOpenCLPipeArg(S, Call)) 1254 return true; 1255 1256 // Check reserve_id_t. 1257 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1258 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1259 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1260 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1261 return true; 1262 } 1263 1264 return false; 1265 } 1266 1267 // Performs a semantic analysis on the call to built-in Pipe 1268 // Query Functions. 1269 // \param S Reference to the semantic analyzer. 1270 // \param Call The call to the builtin function to be analyzed. 1271 // \return True if a semantic error was found, false otherwise. 1272 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1273 if (checkArgCount(S, Call, 1)) 1274 return true; 1275 1276 if (!Call->getArg(0)->getType()->isPipeType()) { 1277 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1278 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1279 return true; 1280 } 1281 1282 return false; 1283 } 1284 1285 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1286 // Performs semantic analysis for the to_global/local/private call. 1287 // \param S Reference to the semantic analyzer. 1288 // \param BuiltinID ID of the builtin function. 1289 // \param Call A pointer to the builtin call. 1290 // \return True if a semantic error has been found, false otherwise. 1291 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1292 CallExpr *Call) { 1293 if (checkArgCount(S, Call, 1)) 1294 return true; 1295 1296 auto RT = Call->getArg(0)->getType(); 1297 if (!RT->isPointerType() || RT->getPointeeType() 1298 .getAddressSpace() == LangAS::opencl_constant) { 1299 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1300 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1301 return true; 1302 } 1303 1304 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1305 S.Diag(Call->getArg(0)->getBeginLoc(), 1306 diag::warn_opencl_generic_address_space_arg) 1307 << Call->getDirectCallee()->getNameInfo().getAsString() 1308 << Call->getArg(0)->getSourceRange(); 1309 } 1310 1311 RT = RT->getPointeeType(); 1312 auto Qual = RT.getQualifiers(); 1313 switch (BuiltinID) { 1314 case Builtin::BIto_global: 1315 Qual.setAddressSpace(LangAS::opencl_global); 1316 break; 1317 case Builtin::BIto_local: 1318 Qual.setAddressSpace(LangAS::opencl_local); 1319 break; 1320 case Builtin::BIto_private: 1321 Qual.setAddressSpace(LangAS::opencl_private); 1322 break; 1323 default: 1324 llvm_unreachable("Invalid builtin function"); 1325 } 1326 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1327 RT.getUnqualifiedType(), Qual))); 1328 1329 return false; 1330 } 1331 1332 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1333 if (checkArgCount(S, TheCall, 1)) 1334 return ExprError(); 1335 1336 // Compute __builtin_launder's parameter type from the argument. 1337 // The parameter type is: 1338 // * The type of the argument if it's not an array or function type, 1339 // Otherwise, 1340 // * The decayed argument type. 1341 QualType ParamTy = [&]() { 1342 QualType ArgTy = TheCall->getArg(0)->getType(); 1343 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1344 return S.Context.getPointerType(Ty->getElementType()); 1345 if (ArgTy->isFunctionType()) { 1346 return S.Context.getPointerType(ArgTy); 1347 } 1348 return ArgTy; 1349 }(); 1350 1351 TheCall->setType(ParamTy); 1352 1353 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1354 if (!ParamTy->isPointerType()) 1355 return 0; 1356 if (ParamTy->isFunctionPointerType()) 1357 return 1; 1358 if (ParamTy->isVoidPointerType()) 1359 return 2; 1360 return llvm::Optional<unsigned>{}; 1361 }(); 1362 if (DiagSelect.hasValue()) { 1363 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1364 << DiagSelect.getValue() << TheCall->getSourceRange(); 1365 return ExprError(); 1366 } 1367 1368 // We either have an incomplete class type, or we have a class template 1369 // whose instantiation has not been forced. Example: 1370 // 1371 // template <class T> struct Foo { T value; }; 1372 // Foo<int> *p = nullptr; 1373 // auto *d = __builtin_launder(p); 1374 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1375 diag::err_incomplete_type)) 1376 return ExprError(); 1377 1378 assert(ParamTy->getPointeeType()->isObjectType() && 1379 "Unhandled non-object pointer case"); 1380 1381 InitializedEntity Entity = 1382 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1383 ExprResult Arg = 1384 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1385 if (Arg.isInvalid()) 1386 return ExprError(); 1387 TheCall->setArg(0, Arg.get()); 1388 1389 return TheCall; 1390 } 1391 1392 // Emit an error and return true if the current architecture is not in the list 1393 // of supported architectures. 1394 static bool 1395 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1396 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1397 llvm::Triple::ArchType CurArch = 1398 S.getASTContext().getTargetInfo().getTriple().getArch(); 1399 if (llvm::is_contained(SupportedArchs, CurArch)) 1400 return false; 1401 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1402 << TheCall->getSourceRange(); 1403 return true; 1404 } 1405 1406 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1407 SourceLocation CallSiteLoc); 1408 1409 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1410 CallExpr *TheCall) { 1411 switch (TI.getTriple().getArch()) { 1412 default: 1413 // Some builtins don't require additional checking, so just consider these 1414 // acceptable. 1415 return false; 1416 case llvm::Triple::arm: 1417 case llvm::Triple::armeb: 1418 case llvm::Triple::thumb: 1419 case llvm::Triple::thumbeb: 1420 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1421 case llvm::Triple::aarch64: 1422 case llvm::Triple::aarch64_32: 1423 case llvm::Triple::aarch64_be: 1424 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1425 case llvm::Triple::bpfeb: 1426 case llvm::Triple::bpfel: 1427 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1428 case llvm::Triple::hexagon: 1429 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1430 case llvm::Triple::mips: 1431 case llvm::Triple::mipsel: 1432 case llvm::Triple::mips64: 1433 case llvm::Triple::mips64el: 1434 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1435 case llvm::Triple::systemz: 1436 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1437 case llvm::Triple::x86: 1438 case llvm::Triple::x86_64: 1439 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1440 case llvm::Triple::ppc: 1441 case llvm::Triple::ppcle: 1442 case llvm::Triple::ppc64: 1443 case llvm::Triple::ppc64le: 1444 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1445 case llvm::Triple::amdgcn: 1446 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1447 case llvm::Triple::riscv32: 1448 case llvm::Triple::riscv64: 1449 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1450 } 1451 } 1452 1453 ExprResult 1454 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1455 CallExpr *TheCall) { 1456 ExprResult TheCallResult(TheCall); 1457 1458 // Find out if any arguments are required to be integer constant expressions. 1459 unsigned ICEArguments = 0; 1460 ASTContext::GetBuiltinTypeError Error; 1461 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1462 if (Error != ASTContext::GE_None) 1463 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1464 1465 // If any arguments are required to be ICE's, check and diagnose. 1466 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1467 // Skip arguments not required to be ICE's. 1468 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1469 1470 llvm::APSInt Result; 1471 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1472 return true; 1473 ICEArguments &= ~(1 << ArgNo); 1474 } 1475 1476 switch (BuiltinID) { 1477 case Builtin::BI__builtin___CFStringMakeConstantString: 1478 assert(TheCall->getNumArgs() == 1 && 1479 "Wrong # arguments to builtin CFStringMakeConstantString"); 1480 if (CheckObjCString(TheCall->getArg(0))) 1481 return ExprError(); 1482 break; 1483 case Builtin::BI__builtin_ms_va_start: 1484 case Builtin::BI__builtin_stdarg_start: 1485 case Builtin::BI__builtin_va_start: 1486 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1487 return ExprError(); 1488 break; 1489 case Builtin::BI__va_start: { 1490 switch (Context.getTargetInfo().getTriple().getArch()) { 1491 case llvm::Triple::aarch64: 1492 case llvm::Triple::arm: 1493 case llvm::Triple::thumb: 1494 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1495 return ExprError(); 1496 break; 1497 default: 1498 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1499 return ExprError(); 1500 break; 1501 } 1502 break; 1503 } 1504 1505 // The acquire, release, and no fence variants are ARM and AArch64 only. 1506 case Builtin::BI_interlockedbittestandset_acq: 1507 case Builtin::BI_interlockedbittestandset_rel: 1508 case Builtin::BI_interlockedbittestandset_nf: 1509 case Builtin::BI_interlockedbittestandreset_acq: 1510 case Builtin::BI_interlockedbittestandreset_rel: 1511 case Builtin::BI_interlockedbittestandreset_nf: 1512 if (CheckBuiltinTargetSupport( 1513 *this, BuiltinID, TheCall, 1514 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1515 return ExprError(); 1516 break; 1517 1518 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1519 case Builtin::BI_bittest64: 1520 case Builtin::BI_bittestandcomplement64: 1521 case Builtin::BI_bittestandreset64: 1522 case Builtin::BI_bittestandset64: 1523 case Builtin::BI_interlockedbittestandreset64: 1524 case Builtin::BI_interlockedbittestandset64: 1525 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1526 {llvm::Triple::x86_64, llvm::Triple::arm, 1527 llvm::Triple::thumb, llvm::Triple::aarch64})) 1528 return ExprError(); 1529 break; 1530 1531 case Builtin::BI__builtin_isgreater: 1532 case Builtin::BI__builtin_isgreaterequal: 1533 case Builtin::BI__builtin_isless: 1534 case Builtin::BI__builtin_islessequal: 1535 case Builtin::BI__builtin_islessgreater: 1536 case Builtin::BI__builtin_isunordered: 1537 if (SemaBuiltinUnorderedCompare(TheCall)) 1538 return ExprError(); 1539 break; 1540 case Builtin::BI__builtin_fpclassify: 1541 if (SemaBuiltinFPClassification(TheCall, 6)) 1542 return ExprError(); 1543 break; 1544 case Builtin::BI__builtin_isfinite: 1545 case Builtin::BI__builtin_isinf: 1546 case Builtin::BI__builtin_isinf_sign: 1547 case Builtin::BI__builtin_isnan: 1548 case Builtin::BI__builtin_isnormal: 1549 case Builtin::BI__builtin_signbit: 1550 case Builtin::BI__builtin_signbitf: 1551 case Builtin::BI__builtin_signbitl: 1552 if (SemaBuiltinFPClassification(TheCall, 1)) 1553 return ExprError(); 1554 break; 1555 case Builtin::BI__builtin_shufflevector: 1556 return SemaBuiltinShuffleVector(TheCall); 1557 // TheCall will be freed by the smart pointer here, but that's fine, since 1558 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1559 case Builtin::BI__builtin_prefetch: 1560 if (SemaBuiltinPrefetch(TheCall)) 1561 return ExprError(); 1562 break; 1563 case Builtin::BI__builtin_alloca_with_align: 1564 if (SemaBuiltinAllocaWithAlign(TheCall)) 1565 return ExprError(); 1566 LLVM_FALLTHROUGH; 1567 case Builtin::BI__builtin_alloca: 1568 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1569 << TheCall->getDirectCallee(); 1570 break; 1571 case Builtin::BI__arithmetic_fence: 1572 if (SemaBuiltinArithmeticFence(TheCall)) 1573 return ExprError(); 1574 break; 1575 case Builtin::BI__assume: 1576 case Builtin::BI__builtin_assume: 1577 if (SemaBuiltinAssume(TheCall)) 1578 return ExprError(); 1579 break; 1580 case Builtin::BI__builtin_assume_aligned: 1581 if (SemaBuiltinAssumeAligned(TheCall)) 1582 return ExprError(); 1583 break; 1584 case Builtin::BI__builtin_dynamic_object_size: 1585 case Builtin::BI__builtin_object_size: 1586 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1587 return ExprError(); 1588 break; 1589 case Builtin::BI__builtin_longjmp: 1590 if (SemaBuiltinLongjmp(TheCall)) 1591 return ExprError(); 1592 break; 1593 case Builtin::BI__builtin_setjmp: 1594 if (SemaBuiltinSetjmp(TheCall)) 1595 return ExprError(); 1596 break; 1597 case Builtin::BI__builtin_classify_type: 1598 if (checkArgCount(*this, TheCall, 1)) return true; 1599 TheCall->setType(Context.IntTy); 1600 break; 1601 case Builtin::BI__builtin_complex: 1602 if (SemaBuiltinComplex(TheCall)) 1603 return ExprError(); 1604 break; 1605 case Builtin::BI__builtin_constant_p: { 1606 if (checkArgCount(*this, TheCall, 1)) return true; 1607 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1608 if (Arg.isInvalid()) return true; 1609 TheCall->setArg(0, Arg.get()); 1610 TheCall->setType(Context.IntTy); 1611 break; 1612 } 1613 case Builtin::BI__builtin_launder: 1614 return SemaBuiltinLaunder(*this, TheCall); 1615 case Builtin::BI__sync_fetch_and_add: 1616 case Builtin::BI__sync_fetch_and_add_1: 1617 case Builtin::BI__sync_fetch_and_add_2: 1618 case Builtin::BI__sync_fetch_and_add_4: 1619 case Builtin::BI__sync_fetch_and_add_8: 1620 case Builtin::BI__sync_fetch_and_add_16: 1621 case Builtin::BI__sync_fetch_and_sub: 1622 case Builtin::BI__sync_fetch_and_sub_1: 1623 case Builtin::BI__sync_fetch_and_sub_2: 1624 case Builtin::BI__sync_fetch_and_sub_4: 1625 case Builtin::BI__sync_fetch_and_sub_8: 1626 case Builtin::BI__sync_fetch_and_sub_16: 1627 case Builtin::BI__sync_fetch_and_or: 1628 case Builtin::BI__sync_fetch_and_or_1: 1629 case Builtin::BI__sync_fetch_and_or_2: 1630 case Builtin::BI__sync_fetch_and_or_4: 1631 case Builtin::BI__sync_fetch_and_or_8: 1632 case Builtin::BI__sync_fetch_and_or_16: 1633 case Builtin::BI__sync_fetch_and_and: 1634 case Builtin::BI__sync_fetch_and_and_1: 1635 case Builtin::BI__sync_fetch_and_and_2: 1636 case Builtin::BI__sync_fetch_and_and_4: 1637 case Builtin::BI__sync_fetch_and_and_8: 1638 case Builtin::BI__sync_fetch_and_and_16: 1639 case Builtin::BI__sync_fetch_and_xor: 1640 case Builtin::BI__sync_fetch_and_xor_1: 1641 case Builtin::BI__sync_fetch_and_xor_2: 1642 case Builtin::BI__sync_fetch_and_xor_4: 1643 case Builtin::BI__sync_fetch_and_xor_8: 1644 case Builtin::BI__sync_fetch_and_xor_16: 1645 case Builtin::BI__sync_fetch_and_nand: 1646 case Builtin::BI__sync_fetch_and_nand_1: 1647 case Builtin::BI__sync_fetch_and_nand_2: 1648 case Builtin::BI__sync_fetch_and_nand_4: 1649 case Builtin::BI__sync_fetch_and_nand_8: 1650 case Builtin::BI__sync_fetch_and_nand_16: 1651 case Builtin::BI__sync_add_and_fetch: 1652 case Builtin::BI__sync_add_and_fetch_1: 1653 case Builtin::BI__sync_add_and_fetch_2: 1654 case Builtin::BI__sync_add_and_fetch_4: 1655 case Builtin::BI__sync_add_and_fetch_8: 1656 case Builtin::BI__sync_add_and_fetch_16: 1657 case Builtin::BI__sync_sub_and_fetch: 1658 case Builtin::BI__sync_sub_and_fetch_1: 1659 case Builtin::BI__sync_sub_and_fetch_2: 1660 case Builtin::BI__sync_sub_and_fetch_4: 1661 case Builtin::BI__sync_sub_and_fetch_8: 1662 case Builtin::BI__sync_sub_and_fetch_16: 1663 case Builtin::BI__sync_and_and_fetch: 1664 case Builtin::BI__sync_and_and_fetch_1: 1665 case Builtin::BI__sync_and_and_fetch_2: 1666 case Builtin::BI__sync_and_and_fetch_4: 1667 case Builtin::BI__sync_and_and_fetch_8: 1668 case Builtin::BI__sync_and_and_fetch_16: 1669 case Builtin::BI__sync_or_and_fetch: 1670 case Builtin::BI__sync_or_and_fetch_1: 1671 case Builtin::BI__sync_or_and_fetch_2: 1672 case Builtin::BI__sync_or_and_fetch_4: 1673 case Builtin::BI__sync_or_and_fetch_8: 1674 case Builtin::BI__sync_or_and_fetch_16: 1675 case Builtin::BI__sync_xor_and_fetch: 1676 case Builtin::BI__sync_xor_and_fetch_1: 1677 case Builtin::BI__sync_xor_and_fetch_2: 1678 case Builtin::BI__sync_xor_and_fetch_4: 1679 case Builtin::BI__sync_xor_and_fetch_8: 1680 case Builtin::BI__sync_xor_and_fetch_16: 1681 case Builtin::BI__sync_nand_and_fetch: 1682 case Builtin::BI__sync_nand_and_fetch_1: 1683 case Builtin::BI__sync_nand_and_fetch_2: 1684 case Builtin::BI__sync_nand_and_fetch_4: 1685 case Builtin::BI__sync_nand_and_fetch_8: 1686 case Builtin::BI__sync_nand_and_fetch_16: 1687 case Builtin::BI__sync_val_compare_and_swap: 1688 case Builtin::BI__sync_val_compare_and_swap_1: 1689 case Builtin::BI__sync_val_compare_and_swap_2: 1690 case Builtin::BI__sync_val_compare_and_swap_4: 1691 case Builtin::BI__sync_val_compare_and_swap_8: 1692 case Builtin::BI__sync_val_compare_and_swap_16: 1693 case Builtin::BI__sync_bool_compare_and_swap: 1694 case Builtin::BI__sync_bool_compare_and_swap_1: 1695 case Builtin::BI__sync_bool_compare_and_swap_2: 1696 case Builtin::BI__sync_bool_compare_and_swap_4: 1697 case Builtin::BI__sync_bool_compare_and_swap_8: 1698 case Builtin::BI__sync_bool_compare_and_swap_16: 1699 case Builtin::BI__sync_lock_test_and_set: 1700 case Builtin::BI__sync_lock_test_and_set_1: 1701 case Builtin::BI__sync_lock_test_and_set_2: 1702 case Builtin::BI__sync_lock_test_and_set_4: 1703 case Builtin::BI__sync_lock_test_and_set_8: 1704 case Builtin::BI__sync_lock_test_and_set_16: 1705 case Builtin::BI__sync_lock_release: 1706 case Builtin::BI__sync_lock_release_1: 1707 case Builtin::BI__sync_lock_release_2: 1708 case Builtin::BI__sync_lock_release_4: 1709 case Builtin::BI__sync_lock_release_8: 1710 case Builtin::BI__sync_lock_release_16: 1711 case Builtin::BI__sync_swap: 1712 case Builtin::BI__sync_swap_1: 1713 case Builtin::BI__sync_swap_2: 1714 case Builtin::BI__sync_swap_4: 1715 case Builtin::BI__sync_swap_8: 1716 case Builtin::BI__sync_swap_16: 1717 return SemaBuiltinAtomicOverloaded(TheCallResult); 1718 case Builtin::BI__sync_synchronize: 1719 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1720 << TheCall->getCallee()->getSourceRange(); 1721 break; 1722 case Builtin::BI__builtin_nontemporal_load: 1723 case Builtin::BI__builtin_nontemporal_store: 1724 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1725 case Builtin::BI__builtin_memcpy_inline: { 1726 clang::Expr *SizeOp = TheCall->getArg(2); 1727 // We warn about copying to or from `nullptr` pointers when `size` is 1728 // greater than 0. When `size` is value dependent we cannot evaluate its 1729 // value so we bail out. 1730 if (SizeOp->isValueDependent()) 1731 break; 1732 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1733 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1734 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1735 } 1736 break; 1737 } 1738 #define BUILTIN(ID, TYPE, ATTRS) 1739 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1740 case Builtin::BI##ID: \ 1741 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1742 #include "clang/Basic/Builtins.def" 1743 case Builtin::BI__annotation: 1744 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1745 return ExprError(); 1746 break; 1747 case Builtin::BI__builtin_annotation: 1748 if (SemaBuiltinAnnotation(*this, TheCall)) 1749 return ExprError(); 1750 break; 1751 case Builtin::BI__builtin_addressof: 1752 if (SemaBuiltinAddressof(*this, TheCall)) 1753 return ExprError(); 1754 break; 1755 case Builtin::BI__builtin_is_aligned: 1756 case Builtin::BI__builtin_align_up: 1757 case Builtin::BI__builtin_align_down: 1758 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1759 return ExprError(); 1760 break; 1761 case Builtin::BI__builtin_add_overflow: 1762 case Builtin::BI__builtin_sub_overflow: 1763 case Builtin::BI__builtin_mul_overflow: 1764 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1765 return ExprError(); 1766 break; 1767 case Builtin::BI__builtin_operator_new: 1768 case Builtin::BI__builtin_operator_delete: { 1769 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1770 ExprResult Res = 1771 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1772 if (Res.isInvalid()) 1773 CorrectDelayedTyposInExpr(TheCallResult.get()); 1774 return Res; 1775 } 1776 case Builtin::BI__builtin_dump_struct: { 1777 // We first want to ensure we are called with 2 arguments 1778 if (checkArgCount(*this, TheCall, 2)) 1779 return ExprError(); 1780 // Ensure that the first argument is of type 'struct XX *' 1781 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1782 const QualType PtrArgType = PtrArg->getType(); 1783 if (!PtrArgType->isPointerType() || 1784 !PtrArgType->getPointeeType()->isRecordType()) { 1785 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1786 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1787 << "structure pointer"; 1788 return ExprError(); 1789 } 1790 1791 // Ensure that the second argument is of type 'FunctionType' 1792 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1793 const QualType FnPtrArgType = FnPtrArg->getType(); 1794 if (!FnPtrArgType->isPointerType()) { 1795 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1796 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1797 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1798 return ExprError(); 1799 } 1800 1801 const auto *FuncType = 1802 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1803 1804 if (!FuncType) { 1805 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1806 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1807 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1808 return ExprError(); 1809 } 1810 1811 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1812 if (!FT->getNumParams()) { 1813 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1814 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1815 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1816 return ExprError(); 1817 } 1818 QualType PT = FT->getParamType(0); 1819 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1820 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1821 !PT->getPointeeType().isConstQualified()) { 1822 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1823 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1824 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1825 return ExprError(); 1826 } 1827 } 1828 1829 TheCall->setType(Context.IntTy); 1830 break; 1831 } 1832 case Builtin::BI__builtin_expect_with_probability: { 1833 // We first want to ensure we are called with 3 arguments 1834 if (checkArgCount(*this, TheCall, 3)) 1835 return ExprError(); 1836 // then check probability is constant float in range [0.0, 1.0] 1837 const Expr *ProbArg = TheCall->getArg(2); 1838 SmallVector<PartialDiagnosticAt, 8> Notes; 1839 Expr::EvalResult Eval; 1840 Eval.Diag = &Notes; 1841 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1842 !Eval.Val.isFloat()) { 1843 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1844 << ProbArg->getSourceRange(); 1845 for (const PartialDiagnosticAt &PDiag : Notes) 1846 Diag(PDiag.first, PDiag.second); 1847 return ExprError(); 1848 } 1849 llvm::APFloat Probability = Eval.Val.getFloat(); 1850 bool LoseInfo = false; 1851 Probability.convert(llvm::APFloat::IEEEdouble(), 1852 llvm::RoundingMode::Dynamic, &LoseInfo); 1853 if (!(Probability >= llvm::APFloat(0.0) && 1854 Probability <= llvm::APFloat(1.0))) { 1855 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1856 << ProbArg->getSourceRange(); 1857 return ExprError(); 1858 } 1859 break; 1860 } 1861 case Builtin::BI__builtin_preserve_access_index: 1862 if (SemaBuiltinPreserveAI(*this, TheCall)) 1863 return ExprError(); 1864 break; 1865 case Builtin::BI__builtin_call_with_static_chain: 1866 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1867 return ExprError(); 1868 break; 1869 case Builtin::BI__exception_code: 1870 case Builtin::BI_exception_code: 1871 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1872 diag::err_seh___except_block)) 1873 return ExprError(); 1874 break; 1875 case Builtin::BI__exception_info: 1876 case Builtin::BI_exception_info: 1877 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1878 diag::err_seh___except_filter)) 1879 return ExprError(); 1880 break; 1881 case Builtin::BI__GetExceptionInfo: 1882 if (checkArgCount(*this, TheCall, 1)) 1883 return ExprError(); 1884 1885 if (CheckCXXThrowOperand( 1886 TheCall->getBeginLoc(), 1887 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1888 TheCall)) 1889 return ExprError(); 1890 1891 TheCall->setType(Context.VoidPtrTy); 1892 break; 1893 // OpenCL v2.0, s6.13.16 - Pipe functions 1894 case Builtin::BIread_pipe: 1895 case Builtin::BIwrite_pipe: 1896 // Since those two functions are declared with var args, we need a semantic 1897 // check for the argument. 1898 if (SemaBuiltinRWPipe(*this, TheCall)) 1899 return ExprError(); 1900 break; 1901 case Builtin::BIreserve_read_pipe: 1902 case Builtin::BIreserve_write_pipe: 1903 case Builtin::BIwork_group_reserve_read_pipe: 1904 case Builtin::BIwork_group_reserve_write_pipe: 1905 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1906 return ExprError(); 1907 break; 1908 case Builtin::BIsub_group_reserve_read_pipe: 1909 case Builtin::BIsub_group_reserve_write_pipe: 1910 if (checkOpenCLSubgroupExt(*this, TheCall) || 1911 SemaBuiltinReserveRWPipe(*this, TheCall)) 1912 return ExprError(); 1913 break; 1914 case Builtin::BIcommit_read_pipe: 1915 case Builtin::BIcommit_write_pipe: 1916 case Builtin::BIwork_group_commit_read_pipe: 1917 case Builtin::BIwork_group_commit_write_pipe: 1918 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1919 return ExprError(); 1920 break; 1921 case Builtin::BIsub_group_commit_read_pipe: 1922 case Builtin::BIsub_group_commit_write_pipe: 1923 if (checkOpenCLSubgroupExt(*this, TheCall) || 1924 SemaBuiltinCommitRWPipe(*this, TheCall)) 1925 return ExprError(); 1926 break; 1927 case Builtin::BIget_pipe_num_packets: 1928 case Builtin::BIget_pipe_max_packets: 1929 if (SemaBuiltinPipePackets(*this, TheCall)) 1930 return ExprError(); 1931 break; 1932 case Builtin::BIto_global: 1933 case Builtin::BIto_local: 1934 case Builtin::BIto_private: 1935 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1936 return ExprError(); 1937 break; 1938 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1939 case Builtin::BIenqueue_kernel: 1940 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1941 return ExprError(); 1942 break; 1943 case Builtin::BIget_kernel_work_group_size: 1944 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1945 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1946 return ExprError(); 1947 break; 1948 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1949 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1950 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1951 return ExprError(); 1952 break; 1953 case Builtin::BI__builtin_os_log_format: 1954 Cleanup.setExprNeedsCleanups(true); 1955 LLVM_FALLTHROUGH; 1956 case Builtin::BI__builtin_os_log_format_buffer_size: 1957 if (SemaBuiltinOSLogFormat(TheCall)) 1958 return ExprError(); 1959 break; 1960 case Builtin::BI__builtin_frame_address: 1961 case Builtin::BI__builtin_return_address: { 1962 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1963 return ExprError(); 1964 1965 // -Wframe-address warning if non-zero passed to builtin 1966 // return/frame address. 1967 Expr::EvalResult Result; 1968 if (!TheCall->getArg(0)->isValueDependent() && 1969 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1970 Result.Val.getInt() != 0) 1971 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1972 << ((BuiltinID == Builtin::BI__builtin_return_address) 1973 ? "__builtin_return_address" 1974 : "__builtin_frame_address") 1975 << TheCall->getSourceRange(); 1976 break; 1977 } 1978 1979 case Builtin::BI__builtin_matrix_transpose: 1980 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1981 1982 case Builtin::BI__builtin_matrix_column_major_load: 1983 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1984 1985 case Builtin::BI__builtin_matrix_column_major_store: 1986 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1987 1988 case Builtin::BI__builtin_get_device_side_mangled_name: { 1989 auto Check = [](CallExpr *TheCall) { 1990 if (TheCall->getNumArgs() != 1) 1991 return false; 1992 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 1993 if (!DRE) 1994 return false; 1995 auto *D = DRE->getDecl(); 1996 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 1997 return false; 1998 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 1999 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2000 }; 2001 if (!Check(TheCall)) { 2002 Diag(TheCall->getBeginLoc(), 2003 diag::err_hip_invalid_args_builtin_mangled_name); 2004 return ExprError(); 2005 } 2006 } 2007 } 2008 2009 // Since the target specific builtins for each arch overlap, only check those 2010 // of the arch we are compiling for. 2011 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2012 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2013 assert(Context.getAuxTargetInfo() && 2014 "Aux Target Builtin, but not an aux target?"); 2015 2016 if (CheckTSBuiltinFunctionCall( 2017 *Context.getAuxTargetInfo(), 2018 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2019 return ExprError(); 2020 } else { 2021 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2022 TheCall)) 2023 return ExprError(); 2024 } 2025 } 2026 2027 return TheCallResult; 2028 } 2029 2030 // Get the valid immediate range for the specified NEON type code. 2031 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2032 NeonTypeFlags Type(t); 2033 int IsQuad = ForceQuad ? true : Type.isQuad(); 2034 switch (Type.getEltType()) { 2035 case NeonTypeFlags::Int8: 2036 case NeonTypeFlags::Poly8: 2037 return shift ? 7 : (8 << IsQuad) - 1; 2038 case NeonTypeFlags::Int16: 2039 case NeonTypeFlags::Poly16: 2040 return shift ? 15 : (4 << IsQuad) - 1; 2041 case NeonTypeFlags::Int32: 2042 return shift ? 31 : (2 << IsQuad) - 1; 2043 case NeonTypeFlags::Int64: 2044 case NeonTypeFlags::Poly64: 2045 return shift ? 63 : (1 << IsQuad) - 1; 2046 case NeonTypeFlags::Poly128: 2047 return shift ? 127 : (1 << IsQuad) - 1; 2048 case NeonTypeFlags::Float16: 2049 assert(!shift && "cannot shift float types!"); 2050 return (4 << IsQuad) - 1; 2051 case NeonTypeFlags::Float32: 2052 assert(!shift && "cannot shift float types!"); 2053 return (2 << IsQuad) - 1; 2054 case NeonTypeFlags::Float64: 2055 assert(!shift && "cannot shift float types!"); 2056 return (1 << IsQuad) - 1; 2057 case NeonTypeFlags::BFloat16: 2058 assert(!shift && "cannot shift float types!"); 2059 return (4 << IsQuad) - 1; 2060 } 2061 llvm_unreachable("Invalid NeonTypeFlag!"); 2062 } 2063 2064 /// getNeonEltType - Return the QualType corresponding to the elements of 2065 /// the vector type specified by the NeonTypeFlags. This is used to check 2066 /// the pointer arguments for Neon load/store intrinsics. 2067 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2068 bool IsPolyUnsigned, bool IsInt64Long) { 2069 switch (Flags.getEltType()) { 2070 case NeonTypeFlags::Int8: 2071 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2072 case NeonTypeFlags::Int16: 2073 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2074 case NeonTypeFlags::Int32: 2075 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2076 case NeonTypeFlags::Int64: 2077 if (IsInt64Long) 2078 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2079 else 2080 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2081 : Context.LongLongTy; 2082 case NeonTypeFlags::Poly8: 2083 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2084 case NeonTypeFlags::Poly16: 2085 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2086 case NeonTypeFlags::Poly64: 2087 if (IsInt64Long) 2088 return Context.UnsignedLongTy; 2089 else 2090 return Context.UnsignedLongLongTy; 2091 case NeonTypeFlags::Poly128: 2092 break; 2093 case NeonTypeFlags::Float16: 2094 return Context.HalfTy; 2095 case NeonTypeFlags::Float32: 2096 return Context.FloatTy; 2097 case NeonTypeFlags::Float64: 2098 return Context.DoubleTy; 2099 case NeonTypeFlags::BFloat16: 2100 return Context.BFloat16Ty; 2101 } 2102 llvm_unreachable("Invalid NeonTypeFlag!"); 2103 } 2104 2105 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2106 // Range check SVE intrinsics that take immediate values. 2107 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2108 2109 switch (BuiltinID) { 2110 default: 2111 return false; 2112 #define GET_SVE_IMMEDIATE_CHECK 2113 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2114 #undef GET_SVE_IMMEDIATE_CHECK 2115 } 2116 2117 // Perform all the immediate checks for this builtin call. 2118 bool HasError = false; 2119 for (auto &I : ImmChecks) { 2120 int ArgNum, CheckTy, ElementSizeInBits; 2121 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2122 2123 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2124 2125 // Function that checks whether the operand (ArgNum) is an immediate 2126 // that is one of the predefined values. 2127 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2128 int ErrDiag) -> bool { 2129 // We can't check the value of a dependent argument. 2130 Expr *Arg = TheCall->getArg(ArgNum); 2131 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2132 return false; 2133 2134 // Check constant-ness first. 2135 llvm::APSInt Imm; 2136 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2137 return true; 2138 2139 if (!CheckImm(Imm.getSExtValue())) 2140 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2141 return false; 2142 }; 2143 2144 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2145 case SVETypeFlags::ImmCheck0_31: 2146 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2147 HasError = true; 2148 break; 2149 case SVETypeFlags::ImmCheck0_13: 2150 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2151 HasError = true; 2152 break; 2153 case SVETypeFlags::ImmCheck1_16: 2154 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2155 HasError = true; 2156 break; 2157 case SVETypeFlags::ImmCheck0_7: 2158 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2159 HasError = true; 2160 break; 2161 case SVETypeFlags::ImmCheckExtract: 2162 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2163 (2048 / ElementSizeInBits) - 1)) 2164 HasError = true; 2165 break; 2166 case SVETypeFlags::ImmCheckShiftRight: 2167 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2168 HasError = true; 2169 break; 2170 case SVETypeFlags::ImmCheckShiftRightNarrow: 2171 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2172 ElementSizeInBits / 2)) 2173 HasError = true; 2174 break; 2175 case SVETypeFlags::ImmCheckShiftLeft: 2176 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2177 ElementSizeInBits - 1)) 2178 HasError = true; 2179 break; 2180 case SVETypeFlags::ImmCheckLaneIndex: 2181 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2182 (128 / (1 * ElementSizeInBits)) - 1)) 2183 HasError = true; 2184 break; 2185 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2186 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2187 (128 / (2 * ElementSizeInBits)) - 1)) 2188 HasError = true; 2189 break; 2190 case SVETypeFlags::ImmCheckLaneIndexDot: 2191 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2192 (128 / (4 * ElementSizeInBits)) - 1)) 2193 HasError = true; 2194 break; 2195 case SVETypeFlags::ImmCheckComplexRot90_270: 2196 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2197 diag::err_rotation_argument_to_cadd)) 2198 HasError = true; 2199 break; 2200 case SVETypeFlags::ImmCheckComplexRotAll90: 2201 if (CheckImmediateInSet( 2202 [](int64_t V) { 2203 return V == 0 || V == 90 || V == 180 || V == 270; 2204 }, 2205 diag::err_rotation_argument_to_cmla)) 2206 HasError = true; 2207 break; 2208 case SVETypeFlags::ImmCheck0_1: 2209 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2210 HasError = true; 2211 break; 2212 case SVETypeFlags::ImmCheck0_2: 2213 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2214 HasError = true; 2215 break; 2216 case SVETypeFlags::ImmCheck0_3: 2217 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2218 HasError = true; 2219 break; 2220 } 2221 } 2222 2223 return HasError; 2224 } 2225 2226 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2227 unsigned BuiltinID, CallExpr *TheCall) { 2228 llvm::APSInt Result; 2229 uint64_t mask = 0; 2230 unsigned TV = 0; 2231 int PtrArgNum = -1; 2232 bool HasConstPtr = false; 2233 switch (BuiltinID) { 2234 #define GET_NEON_OVERLOAD_CHECK 2235 #include "clang/Basic/arm_neon.inc" 2236 #include "clang/Basic/arm_fp16.inc" 2237 #undef GET_NEON_OVERLOAD_CHECK 2238 } 2239 2240 // For NEON intrinsics which are overloaded on vector element type, validate 2241 // the immediate which specifies which variant to emit. 2242 unsigned ImmArg = TheCall->getNumArgs()-1; 2243 if (mask) { 2244 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2245 return true; 2246 2247 TV = Result.getLimitedValue(64); 2248 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2249 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2250 << TheCall->getArg(ImmArg)->getSourceRange(); 2251 } 2252 2253 if (PtrArgNum >= 0) { 2254 // Check that pointer arguments have the specified type. 2255 Expr *Arg = TheCall->getArg(PtrArgNum); 2256 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2257 Arg = ICE->getSubExpr(); 2258 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2259 QualType RHSTy = RHS.get()->getType(); 2260 2261 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2262 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2263 Arch == llvm::Triple::aarch64_32 || 2264 Arch == llvm::Triple::aarch64_be; 2265 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2266 QualType EltTy = 2267 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2268 if (HasConstPtr) 2269 EltTy = EltTy.withConst(); 2270 QualType LHSTy = Context.getPointerType(EltTy); 2271 AssignConvertType ConvTy; 2272 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2273 if (RHS.isInvalid()) 2274 return true; 2275 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2276 RHS.get(), AA_Assigning)) 2277 return true; 2278 } 2279 2280 // For NEON intrinsics which take an immediate value as part of the 2281 // instruction, range check them here. 2282 unsigned i = 0, l = 0, u = 0; 2283 switch (BuiltinID) { 2284 default: 2285 return false; 2286 #define GET_NEON_IMMEDIATE_CHECK 2287 #include "clang/Basic/arm_neon.inc" 2288 #include "clang/Basic/arm_fp16.inc" 2289 #undef GET_NEON_IMMEDIATE_CHECK 2290 } 2291 2292 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2293 } 2294 2295 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2296 switch (BuiltinID) { 2297 default: 2298 return false; 2299 #include "clang/Basic/arm_mve_builtin_sema.inc" 2300 } 2301 } 2302 2303 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2304 CallExpr *TheCall) { 2305 bool Err = false; 2306 switch (BuiltinID) { 2307 default: 2308 return false; 2309 #include "clang/Basic/arm_cde_builtin_sema.inc" 2310 } 2311 2312 if (Err) 2313 return true; 2314 2315 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2316 } 2317 2318 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2319 const Expr *CoprocArg, bool WantCDE) { 2320 if (isConstantEvaluated()) 2321 return false; 2322 2323 // We can't check the value of a dependent argument. 2324 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2325 return false; 2326 2327 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2328 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2329 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2330 2331 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2332 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2333 2334 if (IsCDECoproc != WantCDE) 2335 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2336 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2337 2338 return false; 2339 } 2340 2341 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2342 unsigned MaxWidth) { 2343 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2344 BuiltinID == ARM::BI__builtin_arm_ldaex || 2345 BuiltinID == ARM::BI__builtin_arm_strex || 2346 BuiltinID == ARM::BI__builtin_arm_stlex || 2347 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2348 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2349 BuiltinID == AArch64::BI__builtin_arm_strex || 2350 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2351 "unexpected ARM builtin"); 2352 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2353 BuiltinID == ARM::BI__builtin_arm_ldaex || 2354 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2355 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2356 2357 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2358 2359 // Ensure that we have the proper number of arguments. 2360 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2361 return true; 2362 2363 // Inspect the pointer argument of the atomic builtin. This should always be 2364 // a pointer type, whose element is an integral scalar or pointer type. 2365 // Because it is a pointer type, we don't have to worry about any implicit 2366 // casts here. 2367 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2368 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2369 if (PointerArgRes.isInvalid()) 2370 return true; 2371 PointerArg = PointerArgRes.get(); 2372 2373 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2374 if (!pointerType) { 2375 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2376 << PointerArg->getType() << PointerArg->getSourceRange(); 2377 return true; 2378 } 2379 2380 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2381 // task is to insert the appropriate casts into the AST. First work out just 2382 // what the appropriate type is. 2383 QualType ValType = pointerType->getPointeeType(); 2384 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2385 if (IsLdrex) 2386 AddrType.addConst(); 2387 2388 // Issue a warning if the cast is dodgy. 2389 CastKind CastNeeded = CK_NoOp; 2390 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2391 CastNeeded = CK_BitCast; 2392 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2393 << PointerArg->getType() << Context.getPointerType(AddrType) 2394 << AA_Passing << PointerArg->getSourceRange(); 2395 } 2396 2397 // Finally, do the cast and replace the argument with the corrected version. 2398 AddrType = Context.getPointerType(AddrType); 2399 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2400 if (PointerArgRes.isInvalid()) 2401 return true; 2402 PointerArg = PointerArgRes.get(); 2403 2404 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2405 2406 // In general, we allow ints, floats and pointers to be loaded and stored. 2407 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2408 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2409 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2410 << PointerArg->getType() << PointerArg->getSourceRange(); 2411 return true; 2412 } 2413 2414 // But ARM doesn't have instructions to deal with 128-bit versions. 2415 if (Context.getTypeSize(ValType) > MaxWidth) { 2416 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2417 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2418 << PointerArg->getType() << PointerArg->getSourceRange(); 2419 return true; 2420 } 2421 2422 switch (ValType.getObjCLifetime()) { 2423 case Qualifiers::OCL_None: 2424 case Qualifiers::OCL_ExplicitNone: 2425 // okay 2426 break; 2427 2428 case Qualifiers::OCL_Weak: 2429 case Qualifiers::OCL_Strong: 2430 case Qualifiers::OCL_Autoreleasing: 2431 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2432 << ValType << PointerArg->getSourceRange(); 2433 return true; 2434 } 2435 2436 if (IsLdrex) { 2437 TheCall->setType(ValType); 2438 return false; 2439 } 2440 2441 // Initialize the argument to be stored. 2442 ExprResult ValArg = TheCall->getArg(0); 2443 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2444 Context, ValType, /*consume*/ false); 2445 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2446 if (ValArg.isInvalid()) 2447 return true; 2448 TheCall->setArg(0, ValArg.get()); 2449 2450 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2451 // but the custom checker bypasses all default analysis. 2452 TheCall->setType(Context.IntTy); 2453 return false; 2454 } 2455 2456 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2457 CallExpr *TheCall) { 2458 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2459 BuiltinID == ARM::BI__builtin_arm_ldaex || 2460 BuiltinID == ARM::BI__builtin_arm_strex || 2461 BuiltinID == ARM::BI__builtin_arm_stlex) { 2462 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2463 } 2464 2465 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2466 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2467 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2468 } 2469 2470 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2471 BuiltinID == ARM::BI__builtin_arm_wsr64) 2472 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2473 2474 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2475 BuiltinID == ARM::BI__builtin_arm_rsrp || 2476 BuiltinID == ARM::BI__builtin_arm_wsr || 2477 BuiltinID == ARM::BI__builtin_arm_wsrp) 2478 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2479 2480 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2481 return true; 2482 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2483 return true; 2484 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2485 return true; 2486 2487 // For intrinsics which take an immediate value as part of the instruction, 2488 // range check them here. 2489 // FIXME: VFP Intrinsics should error if VFP not present. 2490 switch (BuiltinID) { 2491 default: return false; 2492 case ARM::BI__builtin_arm_ssat: 2493 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2494 case ARM::BI__builtin_arm_usat: 2495 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2496 case ARM::BI__builtin_arm_ssat16: 2497 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2498 case ARM::BI__builtin_arm_usat16: 2499 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2500 case ARM::BI__builtin_arm_vcvtr_f: 2501 case ARM::BI__builtin_arm_vcvtr_d: 2502 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2503 case ARM::BI__builtin_arm_dmb: 2504 case ARM::BI__builtin_arm_dsb: 2505 case ARM::BI__builtin_arm_isb: 2506 case ARM::BI__builtin_arm_dbg: 2507 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2508 case ARM::BI__builtin_arm_cdp: 2509 case ARM::BI__builtin_arm_cdp2: 2510 case ARM::BI__builtin_arm_mcr: 2511 case ARM::BI__builtin_arm_mcr2: 2512 case ARM::BI__builtin_arm_mrc: 2513 case ARM::BI__builtin_arm_mrc2: 2514 case ARM::BI__builtin_arm_mcrr: 2515 case ARM::BI__builtin_arm_mcrr2: 2516 case ARM::BI__builtin_arm_mrrc: 2517 case ARM::BI__builtin_arm_mrrc2: 2518 case ARM::BI__builtin_arm_ldc: 2519 case ARM::BI__builtin_arm_ldcl: 2520 case ARM::BI__builtin_arm_ldc2: 2521 case ARM::BI__builtin_arm_ldc2l: 2522 case ARM::BI__builtin_arm_stc: 2523 case ARM::BI__builtin_arm_stcl: 2524 case ARM::BI__builtin_arm_stc2: 2525 case ARM::BI__builtin_arm_stc2l: 2526 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2527 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2528 /*WantCDE*/ false); 2529 } 2530 } 2531 2532 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2533 unsigned BuiltinID, 2534 CallExpr *TheCall) { 2535 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2536 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2537 BuiltinID == AArch64::BI__builtin_arm_strex || 2538 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2539 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2540 } 2541 2542 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2543 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2544 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2545 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2546 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2547 } 2548 2549 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2550 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2551 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2552 2553 // Memory Tagging Extensions (MTE) Intrinsics 2554 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2555 BuiltinID == AArch64::BI__builtin_arm_addg || 2556 BuiltinID == AArch64::BI__builtin_arm_gmi || 2557 BuiltinID == AArch64::BI__builtin_arm_ldg || 2558 BuiltinID == AArch64::BI__builtin_arm_stg || 2559 BuiltinID == AArch64::BI__builtin_arm_subp) { 2560 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2561 } 2562 2563 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2564 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2565 BuiltinID == AArch64::BI__builtin_arm_wsr || 2566 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2567 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2568 2569 // Only check the valid encoding range. Any constant in this range would be 2570 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2571 // an exception for incorrect registers. This matches MSVC behavior. 2572 if (BuiltinID == AArch64::BI_ReadStatusReg || 2573 BuiltinID == AArch64::BI_WriteStatusReg) 2574 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2575 2576 if (BuiltinID == AArch64::BI__getReg) 2577 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2578 2579 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2580 return true; 2581 2582 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2583 return true; 2584 2585 // For intrinsics which take an immediate value as part of the instruction, 2586 // range check them here. 2587 unsigned i = 0, l = 0, u = 0; 2588 switch (BuiltinID) { 2589 default: return false; 2590 case AArch64::BI__builtin_arm_dmb: 2591 case AArch64::BI__builtin_arm_dsb: 2592 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2593 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2594 } 2595 2596 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2597 } 2598 2599 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2600 if (Arg->getType()->getAsPlaceholderType()) 2601 return false; 2602 2603 // The first argument needs to be a record field access. 2604 // If it is an array element access, we delay decision 2605 // to BPF backend to check whether the access is a 2606 // field access or not. 2607 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2608 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2609 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2610 } 2611 2612 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2613 QualType VectorTy, QualType EltTy) { 2614 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2615 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2616 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2617 << Call->getSourceRange() << VectorEltTy << EltTy; 2618 return false; 2619 } 2620 return true; 2621 } 2622 2623 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2624 QualType ArgType = Arg->getType(); 2625 if (ArgType->getAsPlaceholderType()) 2626 return false; 2627 2628 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2629 // format: 2630 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2631 // 2. <type> var; 2632 // __builtin_preserve_type_info(var, flag); 2633 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2634 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2635 return false; 2636 2637 // Typedef type. 2638 if (ArgType->getAs<TypedefType>()) 2639 return true; 2640 2641 // Record type or Enum type. 2642 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2643 if (const auto *RT = Ty->getAs<RecordType>()) { 2644 if (!RT->getDecl()->getDeclName().isEmpty()) 2645 return true; 2646 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2647 if (!ET->getDecl()->getDeclName().isEmpty()) 2648 return true; 2649 } 2650 2651 return false; 2652 } 2653 2654 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2655 QualType ArgType = Arg->getType(); 2656 if (ArgType->getAsPlaceholderType()) 2657 return false; 2658 2659 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2660 // format: 2661 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2662 // flag); 2663 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2664 if (!UO) 2665 return false; 2666 2667 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2668 if (!CE) 2669 return false; 2670 if (CE->getCastKind() != CK_IntegralToPointer && 2671 CE->getCastKind() != CK_NullToPointer) 2672 return false; 2673 2674 // The integer must be from an EnumConstantDecl. 2675 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2676 if (!DR) 2677 return false; 2678 2679 const EnumConstantDecl *Enumerator = 2680 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2681 if (!Enumerator) 2682 return false; 2683 2684 // The type must be EnumType. 2685 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2686 const auto *ET = Ty->getAs<EnumType>(); 2687 if (!ET) 2688 return false; 2689 2690 // The enum value must be supported. 2691 for (auto *EDI : ET->getDecl()->enumerators()) { 2692 if (EDI == Enumerator) 2693 return true; 2694 } 2695 2696 return false; 2697 } 2698 2699 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2700 CallExpr *TheCall) { 2701 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2702 BuiltinID == BPF::BI__builtin_btf_type_id || 2703 BuiltinID == BPF::BI__builtin_preserve_type_info || 2704 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2705 "unexpected BPF builtin"); 2706 2707 if (checkArgCount(*this, TheCall, 2)) 2708 return true; 2709 2710 // The second argument needs to be a constant int 2711 Expr *Arg = TheCall->getArg(1); 2712 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2713 diag::kind kind; 2714 if (!Value) { 2715 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2716 kind = diag::err_preserve_field_info_not_const; 2717 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2718 kind = diag::err_btf_type_id_not_const; 2719 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2720 kind = diag::err_preserve_type_info_not_const; 2721 else 2722 kind = diag::err_preserve_enum_value_not_const; 2723 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2724 return true; 2725 } 2726 2727 // The first argument 2728 Arg = TheCall->getArg(0); 2729 bool InvalidArg = false; 2730 bool ReturnUnsignedInt = true; 2731 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2732 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2733 InvalidArg = true; 2734 kind = diag::err_preserve_field_info_not_field; 2735 } 2736 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2737 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2738 InvalidArg = true; 2739 kind = diag::err_preserve_type_info_invalid; 2740 } 2741 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2742 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2743 InvalidArg = true; 2744 kind = diag::err_preserve_enum_value_invalid; 2745 } 2746 ReturnUnsignedInt = false; 2747 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2748 ReturnUnsignedInt = false; 2749 } 2750 2751 if (InvalidArg) { 2752 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2753 return true; 2754 } 2755 2756 if (ReturnUnsignedInt) 2757 TheCall->setType(Context.UnsignedIntTy); 2758 else 2759 TheCall->setType(Context.UnsignedLongTy); 2760 return false; 2761 } 2762 2763 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2764 struct ArgInfo { 2765 uint8_t OpNum; 2766 bool IsSigned; 2767 uint8_t BitWidth; 2768 uint8_t Align; 2769 }; 2770 struct BuiltinInfo { 2771 unsigned BuiltinID; 2772 ArgInfo Infos[2]; 2773 }; 2774 2775 static BuiltinInfo Infos[] = { 2776 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2777 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2778 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2779 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2780 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2781 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2782 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2783 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2784 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2785 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2786 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2787 2788 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2799 2800 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2847 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2852 {{ 1, false, 6, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2855 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2860 {{ 1, false, 5, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2862 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2864 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2866 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2867 { 2, false, 5, 0 }} }, 2868 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2869 { 2, false, 6, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2871 { 3, false, 5, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2873 { 3, false, 6, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2885 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2886 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2888 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2889 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2890 {{ 2, false, 4, 0 }, 2891 { 3, false, 5, 0 }} }, 2892 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2893 {{ 2, false, 4, 0 }, 2894 { 3, false, 5, 0 }} }, 2895 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2896 {{ 2, false, 4, 0 }, 2897 { 3, false, 5, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2899 {{ 2, false, 4, 0 }, 2900 { 3, false, 5, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2912 { 2, false, 5, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2914 { 2, false, 6, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2924 {{ 1, false, 4, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2927 {{ 1, false, 4, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2940 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2941 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2943 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2944 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2945 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2946 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2947 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2948 {{ 3, false, 1, 0 }} }, 2949 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2950 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2951 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2952 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2953 {{ 3, false, 1, 0 }} }, 2954 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2955 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2956 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2957 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2958 {{ 3, false, 1, 0 }} }, 2959 }; 2960 2961 // Use a dynamically initialized static to sort the table exactly once on 2962 // first run. 2963 static const bool SortOnce = 2964 (llvm::sort(Infos, 2965 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2966 return LHS.BuiltinID < RHS.BuiltinID; 2967 }), 2968 true); 2969 (void)SortOnce; 2970 2971 const BuiltinInfo *F = llvm::partition_point( 2972 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2973 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2974 return false; 2975 2976 bool Error = false; 2977 2978 for (const ArgInfo &A : F->Infos) { 2979 // Ignore empty ArgInfo elements. 2980 if (A.BitWidth == 0) 2981 continue; 2982 2983 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2984 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2985 if (!A.Align) { 2986 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2987 } else { 2988 unsigned M = 1 << A.Align; 2989 Min *= M; 2990 Max *= M; 2991 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2992 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2993 } 2994 } 2995 return Error; 2996 } 2997 2998 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2999 CallExpr *TheCall) { 3000 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3001 } 3002 3003 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 3004 unsigned BuiltinID, CallExpr *TheCall) { 3005 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 3006 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3007 } 3008 3009 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 3010 CallExpr *TheCall) { 3011 3012 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3013 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3014 if (!TI.hasFeature("dsp")) 3015 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3016 } 3017 3018 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3019 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3020 if (!TI.hasFeature("dspr2")) 3021 return Diag(TheCall->getBeginLoc(), 3022 diag::err_mips_builtin_requires_dspr2); 3023 } 3024 3025 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3026 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3027 if (!TI.hasFeature("msa")) 3028 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3029 } 3030 3031 return false; 3032 } 3033 3034 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3035 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3036 // ordering for DSP is unspecified. MSA is ordered by the data format used 3037 // by the underlying instruction i.e., df/m, df/n and then by size. 3038 // 3039 // FIXME: The size tests here should instead be tablegen'd along with the 3040 // definitions from include/clang/Basic/BuiltinsMips.def. 3041 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3042 // be too. 3043 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3044 unsigned i = 0, l = 0, u = 0, m = 0; 3045 switch (BuiltinID) { 3046 default: return false; 3047 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3048 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3049 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3050 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3051 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3052 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3053 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3054 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3055 // df/m field. 3056 // These intrinsics take an unsigned 3 bit immediate. 3057 case Mips::BI__builtin_msa_bclri_b: 3058 case Mips::BI__builtin_msa_bnegi_b: 3059 case Mips::BI__builtin_msa_bseti_b: 3060 case Mips::BI__builtin_msa_sat_s_b: 3061 case Mips::BI__builtin_msa_sat_u_b: 3062 case Mips::BI__builtin_msa_slli_b: 3063 case Mips::BI__builtin_msa_srai_b: 3064 case Mips::BI__builtin_msa_srari_b: 3065 case Mips::BI__builtin_msa_srli_b: 3066 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3067 case Mips::BI__builtin_msa_binsli_b: 3068 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3069 // These intrinsics take an unsigned 4 bit immediate. 3070 case Mips::BI__builtin_msa_bclri_h: 3071 case Mips::BI__builtin_msa_bnegi_h: 3072 case Mips::BI__builtin_msa_bseti_h: 3073 case Mips::BI__builtin_msa_sat_s_h: 3074 case Mips::BI__builtin_msa_sat_u_h: 3075 case Mips::BI__builtin_msa_slli_h: 3076 case Mips::BI__builtin_msa_srai_h: 3077 case Mips::BI__builtin_msa_srari_h: 3078 case Mips::BI__builtin_msa_srli_h: 3079 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3080 case Mips::BI__builtin_msa_binsli_h: 3081 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3082 // These intrinsics take an unsigned 5 bit immediate. 3083 // The first block of intrinsics actually have an unsigned 5 bit field, 3084 // not a df/n field. 3085 case Mips::BI__builtin_msa_cfcmsa: 3086 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3087 case Mips::BI__builtin_msa_clei_u_b: 3088 case Mips::BI__builtin_msa_clei_u_h: 3089 case Mips::BI__builtin_msa_clei_u_w: 3090 case Mips::BI__builtin_msa_clei_u_d: 3091 case Mips::BI__builtin_msa_clti_u_b: 3092 case Mips::BI__builtin_msa_clti_u_h: 3093 case Mips::BI__builtin_msa_clti_u_w: 3094 case Mips::BI__builtin_msa_clti_u_d: 3095 case Mips::BI__builtin_msa_maxi_u_b: 3096 case Mips::BI__builtin_msa_maxi_u_h: 3097 case Mips::BI__builtin_msa_maxi_u_w: 3098 case Mips::BI__builtin_msa_maxi_u_d: 3099 case Mips::BI__builtin_msa_mini_u_b: 3100 case Mips::BI__builtin_msa_mini_u_h: 3101 case Mips::BI__builtin_msa_mini_u_w: 3102 case Mips::BI__builtin_msa_mini_u_d: 3103 case Mips::BI__builtin_msa_addvi_b: 3104 case Mips::BI__builtin_msa_addvi_h: 3105 case Mips::BI__builtin_msa_addvi_w: 3106 case Mips::BI__builtin_msa_addvi_d: 3107 case Mips::BI__builtin_msa_bclri_w: 3108 case Mips::BI__builtin_msa_bnegi_w: 3109 case Mips::BI__builtin_msa_bseti_w: 3110 case Mips::BI__builtin_msa_sat_s_w: 3111 case Mips::BI__builtin_msa_sat_u_w: 3112 case Mips::BI__builtin_msa_slli_w: 3113 case Mips::BI__builtin_msa_srai_w: 3114 case Mips::BI__builtin_msa_srari_w: 3115 case Mips::BI__builtin_msa_srli_w: 3116 case Mips::BI__builtin_msa_srlri_w: 3117 case Mips::BI__builtin_msa_subvi_b: 3118 case Mips::BI__builtin_msa_subvi_h: 3119 case Mips::BI__builtin_msa_subvi_w: 3120 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3121 case Mips::BI__builtin_msa_binsli_w: 3122 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3123 // These intrinsics take an unsigned 6 bit immediate. 3124 case Mips::BI__builtin_msa_bclri_d: 3125 case Mips::BI__builtin_msa_bnegi_d: 3126 case Mips::BI__builtin_msa_bseti_d: 3127 case Mips::BI__builtin_msa_sat_s_d: 3128 case Mips::BI__builtin_msa_sat_u_d: 3129 case Mips::BI__builtin_msa_slli_d: 3130 case Mips::BI__builtin_msa_srai_d: 3131 case Mips::BI__builtin_msa_srari_d: 3132 case Mips::BI__builtin_msa_srli_d: 3133 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3134 case Mips::BI__builtin_msa_binsli_d: 3135 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3136 // These intrinsics take a signed 5 bit immediate. 3137 case Mips::BI__builtin_msa_ceqi_b: 3138 case Mips::BI__builtin_msa_ceqi_h: 3139 case Mips::BI__builtin_msa_ceqi_w: 3140 case Mips::BI__builtin_msa_ceqi_d: 3141 case Mips::BI__builtin_msa_clti_s_b: 3142 case Mips::BI__builtin_msa_clti_s_h: 3143 case Mips::BI__builtin_msa_clti_s_w: 3144 case Mips::BI__builtin_msa_clti_s_d: 3145 case Mips::BI__builtin_msa_clei_s_b: 3146 case Mips::BI__builtin_msa_clei_s_h: 3147 case Mips::BI__builtin_msa_clei_s_w: 3148 case Mips::BI__builtin_msa_clei_s_d: 3149 case Mips::BI__builtin_msa_maxi_s_b: 3150 case Mips::BI__builtin_msa_maxi_s_h: 3151 case Mips::BI__builtin_msa_maxi_s_w: 3152 case Mips::BI__builtin_msa_maxi_s_d: 3153 case Mips::BI__builtin_msa_mini_s_b: 3154 case Mips::BI__builtin_msa_mini_s_h: 3155 case Mips::BI__builtin_msa_mini_s_w: 3156 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3157 // These intrinsics take an unsigned 8 bit immediate. 3158 case Mips::BI__builtin_msa_andi_b: 3159 case Mips::BI__builtin_msa_nori_b: 3160 case Mips::BI__builtin_msa_ori_b: 3161 case Mips::BI__builtin_msa_shf_b: 3162 case Mips::BI__builtin_msa_shf_h: 3163 case Mips::BI__builtin_msa_shf_w: 3164 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3165 case Mips::BI__builtin_msa_bseli_b: 3166 case Mips::BI__builtin_msa_bmnzi_b: 3167 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3168 // df/n format 3169 // These intrinsics take an unsigned 4 bit immediate. 3170 case Mips::BI__builtin_msa_copy_s_b: 3171 case Mips::BI__builtin_msa_copy_u_b: 3172 case Mips::BI__builtin_msa_insve_b: 3173 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3174 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3175 // These intrinsics take an unsigned 3 bit immediate. 3176 case Mips::BI__builtin_msa_copy_s_h: 3177 case Mips::BI__builtin_msa_copy_u_h: 3178 case Mips::BI__builtin_msa_insve_h: 3179 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3180 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3181 // These intrinsics take an unsigned 2 bit immediate. 3182 case Mips::BI__builtin_msa_copy_s_w: 3183 case Mips::BI__builtin_msa_copy_u_w: 3184 case Mips::BI__builtin_msa_insve_w: 3185 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3186 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3187 // These intrinsics take an unsigned 1 bit immediate. 3188 case Mips::BI__builtin_msa_copy_s_d: 3189 case Mips::BI__builtin_msa_copy_u_d: 3190 case Mips::BI__builtin_msa_insve_d: 3191 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3192 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3193 // Memory offsets and immediate loads. 3194 // These intrinsics take a signed 10 bit immediate. 3195 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3196 case Mips::BI__builtin_msa_ldi_h: 3197 case Mips::BI__builtin_msa_ldi_w: 3198 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3199 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3200 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3201 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3202 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3203 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3204 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3205 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3206 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3207 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3208 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3209 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3210 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3211 } 3212 3213 if (!m) 3214 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3215 3216 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3217 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3218 } 3219 3220 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3221 /// advancing the pointer over the consumed characters. The decoded type is 3222 /// returned. If the decoded type represents a constant integer with a 3223 /// constraint on its value then Mask is set to that value. The type descriptors 3224 /// used in Str are specific to PPC MMA builtins and are documented in the file 3225 /// defining the PPC builtins. 3226 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3227 unsigned &Mask) { 3228 bool RequireICE = false; 3229 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3230 switch (*Str++) { 3231 case 'V': 3232 return Context.getVectorType(Context.UnsignedCharTy, 16, 3233 VectorType::VectorKind::AltiVecVector); 3234 case 'i': { 3235 char *End; 3236 unsigned size = strtoul(Str, &End, 10); 3237 assert(End != Str && "Missing constant parameter constraint"); 3238 Str = End; 3239 Mask = size; 3240 return Context.IntTy; 3241 } 3242 case 'W': { 3243 char *End; 3244 unsigned size = strtoul(Str, &End, 10); 3245 assert(End != Str && "Missing PowerPC MMA type size"); 3246 Str = End; 3247 QualType Type; 3248 switch (size) { 3249 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3250 case size: Type = Context.Id##Ty; break; 3251 #include "clang/Basic/PPCTypes.def" 3252 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3253 } 3254 bool CheckVectorArgs = false; 3255 while (!CheckVectorArgs) { 3256 switch (*Str++) { 3257 case '*': 3258 Type = Context.getPointerType(Type); 3259 break; 3260 case 'C': 3261 Type = Type.withConst(); 3262 break; 3263 default: 3264 CheckVectorArgs = true; 3265 --Str; 3266 break; 3267 } 3268 } 3269 return Type; 3270 } 3271 default: 3272 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3273 } 3274 } 3275 3276 static bool isPPC_64Builtin(unsigned BuiltinID) { 3277 // These builtins only work on PPC 64bit targets. 3278 switch (BuiltinID) { 3279 case PPC::BI__builtin_divde: 3280 case PPC::BI__builtin_divdeu: 3281 case PPC::BI__builtin_bpermd: 3282 case PPC::BI__builtin_ppc_ldarx: 3283 case PPC::BI__builtin_ppc_stdcx: 3284 case PPC::BI__builtin_ppc_tdw: 3285 case PPC::BI__builtin_ppc_trapd: 3286 case PPC::BI__builtin_ppc_cmpeqb: 3287 case PPC::BI__builtin_ppc_setb: 3288 case PPC::BI__builtin_ppc_mulhd: 3289 case PPC::BI__builtin_ppc_mulhdu: 3290 case PPC::BI__builtin_ppc_maddhd: 3291 case PPC::BI__builtin_ppc_maddhdu: 3292 case PPC::BI__builtin_ppc_maddld: 3293 case PPC::BI__builtin_ppc_load8r: 3294 case PPC::BI__builtin_ppc_store8r: 3295 case PPC::BI__builtin_ppc_insert_exp: 3296 case PPC::BI__builtin_ppc_extract_sig: 3297 case PPC::BI__builtin_ppc_addex: 3298 case PPC::BI__builtin_darn: 3299 case PPC::BI__builtin_darn_raw: 3300 return true; 3301 } 3302 return false; 3303 } 3304 3305 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3306 StringRef FeatureToCheck, unsigned DiagID, 3307 StringRef DiagArg = "") { 3308 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3309 return false; 3310 3311 if (DiagArg.empty()) 3312 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3313 else 3314 S.Diag(TheCall->getBeginLoc(), DiagID) 3315 << DiagArg << TheCall->getSourceRange(); 3316 3317 return true; 3318 } 3319 3320 /// Returns true if the argument consists of one contiguous run of 1s with any 3321 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3322 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3323 /// since all 1s are not contiguous. 3324 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3325 llvm::APSInt Result; 3326 // We can't check the value of a dependent argument. 3327 Expr *Arg = TheCall->getArg(ArgNum); 3328 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3329 return false; 3330 3331 // Check constant-ness first. 3332 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3333 return true; 3334 3335 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3336 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3337 return false; 3338 3339 return Diag(TheCall->getBeginLoc(), 3340 diag::err_argument_not_contiguous_bit_field) 3341 << ArgNum << Arg->getSourceRange(); 3342 } 3343 3344 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3345 CallExpr *TheCall) { 3346 unsigned i = 0, l = 0, u = 0; 3347 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3348 llvm::APSInt Result; 3349 3350 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3351 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3352 << TheCall->getSourceRange(); 3353 3354 switch (BuiltinID) { 3355 default: return false; 3356 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3357 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3358 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3359 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3360 case PPC::BI__builtin_altivec_dss: 3361 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3362 case PPC::BI__builtin_tbegin: 3363 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3364 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3365 case PPC::BI__builtin_tabortwc: 3366 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3367 case PPC::BI__builtin_tabortwci: 3368 case PPC::BI__builtin_tabortdci: 3369 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3370 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3371 case PPC::BI__builtin_altivec_dst: 3372 case PPC::BI__builtin_altivec_dstt: 3373 case PPC::BI__builtin_altivec_dstst: 3374 case PPC::BI__builtin_altivec_dststt: 3375 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3376 case PPC::BI__builtin_vsx_xxpermdi: 3377 case PPC::BI__builtin_vsx_xxsldwi: 3378 return SemaBuiltinVSX(TheCall); 3379 case PPC::BI__builtin_divwe: 3380 case PPC::BI__builtin_divweu: 3381 case PPC::BI__builtin_divde: 3382 case PPC::BI__builtin_divdeu: 3383 return SemaFeatureCheck(*this, TheCall, "extdiv", 3384 diag::err_ppc_builtin_only_on_arch, "7"); 3385 case PPC::BI__builtin_bpermd: 3386 return SemaFeatureCheck(*this, TheCall, "bpermd", 3387 diag::err_ppc_builtin_only_on_arch, "7"); 3388 case PPC::BI__builtin_unpack_vector_int128: 3389 return SemaFeatureCheck(*this, TheCall, "vsx", 3390 diag::err_ppc_builtin_only_on_arch, "7") || 3391 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3392 case PPC::BI__builtin_pack_vector_int128: 3393 return SemaFeatureCheck(*this, TheCall, "vsx", 3394 diag::err_ppc_builtin_only_on_arch, "7"); 3395 case PPC::BI__builtin_altivec_vgnb: 3396 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3397 case PPC::BI__builtin_altivec_vec_replace_elt: 3398 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3399 QualType VecTy = TheCall->getArg(0)->getType(); 3400 QualType EltTy = TheCall->getArg(1)->getType(); 3401 unsigned Width = Context.getIntWidth(EltTy); 3402 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3403 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3404 } 3405 case PPC::BI__builtin_vsx_xxeval: 3406 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3407 case PPC::BI__builtin_altivec_vsldbi: 3408 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3409 case PPC::BI__builtin_altivec_vsrdbi: 3410 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3411 case PPC::BI__builtin_vsx_xxpermx: 3412 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3413 case PPC::BI__builtin_ppc_tw: 3414 case PPC::BI__builtin_ppc_tdw: 3415 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); 3416 case PPC::BI__builtin_ppc_cmpeqb: 3417 case PPC::BI__builtin_ppc_setb: 3418 case PPC::BI__builtin_ppc_maddhd: 3419 case PPC::BI__builtin_ppc_maddhdu: 3420 case PPC::BI__builtin_ppc_maddld: 3421 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3422 diag::err_ppc_builtin_only_on_arch, "9"); 3423 case PPC::BI__builtin_ppc_cmprb: 3424 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3425 diag::err_ppc_builtin_only_on_arch, "9") || 3426 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3427 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3428 // be a constant that represents a contiguous bit field. 3429 case PPC::BI__builtin_ppc_rlwnm: 3430 return SemaBuiltinConstantArg(TheCall, 1, Result) || 3431 SemaValueIsRunOfOnes(TheCall, 2); 3432 case PPC::BI__builtin_ppc_rlwimi: 3433 case PPC::BI__builtin_ppc_rldimi: 3434 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3435 SemaValueIsRunOfOnes(TheCall, 3); 3436 case PPC::BI__builtin_ppc_extract_exp: 3437 case PPC::BI__builtin_ppc_extract_sig: 3438 case PPC::BI__builtin_ppc_insert_exp: 3439 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3440 diag::err_ppc_builtin_only_on_arch, "9"); 3441 case PPC::BI__builtin_ppc_addex: { 3442 if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3443 diag::err_ppc_builtin_only_on_arch, "9") || 3444 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3)) 3445 return true; 3446 // Output warning for reserved values 1 to 3. 3447 int ArgValue = 3448 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue(); 3449 if (ArgValue != 0) 3450 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour) 3451 << ArgValue; 3452 return false; 3453 } 3454 case PPC::BI__builtin_ppc_mtfsb0: 3455 case PPC::BI__builtin_ppc_mtfsb1: 3456 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3457 case PPC::BI__builtin_ppc_mtfsf: 3458 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3459 case PPC::BI__builtin_ppc_mtfsfi: 3460 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3461 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3462 case PPC::BI__builtin_ppc_alignx: 3463 return SemaBuiltinConstantArgPower2(TheCall, 0); 3464 case PPC::BI__builtin_ppc_rdlam: 3465 return SemaValueIsRunOfOnes(TheCall, 2); 3466 case PPC::BI__builtin_ppc_icbt: 3467 case PPC::BI__builtin_ppc_sthcx: 3468 case PPC::BI__builtin_ppc_stbcx: 3469 case PPC::BI__builtin_ppc_lharx: 3470 case PPC::BI__builtin_ppc_lbarx: 3471 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3472 diag::err_ppc_builtin_only_on_arch, "8"); 3473 case PPC::BI__builtin_vsx_ldrmb: 3474 case PPC::BI__builtin_vsx_strmb: 3475 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3476 diag::err_ppc_builtin_only_on_arch, "8") || 3477 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 3478 case PPC::BI__builtin_altivec_vcntmbb: 3479 case PPC::BI__builtin_altivec_vcntmbh: 3480 case PPC::BI__builtin_altivec_vcntmbw: 3481 case PPC::BI__builtin_altivec_vcntmbd: 3482 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3483 case PPC::BI__builtin_darn: 3484 case PPC::BI__builtin_darn_raw: 3485 case PPC::BI__builtin_darn_32: 3486 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3487 diag::err_ppc_builtin_only_on_arch, "9"); 3488 case PPC::BI__builtin_vsx_xxgenpcvbm: 3489 case PPC::BI__builtin_vsx_xxgenpcvhm: 3490 case PPC::BI__builtin_vsx_xxgenpcvwm: 3491 case PPC::BI__builtin_vsx_xxgenpcvdm: 3492 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3493 case PPC::BI__builtin_ppc_compare_exp_uo: 3494 case PPC::BI__builtin_ppc_compare_exp_lt: 3495 case PPC::BI__builtin_ppc_compare_exp_gt: 3496 case PPC::BI__builtin_ppc_compare_exp_eq: 3497 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3498 diag::err_ppc_builtin_only_on_arch, "9") || 3499 SemaFeatureCheck(*this, TheCall, "vsx", 3500 diag::err_ppc_builtin_requires_vsx); 3501 case PPC::BI__builtin_ppc_test_data_class: { 3502 // Check if the first argument of the __builtin_ppc_test_data_class call is 3503 // valid. The argument must be either a 'float' or a 'double'. 3504 QualType ArgType = TheCall->getArg(0)->getType(); 3505 if (ArgType != QualType(Context.FloatTy) && 3506 ArgType != QualType(Context.DoubleTy)) 3507 return Diag(TheCall->getBeginLoc(), 3508 diag::err_ppc_invalid_test_data_class_type); 3509 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3510 diag::err_ppc_builtin_only_on_arch, "9") || 3511 SemaFeatureCheck(*this, TheCall, "vsx", 3512 diag::err_ppc_builtin_requires_vsx) || 3513 SemaBuiltinConstantArgRange(TheCall, 1, 0, 127); 3514 } 3515 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3516 case PPC::BI__builtin_##Name: \ 3517 return SemaBuiltinPPCMMACall(TheCall, Types); 3518 #include "clang/Basic/BuiltinsPPC.def" 3519 } 3520 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3521 } 3522 3523 // Check if the given type is a non-pointer PPC MMA type. This function is used 3524 // in Sema to prevent invalid uses of restricted PPC MMA types. 3525 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3526 if (Type->isPointerType() || Type->isArrayType()) 3527 return false; 3528 3529 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3530 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3531 if (false 3532 #include "clang/Basic/PPCTypes.def" 3533 ) { 3534 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3535 return true; 3536 } 3537 return false; 3538 } 3539 3540 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3541 CallExpr *TheCall) { 3542 // position of memory order and scope arguments in the builtin 3543 unsigned OrderIndex, ScopeIndex; 3544 switch (BuiltinID) { 3545 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3546 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3547 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3548 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3549 OrderIndex = 2; 3550 ScopeIndex = 3; 3551 break; 3552 case AMDGPU::BI__builtin_amdgcn_fence: 3553 OrderIndex = 0; 3554 ScopeIndex = 1; 3555 break; 3556 default: 3557 return false; 3558 } 3559 3560 ExprResult Arg = TheCall->getArg(OrderIndex); 3561 auto ArgExpr = Arg.get(); 3562 Expr::EvalResult ArgResult; 3563 3564 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3565 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3566 << ArgExpr->getType(); 3567 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3568 3569 // Check validity of memory ordering as per C11 / C++11's memody model. 3570 // Only fence needs check. Atomic dec/inc allow all memory orders. 3571 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3572 return Diag(ArgExpr->getBeginLoc(), 3573 diag::warn_atomic_op_has_invalid_memory_order) 3574 << ArgExpr->getSourceRange(); 3575 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3576 case llvm::AtomicOrderingCABI::relaxed: 3577 case llvm::AtomicOrderingCABI::consume: 3578 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3579 return Diag(ArgExpr->getBeginLoc(), 3580 diag::warn_atomic_op_has_invalid_memory_order) 3581 << ArgExpr->getSourceRange(); 3582 break; 3583 case llvm::AtomicOrderingCABI::acquire: 3584 case llvm::AtomicOrderingCABI::release: 3585 case llvm::AtomicOrderingCABI::acq_rel: 3586 case llvm::AtomicOrderingCABI::seq_cst: 3587 break; 3588 } 3589 3590 Arg = TheCall->getArg(ScopeIndex); 3591 ArgExpr = Arg.get(); 3592 Expr::EvalResult ArgResult1; 3593 // Check that sync scope is a constant literal 3594 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3595 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3596 << ArgExpr->getType(); 3597 3598 return false; 3599 } 3600 3601 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3602 llvm::APSInt Result; 3603 3604 // We can't check the value of a dependent argument. 3605 Expr *Arg = TheCall->getArg(ArgNum); 3606 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3607 return false; 3608 3609 // Check constant-ness first. 3610 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3611 return true; 3612 3613 int64_t Val = Result.getSExtValue(); 3614 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3615 return false; 3616 3617 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3618 << Arg->getSourceRange(); 3619 } 3620 3621 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3622 unsigned BuiltinID, 3623 CallExpr *TheCall) { 3624 // CodeGenFunction can also detect this, but this gives a better error 3625 // message. 3626 bool FeatureMissing = false; 3627 SmallVector<StringRef> ReqFeatures; 3628 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3629 Features.split(ReqFeatures, ','); 3630 3631 // Check if each required feature is included 3632 for (StringRef F : ReqFeatures) { 3633 if (TI.hasFeature(F)) 3634 continue; 3635 3636 // If the feature is 64bit, alter the string so it will print better in 3637 // the diagnostic. 3638 if (F == "64bit") 3639 F = "RV64"; 3640 3641 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3642 F.consume_front("experimental-"); 3643 std::string FeatureStr = F.str(); 3644 FeatureStr[0] = std::toupper(FeatureStr[0]); 3645 3646 // Error message 3647 FeatureMissing = true; 3648 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3649 << TheCall->getSourceRange() << StringRef(FeatureStr); 3650 } 3651 3652 if (FeatureMissing) 3653 return true; 3654 3655 switch (BuiltinID) { 3656 case RISCV::BI__builtin_rvv_vsetvli: 3657 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3658 CheckRISCVLMUL(TheCall, 2); 3659 case RISCV::BI__builtin_rvv_vsetvlimax: 3660 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3661 CheckRISCVLMUL(TheCall, 1); 3662 case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1: 3663 case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1: 3664 case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1: 3665 case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1: 3666 case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1: 3667 case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1: 3668 case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1: 3669 case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1: 3670 case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1: 3671 case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1: 3672 case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2: 3673 case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2: 3674 case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2: 3675 case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2: 3676 case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2: 3677 case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2: 3678 case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2: 3679 case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2: 3680 case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2: 3681 case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2: 3682 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4: 3683 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4: 3684 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4: 3685 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4: 3686 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4: 3687 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4: 3688 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4: 3689 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4: 3690 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4: 3691 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4: 3692 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3693 case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1: 3694 case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1: 3695 case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1: 3696 case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1: 3697 case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1: 3698 case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1: 3699 case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1: 3700 case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1: 3701 case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1: 3702 case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1: 3703 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2: 3704 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2: 3705 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2: 3706 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2: 3707 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2: 3708 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2: 3709 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2: 3710 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2: 3711 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2: 3712 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2: 3713 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3714 case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1: 3715 case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1: 3716 case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1: 3717 case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1: 3718 case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1: 3719 case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1: 3720 case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1: 3721 case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1: 3722 case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1: 3723 case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1: 3724 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3725 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2: 3726 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2: 3727 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2: 3728 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2: 3729 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2: 3730 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2: 3731 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2: 3732 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2: 3733 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2: 3734 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2: 3735 case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4: 3736 case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4: 3737 case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4: 3738 case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4: 3739 case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4: 3740 case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4: 3741 case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4: 3742 case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4: 3743 case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4: 3744 case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4: 3745 case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8: 3746 case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8: 3747 case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8: 3748 case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8: 3749 case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8: 3750 case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8: 3751 case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8: 3752 case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8: 3753 case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8: 3754 case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8: 3755 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3756 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4: 3757 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4: 3758 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4: 3759 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4: 3760 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4: 3761 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4: 3762 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4: 3763 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4: 3764 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4: 3765 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4: 3766 case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8: 3767 case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8: 3768 case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8: 3769 case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8: 3770 case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8: 3771 case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8: 3772 case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8: 3773 case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8: 3774 case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8: 3775 case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8: 3776 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3777 case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8: 3778 case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8: 3779 case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8: 3780 case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8: 3781 case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8: 3782 case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8: 3783 case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8: 3784 case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8: 3785 case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8: 3786 case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8: 3787 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3788 } 3789 3790 return false; 3791 } 3792 3793 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3794 CallExpr *TheCall) { 3795 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3796 Expr *Arg = TheCall->getArg(0); 3797 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3798 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3799 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3800 << Arg->getSourceRange(); 3801 } 3802 3803 // For intrinsics which take an immediate value as part of the instruction, 3804 // range check them here. 3805 unsigned i = 0, l = 0, u = 0; 3806 switch (BuiltinID) { 3807 default: return false; 3808 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3809 case SystemZ::BI__builtin_s390_verimb: 3810 case SystemZ::BI__builtin_s390_verimh: 3811 case SystemZ::BI__builtin_s390_verimf: 3812 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3813 case SystemZ::BI__builtin_s390_vfaeb: 3814 case SystemZ::BI__builtin_s390_vfaeh: 3815 case SystemZ::BI__builtin_s390_vfaef: 3816 case SystemZ::BI__builtin_s390_vfaebs: 3817 case SystemZ::BI__builtin_s390_vfaehs: 3818 case SystemZ::BI__builtin_s390_vfaefs: 3819 case SystemZ::BI__builtin_s390_vfaezb: 3820 case SystemZ::BI__builtin_s390_vfaezh: 3821 case SystemZ::BI__builtin_s390_vfaezf: 3822 case SystemZ::BI__builtin_s390_vfaezbs: 3823 case SystemZ::BI__builtin_s390_vfaezhs: 3824 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3825 case SystemZ::BI__builtin_s390_vfisb: 3826 case SystemZ::BI__builtin_s390_vfidb: 3827 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3828 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3829 case SystemZ::BI__builtin_s390_vftcisb: 3830 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3831 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3832 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3833 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3834 case SystemZ::BI__builtin_s390_vstrcb: 3835 case SystemZ::BI__builtin_s390_vstrch: 3836 case SystemZ::BI__builtin_s390_vstrcf: 3837 case SystemZ::BI__builtin_s390_vstrczb: 3838 case SystemZ::BI__builtin_s390_vstrczh: 3839 case SystemZ::BI__builtin_s390_vstrczf: 3840 case SystemZ::BI__builtin_s390_vstrcbs: 3841 case SystemZ::BI__builtin_s390_vstrchs: 3842 case SystemZ::BI__builtin_s390_vstrcfs: 3843 case SystemZ::BI__builtin_s390_vstrczbs: 3844 case SystemZ::BI__builtin_s390_vstrczhs: 3845 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3846 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3847 case SystemZ::BI__builtin_s390_vfminsb: 3848 case SystemZ::BI__builtin_s390_vfmaxsb: 3849 case SystemZ::BI__builtin_s390_vfmindb: 3850 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3851 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3852 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3853 case SystemZ::BI__builtin_s390_vclfnhs: 3854 case SystemZ::BI__builtin_s390_vclfnls: 3855 case SystemZ::BI__builtin_s390_vcfn: 3856 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 3857 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 3858 } 3859 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3860 } 3861 3862 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3863 /// This checks that the target supports __builtin_cpu_supports and 3864 /// that the string argument is constant and valid. 3865 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3866 CallExpr *TheCall) { 3867 Expr *Arg = TheCall->getArg(0); 3868 3869 // Check if the argument is a string literal. 3870 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3871 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3872 << Arg->getSourceRange(); 3873 3874 // Check the contents of the string. 3875 StringRef Feature = 3876 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3877 if (!TI.validateCpuSupports(Feature)) 3878 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3879 << Arg->getSourceRange(); 3880 return false; 3881 } 3882 3883 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3884 /// This checks that the target supports __builtin_cpu_is and 3885 /// that the string argument is constant and valid. 3886 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3887 Expr *Arg = TheCall->getArg(0); 3888 3889 // Check if the argument is a string literal. 3890 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3891 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3892 << Arg->getSourceRange(); 3893 3894 // Check the contents of the string. 3895 StringRef Feature = 3896 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3897 if (!TI.validateCpuIs(Feature)) 3898 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3899 << Arg->getSourceRange(); 3900 return false; 3901 } 3902 3903 // Check if the rounding mode is legal. 3904 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3905 // Indicates if this instruction has rounding control or just SAE. 3906 bool HasRC = false; 3907 3908 unsigned ArgNum = 0; 3909 switch (BuiltinID) { 3910 default: 3911 return false; 3912 case X86::BI__builtin_ia32_vcvttsd2si32: 3913 case X86::BI__builtin_ia32_vcvttsd2si64: 3914 case X86::BI__builtin_ia32_vcvttsd2usi32: 3915 case X86::BI__builtin_ia32_vcvttsd2usi64: 3916 case X86::BI__builtin_ia32_vcvttss2si32: 3917 case X86::BI__builtin_ia32_vcvttss2si64: 3918 case X86::BI__builtin_ia32_vcvttss2usi32: 3919 case X86::BI__builtin_ia32_vcvttss2usi64: 3920 case X86::BI__builtin_ia32_vcvttsh2si32: 3921 case X86::BI__builtin_ia32_vcvttsh2si64: 3922 case X86::BI__builtin_ia32_vcvttsh2usi32: 3923 case X86::BI__builtin_ia32_vcvttsh2usi64: 3924 ArgNum = 1; 3925 break; 3926 case X86::BI__builtin_ia32_maxpd512: 3927 case X86::BI__builtin_ia32_maxps512: 3928 case X86::BI__builtin_ia32_minpd512: 3929 case X86::BI__builtin_ia32_minps512: 3930 case X86::BI__builtin_ia32_maxph512: 3931 case X86::BI__builtin_ia32_minph512: 3932 ArgNum = 2; 3933 break; 3934 case X86::BI__builtin_ia32_vcvtph2pd512_mask: 3935 case X86::BI__builtin_ia32_vcvtph2psx512_mask: 3936 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3937 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3938 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3939 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3940 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3941 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3942 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3943 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3944 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3945 case X86::BI__builtin_ia32_vcvttph2w512_mask: 3946 case X86::BI__builtin_ia32_vcvttph2uw512_mask: 3947 case X86::BI__builtin_ia32_vcvttph2dq512_mask: 3948 case X86::BI__builtin_ia32_vcvttph2udq512_mask: 3949 case X86::BI__builtin_ia32_vcvttph2qq512_mask: 3950 case X86::BI__builtin_ia32_vcvttph2uqq512_mask: 3951 case X86::BI__builtin_ia32_exp2pd_mask: 3952 case X86::BI__builtin_ia32_exp2ps_mask: 3953 case X86::BI__builtin_ia32_getexppd512_mask: 3954 case X86::BI__builtin_ia32_getexpps512_mask: 3955 case X86::BI__builtin_ia32_getexpph512_mask: 3956 case X86::BI__builtin_ia32_rcp28pd_mask: 3957 case X86::BI__builtin_ia32_rcp28ps_mask: 3958 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3959 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3960 case X86::BI__builtin_ia32_vcomisd: 3961 case X86::BI__builtin_ia32_vcomiss: 3962 case X86::BI__builtin_ia32_vcomish: 3963 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3964 ArgNum = 3; 3965 break; 3966 case X86::BI__builtin_ia32_cmppd512_mask: 3967 case X86::BI__builtin_ia32_cmpps512_mask: 3968 case X86::BI__builtin_ia32_cmpsd_mask: 3969 case X86::BI__builtin_ia32_cmpss_mask: 3970 case X86::BI__builtin_ia32_cmpsh_mask: 3971 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: 3972 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: 3973 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3974 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3975 case X86::BI__builtin_ia32_getexpss128_round_mask: 3976 case X86::BI__builtin_ia32_getexpsh128_round_mask: 3977 case X86::BI__builtin_ia32_getmantpd512_mask: 3978 case X86::BI__builtin_ia32_getmantps512_mask: 3979 case X86::BI__builtin_ia32_getmantph512_mask: 3980 case X86::BI__builtin_ia32_maxsd_round_mask: 3981 case X86::BI__builtin_ia32_maxss_round_mask: 3982 case X86::BI__builtin_ia32_maxsh_round_mask: 3983 case X86::BI__builtin_ia32_minsd_round_mask: 3984 case X86::BI__builtin_ia32_minss_round_mask: 3985 case X86::BI__builtin_ia32_minsh_round_mask: 3986 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3987 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3988 case X86::BI__builtin_ia32_reducepd512_mask: 3989 case X86::BI__builtin_ia32_reduceps512_mask: 3990 case X86::BI__builtin_ia32_reduceph512_mask: 3991 case X86::BI__builtin_ia32_rndscalepd_mask: 3992 case X86::BI__builtin_ia32_rndscaleps_mask: 3993 case X86::BI__builtin_ia32_rndscaleph_mask: 3994 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3995 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3996 ArgNum = 4; 3997 break; 3998 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3999 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4000 case X86::BI__builtin_ia32_fixupimmps512_mask: 4001 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4002 case X86::BI__builtin_ia32_fixupimmsd_mask: 4003 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4004 case X86::BI__builtin_ia32_fixupimmss_mask: 4005 case X86::BI__builtin_ia32_fixupimmss_maskz: 4006 case X86::BI__builtin_ia32_getmantsd_round_mask: 4007 case X86::BI__builtin_ia32_getmantss_round_mask: 4008 case X86::BI__builtin_ia32_getmantsh_round_mask: 4009 case X86::BI__builtin_ia32_rangepd512_mask: 4010 case X86::BI__builtin_ia32_rangeps512_mask: 4011 case X86::BI__builtin_ia32_rangesd128_round_mask: 4012 case X86::BI__builtin_ia32_rangess128_round_mask: 4013 case X86::BI__builtin_ia32_reducesd_mask: 4014 case X86::BI__builtin_ia32_reducess_mask: 4015 case X86::BI__builtin_ia32_reducesh_mask: 4016 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4017 case X86::BI__builtin_ia32_rndscaless_round_mask: 4018 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4019 ArgNum = 5; 4020 break; 4021 case X86::BI__builtin_ia32_vcvtsd2si64: 4022 case X86::BI__builtin_ia32_vcvtsd2si32: 4023 case X86::BI__builtin_ia32_vcvtsd2usi32: 4024 case X86::BI__builtin_ia32_vcvtsd2usi64: 4025 case X86::BI__builtin_ia32_vcvtss2si32: 4026 case X86::BI__builtin_ia32_vcvtss2si64: 4027 case X86::BI__builtin_ia32_vcvtss2usi32: 4028 case X86::BI__builtin_ia32_vcvtss2usi64: 4029 case X86::BI__builtin_ia32_vcvtsh2si32: 4030 case X86::BI__builtin_ia32_vcvtsh2si64: 4031 case X86::BI__builtin_ia32_vcvtsh2usi32: 4032 case X86::BI__builtin_ia32_vcvtsh2usi64: 4033 case X86::BI__builtin_ia32_sqrtpd512: 4034 case X86::BI__builtin_ia32_sqrtps512: 4035 case X86::BI__builtin_ia32_sqrtph512: 4036 ArgNum = 1; 4037 HasRC = true; 4038 break; 4039 case X86::BI__builtin_ia32_addph512: 4040 case X86::BI__builtin_ia32_divph512: 4041 case X86::BI__builtin_ia32_mulph512: 4042 case X86::BI__builtin_ia32_subph512: 4043 case X86::BI__builtin_ia32_addpd512: 4044 case X86::BI__builtin_ia32_addps512: 4045 case X86::BI__builtin_ia32_divpd512: 4046 case X86::BI__builtin_ia32_divps512: 4047 case X86::BI__builtin_ia32_mulpd512: 4048 case X86::BI__builtin_ia32_mulps512: 4049 case X86::BI__builtin_ia32_subpd512: 4050 case X86::BI__builtin_ia32_subps512: 4051 case X86::BI__builtin_ia32_cvtsi2sd64: 4052 case X86::BI__builtin_ia32_cvtsi2ss32: 4053 case X86::BI__builtin_ia32_cvtsi2ss64: 4054 case X86::BI__builtin_ia32_cvtusi2sd64: 4055 case X86::BI__builtin_ia32_cvtusi2ss32: 4056 case X86::BI__builtin_ia32_cvtusi2ss64: 4057 case X86::BI__builtin_ia32_vcvtusi2sh: 4058 case X86::BI__builtin_ia32_vcvtusi642sh: 4059 case X86::BI__builtin_ia32_vcvtsi2sh: 4060 case X86::BI__builtin_ia32_vcvtsi642sh: 4061 ArgNum = 2; 4062 HasRC = true; 4063 break; 4064 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 4065 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 4066 case X86::BI__builtin_ia32_vcvtpd2ph512_mask: 4067 case X86::BI__builtin_ia32_vcvtps2phx512_mask: 4068 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 4069 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 4070 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 4071 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 4072 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 4073 case X86::BI__builtin_ia32_cvtps2dq512_mask: 4074 case X86::BI__builtin_ia32_cvtps2qq512_mask: 4075 case X86::BI__builtin_ia32_cvtps2udq512_mask: 4076 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 4077 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 4078 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 4079 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 4080 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 4081 case X86::BI__builtin_ia32_vcvtdq2ph512_mask: 4082 case X86::BI__builtin_ia32_vcvtudq2ph512_mask: 4083 case X86::BI__builtin_ia32_vcvtw2ph512_mask: 4084 case X86::BI__builtin_ia32_vcvtuw2ph512_mask: 4085 case X86::BI__builtin_ia32_vcvtph2w512_mask: 4086 case X86::BI__builtin_ia32_vcvtph2uw512_mask: 4087 case X86::BI__builtin_ia32_vcvtph2dq512_mask: 4088 case X86::BI__builtin_ia32_vcvtph2udq512_mask: 4089 case X86::BI__builtin_ia32_vcvtph2qq512_mask: 4090 case X86::BI__builtin_ia32_vcvtph2uqq512_mask: 4091 case X86::BI__builtin_ia32_vcvtqq2ph512_mask: 4092 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: 4093 ArgNum = 3; 4094 HasRC = true; 4095 break; 4096 case X86::BI__builtin_ia32_addsh_round_mask: 4097 case X86::BI__builtin_ia32_addss_round_mask: 4098 case X86::BI__builtin_ia32_addsd_round_mask: 4099 case X86::BI__builtin_ia32_divsh_round_mask: 4100 case X86::BI__builtin_ia32_divss_round_mask: 4101 case X86::BI__builtin_ia32_divsd_round_mask: 4102 case X86::BI__builtin_ia32_mulsh_round_mask: 4103 case X86::BI__builtin_ia32_mulss_round_mask: 4104 case X86::BI__builtin_ia32_mulsd_round_mask: 4105 case X86::BI__builtin_ia32_subsh_round_mask: 4106 case X86::BI__builtin_ia32_subss_round_mask: 4107 case X86::BI__builtin_ia32_subsd_round_mask: 4108 case X86::BI__builtin_ia32_scalefph512_mask: 4109 case X86::BI__builtin_ia32_scalefpd512_mask: 4110 case X86::BI__builtin_ia32_scalefps512_mask: 4111 case X86::BI__builtin_ia32_scalefsd_round_mask: 4112 case X86::BI__builtin_ia32_scalefss_round_mask: 4113 case X86::BI__builtin_ia32_scalefsh_round_mask: 4114 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4115 case X86::BI__builtin_ia32_vcvtss2sh_round_mask: 4116 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: 4117 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4118 case X86::BI__builtin_ia32_sqrtss_round_mask: 4119 case X86::BI__builtin_ia32_sqrtsh_round_mask: 4120 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4121 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4122 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4123 case X86::BI__builtin_ia32_vfmaddss3_mask: 4124 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4125 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4126 case X86::BI__builtin_ia32_vfmaddsh3_mask: 4127 case X86::BI__builtin_ia32_vfmaddsh3_maskz: 4128 case X86::BI__builtin_ia32_vfmaddsh3_mask3: 4129 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4130 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4131 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4132 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4133 case X86::BI__builtin_ia32_vfmaddps512_mask: 4134 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4135 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4136 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4137 case X86::BI__builtin_ia32_vfmaddph512_mask: 4138 case X86::BI__builtin_ia32_vfmaddph512_maskz: 4139 case X86::BI__builtin_ia32_vfmaddph512_mask3: 4140 case X86::BI__builtin_ia32_vfmsubph512_mask3: 4141 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4142 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4143 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4144 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4145 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4146 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4147 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4148 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4149 case X86::BI__builtin_ia32_vfmaddsubph512_mask: 4150 case X86::BI__builtin_ia32_vfmaddsubph512_maskz: 4151 case X86::BI__builtin_ia32_vfmaddsubph512_mask3: 4152 case X86::BI__builtin_ia32_vfmsubaddph512_mask3: 4153 case X86::BI__builtin_ia32_vfmaddcsh_mask: 4154 case X86::BI__builtin_ia32_vfmaddcsh_round_mask: 4155 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3: 4156 case X86::BI__builtin_ia32_vfmaddcph512_mask: 4157 case X86::BI__builtin_ia32_vfmaddcph512_maskz: 4158 case X86::BI__builtin_ia32_vfmaddcph512_mask3: 4159 case X86::BI__builtin_ia32_vfcmaddcsh_mask: 4160 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask: 4161 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3: 4162 case X86::BI__builtin_ia32_vfcmaddcph512_mask: 4163 case X86::BI__builtin_ia32_vfcmaddcph512_maskz: 4164 case X86::BI__builtin_ia32_vfcmaddcph512_mask3: 4165 case X86::BI__builtin_ia32_vfmulcsh_mask: 4166 case X86::BI__builtin_ia32_vfmulcph512_mask: 4167 case X86::BI__builtin_ia32_vfcmulcsh_mask: 4168 case X86::BI__builtin_ia32_vfcmulcph512_mask: 4169 ArgNum = 4; 4170 HasRC = true; 4171 break; 4172 } 4173 4174 llvm::APSInt Result; 4175 4176 // We can't check the value of a dependent argument. 4177 Expr *Arg = TheCall->getArg(ArgNum); 4178 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4179 return false; 4180 4181 // Check constant-ness first. 4182 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4183 return true; 4184 4185 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4186 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4187 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4188 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4189 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4190 Result == 8/*ROUND_NO_EXC*/ || 4191 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4192 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4193 return false; 4194 4195 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4196 << Arg->getSourceRange(); 4197 } 4198 4199 // Check if the gather/scatter scale is legal. 4200 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4201 CallExpr *TheCall) { 4202 unsigned ArgNum = 0; 4203 switch (BuiltinID) { 4204 default: 4205 return false; 4206 case X86::BI__builtin_ia32_gatherpfdpd: 4207 case X86::BI__builtin_ia32_gatherpfdps: 4208 case X86::BI__builtin_ia32_gatherpfqpd: 4209 case X86::BI__builtin_ia32_gatherpfqps: 4210 case X86::BI__builtin_ia32_scatterpfdpd: 4211 case X86::BI__builtin_ia32_scatterpfdps: 4212 case X86::BI__builtin_ia32_scatterpfqpd: 4213 case X86::BI__builtin_ia32_scatterpfqps: 4214 ArgNum = 3; 4215 break; 4216 case X86::BI__builtin_ia32_gatherd_pd: 4217 case X86::BI__builtin_ia32_gatherd_pd256: 4218 case X86::BI__builtin_ia32_gatherq_pd: 4219 case X86::BI__builtin_ia32_gatherq_pd256: 4220 case X86::BI__builtin_ia32_gatherd_ps: 4221 case X86::BI__builtin_ia32_gatherd_ps256: 4222 case X86::BI__builtin_ia32_gatherq_ps: 4223 case X86::BI__builtin_ia32_gatherq_ps256: 4224 case X86::BI__builtin_ia32_gatherd_q: 4225 case X86::BI__builtin_ia32_gatherd_q256: 4226 case X86::BI__builtin_ia32_gatherq_q: 4227 case X86::BI__builtin_ia32_gatherq_q256: 4228 case X86::BI__builtin_ia32_gatherd_d: 4229 case X86::BI__builtin_ia32_gatherd_d256: 4230 case X86::BI__builtin_ia32_gatherq_d: 4231 case X86::BI__builtin_ia32_gatherq_d256: 4232 case X86::BI__builtin_ia32_gather3div2df: 4233 case X86::BI__builtin_ia32_gather3div2di: 4234 case X86::BI__builtin_ia32_gather3div4df: 4235 case X86::BI__builtin_ia32_gather3div4di: 4236 case X86::BI__builtin_ia32_gather3div4sf: 4237 case X86::BI__builtin_ia32_gather3div4si: 4238 case X86::BI__builtin_ia32_gather3div8sf: 4239 case X86::BI__builtin_ia32_gather3div8si: 4240 case X86::BI__builtin_ia32_gather3siv2df: 4241 case X86::BI__builtin_ia32_gather3siv2di: 4242 case X86::BI__builtin_ia32_gather3siv4df: 4243 case X86::BI__builtin_ia32_gather3siv4di: 4244 case X86::BI__builtin_ia32_gather3siv4sf: 4245 case X86::BI__builtin_ia32_gather3siv4si: 4246 case X86::BI__builtin_ia32_gather3siv8sf: 4247 case X86::BI__builtin_ia32_gather3siv8si: 4248 case X86::BI__builtin_ia32_gathersiv8df: 4249 case X86::BI__builtin_ia32_gathersiv16sf: 4250 case X86::BI__builtin_ia32_gatherdiv8df: 4251 case X86::BI__builtin_ia32_gatherdiv16sf: 4252 case X86::BI__builtin_ia32_gathersiv8di: 4253 case X86::BI__builtin_ia32_gathersiv16si: 4254 case X86::BI__builtin_ia32_gatherdiv8di: 4255 case X86::BI__builtin_ia32_gatherdiv16si: 4256 case X86::BI__builtin_ia32_scatterdiv2df: 4257 case X86::BI__builtin_ia32_scatterdiv2di: 4258 case X86::BI__builtin_ia32_scatterdiv4df: 4259 case X86::BI__builtin_ia32_scatterdiv4di: 4260 case X86::BI__builtin_ia32_scatterdiv4sf: 4261 case X86::BI__builtin_ia32_scatterdiv4si: 4262 case X86::BI__builtin_ia32_scatterdiv8sf: 4263 case X86::BI__builtin_ia32_scatterdiv8si: 4264 case X86::BI__builtin_ia32_scattersiv2df: 4265 case X86::BI__builtin_ia32_scattersiv2di: 4266 case X86::BI__builtin_ia32_scattersiv4df: 4267 case X86::BI__builtin_ia32_scattersiv4di: 4268 case X86::BI__builtin_ia32_scattersiv4sf: 4269 case X86::BI__builtin_ia32_scattersiv4si: 4270 case X86::BI__builtin_ia32_scattersiv8sf: 4271 case X86::BI__builtin_ia32_scattersiv8si: 4272 case X86::BI__builtin_ia32_scattersiv8df: 4273 case X86::BI__builtin_ia32_scattersiv16sf: 4274 case X86::BI__builtin_ia32_scatterdiv8df: 4275 case X86::BI__builtin_ia32_scatterdiv16sf: 4276 case X86::BI__builtin_ia32_scattersiv8di: 4277 case X86::BI__builtin_ia32_scattersiv16si: 4278 case X86::BI__builtin_ia32_scatterdiv8di: 4279 case X86::BI__builtin_ia32_scatterdiv16si: 4280 ArgNum = 4; 4281 break; 4282 } 4283 4284 llvm::APSInt Result; 4285 4286 // We can't check the value of a dependent argument. 4287 Expr *Arg = TheCall->getArg(ArgNum); 4288 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4289 return false; 4290 4291 // Check constant-ness first. 4292 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4293 return true; 4294 4295 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4296 return false; 4297 4298 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4299 << Arg->getSourceRange(); 4300 } 4301 4302 enum { TileRegLow = 0, TileRegHigh = 7 }; 4303 4304 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4305 ArrayRef<int> ArgNums) { 4306 for (int ArgNum : ArgNums) { 4307 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4308 return true; 4309 } 4310 return false; 4311 } 4312 4313 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4314 ArrayRef<int> ArgNums) { 4315 // Because the max number of tile register is TileRegHigh + 1, so here we use 4316 // each bit to represent the usage of them in bitset. 4317 std::bitset<TileRegHigh + 1> ArgValues; 4318 for (int ArgNum : ArgNums) { 4319 Expr *Arg = TheCall->getArg(ArgNum); 4320 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4321 continue; 4322 4323 llvm::APSInt Result; 4324 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4325 return true; 4326 int ArgExtValue = Result.getExtValue(); 4327 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4328 "Incorrect tile register num."); 4329 if (ArgValues.test(ArgExtValue)) 4330 return Diag(TheCall->getBeginLoc(), 4331 diag::err_x86_builtin_tile_arg_duplicate) 4332 << TheCall->getArg(ArgNum)->getSourceRange(); 4333 ArgValues.set(ArgExtValue); 4334 } 4335 return false; 4336 } 4337 4338 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4339 ArrayRef<int> ArgNums) { 4340 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4341 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4342 } 4343 4344 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4345 switch (BuiltinID) { 4346 default: 4347 return false; 4348 case X86::BI__builtin_ia32_tileloadd64: 4349 case X86::BI__builtin_ia32_tileloaddt164: 4350 case X86::BI__builtin_ia32_tilestored64: 4351 case X86::BI__builtin_ia32_tilezero: 4352 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4353 case X86::BI__builtin_ia32_tdpbssd: 4354 case X86::BI__builtin_ia32_tdpbsud: 4355 case X86::BI__builtin_ia32_tdpbusd: 4356 case X86::BI__builtin_ia32_tdpbuud: 4357 case X86::BI__builtin_ia32_tdpbf16ps: 4358 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4359 } 4360 } 4361 static bool isX86_32Builtin(unsigned BuiltinID) { 4362 // These builtins only work on x86-32 targets. 4363 switch (BuiltinID) { 4364 case X86::BI__builtin_ia32_readeflags_u32: 4365 case X86::BI__builtin_ia32_writeeflags_u32: 4366 return true; 4367 } 4368 4369 return false; 4370 } 4371 4372 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4373 CallExpr *TheCall) { 4374 if (BuiltinID == X86::BI__builtin_cpu_supports) 4375 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4376 4377 if (BuiltinID == X86::BI__builtin_cpu_is) 4378 return SemaBuiltinCpuIs(*this, TI, TheCall); 4379 4380 // Check for 32-bit only builtins on a 64-bit target. 4381 const llvm::Triple &TT = TI.getTriple(); 4382 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4383 return Diag(TheCall->getCallee()->getBeginLoc(), 4384 diag::err_32_bit_builtin_64_bit_tgt); 4385 4386 // If the intrinsic has rounding or SAE make sure its valid. 4387 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4388 return true; 4389 4390 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4391 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4392 return true; 4393 4394 // If the intrinsic has a tile arguments, make sure they are valid. 4395 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4396 return true; 4397 4398 // For intrinsics which take an immediate value as part of the instruction, 4399 // range check them here. 4400 int i = 0, l = 0, u = 0; 4401 switch (BuiltinID) { 4402 default: 4403 return false; 4404 case X86::BI__builtin_ia32_vec_ext_v2si: 4405 case X86::BI__builtin_ia32_vec_ext_v2di: 4406 case X86::BI__builtin_ia32_vextractf128_pd256: 4407 case X86::BI__builtin_ia32_vextractf128_ps256: 4408 case X86::BI__builtin_ia32_vextractf128_si256: 4409 case X86::BI__builtin_ia32_extract128i256: 4410 case X86::BI__builtin_ia32_extractf64x4_mask: 4411 case X86::BI__builtin_ia32_extracti64x4_mask: 4412 case X86::BI__builtin_ia32_extractf32x8_mask: 4413 case X86::BI__builtin_ia32_extracti32x8_mask: 4414 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4415 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4416 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4417 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4418 i = 1; l = 0; u = 1; 4419 break; 4420 case X86::BI__builtin_ia32_vec_set_v2di: 4421 case X86::BI__builtin_ia32_vinsertf128_pd256: 4422 case X86::BI__builtin_ia32_vinsertf128_ps256: 4423 case X86::BI__builtin_ia32_vinsertf128_si256: 4424 case X86::BI__builtin_ia32_insert128i256: 4425 case X86::BI__builtin_ia32_insertf32x8: 4426 case X86::BI__builtin_ia32_inserti32x8: 4427 case X86::BI__builtin_ia32_insertf64x4: 4428 case X86::BI__builtin_ia32_inserti64x4: 4429 case X86::BI__builtin_ia32_insertf64x2_256: 4430 case X86::BI__builtin_ia32_inserti64x2_256: 4431 case X86::BI__builtin_ia32_insertf32x4_256: 4432 case X86::BI__builtin_ia32_inserti32x4_256: 4433 i = 2; l = 0; u = 1; 4434 break; 4435 case X86::BI__builtin_ia32_vpermilpd: 4436 case X86::BI__builtin_ia32_vec_ext_v4hi: 4437 case X86::BI__builtin_ia32_vec_ext_v4si: 4438 case X86::BI__builtin_ia32_vec_ext_v4sf: 4439 case X86::BI__builtin_ia32_vec_ext_v4di: 4440 case X86::BI__builtin_ia32_extractf32x4_mask: 4441 case X86::BI__builtin_ia32_extracti32x4_mask: 4442 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4443 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4444 i = 1; l = 0; u = 3; 4445 break; 4446 case X86::BI_mm_prefetch: 4447 case X86::BI__builtin_ia32_vec_ext_v8hi: 4448 case X86::BI__builtin_ia32_vec_ext_v8si: 4449 i = 1; l = 0; u = 7; 4450 break; 4451 case X86::BI__builtin_ia32_sha1rnds4: 4452 case X86::BI__builtin_ia32_blendpd: 4453 case X86::BI__builtin_ia32_shufpd: 4454 case X86::BI__builtin_ia32_vec_set_v4hi: 4455 case X86::BI__builtin_ia32_vec_set_v4si: 4456 case X86::BI__builtin_ia32_vec_set_v4di: 4457 case X86::BI__builtin_ia32_shuf_f32x4_256: 4458 case X86::BI__builtin_ia32_shuf_f64x2_256: 4459 case X86::BI__builtin_ia32_shuf_i32x4_256: 4460 case X86::BI__builtin_ia32_shuf_i64x2_256: 4461 case X86::BI__builtin_ia32_insertf64x2_512: 4462 case X86::BI__builtin_ia32_inserti64x2_512: 4463 case X86::BI__builtin_ia32_insertf32x4: 4464 case X86::BI__builtin_ia32_inserti32x4: 4465 i = 2; l = 0; u = 3; 4466 break; 4467 case X86::BI__builtin_ia32_vpermil2pd: 4468 case X86::BI__builtin_ia32_vpermil2pd256: 4469 case X86::BI__builtin_ia32_vpermil2ps: 4470 case X86::BI__builtin_ia32_vpermil2ps256: 4471 i = 3; l = 0; u = 3; 4472 break; 4473 case X86::BI__builtin_ia32_cmpb128_mask: 4474 case X86::BI__builtin_ia32_cmpw128_mask: 4475 case X86::BI__builtin_ia32_cmpd128_mask: 4476 case X86::BI__builtin_ia32_cmpq128_mask: 4477 case X86::BI__builtin_ia32_cmpb256_mask: 4478 case X86::BI__builtin_ia32_cmpw256_mask: 4479 case X86::BI__builtin_ia32_cmpd256_mask: 4480 case X86::BI__builtin_ia32_cmpq256_mask: 4481 case X86::BI__builtin_ia32_cmpb512_mask: 4482 case X86::BI__builtin_ia32_cmpw512_mask: 4483 case X86::BI__builtin_ia32_cmpd512_mask: 4484 case X86::BI__builtin_ia32_cmpq512_mask: 4485 case X86::BI__builtin_ia32_ucmpb128_mask: 4486 case X86::BI__builtin_ia32_ucmpw128_mask: 4487 case X86::BI__builtin_ia32_ucmpd128_mask: 4488 case X86::BI__builtin_ia32_ucmpq128_mask: 4489 case X86::BI__builtin_ia32_ucmpb256_mask: 4490 case X86::BI__builtin_ia32_ucmpw256_mask: 4491 case X86::BI__builtin_ia32_ucmpd256_mask: 4492 case X86::BI__builtin_ia32_ucmpq256_mask: 4493 case X86::BI__builtin_ia32_ucmpb512_mask: 4494 case X86::BI__builtin_ia32_ucmpw512_mask: 4495 case X86::BI__builtin_ia32_ucmpd512_mask: 4496 case X86::BI__builtin_ia32_ucmpq512_mask: 4497 case X86::BI__builtin_ia32_vpcomub: 4498 case X86::BI__builtin_ia32_vpcomuw: 4499 case X86::BI__builtin_ia32_vpcomud: 4500 case X86::BI__builtin_ia32_vpcomuq: 4501 case X86::BI__builtin_ia32_vpcomb: 4502 case X86::BI__builtin_ia32_vpcomw: 4503 case X86::BI__builtin_ia32_vpcomd: 4504 case X86::BI__builtin_ia32_vpcomq: 4505 case X86::BI__builtin_ia32_vec_set_v8hi: 4506 case X86::BI__builtin_ia32_vec_set_v8si: 4507 i = 2; l = 0; u = 7; 4508 break; 4509 case X86::BI__builtin_ia32_vpermilpd256: 4510 case X86::BI__builtin_ia32_roundps: 4511 case X86::BI__builtin_ia32_roundpd: 4512 case X86::BI__builtin_ia32_roundps256: 4513 case X86::BI__builtin_ia32_roundpd256: 4514 case X86::BI__builtin_ia32_getmantpd128_mask: 4515 case X86::BI__builtin_ia32_getmantpd256_mask: 4516 case X86::BI__builtin_ia32_getmantps128_mask: 4517 case X86::BI__builtin_ia32_getmantps256_mask: 4518 case X86::BI__builtin_ia32_getmantpd512_mask: 4519 case X86::BI__builtin_ia32_getmantps512_mask: 4520 case X86::BI__builtin_ia32_getmantph128_mask: 4521 case X86::BI__builtin_ia32_getmantph256_mask: 4522 case X86::BI__builtin_ia32_getmantph512_mask: 4523 case X86::BI__builtin_ia32_vec_ext_v16qi: 4524 case X86::BI__builtin_ia32_vec_ext_v16hi: 4525 i = 1; l = 0; u = 15; 4526 break; 4527 case X86::BI__builtin_ia32_pblendd128: 4528 case X86::BI__builtin_ia32_blendps: 4529 case X86::BI__builtin_ia32_blendpd256: 4530 case X86::BI__builtin_ia32_shufpd256: 4531 case X86::BI__builtin_ia32_roundss: 4532 case X86::BI__builtin_ia32_roundsd: 4533 case X86::BI__builtin_ia32_rangepd128_mask: 4534 case X86::BI__builtin_ia32_rangepd256_mask: 4535 case X86::BI__builtin_ia32_rangepd512_mask: 4536 case X86::BI__builtin_ia32_rangeps128_mask: 4537 case X86::BI__builtin_ia32_rangeps256_mask: 4538 case X86::BI__builtin_ia32_rangeps512_mask: 4539 case X86::BI__builtin_ia32_getmantsd_round_mask: 4540 case X86::BI__builtin_ia32_getmantss_round_mask: 4541 case X86::BI__builtin_ia32_getmantsh_round_mask: 4542 case X86::BI__builtin_ia32_vec_set_v16qi: 4543 case X86::BI__builtin_ia32_vec_set_v16hi: 4544 i = 2; l = 0; u = 15; 4545 break; 4546 case X86::BI__builtin_ia32_vec_ext_v32qi: 4547 i = 1; l = 0; u = 31; 4548 break; 4549 case X86::BI__builtin_ia32_cmpps: 4550 case X86::BI__builtin_ia32_cmpss: 4551 case X86::BI__builtin_ia32_cmppd: 4552 case X86::BI__builtin_ia32_cmpsd: 4553 case X86::BI__builtin_ia32_cmpps256: 4554 case X86::BI__builtin_ia32_cmppd256: 4555 case X86::BI__builtin_ia32_cmpps128_mask: 4556 case X86::BI__builtin_ia32_cmppd128_mask: 4557 case X86::BI__builtin_ia32_cmpps256_mask: 4558 case X86::BI__builtin_ia32_cmppd256_mask: 4559 case X86::BI__builtin_ia32_cmpps512_mask: 4560 case X86::BI__builtin_ia32_cmppd512_mask: 4561 case X86::BI__builtin_ia32_cmpsd_mask: 4562 case X86::BI__builtin_ia32_cmpss_mask: 4563 case X86::BI__builtin_ia32_vec_set_v32qi: 4564 i = 2; l = 0; u = 31; 4565 break; 4566 case X86::BI__builtin_ia32_permdf256: 4567 case X86::BI__builtin_ia32_permdi256: 4568 case X86::BI__builtin_ia32_permdf512: 4569 case X86::BI__builtin_ia32_permdi512: 4570 case X86::BI__builtin_ia32_vpermilps: 4571 case X86::BI__builtin_ia32_vpermilps256: 4572 case X86::BI__builtin_ia32_vpermilpd512: 4573 case X86::BI__builtin_ia32_vpermilps512: 4574 case X86::BI__builtin_ia32_pshufd: 4575 case X86::BI__builtin_ia32_pshufd256: 4576 case X86::BI__builtin_ia32_pshufd512: 4577 case X86::BI__builtin_ia32_pshufhw: 4578 case X86::BI__builtin_ia32_pshufhw256: 4579 case X86::BI__builtin_ia32_pshufhw512: 4580 case X86::BI__builtin_ia32_pshuflw: 4581 case X86::BI__builtin_ia32_pshuflw256: 4582 case X86::BI__builtin_ia32_pshuflw512: 4583 case X86::BI__builtin_ia32_vcvtps2ph: 4584 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4585 case X86::BI__builtin_ia32_vcvtps2ph256: 4586 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4587 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4588 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4589 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4590 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4591 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4592 case X86::BI__builtin_ia32_rndscaleps_mask: 4593 case X86::BI__builtin_ia32_rndscalepd_mask: 4594 case X86::BI__builtin_ia32_rndscaleph_mask: 4595 case X86::BI__builtin_ia32_reducepd128_mask: 4596 case X86::BI__builtin_ia32_reducepd256_mask: 4597 case X86::BI__builtin_ia32_reducepd512_mask: 4598 case X86::BI__builtin_ia32_reduceps128_mask: 4599 case X86::BI__builtin_ia32_reduceps256_mask: 4600 case X86::BI__builtin_ia32_reduceps512_mask: 4601 case X86::BI__builtin_ia32_reduceph128_mask: 4602 case X86::BI__builtin_ia32_reduceph256_mask: 4603 case X86::BI__builtin_ia32_reduceph512_mask: 4604 case X86::BI__builtin_ia32_prold512: 4605 case X86::BI__builtin_ia32_prolq512: 4606 case X86::BI__builtin_ia32_prold128: 4607 case X86::BI__builtin_ia32_prold256: 4608 case X86::BI__builtin_ia32_prolq128: 4609 case X86::BI__builtin_ia32_prolq256: 4610 case X86::BI__builtin_ia32_prord512: 4611 case X86::BI__builtin_ia32_prorq512: 4612 case X86::BI__builtin_ia32_prord128: 4613 case X86::BI__builtin_ia32_prord256: 4614 case X86::BI__builtin_ia32_prorq128: 4615 case X86::BI__builtin_ia32_prorq256: 4616 case X86::BI__builtin_ia32_fpclasspd128_mask: 4617 case X86::BI__builtin_ia32_fpclasspd256_mask: 4618 case X86::BI__builtin_ia32_fpclassps128_mask: 4619 case X86::BI__builtin_ia32_fpclassps256_mask: 4620 case X86::BI__builtin_ia32_fpclassps512_mask: 4621 case X86::BI__builtin_ia32_fpclasspd512_mask: 4622 case X86::BI__builtin_ia32_fpclassph128_mask: 4623 case X86::BI__builtin_ia32_fpclassph256_mask: 4624 case X86::BI__builtin_ia32_fpclassph512_mask: 4625 case X86::BI__builtin_ia32_fpclasssd_mask: 4626 case X86::BI__builtin_ia32_fpclassss_mask: 4627 case X86::BI__builtin_ia32_fpclasssh_mask: 4628 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4629 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4630 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4631 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4632 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4633 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4634 case X86::BI__builtin_ia32_kshiftliqi: 4635 case X86::BI__builtin_ia32_kshiftlihi: 4636 case X86::BI__builtin_ia32_kshiftlisi: 4637 case X86::BI__builtin_ia32_kshiftlidi: 4638 case X86::BI__builtin_ia32_kshiftriqi: 4639 case X86::BI__builtin_ia32_kshiftrihi: 4640 case X86::BI__builtin_ia32_kshiftrisi: 4641 case X86::BI__builtin_ia32_kshiftridi: 4642 i = 1; l = 0; u = 255; 4643 break; 4644 case X86::BI__builtin_ia32_vperm2f128_pd256: 4645 case X86::BI__builtin_ia32_vperm2f128_ps256: 4646 case X86::BI__builtin_ia32_vperm2f128_si256: 4647 case X86::BI__builtin_ia32_permti256: 4648 case X86::BI__builtin_ia32_pblendw128: 4649 case X86::BI__builtin_ia32_pblendw256: 4650 case X86::BI__builtin_ia32_blendps256: 4651 case X86::BI__builtin_ia32_pblendd256: 4652 case X86::BI__builtin_ia32_palignr128: 4653 case X86::BI__builtin_ia32_palignr256: 4654 case X86::BI__builtin_ia32_palignr512: 4655 case X86::BI__builtin_ia32_alignq512: 4656 case X86::BI__builtin_ia32_alignd512: 4657 case X86::BI__builtin_ia32_alignd128: 4658 case X86::BI__builtin_ia32_alignd256: 4659 case X86::BI__builtin_ia32_alignq128: 4660 case X86::BI__builtin_ia32_alignq256: 4661 case X86::BI__builtin_ia32_vcomisd: 4662 case X86::BI__builtin_ia32_vcomiss: 4663 case X86::BI__builtin_ia32_shuf_f32x4: 4664 case X86::BI__builtin_ia32_shuf_f64x2: 4665 case X86::BI__builtin_ia32_shuf_i32x4: 4666 case X86::BI__builtin_ia32_shuf_i64x2: 4667 case X86::BI__builtin_ia32_shufpd512: 4668 case X86::BI__builtin_ia32_shufps: 4669 case X86::BI__builtin_ia32_shufps256: 4670 case X86::BI__builtin_ia32_shufps512: 4671 case X86::BI__builtin_ia32_dbpsadbw128: 4672 case X86::BI__builtin_ia32_dbpsadbw256: 4673 case X86::BI__builtin_ia32_dbpsadbw512: 4674 case X86::BI__builtin_ia32_vpshldd128: 4675 case X86::BI__builtin_ia32_vpshldd256: 4676 case X86::BI__builtin_ia32_vpshldd512: 4677 case X86::BI__builtin_ia32_vpshldq128: 4678 case X86::BI__builtin_ia32_vpshldq256: 4679 case X86::BI__builtin_ia32_vpshldq512: 4680 case X86::BI__builtin_ia32_vpshldw128: 4681 case X86::BI__builtin_ia32_vpshldw256: 4682 case X86::BI__builtin_ia32_vpshldw512: 4683 case X86::BI__builtin_ia32_vpshrdd128: 4684 case X86::BI__builtin_ia32_vpshrdd256: 4685 case X86::BI__builtin_ia32_vpshrdd512: 4686 case X86::BI__builtin_ia32_vpshrdq128: 4687 case X86::BI__builtin_ia32_vpshrdq256: 4688 case X86::BI__builtin_ia32_vpshrdq512: 4689 case X86::BI__builtin_ia32_vpshrdw128: 4690 case X86::BI__builtin_ia32_vpshrdw256: 4691 case X86::BI__builtin_ia32_vpshrdw512: 4692 i = 2; l = 0; u = 255; 4693 break; 4694 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4695 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4696 case X86::BI__builtin_ia32_fixupimmps512_mask: 4697 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4698 case X86::BI__builtin_ia32_fixupimmsd_mask: 4699 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4700 case X86::BI__builtin_ia32_fixupimmss_mask: 4701 case X86::BI__builtin_ia32_fixupimmss_maskz: 4702 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4703 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4704 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4705 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4706 case X86::BI__builtin_ia32_fixupimmps128_mask: 4707 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4708 case X86::BI__builtin_ia32_fixupimmps256_mask: 4709 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4710 case X86::BI__builtin_ia32_pternlogd512_mask: 4711 case X86::BI__builtin_ia32_pternlogd512_maskz: 4712 case X86::BI__builtin_ia32_pternlogq512_mask: 4713 case X86::BI__builtin_ia32_pternlogq512_maskz: 4714 case X86::BI__builtin_ia32_pternlogd128_mask: 4715 case X86::BI__builtin_ia32_pternlogd128_maskz: 4716 case X86::BI__builtin_ia32_pternlogd256_mask: 4717 case X86::BI__builtin_ia32_pternlogd256_maskz: 4718 case X86::BI__builtin_ia32_pternlogq128_mask: 4719 case X86::BI__builtin_ia32_pternlogq128_maskz: 4720 case X86::BI__builtin_ia32_pternlogq256_mask: 4721 case X86::BI__builtin_ia32_pternlogq256_maskz: 4722 i = 3; l = 0; u = 255; 4723 break; 4724 case X86::BI__builtin_ia32_gatherpfdpd: 4725 case X86::BI__builtin_ia32_gatherpfdps: 4726 case X86::BI__builtin_ia32_gatherpfqpd: 4727 case X86::BI__builtin_ia32_gatherpfqps: 4728 case X86::BI__builtin_ia32_scatterpfdpd: 4729 case X86::BI__builtin_ia32_scatterpfdps: 4730 case X86::BI__builtin_ia32_scatterpfqpd: 4731 case X86::BI__builtin_ia32_scatterpfqps: 4732 i = 4; l = 2; u = 3; 4733 break; 4734 case X86::BI__builtin_ia32_reducesd_mask: 4735 case X86::BI__builtin_ia32_reducess_mask: 4736 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4737 case X86::BI__builtin_ia32_rndscaless_round_mask: 4738 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4739 case X86::BI__builtin_ia32_reducesh_mask: 4740 i = 4; l = 0; u = 255; 4741 break; 4742 } 4743 4744 // Note that we don't force a hard error on the range check here, allowing 4745 // template-generated or macro-generated dead code to potentially have out-of- 4746 // range values. These need to code generate, but don't need to necessarily 4747 // make any sense. We use a warning that defaults to an error. 4748 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4749 } 4750 4751 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4752 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4753 /// Returns true when the format fits the function and the FormatStringInfo has 4754 /// been populated. 4755 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4756 FormatStringInfo *FSI) { 4757 FSI->HasVAListArg = Format->getFirstArg() == 0; 4758 FSI->FormatIdx = Format->getFormatIdx() - 1; 4759 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4760 4761 // The way the format attribute works in GCC, the implicit this argument 4762 // of member functions is counted. However, it doesn't appear in our own 4763 // lists, so decrement format_idx in that case. 4764 if (IsCXXMember) { 4765 if(FSI->FormatIdx == 0) 4766 return false; 4767 --FSI->FormatIdx; 4768 if (FSI->FirstDataArg != 0) 4769 --FSI->FirstDataArg; 4770 } 4771 return true; 4772 } 4773 4774 /// Checks if a the given expression evaluates to null. 4775 /// 4776 /// Returns true if the value evaluates to null. 4777 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4778 // If the expression has non-null type, it doesn't evaluate to null. 4779 if (auto nullability 4780 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4781 if (*nullability == NullabilityKind::NonNull) 4782 return false; 4783 } 4784 4785 // As a special case, transparent unions initialized with zero are 4786 // considered null for the purposes of the nonnull attribute. 4787 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4788 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4789 if (const CompoundLiteralExpr *CLE = 4790 dyn_cast<CompoundLiteralExpr>(Expr)) 4791 if (const InitListExpr *ILE = 4792 dyn_cast<InitListExpr>(CLE->getInitializer())) 4793 Expr = ILE->getInit(0); 4794 } 4795 4796 bool Result; 4797 return (!Expr->isValueDependent() && 4798 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4799 !Result); 4800 } 4801 4802 static void CheckNonNullArgument(Sema &S, 4803 const Expr *ArgExpr, 4804 SourceLocation CallSiteLoc) { 4805 if (CheckNonNullExpr(S, ArgExpr)) 4806 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4807 S.PDiag(diag::warn_null_arg) 4808 << ArgExpr->getSourceRange()); 4809 } 4810 4811 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4812 FormatStringInfo FSI; 4813 if ((GetFormatStringType(Format) == FST_NSString) && 4814 getFormatStringInfo(Format, false, &FSI)) { 4815 Idx = FSI.FormatIdx; 4816 return true; 4817 } 4818 return false; 4819 } 4820 4821 /// Diagnose use of %s directive in an NSString which is being passed 4822 /// as formatting string to formatting method. 4823 static void 4824 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4825 const NamedDecl *FDecl, 4826 Expr **Args, 4827 unsigned NumArgs) { 4828 unsigned Idx = 0; 4829 bool Format = false; 4830 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4831 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4832 Idx = 2; 4833 Format = true; 4834 } 4835 else 4836 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4837 if (S.GetFormatNSStringIdx(I, Idx)) { 4838 Format = true; 4839 break; 4840 } 4841 } 4842 if (!Format || NumArgs <= Idx) 4843 return; 4844 const Expr *FormatExpr = Args[Idx]; 4845 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4846 FormatExpr = CSCE->getSubExpr(); 4847 const StringLiteral *FormatString; 4848 if (const ObjCStringLiteral *OSL = 4849 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4850 FormatString = OSL->getString(); 4851 else 4852 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4853 if (!FormatString) 4854 return; 4855 if (S.FormatStringHasSArg(FormatString)) { 4856 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4857 << "%s" << 1 << 1; 4858 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4859 << FDecl->getDeclName(); 4860 } 4861 } 4862 4863 /// Determine whether the given type has a non-null nullability annotation. 4864 static bool isNonNullType(ASTContext &ctx, QualType type) { 4865 if (auto nullability = type->getNullability(ctx)) 4866 return *nullability == NullabilityKind::NonNull; 4867 4868 return false; 4869 } 4870 4871 static void CheckNonNullArguments(Sema &S, 4872 const NamedDecl *FDecl, 4873 const FunctionProtoType *Proto, 4874 ArrayRef<const Expr *> Args, 4875 SourceLocation CallSiteLoc) { 4876 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4877 4878 // Already checked by by constant evaluator. 4879 if (S.isConstantEvaluated()) 4880 return; 4881 // Check the attributes attached to the method/function itself. 4882 llvm::SmallBitVector NonNullArgs; 4883 if (FDecl) { 4884 // Handle the nonnull attribute on the function/method declaration itself. 4885 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4886 if (!NonNull->args_size()) { 4887 // Easy case: all pointer arguments are nonnull. 4888 for (const auto *Arg : Args) 4889 if (S.isValidPointerAttrType(Arg->getType())) 4890 CheckNonNullArgument(S, Arg, CallSiteLoc); 4891 return; 4892 } 4893 4894 for (const ParamIdx &Idx : NonNull->args()) { 4895 unsigned IdxAST = Idx.getASTIndex(); 4896 if (IdxAST >= Args.size()) 4897 continue; 4898 if (NonNullArgs.empty()) 4899 NonNullArgs.resize(Args.size()); 4900 NonNullArgs.set(IdxAST); 4901 } 4902 } 4903 } 4904 4905 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4906 // Handle the nonnull attribute on the parameters of the 4907 // function/method. 4908 ArrayRef<ParmVarDecl*> parms; 4909 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4910 parms = FD->parameters(); 4911 else 4912 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4913 4914 unsigned ParamIndex = 0; 4915 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4916 I != E; ++I, ++ParamIndex) { 4917 const ParmVarDecl *PVD = *I; 4918 if (PVD->hasAttr<NonNullAttr>() || 4919 isNonNullType(S.Context, PVD->getType())) { 4920 if (NonNullArgs.empty()) 4921 NonNullArgs.resize(Args.size()); 4922 4923 NonNullArgs.set(ParamIndex); 4924 } 4925 } 4926 } else { 4927 // If we have a non-function, non-method declaration but no 4928 // function prototype, try to dig out the function prototype. 4929 if (!Proto) { 4930 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4931 QualType type = VD->getType().getNonReferenceType(); 4932 if (auto pointerType = type->getAs<PointerType>()) 4933 type = pointerType->getPointeeType(); 4934 else if (auto blockType = type->getAs<BlockPointerType>()) 4935 type = blockType->getPointeeType(); 4936 // FIXME: data member pointers? 4937 4938 // Dig out the function prototype, if there is one. 4939 Proto = type->getAs<FunctionProtoType>(); 4940 } 4941 } 4942 4943 // Fill in non-null argument information from the nullability 4944 // information on the parameter types (if we have them). 4945 if (Proto) { 4946 unsigned Index = 0; 4947 for (auto paramType : Proto->getParamTypes()) { 4948 if (isNonNullType(S.Context, paramType)) { 4949 if (NonNullArgs.empty()) 4950 NonNullArgs.resize(Args.size()); 4951 4952 NonNullArgs.set(Index); 4953 } 4954 4955 ++Index; 4956 } 4957 } 4958 } 4959 4960 // Check for non-null arguments. 4961 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4962 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4963 if (NonNullArgs[ArgIndex]) 4964 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4965 } 4966 } 4967 4968 /// Warn if a pointer or reference argument passed to a function points to an 4969 /// object that is less aligned than the parameter. This can happen when 4970 /// creating a typedef with a lower alignment than the original type and then 4971 /// calling functions defined in terms of the original type. 4972 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4973 StringRef ParamName, QualType ArgTy, 4974 QualType ParamTy) { 4975 4976 // If a function accepts a pointer or reference type 4977 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4978 return; 4979 4980 // If the parameter is a pointer type, get the pointee type for the 4981 // argument too. If the parameter is a reference type, don't try to get 4982 // the pointee type for the argument. 4983 if (ParamTy->isPointerType()) 4984 ArgTy = ArgTy->getPointeeType(); 4985 4986 // Remove reference or pointer 4987 ParamTy = ParamTy->getPointeeType(); 4988 4989 // Find expected alignment, and the actual alignment of the passed object. 4990 // getTypeAlignInChars requires complete types 4991 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 4992 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 4993 ArgTy->isUndeducedType()) 4994 return; 4995 4996 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 4997 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 4998 4999 // If the argument is less aligned than the parameter, there is a 5000 // potential alignment issue. 5001 if (ArgAlign < ParamAlign) 5002 Diag(Loc, diag::warn_param_mismatched_alignment) 5003 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 5004 << ParamName << FDecl; 5005 } 5006 5007 /// Handles the checks for format strings, non-POD arguments to vararg 5008 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 5009 /// attributes. 5010 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 5011 const Expr *ThisArg, ArrayRef<const Expr *> Args, 5012 bool IsMemberFunction, SourceLocation Loc, 5013 SourceRange Range, VariadicCallType CallType) { 5014 // FIXME: We should check as much as we can in the template definition. 5015 if (CurContext->isDependentContext()) 5016 return; 5017 5018 // Printf and scanf checking. 5019 llvm::SmallBitVector CheckedVarArgs; 5020 if (FDecl) { 5021 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5022 // Only create vector if there are format attributes. 5023 CheckedVarArgs.resize(Args.size()); 5024 5025 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 5026 CheckedVarArgs); 5027 } 5028 } 5029 5030 // Refuse POD arguments that weren't caught by the format string 5031 // checks above. 5032 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 5033 if (CallType != VariadicDoesNotApply && 5034 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 5035 unsigned NumParams = Proto ? Proto->getNumParams() 5036 : FDecl && isa<FunctionDecl>(FDecl) 5037 ? cast<FunctionDecl>(FDecl)->getNumParams() 5038 : FDecl && isa<ObjCMethodDecl>(FDecl) 5039 ? cast<ObjCMethodDecl>(FDecl)->param_size() 5040 : 0; 5041 5042 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 5043 // Args[ArgIdx] can be null in malformed code. 5044 if (const Expr *Arg = Args[ArgIdx]) { 5045 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 5046 checkVariadicArgument(Arg, CallType); 5047 } 5048 } 5049 } 5050 5051 if (FDecl || Proto) { 5052 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 5053 5054 // Type safety checking. 5055 if (FDecl) { 5056 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 5057 CheckArgumentWithTypeTag(I, Args, Loc); 5058 } 5059 } 5060 5061 // Check that passed arguments match the alignment of original arguments. 5062 // Try to get the missing prototype from the declaration. 5063 if (!Proto && FDecl) { 5064 const auto *FT = FDecl->getFunctionType(); 5065 if (isa_and_nonnull<FunctionProtoType>(FT)) 5066 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 5067 } 5068 if (Proto) { 5069 // For variadic functions, we may have more args than parameters. 5070 // For some K&R functions, we may have less args than parameters. 5071 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 5072 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 5073 // Args[ArgIdx] can be null in malformed code. 5074 if (const Expr *Arg = Args[ArgIdx]) { 5075 if (Arg->containsErrors()) 5076 continue; 5077 5078 QualType ParamTy = Proto->getParamType(ArgIdx); 5079 QualType ArgTy = Arg->getType(); 5080 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 5081 ArgTy, ParamTy); 5082 } 5083 } 5084 } 5085 5086 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 5087 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 5088 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 5089 if (!Arg->isValueDependent()) { 5090 Expr::EvalResult Align; 5091 if (Arg->EvaluateAsInt(Align, Context)) { 5092 const llvm::APSInt &I = Align.Val.getInt(); 5093 if (!I.isPowerOf2()) 5094 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 5095 << Arg->getSourceRange(); 5096 5097 if (I > Sema::MaximumAlignment) 5098 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 5099 << Arg->getSourceRange() << Sema::MaximumAlignment; 5100 } 5101 } 5102 } 5103 5104 if (FD) 5105 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 5106 } 5107 5108 /// CheckConstructorCall - Check a constructor call for correctness and safety 5109 /// properties not enforced by the C type system. 5110 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 5111 ArrayRef<const Expr *> Args, 5112 const FunctionProtoType *Proto, 5113 SourceLocation Loc) { 5114 VariadicCallType CallType = 5115 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5116 5117 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 5118 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 5119 Context.getPointerType(Ctor->getThisObjectType())); 5120 5121 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 5122 Loc, SourceRange(), CallType); 5123 } 5124 5125 /// CheckFunctionCall - Check a direct function call for various correctness 5126 /// and safety properties not strictly enforced by the C type system. 5127 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 5128 const FunctionProtoType *Proto) { 5129 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 5130 isa<CXXMethodDecl>(FDecl); 5131 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 5132 IsMemberOperatorCall; 5133 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 5134 TheCall->getCallee()); 5135 Expr** Args = TheCall->getArgs(); 5136 unsigned NumArgs = TheCall->getNumArgs(); 5137 5138 Expr *ImplicitThis = nullptr; 5139 if (IsMemberOperatorCall) { 5140 // If this is a call to a member operator, hide the first argument 5141 // from checkCall. 5142 // FIXME: Our choice of AST representation here is less than ideal. 5143 ImplicitThis = Args[0]; 5144 ++Args; 5145 --NumArgs; 5146 } else if (IsMemberFunction) 5147 ImplicitThis = 5148 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 5149 5150 if (ImplicitThis) { 5151 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 5152 // used. 5153 QualType ThisType = ImplicitThis->getType(); 5154 if (!ThisType->isPointerType()) { 5155 assert(!ThisType->isReferenceType()); 5156 ThisType = Context.getPointerType(ThisType); 5157 } 5158 5159 QualType ThisTypeFromDecl = 5160 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5161 5162 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5163 ThisTypeFromDecl); 5164 } 5165 5166 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5167 IsMemberFunction, TheCall->getRParenLoc(), 5168 TheCall->getCallee()->getSourceRange(), CallType); 5169 5170 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5171 // None of the checks below are needed for functions that don't have 5172 // simple names (e.g., C++ conversion functions). 5173 if (!FnInfo) 5174 return false; 5175 5176 CheckTCBEnforcement(TheCall, FDecl); 5177 5178 CheckAbsoluteValueFunction(TheCall, FDecl); 5179 CheckMaxUnsignedZero(TheCall, FDecl); 5180 5181 if (getLangOpts().ObjC) 5182 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5183 5184 unsigned CMId = FDecl->getMemoryFunctionKind(); 5185 5186 // Handle memory setting and copying functions. 5187 switch (CMId) { 5188 case 0: 5189 return false; 5190 case Builtin::BIstrlcpy: // fallthrough 5191 case Builtin::BIstrlcat: 5192 CheckStrlcpycatArguments(TheCall, FnInfo); 5193 break; 5194 case Builtin::BIstrncat: 5195 CheckStrncatArguments(TheCall, FnInfo); 5196 break; 5197 case Builtin::BIfree: 5198 CheckFreeArguments(TheCall); 5199 break; 5200 default: 5201 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5202 } 5203 5204 return false; 5205 } 5206 5207 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5208 ArrayRef<const Expr *> Args) { 5209 VariadicCallType CallType = 5210 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5211 5212 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5213 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5214 CallType); 5215 5216 return false; 5217 } 5218 5219 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5220 const FunctionProtoType *Proto) { 5221 QualType Ty; 5222 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5223 Ty = V->getType().getNonReferenceType(); 5224 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5225 Ty = F->getType().getNonReferenceType(); 5226 else 5227 return false; 5228 5229 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5230 !Ty->isFunctionProtoType()) 5231 return false; 5232 5233 VariadicCallType CallType; 5234 if (!Proto || !Proto->isVariadic()) { 5235 CallType = VariadicDoesNotApply; 5236 } else if (Ty->isBlockPointerType()) { 5237 CallType = VariadicBlock; 5238 } else { // Ty->isFunctionPointerType() 5239 CallType = VariadicFunction; 5240 } 5241 5242 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5243 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5244 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5245 TheCall->getCallee()->getSourceRange(), CallType); 5246 5247 return false; 5248 } 5249 5250 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5251 /// such as function pointers returned from functions. 5252 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5253 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5254 TheCall->getCallee()); 5255 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5256 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5257 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5258 TheCall->getCallee()->getSourceRange(), CallType); 5259 5260 return false; 5261 } 5262 5263 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5264 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5265 return false; 5266 5267 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5268 switch (Op) { 5269 case AtomicExpr::AO__c11_atomic_init: 5270 case AtomicExpr::AO__opencl_atomic_init: 5271 llvm_unreachable("There is no ordering argument for an init"); 5272 5273 case AtomicExpr::AO__c11_atomic_load: 5274 case AtomicExpr::AO__opencl_atomic_load: 5275 case AtomicExpr::AO__atomic_load_n: 5276 case AtomicExpr::AO__atomic_load: 5277 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5278 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5279 5280 case AtomicExpr::AO__c11_atomic_store: 5281 case AtomicExpr::AO__opencl_atomic_store: 5282 case AtomicExpr::AO__atomic_store: 5283 case AtomicExpr::AO__atomic_store_n: 5284 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5285 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5286 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5287 5288 default: 5289 return true; 5290 } 5291 } 5292 5293 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5294 AtomicExpr::AtomicOp Op) { 5295 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5296 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5297 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5298 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5299 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5300 Op); 5301 } 5302 5303 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5304 SourceLocation RParenLoc, MultiExprArg Args, 5305 AtomicExpr::AtomicOp Op, 5306 AtomicArgumentOrder ArgOrder) { 5307 // All the non-OpenCL operations take one of the following forms. 5308 // The OpenCL operations take the __c11 forms with one extra argument for 5309 // synchronization scope. 5310 enum { 5311 // C __c11_atomic_init(A *, C) 5312 Init, 5313 5314 // C __c11_atomic_load(A *, int) 5315 Load, 5316 5317 // void __atomic_load(A *, CP, int) 5318 LoadCopy, 5319 5320 // void __atomic_store(A *, CP, int) 5321 Copy, 5322 5323 // C __c11_atomic_add(A *, M, int) 5324 Arithmetic, 5325 5326 // C __atomic_exchange_n(A *, CP, int) 5327 Xchg, 5328 5329 // void __atomic_exchange(A *, C *, CP, int) 5330 GNUXchg, 5331 5332 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5333 C11CmpXchg, 5334 5335 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5336 GNUCmpXchg 5337 } Form = Init; 5338 5339 const unsigned NumForm = GNUCmpXchg + 1; 5340 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5341 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5342 // where: 5343 // C is an appropriate type, 5344 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5345 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5346 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5347 // the int parameters are for orderings. 5348 5349 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5350 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5351 "need to update code for modified forms"); 5352 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5353 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5354 AtomicExpr::AO__atomic_load, 5355 "need to update code for modified C11 atomics"); 5356 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5357 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5358 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5359 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5360 IsOpenCL; 5361 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5362 Op == AtomicExpr::AO__atomic_store_n || 5363 Op == AtomicExpr::AO__atomic_exchange_n || 5364 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5365 bool IsAddSub = false; 5366 5367 switch (Op) { 5368 case AtomicExpr::AO__c11_atomic_init: 5369 case AtomicExpr::AO__opencl_atomic_init: 5370 Form = Init; 5371 break; 5372 5373 case AtomicExpr::AO__c11_atomic_load: 5374 case AtomicExpr::AO__opencl_atomic_load: 5375 case AtomicExpr::AO__atomic_load_n: 5376 Form = Load; 5377 break; 5378 5379 case AtomicExpr::AO__atomic_load: 5380 Form = LoadCopy; 5381 break; 5382 5383 case AtomicExpr::AO__c11_atomic_store: 5384 case AtomicExpr::AO__opencl_atomic_store: 5385 case AtomicExpr::AO__atomic_store: 5386 case AtomicExpr::AO__atomic_store_n: 5387 Form = Copy; 5388 break; 5389 5390 case AtomicExpr::AO__c11_atomic_fetch_add: 5391 case AtomicExpr::AO__c11_atomic_fetch_sub: 5392 case AtomicExpr::AO__opencl_atomic_fetch_add: 5393 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5394 case AtomicExpr::AO__atomic_fetch_add: 5395 case AtomicExpr::AO__atomic_fetch_sub: 5396 case AtomicExpr::AO__atomic_add_fetch: 5397 case AtomicExpr::AO__atomic_sub_fetch: 5398 IsAddSub = true; 5399 Form = Arithmetic; 5400 break; 5401 case AtomicExpr::AO__c11_atomic_fetch_and: 5402 case AtomicExpr::AO__c11_atomic_fetch_or: 5403 case AtomicExpr::AO__c11_atomic_fetch_xor: 5404 case AtomicExpr::AO__opencl_atomic_fetch_and: 5405 case AtomicExpr::AO__opencl_atomic_fetch_or: 5406 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5407 case AtomicExpr::AO__atomic_fetch_and: 5408 case AtomicExpr::AO__atomic_fetch_or: 5409 case AtomicExpr::AO__atomic_fetch_xor: 5410 case AtomicExpr::AO__atomic_fetch_nand: 5411 case AtomicExpr::AO__atomic_and_fetch: 5412 case AtomicExpr::AO__atomic_or_fetch: 5413 case AtomicExpr::AO__atomic_xor_fetch: 5414 case AtomicExpr::AO__atomic_nand_fetch: 5415 Form = Arithmetic; 5416 break; 5417 case AtomicExpr::AO__c11_atomic_fetch_min: 5418 case AtomicExpr::AO__c11_atomic_fetch_max: 5419 case AtomicExpr::AO__opencl_atomic_fetch_min: 5420 case AtomicExpr::AO__opencl_atomic_fetch_max: 5421 case AtomicExpr::AO__atomic_min_fetch: 5422 case AtomicExpr::AO__atomic_max_fetch: 5423 case AtomicExpr::AO__atomic_fetch_min: 5424 case AtomicExpr::AO__atomic_fetch_max: 5425 Form = Arithmetic; 5426 break; 5427 5428 case AtomicExpr::AO__c11_atomic_exchange: 5429 case AtomicExpr::AO__opencl_atomic_exchange: 5430 case AtomicExpr::AO__atomic_exchange_n: 5431 Form = Xchg; 5432 break; 5433 5434 case AtomicExpr::AO__atomic_exchange: 5435 Form = GNUXchg; 5436 break; 5437 5438 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5439 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5440 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5441 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5442 Form = C11CmpXchg; 5443 break; 5444 5445 case AtomicExpr::AO__atomic_compare_exchange: 5446 case AtomicExpr::AO__atomic_compare_exchange_n: 5447 Form = GNUCmpXchg; 5448 break; 5449 } 5450 5451 unsigned AdjustedNumArgs = NumArgs[Form]; 5452 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 5453 ++AdjustedNumArgs; 5454 // Check we have the right number of arguments. 5455 if (Args.size() < AdjustedNumArgs) { 5456 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5457 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5458 << ExprRange; 5459 return ExprError(); 5460 } else if (Args.size() > AdjustedNumArgs) { 5461 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5462 diag::err_typecheck_call_too_many_args) 5463 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5464 << ExprRange; 5465 return ExprError(); 5466 } 5467 5468 // Inspect the first argument of the atomic operation. 5469 Expr *Ptr = Args[0]; 5470 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5471 if (ConvertedPtr.isInvalid()) 5472 return ExprError(); 5473 5474 Ptr = ConvertedPtr.get(); 5475 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5476 if (!pointerType) { 5477 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5478 << Ptr->getType() << Ptr->getSourceRange(); 5479 return ExprError(); 5480 } 5481 5482 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5483 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5484 QualType ValType = AtomTy; // 'C' 5485 if (IsC11) { 5486 if (!AtomTy->isAtomicType()) { 5487 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5488 << Ptr->getType() << Ptr->getSourceRange(); 5489 return ExprError(); 5490 } 5491 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5492 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5493 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5494 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5495 << Ptr->getSourceRange(); 5496 return ExprError(); 5497 } 5498 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5499 } else if (Form != Load && Form != LoadCopy) { 5500 if (ValType.isConstQualified()) { 5501 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5502 << Ptr->getType() << Ptr->getSourceRange(); 5503 return ExprError(); 5504 } 5505 } 5506 5507 // For an arithmetic operation, the implied arithmetic must be well-formed. 5508 if (Form == Arithmetic) { 5509 // gcc does not enforce these rules for GNU atomics, but we do so for 5510 // sanity. 5511 auto IsAllowedValueType = [&](QualType ValType) { 5512 if (ValType->isIntegerType()) 5513 return true; 5514 if (ValType->isPointerType()) 5515 return true; 5516 if (!ValType->isFloatingType()) 5517 return false; 5518 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5519 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5520 &Context.getTargetInfo().getLongDoubleFormat() == 5521 &llvm::APFloat::x87DoubleExtended()) 5522 return false; 5523 return true; 5524 }; 5525 if (IsAddSub && !IsAllowedValueType(ValType)) { 5526 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5527 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5528 return ExprError(); 5529 } 5530 if (!IsAddSub && !ValType->isIntegerType()) { 5531 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5532 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5533 return ExprError(); 5534 } 5535 if (IsC11 && ValType->isPointerType() && 5536 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5537 diag::err_incomplete_type)) { 5538 return ExprError(); 5539 } 5540 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5541 // For __atomic_*_n operations, the value type must be a scalar integral or 5542 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5543 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5544 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5545 return ExprError(); 5546 } 5547 5548 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5549 !AtomTy->isScalarType()) { 5550 // For GNU atomics, require a trivially-copyable type. This is not part of 5551 // the GNU atomics specification, but we enforce it for sanity. 5552 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5553 << Ptr->getType() << Ptr->getSourceRange(); 5554 return ExprError(); 5555 } 5556 5557 switch (ValType.getObjCLifetime()) { 5558 case Qualifiers::OCL_None: 5559 case Qualifiers::OCL_ExplicitNone: 5560 // okay 5561 break; 5562 5563 case Qualifiers::OCL_Weak: 5564 case Qualifiers::OCL_Strong: 5565 case Qualifiers::OCL_Autoreleasing: 5566 // FIXME: Can this happen? By this point, ValType should be known 5567 // to be trivially copyable. 5568 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5569 << ValType << Ptr->getSourceRange(); 5570 return ExprError(); 5571 } 5572 5573 // All atomic operations have an overload which takes a pointer to a volatile 5574 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5575 // into the result or the other operands. Similarly atomic_load takes a 5576 // pointer to a const 'A'. 5577 ValType.removeLocalVolatile(); 5578 ValType.removeLocalConst(); 5579 QualType ResultType = ValType; 5580 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5581 Form == Init) 5582 ResultType = Context.VoidTy; 5583 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5584 ResultType = Context.BoolTy; 5585 5586 // The type of a parameter passed 'by value'. In the GNU atomics, such 5587 // arguments are actually passed as pointers. 5588 QualType ByValType = ValType; // 'CP' 5589 bool IsPassedByAddress = false; 5590 if (!IsC11 && !IsN) { 5591 ByValType = Ptr->getType(); 5592 IsPassedByAddress = true; 5593 } 5594 5595 SmallVector<Expr *, 5> APIOrderedArgs; 5596 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5597 APIOrderedArgs.push_back(Args[0]); 5598 switch (Form) { 5599 case Init: 5600 case Load: 5601 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5602 break; 5603 case LoadCopy: 5604 case Copy: 5605 case Arithmetic: 5606 case Xchg: 5607 APIOrderedArgs.push_back(Args[2]); // Val1 5608 APIOrderedArgs.push_back(Args[1]); // Order 5609 break; 5610 case GNUXchg: 5611 APIOrderedArgs.push_back(Args[2]); // Val1 5612 APIOrderedArgs.push_back(Args[3]); // Val2 5613 APIOrderedArgs.push_back(Args[1]); // Order 5614 break; 5615 case C11CmpXchg: 5616 APIOrderedArgs.push_back(Args[2]); // Val1 5617 APIOrderedArgs.push_back(Args[4]); // Val2 5618 APIOrderedArgs.push_back(Args[1]); // Order 5619 APIOrderedArgs.push_back(Args[3]); // OrderFail 5620 break; 5621 case GNUCmpXchg: 5622 APIOrderedArgs.push_back(Args[2]); // Val1 5623 APIOrderedArgs.push_back(Args[4]); // Val2 5624 APIOrderedArgs.push_back(Args[5]); // Weak 5625 APIOrderedArgs.push_back(Args[1]); // Order 5626 APIOrderedArgs.push_back(Args[3]); // OrderFail 5627 break; 5628 } 5629 } else 5630 APIOrderedArgs.append(Args.begin(), Args.end()); 5631 5632 // The first argument's non-CV pointer type is used to deduce the type of 5633 // subsequent arguments, except for: 5634 // - weak flag (always converted to bool) 5635 // - memory order (always converted to int) 5636 // - scope (always converted to int) 5637 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5638 QualType Ty; 5639 if (i < NumVals[Form] + 1) { 5640 switch (i) { 5641 case 0: 5642 // The first argument is always a pointer. It has a fixed type. 5643 // It is always dereferenced, a nullptr is undefined. 5644 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5645 // Nothing else to do: we already know all we want about this pointer. 5646 continue; 5647 case 1: 5648 // The second argument is the non-atomic operand. For arithmetic, this 5649 // is always passed by value, and for a compare_exchange it is always 5650 // passed by address. For the rest, GNU uses by-address and C11 uses 5651 // by-value. 5652 assert(Form != Load); 5653 if (Form == Arithmetic && ValType->isPointerType()) 5654 Ty = Context.getPointerDiffType(); 5655 else if (Form == Init || Form == Arithmetic) 5656 Ty = ValType; 5657 else if (Form == Copy || Form == Xchg) { 5658 if (IsPassedByAddress) { 5659 // The value pointer is always dereferenced, a nullptr is undefined. 5660 CheckNonNullArgument(*this, APIOrderedArgs[i], 5661 ExprRange.getBegin()); 5662 } 5663 Ty = ByValType; 5664 } else { 5665 Expr *ValArg = APIOrderedArgs[i]; 5666 // The value pointer is always dereferenced, a nullptr is undefined. 5667 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5668 LangAS AS = LangAS::Default; 5669 // Keep address space of non-atomic pointer type. 5670 if (const PointerType *PtrTy = 5671 ValArg->getType()->getAs<PointerType>()) { 5672 AS = PtrTy->getPointeeType().getAddressSpace(); 5673 } 5674 Ty = Context.getPointerType( 5675 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5676 } 5677 break; 5678 case 2: 5679 // The third argument to compare_exchange / GNU exchange is the desired 5680 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5681 if (IsPassedByAddress) 5682 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5683 Ty = ByValType; 5684 break; 5685 case 3: 5686 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5687 Ty = Context.BoolTy; 5688 break; 5689 } 5690 } else { 5691 // The order(s) and scope are always converted to int. 5692 Ty = Context.IntTy; 5693 } 5694 5695 InitializedEntity Entity = 5696 InitializedEntity::InitializeParameter(Context, Ty, false); 5697 ExprResult Arg = APIOrderedArgs[i]; 5698 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5699 if (Arg.isInvalid()) 5700 return true; 5701 APIOrderedArgs[i] = Arg.get(); 5702 } 5703 5704 // Permute the arguments into a 'consistent' order. 5705 SmallVector<Expr*, 5> SubExprs; 5706 SubExprs.push_back(Ptr); 5707 switch (Form) { 5708 case Init: 5709 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5710 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5711 break; 5712 case Load: 5713 SubExprs.push_back(APIOrderedArgs[1]); // Order 5714 break; 5715 case LoadCopy: 5716 case Copy: 5717 case Arithmetic: 5718 case Xchg: 5719 SubExprs.push_back(APIOrderedArgs[2]); // Order 5720 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5721 break; 5722 case GNUXchg: 5723 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5724 SubExprs.push_back(APIOrderedArgs[3]); // Order 5725 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5726 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5727 break; 5728 case C11CmpXchg: 5729 SubExprs.push_back(APIOrderedArgs[3]); // Order 5730 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5731 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5732 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5733 break; 5734 case GNUCmpXchg: 5735 SubExprs.push_back(APIOrderedArgs[4]); // Order 5736 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5737 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5738 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5739 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5740 break; 5741 } 5742 5743 if (SubExprs.size() >= 2 && Form != Init) { 5744 if (Optional<llvm::APSInt> Result = 5745 SubExprs[1]->getIntegerConstantExpr(Context)) 5746 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5747 Diag(SubExprs[1]->getBeginLoc(), 5748 diag::warn_atomic_op_has_invalid_memory_order) 5749 << SubExprs[1]->getSourceRange(); 5750 } 5751 5752 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5753 auto *Scope = Args[Args.size() - 1]; 5754 if (Optional<llvm::APSInt> Result = 5755 Scope->getIntegerConstantExpr(Context)) { 5756 if (!ScopeModel->isValid(Result->getZExtValue())) 5757 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5758 << Scope->getSourceRange(); 5759 } 5760 SubExprs.push_back(Scope); 5761 } 5762 5763 AtomicExpr *AE = new (Context) 5764 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5765 5766 if ((Op == AtomicExpr::AO__c11_atomic_load || 5767 Op == AtomicExpr::AO__c11_atomic_store || 5768 Op == AtomicExpr::AO__opencl_atomic_load || 5769 Op == AtomicExpr::AO__opencl_atomic_store ) && 5770 Context.AtomicUsesUnsupportedLibcall(AE)) 5771 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5772 << ((Op == AtomicExpr::AO__c11_atomic_load || 5773 Op == AtomicExpr::AO__opencl_atomic_load) 5774 ? 0 5775 : 1); 5776 5777 if (ValType->isExtIntType()) { 5778 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5779 return ExprError(); 5780 } 5781 5782 return AE; 5783 } 5784 5785 /// checkBuiltinArgument - Given a call to a builtin function, perform 5786 /// normal type-checking on the given argument, updating the call in 5787 /// place. This is useful when a builtin function requires custom 5788 /// type-checking for some of its arguments but not necessarily all of 5789 /// them. 5790 /// 5791 /// Returns true on error. 5792 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5793 FunctionDecl *Fn = E->getDirectCallee(); 5794 assert(Fn && "builtin call without direct callee!"); 5795 5796 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5797 InitializedEntity Entity = 5798 InitializedEntity::InitializeParameter(S.Context, Param); 5799 5800 ExprResult Arg = E->getArg(0); 5801 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5802 if (Arg.isInvalid()) 5803 return true; 5804 5805 E->setArg(ArgIndex, Arg.get()); 5806 return false; 5807 } 5808 5809 /// We have a call to a function like __sync_fetch_and_add, which is an 5810 /// overloaded function based on the pointer type of its first argument. 5811 /// The main BuildCallExpr routines have already promoted the types of 5812 /// arguments because all of these calls are prototyped as void(...). 5813 /// 5814 /// This function goes through and does final semantic checking for these 5815 /// builtins, as well as generating any warnings. 5816 ExprResult 5817 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5818 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5819 Expr *Callee = TheCall->getCallee(); 5820 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5821 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5822 5823 // Ensure that we have at least one argument to do type inference from. 5824 if (TheCall->getNumArgs() < 1) { 5825 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5826 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5827 return ExprError(); 5828 } 5829 5830 // Inspect the first argument of the atomic builtin. This should always be 5831 // a pointer type, whose element is an integral scalar or pointer type. 5832 // Because it is a pointer type, we don't have to worry about any implicit 5833 // casts here. 5834 // FIXME: We don't allow floating point scalars as input. 5835 Expr *FirstArg = TheCall->getArg(0); 5836 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5837 if (FirstArgResult.isInvalid()) 5838 return ExprError(); 5839 FirstArg = FirstArgResult.get(); 5840 TheCall->setArg(0, FirstArg); 5841 5842 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5843 if (!pointerType) { 5844 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5845 << FirstArg->getType() << FirstArg->getSourceRange(); 5846 return ExprError(); 5847 } 5848 5849 QualType ValType = pointerType->getPointeeType(); 5850 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5851 !ValType->isBlockPointerType()) { 5852 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5853 << FirstArg->getType() << FirstArg->getSourceRange(); 5854 return ExprError(); 5855 } 5856 5857 if (ValType.isConstQualified()) { 5858 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5859 << FirstArg->getType() << FirstArg->getSourceRange(); 5860 return ExprError(); 5861 } 5862 5863 switch (ValType.getObjCLifetime()) { 5864 case Qualifiers::OCL_None: 5865 case Qualifiers::OCL_ExplicitNone: 5866 // okay 5867 break; 5868 5869 case Qualifiers::OCL_Weak: 5870 case Qualifiers::OCL_Strong: 5871 case Qualifiers::OCL_Autoreleasing: 5872 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5873 << ValType << FirstArg->getSourceRange(); 5874 return ExprError(); 5875 } 5876 5877 // Strip any qualifiers off ValType. 5878 ValType = ValType.getUnqualifiedType(); 5879 5880 // The majority of builtins return a value, but a few have special return 5881 // types, so allow them to override appropriately below. 5882 QualType ResultType = ValType; 5883 5884 // We need to figure out which concrete builtin this maps onto. For example, 5885 // __sync_fetch_and_add with a 2 byte object turns into 5886 // __sync_fetch_and_add_2. 5887 #define BUILTIN_ROW(x) \ 5888 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5889 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5890 5891 static const unsigned BuiltinIndices[][5] = { 5892 BUILTIN_ROW(__sync_fetch_and_add), 5893 BUILTIN_ROW(__sync_fetch_and_sub), 5894 BUILTIN_ROW(__sync_fetch_and_or), 5895 BUILTIN_ROW(__sync_fetch_and_and), 5896 BUILTIN_ROW(__sync_fetch_and_xor), 5897 BUILTIN_ROW(__sync_fetch_and_nand), 5898 5899 BUILTIN_ROW(__sync_add_and_fetch), 5900 BUILTIN_ROW(__sync_sub_and_fetch), 5901 BUILTIN_ROW(__sync_and_and_fetch), 5902 BUILTIN_ROW(__sync_or_and_fetch), 5903 BUILTIN_ROW(__sync_xor_and_fetch), 5904 BUILTIN_ROW(__sync_nand_and_fetch), 5905 5906 BUILTIN_ROW(__sync_val_compare_and_swap), 5907 BUILTIN_ROW(__sync_bool_compare_and_swap), 5908 BUILTIN_ROW(__sync_lock_test_and_set), 5909 BUILTIN_ROW(__sync_lock_release), 5910 BUILTIN_ROW(__sync_swap) 5911 }; 5912 #undef BUILTIN_ROW 5913 5914 // Determine the index of the size. 5915 unsigned SizeIndex; 5916 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5917 case 1: SizeIndex = 0; break; 5918 case 2: SizeIndex = 1; break; 5919 case 4: SizeIndex = 2; break; 5920 case 8: SizeIndex = 3; break; 5921 case 16: SizeIndex = 4; break; 5922 default: 5923 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5924 << FirstArg->getType() << FirstArg->getSourceRange(); 5925 return ExprError(); 5926 } 5927 5928 // Each of these builtins has one pointer argument, followed by some number of 5929 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5930 // that we ignore. Find out which row of BuiltinIndices to read from as well 5931 // as the number of fixed args. 5932 unsigned BuiltinID = FDecl->getBuiltinID(); 5933 unsigned BuiltinIndex, NumFixed = 1; 5934 bool WarnAboutSemanticsChange = false; 5935 switch (BuiltinID) { 5936 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5937 case Builtin::BI__sync_fetch_and_add: 5938 case Builtin::BI__sync_fetch_and_add_1: 5939 case Builtin::BI__sync_fetch_and_add_2: 5940 case Builtin::BI__sync_fetch_and_add_4: 5941 case Builtin::BI__sync_fetch_and_add_8: 5942 case Builtin::BI__sync_fetch_and_add_16: 5943 BuiltinIndex = 0; 5944 break; 5945 5946 case Builtin::BI__sync_fetch_and_sub: 5947 case Builtin::BI__sync_fetch_and_sub_1: 5948 case Builtin::BI__sync_fetch_and_sub_2: 5949 case Builtin::BI__sync_fetch_and_sub_4: 5950 case Builtin::BI__sync_fetch_and_sub_8: 5951 case Builtin::BI__sync_fetch_and_sub_16: 5952 BuiltinIndex = 1; 5953 break; 5954 5955 case Builtin::BI__sync_fetch_and_or: 5956 case Builtin::BI__sync_fetch_and_or_1: 5957 case Builtin::BI__sync_fetch_and_or_2: 5958 case Builtin::BI__sync_fetch_and_or_4: 5959 case Builtin::BI__sync_fetch_and_or_8: 5960 case Builtin::BI__sync_fetch_and_or_16: 5961 BuiltinIndex = 2; 5962 break; 5963 5964 case Builtin::BI__sync_fetch_and_and: 5965 case Builtin::BI__sync_fetch_and_and_1: 5966 case Builtin::BI__sync_fetch_and_and_2: 5967 case Builtin::BI__sync_fetch_and_and_4: 5968 case Builtin::BI__sync_fetch_and_and_8: 5969 case Builtin::BI__sync_fetch_and_and_16: 5970 BuiltinIndex = 3; 5971 break; 5972 5973 case Builtin::BI__sync_fetch_and_xor: 5974 case Builtin::BI__sync_fetch_and_xor_1: 5975 case Builtin::BI__sync_fetch_and_xor_2: 5976 case Builtin::BI__sync_fetch_and_xor_4: 5977 case Builtin::BI__sync_fetch_and_xor_8: 5978 case Builtin::BI__sync_fetch_and_xor_16: 5979 BuiltinIndex = 4; 5980 break; 5981 5982 case Builtin::BI__sync_fetch_and_nand: 5983 case Builtin::BI__sync_fetch_and_nand_1: 5984 case Builtin::BI__sync_fetch_and_nand_2: 5985 case Builtin::BI__sync_fetch_and_nand_4: 5986 case Builtin::BI__sync_fetch_and_nand_8: 5987 case Builtin::BI__sync_fetch_and_nand_16: 5988 BuiltinIndex = 5; 5989 WarnAboutSemanticsChange = true; 5990 break; 5991 5992 case Builtin::BI__sync_add_and_fetch: 5993 case Builtin::BI__sync_add_and_fetch_1: 5994 case Builtin::BI__sync_add_and_fetch_2: 5995 case Builtin::BI__sync_add_and_fetch_4: 5996 case Builtin::BI__sync_add_and_fetch_8: 5997 case Builtin::BI__sync_add_and_fetch_16: 5998 BuiltinIndex = 6; 5999 break; 6000 6001 case Builtin::BI__sync_sub_and_fetch: 6002 case Builtin::BI__sync_sub_and_fetch_1: 6003 case Builtin::BI__sync_sub_and_fetch_2: 6004 case Builtin::BI__sync_sub_and_fetch_4: 6005 case Builtin::BI__sync_sub_and_fetch_8: 6006 case Builtin::BI__sync_sub_and_fetch_16: 6007 BuiltinIndex = 7; 6008 break; 6009 6010 case Builtin::BI__sync_and_and_fetch: 6011 case Builtin::BI__sync_and_and_fetch_1: 6012 case Builtin::BI__sync_and_and_fetch_2: 6013 case Builtin::BI__sync_and_and_fetch_4: 6014 case Builtin::BI__sync_and_and_fetch_8: 6015 case Builtin::BI__sync_and_and_fetch_16: 6016 BuiltinIndex = 8; 6017 break; 6018 6019 case Builtin::BI__sync_or_and_fetch: 6020 case Builtin::BI__sync_or_and_fetch_1: 6021 case Builtin::BI__sync_or_and_fetch_2: 6022 case Builtin::BI__sync_or_and_fetch_4: 6023 case Builtin::BI__sync_or_and_fetch_8: 6024 case Builtin::BI__sync_or_and_fetch_16: 6025 BuiltinIndex = 9; 6026 break; 6027 6028 case Builtin::BI__sync_xor_and_fetch: 6029 case Builtin::BI__sync_xor_and_fetch_1: 6030 case Builtin::BI__sync_xor_and_fetch_2: 6031 case Builtin::BI__sync_xor_and_fetch_4: 6032 case Builtin::BI__sync_xor_and_fetch_8: 6033 case Builtin::BI__sync_xor_and_fetch_16: 6034 BuiltinIndex = 10; 6035 break; 6036 6037 case Builtin::BI__sync_nand_and_fetch: 6038 case Builtin::BI__sync_nand_and_fetch_1: 6039 case Builtin::BI__sync_nand_and_fetch_2: 6040 case Builtin::BI__sync_nand_and_fetch_4: 6041 case Builtin::BI__sync_nand_and_fetch_8: 6042 case Builtin::BI__sync_nand_and_fetch_16: 6043 BuiltinIndex = 11; 6044 WarnAboutSemanticsChange = true; 6045 break; 6046 6047 case Builtin::BI__sync_val_compare_and_swap: 6048 case Builtin::BI__sync_val_compare_and_swap_1: 6049 case Builtin::BI__sync_val_compare_and_swap_2: 6050 case Builtin::BI__sync_val_compare_and_swap_4: 6051 case Builtin::BI__sync_val_compare_and_swap_8: 6052 case Builtin::BI__sync_val_compare_and_swap_16: 6053 BuiltinIndex = 12; 6054 NumFixed = 2; 6055 break; 6056 6057 case Builtin::BI__sync_bool_compare_and_swap: 6058 case Builtin::BI__sync_bool_compare_and_swap_1: 6059 case Builtin::BI__sync_bool_compare_and_swap_2: 6060 case Builtin::BI__sync_bool_compare_and_swap_4: 6061 case Builtin::BI__sync_bool_compare_and_swap_8: 6062 case Builtin::BI__sync_bool_compare_and_swap_16: 6063 BuiltinIndex = 13; 6064 NumFixed = 2; 6065 ResultType = Context.BoolTy; 6066 break; 6067 6068 case Builtin::BI__sync_lock_test_and_set: 6069 case Builtin::BI__sync_lock_test_and_set_1: 6070 case Builtin::BI__sync_lock_test_and_set_2: 6071 case Builtin::BI__sync_lock_test_and_set_4: 6072 case Builtin::BI__sync_lock_test_and_set_8: 6073 case Builtin::BI__sync_lock_test_and_set_16: 6074 BuiltinIndex = 14; 6075 break; 6076 6077 case Builtin::BI__sync_lock_release: 6078 case Builtin::BI__sync_lock_release_1: 6079 case Builtin::BI__sync_lock_release_2: 6080 case Builtin::BI__sync_lock_release_4: 6081 case Builtin::BI__sync_lock_release_8: 6082 case Builtin::BI__sync_lock_release_16: 6083 BuiltinIndex = 15; 6084 NumFixed = 0; 6085 ResultType = Context.VoidTy; 6086 break; 6087 6088 case Builtin::BI__sync_swap: 6089 case Builtin::BI__sync_swap_1: 6090 case Builtin::BI__sync_swap_2: 6091 case Builtin::BI__sync_swap_4: 6092 case Builtin::BI__sync_swap_8: 6093 case Builtin::BI__sync_swap_16: 6094 BuiltinIndex = 16; 6095 break; 6096 } 6097 6098 // Now that we know how many fixed arguments we expect, first check that we 6099 // have at least that many. 6100 if (TheCall->getNumArgs() < 1+NumFixed) { 6101 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6102 << 0 << 1 + NumFixed << TheCall->getNumArgs() 6103 << Callee->getSourceRange(); 6104 return ExprError(); 6105 } 6106 6107 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 6108 << Callee->getSourceRange(); 6109 6110 if (WarnAboutSemanticsChange) { 6111 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 6112 << Callee->getSourceRange(); 6113 } 6114 6115 // Get the decl for the concrete builtin from this, we can tell what the 6116 // concrete integer type we should convert to is. 6117 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 6118 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 6119 FunctionDecl *NewBuiltinDecl; 6120 if (NewBuiltinID == BuiltinID) 6121 NewBuiltinDecl = FDecl; 6122 else { 6123 // Perform builtin lookup to avoid redeclaring it. 6124 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 6125 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 6126 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 6127 assert(Res.getFoundDecl()); 6128 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 6129 if (!NewBuiltinDecl) 6130 return ExprError(); 6131 } 6132 6133 // The first argument --- the pointer --- has a fixed type; we 6134 // deduce the types of the rest of the arguments accordingly. Walk 6135 // the remaining arguments, converting them to the deduced value type. 6136 for (unsigned i = 0; i != NumFixed; ++i) { 6137 ExprResult Arg = TheCall->getArg(i+1); 6138 6139 // GCC does an implicit conversion to the pointer or integer ValType. This 6140 // can fail in some cases (1i -> int**), check for this error case now. 6141 // Initialize the argument. 6142 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6143 ValType, /*consume*/ false); 6144 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6145 if (Arg.isInvalid()) 6146 return ExprError(); 6147 6148 // Okay, we have something that *can* be converted to the right type. Check 6149 // to see if there is a potentially weird extension going on here. This can 6150 // happen when you do an atomic operation on something like an char* and 6151 // pass in 42. The 42 gets converted to char. This is even more strange 6152 // for things like 45.123 -> char, etc. 6153 // FIXME: Do this check. 6154 TheCall->setArg(i+1, Arg.get()); 6155 } 6156 6157 // Create a new DeclRefExpr to refer to the new decl. 6158 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6159 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6160 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6161 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6162 6163 // Set the callee in the CallExpr. 6164 // FIXME: This loses syntactic information. 6165 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6166 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6167 CK_BuiltinFnToFnPtr); 6168 TheCall->setCallee(PromotedCall.get()); 6169 6170 // Change the result type of the call to match the original value type. This 6171 // is arbitrary, but the codegen for these builtins ins design to handle it 6172 // gracefully. 6173 TheCall->setType(ResultType); 6174 6175 // Prohibit use of _ExtInt with atomic builtins. 6176 // The arguments would have already been converted to the first argument's 6177 // type, so only need to check the first argument. 6178 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 6179 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 6180 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6181 return ExprError(); 6182 } 6183 6184 return TheCallResult; 6185 } 6186 6187 /// SemaBuiltinNontemporalOverloaded - We have a call to 6188 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6189 /// overloaded function based on the pointer type of its last argument. 6190 /// 6191 /// This function goes through and does final semantic checking for these 6192 /// builtins. 6193 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6194 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6195 DeclRefExpr *DRE = 6196 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6197 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6198 unsigned BuiltinID = FDecl->getBuiltinID(); 6199 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6200 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6201 "Unexpected nontemporal load/store builtin!"); 6202 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6203 unsigned numArgs = isStore ? 2 : 1; 6204 6205 // Ensure that we have the proper number of arguments. 6206 if (checkArgCount(*this, TheCall, numArgs)) 6207 return ExprError(); 6208 6209 // Inspect the last argument of the nontemporal builtin. This should always 6210 // be a pointer type, from which we imply the type of the memory access. 6211 // Because it is a pointer type, we don't have to worry about any implicit 6212 // casts here. 6213 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6214 ExprResult PointerArgResult = 6215 DefaultFunctionArrayLvalueConversion(PointerArg); 6216 6217 if (PointerArgResult.isInvalid()) 6218 return ExprError(); 6219 PointerArg = PointerArgResult.get(); 6220 TheCall->setArg(numArgs - 1, PointerArg); 6221 6222 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6223 if (!pointerType) { 6224 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6225 << PointerArg->getType() << PointerArg->getSourceRange(); 6226 return ExprError(); 6227 } 6228 6229 QualType ValType = pointerType->getPointeeType(); 6230 6231 // Strip any qualifiers off ValType. 6232 ValType = ValType.getUnqualifiedType(); 6233 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6234 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6235 !ValType->isVectorType()) { 6236 Diag(DRE->getBeginLoc(), 6237 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6238 << PointerArg->getType() << PointerArg->getSourceRange(); 6239 return ExprError(); 6240 } 6241 6242 if (!isStore) { 6243 TheCall->setType(ValType); 6244 return TheCallResult; 6245 } 6246 6247 ExprResult ValArg = TheCall->getArg(0); 6248 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6249 Context, ValType, /*consume*/ false); 6250 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6251 if (ValArg.isInvalid()) 6252 return ExprError(); 6253 6254 TheCall->setArg(0, ValArg.get()); 6255 TheCall->setType(Context.VoidTy); 6256 return TheCallResult; 6257 } 6258 6259 /// CheckObjCString - Checks that the argument to the builtin 6260 /// CFString constructor is correct 6261 /// Note: It might also make sense to do the UTF-16 conversion here (would 6262 /// simplify the backend). 6263 bool Sema::CheckObjCString(Expr *Arg) { 6264 Arg = Arg->IgnoreParenCasts(); 6265 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6266 6267 if (!Literal || !Literal->isAscii()) { 6268 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6269 << Arg->getSourceRange(); 6270 return true; 6271 } 6272 6273 if (Literal->containsNonAsciiOrNull()) { 6274 StringRef String = Literal->getString(); 6275 unsigned NumBytes = String.size(); 6276 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6277 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6278 llvm::UTF16 *ToPtr = &ToBuf[0]; 6279 6280 llvm::ConversionResult Result = 6281 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6282 ToPtr + NumBytes, llvm::strictConversion); 6283 // Check for conversion failure. 6284 if (Result != llvm::conversionOK) 6285 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6286 << Arg->getSourceRange(); 6287 } 6288 return false; 6289 } 6290 6291 /// CheckObjCString - Checks that the format string argument to the os_log() 6292 /// and os_trace() functions is correct, and converts it to const char *. 6293 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6294 Arg = Arg->IgnoreParenCasts(); 6295 auto *Literal = dyn_cast<StringLiteral>(Arg); 6296 if (!Literal) { 6297 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6298 Literal = ObjcLiteral->getString(); 6299 } 6300 } 6301 6302 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6303 return ExprError( 6304 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6305 << Arg->getSourceRange()); 6306 } 6307 6308 ExprResult Result(Literal); 6309 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6310 InitializedEntity Entity = 6311 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6312 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6313 return Result; 6314 } 6315 6316 /// Check that the user is calling the appropriate va_start builtin for the 6317 /// target and calling convention. 6318 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6319 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6320 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6321 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6322 TT.getArch() == llvm::Triple::aarch64_32); 6323 bool IsWindows = TT.isOSWindows(); 6324 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6325 if (IsX64 || IsAArch64) { 6326 CallingConv CC = CC_C; 6327 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6328 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6329 if (IsMSVAStart) { 6330 // Don't allow this in System V ABI functions. 6331 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6332 return S.Diag(Fn->getBeginLoc(), 6333 diag::err_ms_va_start_used_in_sysv_function); 6334 } else { 6335 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6336 // On x64 Windows, don't allow this in System V ABI functions. 6337 // (Yes, that means there's no corresponding way to support variadic 6338 // System V ABI functions on Windows.) 6339 if ((IsWindows && CC == CC_X86_64SysV) || 6340 (!IsWindows && CC == CC_Win64)) 6341 return S.Diag(Fn->getBeginLoc(), 6342 diag::err_va_start_used_in_wrong_abi_function) 6343 << !IsWindows; 6344 } 6345 return false; 6346 } 6347 6348 if (IsMSVAStart) 6349 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6350 return false; 6351 } 6352 6353 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6354 ParmVarDecl **LastParam = nullptr) { 6355 // Determine whether the current function, block, or obj-c method is variadic 6356 // and get its parameter list. 6357 bool IsVariadic = false; 6358 ArrayRef<ParmVarDecl *> Params; 6359 DeclContext *Caller = S.CurContext; 6360 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6361 IsVariadic = Block->isVariadic(); 6362 Params = Block->parameters(); 6363 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6364 IsVariadic = FD->isVariadic(); 6365 Params = FD->parameters(); 6366 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6367 IsVariadic = MD->isVariadic(); 6368 // FIXME: This isn't correct for methods (results in bogus warning). 6369 Params = MD->parameters(); 6370 } else if (isa<CapturedDecl>(Caller)) { 6371 // We don't support va_start in a CapturedDecl. 6372 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6373 return true; 6374 } else { 6375 // This must be some other declcontext that parses exprs. 6376 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6377 return true; 6378 } 6379 6380 if (!IsVariadic) { 6381 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6382 return true; 6383 } 6384 6385 if (LastParam) 6386 *LastParam = Params.empty() ? nullptr : Params.back(); 6387 6388 return false; 6389 } 6390 6391 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6392 /// for validity. Emit an error and return true on failure; return false 6393 /// on success. 6394 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6395 Expr *Fn = TheCall->getCallee(); 6396 6397 if (checkVAStartABI(*this, BuiltinID, Fn)) 6398 return true; 6399 6400 if (checkArgCount(*this, TheCall, 2)) 6401 return true; 6402 6403 // Type-check the first argument normally. 6404 if (checkBuiltinArgument(*this, TheCall, 0)) 6405 return true; 6406 6407 // Check that the current function is variadic, and get its last parameter. 6408 ParmVarDecl *LastParam; 6409 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6410 return true; 6411 6412 // Verify that the second argument to the builtin is the last argument of the 6413 // current function or method. 6414 bool SecondArgIsLastNamedArgument = false; 6415 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6416 6417 // These are valid if SecondArgIsLastNamedArgument is false after the next 6418 // block. 6419 QualType Type; 6420 SourceLocation ParamLoc; 6421 bool IsCRegister = false; 6422 6423 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6424 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6425 SecondArgIsLastNamedArgument = PV == LastParam; 6426 6427 Type = PV->getType(); 6428 ParamLoc = PV->getLocation(); 6429 IsCRegister = 6430 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6431 } 6432 } 6433 6434 if (!SecondArgIsLastNamedArgument) 6435 Diag(TheCall->getArg(1)->getBeginLoc(), 6436 diag::warn_second_arg_of_va_start_not_last_named_param); 6437 else if (IsCRegister || Type->isReferenceType() || 6438 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6439 // Promotable integers are UB, but enumerations need a bit of 6440 // extra checking to see what their promotable type actually is. 6441 if (!Type->isPromotableIntegerType()) 6442 return false; 6443 if (!Type->isEnumeralType()) 6444 return true; 6445 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6446 return !(ED && 6447 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6448 }()) { 6449 unsigned Reason = 0; 6450 if (Type->isReferenceType()) Reason = 1; 6451 else if (IsCRegister) Reason = 2; 6452 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6453 Diag(ParamLoc, diag::note_parameter_type) << Type; 6454 } 6455 6456 TheCall->setType(Context.VoidTy); 6457 return false; 6458 } 6459 6460 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6461 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { 6462 const LangOptions &LO = getLangOpts(); 6463 6464 if (LO.CPlusPlus) 6465 return Arg->getType() 6466 .getCanonicalType() 6467 .getTypePtr() 6468 ->getPointeeType() 6469 .withoutLocalFastQualifiers() == Context.CharTy; 6470 6471 // In C, allow aliasing through `char *`, this is required for AArch64 at 6472 // least. 6473 return true; 6474 }; 6475 6476 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6477 // const char *named_addr); 6478 6479 Expr *Func = Call->getCallee(); 6480 6481 if (Call->getNumArgs() < 3) 6482 return Diag(Call->getEndLoc(), 6483 diag::err_typecheck_call_too_few_args_at_least) 6484 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6485 6486 // Type-check the first argument normally. 6487 if (checkBuiltinArgument(*this, Call, 0)) 6488 return true; 6489 6490 // Check that the current function is variadic. 6491 if (checkVAStartIsInVariadicFunction(*this, Func)) 6492 return true; 6493 6494 // __va_start on Windows does not validate the parameter qualifiers 6495 6496 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6497 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6498 6499 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6500 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6501 6502 const QualType &ConstCharPtrTy = 6503 Context.getPointerType(Context.CharTy.withConst()); 6504 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) 6505 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6506 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6507 << 0 /* qualifier difference */ 6508 << 3 /* parameter mismatch */ 6509 << 2 << Arg1->getType() << ConstCharPtrTy; 6510 6511 const QualType SizeTy = Context.getSizeType(); 6512 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6513 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6514 << Arg2->getType() << SizeTy << 1 /* different class */ 6515 << 0 /* qualifier difference */ 6516 << 3 /* parameter mismatch */ 6517 << 3 << Arg2->getType() << SizeTy; 6518 6519 return false; 6520 } 6521 6522 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6523 /// friends. This is declared to take (...), so we have to check everything. 6524 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6525 if (checkArgCount(*this, TheCall, 2)) 6526 return true; 6527 6528 ExprResult OrigArg0 = TheCall->getArg(0); 6529 ExprResult OrigArg1 = TheCall->getArg(1); 6530 6531 // Do standard promotions between the two arguments, returning their common 6532 // type. 6533 QualType Res = UsualArithmeticConversions( 6534 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6535 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6536 return true; 6537 6538 // Make sure any conversions are pushed back into the call; this is 6539 // type safe since unordered compare builtins are declared as "_Bool 6540 // foo(...)". 6541 TheCall->setArg(0, OrigArg0.get()); 6542 TheCall->setArg(1, OrigArg1.get()); 6543 6544 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6545 return false; 6546 6547 // If the common type isn't a real floating type, then the arguments were 6548 // invalid for this operation. 6549 if (Res.isNull() || !Res->isRealFloatingType()) 6550 return Diag(OrigArg0.get()->getBeginLoc(), 6551 diag::err_typecheck_call_invalid_ordered_compare) 6552 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6553 << SourceRange(OrigArg0.get()->getBeginLoc(), 6554 OrigArg1.get()->getEndLoc()); 6555 6556 return false; 6557 } 6558 6559 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6560 /// __builtin_isnan and friends. This is declared to take (...), so we have 6561 /// to check everything. We expect the last argument to be a floating point 6562 /// value. 6563 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6564 if (checkArgCount(*this, TheCall, NumArgs)) 6565 return true; 6566 6567 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6568 // on all preceding parameters just being int. Try all of those. 6569 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6570 Expr *Arg = TheCall->getArg(i); 6571 6572 if (Arg->isTypeDependent()) 6573 return false; 6574 6575 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6576 6577 if (Res.isInvalid()) 6578 return true; 6579 TheCall->setArg(i, Res.get()); 6580 } 6581 6582 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6583 6584 if (OrigArg->isTypeDependent()) 6585 return false; 6586 6587 // Usual Unary Conversions will convert half to float, which we want for 6588 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6589 // type how it is, but do normal L->Rvalue conversions. 6590 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6591 OrigArg = UsualUnaryConversions(OrigArg).get(); 6592 else 6593 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6594 TheCall->setArg(NumArgs - 1, OrigArg); 6595 6596 // This operation requires a non-_Complex floating-point number. 6597 if (!OrigArg->getType()->isRealFloatingType()) 6598 return Diag(OrigArg->getBeginLoc(), 6599 diag::err_typecheck_call_invalid_unary_fp) 6600 << OrigArg->getType() << OrigArg->getSourceRange(); 6601 6602 return false; 6603 } 6604 6605 /// Perform semantic analysis for a call to __builtin_complex. 6606 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6607 if (checkArgCount(*this, TheCall, 2)) 6608 return true; 6609 6610 bool Dependent = false; 6611 for (unsigned I = 0; I != 2; ++I) { 6612 Expr *Arg = TheCall->getArg(I); 6613 QualType T = Arg->getType(); 6614 if (T->isDependentType()) { 6615 Dependent = true; 6616 continue; 6617 } 6618 6619 // Despite supporting _Complex int, GCC requires a real floating point type 6620 // for the operands of __builtin_complex. 6621 if (!T->isRealFloatingType()) { 6622 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6623 << Arg->getType() << Arg->getSourceRange(); 6624 } 6625 6626 ExprResult Converted = DefaultLvalueConversion(Arg); 6627 if (Converted.isInvalid()) 6628 return true; 6629 TheCall->setArg(I, Converted.get()); 6630 } 6631 6632 if (Dependent) { 6633 TheCall->setType(Context.DependentTy); 6634 return false; 6635 } 6636 6637 Expr *Real = TheCall->getArg(0); 6638 Expr *Imag = TheCall->getArg(1); 6639 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6640 return Diag(Real->getBeginLoc(), 6641 diag::err_typecheck_call_different_arg_types) 6642 << Real->getType() << Imag->getType() 6643 << Real->getSourceRange() << Imag->getSourceRange(); 6644 } 6645 6646 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6647 // don't allow this builtin to form those types either. 6648 // FIXME: Should we allow these types? 6649 if (Real->getType()->isFloat16Type()) 6650 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6651 << "_Float16"; 6652 if (Real->getType()->isHalfType()) 6653 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6654 << "half"; 6655 6656 TheCall->setType(Context.getComplexType(Real->getType())); 6657 return false; 6658 } 6659 6660 // Customized Sema Checking for VSX builtins that have the following signature: 6661 // vector [...] builtinName(vector [...], vector [...], const int); 6662 // Which takes the same type of vectors (any legal vector type) for the first 6663 // two arguments and takes compile time constant for the third argument. 6664 // Example builtins are : 6665 // vector double vec_xxpermdi(vector double, vector double, int); 6666 // vector short vec_xxsldwi(vector short, vector short, int); 6667 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6668 unsigned ExpectedNumArgs = 3; 6669 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6670 return true; 6671 6672 // Check the third argument is a compile time constant 6673 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6674 return Diag(TheCall->getBeginLoc(), 6675 diag::err_vsx_builtin_nonconstant_argument) 6676 << 3 /* argument index */ << TheCall->getDirectCallee() 6677 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6678 TheCall->getArg(2)->getEndLoc()); 6679 6680 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6681 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6682 6683 // Check the type of argument 1 and argument 2 are vectors. 6684 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6685 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6686 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6687 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6688 << TheCall->getDirectCallee() 6689 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6690 TheCall->getArg(1)->getEndLoc()); 6691 } 6692 6693 // Check the first two arguments are the same type. 6694 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6695 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6696 << TheCall->getDirectCallee() 6697 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6698 TheCall->getArg(1)->getEndLoc()); 6699 } 6700 6701 // When default clang type checking is turned off and the customized type 6702 // checking is used, the returning type of the function must be explicitly 6703 // set. Otherwise it is _Bool by default. 6704 TheCall->setType(Arg1Ty); 6705 6706 return false; 6707 } 6708 6709 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6710 // This is declared to take (...), so we have to check everything. 6711 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6712 if (TheCall->getNumArgs() < 2) 6713 return ExprError(Diag(TheCall->getEndLoc(), 6714 diag::err_typecheck_call_too_few_args_at_least) 6715 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6716 << TheCall->getSourceRange()); 6717 6718 // Determine which of the following types of shufflevector we're checking: 6719 // 1) unary, vector mask: (lhs, mask) 6720 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6721 QualType resType = TheCall->getArg(0)->getType(); 6722 unsigned numElements = 0; 6723 6724 if (!TheCall->getArg(0)->isTypeDependent() && 6725 !TheCall->getArg(1)->isTypeDependent()) { 6726 QualType LHSType = TheCall->getArg(0)->getType(); 6727 QualType RHSType = TheCall->getArg(1)->getType(); 6728 6729 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6730 return ExprError( 6731 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6732 << TheCall->getDirectCallee() 6733 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6734 TheCall->getArg(1)->getEndLoc())); 6735 6736 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6737 unsigned numResElements = TheCall->getNumArgs() - 2; 6738 6739 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6740 // with mask. If so, verify that RHS is an integer vector type with the 6741 // same number of elts as lhs. 6742 if (TheCall->getNumArgs() == 2) { 6743 if (!RHSType->hasIntegerRepresentation() || 6744 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6745 return ExprError(Diag(TheCall->getBeginLoc(), 6746 diag::err_vec_builtin_incompatible_vector) 6747 << TheCall->getDirectCallee() 6748 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6749 TheCall->getArg(1)->getEndLoc())); 6750 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6751 return ExprError(Diag(TheCall->getBeginLoc(), 6752 diag::err_vec_builtin_incompatible_vector) 6753 << TheCall->getDirectCallee() 6754 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6755 TheCall->getArg(1)->getEndLoc())); 6756 } else if (numElements != numResElements) { 6757 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6758 resType = Context.getVectorType(eltType, numResElements, 6759 VectorType::GenericVector); 6760 } 6761 } 6762 6763 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6764 if (TheCall->getArg(i)->isTypeDependent() || 6765 TheCall->getArg(i)->isValueDependent()) 6766 continue; 6767 6768 Optional<llvm::APSInt> Result; 6769 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6770 return ExprError(Diag(TheCall->getBeginLoc(), 6771 diag::err_shufflevector_nonconstant_argument) 6772 << TheCall->getArg(i)->getSourceRange()); 6773 6774 // Allow -1 which will be translated to undef in the IR. 6775 if (Result->isSigned() && Result->isAllOnesValue()) 6776 continue; 6777 6778 if (Result->getActiveBits() > 64 || 6779 Result->getZExtValue() >= numElements * 2) 6780 return ExprError(Diag(TheCall->getBeginLoc(), 6781 diag::err_shufflevector_argument_too_large) 6782 << TheCall->getArg(i)->getSourceRange()); 6783 } 6784 6785 SmallVector<Expr*, 32> exprs; 6786 6787 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6788 exprs.push_back(TheCall->getArg(i)); 6789 TheCall->setArg(i, nullptr); 6790 } 6791 6792 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6793 TheCall->getCallee()->getBeginLoc(), 6794 TheCall->getRParenLoc()); 6795 } 6796 6797 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6798 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6799 SourceLocation BuiltinLoc, 6800 SourceLocation RParenLoc) { 6801 ExprValueKind VK = VK_PRValue; 6802 ExprObjectKind OK = OK_Ordinary; 6803 QualType DstTy = TInfo->getType(); 6804 QualType SrcTy = E->getType(); 6805 6806 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6807 return ExprError(Diag(BuiltinLoc, 6808 diag::err_convertvector_non_vector) 6809 << E->getSourceRange()); 6810 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6811 return ExprError(Diag(BuiltinLoc, 6812 diag::err_convertvector_non_vector_type)); 6813 6814 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6815 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6816 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6817 if (SrcElts != DstElts) 6818 return ExprError(Diag(BuiltinLoc, 6819 diag::err_convertvector_incompatible_vector) 6820 << E->getSourceRange()); 6821 } 6822 6823 return new (Context) 6824 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6825 } 6826 6827 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6828 // This is declared to take (const void*, ...) and can take two 6829 // optional constant int args. 6830 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6831 unsigned NumArgs = TheCall->getNumArgs(); 6832 6833 if (NumArgs > 3) 6834 return Diag(TheCall->getEndLoc(), 6835 diag::err_typecheck_call_too_many_args_at_most) 6836 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6837 6838 // Argument 0 is checked for us and the remaining arguments must be 6839 // constant integers. 6840 for (unsigned i = 1; i != NumArgs; ++i) 6841 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6842 return true; 6843 6844 return false; 6845 } 6846 6847 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 6848 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 6849 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 6850 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 6851 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6852 if (checkArgCount(*this, TheCall, 1)) 6853 return true; 6854 Expr *Arg = TheCall->getArg(0); 6855 if (Arg->isInstantiationDependent()) 6856 return false; 6857 6858 QualType ArgTy = Arg->getType(); 6859 if (!ArgTy->hasFloatingRepresentation()) 6860 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 6861 << ArgTy; 6862 if (Arg->isLValue()) { 6863 ExprResult FirstArg = DefaultLvalueConversion(Arg); 6864 TheCall->setArg(0, FirstArg.get()); 6865 } 6866 TheCall->setType(TheCall->getArg(0)->getType()); 6867 return false; 6868 } 6869 6870 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6871 // __assume does not evaluate its arguments, and should warn if its argument 6872 // has side effects. 6873 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6874 Expr *Arg = TheCall->getArg(0); 6875 if (Arg->isInstantiationDependent()) return false; 6876 6877 if (Arg->HasSideEffects(Context)) 6878 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6879 << Arg->getSourceRange() 6880 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6881 6882 return false; 6883 } 6884 6885 /// Handle __builtin_alloca_with_align. This is declared 6886 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6887 /// than 8. 6888 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6889 // The alignment must be a constant integer. 6890 Expr *Arg = TheCall->getArg(1); 6891 6892 // We can't check the value of a dependent argument. 6893 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6894 if (const auto *UE = 6895 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6896 if (UE->getKind() == UETT_AlignOf || 6897 UE->getKind() == UETT_PreferredAlignOf) 6898 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6899 << Arg->getSourceRange(); 6900 6901 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6902 6903 if (!Result.isPowerOf2()) 6904 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6905 << Arg->getSourceRange(); 6906 6907 if (Result < Context.getCharWidth()) 6908 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6909 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6910 6911 if (Result > std::numeric_limits<int32_t>::max()) 6912 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6913 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6914 } 6915 6916 return false; 6917 } 6918 6919 /// Handle __builtin_assume_aligned. This is declared 6920 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6921 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6922 unsigned NumArgs = TheCall->getNumArgs(); 6923 6924 if (NumArgs > 3) 6925 return Diag(TheCall->getEndLoc(), 6926 diag::err_typecheck_call_too_many_args_at_most) 6927 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6928 6929 // The alignment must be a constant integer. 6930 Expr *Arg = TheCall->getArg(1); 6931 6932 // We can't check the value of a dependent argument. 6933 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6934 llvm::APSInt Result; 6935 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6936 return true; 6937 6938 if (!Result.isPowerOf2()) 6939 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6940 << Arg->getSourceRange(); 6941 6942 if (Result > Sema::MaximumAlignment) 6943 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6944 << Arg->getSourceRange() << Sema::MaximumAlignment; 6945 } 6946 6947 if (NumArgs > 2) { 6948 ExprResult Arg(TheCall->getArg(2)); 6949 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6950 Context.getSizeType(), false); 6951 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6952 if (Arg.isInvalid()) return true; 6953 TheCall->setArg(2, Arg.get()); 6954 } 6955 6956 return false; 6957 } 6958 6959 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6960 unsigned BuiltinID = 6961 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6962 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6963 6964 unsigned NumArgs = TheCall->getNumArgs(); 6965 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6966 if (NumArgs < NumRequiredArgs) { 6967 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6968 << 0 /* function call */ << NumRequiredArgs << NumArgs 6969 << TheCall->getSourceRange(); 6970 } 6971 if (NumArgs >= NumRequiredArgs + 0x100) { 6972 return Diag(TheCall->getEndLoc(), 6973 diag::err_typecheck_call_too_many_args_at_most) 6974 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6975 << TheCall->getSourceRange(); 6976 } 6977 unsigned i = 0; 6978 6979 // For formatting call, check buffer arg. 6980 if (!IsSizeCall) { 6981 ExprResult Arg(TheCall->getArg(i)); 6982 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6983 Context, Context.VoidPtrTy, false); 6984 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6985 if (Arg.isInvalid()) 6986 return true; 6987 TheCall->setArg(i, Arg.get()); 6988 i++; 6989 } 6990 6991 // Check string literal arg. 6992 unsigned FormatIdx = i; 6993 { 6994 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6995 if (Arg.isInvalid()) 6996 return true; 6997 TheCall->setArg(i, Arg.get()); 6998 i++; 6999 } 7000 7001 // Make sure variadic args are scalar. 7002 unsigned FirstDataArg = i; 7003 while (i < NumArgs) { 7004 ExprResult Arg = DefaultVariadicArgumentPromotion( 7005 TheCall->getArg(i), VariadicFunction, nullptr); 7006 if (Arg.isInvalid()) 7007 return true; 7008 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 7009 if (ArgSize.getQuantity() >= 0x100) { 7010 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 7011 << i << (int)ArgSize.getQuantity() << 0xff 7012 << TheCall->getSourceRange(); 7013 } 7014 TheCall->setArg(i, Arg.get()); 7015 i++; 7016 } 7017 7018 // Check formatting specifiers. NOTE: We're only doing this for the non-size 7019 // call to avoid duplicate diagnostics. 7020 if (!IsSizeCall) { 7021 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 7022 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 7023 bool Success = CheckFormatArguments( 7024 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 7025 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 7026 CheckedVarArgs); 7027 if (!Success) 7028 return true; 7029 } 7030 7031 if (IsSizeCall) { 7032 TheCall->setType(Context.getSizeType()); 7033 } else { 7034 TheCall->setType(Context.VoidPtrTy); 7035 } 7036 return false; 7037 } 7038 7039 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 7040 /// TheCall is a constant expression. 7041 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7042 llvm::APSInt &Result) { 7043 Expr *Arg = TheCall->getArg(ArgNum); 7044 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 7045 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 7046 7047 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 7048 7049 Optional<llvm::APSInt> R; 7050 if (!(R = Arg->getIntegerConstantExpr(Context))) 7051 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 7052 << FDecl->getDeclName() << Arg->getSourceRange(); 7053 Result = *R; 7054 return false; 7055 } 7056 7057 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 7058 /// TheCall is a constant expression in the range [Low, High]. 7059 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 7060 int Low, int High, bool RangeIsError) { 7061 if (isConstantEvaluated()) 7062 return false; 7063 llvm::APSInt Result; 7064 7065 // We can't check the value of a dependent argument. 7066 Expr *Arg = TheCall->getArg(ArgNum); 7067 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7068 return false; 7069 7070 // Check constant-ness first. 7071 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7072 return true; 7073 7074 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 7075 if (RangeIsError) 7076 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 7077 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 7078 else 7079 // Defer the warning until we know if the code will be emitted so that 7080 // dead code can ignore this. 7081 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 7082 PDiag(diag::warn_argument_invalid_range) 7083 << toString(Result, 10) << Low << High 7084 << Arg->getSourceRange()); 7085 } 7086 7087 return false; 7088 } 7089 7090 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 7091 /// TheCall is a constant expression is a multiple of Num.. 7092 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 7093 unsigned Num) { 7094 llvm::APSInt Result; 7095 7096 // We can't check the value of a dependent argument. 7097 Expr *Arg = TheCall->getArg(ArgNum); 7098 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7099 return false; 7100 7101 // Check constant-ness first. 7102 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7103 return true; 7104 7105 if (Result.getSExtValue() % Num != 0) 7106 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 7107 << Num << Arg->getSourceRange(); 7108 7109 return false; 7110 } 7111 7112 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 7113 /// constant expression representing a power of 2. 7114 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 7115 llvm::APSInt Result; 7116 7117 // We can't check the value of a dependent argument. 7118 Expr *Arg = TheCall->getArg(ArgNum); 7119 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7120 return false; 7121 7122 // Check constant-ness first. 7123 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7124 return true; 7125 7126 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 7127 // and only if x is a power of 2. 7128 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 7129 return false; 7130 7131 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 7132 << Arg->getSourceRange(); 7133 } 7134 7135 static bool IsShiftedByte(llvm::APSInt Value) { 7136 if (Value.isNegative()) 7137 return false; 7138 7139 // Check if it's a shifted byte, by shifting it down 7140 while (true) { 7141 // If the value fits in the bottom byte, the check passes. 7142 if (Value < 0x100) 7143 return true; 7144 7145 // Otherwise, if the value has _any_ bits in the bottom byte, the check 7146 // fails. 7147 if ((Value & 0xFF) != 0) 7148 return false; 7149 7150 // If the bottom 8 bits are all 0, but something above that is nonzero, 7151 // then shifting the value right by 8 bits won't affect whether it's a 7152 // shifted byte or not. So do that, and go round again. 7153 Value >>= 8; 7154 } 7155 } 7156 7157 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 7158 /// a constant expression representing an arbitrary byte value shifted left by 7159 /// a multiple of 8 bits. 7160 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 7161 unsigned ArgBits) { 7162 llvm::APSInt Result; 7163 7164 // We can't check the value of a dependent argument. 7165 Expr *Arg = TheCall->getArg(ArgNum); 7166 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7167 return false; 7168 7169 // Check constant-ness first. 7170 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7171 return true; 7172 7173 // Truncate to the given size. 7174 Result = Result.getLoBits(ArgBits); 7175 Result.setIsUnsigned(true); 7176 7177 if (IsShiftedByte(Result)) 7178 return false; 7179 7180 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7181 << Arg->getSourceRange(); 7182 } 7183 7184 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7185 /// TheCall is a constant expression representing either a shifted byte value, 7186 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7187 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7188 /// Arm MVE intrinsics. 7189 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7190 int ArgNum, 7191 unsigned ArgBits) { 7192 llvm::APSInt Result; 7193 7194 // We can't check the value of a dependent argument. 7195 Expr *Arg = TheCall->getArg(ArgNum); 7196 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7197 return false; 7198 7199 // Check constant-ness first. 7200 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7201 return true; 7202 7203 // Truncate to the given size. 7204 Result = Result.getLoBits(ArgBits); 7205 Result.setIsUnsigned(true); 7206 7207 // Check to see if it's in either of the required forms. 7208 if (IsShiftedByte(Result) || 7209 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7210 return false; 7211 7212 return Diag(TheCall->getBeginLoc(), 7213 diag::err_argument_not_shifted_byte_or_xxff) 7214 << Arg->getSourceRange(); 7215 } 7216 7217 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7218 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7219 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7220 if (checkArgCount(*this, TheCall, 2)) 7221 return true; 7222 Expr *Arg0 = TheCall->getArg(0); 7223 Expr *Arg1 = TheCall->getArg(1); 7224 7225 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7226 if (FirstArg.isInvalid()) 7227 return true; 7228 QualType FirstArgType = FirstArg.get()->getType(); 7229 if (!FirstArgType->isAnyPointerType()) 7230 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7231 << "first" << FirstArgType << Arg0->getSourceRange(); 7232 TheCall->setArg(0, FirstArg.get()); 7233 7234 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7235 if (SecArg.isInvalid()) 7236 return true; 7237 QualType SecArgType = SecArg.get()->getType(); 7238 if (!SecArgType->isIntegerType()) 7239 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7240 << "second" << SecArgType << Arg1->getSourceRange(); 7241 7242 // Derive the return type from the pointer argument. 7243 TheCall->setType(FirstArgType); 7244 return false; 7245 } 7246 7247 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7248 if (checkArgCount(*this, TheCall, 2)) 7249 return true; 7250 7251 Expr *Arg0 = TheCall->getArg(0); 7252 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7253 if (FirstArg.isInvalid()) 7254 return true; 7255 QualType FirstArgType = FirstArg.get()->getType(); 7256 if (!FirstArgType->isAnyPointerType()) 7257 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7258 << "first" << FirstArgType << Arg0->getSourceRange(); 7259 TheCall->setArg(0, FirstArg.get()); 7260 7261 // Derive the return type from the pointer argument. 7262 TheCall->setType(FirstArgType); 7263 7264 // Second arg must be an constant in range [0,15] 7265 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7266 } 7267 7268 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7269 if (checkArgCount(*this, TheCall, 2)) 7270 return true; 7271 Expr *Arg0 = TheCall->getArg(0); 7272 Expr *Arg1 = TheCall->getArg(1); 7273 7274 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7275 if (FirstArg.isInvalid()) 7276 return true; 7277 QualType FirstArgType = FirstArg.get()->getType(); 7278 if (!FirstArgType->isAnyPointerType()) 7279 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7280 << "first" << FirstArgType << Arg0->getSourceRange(); 7281 7282 QualType SecArgType = Arg1->getType(); 7283 if (!SecArgType->isIntegerType()) 7284 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7285 << "second" << SecArgType << Arg1->getSourceRange(); 7286 TheCall->setType(Context.IntTy); 7287 return false; 7288 } 7289 7290 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7291 BuiltinID == AArch64::BI__builtin_arm_stg) { 7292 if (checkArgCount(*this, TheCall, 1)) 7293 return true; 7294 Expr *Arg0 = TheCall->getArg(0); 7295 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7296 if (FirstArg.isInvalid()) 7297 return true; 7298 7299 QualType FirstArgType = FirstArg.get()->getType(); 7300 if (!FirstArgType->isAnyPointerType()) 7301 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7302 << "first" << FirstArgType << Arg0->getSourceRange(); 7303 TheCall->setArg(0, FirstArg.get()); 7304 7305 // Derive the return type from the pointer argument. 7306 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7307 TheCall->setType(FirstArgType); 7308 return false; 7309 } 7310 7311 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7312 Expr *ArgA = TheCall->getArg(0); 7313 Expr *ArgB = TheCall->getArg(1); 7314 7315 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7316 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7317 7318 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7319 return true; 7320 7321 QualType ArgTypeA = ArgExprA.get()->getType(); 7322 QualType ArgTypeB = ArgExprB.get()->getType(); 7323 7324 auto isNull = [&] (Expr *E) -> bool { 7325 return E->isNullPointerConstant( 7326 Context, Expr::NPC_ValueDependentIsNotNull); }; 7327 7328 // argument should be either a pointer or null 7329 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7330 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7331 << "first" << ArgTypeA << ArgA->getSourceRange(); 7332 7333 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7334 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7335 << "second" << ArgTypeB << ArgB->getSourceRange(); 7336 7337 // Ensure Pointee types are compatible 7338 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7339 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7340 QualType pointeeA = ArgTypeA->getPointeeType(); 7341 QualType pointeeB = ArgTypeB->getPointeeType(); 7342 if (!Context.typesAreCompatible( 7343 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7344 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7345 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7346 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7347 << ArgB->getSourceRange(); 7348 } 7349 } 7350 7351 // at least one argument should be pointer type 7352 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7353 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7354 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7355 7356 if (isNull(ArgA)) // adopt type of the other pointer 7357 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7358 7359 if (isNull(ArgB)) 7360 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7361 7362 TheCall->setArg(0, ArgExprA.get()); 7363 TheCall->setArg(1, ArgExprB.get()); 7364 TheCall->setType(Context.LongLongTy); 7365 return false; 7366 } 7367 assert(false && "Unhandled ARM MTE intrinsic"); 7368 return true; 7369 } 7370 7371 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7372 /// TheCall is an ARM/AArch64 special register string literal. 7373 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7374 int ArgNum, unsigned ExpectedFieldNum, 7375 bool AllowName) { 7376 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7377 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7378 BuiltinID == ARM::BI__builtin_arm_rsr || 7379 BuiltinID == ARM::BI__builtin_arm_rsrp || 7380 BuiltinID == ARM::BI__builtin_arm_wsr || 7381 BuiltinID == ARM::BI__builtin_arm_wsrp; 7382 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7383 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7384 BuiltinID == AArch64::BI__builtin_arm_rsr || 7385 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7386 BuiltinID == AArch64::BI__builtin_arm_wsr || 7387 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7388 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7389 7390 // We can't check the value of a dependent argument. 7391 Expr *Arg = TheCall->getArg(ArgNum); 7392 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7393 return false; 7394 7395 // Check if the argument is a string literal. 7396 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7397 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7398 << Arg->getSourceRange(); 7399 7400 // Check the type of special register given. 7401 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7402 SmallVector<StringRef, 6> Fields; 7403 Reg.split(Fields, ":"); 7404 7405 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7406 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7407 << Arg->getSourceRange(); 7408 7409 // If the string is the name of a register then we cannot check that it is 7410 // valid here but if the string is of one the forms described in ACLE then we 7411 // can check that the supplied fields are integers and within the valid 7412 // ranges. 7413 if (Fields.size() > 1) { 7414 bool FiveFields = Fields.size() == 5; 7415 7416 bool ValidString = true; 7417 if (IsARMBuiltin) { 7418 ValidString &= Fields[0].startswith_insensitive("cp") || 7419 Fields[0].startswith_insensitive("p"); 7420 if (ValidString) 7421 Fields[0] = Fields[0].drop_front( 7422 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7423 7424 ValidString &= Fields[2].startswith_insensitive("c"); 7425 if (ValidString) 7426 Fields[2] = Fields[2].drop_front(1); 7427 7428 if (FiveFields) { 7429 ValidString &= Fields[3].startswith_insensitive("c"); 7430 if (ValidString) 7431 Fields[3] = Fields[3].drop_front(1); 7432 } 7433 } 7434 7435 SmallVector<int, 5> Ranges; 7436 if (FiveFields) 7437 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7438 else 7439 Ranges.append({15, 7, 15}); 7440 7441 for (unsigned i=0; i<Fields.size(); ++i) { 7442 int IntField; 7443 ValidString &= !Fields[i].getAsInteger(10, IntField); 7444 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7445 } 7446 7447 if (!ValidString) 7448 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7449 << Arg->getSourceRange(); 7450 } else if (IsAArch64Builtin && Fields.size() == 1) { 7451 // If the register name is one of those that appear in the condition below 7452 // and the special register builtin being used is one of the write builtins, 7453 // then we require that the argument provided for writing to the register 7454 // is an integer constant expression. This is because it will be lowered to 7455 // an MSR (immediate) instruction, so we need to know the immediate at 7456 // compile time. 7457 if (TheCall->getNumArgs() != 2) 7458 return false; 7459 7460 std::string RegLower = Reg.lower(); 7461 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7462 RegLower != "pan" && RegLower != "uao") 7463 return false; 7464 7465 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7466 } 7467 7468 return false; 7469 } 7470 7471 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7472 /// Emit an error and return true on failure; return false on success. 7473 /// TypeStr is a string containing the type descriptor of the value returned by 7474 /// the builtin and the descriptors of the expected type of the arguments. 7475 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) { 7476 7477 assert((TypeStr[0] != '\0') && 7478 "Invalid types in PPC MMA builtin declaration"); 7479 7480 unsigned Mask = 0; 7481 unsigned ArgNum = 0; 7482 7483 // The first type in TypeStr is the type of the value returned by the 7484 // builtin. So we first read that type and change the type of TheCall. 7485 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7486 TheCall->setType(type); 7487 7488 while (*TypeStr != '\0') { 7489 Mask = 0; 7490 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7491 if (ArgNum >= TheCall->getNumArgs()) { 7492 ArgNum++; 7493 break; 7494 } 7495 7496 Expr *Arg = TheCall->getArg(ArgNum); 7497 QualType ArgType = Arg->getType(); 7498 7499 if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) || 7500 (!ExpectedType->isVoidPointerType() && 7501 ArgType.getCanonicalType() != ExpectedType)) 7502 return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 7503 << ArgType << ExpectedType << 1 << 0 << 0; 7504 7505 // If the value of the Mask is not 0, we have a constraint in the size of 7506 // the integer argument so here we ensure the argument is a constant that 7507 // is in the valid range. 7508 if (Mask != 0 && 7509 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7510 return true; 7511 7512 ArgNum++; 7513 } 7514 7515 // In case we exited early from the previous loop, there are other types to 7516 // read from TypeStr. So we need to read them all to ensure we have the right 7517 // number of arguments in TheCall and if it is not the case, to display a 7518 // better error message. 7519 while (*TypeStr != '\0') { 7520 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7521 ArgNum++; 7522 } 7523 if (checkArgCount(*this, TheCall, ArgNum)) 7524 return true; 7525 7526 return false; 7527 } 7528 7529 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7530 /// This checks that the target supports __builtin_longjmp and 7531 /// that val is a constant 1. 7532 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7533 if (!Context.getTargetInfo().hasSjLjLowering()) 7534 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7535 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7536 7537 Expr *Arg = TheCall->getArg(1); 7538 llvm::APSInt Result; 7539 7540 // TODO: This is less than ideal. Overload this to take a value. 7541 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7542 return true; 7543 7544 if (Result != 1) 7545 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7546 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7547 7548 return false; 7549 } 7550 7551 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7552 /// This checks that the target supports __builtin_setjmp. 7553 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7554 if (!Context.getTargetInfo().hasSjLjLowering()) 7555 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7556 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7557 return false; 7558 } 7559 7560 namespace { 7561 7562 class UncoveredArgHandler { 7563 enum { Unknown = -1, AllCovered = -2 }; 7564 7565 signed FirstUncoveredArg = Unknown; 7566 SmallVector<const Expr *, 4> DiagnosticExprs; 7567 7568 public: 7569 UncoveredArgHandler() = default; 7570 7571 bool hasUncoveredArg() const { 7572 return (FirstUncoveredArg >= 0); 7573 } 7574 7575 unsigned getUncoveredArg() const { 7576 assert(hasUncoveredArg() && "no uncovered argument"); 7577 return FirstUncoveredArg; 7578 } 7579 7580 void setAllCovered() { 7581 // A string has been found with all arguments covered, so clear out 7582 // the diagnostics. 7583 DiagnosticExprs.clear(); 7584 FirstUncoveredArg = AllCovered; 7585 } 7586 7587 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7588 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7589 7590 // Don't update if a previous string covers all arguments. 7591 if (FirstUncoveredArg == AllCovered) 7592 return; 7593 7594 // UncoveredArgHandler tracks the highest uncovered argument index 7595 // and with it all the strings that match this index. 7596 if (NewFirstUncoveredArg == FirstUncoveredArg) 7597 DiagnosticExprs.push_back(StrExpr); 7598 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7599 DiagnosticExprs.clear(); 7600 DiagnosticExprs.push_back(StrExpr); 7601 FirstUncoveredArg = NewFirstUncoveredArg; 7602 } 7603 } 7604 7605 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7606 }; 7607 7608 enum StringLiteralCheckType { 7609 SLCT_NotALiteral, 7610 SLCT_UncheckedLiteral, 7611 SLCT_CheckedLiteral 7612 }; 7613 7614 } // namespace 7615 7616 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7617 BinaryOperatorKind BinOpKind, 7618 bool AddendIsRight) { 7619 unsigned BitWidth = Offset.getBitWidth(); 7620 unsigned AddendBitWidth = Addend.getBitWidth(); 7621 // There might be negative interim results. 7622 if (Addend.isUnsigned()) { 7623 Addend = Addend.zext(++AddendBitWidth); 7624 Addend.setIsSigned(true); 7625 } 7626 // Adjust the bit width of the APSInts. 7627 if (AddendBitWidth > BitWidth) { 7628 Offset = Offset.sext(AddendBitWidth); 7629 BitWidth = AddendBitWidth; 7630 } else if (BitWidth > AddendBitWidth) { 7631 Addend = Addend.sext(BitWidth); 7632 } 7633 7634 bool Ov = false; 7635 llvm::APSInt ResOffset = Offset; 7636 if (BinOpKind == BO_Add) 7637 ResOffset = Offset.sadd_ov(Addend, Ov); 7638 else { 7639 assert(AddendIsRight && BinOpKind == BO_Sub && 7640 "operator must be add or sub with addend on the right"); 7641 ResOffset = Offset.ssub_ov(Addend, Ov); 7642 } 7643 7644 // We add an offset to a pointer here so we should support an offset as big as 7645 // possible. 7646 if (Ov) { 7647 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7648 "index (intermediate) result too big"); 7649 Offset = Offset.sext(2 * BitWidth); 7650 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7651 return; 7652 } 7653 7654 Offset = ResOffset; 7655 } 7656 7657 namespace { 7658 7659 // This is a wrapper class around StringLiteral to support offsetted string 7660 // literals as format strings. It takes the offset into account when returning 7661 // the string and its length or the source locations to display notes correctly. 7662 class FormatStringLiteral { 7663 const StringLiteral *FExpr; 7664 int64_t Offset; 7665 7666 public: 7667 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7668 : FExpr(fexpr), Offset(Offset) {} 7669 7670 StringRef getString() const { 7671 return FExpr->getString().drop_front(Offset); 7672 } 7673 7674 unsigned getByteLength() const { 7675 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7676 } 7677 7678 unsigned getLength() const { return FExpr->getLength() - Offset; } 7679 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7680 7681 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7682 7683 QualType getType() const { return FExpr->getType(); } 7684 7685 bool isAscii() const { return FExpr->isAscii(); } 7686 bool isWide() const { return FExpr->isWide(); } 7687 bool isUTF8() const { return FExpr->isUTF8(); } 7688 bool isUTF16() const { return FExpr->isUTF16(); } 7689 bool isUTF32() const { return FExpr->isUTF32(); } 7690 bool isPascal() const { return FExpr->isPascal(); } 7691 7692 SourceLocation getLocationOfByte( 7693 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7694 const TargetInfo &Target, unsigned *StartToken = nullptr, 7695 unsigned *StartTokenByteOffset = nullptr) const { 7696 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7697 StartToken, StartTokenByteOffset); 7698 } 7699 7700 SourceLocation getBeginLoc() const LLVM_READONLY { 7701 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7702 } 7703 7704 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7705 }; 7706 7707 } // namespace 7708 7709 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7710 const Expr *OrigFormatExpr, 7711 ArrayRef<const Expr *> Args, 7712 bool HasVAListArg, unsigned format_idx, 7713 unsigned firstDataArg, 7714 Sema::FormatStringType Type, 7715 bool inFunctionCall, 7716 Sema::VariadicCallType CallType, 7717 llvm::SmallBitVector &CheckedVarArgs, 7718 UncoveredArgHandler &UncoveredArg, 7719 bool IgnoreStringsWithoutSpecifiers); 7720 7721 // Determine if an expression is a string literal or constant string. 7722 // If this function returns false on the arguments to a function expecting a 7723 // format string, we will usually need to emit a warning. 7724 // True string literals are then checked by CheckFormatString. 7725 static StringLiteralCheckType 7726 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7727 bool HasVAListArg, unsigned format_idx, 7728 unsigned firstDataArg, Sema::FormatStringType Type, 7729 Sema::VariadicCallType CallType, bool InFunctionCall, 7730 llvm::SmallBitVector &CheckedVarArgs, 7731 UncoveredArgHandler &UncoveredArg, 7732 llvm::APSInt Offset, 7733 bool IgnoreStringsWithoutSpecifiers = false) { 7734 if (S.isConstantEvaluated()) 7735 return SLCT_NotALiteral; 7736 tryAgain: 7737 assert(Offset.isSigned() && "invalid offset"); 7738 7739 if (E->isTypeDependent() || E->isValueDependent()) 7740 return SLCT_NotALiteral; 7741 7742 E = E->IgnoreParenCasts(); 7743 7744 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7745 // Technically -Wformat-nonliteral does not warn about this case. 7746 // The behavior of printf and friends in this case is implementation 7747 // dependent. Ideally if the format string cannot be null then 7748 // it should have a 'nonnull' attribute in the function prototype. 7749 return SLCT_UncheckedLiteral; 7750 7751 switch (E->getStmtClass()) { 7752 case Stmt::BinaryConditionalOperatorClass: 7753 case Stmt::ConditionalOperatorClass: { 7754 // The expression is a literal if both sub-expressions were, and it was 7755 // completely checked only if both sub-expressions were checked. 7756 const AbstractConditionalOperator *C = 7757 cast<AbstractConditionalOperator>(E); 7758 7759 // Determine whether it is necessary to check both sub-expressions, for 7760 // example, because the condition expression is a constant that can be 7761 // evaluated at compile time. 7762 bool CheckLeft = true, CheckRight = true; 7763 7764 bool Cond; 7765 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7766 S.isConstantEvaluated())) { 7767 if (Cond) 7768 CheckRight = false; 7769 else 7770 CheckLeft = false; 7771 } 7772 7773 // We need to maintain the offsets for the right and the left hand side 7774 // separately to check if every possible indexed expression is a valid 7775 // string literal. They might have different offsets for different string 7776 // literals in the end. 7777 StringLiteralCheckType Left; 7778 if (!CheckLeft) 7779 Left = SLCT_UncheckedLiteral; 7780 else { 7781 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7782 HasVAListArg, format_idx, firstDataArg, 7783 Type, CallType, InFunctionCall, 7784 CheckedVarArgs, UncoveredArg, Offset, 7785 IgnoreStringsWithoutSpecifiers); 7786 if (Left == SLCT_NotALiteral || !CheckRight) { 7787 return Left; 7788 } 7789 } 7790 7791 StringLiteralCheckType Right = checkFormatStringExpr( 7792 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7793 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7794 IgnoreStringsWithoutSpecifiers); 7795 7796 return (CheckLeft && Left < Right) ? Left : Right; 7797 } 7798 7799 case Stmt::ImplicitCastExprClass: 7800 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7801 goto tryAgain; 7802 7803 case Stmt::OpaqueValueExprClass: 7804 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7805 E = src; 7806 goto tryAgain; 7807 } 7808 return SLCT_NotALiteral; 7809 7810 case Stmt::PredefinedExprClass: 7811 // While __func__, etc., are technically not string literals, they 7812 // cannot contain format specifiers and thus are not a security 7813 // liability. 7814 return SLCT_UncheckedLiteral; 7815 7816 case Stmt::DeclRefExprClass: { 7817 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7818 7819 // As an exception, do not flag errors for variables binding to 7820 // const string literals. 7821 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7822 bool isConstant = false; 7823 QualType T = DR->getType(); 7824 7825 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7826 isConstant = AT->getElementType().isConstant(S.Context); 7827 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7828 isConstant = T.isConstant(S.Context) && 7829 PT->getPointeeType().isConstant(S.Context); 7830 } else if (T->isObjCObjectPointerType()) { 7831 // In ObjC, there is usually no "const ObjectPointer" type, 7832 // so don't check if the pointee type is constant. 7833 isConstant = T.isConstant(S.Context); 7834 } 7835 7836 if (isConstant) { 7837 if (const Expr *Init = VD->getAnyInitializer()) { 7838 // Look through initializers like const char c[] = { "foo" } 7839 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7840 if (InitList->isStringLiteralInit()) 7841 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7842 } 7843 return checkFormatStringExpr(S, Init, Args, 7844 HasVAListArg, format_idx, 7845 firstDataArg, Type, CallType, 7846 /*InFunctionCall*/ false, CheckedVarArgs, 7847 UncoveredArg, Offset); 7848 } 7849 } 7850 7851 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7852 // special check to see if the format string is a function parameter 7853 // of the function calling the printf function. If the function 7854 // has an attribute indicating it is a printf-like function, then we 7855 // should suppress warnings concerning non-literals being used in a call 7856 // to a vprintf function. For example: 7857 // 7858 // void 7859 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7860 // va_list ap; 7861 // va_start(ap, fmt); 7862 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7863 // ... 7864 // } 7865 if (HasVAListArg) { 7866 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7867 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7868 int PVIndex = PV->getFunctionScopeIndex() + 1; 7869 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7870 // adjust for implicit parameter 7871 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7872 if (MD->isInstance()) 7873 ++PVIndex; 7874 // We also check if the formats are compatible. 7875 // We can't pass a 'scanf' string to a 'printf' function. 7876 if (PVIndex == PVFormat->getFormatIdx() && 7877 Type == S.GetFormatStringType(PVFormat)) 7878 return SLCT_UncheckedLiteral; 7879 } 7880 } 7881 } 7882 } 7883 } 7884 7885 return SLCT_NotALiteral; 7886 } 7887 7888 case Stmt::CallExprClass: 7889 case Stmt::CXXMemberCallExprClass: { 7890 const CallExpr *CE = cast<CallExpr>(E); 7891 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7892 bool IsFirst = true; 7893 StringLiteralCheckType CommonResult; 7894 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7895 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7896 StringLiteralCheckType Result = checkFormatStringExpr( 7897 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7898 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7899 IgnoreStringsWithoutSpecifiers); 7900 if (IsFirst) { 7901 CommonResult = Result; 7902 IsFirst = false; 7903 } 7904 } 7905 if (!IsFirst) 7906 return CommonResult; 7907 7908 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7909 unsigned BuiltinID = FD->getBuiltinID(); 7910 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7911 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7912 const Expr *Arg = CE->getArg(0); 7913 return checkFormatStringExpr(S, Arg, Args, 7914 HasVAListArg, format_idx, 7915 firstDataArg, Type, CallType, 7916 InFunctionCall, CheckedVarArgs, 7917 UncoveredArg, Offset, 7918 IgnoreStringsWithoutSpecifiers); 7919 } 7920 } 7921 } 7922 7923 return SLCT_NotALiteral; 7924 } 7925 case Stmt::ObjCMessageExprClass: { 7926 const auto *ME = cast<ObjCMessageExpr>(E); 7927 if (const auto *MD = ME->getMethodDecl()) { 7928 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7929 // As a special case heuristic, if we're using the method -[NSBundle 7930 // localizedStringForKey:value:table:], ignore any key strings that lack 7931 // format specifiers. The idea is that if the key doesn't have any 7932 // format specifiers then its probably just a key to map to the 7933 // localized strings. If it does have format specifiers though, then its 7934 // likely that the text of the key is the format string in the 7935 // programmer's language, and should be checked. 7936 const ObjCInterfaceDecl *IFace; 7937 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7938 IFace->getIdentifier()->isStr("NSBundle") && 7939 MD->getSelector().isKeywordSelector( 7940 {"localizedStringForKey", "value", "table"})) { 7941 IgnoreStringsWithoutSpecifiers = true; 7942 } 7943 7944 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7945 return checkFormatStringExpr( 7946 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7947 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7948 IgnoreStringsWithoutSpecifiers); 7949 } 7950 } 7951 7952 return SLCT_NotALiteral; 7953 } 7954 case Stmt::ObjCStringLiteralClass: 7955 case Stmt::StringLiteralClass: { 7956 const StringLiteral *StrE = nullptr; 7957 7958 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7959 StrE = ObjCFExpr->getString(); 7960 else 7961 StrE = cast<StringLiteral>(E); 7962 7963 if (StrE) { 7964 if (Offset.isNegative() || Offset > StrE->getLength()) { 7965 // TODO: It would be better to have an explicit warning for out of 7966 // bounds literals. 7967 return SLCT_NotALiteral; 7968 } 7969 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7970 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7971 firstDataArg, Type, InFunctionCall, CallType, 7972 CheckedVarArgs, UncoveredArg, 7973 IgnoreStringsWithoutSpecifiers); 7974 return SLCT_CheckedLiteral; 7975 } 7976 7977 return SLCT_NotALiteral; 7978 } 7979 case Stmt::BinaryOperatorClass: { 7980 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7981 7982 // A string literal + an int offset is still a string literal. 7983 if (BinOp->isAdditiveOp()) { 7984 Expr::EvalResult LResult, RResult; 7985 7986 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7987 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7988 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7989 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7990 7991 if (LIsInt != RIsInt) { 7992 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7993 7994 if (LIsInt) { 7995 if (BinOpKind == BO_Add) { 7996 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7997 E = BinOp->getRHS(); 7998 goto tryAgain; 7999 } 8000 } else { 8001 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 8002 E = BinOp->getLHS(); 8003 goto tryAgain; 8004 } 8005 } 8006 } 8007 8008 return SLCT_NotALiteral; 8009 } 8010 case Stmt::UnaryOperatorClass: { 8011 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 8012 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 8013 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 8014 Expr::EvalResult IndexResult; 8015 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 8016 Expr::SE_NoSideEffects, 8017 S.isConstantEvaluated())) { 8018 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 8019 /*RHS is int*/ true); 8020 E = ASE->getBase(); 8021 goto tryAgain; 8022 } 8023 } 8024 8025 return SLCT_NotALiteral; 8026 } 8027 8028 default: 8029 return SLCT_NotALiteral; 8030 } 8031 } 8032 8033 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 8034 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 8035 .Case("scanf", FST_Scanf) 8036 .Cases("printf", "printf0", FST_Printf) 8037 .Cases("NSString", "CFString", FST_NSString) 8038 .Case("strftime", FST_Strftime) 8039 .Case("strfmon", FST_Strfmon) 8040 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 8041 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 8042 .Case("os_trace", FST_OSLog) 8043 .Case("os_log", FST_OSLog) 8044 .Default(FST_Unknown); 8045 } 8046 8047 /// CheckFormatArguments - Check calls to printf and scanf (and similar 8048 /// functions) for correct use of format strings. 8049 /// Returns true if a format string has been fully checked. 8050 bool Sema::CheckFormatArguments(const FormatAttr *Format, 8051 ArrayRef<const Expr *> Args, 8052 bool IsCXXMember, 8053 VariadicCallType CallType, 8054 SourceLocation Loc, SourceRange Range, 8055 llvm::SmallBitVector &CheckedVarArgs) { 8056 FormatStringInfo FSI; 8057 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 8058 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 8059 FSI.FirstDataArg, GetFormatStringType(Format), 8060 CallType, Loc, Range, CheckedVarArgs); 8061 return false; 8062 } 8063 8064 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 8065 bool HasVAListArg, unsigned format_idx, 8066 unsigned firstDataArg, FormatStringType Type, 8067 VariadicCallType CallType, 8068 SourceLocation Loc, SourceRange Range, 8069 llvm::SmallBitVector &CheckedVarArgs) { 8070 // CHECK: printf/scanf-like function is called with no format string. 8071 if (format_idx >= Args.size()) { 8072 Diag(Loc, diag::warn_missing_format_string) << Range; 8073 return false; 8074 } 8075 8076 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 8077 8078 // CHECK: format string is not a string literal. 8079 // 8080 // Dynamically generated format strings are difficult to 8081 // automatically vet at compile time. Requiring that format strings 8082 // are string literals: (1) permits the checking of format strings by 8083 // the compiler and thereby (2) can practically remove the source of 8084 // many format string exploits. 8085 8086 // Format string can be either ObjC string (e.g. @"%d") or 8087 // C string (e.g. "%d") 8088 // ObjC string uses the same format specifiers as C string, so we can use 8089 // the same format string checking logic for both ObjC and C strings. 8090 UncoveredArgHandler UncoveredArg; 8091 StringLiteralCheckType CT = 8092 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 8093 format_idx, firstDataArg, Type, CallType, 8094 /*IsFunctionCall*/ true, CheckedVarArgs, 8095 UncoveredArg, 8096 /*no string offset*/ llvm::APSInt(64, false) = 0); 8097 8098 // Generate a diagnostic where an uncovered argument is detected. 8099 if (UncoveredArg.hasUncoveredArg()) { 8100 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 8101 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 8102 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 8103 } 8104 8105 if (CT != SLCT_NotALiteral) 8106 // Literal format string found, check done! 8107 return CT == SLCT_CheckedLiteral; 8108 8109 // Strftime is particular as it always uses a single 'time' argument, 8110 // so it is safe to pass a non-literal string. 8111 if (Type == FST_Strftime) 8112 return false; 8113 8114 // Do not emit diag when the string param is a macro expansion and the 8115 // format is either NSString or CFString. This is a hack to prevent 8116 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 8117 // which are usually used in place of NS and CF string literals. 8118 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 8119 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 8120 return false; 8121 8122 // If there are no arguments specified, warn with -Wformat-security, otherwise 8123 // warn only with -Wformat-nonliteral. 8124 if (Args.size() == firstDataArg) { 8125 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 8126 << OrigFormatExpr->getSourceRange(); 8127 switch (Type) { 8128 default: 8129 break; 8130 case FST_Kprintf: 8131 case FST_FreeBSDKPrintf: 8132 case FST_Printf: 8133 Diag(FormatLoc, diag::note_format_security_fixit) 8134 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 8135 break; 8136 case FST_NSString: 8137 Diag(FormatLoc, diag::note_format_security_fixit) 8138 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 8139 break; 8140 } 8141 } else { 8142 Diag(FormatLoc, diag::warn_format_nonliteral) 8143 << OrigFormatExpr->getSourceRange(); 8144 } 8145 return false; 8146 } 8147 8148 namespace { 8149 8150 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 8151 protected: 8152 Sema &S; 8153 const FormatStringLiteral *FExpr; 8154 const Expr *OrigFormatExpr; 8155 const Sema::FormatStringType FSType; 8156 const unsigned FirstDataArg; 8157 const unsigned NumDataArgs; 8158 const char *Beg; // Start of format string. 8159 const bool HasVAListArg; 8160 ArrayRef<const Expr *> Args; 8161 unsigned FormatIdx; 8162 llvm::SmallBitVector CoveredArgs; 8163 bool usesPositionalArgs = false; 8164 bool atFirstArg = true; 8165 bool inFunctionCall; 8166 Sema::VariadicCallType CallType; 8167 llvm::SmallBitVector &CheckedVarArgs; 8168 UncoveredArgHandler &UncoveredArg; 8169 8170 public: 8171 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8172 const Expr *origFormatExpr, 8173 const Sema::FormatStringType type, unsigned firstDataArg, 8174 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8175 ArrayRef<const Expr *> Args, unsigned formatIdx, 8176 bool inFunctionCall, Sema::VariadicCallType callType, 8177 llvm::SmallBitVector &CheckedVarArgs, 8178 UncoveredArgHandler &UncoveredArg) 8179 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8180 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8181 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8182 inFunctionCall(inFunctionCall), CallType(callType), 8183 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8184 CoveredArgs.resize(numDataArgs); 8185 CoveredArgs.reset(); 8186 } 8187 8188 void DoneProcessing(); 8189 8190 void HandleIncompleteSpecifier(const char *startSpecifier, 8191 unsigned specifierLen) override; 8192 8193 void HandleInvalidLengthModifier( 8194 const analyze_format_string::FormatSpecifier &FS, 8195 const analyze_format_string::ConversionSpecifier &CS, 8196 const char *startSpecifier, unsigned specifierLen, 8197 unsigned DiagID); 8198 8199 void HandleNonStandardLengthModifier( 8200 const analyze_format_string::FormatSpecifier &FS, 8201 const char *startSpecifier, unsigned specifierLen); 8202 8203 void HandleNonStandardConversionSpecifier( 8204 const analyze_format_string::ConversionSpecifier &CS, 8205 const char *startSpecifier, unsigned specifierLen); 8206 8207 void HandlePosition(const char *startPos, unsigned posLen) override; 8208 8209 void HandleInvalidPosition(const char *startSpecifier, 8210 unsigned specifierLen, 8211 analyze_format_string::PositionContext p) override; 8212 8213 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8214 8215 void HandleNullChar(const char *nullCharacter) override; 8216 8217 template <typename Range> 8218 static void 8219 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8220 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8221 bool IsStringLocation, Range StringRange, 8222 ArrayRef<FixItHint> Fixit = None); 8223 8224 protected: 8225 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8226 const char *startSpec, 8227 unsigned specifierLen, 8228 const char *csStart, unsigned csLen); 8229 8230 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8231 const char *startSpec, 8232 unsigned specifierLen); 8233 8234 SourceRange getFormatStringRange(); 8235 CharSourceRange getSpecifierRange(const char *startSpecifier, 8236 unsigned specifierLen); 8237 SourceLocation getLocationOfByte(const char *x); 8238 8239 const Expr *getDataArg(unsigned i) const; 8240 8241 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8242 const analyze_format_string::ConversionSpecifier &CS, 8243 const char *startSpecifier, unsigned specifierLen, 8244 unsigned argIndex); 8245 8246 template <typename Range> 8247 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8248 bool IsStringLocation, Range StringRange, 8249 ArrayRef<FixItHint> Fixit = None); 8250 }; 8251 8252 } // namespace 8253 8254 SourceRange CheckFormatHandler::getFormatStringRange() { 8255 return OrigFormatExpr->getSourceRange(); 8256 } 8257 8258 CharSourceRange CheckFormatHandler:: 8259 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8260 SourceLocation Start = getLocationOfByte(startSpecifier); 8261 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8262 8263 // Advance the end SourceLocation by one due to half-open ranges. 8264 End = End.getLocWithOffset(1); 8265 8266 return CharSourceRange::getCharRange(Start, End); 8267 } 8268 8269 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8270 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8271 S.getLangOpts(), S.Context.getTargetInfo()); 8272 } 8273 8274 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8275 unsigned specifierLen){ 8276 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8277 getLocationOfByte(startSpecifier), 8278 /*IsStringLocation*/true, 8279 getSpecifierRange(startSpecifier, specifierLen)); 8280 } 8281 8282 void CheckFormatHandler::HandleInvalidLengthModifier( 8283 const analyze_format_string::FormatSpecifier &FS, 8284 const analyze_format_string::ConversionSpecifier &CS, 8285 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8286 using namespace analyze_format_string; 8287 8288 const LengthModifier &LM = FS.getLengthModifier(); 8289 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8290 8291 // See if we know how to fix this length modifier. 8292 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8293 if (FixedLM) { 8294 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8295 getLocationOfByte(LM.getStart()), 8296 /*IsStringLocation*/true, 8297 getSpecifierRange(startSpecifier, specifierLen)); 8298 8299 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8300 << FixedLM->toString() 8301 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8302 8303 } else { 8304 FixItHint Hint; 8305 if (DiagID == diag::warn_format_nonsensical_length) 8306 Hint = FixItHint::CreateRemoval(LMRange); 8307 8308 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8309 getLocationOfByte(LM.getStart()), 8310 /*IsStringLocation*/true, 8311 getSpecifierRange(startSpecifier, specifierLen), 8312 Hint); 8313 } 8314 } 8315 8316 void CheckFormatHandler::HandleNonStandardLengthModifier( 8317 const analyze_format_string::FormatSpecifier &FS, 8318 const char *startSpecifier, unsigned specifierLen) { 8319 using namespace analyze_format_string; 8320 8321 const LengthModifier &LM = FS.getLengthModifier(); 8322 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8323 8324 // See if we know how to fix this length modifier. 8325 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8326 if (FixedLM) { 8327 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8328 << LM.toString() << 0, 8329 getLocationOfByte(LM.getStart()), 8330 /*IsStringLocation*/true, 8331 getSpecifierRange(startSpecifier, specifierLen)); 8332 8333 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8334 << FixedLM->toString() 8335 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8336 8337 } else { 8338 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8339 << LM.toString() << 0, 8340 getLocationOfByte(LM.getStart()), 8341 /*IsStringLocation*/true, 8342 getSpecifierRange(startSpecifier, specifierLen)); 8343 } 8344 } 8345 8346 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8347 const analyze_format_string::ConversionSpecifier &CS, 8348 const char *startSpecifier, unsigned specifierLen) { 8349 using namespace analyze_format_string; 8350 8351 // See if we know how to fix this conversion specifier. 8352 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8353 if (FixedCS) { 8354 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8355 << CS.toString() << /*conversion specifier*/1, 8356 getLocationOfByte(CS.getStart()), 8357 /*IsStringLocation*/true, 8358 getSpecifierRange(startSpecifier, specifierLen)); 8359 8360 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8361 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8362 << FixedCS->toString() 8363 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8364 } else { 8365 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8366 << CS.toString() << /*conversion specifier*/1, 8367 getLocationOfByte(CS.getStart()), 8368 /*IsStringLocation*/true, 8369 getSpecifierRange(startSpecifier, specifierLen)); 8370 } 8371 } 8372 8373 void CheckFormatHandler::HandlePosition(const char *startPos, 8374 unsigned posLen) { 8375 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8376 getLocationOfByte(startPos), 8377 /*IsStringLocation*/true, 8378 getSpecifierRange(startPos, posLen)); 8379 } 8380 8381 void 8382 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8383 analyze_format_string::PositionContext p) { 8384 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8385 << (unsigned) p, 8386 getLocationOfByte(startPos), /*IsStringLocation*/true, 8387 getSpecifierRange(startPos, posLen)); 8388 } 8389 8390 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8391 unsigned posLen) { 8392 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8393 getLocationOfByte(startPos), 8394 /*IsStringLocation*/true, 8395 getSpecifierRange(startPos, posLen)); 8396 } 8397 8398 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8399 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8400 // The presence of a null character is likely an error. 8401 EmitFormatDiagnostic( 8402 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8403 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8404 getFormatStringRange()); 8405 } 8406 } 8407 8408 // Note that this may return NULL if there was an error parsing or building 8409 // one of the argument expressions. 8410 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8411 return Args[FirstDataArg + i]; 8412 } 8413 8414 void CheckFormatHandler::DoneProcessing() { 8415 // Does the number of data arguments exceed the number of 8416 // format conversions in the format string? 8417 if (!HasVAListArg) { 8418 // Find any arguments that weren't covered. 8419 CoveredArgs.flip(); 8420 signed notCoveredArg = CoveredArgs.find_first(); 8421 if (notCoveredArg >= 0) { 8422 assert((unsigned)notCoveredArg < NumDataArgs); 8423 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8424 } else { 8425 UncoveredArg.setAllCovered(); 8426 } 8427 } 8428 } 8429 8430 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8431 const Expr *ArgExpr) { 8432 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8433 "Invalid state"); 8434 8435 if (!ArgExpr) 8436 return; 8437 8438 SourceLocation Loc = ArgExpr->getBeginLoc(); 8439 8440 if (S.getSourceManager().isInSystemMacro(Loc)) 8441 return; 8442 8443 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8444 for (auto E : DiagnosticExprs) 8445 PDiag << E->getSourceRange(); 8446 8447 CheckFormatHandler::EmitFormatDiagnostic( 8448 S, IsFunctionCall, DiagnosticExprs[0], 8449 PDiag, Loc, /*IsStringLocation*/false, 8450 DiagnosticExprs[0]->getSourceRange()); 8451 } 8452 8453 bool 8454 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8455 SourceLocation Loc, 8456 const char *startSpec, 8457 unsigned specifierLen, 8458 const char *csStart, 8459 unsigned csLen) { 8460 bool keepGoing = true; 8461 if (argIndex < NumDataArgs) { 8462 // Consider the argument coverered, even though the specifier doesn't 8463 // make sense. 8464 CoveredArgs.set(argIndex); 8465 } 8466 else { 8467 // If argIndex exceeds the number of data arguments we 8468 // don't issue a warning because that is just a cascade of warnings (and 8469 // they may have intended '%%' anyway). We don't want to continue processing 8470 // the format string after this point, however, as we will like just get 8471 // gibberish when trying to match arguments. 8472 keepGoing = false; 8473 } 8474 8475 StringRef Specifier(csStart, csLen); 8476 8477 // If the specifier in non-printable, it could be the first byte of a UTF-8 8478 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8479 // hex value. 8480 std::string CodePointStr; 8481 if (!llvm::sys::locale::isPrint(*csStart)) { 8482 llvm::UTF32 CodePoint; 8483 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8484 const llvm::UTF8 *E = 8485 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8486 llvm::ConversionResult Result = 8487 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8488 8489 if (Result != llvm::conversionOK) { 8490 unsigned char FirstChar = *csStart; 8491 CodePoint = (llvm::UTF32)FirstChar; 8492 } 8493 8494 llvm::raw_string_ostream OS(CodePointStr); 8495 if (CodePoint < 256) 8496 OS << "\\x" << llvm::format("%02x", CodePoint); 8497 else if (CodePoint <= 0xFFFF) 8498 OS << "\\u" << llvm::format("%04x", CodePoint); 8499 else 8500 OS << "\\U" << llvm::format("%08x", CodePoint); 8501 OS.flush(); 8502 Specifier = CodePointStr; 8503 } 8504 8505 EmitFormatDiagnostic( 8506 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8507 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8508 8509 return keepGoing; 8510 } 8511 8512 void 8513 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8514 const char *startSpec, 8515 unsigned specifierLen) { 8516 EmitFormatDiagnostic( 8517 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8518 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8519 } 8520 8521 bool 8522 CheckFormatHandler::CheckNumArgs( 8523 const analyze_format_string::FormatSpecifier &FS, 8524 const analyze_format_string::ConversionSpecifier &CS, 8525 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8526 8527 if (argIndex >= NumDataArgs) { 8528 PartialDiagnostic PDiag = FS.usesPositionalArg() 8529 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8530 << (argIndex+1) << NumDataArgs) 8531 : S.PDiag(diag::warn_printf_insufficient_data_args); 8532 EmitFormatDiagnostic( 8533 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8534 getSpecifierRange(startSpecifier, specifierLen)); 8535 8536 // Since more arguments than conversion tokens are given, by extension 8537 // all arguments are covered, so mark this as so. 8538 UncoveredArg.setAllCovered(); 8539 return false; 8540 } 8541 return true; 8542 } 8543 8544 template<typename Range> 8545 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8546 SourceLocation Loc, 8547 bool IsStringLocation, 8548 Range StringRange, 8549 ArrayRef<FixItHint> FixIt) { 8550 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8551 Loc, IsStringLocation, StringRange, FixIt); 8552 } 8553 8554 /// If the format string is not within the function call, emit a note 8555 /// so that the function call and string are in diagnostic messages. 8556 /// 8557 /// \param InFunctionCall if true, the format string is within the function 8558 /// call and only one diagnostic message will be produced. Otherwise, an 8559 /// extra note will be emitted pointing to location of the format string. 8560 /// 8561 /// \param ArgumentExpr the expression that is passed as the format string 8562 /// argument in the function call. Used for getting locations when two 8563 /// diagnostics are emitted. 8564 /// 8565 /// \param PDiag the callee should already have provided any strings for the 8566 /// diagnostic message. This function only adds locations and fixits 8567 /// to diagnostics. 8568 /// 8569 /// \param Loc primary location for diagnostic. If two diagnostics are 8570 /// required, one will be at Loc and a new SourceLocation will be created for 8571 /// the other one. 8572 /// 8573 /// \param IsStringLocation if true, Loc points to the format string should be 8574 /// used for the note. Otherwise, Loc points to the argument list and will 8575 /// be used with PDiag. 8576 /// 8577 /// \param StringRange some or all of the string to highlight. This is 8578 /// templated so it can accept either a CharSourceRange or a SourceRange. 8579 /// 8580 /// \param FixIt optional fix it hint for the format string. 8581 template <typename Range> 8582 void CheckFormatHandler::EmitFormatDiagnostic( 8583 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8584 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8585 Range StringRange, ArrayRef<FixItHint> FixIt) { 8586 if (InFunctionCall) { 8587 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8588 D << StringRange; 8589 D << FixIt; 8590 } else { 8591 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8592 << ArgumentExpr->getSourceRange(); 8593 8594 const Sema::SemaDiagnosticBuilder &Note = 8595 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8596 diag::note_format_string_defined); 8597 8598 Note << StringRange; 8599 Note << FixIt; 8600 } 8601 } 8602 8603 //===--- CHECK: Printf format string checking ------------------------------===// 8604 8605 namespace { 8606 8607 class CheckPrintfHandler : public CheckFormatHandler { 8608 public: 8609 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8610 const Expr *origFormatExpr, 8611 const Sema::FormatStringType type, unsigned firstDataArg, 8612 unsigned numDataArgs, bool isObjC, const char *beg, 8613 bool hasVAListArg, ArrayRef<const Expr *> Args, 8614 unsigned formatIdx, bool inFunctionCall, 8615 Sema::VariadicCallType CallType, 8616 llvm::SmallBitVector &CheckedVarArgs, 8617 UncoveredArgHandler &UncoveredArg) 8618 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8619 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8620 inFunctionCall, CallType, CheckedVarArgs, 8621 UncoveredArg) {} 8622 8623 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8624 8625 /// Returns true if '%@' specifiers are allowed in the format string. 8626 bool allowsObjCArg() const { 8627 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8628 FSType == Sema::FST_OSTrace; 8629 } 8630 8631 bool HandleInvalidPrintfConversionSpecifier( 8632 const analyze_printf::PrintfSpecifier &FS, 8633 const char *startSpecifier, 8634 unsigned specifierLen) override; 8635 8636 void handleInvalidMaskType(StringRef MaskType) override; 8637 8638 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8639 const char *startSpecifier, 8640 unsigned specifierLen) override; 8641 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8642 const char *StartSpecifier, 8643 unsigned SpecifierLen, 8644 const Expr *E); 8645 8646 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8647 const char *startSpecifier, unsigned specifierLen); 8648 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8649 const analyze_printf::OptionalAmount &Amt, 8650 unsigned type, 8651 const char *startSpecifier, unsigned specifierLen); 8652 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8653 const analyze_printf::OptionalFlag &flag, 8654 const char *startSpecifier, unsigned specifierLen); 8655 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8656 const analyze_printf::OptionalFlag &ignoredFlag, 8657 const analyze_printf::OptionalFlag &flag, 8658 const char *startSpecifier, unsigned specifierLen); 8659 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8660 const Expr *E); 8661 8662 void HandleEmptyObjCModifierFlag(const char *startFlag, 8663 unsigned flagLen) override; 8664 8665 void HandleInvalidObjCModifierFlag(const char *startFlag, 8666 unsigned flagLen) override; 8667 8668 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8669 const char *flagsEnd, 8670 const char *conversionPosition) 8671 override; 8672 }; 8673 8674 } // namespace 8675 8676 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8677 const analyze_printf::PrintfSpecifier &FS, 8678 const char *startSpecifier, 8679 unsigned specifierLen) { 8680 const analyze_printf::PrintfConversionSpecifier &CS = 8681 FS.getConversionSpecifier(); 8682 8683 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8684 getLocationOfByte(CS.getStart()), 8685 startSpecifier, specifierLen, 8686 CS.getStart(), CS.getLength()); 8687 } 8688 8689 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8690 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8691 } 8692 8693 bool CheckPrintfHandler::HandleAmount( 8694 const analyze_format_string::OptionalAmount &Amt, 8695 unsigned k, const char *startSpecifier, 8696 unsigned specifierLen) { 8697 if (Amt.hasDataArgument()) { 8698 if (!HasVAListArg) { 8699 unsigned argIndex = Amt.getArgIndex(); 8700 if (argIndex >= NumDataArgs) { 8701 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8702 << k, 8703 getLocationOfByte(Amt.getStart()), 8704 /*IsStringLocation*/true, 8705 getSpecifierRange(startSpecifier, specifierLen)); 8706 // Don't do any more checking. We will just emit 8707 // spurious errors. 8708 return false; 8709 } 8710 8711 // Type check the data argument. It should be an 'int'. 8712 // Although not in conformance with C99, we also allow the argument to be 8713 // an 'unsigned int' as that is a reasonably safe case. GCC also 8714 // doesn't emit a warning for that case. 8715 CoveredArgs.set(argIndex); 8716 const Expr *Arg = getDataArg(argIndex); 8717 if (!Arg) 8718 return false; 8719 8720 QualType T = Arg->getType(); 8721 8722 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8723 assert(AT.isValid()); 8724 8725 if (!AT.matchesType(S.Context, T)) { 8726 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8727 << k << AT.getRepresentativeTypeName(S.Context) 8728 << T << Arg->getSourceRange(), 8729 getLocationOfByte(Amt.getStart()), 8730 /*IsStringLocation*/true, 8731 getSpecifierRange(startSpecifier, specifierLen)); 8732 // Don't do any more checking. We will just emit 8733 // spurious errors. 8734 return false; 8735 } 8736 } 8737 } 8738 return true; 8739 } 8740 8741 void CheckPrintfHandler::HandleInvalidAmount( 8742 const analyze_printf::PrintfSpecifier &FS, 8743 const analyze_printf::OptionalAmount &Amt, 8744 unsigned type, 8745 const char *startSpecifier, 8746 unsigned specifierLen) { 8747 const analyze_printf::PrintfConversionSpecifier &CS = 8748 FS.getConversionSpecifier(); 8749 8750 FixItHint fixit = 8751 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8752 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8753 Amt.getConstantLength())) 8754 : FixItHint(); 8755 8756 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8757 << type << CS.toString(), 8758 getLocationOfByte(Amt.getStart()), 8759 /*IsStringLocation*/true, 8760 getSpecifierRange(startSpecifier, specifierLen), 8761 fixit); 8762 } 8763 8764 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8765 const analyze_printf::OptionalFlag &flag, 8766 const char *startSpecifier, 8767 unsigned specifierLen) { 8768 // Warn about pointless flag with a fixit removal. 8769 const analyze_printf::PrintfConversionSpecifier &CS = 8770 FS.getConversionSpecifier(); 8771 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8772 << flag.toString() << CS.toString(), 8773 getLocationOfByte(flag.getPosition()), 8774 /*IsStringLocation*/true, 8775 getSpecifierRange(startSpecifier, specifierLen), 8776 FixItHint::CreateRemoval( 8777 getSpecifierRange(flag.getPosition(), 1))); 8778 } 8779 8780 void CheckPrintfHandler::HandleIgnoredFlag( 8781 const analyze_printf::PrintfSpecifier &FS, 8782 const analyze_printf::OptionalFlag &ignoredFlag, 8783 const analyze_printf::OptionalFlag &flag, 8784 const char *startSpecifier, 8785 unsigned specifierLen) { 8786 // Warn about ignored flag with a fixit removal. 8787 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8788 << ignoredFlag.toString() << flag.toString(), 8789 getLocationOfByte(ignoredFlag.getPosition()), 8790 /*IsStringLocation*/true, 8791 getSpecifierRange(startSpecifier, specifierLen), 8792 FixItHint::CreateRemoval( 8793 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8794 } 8795 8796 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8797 unsigned flagLen) { 8798 // Warn about an empty flag. 8799 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8800 getLocationOfByte(startFlag), 8801 /*IsStringLocation*/true, 8802 getSpecifierRange(startFlag, flagLen)); 8803 } 8804 8805 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8806 unsigned flagLen) { 8807 // Warn about an invalid flag. 8808 auto Range = getSpecifierRange(startFlag, flagLen); 8809 StringRef flag(startFlag, flagLen); 8810 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8811 getLocationOfByte(startFlag), 8812 /*IsStringLocation*/true, 8813 Range, FixItHint::CreateRemoval(Range)); 8814 } 8815 8816 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8817 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8818 // Warn about using '[...]' without a '@' conversion. 8819 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8820 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8821 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8822 getLocationOfByte(conversionPosition), 8823 /*IsStringLocation*/true, 8824 Range, FixItHint::CreateRemoval(Range)); 8825 } 8826 8827 // Determines if the specified is a C++ class or struct containing 8828 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8829 // "c_str()"). 8830 template<typename MemberKind> 8831 static llvm::SmallPtrSet<MemberKind*, 1> 8832 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8833 const RecordType *RT = Ty->getAs<RecordType>(); 8834 llvm::SmallPtrSet<MemberKind*, 1> Results; 8835 8836 if (!RT) 8837 return Results; 8838 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8839 if (!RD || !RD->getDefinition()) 8840 return Results; 8841 8842 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8843 Sema::LookupMemberName); 8844 R.suppressDiagnostics(); 8845 8846 // We just need to include all members of the right kind turned up by the 8847 // filter, at this point. 8848 if (S.LookupQualifiedName(R, RT->getDecl())) 8849 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8850 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8851 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8852 Results.insert(FK); 8853 } 8854 return Results; 8855 } 8856 8857 /// Check if we could call '.c_str()' on an object. 8858 /// 8859 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8860 /// allow the call, or if it would be ambiguous). 8861 bool Sema::hasCStrMethod(const Expr *E) { 8862 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8863 8864 MethodSet Results = 8865 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8866 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8867 MI != ME; ++MI) 8868 if ((*MI)->getMinRequiredArguments() == 0) 8869 return true; 8870 return false; 8871 } 8872 8873 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8874 // better diagnostic if so. AT is assumed to be valid. 8875 // Returns true when a c_str() conversion method is found. 8876 bool CheckPrintfHandler::checkForCStrMembers( 8877 const analyze_printf::ArgType &AT, const Expr *E) { 8878 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8879 8880 MethodSet Results = 8881 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8882 8883 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8884 MI != ME; ++MI) { 8885 const CXXMethodDecl *Method = *MI; 8886 if (Method->getMinRequiredArguments() == 0 && 8887 AT.matchesType(S.Context, Method->getReturnType())) { 8888 // FIXME: Suggest parens if the expression needs them. 8889 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8890 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8891 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8892 return true; 8893 } 8894 } 8895 8896 return false; 8897 } 8898 8899 bool 8900 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8901 &FS, 8902 const char *startSpecifier, 8903 unsigned specifierLen) { 8904 using namespace analyze_format_string; 8905 using namespace analyze_printf; 8906 8907 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8908 8909 if (FS.consumesDataArgument()) { 8910 if (atFirstArg) { 8911 atFirstArg = false; 8912 usesPositionalArgs = FS.usesPositionalArg(); 8913 } 8914 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8915 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8916 startSpecifier, specifierLen); 8917 return false; 8918 } 8919 } 8920 8921 // First check if the field width, precision, and conversion specifier 8922 // have matching data arguments. 8923 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8924 startSpecifier, specifierLen)) { 8925 return false; 8926 } 8927 8928 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8929 startSpecifier, specifierLen)) { 8930 return false; 8931 } 8932 8933 if (!CS.consumesDataArgument()) { 8934 // FIXME: Technically specifying a precision or field width here 8935 // makes no sense. Worth issuing a warning at some point. 8936 return true; 8937 } 8938 8939 // Consume the argument. 8940 unsigned argIndex = FS.getArgIndex(); 8941 if (argIndex < NumDataArgs) { 8942 // The check to see if the argIndex is valid will come later. 8943 // We set the bit here because we may exit early from this 8944 // function if we encounter some other error. 8945 CoveredArgs.set(argIndex); 8946 } 8947 8948 // FreeBSD kernel extensions. 8949 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8950 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8951 // We need at least two arguments. 8952 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8953 return false; 8954 8955 // Claim the second argument. 8956 CoveredArgs.set(argIndex + 1); 8957 8958 // Type check the first argument (int for %b, pointer for %D) 8959 const Expr *Ex = getDataArg(argIndex); 8960 const analyze_printf::ArgType &AT = 8961 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8962 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8963 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8964 EmitFormatDiagnostic( 8965 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8966 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8967 << false << Ex->getSourceRange(), 8968 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8969 getSpecifierRange(startSpecifier, specifierLen)); 8970 8971 // Type check the second argument (char * for both %b and %D) 8972 Ex = getDataArg(argIndex + 1); 8973 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8974 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8975 EmitFormatDiagnostic( 8976 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8977 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8978 << false << Ex->getSourceRange(), 8979 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8980 getSpecifierRange(startSpecifier, specifierLen)); 8981 8982 return true; 8983 } 8984 8985 // Check for using an Objective-C specific conversion specifier 8986 // in a non-ObjC literal. 8987 if (!allowsObjCArg() && CS.isObjCArg()) { 8988 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8989 specifierLen); 8990 } 8991 8992 // %P can only be used with os_log. 8993 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8994 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8995 specifierLen); 8996 } 8997 8998 // %n is not allowed with os_log. 8999 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 9000 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 9001 getLocationOfByte(CS.getStart()), 9002 /*IsStringLocation*/ false, 9003 getSpecifierRange(startSpecifier, specifierLen)); 9004 9005 return true; 9006 } 9007 9008 // Only scalars are allowed for os_trace. 9009 if (FSType == Sema::FST_OSTrace && 9010 (CS.getKind() == ConversionSpecifier::PArg || 9011 CS.getKind() == ConversionSpecifier::sArg || 9012 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 9013 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9014 specifierLen); 9015 } 9016 9017 // Check for use of public/private annotation outside of os_log(). 9018 if (FSType != Sema::FST_OSLog) { 9019 if (FS.isPublic().isSet()) { 9020 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9021 << "public", 9022 getLocationOfByte(FS.isPublic().getPosition()), 9023 /*IsStringLocation*/ false, 9024 getSpecifierRange(startSpecifier, specifierLen)); 9025 } 9026 if (FS.isPrivate().isSet()) { 9027 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9028 << "private", 9029 getLocationOfByte(FS.isPrivate().getPosition()), 9030 /*IsStringLocation*/ false, 9031 getSpecifierRange(startSpecifier, specifierLen)); 9032 } 9033 } 9034 9035 // Check for invalid use of field width 9036 if (!FS.hasValidFieldWidth()) { 9037 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 9038 startSpecifier, specifierLen); 9039 } 9040 9041 // Check for invalid use of precision 9042 if (!FS.hasValidPrecision()) { 9043 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 9044 startSpecifier, specifierLen); 9045 } 9046 9047 // Precision is mandatory for %P specifier. 9048 if (CS.getKind() == ConversionSpecifier::PArg && 9049 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 9050 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 9051 getLocationOfByte(startSpecifier), 9052 /*IsStringLocation*/ false, 9053 getSpecifierRange(startSpecifier, specifierLen)); 9054 } 9055 9056 // Check each flag does not conflict with any other component. 9057 if (!FS.hasValidThousandsGroupingPrefix()) 9058 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 9059 if (!FS.hasValidLeadingZeros()) 9060 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 9061 if (!FS.hasValidPlusPrefix()) 9062 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 9063 if (!FS.hasValidSpacePrefix()) 9064 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 9065 if (!FS.hasValidAlternativeForm()) 9066 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 9067 if (!FS.hasValidLeftJustified()) 9068 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 9069 9070 // Check that flags are not ignored by another flag 9071 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 9072 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 9073 startSpecifier, specifierLen); 9074 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 9075 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 9076 startSpecifier, specifierLen); 9077 9078 // Check the length modifier is valid with the given conversion specifier. 9079 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9080 S.getLangOpts())) 9081 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9082 diag::warn_format_nonsensical_length); 9083 else if (!FS.hasStandardLengthModifier()) 9084 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9085 else if (!FS.hasStandardLengthConversionCombination()) 9086 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9087 diag::warn_format_non_standard_conversion_spec); 9088 9089 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9090 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9091 9092 // The remaining checks depend on the data arguments. 9093 if (HasVAListArg) 9094 return true; 9095 9096 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9097 return false; 9098 9099 const Expr *Arg = getDataArg(argIndex); 9100 if (!Arg) 9101 return true; 9102 9103 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 9104 } 9105 9106 static bool requiresParensToAddCast(const Expr *E) { 9107 // FIXME: We should have a general way to reason about operator 9108 // precedence and whether parens are actually needed here. 9109 // Take care of a few common cases where they aren't. 9110 const Expr *Inside = E->IgnoreImpCasts(); 9111 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 9112 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 9113 9114 switch (Inside->getStmtClass()) { 9115 case Stmt::ArraySubscriptExprClass: 9116 case Stmt::CallExprClass: 9117 case Stmt::CharacterLiteralClass: 9118 case Stmt::CXXBoolLiteralExprClass: 9119 case Stmt::DeclRefExprClass: 9120 case Stmt::FloatingLiteralClass: 9121 case Stmt::IntegerLiteralClass: 9122 case Stmt::MemberExprClass: 9123 case Stmt::ObjCArrayLiteralClass: 9124 case Stmt::ObjCBoolLiteralExprClass: 9125 case Stmt::ObjCBoxedExprClass: 9126 case Stmt::ObjCDictionaryLiteralClass: 9127 case Stmt::ObjCEncodeExprClass: 9128 case Stmt::ObjCIvarRefExprClass: 9129 case Stmt::ObjCMessageExprClass: 9130 case Stmt::ObjCPropertyRefExprClass: 9131 case Stmt::ObjCStringLiteralClass: 9132 case Stmt::ObjCSubscriptRefExprClass: 9133 case Stmt::ParenExprClass: 9134 case Stmt::StringLiteralClass: 9135 case Stmt::UnaryOperatorClass: 9136 return false; 9137 default: 9138 return true; 9139 } 9140 } 9141 9142 static std::pair<QualType, StringRef> 9143 shouldNotPrintDirectly(const ASTContext &Context, 9144 QualType IntendedTy, 9145 const Expr *E) { 9146 // Use a 'while' to peel off layers of typedefs. 9147 QualType TyTy = IntendedTy; 9148 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 9149 StringRef Name = UserTy->getDecl()->getName(); 9150 QualType CastTy = llvm::StringSwitch<QualType>(Name) 9151 .Case("CFIndex", Context.getNSIntegerType()) 9152 .Case("NSInteger", Context.getNSIntegerType()) 9153 .Case("NSUInteger", Context.getNSUIntegerType()) 9154 .Case("SInt32", Context.IntTy) 9155 .Case("UInt32", Context.UnsignedIntTy) 9156 .Default(QualType()); 9157 9158 if (!CastTy.isNull()) 9159 return std::make_pair(CastTy, Name); 9160 9161 TyTy = UserTy->desugar(); 9162 } 9163 9164 // Strip parens if necessary. 9165 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 9166 return shouldNotPrintDirectly(Context, 9167 PE->getSubExpr()->getType(), 9168 PE->getSubExpr()); 9169 9170 // If this is a conditional expression, then its result type is constructed 9171 // via usual arithmetic conversions and thus there might be no necessary 9172 // typedef sugar there. Recurse to operands to check for NSInteger & 9173 // Co. usage condition. 9174 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9175 QualType TrueTy, FalseTy; 9176 StringRef TrueName, FalseName; 9177 9178 std::tie(TrueTy, TrueName) = 9179 shouldNotPrintDirectly(Context, 9180 CO->getTrueExpr()->getType(), 9181 CO->getTrueExpr()); 9182 std::tie(FalseTy, FalseName) = 9183 shouldNotPrintDirectly(Context, 9184 CO->getFalseExpr()->getType(), 9185 CO->getFalseExpr()); 9186 9187 if (TrueTy == FalseTy) 9188 return std::make_pair(TrueTy, TrueName); 9189 else if (TrueTy.isNull()) 9190 return std::make_pair(FalseTy, FalseName); 9191 else if (FalseTy.isNull()) 9192 return std::make_pair(TrueTy, TrueName); 9193 } 9194 9195 return std::make_pair(QualType(), StringRef()); 9196 } 9197 9198 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9199 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9200 /// type do not count. 9201 static bool 9202 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9203 QualType From = ICE->getSubExpr()->getType(); 9204 QualType To = ICE->getType(); 9205 // It's an integer promotion if the destination type is the promoted 9206 // source type. 9207 if (ICE->getCastKind() == CK_IntegralCast && 9208 From->isPromotableIntegerType() && 9209 S.Context.getPromotedIntegerType(From) == To) 9210 return true; 9211 // Look through vector types, since we do default argument promotion for 9212 // those in OpenCL. 9213 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9214 From = VecTy->getElementType(); 9215 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9216 To = VecTy->getElementType(); 9217 // It's a floating promotion if the source type is a lower rank. 9218 return ICE->getCastKind() == CK_FloatingCast && 9219 S.Context.getFloatingTypeOrder(From, To) < 0; 9220 } 9221 9222 bool 9223 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9224 const char *StartSpecifier, 9225 unsigned SpecifierLen, 9226 const Expr *E) { 9227 using namespace analyze_format_string; 9228 using namespace analyze_printf; 9229 9230 // Now type check the data expression that matches the 9231 // format specifier. 9232 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9233 if (!AT.isValid()) 9234 return true; 9235 9236 QualType ExprTy = E->getType(); 9237 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9238 ExprTy = TET->getUnderlyingExpr()->getType(); 9239 } 9240 9241 // Diagnose attempts to print a boolean value as a character. Unlike other 9242 // -Wformat diagnostics, this is fine from a type perspective, but it still 9243 // doesn't make sense. 9244 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9245 E->isKnownToHaveBooleanValue()) { 9246 const CharSourceRange &CSR = 9247 getSpecifierRange(StartSpecifier, SpecifierLen); 9248 SmallString<4> FSString; 9249 llvm::raw_svector_ostream os(FSString); 9250 FS.toString(os); 9251 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9252 << FSString, 9253 E->getExprLoc(), false, CSR); 9254 return true; 9255 } 9256 9257 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9258 if (Match == analyze_printf::ArgType::Match) 9259 return true; 9260 9261 // Look through argument promotions for our error message's reported type. 9262 // This includes the integral and floating promotions, but excludes array 9263 // and function pointer decay (seeing that an argument intended to be a 9264 // string has type 'char [6]' is probably more confusing than 'char *') and 9265 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9266 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9267 if (isArithmeticArgumentPromotion(S, ICE)) { 9268 E = ICE->getSubExpr(); 9269 ExprTy = E->getType(); 9270 9271 // Check if we didn't match because of an implicit cast from a 'char' 9272 // or 'short' to an 'int'. This is done because printf is a varargs 9273 // function. 9274 if (ICE->getType() == S.Context.IntTy || 9275 ICE->getType() == S.Context.UnsignedIntTy) { 9276 // All further checking is done on the subexpression 9277 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9278 AT.matchesType(S.Context, ExprTy); 9279 if (ImplicitMatch == analyze_printf::ArgType::Match) 9280 return true; 9281 if (ImplicitMatch == ArgType::NoMatchPedantic || 9282 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9283 Match = ImplicitMatch; 9284 } 9285 } 9286 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9287 // Special case for 'a', which has type 'int' in C. 9288 // Note, however, that we do /not/ want to treat multibyte constants like 9289 // 'MooV' as characters! This form is deprecated but still exists. In 9290 // addition, don't treat expressions as of type 'char' if one byte length 9291 // modifier is provided. 9292 if (ExprTy == S.Context.IntTy && 9293 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9294 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9295 ExprTy = S.Context.CharTy; 9296 } 9297 9298 // Look through enums to their underlying type. 9299 bool IsEnum = false; 9300 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9301 ExprTy = EnumTy->getDecl()->getIntegerType(); 9302 IsEnum = true; 9303 } 9304 9305 // %C in an Objective-C context prints a unichar, not a wchar_t. 9306 // If the argument is an integer of some kind, believe the %C and suggest 9307 // a cast instead of changing the conversion specifier. 9308 QualType IntendedTy = ExprTy; 9309 if (isObjCContext() && 9310 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9311 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9312 !ExprTy->isCharType()) { 9313 // 'unichar' is defined as a typedef of unsigned short, but we should 9314 // prefer using the typedef if it is visible. 9315 IntendedTy = S.Context.UnsignedShortTy; 9316 9317 // While we are here, check if the value is an IntegerLiteral that happens 9318 // to be within the valid range. 9319 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9320 const llvm::APInt &V = IL->getValue(); 9321 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9322 return true; 9323 } 9324 9325 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9326 Sema::LookupOrdinaryName); 9327 if (S.LookupName(Result, S.getCurScope())) { 9328 NamedDecl *ND = Result.getFoundDecl(); 9329 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9330 if (TD->getUnderlyingType() == IntendedTy) 9331 IntendedTy = S.Context.getTypedefType(TD); 9332 } 9333 } 9334 } 9335 9336 // Special-case some of Darwin's platform-independence types by suggesting 9337 // casts to primitive types that are known to be large enough. 9338 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9339 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9340 QualType CastTy; 9341 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9342 if (!CastTy.isNull()) { 9343 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9344 // (long in ASTContext). Only complain to pedants. 9345 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9346 (AT.isSizeT() || AT.isPtrdiffT()) && 9347 AT.matchesType(S.Context, CastTy)) 9348 Match = ArgType::NoMatchPedantic; 9349 IntendedTy = CastTy; 9350 ShouldNotPrintDirectly = true; 9351 } 9352 } 9353 9354 // We may be able to offer a FixItHint if it is a supported type. 9355 PrintfSpecifier fixedFS = FS; 9356 bool Success = 9357 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9358 9359 if (Success) { 9360 // Get the fix string from the fixed format specifier 9361 SmallString<16> buf; 9362 llvm::raw_svector_ostream os(buf); 9363 fixedFS.toString(os); 9364 9365 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9366 9367 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9368 unsigned Diag; 9369 switch (Match) { 9370 case ArgType::Match: llvm_unreachable("expected non-matching"); 9371 case ArgType::NoMatchPedantic: 9372 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9373 break; 9374 case ArgType::NoMatchTypeConfusion: 9375 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9376 break; 9377 case ArgType::NoMatch: 9378 Diag = diag::warn_format_conversion_argument_type_mismatch; 9379 break; 9380 } 9381 9382 // In this case, the specifier is wrong and should be changed to match 9383 // the argument. 9384 EmitFormatDiagnostic(S.PDiag(Diag) 9385 << AT.getRepresentativeTypeName(S.Context) 9386 << IntendedTy << IsEnum << E->getSourceRange(), 9387 E->getBeginLoc(), 9388 /*IsStringLocation*/ false, SpecRange, 9389 FixItHint::CreateReplacement(SpecRange, os.str())); 9390 } else { 9391 // The canonical type for formatting this value is different from the 9392 // actual type of the expression. (This occurs, for example, with Darwin's 9393 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9394 // should be printed as 'long' for 64-bit compatibility.) 9395 // Rather than emitting a normal format/argument mismatch, we want to 9396 // add a cast to the recommended type (and correct the format string 9397 // if necessary). 9398 SmallString<16> CastBuf; 9399 llvm::raw_svector_ostream CastFix(CastBuf); 9400 CastFix << "("; 9401 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9402 CastFix << ")"; 9403 9404 SmallVector<FixItHint,4> Hints; 9405 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9406 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9407 9408 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9409 // If there's already a cast present, just replace it. 9410 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9411 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9412 9413 } else if (!requiresParensToAddCast(E)) { 9414 // If the expression has high enough precedence, 9415 // just write the C-style cast. 9416 Hints.push_back( 9417 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9418 } else { 9419 // Otherwise, add parens around the expression as well as the cast. 9420 CastFix << "("; 9421 Hints.push_back( 9422 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9423 9424 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9425 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9426 } 9427 9428 if (ShouldNotPrintDirectly) { 9429 // The expression has a type that should not be printed directly. 9430 // We extract the name from the typedef because we don't want to show 9431 // the underlying type in the diagnostic. 9432 StringRef Name; 9433 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9434 Name = TypedefTy->getDecl()->getName(); 9435 else 9436 Name = CastTyName; 9437 unsigned Diag = Match == ArgType::NoMatchPedantic 9438 ? diag::warn_format_argument_needs_cast_pedantic 9439 : diag::warn_format_argument_needs_cast; 9440 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9441 << E->getSourceRange(), 9442 E->getBeginLoc(), /*IsStringLocation=*/false, 9443 SpecRange, Hints); 9444 } else { 9445 // In this case, the expression could be printed using a different 9446 // specifier, but we've decided that the specifier is probably correct 9447 // and we should cast instead. Just use the normal warning message. 9448 EmitFormatDiagnostic( 9449 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9450 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9451 << E->getSourceRange(), 9452 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9453 } 9454 } 9455 } else { 9456 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9457 SpecifierLen); 9458 // Since the warning for passing non-POD types to variadic functions 9459 // was deferred until now, we emit a warning for non-POD 9460 // arguments here. 9461 switch (S.isValidVarArgType(ExprTy)) { 9462 case Sema::VAK_Valid: 9463 case Sema::VAK_ValidInCXX11: { 9464 unsigned Diag; 9465 switch (Match) { 9466 case ArgType::Match: llvm_unreachable("expected non-matching"); 9467 case ArgType::NoMatchPedantic: 9468 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9469 break; 9470 case ArgType::NoMatchTypeConfusion: 9471 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9472 break; 9473 case ArgType::NoMatch: 9474 Diag = diag::warn_format_conversion_argument_type_mismatch; 9475 break; 9476 } 9477 9478 EmitFormatDiagnostic( 9479 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9480 << IsEnum << CSR << E->getSourceRange(), 9481 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9482 break; 9483 } 9484 case Sema::VAK_Undefined: 9485 case Sema::VAK_MSVCUndefined: 9486 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9487 << S.getLangOpts().CPlusPlus11 << ExprTy 9488 << CallType 9489 << AT.getRepresentativeTypeName(S.Context) << CSR 9490 << E->getSourceRange(), 9491 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9492 checkForCStrMembers(AT, E); 9493 break; 9494 9495 case Sema::VAK_Invalid: 9496 if (ExprTy->isObjCObjectType()) 9497 EmitFormatDiagnostic( 9498 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9499 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9500 << AT.getRepresentativeTypeName(S.Context) << CSR 9501 << E->getSourceRange(), 9502 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9503 else 9504 // FIXME: If this is an initializer list, suggest removing the braces 9505 // or inserting a cast to the target type. 9506 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9507 << isa<InitListExpr>(E) << ExprTy << CallType 9508 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9509 break; 9510 } 9511 9512 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9513 "format string specifier index out of range"); 9514 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9515 } 9516 9517 return true; 9518 } 9519 9520 //===--- CHECK: Scanf format string checking ------------------------------===// 9521 9522 namespace { 9523 9524 class CheckScanfHandler : public CheckFormatHandler { 9525 public: 9526 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9527 const Expr *origFormatExpr, Sema::FormatStringType type, 9528 unsigned firstDataArg, unsigned numDataArgs, 9529 const char *beg, bool hasVAListArg, 9530 ArrayRef<const Expr *> Args, unsigned formatIdx, 9531 bool inFunctionCall, Sema::VariadicCallType CallType, 9532 llvm::SmallBitVector &CheckedVarArgs, 9533 UncoveredArgHandler &UncoveredArg) 9534 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9535 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9536 inFunctionCall, CallType, CheckedVarArgs, 9537 UncoveredArg) {} 9538 9539 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9540 const char *startSpecifier, 9541 unsigned specifierLen) override; 9542 9543 bool HandleInvalidScanfConversionSpecifier( 9544 const analyze_scanf::ScanfSpecifier &FS, 9545 const char *startSpecifier, 9546 unsigned specifierLen) override; 9547 9548 void HandleIncompleteScanList(const char *start, const char *end) override; 9549 }; 9550 9551 } // namespace 9552 9553 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9554 const char *end) { 9555 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9556 getLocationOfByte(end), /*IsStringLocation*/true, 9557 getSpecifierRange(start, end - start)); 9558 } 9559 9560 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9561 const analyze_scanf::ScanfSpecifier &FS, 9562 const char *startSpecifier, 9563 unsigned specifierLen) { 9564 const analyze_scanf::ScanfConversionSpecifier &CS = 9565 FS.getConversionSpecifier(); 9566 9567 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9568 getLocationOfByte(CS.getStart()), 9569 startSpecifier, specifierLen, 9570 CS.getStart(), CS.getLength()); 9571 } 9572 9573 bool CheckScanfHandler::HandleScanfSpecifier( 9574 const analyze_scanf::ScanfSpecifier &FS, 9575 const char *startSpecifier, 9576 unsigned specifierLen) { 9577 using namespace analyze_scanf; 9578 using namespace analyze_format_string; 9579 9580 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9581 9582 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9583 // be used to decide if we are using positional arguments consistently. 9584 if (FS.consumesDataArgument()) { 9585 if (atFirstArg) { 9586 atFirstArg = false; 9587 usesPositionalArgs = FS.usesPositionalArg(); 9588 } 9589 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9590 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9591 startSpecifier, specifierLen); 9592 return false; 9593 } 9594 } 9595 9596 // Check if the field with is non-zero. 9597 const OptionalAmount &Amt = FS.getFieldWidth(); 9598 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9599 if (Amt.getConstantAmount() == 0) { 9600 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9601 Amt.getConstantLength()); 9602 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9603 getLocationOfByte(Amt.getStart()), 9604 /*IsStringLocation*/true, R, 9605 FixItHint::CreateRemoval(R)); 9606 } 9607 } 9608 9609 if (!FS.consumesDataArgument()) { 9610 // FIXME: Technically specifying a precision or field width here 9611 // makes no sense. Worth issuing a warning at some point. 9612 return true; 9613 } 9614 9615 // Consume the argument. 9616 unsigned argIndex = FS.getArgIndex(); 9617 if (argIndex < NumDataArgs) { 9618 // The check to see if the argIndex is valid will come later. 9619 // We set the bit here because we may exit early from this 9620 // function if we encounter some other error. 9621 CoveredArgs.set(argIndex); 9622 } 9623 9624 // Check the length modifier is valid with the given conversion specifier. 9625 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9626 S.getLangOpts())) 9627 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9628 diag::warn_format_nonsensical_length); 9629 else if (!FS.hasStandardLengthModifier()) 9630 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9631 else if (!FS.hasStandardLengthConversionCombination()) 9632 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9633 diag::warn_format_non_standard_conversion_spec); 9634 9635 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9636 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9637 9638 // The remaining checks depend on the data arguments. 9639 if (HasVAListArg) 9640 return true; 9641 9642 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9643 return false; 9644 9645 // Check that the argument type matches the format specifier. 9646 const Expr *Ex = getDataArg(argIndex); 9647 if (!Ex) 9648 return true; 9649 9650 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9651 9652 if (!AT.isValid()) { 9653 return true; 9654 } 9655 9656 analyze_format_string::ArgType::MatchKind Match = 9657 AT.matchesType(S.Context, Ex->getType()); 9658 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9659 if (Match == analyze_format_string::ArgType::Match) 9660 return true; 9661 9662 ScanfSpecifier fixedFS = FS; 9663 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9664 S.getLangOpts(), S.Context); 9665 9666 unsigned Diag = 9667 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9668 : diag::warn_format_conversion_argument_type_mismatch; 9669 9670 if (Success) { 9671 // Get the fix string from the fixed format specifier. 9672 SmallString<128> buf; 9673 llvm::raw_svector_ostream os(buf); 9674 fixedFS.toString(os); 9675 9676 EmitFormatDiagnostic( 9677 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9678 << Ex->getType() << false << Ex->getSourceRange(), 9679 Ex->getBeginLoc(), 9680 /*IsStringLocation*/ false, 9681 getSpecifierRange(startSpecifier, specifierLen), 9682 FixItHint::CreateReplacement( 9683 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9684 } else { 9685 EmitFormatDiagnostic(S.PDiag(Diag) 9686 << AT.getRepresentativeTypeName(S.Context) 9687 << Ex->getType() << false << Ex->getSourceRange(), 9688 Ex->getBeginLoc(), 9689 /*IsStringLocation*/ false, 9690 getSpecifierRange(startSpecifier, specifierLen)); 9691 } 9692 9693 return true; 9694 } 9695 9696 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9697 const Expr *OrigFormatExpr, 9698 ArrayRef<const Expr *> Args, 9699 bool HasVAListArg, unsigned format_idx, 9700 unsigned firstDataArg, 9701 Sema::FormatStringType Type, 9702 bool inFunctionCall, 9703 Sema::VariadicCallType CallType, 9704 llvm::SmallBitVector &CheckedVarArgs, 9705 UncoveredArgHandler &UncoveredArg, 9706 bool IgnoreStringsWithoutSpecifiers) { 9707 // CHECK: is the format string a wide literal? 9708 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9709 CheckFormatHandler::EmitFormatDiagnostic( 9710 S, inFunctionCall, Args[format_idx], 9711 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9712 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9713 return; 9714 } 9715 9716 // Str - The format string. NOTE: this is NOT null-terminated! 9717 StringRef StrRef = FExpr->getString(); 9718 const char *Str = StrRef.data(); 9719 // Account for cases where the string literal is truncated in a declaration. 9720 const ConstantArrayType *T = 9721 S.Context.getAsConstantArrayType(FExpr->getType()); 9722 assert(T && "String literal not of constant array type!"); 9723 size_t TypeSize = T->getSize().getZExtValue(); 9724 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9725 const unsigned numDataArgs = Args.size() - firstDataArg; 9726 9727 if (IgnoreStringsWithoutSpecifiers && 9728 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9729 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9730 return; 9731 9732 // Emit a warning if the string literal is truncated and does not contain an 9733 // embedded null character. 9734 if (TypeSize <= StrRef.size() && 9735 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 9736 CheckFormatHandler::EmitFormatDiagnostic( 9737 S, inFunctionCall, Args[format_idx], 9738 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9739 FExpr->getBeginLoc(), 9740 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9741 return; 9742 } 9743 9744 // CHECK: empty format string? 9745 if (StrLen == 0 && numDataArgs > 0) { 9746 CheckFormatHandler::EmitFormatDiagnostic( 9747 S, inFunctionCall, Args[format_idx], 9748 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9749 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9750 return; 9751 } 9752 9753 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9754 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9755 Type == Sema::FST_OSTrace) { 9756 CheckPrintfHandler H( 9757 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9758 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9759 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9760 CheckedVarArgs, UncoveredArg); 9761 9762 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9763 S.getLangOpts(), 9764 S.Context.getTargetInfo(), 9765 Type == Sema::FST_FreeBSDKPrintf)) 9766 H.DoneProcessing(); 9767 } else if (Type == Sema::FST_Scanf) { 9768 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9769 numDataArgs, Str, HasVAListArg, Args, format_idx, 9770 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9771 9772 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9773 S.getLangOpts(), 9774 S.Context.getTargetInfo())) 9775 H.DoneProcessing(); 9776 } // TODO: handle other formats 9777 } 9778 9779 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9780 // Str - The format string. NOTE: this is NOT null-terminated! 9781 StringRef StrRef = FExpr->getString(); 9782 const char *Str = StrRef.data(); 9783 // Account for cases where the string literal is truncated in a declaration. 9784 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9785 assert(T && "String literal not of constant array type!"); 9786 size_t TypeSize = T->getSize().getZExtValue(); 9787 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9788 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9789 getLangOpts(), 9790 Context.getTargetInfo()); 9791 } 9792 9793 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9794 9795 // Returns the related absolute value function that is larger, of 0 if one 9796 // does not exist. 9797 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9798 switch (AbsFunction) { 9799 default: 9800 return 0; 9801 9802 case Builtin::BI__builtin_abs: 9803 return Builtin::BI__builtin_labs; 9804 case Builtin::BI__builtin_labs: 9805 return Builtin::BI__builtin_llabs; 9806 case Builtin::BI__builtin_llabs: 9807 return 0; 9808 9809 case Builtin::BI__builtin_fabsf: 9810 return Builtin::BI__builtin_fabs; 9811 case Builtin::BI__builtin_fabs: 9812 return Builtin::BI__builtin_fabsl; 9813 case Builtin::BI__builtin_fabsl: 9814 return 0; 9815 9816 case Builtin::BI__builtin_cabsf: 9817 return Builtin::BI__builtin_cabs; 9818 case Builtin::BI__builtin_cabs: 9819 return Builtin::BI__builtin_cabsl; 9820 case Builtin::BI__builtin_cabsl: 9821 return 0; 9822 9823 case Builtin::BIabs: 9824 return Builtin::BIlabs; 9825 case Builtin::BIlabs: 9826 return Builtin::BIllabs; 9827 case Builtin::BIllabs: 9828 return 0; 9829 9830 case Builtin::BIfabsf: 9831 return Builtin::BIfabs; 9832 case Builtin::BIfabs: 9833 return Builtin::BIfabsl; 9834 case Builtin::BIfabsl: 9835 return 0; 9836 9837 case Builtin::BIcabsf: 9838 return Builtin::BIcabs; 9839 case Builtin::BIcabs: 9840 return Builtin::BIcabsl; 9841 case Builtin::BIcabsl: 9842 return 0; 9843 } 9844 } 9845 9846 // Returns the argument type of the absolute value function. 9847 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9848 unsigned AbsType) { 9849 if (AbsType == 0) 9850 return QualType(); 9851 9852 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9853 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9854 if (Error != ASTContext::GE_None) 9855 return QualType(); 9856 9857 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9858 if (!FT) 9859 return QualType(); 9860 9861 if (FT->getNumParams() != 1) 9862 return QualType(); 9863 9864 return FT->getParamType(0); 9865 } 9866 9867 // Returns the best absolute value function, or zero, based on type and 9868 // current absolute value function. 9869 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9870 unsigned AbsFunctionKind) { 9871 unsigned BestKind = 0; 9872 uint64_t ArgSize = Context.getTypeSize(ArgType); 9873 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9874 Kind = getLargerAbsoluteValueFunction(Kind)) { 9875 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9876 if (Context.getTypeSize(ParamType) >= ArgSize) { 9877 if (BestKind == 0) 9878 BestKind = Kind; 9879 else if (Context.hasSameType(ParamType, ArgType)) { 9880 BestKind = Kind; 9881 break; 9882 } 9883 } 9884 } 9885 return BestKind; 9886 } 9887 9888 enum AbsoluteValueKind { 9889 AVK_Integer, 9890 AVK_Floating, 9891 AVK_Complex 9892 }; 9893 9894 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9895 if (T->isIntegralOrEnumerationType()) 9896 return AVK_Integer; 9897 if (T->isRealFloatingType()) 9898 return AVK_Floating; 9899 if (T->isAnyComplexType()) 9900 return AVK_Complex; 9901 9902 llvm_unreachable("Type not integer, floating, or complex"); 9903 } 9904 9905 // Changes the absolute value function to a different type. Preserves whether 9906 // the function is a builtin. 9907 static unsigned changeAbsFunction(unsigned AbsKind, 9908 AbsoluteValueKind ValueKind) { 9909 switch (ValueKind) { 9910 case AVK_Integer: 9911 switch (AbsKind) { 9912 default: 9913 return 0; 9914 case Builtin::BI__builtin_fabsf: 9915 case Builtin::BI__builtin_fabs: 9916 case Builtin::BI__builtin_fabsl: 9917 case Builtin::BI__builtin_cabsf: 9918 case Builtin::BI__builtin_cabs: 9919 case Builtin::BI__builtin_cabsl: 9920 return Builtin::BI__builtin_abs; 9921 case Builtin::BIfabsf: 9922 case Builtin::BIfabs: 9923 case Builtin::BIfabsl: 9924 case Builtin::BIcabsf: 9925 case Builtin::BIcabs: 9926 case Builtin::BIcabsl: 9927 return Builtin::BIabs; 9928 } 9929 case AVK_Floating: 9930 switch (AbsKind) { 9931 default: 9932 return 0; 9933 case Builtin::BI__builtin_abs: 9934 case Builtin::BI__builtin_labs: 9935 case Builtin::BI__builtin_llabs: 9936 case Builtin::BI__builtin_cabsf: 9937 case Builtin::BI__builtin_cabs: 9938 case Builtin::BI__builtin_cabsl: 9939 return Builtin::BI__builtin_fabsf; 9940 case Builtin::BIabs: 9941 case Builtin::BIlabs: 9942 case Builtin::BIllabs: 9943 case Builtin::BIcabsf: 9944 case Builtin::BIcabs: 9945 case Builtin::BIcabsl: 9946 return Builtin::BIfabsf; 9947 } 9948 case AVK_Complex: 9949 switch (AbsKind) { 9950 default: 9951 return 0; 9952 case Builtin::BI__builtin_abs: 9953 case Builtin::BI__builtin_labs: 9954 case Builtin::BI__builtin_llabs: 9955 case Builtin::BI__builtin_fabsf: 9956 case Builtin::BI__builtin_fabs: 9957 case Builtin::BI__builtin_fabsl: 9958 return Builtin::BI__builtin_cabsf; 9959 case Builtin::BIabs: 9960 case Builtin::BIlabs: 9961 case Builtin::BIllabs: 9962 case Builtin::BIfabsf: 9963 case Builtin::BIfabs: 9964 case Builtin::BIfabsl: 9965 return Builtin::BIcabsf; 9966 } 9967 } 9968 llvm_unreachable("Unable to convert function"); 9969 } 9970 9971 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9972 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9973 if (!FnInfo) 9974 return 0; 9975 9976 switch (FDecl->getBuiltinID()) { 9977 default: 9978 return 0; 9979 case Builtin::BI__builtin_abs: 9980 case Builtin::BI__builtin_fabs: 9981 case Builtin::BI__builtin_fabsf: 9982 case Builtin::BI__builtin_fabsl: 9983 case Builtin::BI__builtin_labs: 9984 case Builtin::BI__builtin_llabs: 9985 case Builtin::BI__builtin_cabs: 9986 case Builtin::BI__builtin_cabsf: 9987 case Builtin::BI__builtin_cabsl: 9988 case Builtin::BIabs: 9989 case Builtin::BIlabs: 9990 case Builtin::BIllabs: 9991 case Builtin::BIfabs: 9992 case Builtin::BIfabsf: 9993 case Builtin::BIfabsl: 9994 case Builtin::BIcabs: 9995 case Builtin::BIcabsf: 9996 case Builtin::BIcabsl: 9997 return FDecl->getBuiltinID(); 9998 } 9999 llvm_unreachable("Unknown Builtin type"); 10000 } 10001 10002 // If the replacement is valid, emit a note with replacement function. 10003 // Additionally, suggest including the proper header if not already included. 10004 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 10005 unsigned AbsKind, QualType ArgType) { 10006 bool EmitHeaderHint = true; 10007 const char *HeaderName = nullptr; 10008 const char *FunctionName = nullptr; 10009 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 10010 FunctionName = "std::abs"; 10011 if (ArgType->isIntegralOrEnumerationType()) { 10012 HeaderName = "cstdlib"; 10013 } else if (ArgType->isRealFloatingType()) { 10014 HeaderName = "cmath"; 10015 } else { 10016 llvm_unreachable("Invalid Type"); 10017 } 10018 10019 // Lookup all std::abs 10020 if (NamespaceDecl *Std = S.getStdNamespace()) { 10021 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 10022 R.suppressDiagnostics(); 10023 S.LookupQualifiedName(R, Std); 10024 10025 for (const auto *I : R) { 10026 const FunctionDecl *FDecl = nullptr; 10027 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 10028 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 10029 } else { 10030 FDecl = dyn_cast<FunctionDecl>(I); 10031 } 10032 if (!FDecl) 10033 continue; 10034 10035 // Found std::abs(), check that they are the right ones. 10036 if (FDecl->getNumParams() != 1) 10037 continue; 10038 10039 // Check that the parameter type can handle the argument. 10040 QualType ParamType = FDecl->getParamDecl(0)->getType(); 10041 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 10042 S.Context.getTypeSize(ArgType) <= 10043 S.Context.getTypeSize(ParamType)) { 10044 // Found a function, don't need the header hint. 10045 EmitHeaderHint = false; 10046 break; 10047 } 10048 } 10049 } 10050 } else { 10051 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 10052 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 10053 10054 if (HeaderName) { 10055 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 10056 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 10057 R.suppressDiagnostics(); 10058 S.LookupName(R, S.getCurScope()); 10059 10060 if (R.isSingleResult()) { 10061 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 10062 if (FD && FD->getBuiltinID() == AbsKind) { 10063 EmitHeaderHint = false; 10064 } else { 10065 return; 10066 } 10067 } else if (!R.empty()) { 10068 return; 10069 } 10070 } 10071 } 10072 10073 S.Diag(Loc, diag::note_replace_abs_function) 10074 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 10075 10076 if (!HeaderName) 10077 return; 10078 10079 if (!EmitHeaderHint) 10080 return; 10081 10082 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 10083 << FunctionName; 10084 } 10085 10086 template <std::size_t StrLen> 10087 static bool IsStdFunction(const FunctionDecl *FDecl, 10088 const char (&Str)[StrLen]) { 10089 if (!FDecl) 10090 return false; 10091 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 10092 return false; 10093 if (!FDecl->isInStdNamespace()) 10094 return false; 10095 10096 return true; 10097 } 10098 10099 // Warn when using the wrong abs() function. 10100 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 10101 const FunctionDecl *FDecl) { 10102 if (Call->getNumArgs() != 1) 10103 return; 10104 10105 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 10106 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 10107 if (AbsKind == 0 && !IsStdAbs) 10108 return; 10109 10110 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10111 QualType ParamType = Call->getArg(0)->getType(); 10112 10113 // Unsigned types cannot be negative. Suggest removing the absolute value 10114 // function call. 10115 if (ArgType->isUnsignedIntegerType()) { 10116 const char *FunctionName = 10117 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 10118 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 10119 Diag(Call->getExprLoc(), diag::note_remove_abs) 10120 << FunctionName 10121 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 10122 return; 10123 } 10124 10125 // Taking the absolute value of a pointer is very suspicious, they probably 10126 // wanted to index into an array, dereference a pointer, call a function, etc. 10127 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 10128 unsigned DiagType = 0; 10129 if (ArgType->isFunctionType()) 10130 DiagType = 1; 10131 else if (ArgType->isArrayType()) 10132 DiagType = 2; 10133 10134 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 10135 return; 10136 } 10137 10138 // std::abs has overloads which prevent most of the absolute value problems 10139 // from occurring. 10140 if (IsStdAbs) 10141 return; 10142 10143 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 10144 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 10145 10146 // The argument and parameter are the same kind. Check if they are the right 10147 // size. 10148 if (ArgValueKind == ParamValueKind) { 10149 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 10150 return; 10151 10152 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 10153 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 10154 << FDecl << ArgType << ParamType; 10155 10156 if (NewAbsKind == 0) 10157 return; 10158 10159 emitReplacement(*this, Call->getExprLoc(), 10160 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10161 return; 10162 } 10163 10164 // ArgValueKind != ParamValueKind 10165 // The wrong type of absolute value function was used. Attempt to find the 10166 // proper one. 10167 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 10168 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 10169 if (NewAbsKind == 0) 10170 return; 10171 10172 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10173 << FDecl << ParamValueKind << ArgValueKind; 10174 10175 emitReplacement(*this, Call->getExprLoc(), 10176 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10177 } 10178 10179 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10180 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10181 const FunctionDecl *FDecl) { 10182 if (!Call || !FDecl) return; 10183 10184 // Ignore template specializations and macros. 10185 if (inTemplateInstantiation()) return; 10186 if (Call->getExprLoc().isMacroID()) return; 10187 10188 // Only care about the one template argument, two function parameter std::max 10189 if (Call->getNumArgs() != 2) return; 10190 if (!IsStdFunction(FDecl, "max")) return; 10191 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10192 if (!ArgList) return; 10193 if (ArgList->size() != 1) return; 10194 10195 // Check that template type argument is unsigned integer. 10196 const auto& TA = ArgList->get(0); 10197 if (TA.getKind() != TemplateArgument::Type) return; 10198 QualType ArgType = TA.getAsType(); 10199 if (!ArgType->isUnsignedIntegerType()) return; 10200 10201 // See if either argument is a literal zero. 10202 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10203 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10204 if (!MTE) return false; 10205 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10206 if (!Num) return false; 10207 if (Num->getValue() != 0) return false; 10208 return true; 10209 }; 10210 10211 const Expr *FirstArg = Call->getArg(0); 10212 const Expr *SecondArg = Call->getArg(1); 10213 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10214 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10215 10216 // Only warn when exactly one argument is zero. 10217 if (IsFirstArgZero == IsSecondArgZero) return; 10218 10219 SourceRange FirstRange = FirstArg->getSourceRange(); 10220 SourceRange SecondRange = SecondArg->getSourceRange(); 10221 10222 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10223 10224 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10225 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10226 10227 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10228 SourceRange RemovalRange; 10229 if (IsFirstArgZero) { 10230 RemovalRange = SourceRange(FirstRange.getBegin(), 10231 SecondRange.getBegin().getLocWithOffset(-1)); 10232 } else { 10233 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10234 SecondRange.getEnd()); 10235 } 10236 10237 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10238 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10239 << FixItHint::CreateRemoval(RemovalRange); 10240 } 10241 10242 //===--- CHECK: Standard memory functions ---------------------------------===// 10243 10244 /// Takes the expression passed to the size_t parameter of functions 10245 /// such as memcmp, strncat, etc and warns if it's a comparison. 10246 /// 10247 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10248 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10249 IdentifierInfo *FnName, 10250 SourceLocation FnLoc, 10251 SourceLocation RParenLoc) { 10252 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10253 if (!Size) 10254 return false; 10255 10256 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10257 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10258 return false; 10259 10260 SourceRange SizeRange = Size->getSourceRange(); 10261 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10262 << SizeRange << FnName; 10263 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10264 << FnName 10265 << FixItHint::CreateInsertion( 10266 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10267 << FixItHint::CreateRemoval(RParenLoc); 10268 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10269 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10270 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10271 ")"); 10272 10273 return true; 10274 } 10275 10276 /// Determine whether the given type is or contains a dynamic class type 10277 /// (e.g., whether it has a vtable). 10278 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10279 bool &IsContained) { 10280 // Look through array types while ignoring qualifiers. 10281 const Type *Ty = T->getBaseElementTypeUnsafe(); 10282 IsContained = false; 10283 10284 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10285 RD = RD ? RD->getDefinition() : nullptr; 10286 if (!RD || RD->isInvalidDecl()) 10287 return nullptr; 10288 10289 if (RD->isDynamicClass()) 10290 return RD; 10291 10292 // Check all the fields. If any bases were dynamic, the class is dynamic. 10293 // It's impossible for a class to transitively contain itself by value, so 10294 // infinite recursion is impossible. 10295 for (auto *FD : RD->fields()) { 10296 bool SubContained; 10297 if (const CXXRecordDecl *ContainedRD = 10298 getContainedDynamicClass(FD->getType(), SubContained)) { 10299 IsContained = true; 10300 return ContainedRD; 10301 } 10302 } 10303 10304 return nullptr; 10305 } 10306 10307 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10308 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10309 if (Unary->getKind() == UETT_SizeOf) 10310 return Unary; 10311 return nullptr; 10312 } 10313 10314 /// If E is a sizeof expression, returns its argument expression, 10315 /// otherwise returns NULL. 10316 static const Expr *getSizeOfExprArg(const Expr *E) { 10317 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10318 if (!SizeOf->isArgumentType()) 10319 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10320 return nullptr; 10321 } 10322 10323 /// If E is a sizeof expression, returns its argument type. 10324 static QualType getSizeOfArgType(const Expr *E) { 10325 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10326 return SizeOf->getTypeOfArgument(); 10327 return QualType(); 10328 } 10329 10330 namespace { 10331 10332 struct SearchNonTrivialToInitializeField 10333 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10334 using Super = 10335 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10336 10337 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10338 10339 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10340 SourceLocation SL) { 10341 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10342 asDerived().visitArray(PDIK, AT, SL); 10343 return; 10344 } 10345 10346 Super::visitWithKind(PDIK, FT, SL); 10347 } 10348 10349 void visitARCStrong(QualType FT, SourceLocation SL) { 10350 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10351 } 10352 void visitARCWeak(QualType FT, SourceLocation SL) { 10353 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10354 } 10355 void visitStruct(QualType FT, SourceLocation SL) { 10356 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10357 visit(FD->getType(), FD->getLocation()); 10358 } 10359 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10360 const ArrayType *AT, SourceLocation SL) { 10361 visit(getContext().getBaseElementType(AT), SL); 10362 } 10363 void visitTrivial(QualType FT, SourceLocation SL) {} 10364 10365 static void diag(QualType RT, const Expr *E, Sema &S) { 10366 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10367 } 10368 10369 ASTContext &getContext() { return S.getASTContext(); } 10370 10371 const Expr *E; 10372 Sema &S; 10373 }; 10374 10375 struct SearchNonTrivialToCopyField 10376 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10377 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10378 10379 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10380 10381 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10382 SourceLocation SL) { 10383 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10384 asDerived().visitArray(PCK, AT, SL); 10385 return; 10386 } 10387 10388 Super::visitWithKind(PCK, FT, SL); 10389 } 10390 10391 void visitARCStrong(QualType FT, SourceLocation SL) { 10392 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10393 } 10394 void visitARCWeak(QualType FT, SourceLocation SL) { 10395 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10396 } 10397 void visitStruct(QualType FT, SourceLocation SL) { 10398 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10399 visit(FD->getType(), FD->getLocation()); 10400 } 10401 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10402 SourceLocation SL) { 10403 visit(getContext().getBaseElementType(AT), SL); 10404 } 10405 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10406 SourceLocation SL) {} 10407 void visitTrivial(QualType FT, SourceLocation SL) {} 10408 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10409 10410 static void diag(QualType RT, const Expr *E, Sema &S) { 10411 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10412 } 10413 10414 ASTContext &getContext() { return S.getASTContext(); } 10415 10416 const Expr *E; 10417 Sema &S; 10418 }; 10419 10420 } 10421 10422 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10423 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10424 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10425 10426 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10427 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10428 return false; 10429 10430 return doesExprLikelyComputeSize(BO->getLHS()) || 10431 doesExprLikelyComputeSize(BO->getRHS()); 10432 } 10433 10434 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10435 } 10436 10437 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10438 /// 10439 /// \code 10440 /// #define MACRO 0 10441 /// foo(MACRO); 10442 /// foo(0); 10443 /// \endcode 10444 /// 10445 /// This should return true for the first call to foo, but not for the second 10446 /// (regardless of whether foo is a macro or function). 10447 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10448 SourceLocation CallLoc, 10449 SourceLocation ArgLoc) { 10450 if (!CallLoc.isMacroID()) 10451 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10452 10453 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10454 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10455 } 10456 10457 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10458 /// last two arguments transposed. 10459 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10460 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10461 return; 10462 10463 const Expr *SizeArg = 10464 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10465 10466 auto isLiteralZero = [](const Expr *E) { 10467 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10468 }; 10469 10470 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10471 SourceLocation CallLoc = Call->getRParenLoc(); 10472 SourceManager &SM = S.getSourceManager(); 10473 if (isLiteralZero(SizeArg) && 10474 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10475 10476 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10477 10478 // Some platforms #define bzero to __builtin_memset. See if this is the 10479 // case, and if so, emit a better diagnostic. 10480 if (BId == Builtin::BIbzero || 10481 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10482 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10483 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10484 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10485 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10486 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10487 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10488 } 10489 return; 10490 } 10491 10492 // If the second argument to a memset is a sizeof expression and the third 10493 // isn't, this is also likely an error. This should catch 10494 // 'memset(buf, sizeof(buf), 0xff)'. 10495 if (BId == Builtin::BImemset && 10496 doesExprLikelyComputeSize(Call->getArg(1)) && 10497 !doesExprLikelyComputeSize(Call->getArg(2))) { 10498 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10499 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10500 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10501 return; 10502 } 10503 } 10504 10505 /// Check for dangerous or invalid arguments to memset(). 10506 /// 10507 /// This issues warnings on known problematic, dangerous or unspecified 10508 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10509 /// function calls. 10510 /// 10511 /// \param Call The call expression to diagnose. 10512 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10513 unsigned BId, 10514 IdentifierInfo *FnName) { 10515 assert(BId != 0); 10516 10517 // It is possible to have a non-standard definition of memset. Validate 10518 // we have enough arguments, and if not, abort further checking. 10519 unsigned ExpectedNumArgs = 10520 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10521 if (Call->getNumArgs() < ExpectedNumArgs) 10522 return; 10523 10524 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10525 BId == Builtin::BIstrndup ? 1 : 2); 10526 unsigned LenArg = 10527 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10528 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10529 10530 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10531 Call->getBeginLoc(), Call->getRParenLoc())) 10532 return; 10533 10534 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10535 CheckMemaccessSize(*this, BId, Call); 10536 10537 // We have special checking when the length is a sizeof expression. 10538 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10539 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10540 llvm::FoldingSetNodeID SizeOfArgID; 10541 10542 // Although widely used, 'bzero' is not a standard function. Be more strict 10543 // with the argument types before allowing diagnostics and only allow the 10544 // form bzero(ptr, sizeof(...)). 10545 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10546 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10547 return; 10548 10549 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10550 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10551 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10552 10553 QualType DestTy = Dest->getType(); 10554 QualType PointeeTy; 10555 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10556 PointeeTy = DestPtrTy->getPointeeType(); 10557 10558 // Never warn about void type pointers. This can be used to suppress 10559 // false positives. 10560 if (PointeeTy->isVoidType()) 10561 continue; 10562 10563 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10564 // actually comparing the expressions for equality. Because computing the 10565 // expression IDs can be expensive, we only do this if the diagnostic is 10566 // enabled. 10567 if (SizeOfArg && 10568 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10569 SizeOfArg->getExprLoc())) { 10570 // We only compute IDs for expressions if the warning is enabled, and 10571 // cache the sizeof arg's ID. 10572 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10573 SizeOfArg->Profile(SizeOfArgID, Context, true); 10574 llvm::FoldingSetNodeID DestID; 10575 Dest->Profile(DestID, Context, true); 10576 if (DestID == SizeOfArgID) { 10577 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10578 // over sizeof(src) as well. 10579 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10580 StringRef ReadableName = FnName->getName(); 10581 10582 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10583 if (UnaryOp->getOpcode() == UO_AddrOf) 10584 ActionIdx = 1; // If its an address-of operator, just remove it. 10585 if (!PointeeTy->isIncompleteType() && 10586 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10587 ActionIdx = 2; // If the pointee's size is sizeof(char), 10588 // suggest an explicit length. 10589 10590 // If the function is defined as a builtin macro, do not show macro 10591 // expansion. 10592 SourceLocation SL = SizeOfArg->getExprLoc(); 10593 SourceRange DSR = Dest->getSourceRange(); 10594 SourceRange SSR = SizeOfArg->getSourceRange(); 10595 SourceManager &SM = getSourceManager(); 10596 10597 if (SM.isMacroArgExpansion(SL)) { 10598 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10599 SL = SM.getSpellingLoc(SL); 10600 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10601 SM.getSpellingLoc(DSR.getEnd())); 10602 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10603 SM.getSpellingLoc(SSR.getEnd())); 10604 } 10605 10606 DiagRuntimeBehavior(SL, SizeOfArg, 10607 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10608 << ReadableName 10609 << PointeeTy 10610 << DestTy 10611 << DSR 10612 << SSR); 10613 DiagRuntimeBehavior(SL, SizeOfArg, 10614 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10615 << ActionIdx 10616 << SSR); 10617 10618 break; 10619 } 10620 } 10621 10622 // Also check for cases where the sizeof argument is the exact same 10623 // type as the memory argument, and where it points to a user-defined 10624 // record type. 10625 if (SizeOfArgTy != QualType()) { 10626 if (PointeeTy->isRecordType() && 10627 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10628 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10629 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10630 << FnName << SizeOfArgTy << ArgIdx 10631 << PointeeTy << Dest->getSourceRange() 10632 << LenExpr->getSourceRange()); 10633 break; 10634 } 10635 } 10636 } else if (DestTy->isArrayType()) { 10637 PointeeTy = DestTy; 10638 } 10639 10640 if (PointeeTy == QualType()) 10641 continue; 10642 10643 // Always complain about dynamic classes. 10644 bool IsContained; 10645 if (const CXXRecordDecl *ContainedRD = 10646 getContainedDynamicClass(PointeeTy, IsContained)) { 10647 10648 unsigned OperationType = 0; 10649 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10650 // "overwritten" if we're warning about the destination for any call 10651 // but memcmp; otherwise a verb appropriate to the call. 10652 if (ArgIdx != 0 || IsCmp) { 10653 if (BId == Builtin::BImemcpy) 10654 OperationType = 1; 10655 else if(BId == Builtin::BImemmove) 10656 OperationType = 2; 10657 else if (IsCmp) 10658 OperationType = 3; 10659 } 10660 10661 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10662 PDiag(diag::warn_dyn_class_memaccess) 10663 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10664 << IsContained << ContainedRD << OperationType 10665 << Call->getCallee()->getSourceRange()); 10666 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10667 BId != Builtin::BImemset) 10668 DiagRuntimeBehavior( 10669 Dest->getExprLoc(), Dest, 10670 PDiag(diag::warn_arc_object_memaccess) 10671 << ArgIdx << FnName << PointeeTy 10672 << Call->getCallee()->getSourceRange()); 10673 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10674 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10675 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10676 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10677 PDiag(diag::warn_cstruct_memaccess) 10678 << ArgIdx << FnName << PointeeTy << 0); 10679 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10680 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10681 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10682 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10683 PDiag(diag::warn_cstruct_memaccess) 10684 << ArgIdx << FnName << PointeeTy << 1); 10685 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10686 } else { 10687 continue; 10688 } 10689 } else 10690 continue; 10691 10692 DiagRuntimeBehavior( 10693 Dest->getExprLoc(), Dest, 10694 PDiag(diag::note_bad_memaccess_silence) 10695 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10696 break; 10697 } 10698 } 10699 10700 // A little helper routine: ignore addition and subtraction of integer literals. 10701 // This intentionally does not ignore all integer constant expressions because 10702 // we don't want to remove sizeof(). 10703 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10704 Ex = Ex->IgnoreParenCasts(); 10705 10706 while (true) { 10707 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10708 if (!BO || !BO->isAdditiveOp()) 10709 break; 10710 10711 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10712 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10713 10714 if (isa<IntegerLiteral>(RHS)) 10715 Ex = LHS; 10716 else if (isa<IntegerLiteral>(LHS)) 10717 Ex = RHS; 10718 else 10719 break; 10720 } 10721 10722 return Ex; 10723 } 10724 10725 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10726 ASTContext &Context) { 10727 // Only handle constant-sized or VLAs, but not flexible members. 10728 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10729 // Only issue the FIXIT for arrays of size > 1. 10730 if (CAT->getSize().getSExtValue() <= 1) 10731 return false; 10732 } else if (!Ty->isVariableArrayType()) { 10733 return false; 10734 } 10735 return true; 10736 } 10737 10738 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10739 // be the size of the source, instead of the destination. 10740 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10741 IdentifierInfo *FnName) { 10742 10743 // Don't crash if the user has the wrong number of arguments 10744 unsigned NumArgs = Call->getNumArgs(); 10745 if ((NumArgs != 3) && (NumArgs != 4)) 10746 return; 10747 10748 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10749 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10750 const Expr *CompareWithSrc = nullptr; 10751 10752 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10753 Call->getBeginLoc(), Call->getRParenLoc())) 10754 return; 10755 10756 // Look for 'strlcpy(dst, x, sizeof(x))' 10757 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10758 CompareWithSrc = Ex; 10759 else { 10760 // Look for 'strlcpy(dst, x, strlen(x))' 10761 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10762 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10763 SizeCall->getNumArgs() == 1) 10764 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10765 } 10766 } 10767 10768 if (!CompareWithSrc) 10769 return; 10770 10771 // Determine if the argument to sizeof/strlen is equal to the source 10772 // argument. In principle there's all kinds of things you could do 10773 // here, for instance creating an == expression and evaluating it with 10774 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10775 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10776 if (!SrcArgDRE) 10777 return; 10778 10779 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10780 if (!CompareWithSrcDRE || 10781 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10782 return; 10783 10784 const Expr *OriginalSizeArg = Call->getArg(2); 10785 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10786 << OriginalSizeArg->getSourceRange() << FnName; 10787 10788 // Output a FIXIT hint if the destination is an array (rather than a 10789 // pointer to an array). This could be enhanced to handle some 10790 // pointers if we know the actual size, like if DstArg is 'array+2' 10791 // we could say 'sizeof(array)-2'. 10792 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10793 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10794 return; 10795 10796 SmallString<128> sizeString; 10797 llvm::raw_svector_ostream OS(sizeString); 10798 OS << "sizeof("; 10799 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10800 OS << ")"; 10801 10802 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10803 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10804 OS.str()); 10805 } 10806 10807 /// Check if two expressions refer to the same declaration. 10808 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10809 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10810 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10811 return D1->getDecl() == D2->getDecl(); 10812 return false; 10813 } 10814 10815 static const Expr *getStrlenExprArg(const Expr *E) { 10816 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10817 const FunctionDecl *FD = CE->getDirectCallee(); 10818 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10819 return nullptr; 10820 return CE->getArg(0)->IgnoreParenCasts(); 10821 } 10822 return nullptr; 10823 } 10824 10825 // Warn on anti-patterns as the 'size' argument to strncat. 10826 // The correct size argument should look like following: 10827 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10828 void Sema::CheckStrncatArguments(const CallExpr *CE, 10829 IdentifierInfo *FnName) { 10830 // Don't crash if the user has the wrong number of arguments. 10831 if (CE->getNumArgs() < 3) 10832 return; 10833 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10834 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10835 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10836 10837 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10838 CE->getRParenLoc())) 10839 return; 10840 10841 // Identify common expressions, which are wrongly used as the size argument 10842 // to strncat and may lead to buffer overflows. 10843 unsigned PatternType = 0; 10844 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10845 // - sizeof(dst) 10846 if (referToTheSameDecl(SizeOfArg, DstArg)) 10847 PatternType = 1; 10848 // - sizeof(src) 10849 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10850 PatternType = 2; 10851 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10852 if (BE->getOpcode() == BO_Sub) { 10853 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10854 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10855 // - sizeof(dst) - strlen(dst) 10856 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10857 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10858 PatternType = 1; 10859 // - sizeof(src) - (anything) 10860 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10861 PatternType = 2; 10862 } 10863 } 10864 10865 if (PatternType == 0) 10866 return; 10867 10868 // Generate the diagnostic. 10869 SourceLocation SL = LenArg->getBeginLoc(); 10870 SourceRange SR = LenArg->getSourceRange(); 10871 SourceManager &SM = getSourceManager(); 10872 10873 // If the function is defined as a builtin macro, do not show macro expansion. 10874 if (SM.isMacroArgExpansion(SL)) { 10875 SL = SM.getSpellingLoc(SL); 10876 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10877 SM.getSpellingLoc(SR.getEnd())); 10878 } 10879 10880 // Check if the destination is an array (rather than a pointer to an array). 10881 QualType DstTy = DstArg->getType(); 10882 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10883 Context); 10884 if (!isKnownSizeArray) { 10885 if (PatternType == 1) 10886 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10887 else 10888 Diag(SL, diag::warn_strncat_src_size) << SR; 10889 return; 10890 } 10891 10892 if (PatternType == 1) 10893 Diag(SL, diag::warn_strncat_large_size) << SR; 10894 else 10895 Diag(SL, diag::warn_strncat_src_size) << SR; 10896 10897 SmallString<128> sizeString; 10898 llvm::raw_svector_ostream OS(sizeString); 10899 OS << "sizeof("; 10900 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10901 OS << ") - "; 10902 OS << "strlen("; 10903 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10904 OS << ") - 1"; 10905 10906 Diag(SL, diag::note_strncat_wrong_size) 10907 << FixItHint::CreateReplacement(SR, OS.str()); 10908 } 10909 10910 namespace { 10911 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10912 const UnaryOperator *UnaryExpr, const Decl *D) { 10913 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10914 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10915 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10916 return; 10917 } 10918 } 10919 10920 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10921 const UnaryOperator *UnaryExpr) { 10922 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10923 const Decl *D = Lvalue->getDecl(); 10924 if (isa<DeclaratorDecl>(D)) 10925 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 10926 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10927 } 10928 10929 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10930 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10931 Lvalue->getMemberDecl()); 10932 } 10933 10934 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10935 const UnaryOperator *UnaryExpr) { 10936 const auto *Lambda = dyn_cast<LambdaExpr>( 10937 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10938 if (!Lambda) 10939 return; 10940 10941 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10942 << CalleeName << 2 /*object: lambda expression*/; 10943 } 10944 10945 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10946 const DeclRefExpr *Lvalue) { 10947 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10948 if (Var == nullptr) 10949 return; 10950 10951 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10952 << CalleeName << 0 /*object: */ << Var; 10953 } 10954 10955 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10956 const CastExpr *Cast) { 10957 SmallString<128> SizeString; 10958 llvm::raw_svector_ostream OS(SizeString); 10959 10960 clang::CastKind Kind = Cast->getCastKind(); 10961 if (Kind == clang::CK_BitCast && 10962 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10963 return; 10964 if (Kind == clang::CK_IntegralToPointer && 10965 !isa<IntegerLiteral>( 10966 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 10967 return; 10968 10969 switch (Cast->getCastKind()) { 10970 case clang::CK_BitCast: 10971 case clang::CK_IntegralToPointer: 10972 case clang::CK_FunctionToPointerDecay: 10973 OS << '\''; 10974 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 10975 OS << '\''; 10976 break; 10977 default: 10978 return; 10979 } 10980 10981 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 10982 << CalleeName << 0 /*object: */ << OS.str(); 10983 } 10984 } // namespace 10985 10986 /// Alerts the user that they are attempting to free a non-malloc'd object. 10987 void Sema::CheckFreeArguments(const CallExpr *E) { 10988 const std::string CalleeName = 10989 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 10990 10991 { // Prefer something that doesn't involve a cast to make things simpler. 10992 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 10993 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 10994 switch (UnaryExpr->getOpcode()) { 10995 case UnaryOperator::Opcode::UO_AddrOf: 10996 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 10997 case UnaryOperator::Opcode::UO_Plus: 10998 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 10999 default: 11000 break; 11001 } 11002 11003 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 11004 if (Lvalue->getType()->isArrayType()) 11005 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 11006 11007 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 11008 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 11009 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 11010 return; 11011 } 11012 11013 if (isa<BlockExpr>(Arg)) { 11014 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 11015 << CalleeName << 1 /*object: block*/; 11016 return; 11017 } 11018 } 11019 // Maybe the cast was important, check after the other cases. 11020 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 11021 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 11022 } 11023 11024 void 11025 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 11026 SourceLocation ReturnLoc, 11027 bool isObjCMethod, 11028 const AttrVec *Attrs, 11029 const FunctionDecl *FD) { 11030 // Check if the return value is null but should not be. 11031 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 11032 (!isObjCMethod && isNonNullType(Context, lhsType))) && 11033 CheckNonNullExpr(*this, RetValExp)) 11034 Diag(ReturnLoc, diag::warn_null_ret) 11035 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 11036 11037 // C++11 [basic.stc.dynamic.allocation]p4: 11038 // If an allocation function declared with a non-throwing 11039 // exception-specification fails to allocate storage, it shall return 11040 // a null pointer. Any other allocation function that fails to allocate 11041 // storage shall indicate failure only by throwing an exception [...] 11042 if (FD) { 11043 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 11044 if (Op == OO_New || Op == OO_Array_New) { 11045 const FunctionProtoType *Proto 11046 = FD->getType()->castAs<FunctionProtoType>(); 11047 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 11048 CheckNonNullExpr(*this, RetValExp)) 11049 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 11050 << FD << getLangOpts().CPlusPlus11; 11051 } 11052 } 11053 11054 // PPC MMA non-pointer types are not allowed as return type. Checking the type 11055 // here prevent the user from using a PPC MMA type as trailing return type. 11056 if (Context.getTargetInfo().getTriple().isPPC64()) 11057 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 11058 } 11059 11060 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 11061 11062 /// Check for comparisons of floating point operands using != and ==. 11063 /// Issue a warning if these are no self-comparisons, as they are not likely 11064 /// to do what the programmer intended. 11065 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 11066 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 11067 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 11068 11069 // Special case: check for x == x (which is OK). 11070 // Do not emit warnings for such cases. 11071 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 11072 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 11073 if (DRL->getDecl() == DRR->getDecl()) 11074 return; 11075 11076 // Special case: check for comparisons against literals that can be exactly 11077 // represented by APFloat. In such cases, do not emit a warning. This 11078 // is a heuristic: often comparison against such literals are used to 11079 // detect if a value in a variable has not changed. This clearly can 11080 // lead to false negatives. 11081 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 11082 if (FLL->isExact()) 11083 return; 11084 } else 11085 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 11086 if (FLR->isExact()) 11087 return; 11088 11089 // Check for comparisons with builtin types. 11090 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 11091 if (CL->getBuiltinCallee()) 11092 return; 11093 11094 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 11095 if (CR->getBuiltinCallee()) 11096 return; 11097 11098 // Emit the diagnostic. 11099 Diag(Loc, diag::warn_floatingpoint_eq) 11100 << LHS->getSourceRange() << RHS->getSourceRange(); 11101 } 11102 11103 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 11104 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 11105 11106 namespace { 11107 11108 /// Structure recording the 'active' range of an integer-valued 11109 /// expression. 11110 struct IntRange { 11111 /// The number of bits active in the int. Note that this includes exactly one 11112 /// sign bit if !NonNegative. 11113 unsigned Width; 11114 11115 /// True if the int is known not to have negative values. If so, all leading 11116 /// bits before Width are known zero, otherwise they are known to be the 11117 /// same as the MSB within Width. 11118 bool NonNegative; 11119 11120 IntRange(unsigned Width, bool NonNegative) 11121 : Width(Width), NonNegative(NonNegative) {} 11122 11123 /// Number of bits excluding the sign bit. 11124 unsigned valueBits() const { 11125 return NonNegative ? Width : Width - 1; 11126 } 11127 11128 /// Returns the range of the bool type. 11129 static IntRange forBoolType() { 11130 return IntRange(1, true); 11131 } 11132 11133 /// Returns the range of an opaque value of the given integral type. 11134 static IntRange forValueOfType(ASTContext &C, QualType T) { 11135 return forValueOfCanonicalType(C, 11136 T->getCanonicalTypeInternal().getTypePtr()); 11137 } 11138 11139 /// Returns the range of an opaque value of a canonical integral type. 11140 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 11141 assert(T->isCanonicalUnqualified()); 11142 11143 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11144 T = VT->getElementType().getTypePtr(); 11145 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11146 T = CT->getElementType().getTypePtr(); 11147 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11148 T = AT->getValueType().getTypePtr(); 11149 11150 if (!C.getLangOpts().CPlusPlus) { 11151 // For enum types in C code, use the underlying datatype. 11152 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11153 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 11154 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 11155 // For enum types in C++, use the known bit width of the enumerators. 11156 EnumDecl *Enum = ET->getDecl(); 11157 // In C++11, enums can have a fixed underlying type. Use this type to 11158 // compute the range. 11159 if (Enum->isFixed()) { 11160 return IntRange(C.getIntWidth(QualType(T, 0)), 11161 !ET->isSignedIntegerOrEnumerationType()); 11162 } 11163 11164 unsigned NumPositive = Enum->getNumPositiveBits(); 11165 unsigned NumNegative = Enum->getNumNegativeBits(); 11166 11167 if (NumNegative == 0) 11168 return IntRange(NumPositive, true/*NonNegative*/); 11169 else 11170 return IntRange(std::max(NumPositive + 1, NumNegative), 11171 false/*NonNegative*/); 11172 } 11173 11174 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11175 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11176 11177 const BuiltinType *BT = cast<BuiltinType>(T); 11178 assert(BT->isInteger()); 11179 11180 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11181 } 11182 11183 /// Returns the "target" range of a canonical integral type, i.e. 11184 /// the range of values expressible in the type. 11185 /// 11186 /// This matches forValueOfCanonicalType except that enums have the 11187 /// full range of their type, not the range of their enumerators. 11188 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11189 assert(T->isCanonicalUnqualified()); 11190 11191 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11192 T = VT->getElementType().getTypePtr(); 11193 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11194 T = CT->getElementType().getTypePtr(); 11195 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11196 T = AT->getValueType().getTypePtr(); 11197 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11198 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11199 11200 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11201 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11202 11203 const BuiltinType *BT = cast<BuiltinType>(T); 11204 assert(BT->isInteger()); 11205 11206 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11207 } 11208 11209 /// Returns the supremum of two ranges: i.e. their conservative merge. 11210 static IntRange join(IntRange L, IntRange R) { 11211 bool Unsigned = L.NonNegative && R.NonNegative; 11212 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11213 L.NonNegative && R.NonNegative); 11214 } 11215 11216 /// Return the range of a bitwise-AND of the two ranges. 11217 static IntRange bit_and(IntRange L, IntRange R) { 11218 unsigned Bits = std::max(L.Width, R.Width); 11219 bool NonNegative = false; 11220 if (L.NonNegative) { 11221 Bits = std::min(Bits, L.Width); 11222 NonNegative = true; 11223 } 11224 if (R.NonNegative) { 11225 Bits = std::min(Bits, R.Width); 11226 NonNegative = true; 11227 } 11228 return IntRange(Bits, NonNegative); 11229 } 11230 11231 /// Return the range of a sum of the two ranges. 11232 static IntRange sum(IntRange L, IntRange R) { 11233 bool Unsigned = L.NonNegative && R.NonNegative; 11234 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11235 Unsigned); 11236 } 11237 11238 /// Return the range of a difference of the two ranges. 11239 static IntRange difference(IntRange L, IntRange R) { 11240 // We need a 1-bit-wider range if: 11241 // 1) LHS can be negative: least value can be reduced. 11242 // 2) RHS can be negative: greatest value can be increased. 11243 bool CanWiden = !L.NonNegative || !R.NonNegative; 11244 bool Unsigned = L.NonNegative && R.Width == 0; 11245 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11246 !Unsigned, 11247 Unsigned); 11248 } 11249 11250 /// Return the range of a product of the two ranges. 11251 static IntRange product(IntRange L, IntRange R) { 11252 // If both LHS and RHS can be negative, we can form 11253 // -2^L * -2^R = 2^(L + R) 11254 // which requires L + R + 1 value bits to represent. 11255 bool CanWiden = !L.NonNegative && !R.NonNegative; 11256 bool Unsigned = L.NonNegative && R.NonNegative; 11257 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11258 Unsigned); 11259 } 11260 11261 /// Return the range of a remainder operation between the two ranges. 11262 static IntRange rem(IntRange L, IntRange R) { 11263 // The result of a remainder can't be larger than the result of 11264 // either side. The sign of the result is the sign of the LHS. 11265 bool Unsigned = L.NonNegative; 11266 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11267 Unsigned); 11268 } 11269 }; 11270 11271 } // namespace 11272 11273 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11274 unsigned MaxWidth) { 11275 if (value.isSigned() && value.isNegative()) 11276 return IntRange(value.getMinSignedBits(), false); 11277 11278 if (value.getBitWidth() > MaxWidth) 11279 value = value.trunc(MaxWidth); 11280 11281 // isNonNegative() just checks the sign bit without considering 11282 // signedness. 11283 return IntRange(value.getActiveBits(), true); 11284 } 11285 11286 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11287 unsigned MaxWidth) { 11288 if (result.isInt()) 11289 return GetValueRange(C, result.getInt(), MaxWidth); 11290 11291 if (result.isVector()) { 11292 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11293 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11294 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11295 R = IntRange::join(R, El); 11296 } 11297 return R; 11298 } 11299 11300 if (result.isComplexInt()) { 11301 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11302 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11303 return IntRange::join(R, I); 11304 } 11305 11306 // This can happen with lossless casts to intptr_t of "based" lvalues. 11307 // Assume it might use arbitrary bits. 11308 // FIXME: The only reason we need to pass the type in here is to get 11309 // the sign right on this one case. It would be nice if APValue 11310 // preserved this. 11311 assert(result.isLValue() || result.isAddrLabelDiff()); 11312 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11313 } 11314 11315 static QualType GetExprType(const Expr *E) { 11316 QualType Ty = E->getType(); 11317 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11318 Ty = AtomicRHS->getValueType(); 11319 return Ty; 11320 } 11321 11322 /// Pseudo-evaluate the given integer expression, estimating the 11323 /// range of values it might take. 11324 /// 11325 /// \param MaxWidth The width to which the value will be truncated. 11326 /// \param Approximate If \c true, return a likely range for the result: in 11327 /// particular, assume that arithmetic on narrower types doesn't leave 11328 /// those types. If \c false, return a range including all possible 11329 /// result values. 11330 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11331 bool InConstantContext, bool Approximate) { 11332 E = E->IgnoreParens(); 11333 11334 // Try a full evaluation first. 11335 Expr::EvalResult result; 11336 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11337 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11338 11339 // I think we only want to look through implicit casts here; if the 11340 // user has an explicit widening cast, we should treat the value as 11341 // being of the new, wider type. 11342 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11343 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11344 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11345 Approximate); 11346 11347 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11348 11349 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11350 CE->getCastKind() == CK_BooleanToSignedIntegral; 11351 11352 // Assume that non-integer casts can span the full range of the type. 11353 if (!isIntegerCast) 11354 return OutputTypeRange; 11355 11356 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11357 std::min(MaxWidth, OutputTypeRange.Width), 11358 InConstantContext, Approximate); 11359 11360 // Bail out if the subexpr's range is as wide as the cast type. 11361 if (SubRange.Width >= OutputTypeRange.Width) 11362 return OutputTypeRange; 11363 11364 // Otherwise, we take the smaller width, and we're non-negative if 11365 // either the output type or the subexpr is. 11366 return IntRange(SubRange.Width, 11367 SubRange.NonNegative || OutputTypeRange.NonNegative); 11368 } 11369 11370 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11371 // If we can fold the condition, just take that operand. 11372 bool CondResult; 11373 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11374 return GetExprRange(C, 11375 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11376 MaxWidth, InConstantContext, Approximate); 11377 11378 // Otherwise, conservatively merge. 11379 // GetExprRange requires an integer expression, but a throw expression 11380 // results in a void type. 11381 Expr *E = CO->getTrueExpr(); 11382 IntRange L = E->getType()->isVoidType() 11383 ? IntRange{0, true} 11384 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11385 E = CO->getFalseExpr(); 11386 IntRange R = E->getType()->isVoidType() 11387 ? IntRange{0, true} 11388 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11389 return IntRange::join(L, R); 11390 } 11391 11392 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11393 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11394 11395 switch (BO->getOpcode()) { 11396 case BO_Cmp: 11397 llvm_unreachable("builtin <=> should have class type"); 11398 11399 // Boolean-valued operations are single-bit and positive. 11400 case BO_LAnd: 11401 case BO_LOr: 11402 case BO_LT: 11403 case BO_GT: 11404 case BO_LE: 11405 case BO_GE: 11406 case BO_EQ: 11407 case BO_NE: 11408 return IntRange::forBoolType(); 11409 11410 // The type of the assignments is the type of the LHS, so the RHS 11411 // is not necessarily the same type. 11412 case BO_MulAssign: 11413 case BO_DivAssign: 11414 case BO_RemAssign: 11415 case BO_AddAssign: 11416 case BO_SubAssign: 11417 case BO_XorAssign: 11418 case BO_OrAssign: 11419 // TODO: bitfields? 11420 return IntRange::forValueOfType(C, GetExprType(E)); 11421 11422 // Simple assignments just pass through the RHS, which will have 11423 // been coerced to the LHS type. 11424 case BO_Assign: 11425 // TODO: bitfields? 11426 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11427 Approximate); 11428 11429 // Operations with opaque sources are black-listed. 11430 case BO_PtrMemD: 11431 case BO_PtrMemI: 11432 return IntRange::forValueOfType(C, GetExprType(E)); 11433 11434 // Bitwise-and uses the *infinum* of the two source ranges. 11435 case BO_And: 11436 case BO_AndAssign: 11437 Combine = IntRange::bit_and; 11438 break; 11439 11440 // Left shift gets black-listed based on a judgement call. 11441 case BO_Shl: 11442 // ...except that we want to treat '1 << (blah)' as logically 11443 // positive. It's an important idiom. 11444 if (IntegerLiteral *I 11445 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11446 if (I->getValue() == 1) { 11447 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11448 return IntRange(R.Width, /*NonNegative*/ true); 11449 } 11450 } 11451 LLVM_FALLTHROUGH; 11452 11453 case BO_ShlAssign: 11454 return IntRange::forValueOfType(C, GetExprType(E)); 11455 11456 // Right shift by a constant can narrow its left argument. 11457 case BO_Shr: 11458 case BO_ShrAssign: { 11459 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11460 Approximate); 11461 11462 // If the shift amount is a positive constant, drop the width by 11463 // that much. 11464 if (Optional<llvm::APSInt> shift = 11465 BO->getRHS()->getIntegerConstantExpr(C)) { 11466 if (shift->isNonNegative()) { 11467 unsigned zext = shift->getZExtValue(); 11468 if (zext >= L.Width) 11469 L.Width = (L.NonNegative ? 0 : 1); 11470 else 11471 L.Width -= zext; 11472 } 11473 } 11474 11475 return L; 11476 } 11477 11478 // Comma acts as its right operand. 11479 case BO_Comma: 11480 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11481 Approximate); 11482 11483 case BO_Add: 11484 if (!Approximate) 11485 Combine = IntRange::sum; 11486 break; 11487 11488 case BO_Sub: 11489 if (BO->getLHS()->getType()->isPointerType()) 11490 return IntRange::forValueOfType(C, GetExprType(E)); 11491 if (!Approximate) 11492 Combine = IntRange::difference; 11493 break; 11494 11495 case BO_Mul: 11496 if (!Approximate) 11497 Combine = IntRange::product; 11498 break; 11499 11500 // The width of a division result is mostly determined by the size 11501 // of the LHS. 11502 case BO_Div: { 11503 // Don't 'pre-truncate' the operands. 11504 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11505 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11506 Approximate); 11507 11508 // If the divisor is constant, use that. 11509 if (Optional<llvm::APSInt> divisor = 11510 BO->getRHS()->getIntegerConstantExpr(C)) { 11511 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11512 if (log2 >= L.Width) 11513 L.Width = (L.NonNegative ? 0 : 1); 11514 else 11515 L.Width = std::min(L.Width - log2, MaxWidth); 11516 return L; 11517 } 11518 11519 // Otherwise, just use the LHS's width. 11520 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11521 // could be -1. 11522 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11523 Approximate); 11524 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11525 } 11526 11527 case BO_Rem: 11528 Combine = IntRange::rem; 11529 break; 11530 11531 // The default behavior is okay for these. 11532 case BO_Xor: 11533 case BO_Or: 11534 break; 11535 } 11536 11537 // Combine the two ranges, but limit the result to the type in which we 11538 // performed the computation. 11539 QualType T = GetExprType(E); 11540 unsigned opWidth = C.getIntWidth(T); 11541 IntRange L = 11542 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11543 IntRange R = 11544 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11545 IntRange C = Combine(L, R); 11546 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11547 C.Width = std::min(C.Width, MaxWidth); 11548 return C; 11549 } 11550 11551 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11552 switch (UO->getOpcode()) { 11553 // Boolean-valued operations are white-listed. 11554 case UO_LNot: 11555 return IntRange::forBoolType(); 11556 11557 // Operations with opaque sources are black-listed. 11558 case UO_Deref: 11559 case UO_AddrOf: // should be impossible 11560 return IntRange::forValueOfType(C, GetExprType(E)); 11561 11562 default: 11563 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11564 Approximate); 11565 } 11566 } 11567 11568 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11569 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11570 Approximate); 11571 11572 if (const auto *BitField = E->getSourceBitField()) 11573 return IntRange(BitField->getBitWidthValue(C), 11574 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11575 11576 return IntRange::forValueOfType(C, GetExprType(E)); 11577 } 11578 11579 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11580 bool InConstantContext, bool Approximate) { 11581 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11582 Approximate); 11583 } 11584 11585 /// Checks whether the given value, which currently has the given 11586 /// source semantics, has the same value when coerced through the 11587 /// target semantics. 11588 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11589 const llvm::fltSemantics &Src, 11590 const llvm::fltSemantics &Tgt) { 11591 llvm::APFloat truncated = value; 11592 11593 bool ignored; 11594 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11595 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11596 11597 return truncated.bitwiseIsEqual(value); 11598 } 11599 11600 /// Checks whether the given value, which currently has the given 11601 /// source semantics, has the same value when coerced through the 11602 /// target semantics. 11603 /// 11604 /// The value might be a vector of floats (or a complex number). 11605 static bool IsSameFloatAfterCast(const APValue &value, 11606 const llvm::fltSemantics &Src, 11607 const llvm::fltSemantics &Tgt) { 11608 if (value.isFloat()) 11609 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11610 11611 if (value.isVector()) { 11612 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11613 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11614 return false; 11615 return true; 11616 } 11617 11618 assert(value.isComplexFloat()); 11619 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11620 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11621 } 11622 11623 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11624 bool IsListInit = false); 11625 11626 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11627 // Suppress cases where we are comparing against an enum constant. 11628 if (const DeclRefExpr *DR = 11629 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11630 if (isa<EnumConstantDecl>(DR->getDecl())) 11631 return true; 11632 11633 // Suppress cases where the value is expanded from a macro, unless that macro 11634 // is how a language represents a boolean literal. This is the case in both C 11635 // and Objective-C. 11636 SourceLocation BeginLoc = E->getBeginLoc(); 11637 if (BeginLoc.isMacroID()) { 11638 StringRef MacroName = Lexer::getImmediateMacroName( 11639 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11640 return MacroName != "YES" && MacroName != "NO" && 11641 MacroName != "true" && MacroName != "false"; 11642 } 11643 11644 return false; 11645 } 11646 11647 static bool isKnownToHaveUnsignedValue(Expr *E) { 11648 return E->getType()->isIntegerType() && 11649 (!E->getType()->isSignedIntegerType() || 11650 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11651 } 11652 11653 namespace { 11654 /// The promoted range of values of a type. In general this has the 11655 /// following structure: 11656 /// 11657 /// |-----------| . . . |-----------| 11658 /// ^ ^ ^ ^ 11659 /// Min HoleMin HoleMax Max 11660 /// 11661 /// ... where there is only a hole if a signed type is promoted to unsigned 11662 /// (in which case Min and Max are the smallest and largest representable 11663 /// values). 11664 struct PromotedRange { 11665 // Min, or HoleMax if there is a hole. 11666 llvm::APSInt PromotedMin; 11667 // Max, or HoleMin if there is a hole. 11668 llvm::APSInt PromotedMax; 11669 11670 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11671 if (R.Width == 0) 11672 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11673 else if (R.Width >= BitWidth && !Unsigned) { 11674 // Promotion made the type *narrower*. This happens when promoting 11675 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11676 // Treat all values of 'signed int' as being in range for now. 11677 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11678 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11679 } else { 11680 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11681 .extOrTrunc(BitWidth); 11682 PromotedMin.setIsUnsigned(Unsigned); 11683 11684 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11685 .extOrTrunc(BitWidth); 11686 PromotedMax.setIsUnsigned(Unsigned); 11687 } 11688 } 11689 11690 // Determine whether this range is contiguous (has no hole). 11691 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11692 11693 // Where a constant value is within the range. 11694 enum ComparisonResult { 11695 LT = 0x1, 11696 LE = 0x2, 11697 GT = 0x4, 11698 GE = 0x8, 11699 EQ = 0x10, 11700 NE = 0x20, 11701 InRangeFlag = 0x40, 11702 11703 Less = LE | LT | NE, 11704 Min = LE | InRangeFlag, 11705 InRange = InRangeFlag, 11706 Max = GE | InRangeFlag, 11707 Greater = GE | GT | NE, 11708 11709 OnlyValue = LE | GE | EQ | InRangeFlag, 11710 InHole = NE 11711 }; 11712 11713 ComparisonResult compare(const llvm::APSInt &Value) const { 11714 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11715 Value.isUnsigned() == PromotedMin.isUnsigned()); 11716 if (!isContiguous()) { 11717 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11718 if (Value.isMinValue()) return Min; 11719 if (Value.isMaxValue()) return Max; 11720 if (Value >= PromotedMin) return InRange; 11721 if (Value <= PromotedMax) return InRange; 11722 return InHole; 11723 } 11724 11725 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11726 case -1: return Less; 11727 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11728 case 1: 11729 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11730 case -1: return InRange; 11731 case 0: return Max; 11732 case 1: return Greater; 11733 } 11734 } 11735 11736 llvm_unreachable("impossible compare result"); 11737 } 11738 11739 static llvm::Optional<StringRef> 11740 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11741 if (Op == BO_Cmp) { 11742 ComparisonResult LTFlag = LT, GTFlag = GT; 11743 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11744 11745 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11746 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11747 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11748 return llvm::None; 11749 } 11750 11751 ComparisonResult TrueFlag, FalseFlag; 11752 if (Op == BO_EQ) { 11753 TrueFlag = EQ; 11754 FalseFlag = NE; 11755 } else if (Op == BO_NE) { 11756 TrueFlag = NE; 11757 FalseFlag = EQ; 11758 } else { 11759 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11760 TrueFlag = LT; 11761 FalseFlag = GE; 11762 } else { 11763 TrueFlag = GT; 11764 FalseFlag = LE; 11765 } 11766 if (Op == BO_GE || Op == BO_LE) 11767 std::swap(TrueFlag, FalseFlag); 11768 } 11769 if (R & TrueFlag) 11770 return StringRef("true"); 11771 if (R & FalseFlag) 11772 return StringRef("false"); 11773 return llvm::None; 11774 } 11775 }; 11776 } 11777 11778 static bool HasEnumType(Expr *E) { 11779 // Strip off implicit integral promotions. 11780 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11781 if (ICE->getCastKind() != CK_IntegralCast && 11782 ICE->getCastKind() != CK_NoOp) 11783 break; 11784 E = ICE->getSubExpr(); 11785 } 11786 11787 return E->getType()->isEnumeralType(); 11788 } 11789 11790 static int classifyConstantValue(Expr *Constant) { 11791 // The values of this enumeration are used in the diagnostics 11792 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11793 enum ConstantValueKind { 11794 Miscellaneous = 0, 11795 LiteralTrue, 11796 LiteralFalse 11797 }; 11798 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11799 return BL->getValue() ? ConstantValueKind::LiteralTrue 11800 : ConstantValueKind::LiteralFalse; 11801 return ConstantValueKind::Miscellaneous; 11802 } 11803 11804 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11805 Expr *Constant, Expr *Other, 11806 const llvm::APSInt &Value, 11807 bool RhsConstant) { 11808 if (S.inTemplateInstantiation()) 11809 return false; 11810 11811 Expr *OriginalOther = Other; 11812 11813 Constant = Constant->IgnoreParenImpCasts(); 11814 Other = Other->IgnoreParenImpCasts(); 11815 11816 // Suppress warnings on tautological comparisons between values of the same 11817 // enumeration type. There are only two ways we could warn on this: 11818 // - If the constant is outside the range of representable values of 11819 // the enumeration. In such a case, we should warn about the cast 11820 // to enumeration type, not about the comparison. 11821 // - If the constant is the maximum / minimum in-range value. For an 11822 // enumeratin type, such comparisons can be meaningful and useful. 11823 if (Constant->getType()->isEnumeralType() && 11824 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11825 return false; 11826 11827 IntRange OtherValueRange = GetExprRange( 11828 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11829 11830 QualType OtherT = Other->getType(); 11831 if (const auto *AT = OtherT->getAs<AtomicType>()) 11832 OtherT = AT->getValueType(); 11833 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11834 11835 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11836 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11837 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11838 S.NSAPIObj->isObjCBOOLType(OtherT) && 11839 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11840 11841 // Whether we're treating Other as being a bool because of the form of 11842 // expression despite it having another type (typically 'int' in C). 11843 bool OtherIsBooleanDespiteType = 11844 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11845 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11846 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11847 11848 // Check if all values in the range of possible values of this expression 11849 // lead to the same comparison outcome. 11850 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11851 Value.isUnsigned()); 11852 auto Cmp = OtherPromotedValueRange.compare(Value); 11853 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11854 if (!Result) 11855 return false; 11856 11857 // Also consider the range determined by the type alone. This allows us to 11858 // classify the warning under the proper diagnostic group. 11859 bool TautologicalTypeCompare = false; 11860 { 11861 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11862 Value.isUnsigned()); 11863 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11864 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11865 RhsConstant)) { 11866 TautologicalTypeCompare = true; 11867 Cmp = TypeCmp; 11868 Result = TypeResult; 11869 } 11870 } 11871 11872 // Don't warn if the non-constant operand actually always evaluates to the 11873 // same value. 11874 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11875 return false; 11876 11877 // Suppress the diagnostic for an in-range comparison if the constant comes 11878 // from a macro or enumerator. We don't want to diagnose 11879 // 11880 // some_long_value <= INT_MAX 11881 // 11882 // when sizeof(int) == sizeof(long). 11883 bool InRange = Cmp & PromotedRange::InRangeFlag; 11884 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11885 return false; 11886 11887 // A comparison of an unsigned bit-field against 0 is really a type problem, 11888 // even though at the type level the bit-field might promote to 'signed int'. 11889 if (Other->refersToBitField() && InRange && Value == 0 && 11890 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11891 TautologicalTypeCompare = true; 11892 11893 // If this is a comparison to an enum constant, include that 11894 // constant in the diagnostic. 11895 const EnumConstantDecl *ED = nullptr; 11896 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11897 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11898 11899 // Should be enough for uint128 (39 decimal digits) 11900 SmallString<64> PrettySourceValue; 11901 llvm::raw_svector_ostream OS(PrettySourceValue); 11902 if (ED) { 11903 OS << '\'' << *ED << "' (" << Value << ")"; 11904 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11905 Constant->IgnoreParenImpCasts())) { 11906 OS << (BL->getValue() ? "YES" : "NO"); 11907 } else { 11908 OS << Value; 11909 } 11910 11911 if (!TautologicalTypeCompare) { 11912 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11913 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11914 << E->getOpcodeStr() << OS.str() << *Result 11915 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11916 return true; 11917 } 11918 11919 if (IsObjCSignedCharBool) { 11920 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11921 S.PDiag(diag::warn_tautological_compare_objc_bool) 11922 << OS.str() << *Result); 11923 return true; 11924 } 11925 11926 // FIXME: We use a somewhat different formatting for the in-range cases and 11927 // cases involving boolean values for historical reasons. We should pick a 11928 // consistent way of presenting these diagnostics. 11929 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11930 11931 S.DiagRuntimeBehavior( 11932 E->getOperatorLoc(), E, 11933 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11934 : diag::warn_tautological_bool_compare) 11935 << OS.str() << classifyConstantValue(Constant) << OtherT 11936 << OtherIsBooleanDespiteType << *Result 11937 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11938 } else { 11939 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 11940 unsigned Diag = 11941 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11942 ? (HasEnumType(OriginalOther) 11943 ? diag::warn_unsigned_enum_always_true_comparison 11944 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 11945 : diag::warn_unsigned_always_true_comparison) 11946 : diag::warn_tautological_constant_compare; 11947 11948 S.Diag(E->getOperatorLoc(), Diag) 11949 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11950 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11951 } 11952 11953 return true; 11954 } 11955 11956 /// Analyze the operands of the given comparison. Implements the 11957 /// fallback case from AnalyzeComparison. 11958 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11959 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11960 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11961 } 11962 11963 /// Implements -Wsign-compare. 11964 /// 11965 /// \param E the binary operator to check for warnings 11966 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11967 // The type the comparison is being performed in. 11968 QualType T = E->getLHS()->getType(); 11969 11970 // Only analyze comparison operators where both sides have been converted to 11971 // the same type. 11972 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 11973 return AnalyzeImpConvsInComparison(S, E); 11974 11975 // Don't analyze value-dependent comparisons directly. 11976 if (E->isValueDependent()) 11977 return AnalyzeImpConvsInComparison(S, E); 11978 11979 Expr *LHS = E->getLHS(); 11980 Expr *RHS = E->getRHS(); 11981 11982 if (T->isIntegralType(S.Context)) { 11983 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 11984 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 11985 11986 // We don't care about expressions whose result is a constant. 11987 if (RHSValue && LHSValue) 11988 return AnalyzeImpConvsInComparison(S, E); 11989 11990 // We only care about expressions where just one side is literal 11991 if ((bool)RHSValue ^ (bool)LHSValue) { 11992 // Is the constant on the RHS or LHS? 11993 const bool RhsConstant = (bool)RHSValue; 11994 Expr *Const = RhsConstant ? RHS : LHS; 11995 Expr *Other = RhsConstant ? LHS : RHS; 11996 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 11997 11998 // Check whether an integer constant comparison results in a value 11999 // of 'true' or 'false'. 12000 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 12001 return AnalyzeImpConvsInComparison(S, E); 12002 } 12003 } 12004 12005 if (!T->hasUnsignedIntegerRepresentation()) { 12006 // We don't do anything special if this isn't an unsigned integral 12007 // comparison: we're only interested in integral comparisons, and 12008 // signed comparisons only happen in cases we don't care to warn about. 12009 return AnalyzeImpConvsInComparison(S, E); 12010 } 12011 12012 LHS = LHS->IgnoreParenImpCasts(); 12013 RHS = RHS->IgnoreParenImpCasts(); 12014 12015 if (!S.getLangOpts().CPlusPlus) { 12016 // Avoid warning about comparison of integers with different signs when 12017 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 12018 // the type of `E`. 12019 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 12020 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12021 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 12022 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12023 } 12024 12025 // Check to see if one of the (unmodified) operands is of different 12026 // signedness. 12027 Expr *signedOperand, *unsignedOperand; 12028 if (LHS->getType()->hasSignedIntegerRepresentation()) { 12029 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 12030 "unsigned comparison between two signed integer expressions?"); 12031 signedOperand = LHS; 12032 unsignedOperand = RHS; 12033 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 12034 signedOperand = RHS; 12035 unsignedOperand = LHS; 12036 } else { 12037 return AnalyzeImpConvsInComparison(S, E); 12038 } 12039 12040 // Otherwise, calculate the effective range of the signed operand. 12041 IntRange signedRange = GetExprRange( 12042 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 12043 12044 // Go ahead and analyze implicit conversions in the operands. Note 12045 // that we skip the implicit conversions on both sides. 12046 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 12047 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 12048 12049 // If the signed range is non-negative, -Wsign-compare won't fire. 12050 if (signedRange.NonNegative) 12051 return; 12052 12053 // For (in)equality comparisons, if the unsigned operand is a 12054 // constant which cannot collide with a overflowed signed operand, 12055 // then reinterpreting the signed operand as unsigned will not 12056 // change the result of the comparison. 12057 if (E->isEqualityOp()) { 12058 unsigned comparisonWidth = S.Context.getIntWidth(T); 12059 IntRange unsignedRange = 12060 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 12061 /*Approximate*/ true); 12062 12063 // We should never be unable to prove that the unsigned operand is 12064 // non-negative. 12065 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 12066 12067 if (unsignedRange.Width < comparisonWidth) 12068 return; 12069 } 12070 12071 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12072 S.PDiag(diag::warn_mixed_sign_comparison) 12073 << LHS->getType() << RHS->getType() 12074 << LHS->getSourceRange() << RHS->getSourceRange()); 12075 } 12076 12077 /// Analyzes an attempt to assign the given value to a bitfield. 12078 /// 12079 /// Returns true if there was something fishy about the attempt. 12080 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 12081 SourceLocation InitLoc) { 12082 assert(Bitfield->isBitField()); 12083 if (Bitfield->isInvalidDecl()) 12084 return false; 12085 12086 // White-list bool bitfields. 12087 QualType BitfieldType = Bitfield->getType(); 12088 if (BitfieldType->isBooleanType()) 12089 return false; 12090 12091 if (BitfieldType->isEnumeralType()) { 12092 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 12093 // If the underlying enum type was not explicitly specified as an unsigned 12094 // type and the enum contain only positive values, MSVC++ will cause an 12095 // inconsistency by storing this as a signed type. 12096 if (S.getLangOpts().CPlusPlus11 && 12097 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 12098 BitfieldEnumDecl->getNumPositiveBits() > 0 && 12099 BitfieldEnumDecl->getNumNegativeBits() == 0) { 12100 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 12101 << BitfieldEnumDecl; 12102 } 12103 } 12104 12105 if (Bitfield->getType()->isBooleanType()) 12106 return false; 12107 12108 // Ignore value- or type-dependent expressions. 12109 if (Bitfield->getBitWidth()->isValueDependent() || 12110 Bitfield->getBitWidth()->isTypeDependent() || 12111 Init->isValueDependent() || 12112 Init->isTypeDependent()) 12113 return false; 12114 12115 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 12116 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 12117 12118 Expr::EvalResult Result; 12119 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 12120 Expr::SE_AllowSideEffects)) { 12121 // The RHS is not constant. If the RHS has an enum type, make sure the 12122 // bitfield is wide enough to hold all the values of the enum without 12123 // truncation. 12124 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 12125 EnumDecl *ED = EnumTy->getDecl(); 12126 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 12127 12128 // Enum types are implicitly signed on Windows, so check if there are any 12129 // negative enumerators to see if the enum was intended to be signed or 12130 // not. 12131 bool SignedEnum = ED->getNumNegativeBits() > 0; 12132 12133 // Check for surprising sign changes when assigning enum values to a 12134 // bitfield of different signedness. If the bitfield is signed and we 12135 // have exactly the right number of bits to store this unsigned enum, 12136 // suggest changing the enum to an unsigned type. This typically happens 12137 // on Windows where unfixed enums always use an underlying type of 'int'. 12138 unsigned DiagID = 0; 12139 if (SignedEnum && !SignedBitfield) { 12140 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 12141 } else if (SignedBitfield && !SignedEnum && 12142 ED->getNumPositiveBits() == FieldWidth) { 12143 DiagID = diag::warn_signed_bitfield_enum_conversion; 12144 } 12145 12146 if (DiagID) { 12147 S.Diag(InitLoc, DiagID) << Bitfield << ED; 12148 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 12149 SourceRange TypeRange = 12150 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 12151 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 12152 << SignedEnum << TypeRange; 12153 } 12154 12155 // Compute the required bitwidth. If the enum has negative values, we need 12156 // one more bit than the normal number of positive bits to represent the 12157 // sign bit. 12158 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 12159 ED->getNumNegativeBits()) 12160 : ED->getNumPositiveBits(); 12161 12162 // Check the bitwidth. 12163 if (BitsNeeded > FieldWidth) { 12164 Expr *WidthExpr = Bitfield->getBitWidth(); 12165 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 12166 << Bitfield << ED; 12167 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 12168 << BitsNeeded << ED << WidthExpr->getSourceRange(); 12169 } 12170 } 12171 12172 return false; 12173 } 12174 12175 llvm::APSInt Value = Result.Val.getInt(); 12176 12177 unsigned OriginalWidth = Value.getBitWidth(); 12178 12179 if (!Value.isSigned() || Value.isNegative()) 12180 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12181 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12182 OriginalWidth = Value.getMinSignedBits(); 12183 12184 if (OriginalWidth <= FieldWidth) 12185 return false; 12186 12187 // Compute the value which the bitfield will contain. 12188 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12189 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12190 12191 // Check whether the stored value is equal to the original value. 12192 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12193 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12194 return false; 12195 12196 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12197 // therefore don't strictly fit into a signed bitfield of width 1. 12198 if (FieldWidth == 1 && Value == 1) 12199 return false; 12200 12201 std::string PrettyValue = toString(Value, 10); 12202 std::string PrettyTrunc = toString(TruncatedValue, 10); 12203 12204 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12205 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12206 << Init->getSourceRange(); 12207 12208 return true; 12209 } 12210 12211 /// Analyze the given simple or compound assignment for warning-worthy 12212 /// operations. 12213 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12214 // Just recurse on the LHS. 12215 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12216 12217 // We want to recurse on the RHS as normal unless we're assigning to 12218 // a bitfield. 12219 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12220 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12221 E->getOperatorLoc())) { 12222 // Recurse, ignoring any implicit conversions on the RHS. 12223 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12224 E->getOperatorLoc()); 12225 } 12226 } 12227 12228 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12229 12230 // Diagnose implicitly sequentially-consistent atomic assignment. 12231 if (E->getLHS()->getType()->isAtomicType()) 12232 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12233 } 12234 12235 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12236 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12237 SourceLocation CContext, unsigned diag, 12238 bool pruneControlFlow = false) { 12239 if (pruneControlFlow) { 12240 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12241 S.PDiag(diag) 12242 << SourceType << T << E->getSourceRange() 12243 << SourceRange(CContext)); 12244 return; 12245 } 12246 S.Diag(E->getExprLoc(), diag) 12247 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12248 } 12249 12250 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12251 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12252 SourceLocation CContext, 12253 unsigned diag, bool pruneControlFlow = false) { 12254 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12255 } 12256 12257 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12258 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12259 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12260 } 12261 12262 static void adornObjCBoolConversionDiagWithTernaryFixit( 12263 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12264 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12265 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12266 Ignored = OVE->getSourceExpr(); 12267 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12268 isa<BinaryOperator>(Ignored) || 12269 isa<CXXOperatorCallExpr>(Ignored); 12270 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12271 if (NeedsParens) 12272 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12273 << FixItHint::CreateInsertion(EndLoc, ")"); 12274 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12275 } 12276 12277 /// Diagnose an implicit cast from a floating point value to an integer value. 12278 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12279 SourceLocation CContext) { 12280 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12281 const bool PruneWarnings = S.inTemplateInstantiation(); 12282 12283 Expr *InnerE = E->IgnoreParenImpCasts(); 12284 // We also want to warn on, e.g., "int i = -1.234" 12285 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12286 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12287 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12288 12289 const bool IsLiteral = 12290 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12291 12292 llvm::APFloat Value(0.0); 12293 bool IsConstant = 12294 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12295 if (!IsConstant) { 12296 if (isObjCSignedCharBool(S, T)) { 12297 return adornObjCBoolConversionDiagWithTernaryFixit( 12298 S, E, 12299 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12300 << E->getType()); 12301 } 12302 12303 return DiagnoseImpCast(S, E, T, CContext, 12304 diag::warn_impcast_float_integer, PruneWarnings); 12305 } 12306 12307 bool isExact = false; 12308 12309 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12310 T->hasUnsignedIntegerRepresentation()); 12311 llvm::APFloat::opStatus Result = Value.convertToInteger( 12312 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12313 12314 // FIXME: Force the precision of the source value down so we don't print 12315 // digits which are usually useless (we don't really care here if we 12316 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12317 // would automatically print the shortest representation, but it's a bit 12318 // tricky to implement. 12319 SmallString<16> PrettySourceValue; 12320 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12321 precision = (precision * 59 + 195) / 196; 12322 Value.toString(PrettySourceValue, precision); 12323 12324 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12325 return adornObjCBoolConversionDiagWithTernaryFixit( 12326 S, E, 12327 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12328 << PrettySourceValue); 12329 } 12330 12331 if (Result == llvm::APFloat::opOK && isExact) { 12332 if (IsLiteral) return; 12333 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12334 PruneWarnings); 12335 } 12336 12337 // Conversion of a floating-point value to a non-bool integer where the 12338 // integral part cannot be represented by the integer type is undefined. 12339 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12340 return DiagnoseImpCast( 12341 S, E, T, CContext, 12342 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12343 : diag::warn_impcast_float_to_integer_out_of_range, 12344 PruneWarnings); 12345 12346 unsigned DiagID = 0; 12347 if (IsLiteral) { 12348 // Warn on floating point literal to integer. 12349 DiagID = diag::warn_impcast_literal_float_to_integer; 12350 } else if (IntegerValue == 0) { 12351 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12352 return DiagnoseImpCast(S, E, T, CContext, 12353 diag::warn_impcast_float_integer, PruneWarnings); 12354 } 12355 // Warn on non-zero to zero conversion. 12356 DiagID = diag::warn_impcast_float_to_integer_zero; 12357 } else { 12358 if (IntegerValue.isUnsigned()) { 12359 if (!IntegerValue.isMaxValue()) { 12360 return DiagnoseImpCast(S, E, T, CContext, 12361 diag::warn_impcast_float_integer, PruneWarnings); 12362 } 12363 } else { // IntegerValue.isSigned() 12364 if (!IntegerValue.isMaxSignedValue() && 12365 !IntegerValue.isMinSignedValue()) { 12366 return DiagnoseImpCast(S, E, T, CContext, 12367 diag::warn_impcast_float_integer, PruneWarnings); 12368 } 12369 } 12370 // Warn on evaluatable floating point expression to integer conversion. 12371 DiagID = diag::warn_impcast_float_to_integer; 12372 } 12373 12374 SmallString<16> PrettyTargetValue; 12375 if (IsBool) 12376 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12377 else 12378 IntegerValue.toString(PrettyTargetValue); 12379 12380 if (PruneWarnings) { 12381 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12382 S.PDiag(DiagID) 12383 << E->getType() << T.getUnqualifiedType() 12384 << PrettySourceValue << PrettyTargetValue 12385 << E->getSourceRange() << SourceRange(CContext)); 12386 } else { 12387 S.Diag(E->getExprLoc(), DiagID) 12388 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12389 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12390 } 12391 } 12392 12393 /// Analyze the given compound assignment for the possible losing of 12394 /// floating-point precision. 12395 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12396 assert(isa<CompoundAssignOperator>(E) && 12397 "Must be compound assignment operation"); 12398 // Recurse on the LHS and RHS in here 12399 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12400 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12401 12402 if (E->getLHS()->getType()->isAtomicType()) 12403 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12404 12405 // Now check the outermost expression 12406 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12407 const auto *RBT = cast<CompoundAssignOperator>(E) 12408 ->getComputationResultType() 12409 ->getAs<BuiltinType>(); 12410 12411 // The below checks assume source is floating point. 12412 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12413 12414 // If source is floating point but target is an integer. 12415 if (ResultBT->isInteger()) 12416 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12417 E->getExprLoc(), diag::warn_impcast_float_integer); 12418 12419 if (!ResultBT->isFloatingPoint()) 12420 return; 12421 12422 // If both source and target are floating points, warn about losing precision. 12423 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12424 QualType(ResultBT, 0), QualType(RBT, 0)); 12425 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12426 // warn about dropping FP rank. 12427 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12428 diag::warn_impcast_float_result_precision); 12429 } 12430 12431 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12432 IntRange Range) { 12433 if (!Range.Width) return "0"; 12434 12435 llvm::APSInt ValueInRange = Value; 12436 ValueInRange.setIsSigned(!Range.NonNegative); 12437 ValueInRange = ValueInRange.trunc(Range.Width); 12438 return toString(ValueInRange, 10); 12439 } 12440 12441 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12442 if (!isa<ImplicitCastExpr>(Ex)) 12443 return false; 12444 12445 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12446 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12447 const Type *Source = 12448 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12449 if (Target->isDependentType()) 12450 return false; 12451 12452 const BuiltinType *FloatCandidateBT = 12453 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12454 const Type *BoolCandidateType = ToBool ? Target : Source; 12455 12456 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12457 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12458 } 12459 12460 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12461 SourceLocation CC) { 12462 unsigned NumArgs = TheCall->getNumArgs(); 12463 for (unsigned i = 0; i < NumArgs; ++i) { 12464 Expr *CurrA = TheCall->getArg(i); 12465 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12466 continue; 12467 12468 bool IsSwapped = ((i > 0) && 12469 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12470 IsSwapped |= ((i < (NumArgs - 1)) && 12471 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12472 if (IsSwapped) { 12473 // Warn on this floating-point to bool conversion. 12474 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12475 CurrA->getType(), CC, 12476 diag::warn_impcast_floating_point_to_bool); 12477 } 12478 } 12479 } 12480 12481 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12482 SourceLocation CC) { 12483 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12484 E->getExprLoc())) 12485 return; 12486 12487 // Don't warn on functions which have return type nullptr_t. 12488 if (isa<CallExpr>(E)) 12489 return; 12490 12491 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12492 const Expr::NullPointerConstantKind NullKind = 12493 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12494 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12495 return; 12496 12497 // Return if target type is a safe conversion. 12498 if (T->isAnyPointerType() || T->isBlockPointerType() || 12499 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12500 return; 12501 12502 SourceLocation Loc = E->getSourceRange().getBegin(); 12503 12504 // Venture through the macro stacks to get to the source of macro arguments. 12505 // The new location is a better location than the complete location that was 12506 // passed in. 12507 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12508 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12509 12510 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12511 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12512 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12513 Loc, S.SourceMgr, S.getLangOpts()); 12514 if (MacroName == "NULL") 12515 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12516 } 12517 12518 // Only warn if the null and context location are in the same macro expansion. 12519 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12520 return; 12521 12522 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12523 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12524 << FixItHint::CreateReplacement(Loc, 12525 S.getFixItZeroLiteralForType(T, Loc)); 12526 } 12527 12528 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12529 ObjCArrayLiteral *ArrayLiteral); 12530 12531 static void 12532 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12533 ObjCDictionaryLiteral *DictionaryLiteral); 12534 12535 /// Check a single element within a collection literal against the 12536 /// target element type. 12537 static void checkObjCCollectionLiteralElement(Sema &S, 12538 QualType TargetElementType, 12539 Expr *Element, 12540 unsigned ElementKind) { 12541 // Skip a bitcast to 'id' or qualified 'id'. 12542 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12543 if (ICE->getCastKind() == CK_BitCast && 12544 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12545 Element = ICE->getSubExpr(); 12546 } 12547 12548 QualType ElementType = Element->getType(); 12549 ExprResult ElementResult(Element); 12550 if (ElementType->getAs<ObjCObjectPointerType>() && 12551 S.CheckSingleAssignmentConstraints(TargetElementType, 12552 ElementResult, 12553 false, false) 12554 != Sema::Compatible) { 12555 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12556 << ElementType << ElementKind << TargetElementType 12557 << Element->getSourceRange(); 12558 } 12559 12560 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12561 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12562 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12563 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12564 } 12565 12566 /// Check an Objective-C array literal being converted to the given 12567 /// target type. 12568 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12569 ObjCArrayLiteral *ArrayLiteral) { 12570 if (!S.NSArrayDecl) 12571 return; 12572 12573 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12574 if (!TargetObjCPtr) 12575 return; 12576 12577 if (TargetObjCPtr->isUnspecialized() || 12578 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12579 != S.NSArrayDecl->getCanonicalDecl()) 12580 return; 12581 12582 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12583 if (TypeArgs.size() != 1) 12584 return; 12585 12586 QualType TargetElementType = TypeArgs[0]; 12587 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12588 checkObjCCollectionLiteralElement(S, TargetElementType, 12589 ArrayLiteral->getElement(I), 12590 0); 12591 } 12592 } 12593 12594 /// Check an Objective-C dictionary literal being converted to the given 12595 /// target type. 12596 static void 12597 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12598 ObjCDictionaryLiteral *DictionaryLiteral) { 12599 if (!S.NSDictionaryDecl) 12600 return; 12601 12602 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12603 if (!TargetObjCPtr) 12604 return; 12605 12606 if (TargetObjCPtr->isUnspecialized() || 12607 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12608 != S.NSDictionaryDecl->getCanonicalDecl()) 12609 return; 12610 12611 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12612 if (TypeArgs.size() != 2) 12613 return; 12614 12615 QualType TargetKeyType = TypeArgs[0]; 12616 QualType TargetObjectType = TypeArgs[1]; 12617 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12618 auto Element = DictionaryLiteral->getKeyValueElement(I); 12619 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12620 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12621 } 12622 } 12623 12624 // Helper function to filter out cases for constant width constant conversion. 12625 // Don't warn on char array initialization or for non-decimal values. 12626 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12627 SourceLocation CC) { 12628 // If initializing from a constant, and the constant starts with '0', 12629 // then it is a binary, octal, or hexadecimal. Allow these constants 12630 // to fill all the bits, even if there is a sign change. 12631 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12632 const char FirstLiteralCharacter = 12633 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12634 if (FirstLiteralCharacter == '0') 12635 return false; 12636 } 12637 12638 // If the CC location points to a '{', and the type is char, then assume 12639 // assume it is an array initialization. 12640 if (CC.isValid() && T->isCharType()) { 12641 const char FirstContextCharacter = 12642 S.getSourceManager().getCharacterData(CC)[0]; 12643 if (FirstContextCharacter == '{') 12644 return false; 12645 } 12646 12647 return true; 12648 } 12649 12650 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12651 const auto *IL = dyn_cast<IntegerLiteral>(E); 12652 if (!IL) { 12653 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12654 if (UO->getOpcode() == UO_Minus) 12655 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12656 } 12657 } 12658 12659 return IL; 12660 } 12661 12662 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12663 E = E->IgnoreParenImpCasts(); 12664 SourceLocation ExprLoc = E->getExprLoc(); 12665 12666 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12667 BinaryOperator::Opcode Opc = BO->getOpcode(); 12668 Expr::EvalResult Result; 12669 // Do not diagnose unsigned shifts. 12670 if (Opc == BO_Shl) { 12671 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12672 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12673 if (LHS && LHS->getValue() == 0) 12674 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12675 else if (!E->isValueDependent() && LHS && RHS && 12676 RHS->getValue().isNonNegative() && 12677 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12678 S.Diag(ExprLoc, diag::warn_left_shift_always) 12679 << (Result.Val.getInt() != 0); 12680 else if (E->getType()->isSignedIntegerType()) 12681 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12682 } 12683 } 12684 12685 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12686 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12687 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12688 if (!LHS || !RHS) 12689 return; 12690 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12691 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12692 // Do not diagnose common idioms. 12693 return; 12694 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12695 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12696 } 12697 } 12698 12699 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12700 SourceLocation CC, 12701 bool *ICContext = nullptr, 12702 bool IsListInit = false) { 12703 if (E->isTypeDependent() || E->isValueDependent()) return; 12704 12705 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12706 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12707 if (Source == Target) return; 12708 if (Target->isDependentType()) return; 12709 12710 // If the conversion context location is invalid don't complain. We also 12711 // don't want to emit a warning if the issue occurs from the expansion of 12712 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12713 // delay this check as long as possible. Once we detect we are in that 12714 // scenario, we just return. 12715 if (CC.isInvalid()) 12716 return; 12717 12718 if (Source->isAtomicType()) 12719 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12720 12721 // Diagnose implicit casts to bool. 12722 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12723 if (isa<StringLiteral>(E)) 12724 // Warn on string literal to bool. Checks for string literals in logical 12725 // and expressions, for instance, assert(0 && "error here"), are 12726 // prevented by a check in AnalyzeImplicitConversions(). 12727 return DiagnoseImpCast(S, E, T, CC, 12728 diag::warn_impcast_string_literal_to_bool); 12729 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12730 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12731 // This covers the literal expressions that evaluate to Objective-C 12732 // objects. 12733 return DiagnoseImpCast(S, E, T, CC, 12734 diag::warn_impcast_objective_c_literal_to_bool); 12735 } 12736 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12737 // Warn on pointer to bool conversion that is always true. 12738 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12739 SourceRange(CC)); 12740 } 12741 } 12742 12743 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12744 // is a typedef for signed char (macOS), then that constant value has to be 1 12745 // or 0. 12746 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12747 Expr::EvalResult Result; 12748 if (E->EvaluateAsInt(Result, S.getASTContext(), 12749 Expr::SE_AllowSideEffects)) { 12750 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12751 adornObjCBoolConversionDiagWithTernaryFixit( 12752 S, E, 12753 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12754 << toString(Result.Val.getInt(), 10)); 12755 } 12756 return; 12757 } 12758 } 12759 12760 // Check implicit casts from Objective-C collection literals to specialized 12761 // collection types, e.g., NSArray<NSString *> *. 12762 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12763 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12764 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12765 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12766 12767 // Strip vector types. 12768 if (isa<VectorType>(Source)) { 12769 if (Target->isVLSTBuiltinType() && 12770 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 12771 QualType(Source, 0)) || 12772 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 12773 QualType(Source, 0)))) 12774 return; 12775 12776 if (!isa<VectorType>(Target)) { 12777 if (S.SourceMgr.isInSystemMacro(CC)) 12778 return; 12779 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12780 } 12781 12782 // If the vector cast is cast between two vectors of the same size, it is 12783 // a bitcast, not a conversion. 12784 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12785 return; 12786 12787 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12788 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12789 } 12790 if (auto VecTy = dyn_cast<VectorType>(Target)) 12791 Target = VecTy->getElementType().getTypePtr(); 12792 12793 // Strip complex types. 12794 if (isa<ComplexType>(Source)) { 12795 if (!isa<ComplexType>(Target)) { 12796 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12797 return; 12798 12799 return DiagnoseImpCast(S, E, T, CC, 12800 S.getLangOpts().CPlusPlus 12801 ? diag::err_impcast_complex_scalar 12802 : diag::warn_impcast_complex_scalar); 12803 } 12804 12805 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12806 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12807 } 12808 12809 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12810 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12811 12812 // If the source is floating point... 12813 if (SourceBT && SourceBT->isFloatingPoint()) { 12814 // ...and the target is floating point... 12815 if (TargetBT && TargetBT->isFloatingPoint()) { 12816 // ...then warn if we're dropping FP rank. 12817 12818 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12819 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12820 if (Order > 0) { 12821 // Don't warn about float constants that are precisely 12822 // representable in the target type. 12823 Expr::EvalResult result; 12824 if (E->EvaluateAsRValue(result, S.Context)) { 12825 // Value might be a float, a float vector, or a float complex. 12826 if (IsSameFloatAfterCast(result.Val, 12827 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12828 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12829 return; 12830 } 12831 12832 if (S.SourceMgr.isInSystemMacro(CC)) 12833 return; 12834 12835 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12836 } 12837 // ... or possibly if we're increasing rank, too 12838 else if (Order < 0) { 12839 if (S.SourceMgr.isInSystemMacro(CC)) 12840 return; 12841 12842 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12843 } 12844 return; 12845 } 12846 12847 // If the target is integral, always warn. 12848 if (TargetBT && TargetBT->isInteger()) { 12849 if (S.SourceMgr.isInSystemMacro(CC)) 12850 return; 12851 12852 DiagnoseFloatingImpCast(S, E, T, CC); 12853 } 12854 12855 // Detect the case where a call result is converted from floating-point to 12856 // to bool, and the final argument to the call is converted from bool, to 12857 // discover this typo: 12858 // 12859 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12860 // 12861 // FIXME: This is an incredibly special case; is there some more general 12862 // way to detect this class of misplaced-parentheses bug? 12863 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12864 // Check last argument of function call to see if it is an 12865 // implicit cast from a type matching the type the result 12866 // is being cast to. 12867 CallExpr *CEx = cast<CallExpr>(E); 12868 if (unsigned NumArgs = CEx->getNumArgs()) { 12869 Expr *LastA = CEx->getArg(NumArgs - 1); 12870 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12871 if (isa<ImplicitCastExpr>(LastA) && 12872 InnerE->getType()->isBooleanType()) { 12873 // Warn on this floating-point to bool conversion 12874 DiagnoseImpCast(S, E, T, CC, 12875 diag::warn_impcast_floating_point_to_bool); 12876 } 12877 } 12878 } 12879 return; 12880 } 12881 12882 // Valid casts involving fixed point types should be accounted for here. 12883 if (Source->isFixedPointType()) { 12884 if (Target->isUnsaturatedFixedPointType()) { 12885 Expr::EvalResult Result; 12886 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12887 S.isConstantEvaluated())) { 12888 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12889 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12890 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12891 if (Value > MaxVal || Value < MinVal) { 12892 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12893 S.PDiag(diag::warn_impcast_fixed_point_range) 12894 << Value.toString() << T 12895 << E->getSourceRange() 12896 << clang::SourceRange(CC)); 12897 return; 12898 } 12899 } 12900 } else if (Target->isIntegerType()) { 12901 Expr::EvalResult Result; 12902 if (!S.isConstantEvaluated() && 12903 E->EvaluateAsFixedPoint(Result, S.Context, 12904 Expr::SE_AllowSideEffects)) { 12905 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12906 12907 bool Overflowed; 12908 llvm::APSInt IntResult = FXResult.convertToInt( 12909 S.Context.getIntWidth(T), 12910 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12911 12912 if (Overflowed) { 12913 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12914 S.PDiag(diag::warn_impcast_fixed_point_range) 12915 << FXResult.toString() << T 12916 << E->getSourceRange() 12917 << clang::SourceRange(CC)); 12918 return; 12919 } 12920 } 12921 } 12922 } else if (Target->isUnsaturatedFixedPointType()) { 12923 if (Source->isIntegerType()) { 12924 Expr::EvalResult Result; 12925 if (!S.isConstantEvaluated() && 12926 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12927 llvm::APSInt Value = Result.Val.getInt(); 12928 12929 bool Overflowed; 12930 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12931 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12932 12933 if (Overflowed) { 12934 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12935 S.PDiag(diag::warn_impcast_fixed_point_range) 12936 << toString(Value, /*Radix=*/10) << T 12937 << E->getSourceRange() 12938 << clang::SourceRange(CC)); 12939 return; 12940 } 12941 } 12942 } 12943 } 12944 12945 // If we are casting an integer type to a floating point type without 12946 // initialization-list syntax, we might lose accuracy if the floating 12947 // point type has a narrower significand than the integer type. 12948 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12949 TargetBT->isFloatingType() && !IsListInit) { 12950 // Determine the number of precision bits in the source integer type. 12951 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12952 /*Approximate*/ true); 12953 unsigned int SourcePrecision = SourceRange.Width; 12954 12955 // Determine the number of precision bits in the 12956 // target floating point type. 12957 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12958 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12959 12960 if (SourcePrecision > 0 && TargetPrecision > 0 && 12961 SourcePrecision > TargetPrecision) { 12962 12963 if (Optional<llvm::APSInt> SourceInt = 12964 E->getIntegerConstantExpr(S.Context)) { 12965 // If the source integer is a constant, convert it to the target 12966 // floating point type. Issue a warning if the value changes 12967 // during the whole conversion. 12968 llvm::APFloat TargetFloatValue( 12969 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12970 llvm::APFloat::opStatus ConversionStatus = 12971 TargetFloatValue.convertFromAPInt( 12972 *SourceInt, SourceBT->isSignedInteger(), 12973 llvm::APFloat::rmNearestTiesToEven); 12974 12975 if (ConversionStatus != llvm::APFloat::opOK) { 12976 SmallString<32> PrettySourceValue; 12977 SourceInt->toString(PrettySourceValue, 10); 12978 SmallString<32> PrettyTargetValue; 12979 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 12980 12981 S.DiagRuntimeBehavior( 12982 E->getExprLoc(), E, 12983 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 12984 << PrettySourceValue << PrettyTargetValue << E->getType() << T 12985 << E->getSourceRange() << clang::SourceRange(CC)); 12986 } 12987 } else { 12988 // Otherwise, the implicit conversion may lose precision. 12989 DiagnoseImpCast(S, E, T, CC, 12990 diag::warn_impcast_integer_float_precision); 12991 } 12992 } 12993 } 12994 12995 DiagnoseNullConversion(S, E, T, CC); 12996 12997 S.DiscardMisalignedMemberAddress(Target, E); 12998 12999 if (Target->isBooleanType()) 13000 DiagnoseIntInBoolContext(S, E); 13001 13002 if (!Source->isIntegerType() || !Target->isIntegerType()) 13003 return; 13004 13005 // TODO: remove this early return once the false positives for constant->bool 13006 // in templates, macros, etc, are reduced or removed. 13007 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 13008 return; 13009 13010 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 13011 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 13012 return adornObjCBoolConversionDiagWithTernaryFixit( 13013 S, E, 13014 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 13015 << E->getType()); 13016 } 13017 13018 IntRange SourceTypeRange = 13019 IntRange::forTargetOfCanonicalType(S.Context, Source); 13020 IntRange LikelySourceRange = 13021 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 13022 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 13023 13024 if (LikelySourceRange.Width > TargetRange.Width) { 13025 // If the source is a constant, use a default-on diagnostic. 13026 // TODO: this should happen for bitfield stores, too. 13027 Expr::EvalResult Result; 13028 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 13029 S.isConstantEvaluated())) { 13030 llvm::APSInt Value(32); 13031 Value = Result.Val.getInt(); 13032 13033 if (S.SourceMgr.isInSystemMacro(CC)) 13034 return; 13035 13036 std::string PrettySourceValue = toString(Value, 10); 13037 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13038 13039 S.DiagRuntimeBehavior( 13040 E->getExprLoc(), E, 13041 S.PDiag(diag::warn_impcast_integer_precision_constant) 13042 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13043 << E->getSourceRange() << SourceRange(CC)); 13044 return; 13045 } 13046 13047 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 13048 if (S.SourceMgr.isInSystemMacro(CC)) 13049 return; 13050 13051 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 13052 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 13053 /* pruneControlFlow */ true); 13054 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 13055 } 13056 13057 if (TargetRange.Width > SourceTypeRange.Width) { 13058 if (auto *UO = dyn_cast<UnaryOperator>(E)) 13059 if (UO->getOpcode() == UO_Minus) 13060 if (Source->isUnsignedIntegerType()) { 13061 if (Target->isUnsignedIntegerType()) 13062 return DiagnoseImpCast(S, E, T, CC, 13063 diag::warn_impcast_high_order_zero_bits); 13064 if (Target->isSignedIntegerType()) 13065 return DiagnoseImpCast(S, E, T, CC, 13066 diag::warn_impcast_nonnegative_result); 13067 } 13068 } 13069 13070 if (TargetRange.Width == LikelySourceRange.Width && 13071 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 13072 Source->isSignedIntegerType()) { 13073 // Warn when doing a signed to signed conversion, warn if the positive 13074 // source value is exactly the width of the target type, which will 13075 // cause a negative value to be stored. 13076 13077 Expr::EvalResult Result; 13078 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 13079 !S.SourceMgr.isInSystemMacro(CC)) { 13080 llvm::APSInt Value = Result.Val.getInt(); 13081 if (isSameWidthConstantConversion(S, E, T, CC)) { 13082 std::string PrettySourceValue = toString(Value, 10); 13083 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13084 13085 S.DiagRuntimeBehavior( 13086 E->getExprLoc(), E, 13087 S.PDiag(diag::warn_impcast_integer_precision_constant) 13088 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13089 << E->getSourceRange() << SourceRange(CC)); 13090 return; 13091 } 13092 } 13093 13094 // Fall through for non-constants to give a sign conversion warning. 13095 } 13096 13097 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 13098 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 13099 LikelySourceRange.Width == TargetRange.Width)) { 13100 if (S.SourceMgr.isInSystemMacro(CC)) 13101 return; 13102 13103 unsigned DiagID = diag::warn_impcast_integer_sign; 13104 13105 // Traditionally, gcc has warned about this under -Wsign-compare. 13106 // We also want to warn about it in -Wconversion. 13107 // So if -Wconversion is off, use a completely identical diagnostic 13108 // in the sign-compare group. 13109 // The conditional-checking code will 13110 if (ICContext) { 13111 DiagID = diag::warn_impcast_integer_sign_conditional; 13112 *ICContext = true; 13113 } 13114 13115 return DiagnoseImpCast(S, E, T, CC, DiagID); 13116 } 13117 13118 // Diagnose conversions between different enumeration types. 13119 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 13120 // type, to give us better diagnostics. 13121 QualType SourceType = E->getType(); 13122 if (!S.getLangOpts().CPlusPlus) { 13123 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13124 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 13125 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 13126 SourceType = S.Context.getTypeDeclType(Enum); 13127 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 13128 } 13129 } 13130 13131 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 13132 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 13133 if (SourceEnum->getDecl()->hasNameForLinkage() && 13134 TargetEnum->getDecl()->hasNameForLinkage() && 13135 SourceEnum != TargetEnum) { 13136 if (S.SourceMgr.isInSystemMacro(CC)) 13137 return; 13138 13139 return DiagnoseImpCast(S, E, SourceType, T, CC, 13140 diag::warn_impcast_different_enum_types); 13141 } 13142 } 13143 13144 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13145 SourceLocation CC, QualType T); 13146 13147 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 13148 SourceLocation CC, bool &ICContext) { 13149 E = E->IgnoreParenImpCasts(); 13150 13151 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 13152 return CheckConditionalOperator(S, CO, CC, T); 13153 13154 AnalyzeImplicitConversions(S, E, CC); 13155 if (E->getType() != T) 13156 return CheckImplicitConversion(S, E, T, CC, &ICContext); 13157 } 13158 13159 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13160 SourceLocation CC, QualType T) { 13161 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 13162 13163 Expr *TrueExpr = E->getTrueExpr(); 13164 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 13165 TrueExpr = BCO->getCommon(); 13166 13167 bool Suspicious = false; 13168 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 13169 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 13170 13171 if (T->isBooleanType()) 13172 DiagnoseIntInBoolContext(S, E); 13173 13174 // If -Wconversion would have warned about either of the candidates 13175 // for a signedness conversion to the context type... 13176 if (!Suspicious) return; 13177 13178 // ...but it's currently ignored... 13179 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13180 return; 13181 13182 // ...then check whether it would have warned about either of the 13183 // candidates for a signedness conversion to the condition type. 13184 if (E->getType() == T) return; 13185 13186 Suspicious = false; 13187 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13188 E->getType(), CC, &Suspicious); 13189 if (!Suspicious) 13190 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13191 E->getType(), CC, &Suspicious); 13192 } 13193 13194 /// Check conversion of given expression to boolean. 13195 /// Input argument E is a logical expression. 13196 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13197 if (S.getLangOpts().Bool) 13198 return; 13199 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13200 return; 13201 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13202 } 13203 13204 namespace { 13205 struct AnalyzeImplicitConversionsWorkItem { 13206 Expr *E; 13207 SourceLocation CC; 13208 bool IsListInit; 13209 }; 13210 } 13211 13212 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13213 /// that should be visited are added to WorkList. 13214 static void AnalyzeImplicitConversions( 13215 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13216 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13217 Expr *OrigE = Item.E; 13218 SourceLocation CC = Item.CC; 13219 13220 QualType T = OrigE->getType(); 13221 Expr *E = OrigE->IgnoreParenImpCasts(); 13222 13223 // Propagate whether we are in a C++ list initialization expression. 13224 // If so, we do not issue warnings for implicit int-float conversion 13225 // precision loss, because C++11 narrowing already handles it. 13226 bool IsListInit = Item.IsListInit || 13227 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13228 13229 if (E->isTypeDependent() || E->isValueDependent()) 13230 return; 13231 13232 Expr *SourceExpr = E; 13233 // Examine, but don't traverse into the source expression of an 13234 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13235 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13236 // evaluate it in the context of checking the specific conversion to T though. 13237 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13238 if (auto *Src = OVE->getSourceExpr()) 13239 SourceExpr = Src; 13240 13241 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13242 if (UO->getOpcode() == UO_Not && 13243 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13244 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13245 << OrigE->getSourceRange() << T->isBooleanType() 13246 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13247 13248 // For conditional operators, we analyze the arguments as if they 13249 // were being fed directly into the output. 13250 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13251 CheckConditionalOperator(S, CO, CC, T); 13252 return; 13253 } 13254 13255 // Check implicit argument conversions for function calls. 13256 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13257 CheckImplicitArgumentConversions(S, Call, CC); 13258 13259 // Go ahead and check any implicit conversions we might have skipped. 13260 // The non-canonical typecheck is just an optimization; 13261 // CheckImplicitConversion will filter out dead implicit conversions. 13262 if (SourceExpr->getType() != T) 13263 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13264 13265 // Now continue drilling into this expression. 13266 13267 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13268 // The bound subexpressions in a PseudoObjectExpr are not reachable 13269 // as transitive children. 13270 // FIXME: Use a more uniform representation for this. 13271 for (auto *SE : POE->semantics()) 13272 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13273 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13274 } 13275 13276 // Skip past explicit casts. 13277 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13278 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13279 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13280 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13281 WorkList.push_back({E, CC, IsListInit}); 13282 return; 13283 } 13284 13285 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13286 // Do a somewhat different check with comparison operators. 13287 if (BO->isComparisonOp()) 13288 return AnalyzeComparison(S, BO); 13289 13290 // And with simple assignments. 13291 if (BO->getOpcode() == BO_Assign) 13292 return AnalyzeAssignment(S, BO); 13293 // And with compound assignments. 13294 if (BO->isAssignmentOp()) 13295 return AnalyzeCompoundAssignment(S, BO); 13296 } 13297 13298 // These break the otherwise-useful invariant below. Fortunately, 13299 // we don't really need to recurse into them, because any internal 13300 // expressions should have been analyzed already when they were 13301 // built into statements. 13302 if (isa<StmtExpr>(E)) return; 13303 13304 // Don't descend into unevaluated contexts. 13305 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13306 13307 // Now just recurse over the expression's children. 13308 CC = E->getExprLoc(); 13309 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13310 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13311 for (Stmt *SubStmt : E->children()) { 13312 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13313 if (!ChildExpr) 13314 continue; 13315 13316 if (IsLogicalAndOperator && 13317 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13318 // Ignore checking string literals that are in logical and operators. 13319 // This is a common pattern for asserts. 13320 continue; 13321 WorkList.push_back({ChildExpr, CC, IsListInit}); 13322 } 13323 13324 if (BO && BO->isLogicalOp()) { 13325 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13326 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13327 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13328 13329 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13330 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13331 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13332 } 13333 13334 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13335 if (U->getOpcode() == UO_LNot) { 13336 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13337 } else if (U->getOpcode() != UO_AddrOf) { 13338 if (U->getSubExpr()->getType()->isAtomicType()) 13339 S.Diag(U->getSubExpr()->getBeginLoc(), 13340 diag::warn_atomic_implicit_seq_cst); 13341 } 13342 } 13343 } 13344 13345 /// AnalyzeImplicitConversions - Find and report any interesting 13346 /// implicit conversions in the given expression. There are a couple 13347 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13348 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13349 bool IsListInit/*= false*/) { 13350 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13351 WorkList.push_back({OrigE, CC, IsListInit}); 13352 while (!WorkList.empty()) 13353 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13354 } 13355 13356 /// Diagnose integer type and any valid implicit conversion to it. 13357 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13358 // Taking into account implicit conversions, 13359 // allow any integer. 13360 if (!E->getType()->isIntegerType()) { 13361 S.Diag(E->getBeginLoc(), 13362 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13363 return true; 13364 } 13365 // Potentially emit standard warnings for implicit conversions if enabled 13366 // using -Wconversion. 13367 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13368 return false; 13369 } 13370 13371 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13372 // Returns true when emitting a warning about taking the address of a reference. 13373 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13374 const PartialDiagnostic &PD) { 13375 E = E->IgnoreParenImpCasts(); 13376 13377 const FunctionDecl *FD = nullptr; 13378 13379 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13380 if (!DRE->getDecl()->getType()->isReferenceType()) 13381 return false; 13382 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13383 if (!M->getMemberDecl()->getType()->isReferenceType()) 13384 return false; 13385 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13386 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13387 return false; 13388 FD = Call->getDirectCallee(); 13389 } else { 13390 return false; 13391 } 13392 13393 SemaRef.Diag(E->getExprLoc(), PD); 13394 13395 // If possible, point to location of function. 13396 if (FD) { 13397 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13398 } 13399 13400 return true; 13401 } 13402 13403 // Returns true if the SourceLocation is expanded from any macro body. 13404 // Returns false if the SourceLocation is invalid, is from not in a macro 13405 // expansion, or is from expanded from a top-level macro argument. 13406 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13407 if (Loc.isInvalid()) 13408 return false; 13409 13410 while (Loc.isMacroID()) { 13411 if (SM.isMacroBodyExpansion(Loc)) 13412 return true; 13413 Loc = SM.getImmediateMacroCallerLoc(Loc); 13414 } 13415 13416 return false; 13417 } 13418 13419 /// Diagnose pointers that are always non-null. 13420 /// \param E the expression containing the pointer 13421 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13422 /// compared to a null pointer 13423 /// \param IsEqual True when the comparison is equal to a null pointer 13424 /// \param Range Extra SourceRange to highlight in the diagnostic 13425 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13426 Expr::NullPointerConstantKind NullKind, 13427 bool IsEqual, SourceRange Range) { 13428 if (!E) 13429 return; 13430 13431 // Don't warn inside macros. 13432 if (E->getExprLoc().isMacroID()) { 13433 const SourceManager &SM = getSourceManager(); 13434 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13435 IsInAnyMacroBody(SM, Range.getBegin())) 13436 return; 13437 } 13438 E = E->IgnoreImpCasts(); 13439 13440 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13441 13442 if (isa<CXXThisExpr>(E)) { 13443 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13444 : diag::warn_this_bool_conversion; 13445 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13446 return; 13447 } 13448 13449 bool IsAddressOf = false; 13450 13451 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13452 if (UO->getOpcode() != UO_AddrOf) 13453 return; 13454 IsAddressOf = true; 13455 E = UO->getSubExpr(); 13456 } 13457 13458 if (IsAddressOf) { 13459 unsigned DiagID = IsCompare 13460 ? diag::warn_address_of_reference_null_compare 13461 : diag::warn_address_of_reference_bool_conversion; 13462 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13463 << IsEqual; 13464 if (CheckForReference(*this, E, PD)) { 13465 return; 13466 } 13467 } 13468 13469 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13470 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13471 std::string Str; 13472 llvm::raw_string_ostream S(Str); 13473 E->printPretty(S, nullptr, getPrintingPolicy()); 13474 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13475 : diag::warn_cast_nonnull_to_bool; 13476 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13477 << E->getSourceRange() << Range << IsEqual; 13478 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13479 }; 13480 13481 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13482 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13483 if (auto *Callee = Call->getDirectCallee()) { 13484 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13485 ComplainAboutNonnullParamOrCall(A); 13486 return; 13487 } 13488 } 13489 } 13490 13491 // Expect to find a single Decl. Skip anything more complicated. 13492 ValueDecl *D = nullptr; 13493 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13494 D = R->getDecl(); 13495 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13496 D = M->getMemberDecl(); 13497 } 13498 13499 // Weak Decls can be null. 13500 if (!D || D->isWeak()) 13501 return; 13502 13503 // Check for parameter decl with nonnull attribute 13504 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13505 if (getCurFunction() && 13506 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13507 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13508 ComplainAboutNonnullParamOrCall(A); 13509 return; 13510 } 13511 13512 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13513 // Skip function template not specialized yet. 13514 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13515 return; 13516 auto ParamIter = llvm::find(FD->parameters(), PV); 13517 assert(ParamIter != FD->param_end()); 13518 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13519 13520 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13521 if (!NonNull->args_size()) { 13522 ComplainAboutNonnullParamOrCall(NonNull); 13523 return; 13524 } 13525 13526 for (const ParamIdx &ArgNo : NonNull->args()) { 13527 if (ArgNo.getASTIndex() == ParamNo) { 13528 ComplainAboutNonnullParamOrCall(NonNull); 13529 return; 13530 } 13531 } 13532 } 13533 } 13534 } 13535 } 13536 13537 QualType T = D->getType(); 13538 const bool IsArray = T->isArrayType(); 13539 const bool IsFunction = T->isFunctionType(); 13540 13541 // Address of function is used to silence the function warning. 13542 if (IsAddressOf && IsFunction) { 13543 return; 13544 } 13545 13546 // Found nothing. 13547 if (!IsAddressOf && !IsFunction && !IsArray) 13548 return; 13549 13550 // Pretty print the expression for the diagnostic. 13551 std::string Str; 13552 llvm::raw_string_ostream S(Str); 13553 E->printPretty(S, nullptr, getPrintingPolicy()); 13554 13555 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13556 : diag::warn_impcast_pointer_to_bool; 13557 enum { 13558 AddressOf, 13559 FunctionPointer, 13560 ArrayPointer 13561 } DiagType; 13562 if (IsAddressOf) 13563 DiagType = AddressOf; 13564 else if (IsFunction) 13565 DiagType = FunctionPointer; 13566 else if (IsArray) 13567 DiagType = ArrayPointer; 13568 else 13569 llvm_unreachable("Could not determine diagnostic."); 13570 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13571 << Range << IsEqual; 13572 13573 if (!IsFunction) 13574 return; 13575 13576 // Suggest '&' to silence the function warning. 13577 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13578 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13579 13580 // Check to see if '()' fixit should be emitted. 13581 QualType ReturnType; 13582 UnresolvedSet<4> NonTemplateOverloads; 13583 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13584 if (ReturnType.isNull()) 13585 return; 13586 13587 if (IsCompare) { 13588 // There are two cases here. If there is null constant, the only suggest 13589 // for a pointer return type. If the null is 0, then suggest if the return 13590 // type is a pointer or an integer type. 13591 if (!ReturnType->isPointerType()) { 13592 if (NullKind == Expr::NPCK_ZeroExpression || 13593 NullKind == Expr::NPCK_ZeroLiteral) { 13594 if (!ReturnType->isIntegerType()) 13595 return; 13596 } else { 13597 return; 13598 } 13599 } 13600 } else { // !IsCompare 13601 // For function to bool, only suggest if the function pointer has bool 13602 // return type. 13603 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13604 return; 13605 } 13606 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13607 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13608 } 13609 13610 /// Diagnoses "dangerous" implicit conversions within the given 13611 /// expression (which is a full expression). Implements -Wconversion 13612 /// and -Wsign-compare. 13613 /// 13614 /// \param CC the "context" location of the implicit conversion, i.e. 13615 /// the most location of the syntactic entity requiring the implicit 13616 /// conversion 13617 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13618 // Don't diagnose in unevaluated contexts. 13619 if (isUnevaluatedContext()) 13620 return; 13621 13622 // Don't diagnose for value- or type-dependent expressions. 13623 if (E->isTypeDependent() || E->isValueDependent()) 13624 return; 13625 13626 // Check for array bounds violations in cases where the check isn't triggered 13627 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13628 // ArraySubscriptExpr is on the RHS of a variable initialization. 13629 CheckArrayAccess(E); 13630 13631 // This is not the right CC for (e.g.) a variable initialization. 13632 AnalyzeImplicitConversions(*this, E, CC); 13633 } 13634 13635 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13636 /// Input argument E is a logical expression. 13637 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13638 ::CheckBoolLikeConversion(*this, E, CC); 13639 } 13640 13641 /// Diagnose when expression is an integer constant expression and its evaluation 13642 /// results in integer overflow 13643 void Sema::CheckForIntOverflow (Expr *E) { 13644 // Use a work list to deal with nested struct initializers. 13645 SmallVector<Expr *, 2> Exprs(1, E); 13646 13647 do { 13648 Expr *OriginalE = Exprs.pop_back_val(); 13649 Expr *E = OriginalE->IgnoreParenCasts(); 13650 13651 if (isa<BinaryOperator>(E)) { 13652 E->EvaluateForOverflow(Context); 13653 continue; 13654 } 13655 13656 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13657 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13658 else if (isa<ObjCBoxedExpr>(OriginalE)) 13659 E->EvaluateForOverflow(Context); 13660 else if (auto Call = dyn_cast<CallExpr>(E)) 13661 Exprs.append(Call->arg_begin(), Call->arg_end()); 13662 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13663 Exprs.append(Message->arg_begin(), Message->arg_end()); 13664 } while (!Exprs.empty()); 13665 } 13666 13667 namespace { 13668 13669 /// Visitor for expressions which looks for unsequenced operations on the 13670 /// same object. 13671 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13672 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13673 13674 /// A tree of sequenced regions within an expression. Two regions are 13675 /// unsequenced if one is an ancestor or a descendent of the other. When we 13676 /// finish processing an expression with sequencing, such as a comma 13677 /// expression, we fold its tree nodes into its parent, since they are 13678 /// unsequenced with respect to nodes we will visit later. 13679 class SequenceTree { 13680 struct Value { 13681 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13682 unsigned Parent : 31; 13683 unsigned Merged : 1; 13684 }; 13685 SmallVector<Value, 8> Values; 13686 13687 public: 13688 /// A region within an expression which may be sequenced with respect 13689 /// to some other region. 13690 class Seq { 13691 friend class SequenceTree; 13692 13693 unsigned Index; 13694 13695 explicit Seq(unsigned N) : Index(N) {} 13696 13697 public: 13698 Seq() : Index(0) {} 13699 }; 13700 13701 SequenceTree() { Values.push_back(Value(0)); } 13702 Seq root() const { return Seq(0); } 13703 13704 /// Create a new sequence of operations, which is an unsequenced 13705 /// subset of \p Parent. This sequence of operations is sequenced with 13706 /// respect to other children of \p Parent. 13707 Seq allocate(Seq Parent) { 13708 Values.push_back(Value(Parent.Index)); 13709 return Seq(Values.size() - 1); 13710 } 13711 13712 /// Merge a sequence of operations into its parent. 13713 void merge(Seq S) { 13714 Values[S.Index].Merged = true; 13715 } 13716 13717 /// Determine whether two operations are unsequenced. This operation 13718 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13719 /// should have been merged into its parent as appropriate. 13720 bool isUnsequenced(Seq Cur, Seq Old) { 13721 unsigned C = representative(Cur.Index); 13722 unsigned Target = representative(Old.Index); 13723 while (C >= Target) { 13724 if (C == Target) 13725 return true; 13726 C = Values[C].Parent; 13727 } 13728 return false; 13729 } 13730 13731 private: 13732 /// Pick a representative for a sequence. 13733 unsigned representative(unsigned K) { 13734 if (Values[K].Merged) 13735 // Perform path compression as we go. 13736 return Values[K].Parent = representative(Values[K].Parent); 13737 return K; 13738 } 13739 }; 13740 13741 /// An object for which we can track unsequenced uses. 13742 using Object = const NamedDecl *; 13743 13744 /// Different flavors of object usage which we track. We only track the 13745 /// least-sequenced usage of each kind. 13746 enum UsageKind { 13747 /// A read of an object. Multiple unsequenced reads are OK. 13748 UK_Use, 13749 13750 /// A modification of an object which is sequenced before the value 13751 /// computation of the expression, such as ++n in C++. 13752 UK_ModAsValue, 13753 13754 /// A modification of an object which is not sequenced before the value 13755 /// computation of the expression, such as n++. 13756 UK_ModAsSideEffect, 13757 13758 UK_Count = UK_ModAsSideEffect + 1 13759 }; 13760 13761 /// Bundle together a sequencing region and the expression corresponding 13762 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13763 struct Usage { 13764 const Expr *UsageExpr; 13765 SequenceTree::Seq Seq; 13766 13767 Usage() : UsageExpr(nullptr), Seq() {} 13768 }; 13769 13770 struct UsageInfo { 13771 Usage Uses[UK_Count]; 13772 13773 /// Have we issued a diagnostic for this object already? 13774 bool Diagnosed; 13775 13776 UsageInfo() : Uses(), Diagnosed(false) {} 13777 }; 13778 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13779 13780 Sema &SemaRef; 13781 13782 /// Sequenced regions within the expression. 13783 SequenceTree Tree; 13784 13785 /// Declaration modifications and references which we have seen. 13786 UsageInfoMap UsageMap; 13787 13788 /// The region we are currently within. 13789 SequenceTree::Seq Region; 13790 13791 /// Filled in with declarations which were modified as a side-effect 13792 /// (that is, post-increment operations). 13793 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13794 13795 /// Expressions to check later. We defer checking these to reduce 13796 /// stack usage. 13797 SmallVectorImpl<const Expr *> &WorkList; 13798 13799 /// RAII object wrapping the visitation of a sequenced subexpression of an 13800 /// expression. At the end of this process, the side-effects of the evaluation 13801 /// become sequenced with respect to the value computation of the result, so 13802 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13803 /// UK_ModAsValue. 13804 struct SequencedSubexpression { 13805 SequencedSubexpression(SequenceChecker &Self) 13806 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13807 Self.ModAsSideEffect = &ModAsSideEffect; 13808 } 13809 13810 ~SequencedSubexpression() { 13811 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13812 // Add a new usage with usage kind UK_ModAsValue, and then restore 13813 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13814 // the previous one was empty). 13815 UsageInfo &UI = Self.UsageMap[M.first]; 13816 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13817 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13818 SideEffectUsage = M.second; 13819 } 13820 Self.ModAsSideEffect = OldModAsSideEffect; 13821 } 13822 13823 SequenceChecker &Self; 13824 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13825 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13826 }; 13827 13828 /// RAII object wrapping the visitation of a subexpression which we might 13829 /// choose to evaluate as a constant. If any subexpression is evaluated and 13830 /// found to be non-constant, this allows us to suppress the evaluation of 13831 /// the outer expression. 13832 class EvaluationTracker { 13833 public: 13834 EvaluationTracker(SequenceChecker &Self) 13835 : Self(Self), Prev(Self.EvalTracker) { 13836 Self.EvalTracker = this; 13837 } 13838 13839 ~EvaluationTracker() { 13840 Self.EvalTracker = Prev; 13841 if (Prev) 13842 Prev->EvalOK &= EvalOK; 13843 } 13844 13845 bool evaluate(const Expr *E, bool &Result) { 13846 if (!EvalOK || E->isValueDependent()) 13847 return false; 13848 EvalOK = E->EvaluateAsBooleanCondition( 13849 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13850 return EvalOK; 13851 } 13852 13853 private: 13854 SequenceChecker &Self; 13855 EvaluationTracker *Prev; 13856 bool EvalOK = true; 13857 } *EvalTracker = nullptr; 13858 13859 /// Find the object which is produced by the specified expression, 13860 /// if any. 13861 Object getObject(const Expr *E, bool Mod) const { 13862 E = E->IgnoreParenCasts(); 13863 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13864 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13865 return getObject(UO->getSubExpr(), Mod); 13866 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13867 if (BO->getOpcode() == BO_Comma) 13868 return getObject(BO->getRHS(), Mod); 13869 if (Mod && BO->isAssignmentOp()) 13870 return getObject(BO->getLHS(), Mod); 13871 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13872 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13873 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13874 return ME->getMemberDecl(); 13875 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13876 // FIXME: If this is a reference, map through to its value. 13877 return DRE->getDecl(); 13878 return nullptr; 13879 } 13880 13881 /// Note that an object \p O was modified or used by an expression 13882 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13883 /// the object \p O as obtained via the \p UsageMap. 13884 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13885 // Get the old usage for the given object and usage kind. 13886 Usage &U = UI.Uses[UK]; 13887 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13888 // If we have a modification as side effect and are in a sequenced 13889 // subexpression, save the old Usage so that we can restore it later 13890 // in SequencedSubexpression::~SequencedSubexpression. 13891 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13892 ModAsSideEffect->push_back(std::make_pair(O, U)); 13893 // Then record the new usage with the current sequencing region. 13894 U.UsageExpr = UsageExpr; 13895 U.Seq = Region; 13896 } 13897 } 13898 13899 /// Check whether a modification or use of an object \p O in an expression 13900 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13901 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13902 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13903 /// usage and false we are checking for a mod-use unsequenced usage. 13904 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13905 UsageKind OtherKind, bool IsModMod) { 13906 if (UI.Diagnosed) 13907 return; 13908 13909 const Usage &U = UI.Uses[OtherKind]; 13910 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13911 return; 13912 13913 const Expr *Mod = U.UsageExpr; 13914 const Expr *ModOrUse = UsageExpr; 13915 if (OtherKind == UK_Use) 13916 std::swap(Mod, ModOrUse); 13917 13918 SemaRef.DiagRuntimeBehavior( 13919 Mod->getExprLoc(), {Mod, ModOrUse}, 13920 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13921 : diag::warn_unsequenced_mod_use) 13922 << O << SourceRange(ModOrUse->getExprLoc())); 13923 UI.Diagnosed = true; 13924 } 13925 13926 // A note on note{Pre, Post}{Use, Mod}: 13927 // 13928 // (It helps to follow the algorithm with an expression such as 13929 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13930 // operations before C++17 and both are well-defined in C++17). 13931 // 13932 // When visiting a node which uses/modify an object we first call notePreUse 13933 // or notePreMod before visiting its sub-expression(s). At this point the 13934 // children of the current node have not yet been visited and so the eventual 13935 // uses/modifications resulting from the children of the current node have not 13936 // been recorded yet. 13937 // 13938 // We then visit the children of the current node. After that notePostUse or 13939 // notePostMod is called. These will 1) detect an unsequenced modification 13940 // as side effect (as in "k++ + k") and 2) add a new usage with the 13941 // appropriate usage kind. 13942 // 13943 // We also have to be careful that some operation sequences modification as 13944 // side effect as well (for example: || or ,). To account for this we wrap 13945 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13946 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13947 // which record usages which are modifications as side effect, and then 13948 // downgrade them (or more accurately restore the previous usage which was a 13949 // modification as side effect) when exiting the scope of the sequenced 13950 // subexpression. 13951 13952 void notePreUse(Object O, const Expr *UseExpr) { 13953 UsageInfo &UI = UsageMap[O]; 13954 // Uses conflict with other modifications. 13955 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13956 } 13957 13958 void notePostUse(Object O, const Expr *UseExpr) { 13959 UsageInfo &UI = UsageMap[O]; 13960 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 13961 /*IsModMod=*/false); 13962 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 13963 } 13964 13965 void notePreMod(Object O, const Expr *ModExpr) { 13966 UsageInfo &UI = UsageMap[O]; 13967 // Modifications conflict with other modifications and with uses. 13968 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 13969 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 13970 } 13971 13972 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 13973 UsageInfo &UI = UsageMap[O]; 13974 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 13975 /*IsModMod=*/true); 13976 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 13977 } 13978 13979 public: 13980 SequenceChecker(Sema &S, const Expr *E, 13981 SmallVectorImpl<const Expr *> &WorkList) 13982 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 13983 Visit(E); 13984 // Silence a -Wunused-private-field since WorkList is now unused. 13985 // TODO: Evaluate if it can be used, and if not remove it. 13986 (void)this->WorkList; 13987 } 13988 13989 void VisitStmt(const Stmt *S) { 13990 // Skip all statements which aren't expressions for now. 13991 } 13992 13993 void VisitExpr(const Expr *E) { 13994 // By default, just recurse to evaluated subexpressions. 13995 Base::VisitStmt(E); 13996 } 13997 13998 void VisitCastExpr(const CastExpr *E) { 13999 Object O = Object(); 14000 if (E->getCastKind() == CK_LValueToRValue) 14001 O = getObject(E->getSubExpr(), false); 14002 14003 if (O) 14004 notePreUse(O, E); 14005 VisitExpr(E); 14006 if (O) 14007 notePostUse(O, E); 14008 } 14009 14010 void VisitSequencedExpressions(const Expr *SequencedBefore, 14011 const Expr *SequencedAfter) { 14012 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 14013 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 14014 SequenceTree::Seq OldRegion = Region; 14015 14016 { 14017 SequencedSubexpression SeqBefore(*this); 14018 Region = BeforeRegion; 14019 Visit(SequencedBefore); 14020 } 14021 14022 Region = AfterRegion; 14023 Visit(SequencedAfter); 14024 14025 Region = OldRegion; 14026 14027 Tree.merge(BeforeRegion); 14028 Tree.merge(AfterRegion); 14029 } 14030 14031 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 14032 // C++17 [expr.sub]p1: 14033 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 14034 // expression E1 is sequenced before the expression E2. 14035 if (SemaRef.getLangOpts().CPlusPlus17) 14036 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 14037 else { 14038 Visit(ASE->getLHS()); 14039 Visit(ASE->getRHS()); 14040 } 14041 } 14042 14043 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14044 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14045 void VisitBinPtrMem(const BinaryOperator *BO) { 14046 // C++17 [expr.mptr.oper]p4: 14047 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 14048 // the expression E1 is sequenced before the expression E2. 14049 if (SemaRef.getLangOpts().CPlusPlus17) 14050 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14051 else { 14052 Visit(BO->getLHS()); 14053 Visit(BO->getRHS()); 14054 } 14055 } 14056 14057 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14058 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14059 void VisitBinShlShr(const BinaryOperator *BO) { 14060 // C++17 [expr.shift]p4: 14061 // The expression E1 is sequenced before the expression E2. 14062 if (SemaRef.getLangOpts().CPlusPlus17) 14063 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14064 else { 14065 Visit(BO->getLHS()); 14066 Visit(BO->getRHS()); 14067 } 14068 } 14069 14070 void VisitBinComma(const BinaryOperator *BO) { 14071 // C++11 [expr.comma]p1: 14072 // Every value computation and side effect associated with the left 14073 // expression is sequenced before every value computation and side 14074 // effect associated with the right expression. 14075 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14076 } 14077 14078 void VisitBinAssign(const BinaryOperator *BO) { 14079 SequenceTree::Seq RHSRegion; 14080 SequenceTree::Seq LHSRegion; 14081 if (SemaRef.getLangOpts().CPlusPlus17) { 14082 RHSRegion = Tree.allocate(Region); 14083 LHSRegion = Tree.allocate(Region); 14084 } else { 14085 RHSRegion = Region; 14086 LHSRegion = Region; 14087 } 14088 SequenceTree::Seq OldRegion = Region; 14089 14090 // C++11 [expr.ass]p1: 14091 // [...] the assignment is sequenced after the value computation 14092 // of the right and left operands, [...] 14093 // 14094 // so check it before inspecting the operands and update the 14095 // map afterwards. 14096 Object O = getObject(BO->getLHS(), /*Mod=*/true); 14097 if (O) 14098 notePreMod(O, BO); 14099 14100 if (SemaRef.getLangOpts().CPlusPlus17) { 14101 // C++17 [expr.ass]p1: 14102 // [...] The right operand is sequenced before the left operand. [...] 14103 { 14104 SequencedSubexpression SeqBefore(*this); 14105 Region = RHSRegion; 14106 Visit(BO->getRHS()); 14107 } 14108 14109 Region = LHSRegion; 14110 Visit(BO->getLHS()); 14111 14112 if (O && isa<CompoundAssignOperator>(BO)) 14113 notePostUse(O, BO); 14114 14115 } else { 14116 // C++11 does not specify any sequencing between the LHS and RHS. 14117 Region = LHSRegion; 14118 Visit(BO->getLHS()); 14119 14120 if (O && isa<CompoundAssignOperator>(BO)) 14121 notePostUse(O, BO); 14122 14123 Region = RHSRegion; 14124 Visit(BO->getRHS()); 14125 } 14126 14127 // C++11 [expr.ass]p1: 14128 // the assignment is sequenced [...] before the value computation of the 14129 // assignment expression. 14130 // C11 6.5.16/3 has no such rule. 14131 Region = OldRegion; 14132 if (O) 14133 notePostMod(O, BO, 14134 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14135 : UK_ModAsSideEffect); 14136 if (SemaRef.getLangOpts().CPlusPlus17) { 14137 Tree.merge(RHSRegion); 14138 Tree.merge(LHSRegion); 14139 } 14140 } 14141 14142 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 14143 VisitBinAssign(CAO); 14144 } 14145 14146 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14147 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14148 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 14149 Object O = getObject(UO->getSubExpr(), true); 14150 if (!O) 14151 return VisitExpr(UO); 14152 14153 notePreMod(O, UO); 14154 Visit(UO->getSubExpr()); 14155 // C++11 [expr.pre.incr]p1: 14156 // the expression ++x is equivalent to x+=1 14157 notePostMod(O, UO, 14158 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14159 : UK_ModAsSideEffect); 14160 } 14161 14162 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14163 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14164 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 14165 Object O = getObject(UO->getSubExpr(), true); 14166 if (!O) 14167 return VisitExpr(UO); 14168 14169 notePreMod(O, UO); 14170 Visit(UO->getSubExpr()); 14171 notePostMod(O, UO, UK_ModAsSideEffect); 14172 } 14173 14174 void VisitBinLOr(const BinaryOperator *BO) { 14175 // C++11 [expr.log.or]p2: 14176 // If the second expression is evaluated, every value computation and 14177 // side effect associated with the first expression is sequenced before 14178 // every value computation and side effect associated with the 14179 // second expression. 14180 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14181 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14182 SequenceTree::Seq OldRegion = Region; 14183 14184 EvaluationTracker Eval(*this); 14185 { 14186 SequencedSubexpression Sequenced(*this); 14187 Region = LHSRegion; 14188 Visit(BO->getLHS()); 14189 } 14190 14191 // C++11 [expr.log.or]p1: 14192 // [...] the second operand is not evaluated if the first operand 14193 // evaluates to true. 14194 bool EvalResult = false; 14195 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14196 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14197 if (ShouldVisitRHS) { 14198 Region = RHSRegion; 14199 Visit(BO->getRHS()); 14200 } 14201 14202 Region = OldRegion; 14203 Tree.merge(LHSRegion); 14204 Tree.merge(RHSRegion); 14205 } 14206 14207 void VisitBinLAnd(const BinaryOperator *BO) { 14208 // C++11 [expr.log.and]p2: 14209 // If the second expression is evaluated, every value computation and 14210 // side effect associated with the first expression is sequenced before 14211 // every value computation and side effect associated with the 14212 // second expression. 14213 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14214 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14215 SequenceTree::Seq OldRegion = Region; 14216 14217 EvaluationTracker Eval(*this); 14218 { 14219 SequencedSubexpression Sequenced(*this); 14220 Region = LHSRegion; 14221 Visit(BO->getLHS()); 14222 } 14223 14224 // C++11 [expr.log.and]p1: 14225 // [...] the second operand is not evaluated if the first operand is false. 14226 bool EvalResult = false; 14227 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14228 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14229 if (ShouldVisitRHS) { 14230 Region = RHSRegion; 14231 Visit(BO->getRHS()); 14232 } 14233 14234 Region = OldRegion; 14235 Tree.merge(LHSRegion); 14236 Tree.merge(RHSRegion); 14237 } 14238 14239 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14240 // C++11 [expr.cond]p1: 14241 // [...] Every value computation and side effect associated with the first 14242 // expression is sequenced before every value computation and side effect 14243 // associated with the second or third expression. 14244 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14245 14246 // No sequencing is specified between the true and false expression. 14247 // However since exactly one of both is going to be evaluated we can 14248 // consider them to be sequenced. This is needed to avoid warning on 14249 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14250 // both the true and false expressions because we can't evaluate x. 14251 // This will still allow us to detect an expression like (pre C++17) 14252 // "(x ? y += 1 : y += 2) = y". 14253 // 14254 // We don't wrap the visitation of the true and false expression with 14255 // SequencedSubexpression because we don't want to downgrade modifications 14256 // as side effect in the true and false expressions after the visition 14257 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14258 // not warn between the two "y++", but we should warn between the "y++" 14259 // and the "y". 14260 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14261 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14262 SequenceTree::Seq OldRegion = Region; 14263 14264 EvaluationTracker Eval(*this); 14265 { 14266 SequencedSubexpression Sequenced(*this); 14267 Region = ConditionRegion; 14268 Visit(CO->getCond()); 14269 } 14270 14271 // C++11 [expr.cond]p1: 14272 // [...] The first expression is contextually converted to bool (Clause 4). 14273 // It is evaluated and if it is true, the result of the conditional 14274 // expression is the value of the second expression, otherwise that of the 14275 // third expression. Only one of the second and third expressions is 14276 // evaluated. [...] 14277 bool EvalResult = false; 14278 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14279 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14280 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14281 if (ShouldVisitTrueExpr) { 14282 Region = TrueRegion; 14283 Visit(CO->getTrueExpr()); 14284 } 14285 if (ShouldVisitFalseExpr) { 14286 Region = FalseRegion; 14287 Visit(CO->getFalseExpr()); 14288 } 14289 14290 Region = OldRegion; 14291 Tree.merge(ConditionRegion); 14292 Tree.merge(TrueRegion); 14293 Tree.merge(FalseRegion); 14294 } 14295 14296 void VisitCallExpr(const CallExpr *CE) { 14297 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14298 14299 if (CE->isUnevaluatedBuiltinCall(Context)) 14300 return; 14301 14302 // C++11 [intro.execution]p15: 14303 // When calling a function [...], every value computation and side effect 14304 // associated with any argument expression, or with the postfix expression 14305 // designating the called function, is sequenced before execution of every 14306 // expression or statement in the body of the function [and thus before 14307 // the value computation of its result]. 14308 SequencedSubexpression Sequenced(*this); 14309 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14310 // C++17 [expr.call]p5 14311 // The postfix-expression is sequenced before each expression in the 14312 // expression-list and any default argument. [...] 14313 SequenceTree::Seq CalleeRegion; 14314 SequenceTree::Seq OtherRegion; 14315 if (SemaRef.getLangOpts().CPlusPlus17) { 14316 CalleeRegion = Tree.allocate(Region); 14317 OtherRegion = Tree.allocate(Region); 14318 } else { 14319 CalleeRegion = Region; 14320 OtherRegion = Region; 14321 } 14322 SequenceTree::Seq OldRegion = Region; 14323 14324 // Visit the callee expression first. 14325 Region = CalleeRegion; 14326 if (SemaRef.getLangOpts().CPlusPlus17) { 14327 SequencedSubexpression Sequenced(*this); 14328 Visit(CE->getCallee()); 14329 } else { 14330 Visit(CE->getCallee()); 14331 } 14332 14333 // Then visit the argument expressions. 14334 Region = OtherRegion; 14335 for (const Expr *Argument : CE->arguments()) 14336 Visit(Argument); 14337 14338 Region = OldRegion; 14339 if (SemaRef.getLangOpts().CPlusPlus17) { 14340 Tree.merge(CalleeRegion); 14341 Tree.merge(OtherRegion); 14342 } 14343 }); 14344 } 14345 14346 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14347 // C++17 [over.match.oper]p2: 14348 // [...] the operator notation is first transformed to the equivalent 14349 // function-call notation as summarized in Table 12 (where @ denotes one 14350 // of the operators covered in the specified subclause). However, the 14351 // operands are sequenced in the order prescribed for the built-in 14352 // operator (Clause 8). 14353 // 14354 // From the above only overloaded binary operators and overloaded call 14355 // operators have sequencing rules in C++17 that we need to handle 14356 // separately. 14357 if (!SemaRef.getLangOpts().CPlusPlus17 || 14358 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14359 return VisitCallExpr(CXXOCE); 14360 14361 enum { 14362 NoSequencing, 14363 LHSBeforeRHS, 14364 RHSBeforeLHS, 14365 LHSBeforeRest 14366 } SequencingKind; 14367 switch (CXXOCE->getOperator()) { 14368 case OO_Equal: 14369 case OO_PlusEqual: 14370 case OO_MinusEqual: 14371 case OO_StarEqual: 14372 case OO_SlashEqual: 14373 case OO_PercentEqual: 14374 case OO_CaretEqual: 14375 case OO_AmpEqual: 14376 case OO_PipeEqual: 14377 case OO_LessLessEqual: 14378 case OO_GreaterGreaterEqual: 14379 SequencingKind = RHSBeforeLHS; 14380 break; 14381 14382 case OO_LessLess: 14383 case OO_GreaterGreater: 14384 case OO_AmpAmp: 14385 case OO_PipePipe: 14386 case OO_Comma: 14387 case OO_ArrowStar: 14388 case OO_Subscript: 14389 SequencingKind = LHSBeforeRHS; 14390 break; 14391 14392 case OO_Call: 14393 SequencingKind = LHSBeforeRest; 14394 break; 14395 14396 default: 14397 SequencingKind = NoSequencing; 14398 break; 14399 } 14400 14401 if (SequencingKind == NoSequencing) 14402 return VisitCallExpr(CXXOCE); 14403 14404 // This is a call, so all subexpressions are sequenced before the result. 14405 SequencedSubexpression Sequenced(*this); 14406 14407 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14408 assert(SemaRef.getLangOpts().CPlusPlus17 && 14409 "Should only get there with C++17 and above!"); 14410 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14411 "Should only get there with an overloaded binary operator" 14412 " or an overloaded call operator!"); 14413 14414 if (SequencingKind == LHSBeforeRest) { 14415 assert(CXXOCE->getOperator() == OO_Call && 14416 "We should only have an overloaded call operator here!"); 14417 14418 // This is very similar to VisitCallExpr, except that we only have the 14419 // C++17 case. The postfix-expression is the first argument of the 14420 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14421 // are in the following arguments. 14422 // 14423 // Note that we intentionally do not visit the callee expression since 14424 // it is just a decayed reference to a function. 14425 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14426 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14427 SequenceTree::Seq OldRegion = Region; 14428 14429 assert(CXXOCE->getNumArgs() >= 1 && 14430 "An overloaded call operator must have at least one argument" 14431 " for the postfix-expression!"); 14432 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14433 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14434 CXXOCE->getNumArgs() - 1); 14435 14436 // Visit the postfix-expression first. 14437 { 14438 Region = PostfixExprRegion; 14439 SequencedSubexpression Sequenced(*this); 14440 Visit(PostfixExpr); 14441 } 14442 14443 // Then visit the argument expressions. 14444 Region = ArgsRegion; 14445 for (const Expr *Arg : Args) 14446 Visit(Arg); 14447 14448 Region = OldRegion; 14449 Tree.merge(PostfixExprRegion); 14450 Tree.merge(ArgsRegion); 14451 } else { 14452 assert(CXXOCE->getNumArgs() == 2 && 14453 "Should only have two arguments here!"); 14454 assert((SequencingKind == LHSBeforeRHS || 14455 SequencingKind == RHSBeforeLHS) && 14456 "Unexpected sequencing kind!"); 14457 14458 // We do not visit the callee expression since it is just a decayed 14459 // reference to a function. 14460 const Expr *E1 = CXXOCE->getArg(0); 14461 const Expr *E2 = CXXOCE->getArg(1); 14462 if (SequencingKind == RHSBeforeLHS) 14463 std::swap(E1, E2); 14464 14465 return VisitSequencedExpressions(E1, E2); 14466 } 14467 }); 14468 } 14469 14470 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14471 // This is a call, so all subexpressions are sequenced before the result. 14472 SequencedSubexpression Sequenced(*this); 14473 14474 if (!CCE->isListInitialization()) 14475 return VisitExpr(CCE); 14476 14477 // In C++11, list initializations are sequenced. 14478 SmallVector<SequenceTree::Seq, 32> Elts; 14479 SequenceTree::Seq Parent = Region; 14480 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14481 E = CCE->arg_end(); 14482 I != E; ++I) { 14483 Region = Tree.allocate(Parent); 14484 Elts.push_back(Region); 14485 Visit(*I); 14486 } 14487 14488 // Forget that the initializers are sequenced. 14489 Region = Parent; 14490 for (unsigned I = 0; I < Elts.size(); ++I) 14491 Tree.merge(Elts[I]); 14492 } 14493 14494 void VisitInitListExpr(const InitListExpr *ILE) { 14495 if (!SemaRef.getLangOpts().CPlusPlus11) 14496 return VisitExpr(ILE); 14497 14498 // In C++11, list initializations are sequenced. 14499 SmallVector<SequenceTree::Seq, 32> Elts; 14500 SequenceTree::Seq Parent = Region; 14501 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14502 const Expr *E = ILE->getInit(I); 14503 if (!E) 14504 continue; 14505 Region = Tree.allocate(Parent); 14506 Elts.push_back(Region); 14507 Visit(E); 14508 } 14509 14510 // Forget that the initializers are sequenced. 14511 Region = Parent; 14512 for (unsigned I = 0; I < Elts.size(); ++I) 14513 Tree.merge(Elts[I]); 14514 } 14515 }; 14516 14517 } // namespace 14518 14519 void Sema::CheckUnsequencedOperations(const Expr *E) { 14520 SmallVector<const Expr *, 8> WorkList; 14521 WorkList.push_back(E); 14522 while (!WorkList.empty()) { 14523 const Expr *Item = WorkList.pop_back_val(); 14524 SequenceChecker(*this, Item, WorkList); 14525 } 14526 } 14527 14528 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14529 bool IsConstexpr) { 14530 llvm::SaveAndRestore<bool> ConstantContext( 14531 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14532 CheckImplicitConversions(E, CheckLoc); 14533 if (!E->isInstantiationDependent()) 14534 CheckUnsequencedOperations(E); 14535 if (!IsConstexpr && !E->isValueDependent()) 14536 CheckForIntOverflow(E); 14537 DiagnoseMisalignedMembers(); 14538 } 14539 14540 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14541 FieldDecl *BitField, 14542 Expr *Init) { 14543 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14544 } 14545 14546 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14547 SourceLocation Loc) { 14548 if (!PType->isVariablyModifiedType()) 14549 return; 14550 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14551 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14552 return; 14553 } 14554 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14555 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14556 return; 14557 } 14558 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14559 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14560 return; 14561 } 14562 14563 const ArrayType *AT = S.Context.getAsArrayType(PType); 14564 if (!AT) 14565 return; 14566 14567 if (AT->getSizeModifier() != ArrayType::Star) { 14568 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14569 return; 14570 } 14571 14572 S.Diag(Loc, diag::err_array_star_in_function_definition); 14573 } 14574 14575 /// CheckParmsForFunctionDef - Check that the parameters of the given 14576 /// function are appropriate for the definition of a function. This 14577 /// takes care of any checks that cannot be performed on the 14578 /// declaration itself, e.g., that the types of each of the function 14579 /// parameters are complete. 14580 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14581 bool CheckParameterNames) { 14582 bool HasInvalidParm = false; 14583 for (ParmVarDecl *Param : Parameters) { 14584 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14585 // function declarator that is part of a function definition of 14586 // that function shall not have incomplete type. 14587 // 14588 // This is also C++ [dcl.fct]p6. 14589 if (!Param->isInvalidDecl() && 14590 RequireCompleteType(Param->getLocation(), Param->getType(), 14591 diag::err_typecheck_decl_incomplete_type)) { 14592 Param->setInvalidDecl(); 14593 HasInvalidParm = true; 14594 } 14595 14596 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14597 // declaration of each parameter shall include an identifier. 14598 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14599 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14600 // Diagnose this as an extension in C17 and earlier. 14601 if (!getLangOpts().C2x) 14602 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14603 } 14604 14605 // C99 6.7.5.3p12: 14606 // If the function declarator is not part of a definition of that 14607 // function, parameters may have incomplete type and may use the [*] 14608 // notation in their sequences of declarator specifiers to specify 14609 // variable length array types. 14610 QualType PType = Param->getOriginalType(); 14611 // FIXME: This diagnostic should point the '[*]' if source-location 14612 // information is added for it. 14613 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14614 14615 // If the parameter is a c++ class type and it has to be destructed in the 14616 // callee function, declare the destructor so that it can be called by the 14617 // callee function. Do not perform any direct access check on the dtor here. 14618 if (!Param->isInvalidDecl()) { 14619 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14620 if (!ClassDecl->isInvalidDecl() && 14621 !ClassDecl->hasIrrelevantDestructor() && 14622 !ClassDecl->isDependentContext() && 14623 ClassDecl->isParamDestroyedInCallee()) { 14624 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14625 MarkFunctionReferenced(Param->getLocation(), Destructor); 14626 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14627 } 14628 } 14629 } 14630 14631 // Parameters with the pass_object_size attribute only need to be marked 14632 // constant at function definitions. Because we lack information about 14633 // whether we're on a declaration or definition when we're instantiating the 14634 // attribute, we need to check for constness here. 14635 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14636 if (!Param->getType().isConstQualified()) 14637 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14638 << Attr->getSpelling() << 1; 14639 14640 // Check for parameter names shadowing fields from the class. 14641 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14642 // The owning context for the parameter should be the function, but we 14643 // want to see if this function's declaration context is a record. 14644 DeclContext *DC = Param->getDeclContext(); 14645 if (DC && DC->isFunctionOrMethod()) { 14646 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14647 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14648 RD, /*DeclIsField*/ false); 14649 } 14650 } 14651 } 14652 14653 return HasInvalidParm; 14654 } 14655 14656 Optional<std::pair<CharUnits, CharUnits>> 14657 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14658 14659 /// Compute the alignment and offset of the base class object given the 14660 /// derived-to-base cast expression and the alignment and offset of the derived 14661 /// class object. 14662 static std::pair<CharUnits, CharUnits> 14663 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14664 CharUnits BaseAlignment, CharUnits Offset, 14665 ASTContext &Ctx) { 14666 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14667 ++PathI) { 14668 const CXXBaseSpecifier *Base = *PathI; 14669 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14670 if (Base->isVirtual()) { 14671 // The complete object may have a lower alignment than the non-virtual 14672 // alignment of the base, in which case the base may be misaligned. Choose 14673 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14674 // conservative lower bound of the complete object alignment. 14675 CharUnits NonVirtualAlignment = 14676 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14677 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14678 Offset = CharUnits::Zero(); 14679 } else { 14680 const ASTRecordLayout &RL = 14681 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14682 Offset += RL.getBaseClassOffset(BaseDecl); 14683 } 14684 DerivedType = Base->getType(); 14685 } 14686 14687 return std::make_pair(BaseAlignment, Offset); 14688 } 14689 14690 /// Compute the alignment and offset of a binary additive operator. 14691 static Optional<std::pair<CharUnits, CharUnits>> 14692 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14693 bool IsSub, ASTContext &Ctx) { 14694 QualType PointeeType = PtrE->getType()->getPointeeType(); 14695 14696 if (!PointeeType->isConstantSizeType()) 14697 return llvm::None; 14698 14699 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14700 14701 if (!P) 14702 return llvm::None; 14703 14704 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14705 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14706 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14707 if (IsSub) 14708 Offset = -Offset; 14709 return std::make_pair(P->first, P->second + Offset); 14710 } 14711 14712 // If the integer expression isn't a constant expression, compute the lower 14713 // bound of the alignment using the alignment and offset of the pointer 14714 // expression and the element size. 14715 return std::make_pair( 14716 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14717 CharUnits::Zero()); 14718 } 14719 14720 /// This helper function takes an lvalue expression and returns the alignment of 14721 /// a VarDecl and a constant offset from the VarDecl. 14722 Optional<std::pair<CharUnits, CharUnits>> 14723 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14724 E = E->IgnoreParens(); 14725 switch (E->getStmtClass()) { 14726 default: 14727 break; 14728 case Stmt::CStyleCastExprClass: 14729 case Stmt::CXXStaticCastExprClass: 14730 case Stmt::ImplicitCastExprClass: { 14731 auto *CE = cast<CastExpr>(E); 14732 const Expr *From = CE->getSubExpr(); 14733 switch (CE->getCastKind()) { 14734 default: 14735 break; 14736 case CK_NoOp: 14737 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14738 case CK_UncheckedDerivedToBase: 14739 case CK_DerivedToBase: { 14740 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14741 if (!P) 14742 break; 14743 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14744 P->second, Ctx); 14745 } 14746 } 14747 break; 14748 } 14749 case Stmt::ArraySubscriptExprClass: { 14750 auto *ASE = cast<ArraySubscriptExpr>(E); 14751 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14752 false, Ctx); 14753 } 14754 case Stmt::DeclRefExprClass: { 14755 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14756 // FIXME: If VD is captured by copy or is an escaping __block variable, 14757 // use the alignment of VD's type. 14758 if (!VD->getType()->isReferenceType()) 14759 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14760 if (VD->hasInit()) 14761 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14762 } 14763 break; 14764 } 14765 case Stmt::MemberExprClass: { 14766 auto *ME = cast<MemberExpr>(E); 14767 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14768 if (!FD || FD->getType()->isReferenceType() || 14769 FD->getParent()->isInvalidDecl()) 14770 break; 14771 Optional<std::pair<CharUnits, CharUnits>> P; 14772 if (ME->isArrow()) 14773 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14774 else 14775 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14776 if (!P) 14777 break; 14778 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14779 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14780 return std::make_pair(P->first, 14781 P->second + CharUnits::fromQuantity(Offset)); 14782 } 14783 case Stmt::UnaryOperatorClass: { 14784 auto *UO = cast<UnaryOperator>(E); 14785 switch (UO->getOpcode()) { 14786 default: 14787 break; 14788 case UO_Deref: 14789 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14790 } 14791 break; 14792 } 14793 case Stmt::BinaryOperatorClass: { 14794 auto *BO = cast<BinaryOperator>(E); 14795 auto Opcode = BO->getOpcode(); 14796 switch (Opcode) { 14797 default: 14798 break; 14799 case BO_Comma: 14800 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14801 } 14802 break; 14803 } 14804 } 14805 return llvm::None; 14806 } 14807 14808 /// This helper function takes a pointer expression and returns the alignment of 14809 /// a VarDecl and a constant offset from the VarDecl. 14810 Optional<std::pair<CharUnits, CharUnits>> 14811 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14812 E = E->IgnoreParens(); 14813 switch (E->getStmtClass()) { 14814 default: 14815 break; 14816 case Stmt::CStyleCastExprClass: 14817 case Stmt::CXXStaticCastExprClass: 14818 case Stmt::ImplicitCastExprClass: { 14819 auto *CE = cast<CastExpr>(E); 14820 const Expr *From = CE->getSubExpr(); 14821 switch (CE->getCastKind()) { 14822 default: 14823 break; 14824 case CK_NoOp: 14825 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14826 case CK_ArrayToPointerDecay: 14827 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14828 case CK_UncheckedDerivedToBase: 14829 case CK_DerivedToBase: { 14830 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14831 if (!P) 14832 break; 14833 return getDerivedToBaseAlignmentAndOffset( 14834 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14835 } 14836 } 14837 break; 14838 } 14839 case Stmt::CXXThisExprClass: { 14840 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14841 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14842 return std::make_pair(Alignment, CharUnits::Zero()); 14843 } 14844 case Stmt::UnaryOperatorClass: { 14845 auto *UO = cast<UnaryOperator>(E); 14846 if (UO->getOpcode() == UO_AddrOf) 14847 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14848 break; 14849 } 14850 case Stmt::BinaryOperatorClass: { 14851 auto *BO = cast<BinaryOperator>(E); 14852 auto Opcode = BO->getOpcode(); 14853 switch (Opcode) { 14854 default: 14855 break; 14856 case BO_Add: 14857 case BO_Sub: { 14858 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14859 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14860 std::swap(LHS, RHS); 14861 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14862 Ctx); 14863 } 14864 case BO_Comma: 14865 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14866 } 14867 break; 14868 } 14869 } 14870 return llvm::None; 14871 } 14872 14873 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14874 // See if we can compute the alignment of a VarDecl and an offset from it. 14875 Optional<std::pair<CharUnits, CharUnits>> P = 14876 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14877 14878 if (P) 14879 return P->first.alignmentAtOffset(P->second); 14880 14881 // If that failed, return the type's alignment. 14882 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14883 } 14884 14885 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14886 /// pointer cast increases the alignment requirements. 14887 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14888 // This is actually a lot of work to potentially be doing on every 14889 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14890 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14891 return; 14892 14893 // Ignore dependent types. 14894 if (T->isDependentType() || Op->getType()->isDependentType()) 14895 return; 14896 14897 // Require that the destination be a pointer type. 14898 const PointerType *DestPtr = T->getAs<PointerType>(); 14899 if (!DestPtr) return; 14900 14901 // If the destination has alignment 1, we're done. 14902 QualType DestPointee = DestPtr->getPointeeType(); 14903 if (DestPointee->isIncompleteType()) return; 14904 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14905 if (DestAlign.isOne()) return; 14906 14907 // Require that the source be a pointer type. 14908 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14909 if (!SrcPtr) return; 14910 QualType SrcPointee = SrcPtr->getPointeeType(); 14911 14912 // Explicitly allow casts from cv void*. We already implicitly 14913 // allowed casts to cv void*, since they have alignment 1. 14914 // Also allow casts involving incomplete types, which implicitly 14915 // includes 'void'. 14916 if (SrcPointee->isIncompleteType()) return; 14917 14918 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14919 14920 if (SrcAlign >= DestAlign) return; 14921 14922 Diag(TRange.getBegin(), diag::warn_cast_align) 14923 << Op->getType() << T 14924 << static_cast<unsigned>(SrcAlign.getQuantity()) 14925 << static_cast<unsigned>(DestAlign.getQuantity()) 14926 << TRange << Op->getSourceRange(); 14927 } 14928 14929 /// Check whether this array fits the idiom of a size-one tail padded 14930 /// array member of a struct. 14931 /// 14932 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14933 /// commonly used to emulate flexible arrays in C89 code. 14934 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14935 const NamedDecl *ND) { 14936 if (Size != 1 || !ND) return false; 14937 14938 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14939 if (!FD) return false; 14940 14941 // Don't consider sizes resulting from macro expansions or template argument 14942 // substitution to form C89 tail-padded arrays. 14943 14944 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14945 while (TInfo) { 14946 TypeLoc TL = TInfo->getTypeLoc(); 14947 // Look through typedefs. 14948 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14949 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14950 TInfo = TDL->getTypeSourceInfo(); 14951 continue; 14952 } 14953 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14954 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14955 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14956 return false; 14957 } 14958 break; 14959 } 14960 14961 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 14962 if (!RD) return false; 14963 if (RD->isUnion()) return false; 14964 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 14965 if (!CRD->isStandardLayout()) return false; 14966 } 14967 14968 // See if this is the last field decl in the record. 14969 const Decl *D = FD; 14970 while ((D = D->getNextDeclInContext())) 14971 if (isa<FieldDecl>(D)) 14972 return false; 14973 return true; 14974 } 14975 14976 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 14977 const ArraySubscriptExpr *ASE, 14978 bool AllowOnePastEnd, bool IndexNegated) { 14979 // Already diagnosed by the constant evaluator. 14980 if (isConstantEvaluated()) 14981 return; 14982 14983 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 14984 if (IndexExpr->isValueDependent()) 14985 return; 14986 14987 const Type *EffectiveType = 14988 BaseExpr->getType()->getPointeeOrArrayElementType(); 14989 BaseExpr = BaseExpr->IgnoreParenCasts(); 14990 const ConstantArrayType *ArrayTy = 14991 Context.getAsConstantArrayType(BaseExpr->getType()); 14992 14993 const Type *BaseType = 14994 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 14995 bool IsUnboundedArray = (BaseType == nullptr); 14996 if (EffectiveType->isDependentType() || 14997 (!IsUnboundedArray && BaseType->isDependentType())) 14998 return; 14999 15000 Expr::EvalResult Result; 15001 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 15002 return; 15003 15004 llvm::APSInt index = Result.Val.getInt(); 15005 if (IndexNegated) { 15006 index.setIsUnsigned(false); 15007 index = -index; 15008 } 15009 15010 const NamedDecl *ND = nullptr; 15011 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15012 ND = DRE->getDecl(); 15013 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 15014 ND = ME->getMemberDecl(); 15015 15016 if (IsUnboundedArray) { 15017 if (index.isUnsigned() || !index.isNegative()) { 15018 const auto &ASTC = getASTContext(); 15019 unsigned AddrBits = 15020 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 15021 EffectiveType->getCanonicalTypeInternal())); 15022 if (index.getBitWidth() < AddrBits) 15023 index = index.zext(AddrBits); 15024 Optional<CharUnits> ElemCharUnits = 15025 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 15026 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 15027 // pointer) bounds-checking isn't meaningful. 15028 if (!ElemCharUnits) 15029 return; 15030 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 15031 // If index has more active bits than address space, we already know 15032 // we have a bounds violation to warn about. Otherwise, compute 15033 // address of (index + 1)th element, and warn about bounds violation 15034 // only if that address exceeds address space. 15035 if (index.getActiveBits() <= AddrBits) { 15036 bool Overflow; 15037 llvm::APInt Product(index); 15038 Product += 1; 15039 Product = Product.umul_ov(ElemBytes, Overflow); 15040 if (!Overflow && Product.getActiveBits() <= AddrBits) 15041 return; 15042 } 15043 15044 // Need to compute max possible elements in address space, since that 15045 // is included in diag message. 15046 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 15047 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 15048 MaxElems += 1; 15049 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 15050 MaxElems = MaxElems.udiv(ElemBytes); 15051 15052 unsigned DiagID = 15053 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 15054 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 15055 15056 // Diag message shows element size in bits and in "bytes" (platform- 15057 // dependent CharUnits) 15058 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15059 PDiag(DiagID) 15060 << toString(index, 10, true) << AddrBits 15061 << (unsigned)ASTC.toBits(*ElemCharUnits) 15062 << toString(ElemBytes, 10, false) 15063 << toString(MaxElems, 10, false) 15064 << (unsigned)MaxElems.getLimitedValue(~0U) 15065 << IndexExpr->getSourceRange()); 15066 15067 if (!ND) { 15068 // Try harder to find a NamedDecl to point at in the note. 15069 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15070 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15071 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15072 ND = DRE->getDecl(); 15073 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15074 ND = ME->getMemberDecl(); 15075 } 15076 15077 if (ND) 15078 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15079 PDiag(diag::note_array_declared_here) << ND); 15080 } 15081 return; 15082 } 15083 15084 if (index.isUnsigned() || !index.isNegative()) { 15085 // It is possible that the type of the base expression after 15086 // IgnoreParenCasts is incomplete, even though the type of the base 15087 // expression before IgnoreParenCasts is complete (see PR39746 for an 15088 // example). In this case we have no information about whether the array 15089 // access exceeds the array bounds. However we can still diagnose an array 15090 // access which precedes the array bounds. 15091 if (BaseType->isIncompleteType()) 15092 return; 15093 15094 llvm::APInt size = ArrayTy->getSize(); 15095 if (!size.isStrictlyPositive()) 15096 return; 15097 15098 if (BaseType != EffectiveType) { 15099 // Make sure we're comparing apples to apples when comparing index to size 15100 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 15101 uint64_t array_typesize = Context.getTypeSize(BaseType); 15102 // Handle ptrarith_typesize being zero, such as when casting to void* 15103 if (!ptrarith_typesize) ptrarith_typesize = 1; 15104 if (ptrarith_typesize != array_typesize) { 15105 // There's a cast to a different size type involved 15106 uint64_t ratio = array_typesize / ptrarith_typesize; 15107 // TODO: Be smarter about handling cases where array_typesize is not a 15108 // multiple of ptrarith_typesize 15109 if (ptrarith_typesize * ratio == array_typesize) 15110 size *= llvm::APInt(size.getBitWidth(), ratio); 15111 } 15112 } 15113 15114 if (size.getBitWidth() > index.getBitWidth()) 15115 index = index.zext(size.getBitWidth()); 15116 else if (size.getBitWidth() < index.getBitWidth()) 15117 size = size.zext(index.getBitWidth()); 15118 15119 // For array subscripting the index must be less than size, but for pointer 15120 // arithmetic also allow the index (offset) to be equal to size since 15121 // computing the next address after the end of the array is legal and 15122 // commonly done e.g. in C++ iterators and range-based for loops. 15123 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 15124 return; 15125 15126 // Also don't warn for arrays of size 1 which are members of some 15127 // structure. These are often used to approximate flexible arrays in C89 15128 // code. 15129 if (IsTailPaddedMemberArray(*this, size, ND)) 15130 return; 15131 15132 // Suppress the warning if the subscript expression (as identified by the 15133 // ']' location) and the index expression are both from macro expansions 15134 // within a system header. 15135 if (ASE) { 15136 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 15137 ASE->getRBracketLoc()); 15138 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 15139 SourceLocation IndexLoc = 15140 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 15141 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 15142 return; 15143 } 15144 } 15145 15146 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 15147 : diag::warn_ptr_arith_exceeds_bounds; 15148 15149 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15150 PDiag(DiagID) << toString(index, 10, true) 15151 << toString(size, 10, true) 15152 << (unsigned)size.getLimitedValue(~0U) 15153 << IndexExpr->getSourceRange()); 15154 } else { 15155 unsigned DiagID = diag::warn_array_index_precedes_bounds; 15156 if (!ASE) { 15157 DiagID = diag::warn_ptr_arith_precedes_bounds; 15158 if (index.isNegative()) index = -index; 15159 } 15160 15161 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15162 PDiag(DiagID) << toString(index, 10, true) 15163 << IndexExpr->getSourceRange()); 15164 } 15165 15166 if (!ND) { 15167 // Try harder to find a NamedDecl to point at in the note. 15168 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15169 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15170 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15171 ND = DRE->getDecl(); 15172 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15173 ND = ME->getMemberDecl(); 15174 } 15175 15176 if (ND) 15177 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15178 PDiag(diag::note_array_declared_here) << ND); 15179 } 15180 15181 void Sema::CheckArrayAccess(const Expr *expr) { 15182 int AllowOnePastEnd = 0; 15183 while (expr) { 15184 expr = expr->IgnoreParenImpCasts(); 15185 switch (expr->getStmtClass()) { 15186 case Stmt::ArraySubscriptExprClass: { 15187 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15188 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15189 AllowOnePastEnd > 0); 15190 expr = ASE->getBase(); 15191 break; 15192 } 15193 case Stmt::MemberExprClass: { 15194 expr = cast<MemberExpr>(expr)->getBase(); 15195 break; 15196 } 15197 case Stmt::OMPArraySectionExprClass: { 15198 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15199 if (ASE->getLowerBound()) 15200 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15201 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15202 return; 15203 } 15204 case Stmt::UnaryOperatorClass: { 15205 // Only unwrap the * and & unary operators 15206 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15207 expr = UO->getSubExpr(); 15208 switch (UO->getOpcode()) { 15209 case UO_AddrOf: 15210 AllowOnePastEnd++; 15211 break; 15212 case UO_Deref: 15213 AllowOnePastEnd--; 15214 break; 15215 default: 15216 return; 15217 } 15218 break; 15219 } 15220 case Stmt::ConditionalOperatorClass: { 15221 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15222 if (const Expr *lhs = cond->getLHS()) 15223 CheckArrayAccess(lhs); 15224 if (const Expr *rhs = cond->getRHS()) 15225 CheckArrayAccess(rhs); 15226 return; 15227 } 15228 case Stmt::CXXOperatorCallExprClass: { 15229 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15230 for (const auto *Arg : OCE->arguments()) 15231 CheckArrayAccess(Arg); 15232 return; 15233 } 15234 default: 15235 return; 15236 } 15237 } 15238 } 15239 15240 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15241 15242 namespace { 15243 15244 struct RetainCycleOwner { 15245 VarDecl *Variable = nullptr; 15246 SourceRange Range; 15247 SourceLocation Loc; 15248 bool Indirect = false; 15249 15250 RetainCycleOwner() = default; 15251 15252 void setLocsFrom(Expr *e) { 15253 Loc = e->getExprLoc(); 15254 Range = e->getSourceRange(); 15255 } 15256 }; 15257 15258 } // namespace 15259 15260 /// Consider whether capturing the given variable can possibly lead to 15261 /// a retain cycle. 15262 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15263 // In ARC, it's captured strongly iff the variable has __strong 15264 // lifetime. In MRR, it's captured strongly if the variable is 15265 // __block and has an appropriate type. 15266 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15267 return false; 15268 15269 owner.Variable = var; 15270 if (ref) 15271 owner.setLocsFrom(ref); 15272 return true; 15273 } 15274 15275 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15276 while (true) { 15277 e = e->IgnoreParens(); 15278 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15279 switch (cast->getCastKind()) { 15280 case CK_BitCast: 15281 case CK_LValueBitCast: 15282 case CK_LValueToRValue: 15283 case CK_ARCReclaimReturnedObject: 15284 e = cast->getSubExpr(); 15285 continue; 15286 15287 default: 15288 return false; 15289 } 15290 } 15291 15292 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15293 ObjCIvarDecl *ivar = ref->getDecl(); 15294 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15295 return false; 15296 15297 // Try to find a retain cycle in the base. 15298 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15299 return false; 15300 15301 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15302 owner.Indirect = true; 15303 return true; 15304 } 15305 15306 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15307 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15308 if (!var) return false; 15309 return considerVariable(var, ref, owner); 15310 } 15311 15312 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15313 if (member->isArrow()) return false; 15314 15315 // Don't count this as an indirect ownership. 15316 e = member->getBase(); 15317 continue; 15318 } 15319 15320 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15321 // Only pay attention to pseudo-objects on property references. 15322 ObjCPropertyRefExpr *pre 15323 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15324 ->IgnoreParens()); 15325 if (!pre) return false; 15326 if (pre->isImplicitProperty()) return false; 15327 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15328 if (!property->isRetaining() && 15329 !(property->getPropertyIvarDecl() && 15330 property->getPropertyIvarDecl()->getType() 15331 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15332 return false; 15333 15334 owner.Indirect = true; 15335 if (pre->isSuperReceiver()) { 15336 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15337 if (!owner.Variable) 15338 return false; 15339 owner.Loc = pre->getLocation(); 15340 owner.Range = pre->getSourceRange(); 15341 return true; 15342 } 15343 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15344 ->getSourceExpr()); 15345 continue; 15346 } 15347 15348 // Array ivars? 15349 15350 return false; 15351 } 15352 } 15353 15354 namespace { 15355 15356 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15357 ASTContext &Context; 15358 VarDecl *Variable; 15359 Expr *Capturer = nullptr; 15360 bool VarWillBeReased = false; 15361 15362 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15363 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15364 Context(Context), Variable(variable) {} 15365 15366 void VisitDeclRefExpr(DeclRefExpr *ref) { 15367 if (ref->getDecl() == Variable && !Capturer) 15368 Capturer = ref; 15369 } 15370 15371 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15372 if (Capturer) return; 15373 Visit(ref->getBase()); 15374 if (Capturer && ref->isFreeIvar()) 15375 Capturer = ref; 15376 } 15377 15378 void VisitBlockExpr(BlockExpr *block) { 15379 // Look inside nested blocks 15380 if (block->getBlockDecl()->capturesVariable(Variable)) 15381 Visit(block->getBlockDecl()->getBody()); 15382 } 15383 15384 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15385 if (Capturer) return; 15386 if (OVE->getSourceExpr()) 15387 Visit(OVE->getSourceExpr()); 15388 } 15389 15390 void VisitBinaryOperator(BinaryOperator *BinOp) { 15391 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15392 return; 15393 Expr *LHS = BinOp->getLHS(); 15394 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15395 if (DRE->getDecl() != Variable) 15396 return; 15397 if (Expr *RHS = BinOp->getRHS()) { 15398 RHS = RHS->IgnoreParenCasts(); 15399 Optional<llvm::APSInt> Value; 15400 VarWillBeReased = 15401 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15402 *Value == 0); 15403 } 15404 } 15405 } 15406 }; 15407 15408 } // namespace 15409 15410 /// Check whether the given argument is a block which captures a 15411 /// variable. 15412 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15413 assert(owner.Variable && owner.Loc.isValid()); 15414 15415 e = e->IgnoreParenCasts(); 15416 15417 // Look through [^{...} copy] and Block_copy(^{...}). 15418 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15419 Selector Cmd = ME->getSelector(); 15420 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15421 e = ME->getInstanceReceiver(); 15422 if (!e) 15423 return nullptr; 15424 e = e->IgnoreParenCasts(); 15425 } 15426 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15427 if (CE->getNumArgs() == 1) { 15428 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15429 if (Fn) { 15430 const IdentifierInfo *FnI = Fn->getIdentifier(); 15431 if (FnI && FnI->isStr("_Block_copy")) { 15432 e = CE->getArg(0)->IgnoreParenCasts(); 15433 } 15434 } 15435 } 15436 } 15437 15438 BlockExpr *block = dyn_cast<BlockExpr>(e); 15439 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15440 return nullptr; 15441 15442 FindCaptureVisitor visitor(S.Context, owner.Variable); 15443 visitor.Visit(block->getBlockDecl()->getBody()); 15444 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15445 } 15446 15447 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15448 RetainCycleOwner &owner) { 15449 assert(capturer); 15450 assert(owner.Variable && owner.Loc.isValid()); 15451 15452 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15453 << owner.Variable << capturer->getSourceRange(); 15454 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15455 << owner.Indirect << owner.Range; 15456 } 15457 15458 /// Check for a keyword selector that starts with the word 'add' or 15459 /// 'set'. 15460 static bool isSetterLikeSelector(Selector sel) { 15461 if (sel.isUnarySelector()) return false; 15462 15463 StringRef str = sel.getNameForSlot(0); 15464 while (!str.empty() && str.front() == '_') str = str.substr(1); 15465 if (str.startswith("set")) 15466 str = str.substr(3); 15467 else if (str.startswith("add")) { 15468 // Specially allow 'addOperationWithBlock:'. 15469 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15470 return false; 15471 str = str.substr(3); 15472 } 15473 else 15474 return false; 15475 15476 if (str.empty()) return true; 15477 return !isLowercase(str.front()); 15478 } 15479 15480 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15481 ObjCMessageExpr *Message) { 15482 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15483 Message->getReceiverInterface(), 15484 NSAPI::ClassId_NSMutableArray); 15485 if (!IsMutableArray) { 15486 return None; 15487 } 15488 15489 Selector Sel = Message->getSelector(); 15490 15491 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15492 S.NSAPIObj->getNSArrayMethodKind(Sel); 15493 if (!MKOpt) { 15494 return None; 15495 } 15496 15497 NSAPI::NSArrayMethodKind MK = *MKOpt; 15498 15499 switch (MK) { 15500 case NSAPI::NSMutableArr_addObject: 15501 case NSAPI::NSMutableArr_insertObjectAtIndex: 15502 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15503 return 0; 15504 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15505 return 1; 15506 15507 default: 15508 return None; 15509 } 15510 15511 return None; 15512 } 15513 15514 static 15515 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15516 ObjCMessageExpr *Message) { 15517 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15518 Message->getReceiverInterface(), 15519 NSAPI::ClassId_NSMutableDictionary); 15520 if (!IsMutableDictionary) { 15521 return None; 15522 } 15523 15524 Selector Sel = Message->getSelector(); 15525 15526 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15527 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15528 if (!MKOpt) { 15529 return None; 15530 } 15531 15532 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15533 15534 switch (MK) { 15535 case NSAPI::NSMutableDict_setObjectForKey: 15536 case NSAPI::NSMutableDict_setValueForKey: 15537 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15538 return 0; 15539 15540 default: 15541 return None; 15542 } 15543 15544 return None; 15545 } 15546 15547 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15548 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15549 Message->getReceiverInterface(), 15550 NSAPI::ClassId_NSMutableSet); 15551 15552 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15553 Message->getReceiverInterface(), 15554 NSAPI::ClassId_NSMutableOrderedSet); 15555 if (!IsMutableSet && !IsMutableOrderedSet) { 15556 return None; 15557 } 15558 15559 Selector Sel = Message->getSelector(); 15560 15561 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15562 if (!MKOpt) { 15563 return None; 15564 } 15565 15566 NSAPI::NSSetMethodKind MK = *MKOpt; 15567 15568 switch (MK) { 15569 case NSAPI::NSMutableSet_addObject: 15570 case NSAPI::NSOrderedSet_setObjectAtIndex: 15571 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15572 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15573 return 0; 15574 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15575 return 1; 15576 } 15577 15578 return None; 15579 } 15580 15581 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15582 if (!Message->isInstanceMessage()) { 15583 return; 15584 } 15585 15586 Optional<int> ArgOpt; 15587 15588 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15589 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15590 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15591 return; 15592 } 15593 15594 int ArgIndex = *ArgOpt; 15595 15596 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15597 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15598 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15599 } 15600 15601 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15602 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15603 if (ArgRE->isObjCSelfExpr()) { 15604 Diag(Message->getSourceRange().getBegin(), 15605 diag::warn_objc_circular_container) 15606 << ArgRE->getDecl() << StringRef("'super'"); 15607 } 15608 } 15609 } else { 15610 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15611 15612 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15613 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15614 } 15615 15616 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15617 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15618 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15619 ValueDecl *Decl = ReceiverRE->getDecl(); 15620 Diag(Message->getSourceRange().getBegin(), 15621 diag::warn_objc_circular_container) 15622 << Decl << Decl; 15623 if (!ArgRE->isObjCSelfExpr()) { 15624 Diag(Decl->getLocation(), 15625 diag::note_objc_circular_container_declared_here) 15626 << Decl; 15627 } 15628 } 15629 } 15630 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15631 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15632 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15633 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15634 Diag(Message->getSourceRange().getBegin(), 15635 diag::warn_objc_circular_container) 15636 << Decl << Decl; 15637 Diag(Decl->getLocation(), 15638 diag::note_objc_circular_container_declared_here) 15639 << Decl; 15640 } 15641 } 15642 } 15643 } 15644 } 15645 15646 /// Check a message send to see if it's likely to cause a retain cycle. 15647 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15648 // Only check instance methods whose selector looks like a setter. 15649 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15650 return; 15651 15652 // Try to find a variable that the receiver is strongly owned by. 15653 RetainCycleOwner owner; 15654 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15655 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15656 return; 15657 } else { 15658 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15659 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15660 owner.Loc = msg->getSuperLoc(); 15661 owner.Range = msg->getSuperLoc(); 15662 } 15663 15664 // Check whether the receiver is captured by any of the arguments. 15665 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15666 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15667 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15668 // noescape blocks should not be retained by the method. 15669 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15670 continue; 15671 return diagnoseRetainCycle(*this, capturer, owner); 15672 } 15673 } 15674 } 15675 15676 /// Check a property assign to see if it's likely to cause a retain cycle. 15677 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15678 RetainCycleOwner owner; 15679 if (!findRetainCycleOwner(*this, receiver, owner)) 15680 return; 15681 15682 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15683 diagnoseRetainCycle(*this, capturer, owner); 15684 } 15685 15686 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15687 RetainCycleOwner Owner; 15688 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15689 return; 15690 15691 // Because we don't have an expression for the variable, we have to set the 15692 // location explicitly here. 15693 Owner.Loc = Var->getLocation(); 15694 Owner.Range = Var->getSourceRange(); 15695 15696 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15697 diagnoseRetainCycle(*this, Capturer, Owner); 15698 } 15699 15700 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15701 Expr *RHS, bool isProperty) { 15702 // Check if RHS is an Objective-C object literal, which also can get 15703 // immediately zapped in a weak reference. Note that we explicitly 15704 // allow ObjCStringLiterals, since those are designed to never really die. 15705 RHS = RHS->IgnoreParenImpCasts(); 15706 15707 // This enum needs to match with the 'select' in 15708 // warn_objc_arc_literal_assign (off-by-1). 15709 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15710 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15711 return false; 15712 15713 S.Diag(Loc, diag::warn_arc_literal_assign) 15714 << (unsigned) Kind 15715 << (isProperty ? 0 : 1) 15716 << RHS->getSourceRange(); 15717 15718 return true; 15719 } 15720 15721 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15722 Qualifiers::ObjCLifetime LT, 15723 Expr *RHS, bool isProperty) { 15724 // Strip off any implicit cast added to get to the one ARC-specific. 15725 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15726 if (cast->getCastKind() == CK_ARCConsumeObject) { 15727 S.Diag(Loc, diag::warn_arc_retained_assign) 15728 << (LT == Qualifiers::OCL_ExplicitNone) 15729 << (isProperty ? 0 : 1) 15730 << RHS->getSourceRange(); 15731 return true; 15732 } 15733 RHS = cast->getSubExpr(); 15734 } 15735 15736 if (LT == Qualifiers::OCL_Weak && 15737 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15738 return true; 15739 15740 return false; 15741 } 15742 15743 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15744 QualType LHS, Expr *RHS) { 15745 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15746 15747 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15748 return false; 15749 15750 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15751 return true; 15752 15753 return false; 15754 } 15755 15756 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15757 Expr *LHS, Expr *RHS) { 15758 QualType LHSType; 15759 // PropertyRef on LHS type need be directly obtained from 15760 // its declaration as it has a PseudoType. 15761 ObjCPropertyRefExpr *PRE 15762 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15763 if (PRE && !PRE->isImplicitProperty()) { 15764 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15765 if (PD) 15766 LHSType = PD->getType(); 15767 } 15768 15769 if (LHSType.isNull()) 15770 LHSType = LHS->getType(); 15771 15772 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15773 15774 if (LT == Qualifiers::OCL_Weak) { 15775 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15776 getCurFunction()->markSafeWeakUse(LHS); 15777 } 15778 15779 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15780 return; 15781 15782 // FIXME. Check for other life times. 15783 if (LT != Qualifiers::OCL_None) 15784 return; 15785 15786 if (PRE) { 15787 if (PRE->isImplicitProperty()) 15788 return; 15789 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15790 if (!PD) 15791 return; 15792 15793 unsigned Attributes = PD->getPropertyAttributes(); 15794 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15795 // when 'assign' attribute was not explicitly specified 15796 // by user, ignore it and rely on property type itself 15797 // for lifetime info. 15798 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15799 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15800 LHSType->isObjCRetainableType()) 15801 return; 15802 15803 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15804 if (cast->getCastKind() == CK_ARCConsumeObject) { 15805 Diag(Loc, diag::warn_arc_retained_property_assign) 15806 << RHS->getSourceRange(); 15807 return; 15808 } 15809 RHS = cast->getSubExpr(); 15810 } 15811 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15812 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15813 return; 15814 } 15815 } 15816 } 15817 15818 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15819 15820 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15821 SourceLocation StmtLoc, 15822 const NullStmt *Body) { 15823 // Do not warn if the body is a macro that expands to nothing, e.g: 15824 // 15825 // #define CALL(x) 15826 // if (condition) 15827 // CALL(0); 15828 if (Body->hasLeadingEmptyMacro()) 15829 return false; 15830 15831 // Get line numbers of statement and body. 15832 bool StmtLineInvalid; 15833 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15834 &StmtLineInvalid); 15835 if (StmtLineInvalid) 15836 return false; 15837 15838 bool BodyLineInvalid; 15839 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15840 &BodyLineInvalid); 15841 if (BodyLineInvalid) 15842 return false; 15843 15844 // Warn if null statement and body are on the same line. 15845 if (StmtLine != BodyLine) 15846 return false; 15847 15848 return true; 15849 } 15850 15851 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15852 const Stmt *Body, 15853 unsigned DiagID) { 15854 // Since this is a syntactic check, don't emit diagnostic for template 15855 // instantiations, this just adds noise. 15856 if (CurrentInstantiationScope) 15857 return; 15858 15859 // The body should be a null statement. 15860 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15861 if (!NBody) 15862 return; 15863 15864 // Do the usual checks. 15865 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15866 return; 15867 15868 Diag(NBody->getSemiLoc(), DiagID); 15869 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15870 } 15871 15872 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15873 const Stmt *PossibleBody) { 15874 assert(!CurrentInstantiationScope); // Ensured by caller 15875 15876 SourceLocation StmtLoc; 15877 const Stmt *Body; 15878 unsigned DiagID; 15879 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15880 StmtLoc = FS->getRParenLoc(); 15881 Body = FS->getBody(); 15882 DiagID = diag::warn_empty_for_body; 15883 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15884 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15885 Body = WS->getBody(); 15886 DiagID = diag::warn_empty_while_body; 15887 } else 15888 return; // Neither `for' nor `while'. 15889 15890 // The body should be a null statement. 15891 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15892 if (!NBody) 15893 return; 15894 15895 // Skip expensive checks if diagnostic is disabled. 15896 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15897 return; 15898 15899 // Do the usual checks. 15900 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15901 return; 15902 15903 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15904 // noise level low, emit diagnostics only if for/while is followed by a 15905 // CompoundStmt, e.g.: 15906 // for (int i = 0; i < n; i++); 15907 // { 15908 // a(i); 15909 // } 15910 // or if for/while is followed by a statement with more indentation 15911 // than for/while itself: 15912 // for (int i = 0; i < n; i++); 15913 // a(i); 15914 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15915 if (!ProbableTypo) { 15916 bool BodyColInvalid; 15917 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15918 PossibleBody->getBeginLoc(), &BodyColInvalid); 15919 if (BodyColInvalid) 15920 return; 15921 15922 bool StmtColInvalid; 15923 unsigned StmtCol = 15924 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15925 if (StmtColInvalid) 15926 return; 15927 15928 if (BodyCol > StmtCol) 15929 ProbableTypo = true; 15930 } 15931 15932 if (ProbableTypo) { 15933 Diag(NBody->getSemiLoc(), DiagID); 15934 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15935 } 15936 } 15937 15938 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15939 15940 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15941 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15942 SourceLocation OpLoc) { 15943 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15944 return; 15945 15946 if (inTemplateInstantiation()) 15947 return; 15948 15949 // Strip parens and casts away. 15950 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15951 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15952 15953 // Check for a call expression 15954 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15955 if (!CE || CE->getNumArgs() != 1) 15956 return; 15957 15958 // Check for a call to std::move 15959 if (!CE->isCallToStdMove()) 15960 return; 15961 15962 // Get argument from std::move 15963 RHSExpr = CE->getArg(0); 15964 15965 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 15966 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 15967 15968 // Two DeclRefExpr's, check that the decls are the same. 15969 if (LHSDeclRef && RHSDeclRef) { 15970 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 15971 return; 15972 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 15973 RHSDeclRef->getDecl()->getCanonicalDecl()) 15974 return; 15975 15976 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 15977 << LHSExpr->getSourceRange() 15978 << RHSExpr->getSourceRange(); 15979 return; 15980 } 15981 15982 // Member variables require a different approach to check for self moves. 15983 // MemberExpr's are the same if every nested MemberExpr refers to the same 15984 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 15985 // the base Expr's are CXXThisExpr's. 15986 const Expr *LHSBase = LHSExpr; 15987 const Expr *RHSBase = RHSExpr; 15988 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 15989 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 15990 if (!LHSME || !RHSME) 15991 return; 15992 15993 while (LHSME && RHSME) { 15994 if (LHSME->getMemberDecl()->getCanonicalDecl() != 15995 RHSME->getMemberDecl()->getCanonicalDecl()) 15996 return; 15997 15998 LHSBase = LHSME->getBase(); 15999 RHSBase = RHSME->getBase(); 16000 LHSME = dyn_cast<MemberExpr>(LHSBase); 16001 RHSME = dyn_cast<MemberExpr>(RHSBase); 16002 } 16003 16004 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 16005 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 16006 if (LHSDeclRef && RHSDeclRef) { 16007 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16008 return; 16009 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16010 RHSDeclRef->getDecl()->getCanonicalDecl()) 16011 return; 16012 16013 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16014 << LHSExpr->getSourceRange() 16015 << RHSExpr->getSourceRange(); 16016 return; 16017 } 16018 16019 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 16020 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16021 << LHSExpr->getSourceRange() 16022 << RHSExpr->getSourceRange(); 16023 } 16024 16025 //===--- Layout compatibility ----------------------------------------------// 16026 16027 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 16028 16029 /// Check if two enumeration types are layout-compatible. 16030 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 16031 // C++11 [dcl.enum] p8: 16032 // Two enumeration types are layout-compatible if they have the same 16033 // underlying type. 16034 return ED1->isComplete() && ED2->isComplete() && 16035 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 16036 } 16037 16038 /// Check if two fields are layout-compatible. 16039 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 16040 FieldDecl *Field2) { 16041 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 16042 return false; 16043 16044 if (Field1->isBitField() != Field2->isBitField()) 16045 return false; 16046 16047 if (Field1->isBitField()) { 16048 // Make sure that the bit-fields are the same length. 16049 unsigned Bits1 = Field1->getBitWidthValue(C); 16050 unsigned Bits2 = Field2->getBitWidthValue(C); 16051 16052 if (Bits1 != Bits2) 16053 return false; 16054 } 16055 16056 return true; 16057 } 16058 16059 /// Check if two standard-layout structs are layout-compatible. 16060 /// (C++11 [class.mem] p17) 16061 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 16062 RecordDecl *RD2) { 16063 // If both records are C++ classes, check that base classes match. 16064 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 16065 // If one of records is a CXXRecordDecl we are in C++ mode, 16066 // thus the other one is a CXXRecordDecl, too. 16067 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 16068 // Check number of base classes. 16069 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 16070 return false; 16071 16072 // Check the base classes. 16073 for (CXXRecordDecl::base_class_const_iterator 16074 Base1 = D1CXX->bases_begin(), 16075 BaseEnd1 = D1CXX->bases_end(), 16076 Base2 = D2CXX->bases_begin(); 16077 Base1 != BaseEnd1; 16078 ++Base1, ++Base2) { 16079 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 16080 return false; 16081 } 16082 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 16083 // If only RD2 is a C++ class, it should have zero base classes. 16084 if (D2CXX->getNumBases() > 0) 16085 return false; 16086 } 16087 16088 // Check the fields. 16089 RecordDecl::field_iterator Field2 = RD2->field_begin(), 16090 Field2End = RD2->field_end(), 16091 Field1 = RD1->field_begin(), 16092 Field1End = RD1->field_end(); 16093 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 16094 if (!isLayoutCompatible(C, *Field1, *Field2)) 16095 return false; 16096 } 16097 if (Field1 != Field1End || Field2 != Field2End) 16098 return false; 16099 16100 return true; 16101 } 16102 16103 /// Check if two standard-layout unions are layout-compatible. 16104 /// (C++11 [class.mem] p18) 16105 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 16106 RecordDecl *RD2) { 16107 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 16108 for (auto *Field2 : RD2->fields()) 16109 UnmatchedFields.insert(Field2); 16110 16111 for (auto *Field1 : RD1->fields()) { 16112 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 16113 I = UnmatchedFields.begin(), 16114 E = UnmatchedFields.end(); 16115 16116 for ( ; I != E; ++I) { 16117 if (isLayoutCompatible(C, Field1, *I)) { 16118 bool Result = UnmatchedFields.erase(*I); 16119 (void) Result; 16120 assert(Result); 16121 break; 16122 } 16123 } 16124 if (I == E) 16125 return false; 16126 } 16127 16128 return UnmatchedFields.empty(); 16129 } 16130 16131 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 16132 RecordDecl *RD2) { 16133 if (RD1->isUnion() != RD2->isUnion()) 16134 return false; 16135 16136 if (RD1->isUnion()) 16137 return isLayoutCompatibleUnion(C, RD1, RD2); 16138 else 16139 return isLayoutCompatibleStruct(C, RD1, RD2); 16140 } 16141 16142 /// Check if two types are layout-compatible in C++11 sense. 16143 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 16144 if (T1.isNull() || T2.isNull()) 16145 return false; 16146 16147 // C++11 [basic.types] p11: 16148 // If two types T1 and T2 are the same type, then T1 and T2 are 16149 // layout-compatible types. 16150 if (C.hasSameType(T1, T2)) 16151 return true; 16152 16153 T1 = T1.getCanonicalType().getUnqualifiedType(); 16154 T2 = T2.getCanonicalType().getUnqualifiedType(); 16155 16156 const Type::TypeClass TC1 = T1->getTypeClass(); 16157 const Type::TypeClass TC2 = T2->getTypeClass(); 16158 16159 if (TC1 != TC2) 16160 return false; 16161 16162 if (TC1 == Type::Enum) { 16163 return isLayoutCompatible(C, 16164 cast<EnumType>(T1)->getDecl(), 16165 cast<EnumType>(T2)->getDecl()); 16166 } else if (TC1 == Type::Record) { 16167 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 16168 return false; 16169 16170 return isLayoutCompatible(C, 16171 cast<RecordType>(T1)->getDecl(), 16172 cast<RecordType>(T2)->getDecl()); 16173 } 16174 16175 return false; 16176 } 16177 16178 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16179 16180 /// Given a type tag expression find the type tag itself. 16181 /// 16182 /// \param TypeExpr Type tag expression, as it appears in user's code. 16183 /// 16184 /// \param VD Declaration of an identifier that appears in a type tag. 16185 /// 16186 /// \param MagicValue Type tag magic value. 16187 /// 16188 /// \param isConstantEvaluated whether the evalaution should be performed in 16189 16190 /// constant context. 16191 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16192 const ValueDecl **VD, uint64_t *MagicValue, 16193 bool isConstantEvaluated) { 16194 while(true) { 16195 if (!TypeExpr) 16196 return false; 16197 16198 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16199 16200 switch (TypeExpr->getStmtClass()) { 16201 case Stmt::UnaryOperatorClass: { 16202 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16203 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16204 TypeExpr = UO->getSubExpr(); 16205 continue; 16206 } 16207 return false; 16208 } 16209 16210 case Stmt::DeclRefExprClass: { 16211 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16212 *VD = DRE->getDecl(); 16213 return true; 16214 } 16215 16216 case Stmt::IntegerLiteralClass: { 16217 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16218 llvm::APInt MagicValueAPInt = IL->getValue(); 16219 if (MagicValueAPInt.getActiveBits() <= 64) { 16220 *MagicValue = MagicValueAPInt.getZExtValue(); 16221 return true; 16222 } else 16223 return false; 16224 } 16225 16226 case Stmt::BinaryConditionalOperatorClass: 16227 case Stmt::ConditionalOperatorClass: { 16228 const AbstractConditionalOperator *ACO = 16229 cast<AbstractConditionalOperator>(TypeExpr); 16230 bool Result; 16231 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16232 isConstantEvaluated)) { 16233 if (Result) 16234 TypeExpr = ACO->getTrueExpr(); 16235 else 16236 TypeExpr = ACO->getFalseExpr(); 16237 continue; 16238 } 16239 return false; 16240 } 16241 16242 case Stmt::BinaryOperatorClass: { 16243 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16244 if (BO->getOpcode() == BO_Comma) { 16245 TypeExpr = BO->getRHS(); 16246 continue; 16247 } 16248 return false; 16249 } 16250 16251 default: 16252 return false; 16253 } 16254 } 16255 } 16256 16257 /// Retrieve the C type corresponding to type tag TypeExpr. 16258 /// 16259 /// \param TypeExpr Expression that specifies a type tag. 16260 /// 16261 /// \param MagicValues Registered magic values. 16262 /// 16263 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16264 /// kind. 16265 /// 16266 /// \param TypeInfo Information about the corresponding C type. 16267 /// 16268 /// \param isConstantEvaluated whether the evalaution should be performed in 16269 /// constant context. 16270 /// 16271 /// \returns true if the corresponding C type was found. 16272 static bool GetMatchingCType( 16273 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16274 const ASTContext &Ctx, 16275 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16276 *MagicValues, 16277 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16278 bool isConstantEvaluated) { 16279 FoundWrongKind = false; 16280 16281 // Variable declaration that has type_tag_for_datatype attribute. 16282 const ValueDecl *VD = nullptr; 16283 16284 uint64_t MagicValue; 16285 16286 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16287 return false; 16288 16289 if (VD) { 16290 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16291 if (I->getArgumentKind() != ArgumentKind) { 16292 FoundWrongKind = true; 16293 return false; 16294 } 16295 TypeInfo.Type = I->getMatchingCType(); 16296 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16297 TypeInfo.MustBeNull = I->getMustBeNull(); 16298 return true; 16299 } 16300 return false; 16301 } 16302 16303 if (!MagicValues) 16304 return false; 16305 16306 llvm::DenseMap<Sema::TypeTagMagicValue, 16307 Sema::TypeTagData>::const_iterator I = 16308 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16309 if (I == MagicValues->end()) 16310 return false; 16311 16312 TypeInfo = I->second; 16313 return true; 16314 } 16315 16316 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16317 uint64_t MagicValue, QualType Type, 16318 bool LayoutCompatible, 16319 bool MustBeNull) { 16320 if (!TypeTagForDatatypeMagicValues) 16321 TypeTagForDatatypeMagicValues.reset( 16322 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16323 16324 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16325 (*TypeTagForDatatypeMagicValues)[Magic] = 16326 TypeTagData(Type, LayoutCompatible, MustBeNull); 16327 } 16328 16329 static bool IsSameCharType(QualType T1, QualType T2) { 16330 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16331 if (!BT1) 16332 return false; 16333 16334 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16335 if (!BT2) 16336 return false; 16337 16338 BuiltinType::Kind T1Kind = BT1->getKind(); 16339 BuiltinType::Kind T2Kind = BT2->getKind(); 16340 16341 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16342 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16343 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16344 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16345 } 16346 16347 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16348 const ArrayRef<const Expr *> ExprArgs, 16349 SourceLocation CallSiteLoc) { 16350 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16351 bool IsPointerAttr = Attr->getIsPointer(); 16352 16353 // Retrieve the argument representing the 'type_tag'. 16354 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16355 if (TypeTagIdxAST >= ExprArgs.size()) { 16356 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16357 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16358 return; 16359 } 16360 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16361 bool FoundWrongKind; 16362 TypeTagData TypeInfo; 16363 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16364 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16365 TypeInfo, isConstantEvaluated())) { 16366 if (FoundWrongKind) 16367 Diag(TypeTagExpr->getExprLoc(), 16368 diag::warn_type_tag_for_datatype_wrong_kind) 16369 << TypeTagExpr->getSourceRange(); 16370 return; 16371 } 16372 16373 // Retrieve the argument representing the 'arg_idx'. 16374 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16375 if (ArgumentIdxAST >= ExprArgs.size()) { 16376 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16377 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16378 return; 16379 } 16380 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16381 if (IsPointerAttr) { 16382 // Skip implicit cast of pointer to `void *' (as a function argument). 16383 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16384 if (ICE->getType()->isVoidPointerType() && 16385 ICE->getCastKind() == CK_BitCast) 16386 ArgumentExpr = ICE->getSubExpr(); 16387 } 16388 QualType ArgumentType = ArgumentExpr->getType(); 16389 16390 // Passing a `void*' pointer shouldn't trigger a warning. 16391 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16392 return; 16393 16394 if (TypeInfo.MustBeNull) { 16395 // Type tag with matching void type requires a null pointer. 16396 if (!ArgumentExpr->isNullPointerConstant(Context, 16397 Expr::NPC_ValueDependentIsNotNull)) { 16398 Diag(ArgumentExpr->getExprLoc(), 16399 diag::warn_type_safety_null_pointer_required) 16400 << ArgumentKind->getName() 16401 << ArgumentExpr->getSourceRange() 16402 << TypeTagExpr->getSourceRange(); 16403 } 16404 return; 16405 } 16406 16407 QualType RequiredType = TypeInfo.Type; 16408 if (IsPointerAttr) 16409 RequiredType = Context.getPointerType(RequiredType); 16410 16411 bool mismatch = false; 16412 if (!TypeInfo.LayoutCompatible) { 16413 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16414 16415 // C++11 [basic.fundamental] p1: 16416 // Plain char, signed char, and unsigned char are three distinct types. 16417 // 16418 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16419 // char' depending on the current char signedness mode. 16420 if (mismatch) 16421 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16422 RequiredType->getPointeeType())) || 16423 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16424 mismatch = false; 16425 } else 16426 if (IsPointerAttr) 16427 mismatch = !isLayoutCompatible(Context, 16428 ArgumentType->getPointeeType(), 16429 RequiredType->getPointeeType()); 16430 else 16431 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16432 16433 if (mismatch) 16434 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16435 << ArgumentType << ArgumentKind 16436 << TypeInfo.LayoutCompatible << RequiredType 16437 << ArgumentExpr->getSourceRange() 16438 << TypeTagExpr->getSourceRange(); 16439 } 16440 16441 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16442 CharUnits Alignment) { 16443 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16444 } 16445 16446 void Sema::DiagnoseMisalignedMembers() { 16447 for (MisalignedMember &m : MisalignedMembers) { 16448 const NamedDecl *ND = m.RD; 16449 if (ND->getName().empty()) { 16450 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16451 ND = TD; 16452 } 16453 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16454 << m.MD << ND << m.E->getSourceRange(); 16455 } 16456 MisalignedMembers.clear(); 16457 } 16458 16459 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16460 E = E->IgnoreParens(); 16461 if (!T->isPointerType() && !T->isIntegerType()) 16462 return; 16463 if (isa<UnaryOperator>(E) && 16464 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16465 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16466 if (isa<MemberExpr>(Op)) { 16467 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16468 if (MA != MisalignedMembers.end() && 16469 (T->isIntegerType() || 16470 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16471 Context.getTypeAlignInChars( 16472 T->getPointeeType()) <= MA->Alignment)))) 16473 MisalignedMembers.erase(MA); 16474 } 16475 } 16476 } 16477 16478 void Sema::RefersToMemberWithReducedAlignment( 16479 Expr *E, 16480 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16481 Action) { 16482 const auto *ME = dyn_cast<MemberExpr>(E); 16483 if (!ME) 16484 return; 16485 16486 // No need to check expressions with an __unaligned-qualified type. 16487 if (E->getType().getQualifiers().hasUnaligned()) 16488 return; 16489 16490 // For a chain of MemberExpr like "a.b.c.d" this list 16491 // will keep FieldDecl's like [d, c, b]. 16492 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16493 const MemberExpr *TopME = nullptr; 16494 bool AnyIsPacked = false; 16495 do { 16496 QualType BaseType = ME->getBase()->getType(); 16497 if (BaseType->isDependentType()) 16498 return; 16499 if (ME->isArrow()) 16500 BaseType = BaseType->getPointeeType(); 16501 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16502 if (RD->isInvalidDecl()) 16503 return; 16504 16505 ValueDecl *MD = ME->getMemberDecl(); 16506 auto *FD = dyn_cast<FieldDecl>(MD); 16507 // We do not care about non-data members. 16508 if (!FD || FD->isInvalidDecl()) 16509 return; 16510 16511 AnyIsPacked = 16512 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16513 ReverseMemberChain.push_back(FD); 16514 16515 TopME = ME; 16516 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16517 } while (ME); 16518 assert(TopME && "We did not compute a topmost MemberExpr!"); 16519 16520 // Not the scope of this diagnostic. 16521 if (!AnyIsPacked) 16522 return; 16523 16524 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16525 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16526 // TODO: The innermost base of the member expression may be too complicated. 16527 // For now, just disregard these cases. This is left for future 16528 // improvement. 16529 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16530 return; 16531 16532 // Alignment expected by the whole expression. 16533 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16534 16535 // No need to do anything else with this case. 16536 if (ExpectedAlignment.isOne()) 16537 return; 16538 16539 // Synthesize offset of the whole access. 16540 CharUnits Offset; 16541 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 16542 I++) { 16543 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 16544 } 16545 16546 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16547 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16548 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16549 16550 // The base expression of the innermost MemberExpr may give 16551 // stronger guarantees than the class containing the member. 16552 if (DRE && !TopME->isArrow()) { 16553 const ValueDecl *VD = DRE->getDecl(); 16554 if (!VD->getType()->isReferenceType()) 16555 CompleteObjectAlignment = 16556 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16557 } 16558 16559 // Check if the synthesized offset fulfills the alignment. 16560 if (Offset % ExpectedAlignment != 0 || 16561 // It may fulfill the offset it but the effective alignment may still be 16562 // lower than the expected expression alignment. 16563 CompleteObjectAlignment < ExpectedAlignment) { 16564 // If this happens, we want to determine a sensible culprit of this. 16565 // Intuitively, watching the chain of member expressions from right to 16566 // left, we start with the required alignment (as required by the field 16567 // type) but some packed attribute in that chain has reduced the alignment. 16568 // It may happen that another packed structure increases it again. But if 16569 // we are here such increase has not been enough. So pointing the first 16570 // FieldDecl that either is packed or else its RecordDecl is, 16571 // seems reasonable. 16572 FieldDecl *FD = nullptr; 16573 CharUnits Alignment; 16574 for (FieldDecl *FDI : ReverseMemberChain) { 16575 if (FDI->hasAttr<PackedAttr>() || 16576 FDI->getParent()->hasAttr<PackedAttr>()) { 16577 FD = FDI; 16578 Alignment = std::min( 16579 Context.getTypeAlignInChars(FD->getType()), 16580 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16581 break; 16582 } 16583 } 16584 assert(FD && "We did not find a packed FieldDecl!"); 16585 Action(E, FD->getParent(), FD, Alignment); 16586 } 16587 } 16588 16589 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16590 using namespace std::placeholders; 16591 16592 RefersToMemberWithReducedAlignment( 16593 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16594 _2, _3, _4)); 16595 } 16596 16597 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16598 ExprResult CallResult) { 16599 if (checkArgCount(*this, TheCall, 1)) 16600 return ExprError(); 16601 16602 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16603 if (MatrixArg.isInvalid()) 16604 return MatrixArg; 16605 Expr *Matrix = MatrixArg.get(); 16606 16607 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16608 if (!MType) { 16609 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 16610 return ExprError(); 16611 } 16612 16613 // Create returned matrix type by swapping rows and columns of the argument 16614 // matrix type. 16615 QualType ResultType = Context.getConstantMatrixType( 16616 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16617 16618 // Change the return type to the type of the returned matrix. 16619 TheCall->setType(ResultType); 16620 16621 // Update call argument to use the possibly converted matrix argument. 16622 TheCall->setArg(0, Matrix); 16623 return CallResult; 16624 } 16625 16626 // Get and verify the matrix dimensions. 16627 static llvm::Optional<unsigned> 16628 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16629 SourceLocation ErrorPos; 16630 Optional<llvm::APSInt> Value = 16631 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16632 if (!Value) { 16633 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16634 << Name; 16635 return {}; 16636 } 16637 uint64_t Dim = Value->getZExtValue(); 16638 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16639 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16640 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16641 return {}; 16642 } 16643 return Dim; 16644 } 16645 16646 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16647 ExprResult CallResult) { 16648 if (!getLangOpts().MatrixTypes) { 16649 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16650 return ExprError(); 16651 } 16652 16653 if (checkArgCount(*this, TheCall, 4)) 16654 return ExprError(); 16655 16656 unsigned PtrArgIdx = 0; 16657 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16658 Expr *RowsExpr = TheCall->getArg(1); 16659 Expr *ColumnsExpr = TheCall->getArg(2); 16660 Expr *StrideExpr = TheCall->getArg(3); 16661 16662 bool ArgError = false; 16663 16664 // Check pointer argument. 16665 { 16666 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16667 if (PtrConv.isInvalid()) 16668 return PtrConv; 16669 PtrExpr = PtrConv.get(); 16670 TheCall->setArg(0, PtrExpr); 16671 if (PtrExpr->isTypeDependent()) { 16672 TheCall->setType(Context.DependentTy); 16673 return TheCall; 16674 } 16675 } 16676 16677 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16678 QualType ElementTy; 16679 if (!PtrTy) { 16680 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16681 << PtrArgIdx + 1; 16682 ArgError = true; 16683 } else { 16684 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16685 16686 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16687 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16688 << PtrArgIdx + 1; 16689 ArgError = true; 16690 } 16691 } 16692 16693 // Apply default Lvalue conversions and convert the expression to size_t. 16694 auto ApplyArgumentConversions = [this](Expr *E) { 16695 ExprResult Conv = DefaultLvalueConversion(E); 16696 if (Conv.isInvalid()) 16697 return Conv; 16698 16699 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16700 }; 16701 16702 // Apply conversion to row and column expressions. 16703 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16704 if (!RowsConv.isInvalid()) { 16705 RowsExpr = RowsConv.get(); 16706 TheCall->setArg(1, RowsExpr); 16707 } else 16708 RowsExpr = nullptr; 16709 16710 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16711 if (!ColumnsConv.isInvalid()) { 16712 ColumnsExpr = ColumnsConv.get(); 16713 TheCall->setArg(2, ColumnsExpr); 16714 } else 16715 ColumnsExpr = nullptr; 16716 16717 // If any any part of the result matrix type is still pending, just use 16718 // Context.DependentTy, until all parts are resolved. 16719 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16720 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16721 TheCall->setType(Context.DependentTy); 16722 return CallResult; 16723 } 16724 16725 // Check row and column dimensions. 16726 llvm::Optional<unsigned> MaybeRows; 16727 if (RowsExpr) 16728 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16729 16730 llvm::Optional<unsigned> MaybeColumns; 16731 if (ColumnsExpr) 16732 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16733 16734 // Check stride argument. 16735 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16736 if (StrideConv.isInvalid()) 16737 return ExprError(); 16738 StrideExpr = StrideConv.get(); 16739 TheCall->setArg(3, StrideExpr); 16740 16741 if (MaybeRows) { 16742 if (Optional<llvm::APSInt> Value = 16743 StrideExpr->getIntegerConstantExpr(Context)) { 16744 uint64_t Stride = Value->getZExtValue(); 16745 if (Stride < *MaybeRows) { 16746 Diag(StrideExpr->getBeginLoc(), 16747 diag::err_builtin_matrix_stride_too_small); 16748 ArgError = true; 16749 } 16750 } 16751 } 16752 16753 if (ArgError || !MaybeRows || !MaybeColumns) 16754 return ExprError(); 16755 16756 TheCall->setType( 16757 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16758 return CallResult; 16759 } 16760 16761 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16762 ExprResult CallResult) { 16763 if (checkArgCount(*this, TheCall, 3)) 16764 return ExprError(); 16765 16766 unsigned PtrArgIdx = 1; 16767 Expr *MatrixExpr = TheCall->getArg(0); 16768 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16769 Expr *StrideExpr = TheCall->getArg(2); 16770 16771 bool ArgError = false; 16772 16773 { 16774 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16775 if (MatrixConv.isInvalid()) 16776 return MatrixConv; 16777 MatrixExpr = MatrixConv.get(); 16778 TheCall->setArg(0, MatrixExpr); 16779 } 16780 if (MatrixExpr->isTypeDependent()) { 16781 TheCall->setType(Context.DependentTy); 16782 return TheCall; 16783 } 16784 16785 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16786 if (!MatrixTy) { 16787 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16788 ArgError = true; 16789 } 16790 16791 { 16792 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16793 if (PtrConv.isInvalid()) 16794 return PtrConv; 16795 PtrExpr = PtrConv.get(); 16796 TheCall->setArg(1, PtrExpr); 16797 if (PtrExpr->isTypeDependent()) { 16798 TheCall->setType(Context.DependentTy); 16799 return TheCall; 16800 } 16801 } 16802 16803 // Check pointer argument. 16804 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16805 if (!PtrTy) { 16806 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16807 << PtrArgIdx + 1; 16808 ArgError = true; 16809 } else { 16810 QualType ElementTy = PtrTy->getPointeeType(); 16811 if (ElementTy.isConstQualified()) { 16812 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16813 ArgError = true; 16814 } 16815 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16816 if (MatrixTy && 16817 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16818 Diag(PtrExpr->getBeginLoc(), 16819 diag::err_builtin_matrix_pointer_arg_mismatch) 16820 << ElementTy << MatrixTy->getElementType(); 16821 ArgError = true; 16822 } 16823 } 16824 16825 // Apply default Lvalue conversions and convert the stride expression to 16826 // size_t. 16827 { 16828 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16829 if (StrideConv.isInvalid()) 16830 return StrideConv; 16831 16832 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16833 if (StrideConv.isInvalid()) 16834 return StrideConv; 16835 StrideExpr = StrideConv.get(); 16836 TheCall->setArg(2, StrideExpr); 16837 } 16838 16839 // Check stride argument. 16840 if (MatrixTy) { 16841 if (Optional<llvm::APSInt> Value = 16842 StrideExpr->getIntegerConstantExpr(Context)) { 16843 uint64_t Stride = Value->getZExtValue(); 16844 if (Stride < MatrixTy->getNumRows()) { 16845 Diag(StrideExpr->getBeginLoc(), 16846 diag::err_builtin_matrix_stride_too_small); 16847 ArgError = true; 16848 } 16849 } 16850 } 16851 16852 if (ArgError) 16853 return ExprError(); 16854 16855 return CallResult; 16856 } 16857 16858 /// \brief Enforce the bounds of a TCB 16859 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16860 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16861 /// and enforce_tcb_leaf attributes. 16862 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16863 const FunctionDecl *Callee) { 16864 const FunctionDecl *Caller = getCurFunctionDecl(); 16865 16866 // Calls to builtins are not enforced. 16867 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16868 Callee->getBuiltinID() != 0) 16869 return; 16870 16871 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16872 // all TCBs the callee is a part of. 16873 llvm::StringSet<> CalleeTCBs; 16874 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16875 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16876 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16877 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16878 16879 // Go through the TCBs the caller is a part of and emit warnings if Caller 16880 // is in a TCB that the Callee is not. 16881 for_each( 16882 Caller->specific_attrs<EnforceTCBAttr>(), 16883 [&](const auto *A) { 16884 StringRef CallerTCB = A->getTCBName(); 16885 if (CalleeTCBs.count(CallerTCB) == 0) { 16886 this->Diag(TheCall->getExprLoc(), 16887 diag::warn_tcb_enforcement_violation) << Callee 16888 << CallerTCB; 16889 } 16890 }); 16891 } 16892