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 that the argument to __builtin_function_start is a function. 199 static bool SemaBuiltinFunctionStart(Sema &S, CallExpr *TheCall) { 200 if (checkArgCount(S, TheCall, 1)) 201 return true; 202 203 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 204 if (Arg.isInvalid()) 205 return true; 206 207 TheCall->setArg(0, Arg.get()); 208 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>( 209 Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext())); 210 211 if (!FD) { 212 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type) 213 << TheCall->getSourceRange(); 214 return true; 215 } 216 217 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 218 TheCall->getBeginLoc()); 219 } 220 221 /// Check the number of arguments and set the result type to 222 /// the argument type. 223 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 224 if (checkArgCount(S, TheCall, 1)) 225 return true; 226 227 TheCall->setType(TheCall->getArg(0)->getType()); 228 return false; 229 } 230 231 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 232 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 233 /// type (but not a function pointer) and that the alignment is a power-of-two. 234 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 235 if (checkArgCount(S, TheCall, 2)) 236 return true; 237 238 clang::Expr *Source = TheCall->getArg(0); 239 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 240 241 auto IsValidIntegerType = [](QualType Ty) { 242 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 243 }; 244 QualType SrcTy = Source->getType(); 245 // We should also be able to use it with arrays (but not functions!). 246 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 247 SrcTy = S.Context.getDecayedType(SrcTy); 248 } 249 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 250 SrcTy->isFunctionPointerType()) { 251 // FIXME: this is not quite the right error message since we don't allow 252 // floating point types, or member pointers. 253 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 254 << SrcTy; 255 return true; 256 } 257 258 clang::Expr *AlignOp = TheCall->getArg(1); 259 if (!IsValidIntegerType(AlignOp->getType())) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 261 << AlignOp->getType(); 262 return true; 263 } 264 Expr::EvalResult AlignResult; 265 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 266 // We can't check validity of alignment if it is value dependent. 267 if (!AlignOp->isValueDependent() && 268 AlignOp->EvaluateAsInt(AlignResult, S.Context, 269 Expr::SE_AllowSideEffects)) { 270 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 271 llvm::APSInt MaxValue( 272 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 273 if (AlignValue < 1) { 274 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 275 return true; 276 } 277 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 278 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 279 << toString(MaxValue, 10); 280 return true; 281 } 282 if (!AlignValue.isPowerOf2()) { 283 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 284 return true; 285 } 286 if (AlignValue == 1) { 287 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 288 << IsBooleanAlignBuiltin; 289 } 290 } 291 292 ExprResult SrcArg = S.PerformCopyInitialization( 293 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 294 SourceLocation(), Source); 295 if (SrcArg.isInvalid()) 296 return true; 297 TheCall->setArg(0, SrcArg.get()); 298 ExprResult AlignArg = 299 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 300 S.Context, AlignOp->getType(), false), 301 SourceLocation(), AlignOp); 302 if (AlignArg.isInvalid()) 303 return true; 304 TheCall->setArg(1, AlignArg.get()); 305 // For align_up/align_down, the return type is the same as the (potentially 306 // decayed) argument type including qualifiers. For is_aligned(), the result 307 // is always bool. 308 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 309 return false; 310 } 311 312 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 313 unsigned BuiltinID) { 314 if (checkArgCount(S, TheCall, 3)) 315 return true; 316 317 // First two arguments should be integers. 318 for (unsigned I = 0; I < 2; ++I) { 319 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 320 if (Arg.isInvalid()) return true; 321 TheCall->setArg(I, Arg.get()); 322 323 QualType Ty = Arg.get()->getType(); 324 if (!Ty->isIntegerType()) { 325 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 326 << Ty << Arg.get()->getSourceRange(); 327 return true; 328 } 329 } 330 331 // Third argument should be a pointer to a non-const integer. 332 // IRGen correctly handles volatile, restrict, and address spaces, and 333 // the other qualifiers aren't possible. 334 { 335 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 336 if (Arg.isInvalid()) return true; 337 TheCall->setArg(2, Arg.get()); 338 339 QualType Ty = Arg.get()->getType(); 340 const auto *PtrTy = Ty->getAs<PointerType>(); 341 if (!PtrTy || 342 !PtrTy->getPointeeType()->isIntegerType() || 343 PtrTy->getPointeeType().isConstQualified()) { 344 S.Diag(Arg.get()->getBeginLoc(), 345 diag::err_overflow_builtin_must_be_ptr_int) 346 << Ty << Arg.get()->getSourceRange(); 347 return true; 348 } 349 } 350 351 // Disallow signed bit-precise integer args larger than 128 bits to mul 352 // function until we improve backend support. 353 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 354 for (unsigned I = 0; I < 3; ++I) { 355 const auto Arg = TheCall->getArg(I); 356 // Third argument will be a pointer. 357 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 358 if (Ty->isBitIntType() && Ty->isSignedIntegerType() && 359 S.getASTContext().getIntWidth(Ty) > 128) 360 return S.Diag(Arg->getBeginLoc(), 361 diag::err_overflow_builtin_bit_int_max_size) 362 << 128; 363 } 364 } 365 366 return false; 367 } 368 369 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 370 if (checkArgCount(S, BuiltinCall, 2)) 371 return true; 372 373 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 374 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 375 Expr *Call = BuiltinCall->getArg(0); 376 Expr *Chain = BuiltinCall->getArg(1); 377 378 if (Call->getStmtClass() != Stmt::CallExprClass) { 379 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 380 << Call->getSourceRange(); 381 return true; 382 } 383 384 auto CE = cast<CallExpr>(Call); 385 if (CE->getCallee()->getType()->isBlockPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 387 << Call->getSourceRange(); 388 return true; 389 } 390 391 const Decl *TargetDecl = CE->getCalleeDecl(); 392 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 393 if (FD->getBuiltinID()) { 394 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 395 << Call->getSourceRange(); 396 return true; 397 } 398 399 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 400 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 401 << Call->getSourceRange(); 402 return true; 403 } 404 405 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 406 if (ChainResult.isInvalid()) 407 return true; 408 if (!ChainResult.get()->getType()->isPointerType()) { 409 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 410 << Chain->getSourceRange(); 411 return true; 412 } 413 414 QualType ReturnTy = CE->getCallReturnType(S.Context); 415 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 416 QualType BuiltinTy = S.Context.getFunctionType( 417 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 418 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 419 420 Builtin = 421 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 422 423 BuiltinCall->setType(CE->getType()); 424 BuiltinCall->setValueKind(CE->getValueKind()); 425 BuiltinCall->setObjectKind(CE->getObjectKind()); 426 BuiltinCall->setCallee(Builtin); 427 BuiltinCall->setArg(1, ChainResult.get()); 428 429 return false; 430 } 431 432 namespace { 433 434 class ScanfDiagnosticFormatHandler 435 : public analyze_format_string::FormatStringHandler { 436 // Accepts the argument index (relative to the first destination index) of the 437 // argument whose size we want. 438 using ComputeSizeFunction = 439 llvm::function_ref<Optional<llvm::APSInt>(unsigned)>; 440 441 // Accepts the argument index (relative to the first destination index), the 442 // destination size, and the source size). 443 using DiagnoseFunction = 444 llvm::function_ref<void(unsigned, unsigned, unsigned)>; 445 446 ComputeSizeFunction ComputeSizeArgument; 447 DiagnoseFunction Diagnose; 448 449 public: 450 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument, 451 DiagnoseFunction Diagnose) 452 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {} 453 454 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 455 const char *StartSpecifier, 456 unsigned specifierLen) override { 457 if (!FS.consumesDataArgument()) 458 return true; 459 460 unsigned NulByte = 0; 461 switch ((FS.getConversionSpecifier().getKind())) { 462 default: 463 return true; 464 case analyze_format_string::ConversionSpecifier::sArg: 465 case analyze_format_string::ConversionSpecifier::ScanListArg: 466 NulByte = 1; 467 break; 468 case analyze_format_string::ConversionSpecifier::cArg: 469 break; 470 } 471 472 analyze_format_string::OptionalAmount FW = FS.getFieldWidth(); 473 if (FW.getHowSpecified() != 474 analyze_format_string::OptionalAmount::HowSpecified::Constant) 475 return true; 476 477 unsigned SourceSize = FW.getConstantAmount() + NulByte; 478 479 Optional<llvm::APSInt> DestSizeAPS = ComputeSizeArgument(FS.getArgIndex()); 480 if (!DestSizeAPS) 481 return true; 482 483 unsigned DestSize = DestSizeAPS->getZExtValue(); 484 485 if (DestSize < SourceSize) 486 Diagnose(FS.getArgIndex(), DestSize, SourceSize); 487 488 return true; 489 } 490 }; 491 492 class EstimateSizeFormatHandler 493 : public analyze_format_string::FormatStringHandler { 494 size_t Size; 495 496 public: 497 EstimateSizeFormatHandler(StringRef Format) 498 : Size(std::min(Format.find(0), Format.size()) + 499 1 /* null byte always written by sprintf */) {} 500 501 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 502 const char *, unsigned SpecifierLen) override { 503 504 const size_t FieldWidth = computeFieldWidth(FS); 505 const size_t Precision = computePrecision(FS); 506 507 // The actual format. 508 switch (FS.getConversionSpecifier().getKind()) { 509 // Just a char. 510 case analyze_format_string::ConversionSpecifier::cArg: 511 case analyze_format_string::ConversionSpecifier::CArg: 512 Size += std::max(FieldWidth, (size_t)1); 513 break; 514 // Just an integer. 515 case analyze_format_string::ConversionSpecifier::dArg: 516 case analyze_format_string::ConversionSpecifier::DArg: 517 case analyze_format_string::ConversionSpecifier::iArg: 518 case analyze_format_string::ConversionSpecifier::oArg: 519 case analyze_format_string::ConversionSpecifier::OArg: 520 case analyze_format_string::ConversionSpecifier::uArg: 521 case analyze_format_string::ConversionSpecifier::UArg: 522 case analyze_format_string::ConversionSpecifier::xArg: 523 case analyze_format_string::ConversionSpecifier::XArg: 524 Size += std::max(FieldWidth, Precision); 525 break; 526 527 // %g style conversion switches between %f or %e style dynamically. 528 // %f always takes less space, so default to it. 529 case analyze_format_string::ConversionSpecifier::gArg: 530 case analyze_format_string::ConversionSpecifier::GArg: 531 532 // Floating point number in the form '[+]ddd.ddd'. 533 case analyze_format_string::ConversionSpecifier::fArg: 534 case analyze_format_string::ConversionSpecifier::FArg: 535 Size += std::max(FieldWidth, 1 /* integer part */ + 536 (Precision ? 1 + Precision 537 : 0) /* period + decimal */); 538 break; 539 540 // Floating point number in the form '[-]d.ddde[+-]dd'. 541 case analyze_format_string::ConversionSpecifier::eArg: 542 case analyze_format_string::ConversionSpecifier::EArg: 543 Size += 544 std::max(FieldWidth, 545 1 /* integer part */ + 546 (Precision ? 1 + Precision : 0) /* period + decimal */ + 547 1 /* e or E letter */ + 2 /* exponent */); 548 break; 549 550 // Floating point number in the form '[-]0xh.hhhhp±dd'. 551 case analyze_format_string::ConversionSpecifier::aArg: 552 case analyze_format_string::ConversionSpecifier::AArg: 553 Size += 554 std::max(FieldWidth, 555 2 /* 0x */ + 1 /* integer part */ + 556 (Precision ? 1 + Precision : 0) /* period + decimal */ + 557 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 558 break; 559 560 // Just a string. 561 case analyze_format_string::ConversionSpecifier::sArg: 562 case analyze_format_string::ConversionSpecifier::SArg: 563 Size += FieldWidth; 564 break; 565 566 // Just a pointer in the form '0xddd'. 567 case analyze_format_string::ConversionSpecifier::pArg: 568 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 569 break; 570 571 // A plain percent. 572 case analyze_format_string::ConversionSpecifier::PercentArg: 573 Size += 1; 574 break; 575 576 default: 577 break; 578 } 579 580 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 581 582 if (FS.hasAlternativeForm()) { 583 switch (FS.getConversionSpecifier().getKind()) { 584 default: 585 break; 586 // Force a leading '0'. 587 case analyze_format_string::ConversionSpecifier::oArg: 588 Size += 1; 589 break; 590 // Force a leading '0x'. 591 case analyze_format_string::ConversionSpecifier::xArg: 592 case analyze_format_string::ConversionSpecifier::XArg: 593 Size += 2; 594 break; 595 // Force a period '.' before decimal, even if precision is 0. 596 case analyze_format_string::ConversionSpecifier::aArg: 597 case analyze_format_string::ConversionSpecifier::AArg: 598 case analyze_format_string::ConversionSpecifier::eArg: 599 case analyze_format_string::ConversionSpecifier::EArg: 600 case analyze_format_string::ConversionSpecifier::fArg: 601 case analyze_format_string::ConversionSpecifier::FArg: 602 case analyze_format_string::ConversionSpecifier::gArg: 603 case analyze_format_string::ConversionSpecifier::GArg: 604 Size += (Precision ? 0 : 1); 605 break; 606 } 607 } 608 assert(SpecifierLen <= Size && "no underflow"); 609 Size -= SpecifierLen; 610 return true; 611 } 612 613 size_t getSizeLowerBound() const { return Size; } 614 615 private: 616 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 617 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 618 size_t FieldWidth = 0; 619 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 620 FieldWidth = FW.getConstantAmount(); 621 return FieldWidth; 622 } 623 624 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 625 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 626 size_t Precision = 0; 627 628 // See man 3 printf for default precision value based on the specifier. 629 switch (FW.getHowSpecified()) { 630 case analyze_format_string::OptionalAmount::NotSpecified: 631 switch (FS.getConversionSpecifier().getKind()) { 632 default: 633 break; 634 case analyze_format_string::ConversionSpecifier::dArg: // %d 635 case analyze_format_string::ConversionSpecifier::DArg: // %D 636 case analyze_format_string::ConversionSpecifier::iArg: // %i 637 Precision = 1; 638 break; 639 case analyze_format_string::ConversionSpecifier::oArg: // %d 640 case analyze_format_string::ConversionSpecifier::OArg: // %D 641 case analyze_format_string::ConversionSpecifier::uArg: // %d 642 case analyze_format_string::ConversionSpecifier::UArg: // %D 643 case analyze_format_string::ConversionSpecifier::xArg: // %d 644 case analyze_format_string::ConversionSpecifier::XArg: // %D 645 Precision = 1; 646 break; 647 case analyze_format_string::ConversionSpecifier::fArg: // %f 648 case analyze_format_string::ConversionSpecifier::FArg: // %F 649 case analyze_format_string::ConversionSpecifier::eArg: // %e 650 case analyze_format_string::ConversionSpecifier::EArg: // %E 651 case analyze_format_string::ConversionSpecifier::gArg: // %g 652 case analyze_format_string::ConversionSpecifier::GArg: // %G 653 Precision = 6; 654 break; 655 case analyze_format_string::ConversionSpecifier::pArg: // %d 656 Precision = 1; 657 break; 658 } 659 break; 660 case analyze_format_string::OptionalAmount::Constant: 661 Precision = FW.getConstantAmount(); 662 break; 663 default: 664 break; 665 } 666 return Precision; 667 } 668 }; 669 670 } // namespace 671 672 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 673 CallExpr *TheCall) { 674 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 675 isConstantEvaluated()) 676 return; 677 678 bool UseDABAttr = false; 679 const FunctionDecl *UseDecl = FD; 680 681 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>(); 682 if (DABAttr) { 683 UseDecl = DABAttr->getFunction(); 684 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!"); 685 UseDABAttr = true; 686 } 687 688 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true); 689 690 if (!BuiltinID) 691 return; 692 693 const TargetInfo &TI = getASTContext().getTargetInfo(); 694 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 695 696 auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> { 697 // If we refer to a diagnose_as_builtin attribute, we need to change the 698 // argument index to refer to the arguments of the called function. Unless 699 // the index is out of bounds, which presumably means it's a variadic 700 // function. 701 if (!UseDABAttr) 702 return Index; 703 unsigned DABIndices = DABAttr->argIndices_size(); 704 unsigned NewIndex = Index < DABIndices 705 ? DABAttr->argIndices_begin()[Index] 706 : Index - DABIndices + FD->getNumParams(); 707 if (NewIndex >= TheCall->getNumArgs()) 708 return llvm::None; 709 return NewIndex; 710 }; 711 712 auto ComputeExplicitObjectSizeArgument = 713 [&](unsigned Index) -> Optional<llvm::APSInt> { 714 Optional<unsigned> IndexOptional = TranslateIndex(Index); 715 if (!IndexOptional) 716 return llvm::None; 717 unsigned NewIndex = IndexOptional.getValue(); 718 Expr::EvalResult Result; 719 Expr *SizeArg = TheCall->getArg(NewIndex); 720 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 721 return llvm::None; 722 llvm::APSInt Integer = Result.Val.getInt(); 723 Integer.setIsUnsigned(true); 724 return Integer; 725 }; 726 727 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 728 // If the parameter has a pass_object_size attribute, then we should use its 729 // (potentially) more strict checking mode. Otherwise, conservatively assume 730 // type 0. 731 int BOSType = 0; 732 // This check can fail for variadic functions. 733 if (Index < FD->getNumParams()) { 734 if (const auto *POS = 735 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 736 BOSType = POS->getType(); 737 } 738 739 Optional<unsigned> IndexOptional = TranslateIndex(Index); 740 if (!IndexOptional) 741 return llvm::None; 742 unsigned NewIndex = IndexOptional.getValue(); 743 744 const Expr *ObjArg = TheCall->getArg(NewIndex); 745 uint64_t Result; 746 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 747 return llvm::None; 748 749 // Get the object size in the target's size_t width. 750 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 751 }; 752 753 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 754 Optional<unsigned> IndexOptional = TranslateIndex(Index); 755 if (!IndexOptional) 756 return llvm::None; 757 unsigned NewIndex = IndexOptional.getValue(); 758 759 const Expr *ObjArg = TheCall->getArg(NewIndex); 760 uint64_t Result; 761 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 762 return llvm::None; 763 // Add 1 for null byte. 764 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 765 }; 766 767 Optional<llvm::APSInt> SourceSize; 768 Optional<llvm::APSInt> DestinationSize; 769 unsigned DiagID = 0; 770 bool IsChkVariant = false; 771 772 auto GetFunctionName = [&]() { 773 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 774 // Skim off the details of whichever builtin was called to produce a better 775 // diagnostic, as it's unlikely that the user wrote the __builtin 776 // 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 return FunctionName; 784 }; 785 786 switch (BuiltinID) { 787 default: 788 return; 789 case Builtin::BI__builtin_strcpy: 790 case Builtin::BIstrcpy: { 791 DiagID = diag::warn_fortify_strlen_overflow; 792 SourceSize = ComputeStrLenArgument(1); 793 DestinationSize = ComputeSizeArgument(0); 794 break; 795 } 796 797 case Builtin::BI__builtin___strcpy_chk: { 798 DiagID = diag::warn_fortify_strlen_overflow; 799 SourceSize = ComputeStrLenArgument(1); 800 DestinationSize = ComputeExplicitObjectSizeArgument(2); 801 IsChkVariant = true; 802 break; 803 } 804 805 case Builtin::BIscanf: 806 case Builtin::BIfscanf: 807 case Builtin::BIsscanf: { 808 unsigned FormatIndex = 1; 809 unsigned DataIndex = 2; 810 if (BuiltinID == Builtin::BIscanf) { 811 FormatIndex = 0; 812 DataIndex = 1; 813 } 814 815 const auto *FormatExpr = 816 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 817 818 const auto *Format = dyn_cast<StringLiteral>(FormatExpr); 819 if (!Format) 820 return; 821 822 if (!Format->isAscii() && !Format->isUTF8()) 823 return; 824 825 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize, 826 unsigned SourceSize) { 827 DiagID = diag::warn_fortify_scanf_overflow; 828 unsigned Index = ArgIndex + DataIndex; 829 StringRef FunctionName = GetFunctionName(); 830 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall, 831 PDiag(DiagID) << FunctionName << (Index + 1) 832 << DestSize << SourceSize); 833 }; 834 835 StringRef FormatStrRef = Format->getString(); 836 auto ShiftedComputeSizeArgument = [&](unsigned Index) { 837 return ComputeSizeArgument(Index + DataIndex); 838 }; 839 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose); 840 const char *FormatBytes = FormatStrRef.data(); 841 const ConstantArrayType *T = 842 Context.getAsConstantArrayType(Format->getType()); 843 assert(T && "String literal not of constant array type!"); 844 size_t TypeSize = T->getSize().getZExtValue(); 845 846 // In case there's a null byte somewhere. 847 size_t StrLen = 848 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 849 850 analyze_format_string::ParseScanfString(H, FormatBytes, 851 FormatBytes + StrLen, getLangOpts(), 852 Context.getTargetInfo()); 853 854 // Unlike the other cases, in this one we have already issued the diagnostic 855 // here, so no need to continue (because unlike the other cases, here the 856 // diagnostic refers to the argument number). 857 return; 858 } 859 860 case Builtin::BIsprintf: 861 case Builtin::BI__builtin___sprintf_chk: { 862 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 863 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 864 865 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 866 867 if (!Format->isAscii() && !Format->isUTF8()) 868 return; 869 870 StringRef FormatStrRef = Format->getString(); 871 EstimateSizeFormatHandler H(FormatStrRef); 872 const char *FormatBytes = FormatStrRef.data(); 873 const ConstantArrayType *T = 874 Context.getAsConstantArrayType(Format->getType()); 875 assert(T && "String literal not of constant array type!"); 876 size_t TypeSize = T->getSize().getZExtValue(); 877 878 // In case there's a null byte somewhere. 879 size_t StrLen = 880 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 881 if (!analyze_format_string::ParsePrintfString( 882 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 883 Context.getTargetInfo(), false)) { 884 DiagID = diag::warn_fortify_source_format_overflow; 885 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 886 .extOrTrunc(SizeTypeWidth); 887 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 888 DestinationSize = ComputeExplicitObjectSizeArgument(2); 889 IsChkVariant = true; 890 } else { 891 DestinationSize = ComputeSizeArgument(0); 892 } 893 break; 894 } 895 } 896 return; 897 } 898 case Builtin::BI__builtin___memcpy_chk: 899 case Builtin::BI__builtin___memmove_chk: 900 case Builtin::BI__builtin___memset_chk: 901 case Builtin::BI__builtin___strlcat_chk: 902 case Builtin::BI__builtin___strlcpy_chk: 903 case Builtin::BI__builtin___strncat_chk: 904 case Builtin::BI__builtin___strncpy_chk: 905 case Builtin::BI__builtin___stpncpy_chk: 906 case Builtin::BI__builtin___memccpy_chk: 907 case Builtin::BI__builtin___mempcpy_chk: { 908 DiagID = diag::warn_builtin_chk_overflow; 909 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 910 DestinationSize = 911 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 912 IsChkVariant = true; 913 break; 914 } 915 916 case Builtin::BI__builtin___snprintf_chk: 917 case Builtin::BI__builtin___vsnprintf_chk: { 918 DiagID = diag::warn_builtin_chk_overflow; 919 SourceSize = ComputeExplicitObjectSizeArgument(1); 920 DestinationSize = ComputeExplicitObjectSizeArgument(3); 921 IsChkVariant = true; 922 break; 923 } 924 925 case Builtin::BIstrncat: 926 case Builtin::BI__builtin_strncat: 927 case Builtin::BIstrncpy: 928 case Builtin::BI__builtin_strncpy: 929 case Builtin::BIstpncpy: 930 case Builtin::BI__builtin_stpncpy: { 931 // Whether these functions overflow depends on the runtime strlen of the 932 // string, not just the buffer size, so emitting the "always overflow" 933 // diagnostic isn't quite right. We should still diagnose passing a buffer 934 // size larger than the destination buffer though; this is a runtime abort 935 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 936 DiagID = diag::warn_fortify_source_size_mismatch; 937 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 938 DestinationSize = ComputeSizeArgument(0); 939 break; 940 } 941 942 case Builtin::BImemcpy: 943 case Builtin::BI__builtin_memcpy: 944 case Builtin::BImemmove: 945 case Builtin::BI__builtin_memmove: 946 case Builtin::BImemset: 947 case Builtin::BI__builtin_memset: 948 case Builtin::BImempcpy: 949 case Builtin::BI__builtin_mempcpy: { 950 DiagID = diag::warn_fortify_source_overflow; 951 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 952 DestinationSize = ComputeSizeArgument(0); 953 break; 954 } 955 case Builtin::BIsnprintf: 956 case Builtin::BI__builtin_snprintf: 957 case Builtin::BIvsnprintf: 958 case Builtin::BI__builtin_vsnprintf: { 959 DiagID = diag::warn_fortify_source_size_mismatch; 960 SourceSize = ComputeExplicitObjectSizeArgument(1); 961 DestinationSize = ComputeSizeArgument(0); 962 break; 963 } 964 } 965 966 if (!SourceSize || !DestinationSize || 967 llvm::APSInt::compareValues(SourceSize.getValue(), 968 DestinationSize.getValue()) <= 0) 969 return; 970 971 StringRef FunctionName = GetFunctionName(); 972 973 SmallString<16> DestinationStr; 974 SmallString<16> SourceStr; 975 DestinationSize->toString(DestinationStr, /*Radix=*/10); 976 SourceSize->toString(SourceStr, /*Radix=*/10); 977 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 978 PDiag(DiagID) 979 << FunctionName << DestinationStr << SourceStr); 980 } 981 982 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 983 Scope::ScopeFlags NeededScopeFlags, 984 unsigned DiagID) { 985 // Scopes aren't available during instantiation. Fortunately, builtin 986 // functions cannot be template args so they cannot be formed through template 987 // instantiation. Therefore checking once during the parse is sufficient. 988 if (SemaRef.inTemplateInstantiation()) 989 return false; 990 991 Scope *S = SemaRef.getCurScope(); 992 while (S && !S->isSEHExceptScope()) 993 S = S->getParent(); 994 if (!S || !(S->getFlags() & NeededScopeFlags)) { 995 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 996 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 997 << DRE->getDecl()->getIdentifier(); 998 return true; 999 } 1000 1001 return false; 1002 } 1003 1004 static inline bool isBlockPointer(Expr *Arg) { 1005 return Arg->getType()->isBlockPointerType(); 1006 } 1007 1008 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 1009 /// void*, which is a requirement of device side enqueue. 1010 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 1011 const BlockPointerType *BPT = 1012 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 1013 ArrayRef<QualType> Params = 1014 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 1015 unsigned ArgCounter = 0; 1016 bool IllegalParams = false; 1017 // Iterate through the block parameters until either one is found that is not 1018 // a local void*, or the block is valid. 1019 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 1020 I != E; ++I, ++ArgCounter) { 1021 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 1022 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 1023 LangAS::opencl_local) { 1024 // Get the location of the error. If a block literal has been passed 1025 // (BlockExpr) then we can point straight to the offending argument, 1026 // else we just point to the variable reference. 1027 SourceLocation ErrorLoc; 1028 if (isa<BlockExpr>(BlockArg)) { 1029 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 1030 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 1031 } else if (isa<DeclRefExpr>(BlockArg)) { 1032 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 1033 } 1034 S.Diag(ErrorLoc, 1035 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 1036 IllegalParams = true; 1037 } 1038 } 1039 1040 return IllegalParams; 1041 } 1042 1043 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 1044 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 1045 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 1046 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 1047 return true; 1048 } 1049 return false; 1050 } 1051 1052 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 1053 if (checkArgCount(S, TheCall, 2)) 1054 return true; 1055 1056 if (checkOpenCLSubgroupExt(S, TheCall)) 1057 return true; 1058 1059 // First argument is an ndrange_t type. 1060 Expr *NDRangeArg = TheCall->getArg(0); 1061 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 1062 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1063 << TheCall->getDirectCallee() << "'ndrange_t'"; 1064 return true; 1065 } 1066 1067 Expr *BlockArg = TheCall->getArg(1); 1068 if (!isBlockPointer(BlockArg)) { 1069 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1070 << TheCall->getDirectCallee() << "block"; 1071 return true; 1072 } 1073 return checkOpenCLBlockArgs(S, BlockArg); 1074 } 1075 1076 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 1077 /// get_kernel_work_group_size 1078 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 1079 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 1080 if (checkArgCount(S, TheCall, 1)) 1081 return true; 1082 1083 Expr *BlockArg = TheCall->getArg(0); 1084 if (!isBlockPointer(BlockArg)) { 1085 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1086 << TheCall->getDirectCallee() << "block"; 1087 return true; 1088 } 1089 return checkOpenCLBlockArgs(S, BlockArg); 1090 } 1091 1092 /// Diagnose integer type and any valid implicit conversion to it. 1093 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 1094 const QualType &IntType); 1095 1096 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 1097 unsigned Start, unsigned End) { 1098 bool IllegalParams = false; 1099 for (unsigned I = Start; I <= End; ++I) 1100 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 1101 S.Context.getSizeType()); 1102 return IllegalParams; 1103 } 1104 1105 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 1106 /// 'local void*' parameter of passed block. 1107 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 1108 Expr *BlockArg, 1109 unsigned NumNonVarArgs) { 1110 const BlockPointerType *BPT = 1111 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 1112 unsigned NumBlockParams = 1113 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 1114 unsigned TotalNumArgs = TheCall->getNumArgs(); 1115 1116 // For each argument passed to the block, a corresponding uint needs to 1117 // be passed to describe the size of the local memory. 1118 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 1119 S.Diag(TheCall->getBeginLoc(), 1120 diag::err_opencl_enqueue_kernel_local_size_args); 1121 return true; 1122 } 1123 1124 // Check that the sizes of the local memory are specified by integers. 1125 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 1126 TotalNumArgs - 1); 1127 } 1128 1129 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 1130 /// overload formats specified in Table 6.13.17.1. 1131 /// int enqueue_kernel(queue_t queue, 1132 /// kernel_enqueue_flags_t flags, 1133 /// const ndrange_t ndrange, 1134 /// void (^block)(void)) 1135 /// int enqueue_kernel(queue_t queue, 1136 /// kernel_enqueue_flags_t flags, 1137 /// const ndrange_t ndrange, 1138 /// uint num_events_in_wait_list, 1139 /// clk_event_t *event_wait_list, 1140 /// clk_event_t *event_ret, 1141 /// void (^block)(void)) 1142 /// int enqueue_kernel(queue_t queue, 1143 /// kernel_enqueue_flags_t flags, 1144 /// const ndrange_t ndrange, 1145 /// void (^block)(local void*, ...), 1146 /// uint size0, ...) 1147 /// int enqueue_kernel(queue_t queue, 1148 /// kernel_enqueue_flags_t flags, 1149 /// const ndrange_t ndrange, 1150 /// uint num_events_in_wait_list, 1151 /// clk_event_t *event_wait_list, 1152 /// clk_event_t *event_ret, 1153 /// void (^block)(local void*, ...), 1154 /// uint size0, ...) 1155 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 1156 unsigned NumArgs = TheCall->getNumArgs(); 1157 1158 if (NumArgs < 4) { 1159 S.Diag(TheCall->getBeginLoc(), 1160 diag::err_typecheck_call_too_few_args_at_least) 1161 << 0 << 4 << NumArgs; 1162 return true; 1163 } 1164 1165 Expr *Arg0 = TheCall->getArg(0); 1166 Expr *Arg1 = TheCall->getArg(1); 1167 Expr *Arg2 = TheCall->getArg(2); 1168 Expr *Arg3 = TheCall->getArg(3); 1169 1170 // First argument always needs to be a queue_t type. 1171 if (!Arg0->getType()->isQueueT()) { 1172 S.Diag(TheCall->getArg(0)->getBeginLoc(), 1173 diag::err_opencl_builtin_expected_type) 1174 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 1175 return true; 1176 } 1177 1178 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 1179 if (!Arg1->getType()->isIntegerType()) { 1180 S.Diag(TheCall->getArg(1)->getBeginLoc(), 1181 diag::err_opencl_builtin_expected_type) 1182 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 1183 return true; 1184 } 1185 1186 // Third argument is always an ndrange_t type. 1187 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 1188 S.Diag(TheCall->getArg(2)->getBeginLoc(), 1189 diag::err_opencl_builtin_expected_type) 1190 << TheCall->getDirectCallee() << "'ndrange_t'"; 1191 return true; 1192 } 1193 1194 // With four arguments, there is only one form that the function could be 1195 // called in: no events and no variable arguments. 1196 if (NumArgs == 4) { 1197 // check that the last argument is the right block type. 1198 if (!isBlockPointer(Arg3)) { 1199 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1200 << TheCall->getDirectCallee() << "block"; 1201 return true; 1202 } 1203 // we have a block type, check the prototype 1204 const BlockPointerType *BPT = 1205 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1206 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1207 S.Diag(Arg3->getBeginLoc(), 1208 diag::err_opencl_enqueue_kernel_blocks_no_args); 1209 return true; 1210 } 1211 return false; 1212 } 1213 // we can have block + varargs. 1214 if (isBlockPointer(Arg3)) 1215 return (checkOpenCLBlockArgs(S, Arg3) || 1216 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1217 // last two cases with either exactly 7 args or 7 args and varargs. 1218 if (NumArgs >= 7) { 1219 // check common block argument. 1220 Expr *Arg6 = TheCall->getArg(6); 1221 if (!isBlockPointer(Arg6)) { 1222 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1223 << TheCall->getDirectCallee() << "block"; 1224 return true; 1225 } 1226 if (checkOpenCLBlockArgs(S, Arg6)) 1227 return true; 1228 1229 // Forth argument has to be any integer type. 1230 if (!Arg3->getType()->isIntegerType()) { 1231 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1232 diag::err_opencl_builtin_expected_type) 1233 << TheCall->getDirectCallee() << "integer"; 1234 return true; 1235 } 1236 // check remaining common arguments. 1237 Expr *Arg4 = TheCall->getArg(4); 1238 Expr *Arg5 = TheCall->getArg(5); 1239 1240 // Fifth argument is always passed as a pointer to clk_event_t. 1241 if (!Arg4->isNullPointerConstant(S.Context, 1242 Expr::NPC_ValueDependentIsNotNull) && 1243 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1244 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1245 diag::err_opencl_builtin_expected_type) 1246 << TheCall->getDirectCallee() 1247 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1248 return true; 1249 } 1250 1251 // Sixth argument is always passed as a pointer to clk_event_t. 1252 if (!Arg5->isNullPointerConstant(S.Context, 1253 Expr::NPC_ValueDependentIsNotNull) && 1254 !(Arg5->getType()->isPointerType() && 1255 Arg5->getType()->getPointeeType()->isClkEventT())) { 1256 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1257 diag::err_opencl_builtin_expected_type) 1258 << TheCall->getDirectCallee() 1259 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1260 return true; 1261 } 1262 1263 if (NumArgs == 7) 1264 return false; 1265 1266 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1267 } 1268 1269 // None of the specific case has been detected, give generic error 1270 S.Diag(TheCall->getBeginLoc(), 1271 diag::err_opencl_enqueue_kernel_incorrect_args); 1272 return true; 1273 } 1274 1275 /// Returns OpenCL access qual. 1276 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1277 return D->getAttr<OpenCLAccessAttr>(); 1278 } 1279 1280 /// Returns true if pipe element type is different from the pointer. 1281 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1282 const Expr *Arg0 = Call->getArg(0); 1283 // First argument type should always be pipe. 1284 if (!Arg0->getType()->isPipeType()) { 1285 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1286 << Call->getDirectCallee() << Arg0->getSourceRange(); 1287 return true; 1288 } 1289 OpenCLAccessAttr *AccessQual = 1290 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1291 // Validates the access qualifier is compatible with the call. 1292 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1293 // read_only and write_only, and assumed to be read_only if no qualifier is 1294 // specified. 1295 switch (Call->getDirectCallee()->getBuiltinID()) { 1296 case Builtin::BIread_pipe: 1297 case Builtin::BIreserve_read_pipe: 1298 case Builtin::BIcommit_read_pipe: 1299 case Builtin::BIwork_group_reserve_read_pipe: 1300 case Builtin::BIsub_group_reserve_read_pipe: 1301 case Builtin::BIwork_group_commit_read_pipe: 1302 case Builtin::BIsub_group_commit_read_pipe: 1303 if (!(!AccessQual || AccessQual->isReadOnly())) { 1304 S.Diag(Arg0->getBeginLoc(), 1305 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1306 << "read_only" << Arg0->getSourceRange(); 1307 return true; 1308 } 1309 break; 1310 case Builtin::BIwrite_pipe: 1311 case Builtin::BIreserve_write_pipe: 1312 case Builtin::BIcommit_write_pipe: 1313 case Builtin::BIwork_group_reserve_write_pipe: 1314 case Builtin::BIsub_group_reserve_write_pipe: 1315 case Builtin::BIwork_group_commit_write_pipe: 1316 case Builtin::BIsub_group_commit_write_pipe: 1317 if (!(AccessQual && AccessQual->isWriteOnly())) { 1318 S.Diag(Arg0->getBeginLoc(), 1319 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1320 << "write_only" << Arg0->getSourceRange(); 1321 return true; 1322 } 1323 break; 1324 default: 1325 break; 1326 } 1327 return false; 1328 } 1329 1330 /// Returns true if pipe element type is different from the pointer. 1331 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1332 const Expr *Arg0 = Call->getArg(0); 1333 const Expr *ArgIdx = Call->getArg(Idx); 1334 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1335 const QualType EltTy = PipeTy->getElementType(); 1336 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1337 // The Idx argument should be a pointer and the type of the pointer and 1338 // the type of pipe element should also be the same. 1339 if (!ArgTy || 1340 !S.Context.hasSameType( 1341 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1342 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1343 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1344 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1345 return true; 1346 } 1347 return false; 1348 } 1349 1350 // Performs semantic analysis for the read/write_pipe call. 1351 // \param S Reference to the semantic analyzer. 1352 // \param Call A pointer to the builtin call. 1353 // \return True if a semantic error has been found, false otherwise. 1354 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1355 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1356 // functions have two forms. 1357 switch (Call->getNumArgs()) { 1358 case 2: 1359 if (checkOpenCLPipeArg(S, Call)) 1360 return true; 1361 // The call with 2 arguments should be 1362 // read/write_pipe(pipe T, T*). 1363 // Check packet type T. 1364 if (checkOpenCLPipePacketType(S, Call, 1)) 1365 return true; 1366 break; 1367 1368 case 4: { 1369 if (checkOpenCLPipeArg(S, Call)) 1370 return true; 1371 // The call with 4 arguments should be 1372 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1373 // Check reserve_id_t. 1374 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1375 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1376 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1377 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1378 return true; 1379 } 1380 1381 // Check the index. 1382 const Expr *Arg2 = Call->getArg(2); 1383 if (!Arg2->getType()->isIntegerType() && 1384 !Arg2->getType()->isUnsignedIntegerType()) { 1385 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1386 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1387 << Arg2->getType() << Arg2->getSourceRange(); 1388 return true; 1389 } 1390 1391 // Check packet type T. 1392 if (checkOpenCLPipePacketType(S, Call, 3)) 1393 return true; 1394 } break; 1395 default: 1396 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1397 << Call->getDirectCallee() << Call->getSourceRange(); 1398 return true; 1399 } 1400 1401 return false; 1402 } 1403 1404 // Performs a semantic analysis on the {work_group_/sub_group_ 1405 // /_}reserve_{read/write}_pipe 1406 // \param S Reference to the semantic analyzer. 1407 // \param Call The call to the builtin function to be analyzed. 1408 // \return True if a semantic error was found, false otherwise. 1409 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1410 if (checkArgCount(S, Call, 2)) 1411 return true; 1412 1413 if (checkOpenCLPipeArg(S, Call)) 1414 return true; 1415 1416 // Check the reserve size. 1417 if (!Call->getArg(1)->getType()->isIntegerType() && 1418 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1419 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1420 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1421 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1422 return true; 1423 } 1424 1425 // Since return type of reserve_read/write_pipe built-in function is 1426 // reserve_id_t, which is not defined in the builtin def file , we used int 1427 // as return type and need to override the return type of these functions. 1428 Call->setType(S.Context.OCLReserveIDTy); 1429 1430 return false; 1431 } 1432 1433 // Performs a semantic analysis on {work_group_/sub_group_ 1434 // /_}commit_{read/write}_pipe 1435 // \param S Reference to the semantic analyzer. 1436 // \param Call The call to the builtin function to be analyzed. 1437 // \return True if a semantic error was found, false otherwise. 1438 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1439 if (checkArgCount(S, Call, 2)) 1440 return true; 1441 1442 if (checkOpenCLPipeArg(S, Call)) 1443 return true; 1444 1445 // Check reserve_id_t. 1446 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1447 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1448 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1449 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1450 return true; 1451 } 1452 1453 return false; 1454 } 1455 1456 // Performs a semantic analysis on the call to built-in Pipe 1457 // Query Functions. 1458 // \param S Reference to the semantic analyzer. 1459 // \param Call The call to the builtin function to be analyzed. 1460 // \return True if a semantic error was found, false otherwise. 1461 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1462 if (checkArgCount(S, Call, 1)) 1463 return true; 1464 1465 if (!Call->getArg(0)->getType()->isPipeType()) { 1466 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1467 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1468 return true; 1469 } 1470 1471 return false; 1472 } 1473 1474 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1475 // Performs semantic analysis for the to_global/local/private call. 1476 // \param S Reference to the semantic analyzer. 1477 // \param BuiltinID ID of the builtin function. 1478 // \param Call A pointer to the builtin call. 1479 // \return True if a semantic error has been found, false otherwise. 1480 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1481 CallExpr *Call) { 1482 if (checkArgCount(S, Call, 1)) 1483 return true; 1484 1485 auto RT = Call->getArg(0)->getType(); 1486 if (!RT->isPointerType() || RT->getPointeeType() 1487 .getAddressSpace() == LangAS::opencl_constant) { 1488 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1489 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1490 return true; 1491 } 1492 1493 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1494 S.Diag(Call->getArg(0)->getBeginLoc(), 1495 diag::warn_opencl_generic_address_space_arg) 1496 << Call->getDirectCallee()->getNameInfo().getAsString() 1497 << Call->getArg(0)->getSourceRange(); 1498 } 1499 1500 RT = RT->getPointeeType(); 1501 auto Qual = RT.getQualifiers(); 1502 switch (BuiltinID) { 1503 case Builtin::BIto_global: 1504 Qual.setAddressSpace(LangAS::opencl_global); 1505 break; 1506 case Builtin::BIto_local: 1507 Qual.setAddressSpace(LangAS::opencl_local); 1508 break; 1509 case Builtin::BIto_private: 1510 Qual.setAddressSpace(LangAS::opencl_private); 1511 break; 1512 default: 1513 llvm_unreachable("Invalid builtin function"); 1514 } 1515 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1516 RT.getUnqualifiedType(), Qual))); 1517 1518 return false; 1519 } 1520 1521 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1522 if (checkArgCount(S, TheCall, 1)) 1523 return ExprError(); 1524 1525 // Compute __builtin_launder's parameter type from the argument. 1526 // The parameter type is: 1527 // * The type of the argument if it's not an array or function type, 1528 // Otherwise, 1529 // * The decayed argument type. 1530 QualType ParamTy = [&]() { 1531 QualType ArgTy = TheCall->getArg(0)->getType(); 1532 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1533 return S.Context.getPointerType(Ty->getElementType()); 1534 if (ArgTy->isFunctionType()) { 1535 return S.Context.getPointerType(ArgTy); 1536 } 1537 return ArgTy; 1538 }(); 1539 1540 TheCall->setType(ParamTy); 1541 1542 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1543 if (!ParamTy->isPointerType()) 1544 return 0; 1545 if (ParamTy->isFunctionPointerType()) 1546 return 1; 1547 if (ParamTy->isVoidPointerType()) 1548 return 2; 1549 return llvm::Optional<unsigned>{}; 1550 }(); 1551 if (DiagSelect.hasValue()) { 1552 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1553 << DiagSelect.getValue() << TheCall->getSourceRange(); 1554 return ExprError(); 1555 } 1556 1557 // We either have an incomplete class type, or we have a class template 1558 // whose instantiation has not been forced. Example: 1559 // 1560 // template <class T> struct Foo { T value; }; 1561 // Foo<int> *p = nullptr; 1562 // auto *d = __builtin_launder(p); 1563 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1564 diag::err_incomplete_type)) 1565 return ExprError(); 1566 1567 assert(ParamTy->getPointeeType()->isObjectType() && 1568 "Unhandled non-object pointer case"); 1569 1570 InitializedEntity Entity = 1571 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1572 ExprResult Arg = 1573 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1574 if (Arg.isInvalid()) 1575 return ExprError(); 1576 TheCall->setArg(0, Arg.get()); 1577 1578 return TheCall; 1579 } 1580 1581 // Emit an error and return true if the current architecture is not in the list 1582 // of supported architectures. 1583 static bool 1584 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1585 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1586 llvm::Triple::ArchType CurArch = 1587 S.getASTContext().getTargetInfo().getTriple().getArch(); 1588 if (llvm::is_contained(SupportedArchs, CurArch)) 1589 return false; 1590 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1591 << TheCall->getSourceRange(); 1592 return true; 1593 } 1594 1595 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1596 SourceLocation CallSiteLoc); 1597 1598 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1599 CallExpr *TheCall) { 1600 switch (TI.getTriple().getArch()) { 1601 default: 1602 // Some builtins don't require additional checking, so just consider these 1603 // acceptable. 1604 return false; 1605 case llvm::Triple::arm: 1606 case llvm::Triple::armeb: 1607 case llvm::Triple::thumb: 1608 case llvm::Triple::thumbeb: 1609 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1610 case llvm::Triple::aarch64: 1611 case llvm::Triple::aarch64_32: 1612 case llvm::Triple::aarch64_be: 1613 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1614 case llvm::Triple::bpfeb: 1615 case llvm::Triple::bpfel: 1616 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1617 case llvm::Triple::hexagon: 1618 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1619 case llvm::Triple::mips: 1620 case llvm::Triple::mipsel: 1621 case llvm::Triple::mips64: 1622 case llvm::Triple::mips64el: 1623 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1624 case llvm::Triple::systemz: 1625 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1626 case llvm::Triple::x86: 1627 case llvm::Triple::x86_64: 1628 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1629 case llvm::Triple::ppc: 1630 case llvm::Triple::ppcle: 1631 case llvm::Triple::ppc64: 1632 case llvm::Triple::ppc64le: 1633 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1634 case llvm::Triple::amdgcn: 1635 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1636 case llvm::Triple::riscv32: 1637 case llvm::Triple::riscv64: 1638 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1639 } 1640 } 1641 1642 ExprResult 1643 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1644 CallExpr *TheCall) { 1645 ExprResult TheCallResult(TheCall); 1646 1647 // Find out if any arguments are required to be integer constant expressions. 1648 unsigned ICEArguments = 0; 1649 ASTContext::GetBuiltinTypeError Error; 1650 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1651 if (Error != ASTContext::GE_None) 1652 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1653 1654 // If any arguments are required to be ICE's, check and diagnose. 1655 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1656 // Skip arguments not required to be ICE's. 1657 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1658 1659 llvm::APSInt Result; 1660 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1661 return true; 1662 ICEArguments &= ~(1 << ArgNo); 1663 } 1664 1665 switch (BuiltinID) { 1666 case Builtin::BI__builtin___CFStringMakeConstantString: 1667 assert(TheCall->getNumArgs() == 1 && 1668 "Wrong # arguments to builtin CFStringMakeConstantString"); 1669 if (CheckObjCString(TheCall->getArg(0))) 1670 return ExprError(); 1671 break; 1672 case Builtin::BI__builtin_ms_va_start: 1673 case Builtin::BI__builtin_stdarg_start: 1674 case Builtin::BI__builtin_va_start: 1675 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1676 return ExprError(); 1677 break; 1678 case Builtin::BI__va_start: { 1679 switch (Context.getTargetInfo().getTriple().getArch()) { 1680 case llvm::Triple::aarch64: 1681 case llvm::Triple::arm: 1682 case llvm::Triple::thumb: 1683 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1684 return ExprError(); 1685 break; 1686 default: 1687 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1688 return ExprError(); 1689 break; 1690 } 1691 break; 1692 } 1693 1694 // The acquire, release, and no fence variants are ARM and AArch64 only. 1695 case Builtin::BI_interlockedbittestandset_acq: 1696 case Builtin::BI_interlockedbittestandset_rel: 1697 case Builtin::BI_interlockedbittestandset_nf: 1698 case Builtin::BI_interlockedbittestandreset_acq: 1699 case Builtin::BI_interlockedbittestandreset_rel: 1700 case Builtin::BI_interlockedbittestandreset_nf: 1701 if (CheckBuiltinTargetSupport( 1702 *this, BuiltinID, TheCall, 1703 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1704 return ExprError(); 1705 break; 1706 1707 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1708 case Builtin::BI_bittest64: 1709 case Builtin::BI_bittestandcomplement64: 1710 case Builtin::BI_bittestandreset64: 1711 case Builtin::BI_bittestandset64: 1712 case Builtin::BI_interlockedbittestandreset64: 1713 case Builtin::BI_interlockedbittestandset64: 1714 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1715 {llvm::Triple::x86_64, llvm::Triple::arm, 1716 llvm::Triple::thumb, llvm::Triple::aarch64})) 1717 return ExprError(); 1718 break; 1719 1720 case Builtin::BI__builtin_isgreater: 1721 case Builtin::BI__builtin_isgreaterequal: 1722 case Builtin::BI__builtin_isless: 1723 case Builtin::BI__builtin_islessequal: 1724 case Builtin::BI__builtin_islessgreater: 1725 case Builtin::BI__builtin_isunordered: 1726 if (SemaBuiltinUnorderedCompare(TheCall)) 1727 return ExprError(); 1728 break; 1729 case Builtin::BI__builtin_fpclassify: 1730 if (SemaBuiltinFPClassification(TheCall, 6)) 1731 return ExprError(); 1732 break; 1733 case Builtin::BI__builtin_isfinite: 1734 case Builtin::BI__builtin_isinf: 1735 case Builtin::BI__builtin_isinf_sign: 1736 case Builtin::BI__builtin_isnan: 1737 case Builtin::BI__builtin_isnormal: 1738 case Builtin::BI__builtin_signbit: 1739 case Builtin::BI__builtin_signbitf: 1740 case Builtin::BI__builtin_signbitl: 1741 if (SemaBuiltinFPClassification(TheCall, 1)) 1742 return ExprError(); 1743 break; 1744 case Builtin::BI__builtin_shufflevector: 1745 return SemaBuiltinShuffleVector(TheCall); 1746 // TheCall will be freed by the smart pointer here, but that's fine, since 1747 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1748 case Builtin::BI__builtin_prefetch: 1749 if (SemaBuiltinPrefetch(TheCall)) 1750 return ExprError(); 1751 break; 1752 case Builtin::BI__builtin_alloca_with_align: 1753 if (SemaBuiltinAllocaWithAlign(TheCall)) 1754 return ExprError(); 1755 LLVM_FALLTHROUGH; 1756 case Builtin::BI__builtin_alloca: 1757 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1758 << TheCall->getDirectCallee(); 1759 break; 1760 case Builtin::BI__arithmetic_fence: 1761 if (SemaBuiltinArithmeticFence(TheCall)) 1762 return ExprError(); 1763 break; 1764 case Builtin::BI__assume: 1765 case Builtin::BI__builtin_assume: 1766 if (SemaBuiltinAssume(TheCall)) 1767 return ExprError(); 1768 break; 1769 case Builtin::BI__builtin_assume_aligned: 1770 if (SemaBuiltinAssumeAligned(TheCall)) 1771 return ExprError(); 1772 break; 1773 case Builtin::BI__builtin_dynamic_object_size: 1774 case Builtin::BI__builtin_object_size: 1775 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1776 return ExprError(); 1777 break; 1778 case Builtin::BI__builtin_longjmp: 1779 if (SemaBuiltinLongjmp(TheCall)) 1780 return ExprError(); 1781 break; 1782 case Builtin::BI__builtin_setjmp: 1783 if (SemaBuiltinSetjmp(TheCall)) 1784 return ExprError(); 1785 break; 1786 case Builtin::BI__builtin_classify_type: 1787 if (checkArgCount(*this, TheCall, 1)) return true; 1788 TheCall->setType(Context.IntTy); 1789 break; 1790 case Builtin::BI__builtin_complex: 1791 if (SemaBuiltinComplex(TheCall)) 1792 return ExprError(); 1793 break; 1794 case Builtin::BI__builtin_constant_p: { 1795 if (checkArgCount(*this, TheCall, 1)) return true; 1796 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1797 if (Arg.isInvalid()) return true; 1798 TheCall->setArg(0, Arg.get()); 1799 TheCall->setType(Context.IntTy); 1800 break; 1801 } 1802 case Builtin::BI__builtin_launder: 1803 return SemaBuiltinLaunder(*this, TheCall); 1804 case Builtin::BI__sync_fetch_and_add: 1805 case Builtin::BI__sync_fetch_and_add_1: 1806 case Builtin::BI__sync_fetch_and_add_2: 1807 case Builtin::BI__sync_fetch_and_add_4: 1808 case Builtin::BI__sync_fetch_and_add_8: 1809 case Builtin::BI__sync_fetch_and_add_16: 1810 case Builtin::BI__sync_fetch_and_sub: 1811 case Builtin::BI__sync_fetch_and_sub_1: 1812 case Builtin::BI__sync_fetch_and_sub_2: 1813 case Builtin::BI__sync_fetch_and_sub_4: 1814 case Builtin::BI__sync_fetch_and_sub_8: 1815 case Builtin::BI__sync_fetch_and_sub_16: 1816 case Builtin::BI__sync_fetch_and_or: 1817 case Builtin::BI__sync_fetch_and_or_1: 1818 case Builtin::BI__sync_fetch_and_or_2: 1819 case Builtin::BI__sync_fetch_and_or_4: 1820 case Builtin::BI__sync_fetch_and_or_8: 1821 case Builtin::BI__sync_fetch_and_or_16: 1822 case Builtin::BI__sync_fetch_and_and: 1823 case Builtin::BI__sync_fetch_and_and_1: 1824 case Builtin::BI__sync_fetch_and_and_2: 1825 case Builtin::BI__sync_fetch_and_and_4: 1826 case Builtin::BI__sync_fetch_and_and_8: 1827 case Builtin::BI__sync_fetch_and_and_16: 1828 case Builtin::BI__sync_fetch_and_xor: 1829 case Builtin::BI__sync_fetch_and_xor_1: 1830 case Builtin::BI__sync_fetch_and_xor_2: 1831 case Builtin::BI__sync_fetch_and_xor_4: 1832 case Builtin::BI__sync_fetch_and_xor_8: 1833 case Builtin::BI__sync_fetch_and_xor_16: 1834 case Builtin::BI__sync_fetch_and_nand: 1835 case Builtin::BI__sync_fetch_and_nand_1: 1836 case Builtin::BI__sync_fetch_and_nand_2: 1837 case Builtin::BI__sync_fetch_and_nand_4: 1838 case Builtin::BI__sync_fetch_and_nand_8: 1839 case Builtin::BI__sync_fetch_and_nand_16: 1840 case Builtin::BI__sync_add_and_fetch: 1841 case Builtin::BI__sync_add_and_fetch_1: 1842 case Builtin::BI__sync_add_and_fetch_2: 1843 case Builtin::BI__sync_add_and_fetch_4: 1844 case Builtin::BI__sync_add_and_fetch_8: 1845 case Builtin::BI__sync_add_and_fetch_16: 1846 case Builtin::BI__sync_sub_and_fetch: 1847 case Builtin::BI__sync_sub_and_fetch_1: 1848 case Builtin::BI__sync_sub_and_fetch_2: 1849 case Builtin::BI__sync_sub_and_fetch_4: 1850 case Builtin::BI__sync_sub_and_fetch_8: 1851 case Builtin::BI__sync_sub_and_fetch_16: 1852 case Builtin::BI__sync_and_and_fetch: 1853 case Builtin::BI__sync_and_and_fetch_1: 1854 case Builtin::BI__sync_and_and_fetch_2: 1855 case Builtin::BI__sync_and_and_fetch_4: 1856 case Builtin::BI__sync_and_and_fetch_8: 1857 case Builtin::BI__sync_and_and_fetch_16: 1858 case Builtin::BI__sync_or_and_fetch: 1859 case Builtin::BI__sync_or_and_fetch_1: 1860 case Builtin::BI__sync_or_and_fetch_2: 1861 case Builtin::BI__sync_or_and_fetch_4: 1862 case Builtin::BI__sync_or_and_fetch_8: 1863 case Builtin::BI__sync_or_and_fetch_16: 1864 case Builtin::BI__sync_xor_and_fetch: 1865 case Builtin::BI__sync_xor_and_fetch_1: 1866 case Builtin::BI__sync_xor_and_fetch_2: 1867 case Builtin::BI__sync_xor_and_fetch_4: 1868 case Builtin::BI__sync_xor_and_fetch_8: 1869 case Builtin::BI__sync_xor_and_fetch_16: 1870 case Builtin::BI__sync_nand_and_fetch: 1871 case Builtin::BI__sync_nand_and_fetch_1: 1872 case Builtin::BI__sync_nand_and_fetch_2: 1873 case Builtin::BI__sync_nand_and_fetch_4: 1874 case Builtin::BI__sync_nand_and_fetch_8: 1875 case Builtin::BI__sync_nand_and_fetch_16: 1876 case Builtin::BI__sync_val_compare_and_swap: 1877 case Builtin::BI__sync_val_compare_and_swap_1: 1878 case Builtin::BI__sync_val_compare_and_swap_2: 1879 case Builtin::BI__sync_val_compare_and_swap_4: 1880 case Builtin::BI__sync_val_compare_and_swap_8: 1881 case Builtin::BI__sync_val_compare_and_swap_16: 1882 case Builtin::BI__sync_bool_compare_and_swap: 1883 case Builtin::BI__sync_bool_compare_and_swap_1: 1884 case Builtin::BI__sync_bool_compare_and_swap_2: 1885 case Builtin::BI__sync_bool_compare_and_swap_4: 1886 case Builtin::BI__sync_bool_compare_and_swap_8: 1887 case Builtin::BI__sync_bool_compare_and_swap_16: 1888 case Builtin::BI__sync_lock_test_and_set: 1889 case Builtin::BI__sync_lock_test_and_set_1: 1890 case Builtin::BI__sync_lock_test_and_set_2: 1891 case Builtin::BI__sync_lock_test_and_set_4: 1892 case Builtin::BI__sync_lock_test_and_set_8: 1893 case Builtin::BI__sync_lock_test_and_set_16: 1894 case Builtin::BI__sync_lock_release: 1895 case Builtin::BI__sync_lock_release_1: 1896 case Builtin::BI__sync_lock_release_2: 1897 case Builtin::BI__sync_lock_release_4: 1898 case Builtin::BI__sync_lock_release_8: 1899 case Builtin::BI__sync_lock_release_16: 1900 case Builtin::BI__sync_swap: 1901 case Builtin::BI__sync_swap_1: 1902 case Builtin::BI__sync_swap_2: 1903 case Builtin::BI__sync_swap_4: 1904 case Builtin::BI__sync_swap_8: 1905 case Builtin::BI__sync_swap_16: 1906 return SemaBuiltinAtomicOverloaded(TheCallResult); 1907 case Builtin::BI__sync_synchronize: 1908 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1909 << TheCall->getCallee()->getSourceRange(); 1910 break; 1911 case Builtin::BI__builtin_nontemporal_load: 1912 case Builtin::BI__builtin_nontemporal_store: 1913 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1914 case Builtin::BI__builtin_memcpy_inline: { 1915 clang::Expr *SizeOp = TheCall->getArg(2); 1916 // We warn about copying to or from `nullptr` pointers when `size` is 1917 // greater than 0. When `size` is value dependent we cannot evaluate its 1918 // value so we bail out. 1919 if (SizeOp->isValueDependent()) 1920 break; 1921 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) { 1922 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1923 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1924 } 1925 break; 1926 } 1927 #define BUILTIN(ID, TYPE, ATTRS) 1928 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1929 case Builtin::BI##ID: \ 1930 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1931 #include "clang/Basic/Builtins.def" 1932 case Builtin::BI__annotation: 1933 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1934 return ExprError(); 1935 break; 1936 case Builtin::BI__builtin_annotation: 1937 if (SemaBuiltinAnnotation(*this, TheCall)) 1938 return ExprError(); 1939 break; 1940 case Builtin::BI__builtin_addressof: 1941 if (SemaBuiltinAddressof(*this, TheCall)) 1942 return ExprError(); 1943 break; 1944 case Builtin::BI__builtin_function_start: 1945 if (SemaBuiltinFunctionStart(*this, TheCall)) 1946 return ExprError(); 1947 break; 1948 case Builtin::BI__builtin_is_aligned: 1949 case Builtin::BI__builtin_align_up: 1950 case Builtin::BI__builtin_align_down: 1951 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1952 return ExprError(); 1953 break; 1954 case Builtin::BI__builtin_add_overflow: 1955 case Builtin::BI__builtin_sub_overflow: 1956 case Builtin::BI__builtin_mul_overflow: 1957 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1958 return ExprError(); 1959 break; 1960 case Builtin::BI__builtin_operator_new: 1961 case Builtin::BI__builtin_operator_delete: { 1962 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1963 ExprResult Res = 1964 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1965 if (Res.isInvalid()) 1966 CorrectDelayedTyposInExpr(TheCallResult.get()); 1967 return Res; 1968 } 1969 case Builtin::BI__builtin_dump_struct: { 1970 // We first want to ensure we are called with 2 arguments 1971 if (checkArgCount(*this, TheCall, 2)) 1972 return ExprError(); 1973 // Ensure that the first argument is of type 'struct XX *' 1974 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1975 const QualType PtrArgType = PtrArg->getType(); 1976 if (!PtrArgType->isPointerType() || 1977 !PtrArgType->getPointeeType()->isRecordType()) { 1978 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1979 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1980 << "structure pointer"; 1981 return ExprError(); 1982 } 1983 1984 // Ensure that the second argument is of type 'FunctionType' 1985 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1986 const QualType FnPtrArgType = FnPtrArg->getType(); 1987 if (!FnPtrArgType->isPointerType()) { 1988 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1989 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1990 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1991 return ExprError(); 1992 } 1993 1994 const auto *FuncType = 1995 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1996 1997 if (!FuncType) { 1998 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1999 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 2000 << FnPtrArgType << "'int (*)(const char *, ...)'"; 2001 return ExprError(); 2002 } 2003 2004 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 2005 if (!FT->getNumParams()) { 2006 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 2007 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 2008 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 2009 return ExprError(); 2010 } 2011 QualType PT = FT->getParamType(0); 2012 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 2013 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 2014 !PT->getPointeeType().isConstQualified()) { 2015 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 2016 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 2017 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 2018 return ExprError(); 2019 } 2020 } 2021 2022 TheCall->setType(Context.IntTy); 2023 break; 2024 } 2025 case Builtin::BI__builtin_expect_with_probability: { 2026 // We first want to ensure we are called with 3 arguments 2027 if (checkArgCount(*this, TheCall, 3)) 2028 return ExprError(); 2029 // then check probability is constant float in range [0.0, 1.0] 2030 const Expr *ProbArg = TheCall->getArg(2); 2031 SmallVector<PartialDiagnosticAt, 8> Notes; 2032 Expr::EvalResult Eval; 2033 Eval.Diag = &Notes; 2034 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 2035 !Eval.Val.isFloat()) { 2036 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 2037 << ProbArg->getSourceRange(); 2038 for (const PartialDiagnosticAt &PDiag : Notes) 2039 Diag(PDiag.first, PDiag.second); 2040 return ExprError(); 2041 } 2042 llvm::APFloat Probability = Eval.Val.getFloat(); 2043 bool LoseInfo = false; 2044 Probability.convert(llvm::APFloat::IEEEdouble(), 2045 llvm::RoundingMode::Dynamic, &LoseInfo); 2046 if (!(Probability >= llvm::APFloat(0.0) && 2047 Probability <= llvm::APFloat(1.0))) { 2048 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 2049 << ProbArg->getSourceRange(); 2050 return ExprError(); 2051 } 2052 break; 2053 } 2054 case Builtin::BI__builtin_preserve_access_index: 2055 if (SemaBuiltinPreserveAI(*this, TheCall)) 2056 return ExprError(); 2057 break; 2058 case Builtin::BI__builtin_call_with_static_chain: 2059 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 2060 return ExprError(); 2061 break; 2062 case Builtin::BI__exception_code: 2063 case Builtin::BI_exception_code: 2064 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 2065 diag::err_seh___except_block)) 2066 return ExprError(); 2067 break; 2068 case Builtin::BI__exception_info: 2069 case Builtin::BI_exception_info: 2070 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 2071 diag::err_seh___except_filter)) 2072 return ExprError(); 2073 break; 2074 case Builtin::BI__GetExceptionInfo: 2075 if (checkArgCount(*this, TheCall, 1)) 2076 return ExprError(); 2077 2078 if (CheckCXXThrowOperand( 2079 TheCall->getBeginLoc(), 2080 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 2081 TheCall)) 2082 return ExprError(); 2083 2084 TheCall->setType(Context.VoidPtrTy); 2085 break; 2086 // OpenCL v2.0, s6.13.16 - Pipe functions 2087 case Builtin::BIread_pipe: 2088 case Builtin::BIwrite_pipe: 2089 // Since those two functions are declared with var args, we need a semantic 2090 // check for the argument. 2091 if (SemaBuiltinRWPipe(*this, TheCall)) 2092 return ExprError(); 2093 break; 2094 case Builtin::BIreserve_read_pipe: 2095 case Builtin::BIreserve_write_pipe: 2096 case Builtin::BIwork_group_reserve_read_pipe: 2097 case Builtin::BIwork_group_reserve_write_pipe: 2098 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 2099 return ExprError(); 2100 break; 2101 case Builtin::BIsub_group_reserve_read_pipe: 2102 case Builtin::BIsub_group_reserve_write_pipe: 2103 if (checkOpenCLSubgroupExt(*this, TheCall) || 2104 SemaBuiltinReserveRWPipe(*this, TheCall)) 2105 return ExprError(); 2106 break; 2107 case Builtin::BIcommit_read_pipe: 2108 case Builtin::BIcommit_write_pipe: 2109 case Builtin::BIwork_group_commit_read_pipe: 2110 case Builtin::BIwork_group_commit_write_pipe: 2111 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 2112 return ExprError(); 2113 break; 2114 case Builtin::BIsub_group_commit_read_pipe: 2115 case Builtin::BIsub_group_commit_write_pipe: 2116 if (checkOpenCLSubgroupExt(*this, TheCall) || 2117 SemaBuiltinCommitRWPipe(*this, TheCall)) 2118 return ExprError(); 2119 break; 2120 case Builtin::BIget_pipe_num_packets: 2121 case Builtin::BIget_pipe_max_packets: 2122 if (SemaBuiltinPipePackets(*this, TheCall)) 2123 return ExprError(); 2124 break; 2125 case Builtin::BIto_global: 2126 case Builtin::BIto_local: 2127 case Builtin::BIto_private: 2128 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 2129 return ExprError(); 2130 break; 2131 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 2132 case Builtin::BIenqueue_kernel: 2133 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 2134 return ExprError(); 2135 break; 2136 case Builtin::BIget_kernel_work_group_size: 2137 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 2138 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 2139 return ExprError(); 2140 break; 2141 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 2142 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 2143 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 2144 return ExprError(); 2145 break; 2146 case Builtin::BI__builtin_os_log_format: 2147 Cleanup.setExprNeedsCleanups(true); 2148 LLVM_FALLTHROUGH; 2149 case Builtin::BI__builtin_os_log_format_buffer_size: 2150 if (SemaBuiltinOSLogFormat(TheCall)) 2151 return ExprError(); 2152 break; 2153 case Builtin::BI__builtin_frame_address: 2154 case Builtin::BI__builtin_return_address: { 2155 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 2156 return ExprError(); 2157 2158 // -Wframe-address warning if non-zero passed to builtin 2159 // return/frame address. 2160 Expr::EvalResult Result; 2161 if (!TheCall->getArg(0)->isValueDependent() && 2162 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 2163 Result.Val.getInt() != 0) 2164 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 2165 << ((BuiltinID == Builtin::BI__builtin_return_address) 2166 ? "__builtin_return_address" 2167 : "__builtin_frame_address") 2168 << TheCall->getSourceRange(); 2169 break; 2170 } 2171 2172 // __builtin_elementwise_abs restricts the element type to signed integers or 2173 // floating point types only. 2174 case Builtin::BI__builtin_elementwise_abs: { 2175 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall)) 2176 return ExprError(); 2177 2178 QualType ArgTy = TheCall->getArg(0)->getType(); 2179 QualType EltTy = ArgTy; 2180 2181 if (auto *VecTy = EltTy->getAs<VectorType>()) 2182 EltTy = VecTy->getElementType(); 2183 if (EltTy->isUnsignedIntegerType()) { 2184 Diag(TheCall->getArg(0)->getBeginLoc(), 2185 diag::err_builtin_invalid_arg_type) 2186 << 1 << /* signed integer or float ty*/ 3 << ArgTy; 2187 return ExprError(); 2188 } 2189 break; 2190 } 2191 2192 // __builtin_elementwise_ceil restricts the element type to floating point 2193 // types only. 2194 case Builtin::BI__builtin_elementwise_ceil: { 2195 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall)) 2196 return ExprError(); 2197 2198 QualType ArgTy = TheCall->getArg(0)->getType(); 2199 QualType EltTy = ArgTy; 2200 2201 if (auto *VecTy = EltTy->getAs<VectorType>()) 2202 EltTy = VecTy->getElementType(); 2203 if (!EltTy->isFloatingType()) { 2204 Diag(TheCall->getArg(0)->getBeginLoc(), 2205 diag::err_builtin_invalid_arg_type) 2206 << 1 << /* float ty*/ 5 << ArgTy; 2207 2208 return ExprError(); 2209 } 2210 break; 2211 } 2212 2213 case Builtin::BI__builtin_elementwise_min: 2214 case Builtin::BI__builtin_elementwise_max: 2215 if (SemaBuiltinElementwiseMath(TheCall)) 2216 return ExprError(); 2217 break; 2218 case Builtin::BI__builtin_reduce_max: 2219 case Builtin::BI__builtin_reduce_min: 2220 if (SemaBuiltinReduceMath(TheCall)) 2221 return ExprError(); 2222 break; 2223 case Builtin::BI__builtin_matrix_transpose: 2224 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 2225 2226 case Builtin::BI__builtin_matrix_column_major_load: 2227 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 2228 2229 case Builtin::BI__builtin_matrix_column_major_store: 2230 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 2231 2232 case Builtin::BI__builtin_get_device_side_mangled_name: { 2233 auto Check = [](CallExpr *TheCall) { 2234 if (TheCall->getNumArgs() != 1) 2235 return false; 2236 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 2237 if (!DRE) 2238 return false; 2239 auto *D = DRE->getDecl(); 2240 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 2241 return false; 2242 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 2243 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2244 }; 2245 if (!Check(TheCall)) { 2246 Diag(TheCall->getBeginLoc(), 2247 diag::err_hip_invalid_args_builtin_mangled_name); 2248 return ExprError(); 2249 } 2250 } 2251 } 2252 2253 // Since the target specific builtins for each arch overlap, only check those 2254 // of the arch we are compiling for. 2255 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2256 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2257 assert(Context.getAuxTargetInfo() && 2258 "Aux Target Builtin, but not an aux target?"); 2259 2260 if (CheckTSBuiltinFunctionCall( 2261 *Context.getAuxTargetInfo(), 2262 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2263 return ExprError(); 2264 } else { 2265 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2266 TheCall)) 2267 return ExprError(); 2268 } 2269 } 2270 2271 return TheCallResult; 2272 } 2273 2274 // Get the valid immediate range for the specified NEON type code. 2275 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2276 NeonTypeFlags Type(t); 2277 int IsQuad = ForceQuad ? true : Type.isQuad(); 2278 switch (Type.getEltType()) { 2279 case NeonTypeFlags::Int8: 2280 case NeonTypeFlags::Poly8: 2281 return shift ? 7 : (8 << IsQuad) - 1; 2282 case NeonTypeFlags::Int16: 2283 case NeonTypeFlags::Poly16: 2284 return shift ? 15 : (4 << IsQuad) - 1; 2285 case NeonTypeFlags::Int32: 2286 return shift ? 31 : (2 << IsQuad) - 1; 2287 case NeonTypeFlags::Int64: 2288 case NeonTypeFlags::Poly64: 2289 return shift ? 63 : (1 << IsQuad) - 1; 2290 case NeonTypeFlags::Poly128: 2291 return shift ? 127 : (1 << IsQuad) - 1; 2292 case NeonTypeFlags::Float16: 2293 assert(!shift && "cannot shift float types!"); 2294 return (4 << IsQuad) - 1; 2295 case NeonTypeFlags::Float32: 2296 assert(!shift && "cannot shift float types!"); 2297 return (2 << IsQuad) - 1; 2298 case NeonTypeFlags::Float64: 2299 assert(!shift && "cannot shift float types!"); 2300 return (1 << IsQuad) - 1; 2301 case NeonTypeFlags::BFloat16: 2302 assert(!shift && "cannot shift float types!"); 2303 return (4 << IsQuad) - 1; 2304 } 2305 llvm_unreachable("Invalid NeonTypeFlag!"); 2306 } 2307 2308 /// getNeonEltType - Return the QualType corresponding to the elements of 2309 /// the vector type specified by the NeonTypeFlags. This is used to check 2310 /// the pointer arguments for Neon load/store intrinsics. 2311 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2312 bool IsPolyUnsigned, bool IsInt64Long) { 2313 switch (Flags.getEltType()) { 2314 case NeonTypeFlags::Int8: 2315 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2316 case NeonTypeFlags::Int16: 2317 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2318 case NeonTypeFlags::Int32: 2319 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2320 case NeonTypeFlags::Int64: 2321 if (IsInt64Long) 2322 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2323 else 2324 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2325 : Context.LongLongTy; 2326 case NeonTypeFlags::Poly8: 2327 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2328 case NeonTypeFlags::Poly16: 2329 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2330 case NeonTypeFlags::Poly64: 2331 if (IsInt64Long) 2332 return Context.UnsignedLongTy; 2333 else 2334 return Context.UnsignedLongLongTy; 2335 case NeonTypeFlags::Poly128: 2336 break; 2337 case NeonTypeFlags::Float16: 2338 return Context.HalfTy; 2339 case NeonTypeFlags::Float32: 2340 return Context.FloatTy; 2341 case NeonTypeFlags::Float64: 2342 return Context.DoubleTy; 2343 case NeonTypeFlags::BFloat16: 2344 return Context.BFloat16Ty; 2345 } 2346 llvm_unreachable("Invalid NeonTypeFlag!"); 2347 } 2348 2349 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2350 // Range check SVE intrinsics that take immediate values. 2351 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2352 2353 switch (BuiltinID) { 2354 default: 2355 return false; 2356 #define GET_SVE_IMMEDIATE_CHECK 2357 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2358 #undef GET_SVE_IMMEDIATE_CHECK 2359 } 2360 2361 // Perform all the immediate checks for this builtin call. 2362 bool HasError = false; 2363 for (auto &I : ImmChecks) { 2364 int ArgNum, CheckTy, ElementSizeInBits; 2365 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2366 2367 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2368 2369 // Function that checks whether the operand (ArgNum) is an immediate 2370 // that is one of the predefined values. 2371 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2372 int ErrDiag) -> bool { 2373 // We can't check the value of a dependent argument. 2374 Expr *Arg = TheCall->getArg(ArgNum); 2375 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2376 return false; 2377 2378 // Check constant-ness first. 2379 llvm::APSInt Imm; 2380 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2381 return true; 2382 2383 if (!CheckImm(Imm.getSExtValue())) 2384 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2385 return false; 2386 }; 2387 2388 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2389 case SVETypeFlags::ImmCheck0_31: 2390 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2391 HasError = true; 2392 break; 2393 case SVETypeFlags::ImmCheck0_13: 2394 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2395 HasError = true; 2396 break; 2397 case SVETypeFlags::ImmCheck1_16: 2398 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2399 HasError = true; 2400 break; 2401 case SVETypeFlags::ImmCheck0_7: 2402 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2403 HasError = true; 2404 break; 2405 case SVETypeFlags::ImmCheckExtract: 2406 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2407 (2048 / ElementSizeInBits) - 1)) 2408 HasError = true; 2409 break; 2410 case SVETypeFlags::ImmCheckShiftRight: 2411 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2412 HasError = true; 2413 break; 2414 case SVETypeFlags::ImmCheckShiftRightNarrow: 2415 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2416 ElementSizeInBits / 2)) 2417 HasError = true; 2418 break; 2419 case SVETypeFlags::ImmCheckShiftLeft: 2420 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2421 ElementSizeInBits - 1)) 2422 HasError = true; 2423 break; 2424 case SVETypeFlags::ImmCheckLaneIndex: 2425 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2426 (128 / (1 * ElementSizeInBits)) - 1)) 2427 HasError = true; 2428 break; 2429 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2430 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2431 (128 / (2 * ElementSizeInBits)) - 1)) 2432 HasError = true; 2433 break; 2434 case SVETypeFlags::ImmCheckLaneIndexDot: 2435 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2436 (128 / (4 * ElementSizeInBits)) - 1)) 2437 HasError = true; 2438 break; 2439 case SVETypeFlags::ImmCheckComplexRot90_270: 2440 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2441 diag::err_rotation_argument_to_cadd)) 2442 HasError = true; 2443 break; 2444 case SVETypeFlags::ImmCheckComplexRotAll90: 2445 if (CheckImmediateInSet( 2446 [](int64_t V) { 2447 return V == 0 || V == 90 || V == 180 || V == 270; 2448 }, 2449 diag::err_rotation_argument_to_cmla)) 2450 HasError = true; 2451 break; 2452 case SVETypeFlags::ImmCheck0_1: 2453 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2454 HasError = true; 2455 break; 2456 case SVETypeFlags::ImmCheck0_2: 2457 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2458 HasError = true; 2459 break; 2460 case SVETypeFlags::ImmCheck0_3: 2461 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2462 HasError = true; 2463 break; 2464 } 2465 } 2466 2467 return HasError; 2468 } 2469 2470 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2471 unsigned BuiltinID, CallExpr *TheCall) { 2472 llvm::APSInt Result; 2473 uint64_t mask = 0; 2474 unsigned TV = 0; 2475 int PtrArgNum = -1; 2476 bool HasConstPtr = false; 2477 switch (BuiltinID) { 2478 #define GET_NEON_OVERLOAD_CHECK 2479 #include "clang/Basic/arm_neon.inc" 2480 #include "clang/Basic/arm_fp16.inc" 2481 #undef GET_NEON_OVERLOAD_CHECK 2482 } 2483 2484 // For NEON intrinsics which are overloaded on vector element type, validate 2485 // the immediate which specifies which variant to emit. 2486 unsigned ImmArg = TheCall->getNumArgs()-1; 2487 if (mask) { 2488 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2489 return true; 2490 2491 TV = Result.getLimitedValue(64); 2492 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2493 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2494 << TheCall->getArg(ImmArg)->getSourceRange(); 2495 } 2496 2497 if (PtrArgNum >= 0) { 2498 // Check that pointer arguments have the specified type. 2499 Expr *Arg = TheCall->getArg(PtrArgNum); 2500 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2501 Arg = ICE->getSubExpr(); 2502 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2503 QualType RHSTy = RHS.get()->getType(); 2504 2505 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2506 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2507 Arch == llvm::Triple::aarch64_32 || 2508 Arch == llvm::Triple::aarch64_be; 2509 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2510 QualType EltTy = 2511 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2512 if (HasConstPtr) 2513 EltTy = EltTy.withConst(); 2514 QualType LHSTy = Context.getPointerType(EltTy); 2515 AssignConvertType ConvTy; 2516 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2517 if (RHS.isInvalid()) 2518 return true; 2519 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2520 RHS.get(), AA_Assigning)) 2521 return true; 2522 } 2523 2524 // For NEON intrinsics which take an immediate value as part of the 2525 // instruction, range check them here. 2526 unsigned i = 0, l = 0, u = 0; 2527 switch (BuiltinID) { 2528 default: 2529 return false; 2530 #define GET_NEON_IMMEDIATE_CHECK 2531 #include "clang/Basic/arm_neon.inc" 2532 #include "clang/Basic/arm_fp16.inc" 2533 #undef GET_NEON_IMMEDIATE_CHECK 2534 } 2535 2536 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2537 } 2538 2539 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2540 switch (BuiltinID) { 2541 default: 2542 return false; 2543 #include "clang/Basic/arm_mve_builtin_sema.inc" 2544 } 2545 } 2546 2547 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2548 CallExpr *TheCall) { 2549 bool Err = false; 2550 switch (BuiltinID) { 2551 default: 2552 return false; 2553 #include "clang/Basic/arm_cde_builtin_sema.inc" 2554 } 2555 2556 if (Err) 2557 return true; 2558 2559 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2560 } 2561 2562 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2563 const Expr *CoprocArg, bool WantCDE) { 2564 if (isConstantEvaluated()) 2565 return false; 2566 2567 // We can't check the value of a dependent argument. 2568 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2569 return false; 2570 2571 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2572 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2573 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2574 2575 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2576 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2577 2578 if (IsCDECoproc != WantCDE) 2579 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2580 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2581 2582 return false; 2583 } 2584 2585 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2586 unsigned MaxWidth) { 2587 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2588 BuiltinID == ARM::BI__builtin_arm_ldaex || 2589 BuiltinID == ARM::BI__builtin_arm_strex || 2590 BuiltinID == ARM::BI__builtin_arm_stlex || 2591 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2592 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2593 BuiltinID == AArch64::BI__builtin_arm_strex || 2594 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2595 "unexpected ARM builtin"); 2596 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2597 BuiltinID == ARM::BI__builtin_arm_ldaex || 2598 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2599 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2600 2601 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2602 2603 // Ensure that we have the proper number of arguments. 2604 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2605 return true; 2606 2607 // Inspect the pointer argument of the atomic builtin. This should always be 2608 // a pointer type, whose element is an integral scalar or pointer type. 2609 // Because it is a pointer type, we don't have to worry about any implicit 2610 // casts here. 2611 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2612 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2613 if (PointerArgRes.isInvalid()) 2614 return true; 2615 PointerArg = PointerArgRes.get(); 2616 2617 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2618 if (!pointerType) { 2619 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2620 << PointerArg->getType() << PointerArg->getSourceRange(); 2621 return true; 2622 } 2623 2624 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2625 // task is to insert the appropriate casts into the AST. First work out just 2626 // what the appropriate type is. 2627 QualType ValType = pointerType->getPointeeType(); 2628 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2629 if (IsLdrex) 2630 AddrType.addConst(); 2631 2632 // Issue a warning if the cast is dodgy. 2633 CastKind CastNeeded = CK_NoOp; 2634 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2635 CastNeeded = CK_BitCast; 2636 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2637 << PointerArg->getType() << Context.getPointerType(AddrType) 2638 << AA_Passing << PointerArg->getSourceRange(); 2639 } 2640 2641 // Finally, do the cast and replace the argument with the corrected version. 2642 AddrType = Context.getPointerType(AddrType); 2643 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2644 if (PointerArgRes.isInvalid()) 2645 return true; 2646 PointerArg = PointerArgRes.get(); 2647 2648 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2649 2650 // In general, we allow ints, floats and pointers to be loaded and stored. 2651 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2652 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2653 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2654 << PointerArg->getType() << PointerArg->getSourceRange(); 2655 return true; 2656 } 2657 2658 // But ARM doesn't have instructions to deal with 128-bit versions. 2659 if (Context.getTypeSize(ValType) > MaxWidth) { 2660 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2661 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2662 << PointerArg->getType() << PointerArg->getSourceRange(); 2663 return true; 2664 } 2665 2666 switch (ValType.getObjCLifetime()) { 2667 case Qualifiers::OCL_None: 2668 case Qualifiers::OCL_ExplicitNone: 2669 // okay 2670 break; 2671 2672 case Qualifiers::OCL_Weak: 2673 case Qualifiers::OCL_Strong: 2674 case Qualifiers::OCL_Autoreleasing: 2675 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2676 << ValType << PointerArg->getSourceRange(); 2677 return true; 2678 } 2679 2680 if (IsLdrex) { 2681 TheCall->setType(ValType); 2682 return false; 2683 } 2684 2685 // Initialize the argument to be stored. 2686 ExprResult ValArg = TheCall->getArg(0); 2687 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2688 Context, ValType, /*consume*/ false); 2689 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2690 if (ValArg.isInvalid()) 2691 return true; 2692 TheCall->setArg(0, ValArg.get()); 2693 2694 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2695 // but the custom checker bypasses all default analysis. 2696 TheCall->setType(Context.IntTy); 2697 return false; 2698 } 2699 2700 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2701 CallExpr *TheCall) { 2702 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2703 BuiltinID == ARM::BI__builtin_arm_ldaex || 2704 BuiltinID == ARM::BI__builtin_arm_strex || 2705 BuiltinID == ARM::BI__builtin_arm_stlex) { 2706 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2707 } 2708 2709 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2710 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2711 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2712 } 2713 2714 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2715 BuiltinID == ARM::BI__builtin_arm_wsr64) 2716 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2717 2718 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2719 BuiltinID == ARM::BI__builtin_arm_rsrp || 2720 BuiltinID == ARM::BI__builtin_arm_wsr || 2721 BuiltinID == ARM::BI__builtin_arm_wsrp) 2722 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2723 2724 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2725 return true; 2726 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2727 return true; 2728 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2729 return true; 2730 2731 // For intrinsics which take an immediate value as part of the instruction, 2732 // range check them here. 2733 // FIXME: VFP Intrinsics should error if VFP not present. 2734 switch (BuiltinID) { 2735 default: return false; 2736 case ARM::BI__builtin_arm_ssat: 2737 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2738 case ARM::BI__builtin_arm_usat: 2739 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2740 case ARM::BI__builtin_arm_ssat16: 2741 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2742 case ARM::BI__builtin_arm_usat16: 2743 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2744 case ARM::BI__builtin_arm_vcvtr_f: 2745 case ARM::BI__builtin_arm_vcvtr_d: 2746 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2747 case ARM::BI__builtin_arm_dmb: 2748 case ARM::BI__builtin_arm_dsb: 2749 case ARM::BI__builtin_arm_isb: 2750 case ARM::BI__builtin_arm_dbg: 2751 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2752 case ARM::BI__builtin_arm_cdp: 2753 case ARM::BI__builtin_arm_cdp2: 2754 case ARM::BI__builtin_arm_mcr: 2755 case ARM::BI__builtin_arm_mcr2: 2756 case ARM::BI__builtin_arm_mrc: 2757 case ARM::BI__builtin_arm_mrc2: 2758 case ARM::BI__builtin_arm_mcrr: 2759 case ARM::BI__builtin_arm_mcrr2: 2760 case ARM::BI__builtin_arm_mrrc: 2761 case ARM::BI__builtin_arm_mrrc2: 2762 case ARM::BI__builtin_arm_ldc: 2763 case ARM::BI__builtin_arm_ldcl: 2764 case ARM::BI__builtin_arm_ldc2: 2765 case ARM::BI__builtin_arm_ldc2l: 2766 case ARM::BI__builtin_arm_stc: 2767 case ARM::BI__builtin_arm_stcl: 2768 case ARM::BI__builtin_arm_stc2: 2769 case ARM::BI__builtin_arm_stc2l: 2770 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2771 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2772 /*WantCDE*/ false); 2773 } 2774 } 2775 2776 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2777 unsigned BuiltinID, 2778 CallExpr *TheCall) { 2779 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2780 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2781 BuiltinID == AArch64::BI__builtin_arm_strex || 2782 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2783 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2784 } 2785 2786 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2787 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2788 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2789 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2790 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2791 } 2792 2793 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2794 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2795 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2796 2797 // Memory Tagging Extensions (MTE) Intrinsics 2798 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2799 BuiltinID == AArch64::BI__builtin_arm_addg || 2800 BuiltinID == AArch64::BI__builtin_arm_gmi || 2801 BuiltinID == AArch64::BI__builtin_arm_ldg || 2802 BuiltinID == AArch64::BI__builtin_arm_stg || 2803 BuiltinID == AArch64::BI__builtin_arm_subp) { 2804 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2805 } 2806 2807 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2808 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2809 BuiltinID == AArch64::BI__builtin_arm_wsr || 2810 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2811 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2812 2813 // Only check the valid encoding range. Any constant in this range would be 2814 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2815 // an exception for incorrect registers. This matches MSVC behavior. 2816 if (BuiltinID == AArch64::BI_ReadStatusReg || 2817 BuiltinID == AArch64::BI_WriteStatusReg) 2818 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2819 2820 if (BuiltinID == AArch64::BI__getReg) 2821 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2822 2823 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2824 return true; 2825 2826 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2827 return true; 2828 2829 // For intrinsics which take an immediate value as part of the instruction, 2830 // range check them here. 2831 unsigned i = 0, l = 0, u = 0; 2832 switch (BuiltinID) { 2833 default: return false; 2834 case AArch64::BI__builtin_arm_dmb: 2835 case AArch64::BI__builtin_arm_dsb: 2836 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2837 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2838 } 2839 2840 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2841 } 2842 2843 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2844 if (Arg->getType()->getAsPlaceholderType()) 2845 return false; 2846 2847 // The first argument needs to be a record field access. 2848 // If it is an array element access, we delay decision 2849 // to BPF backend to check whether the access is a 2850 // field access or not. 2851 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2852 isa<MemberExpr>(Arg->IgnoreParens()) || 2853 isa<ArraySubscriptExpr>(Arg->IgnoreParens())); 2854 } 2855 2856 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2857 QualType VectorTy, QualType EltTy) { 2858 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2859 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2860 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2861 << Call->getSourceRange() << VectorEltTy << EltTy; 2862 return false; 2863 } 2864 return true; 2865 } 2866 2867 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2868 QualType ArgType = Arg->getType(); 2869 if (ArgType->getAsPlaceholderType()) 2870 return false; 2871 2872 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2873 // format: 2874 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2875 // 2. <type> var; 2876 // __builtin_preserve_type_info(var, flag); 2877 if (!isa<DeclRefExpr>(Arg->IgnoreParens()) && 2878 !isa<UnaryOperator>(Arg->IgnoreParens())) 2879 return false; 2880 2881 // Typedef type. 2882 if (ArgType->getAs<TypedefType>()) 2883 return true; 2884 2885 // Record type or Enum type. 2886 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2887 if (const auto *RT = Ty->getAs<RecordType>()) { 2888 if (!RT->getDecl()->getDeclName().isEmpty()) 2889 return true; 2890 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2891 if (!ET->getDecl()->getDeclName().isEmpty()) 2892 return true; 2893 } 2894 2895 return false; 2896 } 2897 2898 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2899 QualType ArgType = Arg->getType(); 2900 if (ArgType->getAsPlaceholderType()) 2901 return false; 2902 2903 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2904 // format: 2905 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2906 // flag); 2907 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2908 if (!UO) 2909 return false; 2910 2911 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2912 if (!CE) 2913 return false; 2914 if (CE->getCastKind() != CK_IntegralToPointer && 2915 CE->getCastKind() != CK_NullToPointer) 2916 return false; 2917 2918 // The integer must be from an EnumConstantDecl. 2919 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2920 if (!DR) 2921 return false; 2922 2923 const EnumConstantDecl *Enumerator = 2924 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2925 if (!Enumerator) 2926 return false; 2927 2928 // The type must be EnumType. 2929 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2930 const auto *ET = Ty->getAs<EnumType>(); 2931 if (!ET) 2932 return false; 2933 2934 // The enum value must be supported. 2935 return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator); 2936 } 2937 2938 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2939 CallExpr *TheCall) { 2940 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2941 BuiltinID == BPF::BI__builtin_btf_type_id || 2942 BuiltinID == BPF::BI__builtin_preserve_type_info || 2943 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2944 "unexpected BPF builtin"); 2945 2946 if (checkArgCount(*this, TheCall, 2)) 2947 return true; 2948 2949 // The second argument needs to be a constant int 2950 Expr *Arg = TheCall->getArg(1); 2951 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2952 diag::kind kind; 2953 if (!Value) { 2954 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2955 kind = diag::err_preserve_field_info_not_const; 2956 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2957 kind = diag::err_btf_type_id_not_const; 2958 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2959 kind = diag::err_preserve_type_info_not_const; 2960 else 2961 kind = diag::err_preserve_enum_value_not_const; 2962 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2963 return true; 2964 } 2965 2966 // The first argument 2967 Arg = TheCall->getArg(0); 2968 bool InvalidArg = false; 2969 bool ReturnUnsignedInt = true; 2970 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2971 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2972 InvalidArg = true; 2973 kind = diag::err_preserve_field_info_not_field; 2974 } 2975 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2976 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2977 InvalidArg = true; 2978 kind = diag::err_preserve_type_info_invalid; 2979 } 2980 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2981 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2982 InvalidArg = true; 2983 kind = diag::err_preserve_enum_value_invalid; 2984 } 2985 ReturnUnsignedInt = false; 2986 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2987 ReturnUnsignedInt = false; 2988 } 2989 2990 if (InvalidArg) { 2991 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2992 return true; 2993 } 2994 2995 if (ReturnUnsignedInt) 2996 TheCall->setType(Context.UnsignedIntTy); 2997 else 2998 TheCall->setType(Context.UnsignedLongTy); 2999 return false; 3000 } 3001 3002 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3003 struct ArgInfo { 3004 uint8_t OpNum; 3005 bool IsSigned; 3006 uint8_t BitWidth; 3007 uint8_t Align; 3008 }; 3009 struct BuiltinInfo { 3010 unsigned BuiltinID; 3011 ArgInfo Infos[2]; 3012 }; 3013 3014 static BuiltinInfo Infos[] = { 3015 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 3016 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 3017 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 3018 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 3019 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 3020 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 3021 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 3022 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 3023 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 3024 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 3025 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 3026 3027 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 3028 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 3029 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 3030 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 3031 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 3032 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 3033 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 3034 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 3035 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 3036 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 3037 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 3038 3039 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 3040 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 3041 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 3042 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 3043 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 3044 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 3045 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 3046 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 3047 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 3048 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 3049 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 3050 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 3051 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 3052 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 3053 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 3054 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 3055 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 3056 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 3057 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 3058 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 3059 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 3060 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 3061 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 3062 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 3063 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 3064 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 3065 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 3066 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 3067 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 3068 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 3069 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 3070 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 3071 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 3072 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 3073 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 3074 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 3075 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 3076 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 3077 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 3078 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 3079 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 3080 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 3081 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 3082 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 3083 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 3084 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 3085 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 3086 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 3087 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 3088 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 3089 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 3090 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 3091 {{ 1, false, 6, 0 }} }, 3092 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 3093 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 3094 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 3095 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 3096 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 3097 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 3098 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 3099 {{ 1, false, 5, 0 }} }, 3100 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 3101 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 3102 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 3103 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 3104 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 3105 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 3106 { 2, false, 5, 0 }} }, 3107 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 3108 { 2, false, 6, 0 }} }, 3109 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 3110 { 3, false, 5, 0 }} }, 3111 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 3112 { 3, false, 6, 0 }} }, 3113 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 3114 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 3115 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 3116 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 3117 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 3118 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 3119 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 3120 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 3121 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 3122 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 3123 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 3124 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 3125 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 3126 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 3127 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 3128 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 3129 {{ 2, false, 4, 0 }, 3130 { 3, false, 5, 0 }} }, 3131 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 3132 {{ 2, false, 4, 0 }, 3133 { 3, false, 5, 0 }} }, 3134 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 3135 {{ 2, false, 4, 0 }, 3136 { 3, false, 5, 0 }} }, 3137 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 3138 {{ 2, false, 4, 0 }, 3139 { 3, false, 5, 0 }} }, 3140 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 3141 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 3142 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 3143 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 3144 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 3145 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 3146 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 3147 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 3148 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 3149 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 3150 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 3151 { 2, false, 5, 0 }} }, 3152 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 3153 { 2, false, 6, 0 }} }, 3154 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 3155 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 3156 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 3157 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 3158 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 3159 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 3160 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 3161 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 3162 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 3163 {{ 1, false, 4, 0 }} }, 3164 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 3165 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 3166 {{ 1, false, 4, 0 }} }, 3167 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 3168 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 3169 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 3170 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 3171 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 3172 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 3173 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 3174 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 3175 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 3176 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 3177 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 3178 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 3179 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 3180 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 3181 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 3182 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 3183 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 3184 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 3185 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 3186 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 3187 {{ 3, false, 1, 0 }} }, 3188 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 3189 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 3190 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 3191 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 3192 {{ 3, false, 1, 0 }} }, 3193 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 3194 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 3195 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 3196 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 3197 {{ 3, false, 1, 0 }} }, 3198 }; 3199 3200 // Use a dynamically initialized static to sort the table exactly once on 3201 // first run. 3202 static const bool SortOnce = 3203 (llvm::sort(Infos, 3204 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 3205 return LHS.BuiltinID < RHS.BuiltinID; 3206 }), 3207 true); 3208 (void)SortOnce; 3209 3210 const BuiltinInfo *F = llvm::partition_point( 3211 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 3212 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 3213 return false; 3214 3215 bool Error = false; 3216 3217 for (const ArgInfo &A : F->Infos) { 3218 // Ignore empty ArgInfo elements. 3219 if (A.BitWidth == 0) 3220 continue; 3221 3222 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 3223 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 3224 if (!A.Align) { 3225 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3226 } else { 3227 unsigned M = 1 << A.Align; 3228 Min *= M; 3229 Max *= M; 3230 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3231 Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 3232 } 3233 } 3234 return Error; 3235 } 3236 3237 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 3238 CallExpr *TheCall) { 3239 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3240 } 3241 3242 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 3243 unsigned BuiltinID, CallExpr *TheCall) { 3244 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 3245 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3246 } 3247 3248 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 3249 CallExpr *TheCall) { 3250 3251 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3252 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3253 if (!TI.hasFeature("dsp")) 3254 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3255 } 3256 3257 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3258 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3259 if (!TI.hasFeature("dspr2")) 3260 return Diag(TheCall->getBeginLoc(), 3261 diag::err_mips_builtin_requires_dspr2); 3262 } 3263 3264 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3265 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3266 if (!TI.hasFeature("msa")) 3267 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3268 } 3269 3270 return false; 3271 } 3272 3273 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3274 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3275 // ordering for DSP is unspecified. MSA is ordered by the data format used 3276 // by the underlying instruction i.e., df/m, df/n and then by size. 3277 // 3278 // FIXME: The size tests here should instead be tablegen'd along with the 3279 // definitions from include/clang/Basic/BuiltinsMips.def. 3280 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3281 // be too. 3282 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3283 unsigned i = 0, l = 0, u = 0, m = 0; 3284 switch (BuiltinID) { 3285 default: return false; 3286 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3287 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3288 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3289 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3290 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3291 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3292 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3293 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3294 // df/m field. 3295 // These intrinsics take an unsigned 3 bit immediate. 3296 case Mips::BI__builtin_msa_bclri_b: 3297 case Mips::BI__builtin_msa_bnegi_b: 3298 case Mips::BI__builtin_msa_bseti_b: 3299 case Mips::BI__builtin_msa_sat_s_b: 3300 case Mips::BI__builtin_msa_sat_u_b: 3301 case Mips::BI__builtin_msa_slli_b: 3302 case Mips::BI__builtin_msa_srai_b: 3303 case Mips::BI__builtin_msa_srari_b: 3304 case Mips::BI__builtin_msa_srli_b: 3305 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3306 case Mips::BI__builtin_msa_binsli_b: 3307 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3308 // These intrinsics take an unsigned 4 bit immediate. 3309 case Mips::BI__builtin_msa_bclri_h: 3310 case Mips::BI__builtin_msa_bnegi_h: 3311 case Mips::BI__builtin_msa_bseti_h: 3312 case Mips::BI__builtin_msa_sat_s_h: 3313 case Mips::BI__builtin_msa_sat_u_h: 3314 case Mips::BI__builtin_msa_slli_h: 3315 case Mips::BI__builtin_msa_srai_h: 3316 case Mips::BI__builtin_msa_srari_h: 3317 case Mips::BI__builtin_msa_srli_h: 3318 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3319 case Mips::BI__builtin_msa_binsli_h: 3320 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3321 // These intrinsics take an unsigned 5 bit immediate. 3322 // The first block of intrinsics actually have an unsigned 5 bit field, 3323 // not a df/n field. 3324 case Mips::BI__builtin_msa_cfcmsa: 3325 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3326 case Mips::BI__builtin_msa_clei_u_b: 3327 case Mips::BI__builtin_msa_clei_u_h: 3328 case Mips::BI__builtin_msa_clei_u_w: 3329 case Mips::BI__builtin_msa_clei_u_d: 3330 case Mips::BI__builtin_msa_clti_u_b: 3331 case Mips::BI__builtin_msa_clti_u_h: 3332 case Mips::BI__builtin_msa_clti_u_w: 3333 case Mips::BI__builtin_msa_clti_u_d: 3334 case Mips::BI__builtin_msa_maxi_u_b: 3335 case Mips::BI__builtin_msa_maxi_u_h: 3336 case Mips::BI__builtin_msa_maxi_u_w: 3337 case Mips::BI__builtin_msa_maxi_u_d: 3338 case Mips::BI__builtin_msa_mini_u_b: 3339 case Mips::BI__builtin_msa_mini_u_h: 3340 case Mips::BI__builtin_msa_mini_u_w: 3341 case Mips::BI__builtin_msa_mini_u_d: 3342 case Mips::BI__builtin_msa_addvi_b: 3343 case Mips::BI__builtin_msa_addvi_h: 3344 case Mips::BI__builtin_msa_addvi_w: 3345 case Mips::BI__builtin_msa_addvi_d: 3346 case Mips::BI__builtin_msa_bclri_w: 3347 case Mips::BI__builtin_msa_bnegi_w: 3348 case Mips::BI__builtin_msa_bseti_w: 3349 case Mips::BI__builtin_msa_sat_s_w: 3350 case Mips::BI__builtin_msa_sat_u_w: 3351 case Mips::BI__builtin_msa_slli_w: 3352 case Mips::BI__builtin_msa_srai_w: 3353 case Mips::BI__builtin_msa_srari_w: 3354 case Mips::BI__builtin_msa_srli_w: 3355 case Mips::BI__builtin_msa_srlri_w: 3356 case Mips::BI__builtin_msa_subvi_b: 3357 case Mips::BI__builtin_msa_subvi_h: 3358 case Mips::BI__builtin_msa_subvi_w: 3359 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3360 case Mips::BI__builtin_msa_binsli_w: 3361 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3362 // These intrinsics take an unsigned 6 bit immediate. 3363 case Mips::BI__builtin_msa_bclri_d: 3364 case Mips::BI__builtin_msa_bnegi_d: 3365 case Mips::BI__builtin_msa_bseti_d: 3366 case Mips::BI__builtin_msa_sat_s_d: 3367 case Mips::BI__builtin_msa_sat_u_d: 3368 case Mips::BI__builtin_msa_slli_d: 3369 case Mips::BI__builtin_msa_srai_d: 3370 case Mips::BI__builtin_msa_srari_d: 3371 case Mips::BI__builtin_msa_srli_d: 3372 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3373 case Mips::BI__builtin_msa_binsli_d: 3374 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3375 // These intrinsics take a signed 5 bit immediate. 3376 case Mips::BI__builtin_msa_ceqi_b: 3377 case Mips::BI__builtin_msa_ceqi_h: 3378 case Mips::BI__builtin_msa_ceqi_w: 3379 case Mips::BI__builtin_msa_ceqi_d: 3380 case Mips::BI__builtin_msa_clti_s_b: 3381 case Mips::BI__builtin_msa_clti_s_h: 3382 case Mips::BI__builtin_msa_clti_s_w: 3383 case Mips::BI__builtin_msa_clti_s_d: 3384 case Mips::BI__builtin_msa_clei_s_b: 3385 case Mips::BI__builtin_msa_clei_s_h: 3386 case Mips::BI__builtin_msa_clei_s_w: 3387 case Mips::BI__builtin_msa_clei_s_d: 3388 case Mips::BI__builtin_msa_maxi_s_b: 3389 case Mips::BI__builtin_msa_maxi_s_h: 3390 case Mips::BI__builtin_msa_maxi_s_w: 3391 case Mips::BI__builtin_msa_maxi_s_d: 3392 case Mips::BI__builtin_msa_mini_s_b: 3393 case Mips::BI__builtin_msa_mini_s_h: 3394 case Mips::BI__builtin_msa_mini_s_w: 3395 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3396 // These intrinsics take an unsigned 8 bit immediate. 3397 case Mips::BI__builtin_msa_andi_b: 3398 case Mips::BI__builtin_msa_nori_b: 3399 case Mips::BI__builtin_msa_ori_b: 3400 case Mips::BI__builtin_msa_shf_b: 3401 case Mips::BI__builtin_msa_shf_h: 3402 case Mips::BI__builtin_msa_shf_w: 3403 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3404 case Mips::BI__builtin_msa_bseli_b: 3405 case Mips::BI__builtin_msa_bmnzi_b: 3406 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3407 // df/n format 3408 // These intrinsics take an unsigned 4 bit immediate. 3409 case Mips::BI__builtin_msa_copy_s_b: 3410 case Mips::BI__builtin_msa_copy_u_b: 3411 case Mips::BI__builtin_msa_insve_b: 3412 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3413 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3414 // These intrinsics take an unsigned 3 bit immediate. 3415 case Mips::BI__builtin_msa_copy_s_h: 3416 case Mips::BI__builtin_msa_copy_u_h: 3417 case Mips::BI__builtin_msa_insve_h: 3418 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3419 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3420 // These intrinsics take an unsigned 2 bit immediate. 3421 case Mips::BI__builtin_msa_copy_s_w: 3422 case Mips::BI__builtin_msa_copy_u_w: 3423 case Mips::BI__builtin_msa_insve_w: 3424 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3425 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3426 // These intrinsics take an unsigned 1 bit immediate. 3427 case Mips::BI__builtin_msa_copy_s_d: 3428 case Mips::BI__builtin_msa_copy_u_d: 3429 case Mips::BI__builtin_msa_insve_d: 3430 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3431 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3432 // Memory offsets and immediate loads. 3433 // These intrinsics take a signed 10 bit immediate. 3434 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3435 case Mips::BI__builtin_msa_ldi_h: 3436 case Mips::BI__builtin_msa_ldi_w: 3437 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3438 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3439 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3440 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3441 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3442 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3443 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3444 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3445 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3446 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3447 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3448 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3449 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3450 } 3451 3452 if (!m) 3453 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3454 3455 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3456 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3457 } 3458 3459 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3460 /// advancing the pointer over the consumed characters. The decoded type is 3461 /// returned. If the decoded type represents a constant integer with a 3462 /// constraint on its value then Mask is set to that value. The type descriptors 3463 /// used in Str are specific to PPC MMA builtins and are documented in the file 3464 /// defining the PPC builtins. 3465 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3466 unsigned &Mask) { 3467 bool RequireICE = false; 3468 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3469 switch (*Str++) { 3470 case 'V': 3471 return Context.getVectorType(Context.UnsignedCharTy, 16, 3472 VectorType::VectorKind::AltiVecVector); 3473 case 'i': { 3474 char *End; 3475 unsigned size = strtoul(Str, &End, 10); 3476 assert(End != Str && "Missing constant parameter constraint"); 3477 Str = End; 3478 Mask = size; 3479 return Context.IntTy; 3480 } 3481 case 'W': { 3482 char *End; 3483 unsigned size = strtoul(Str, &End, 10); 3484 assert(End != Str && "Missing PowerPC MMA type size"); 3485 Str = End; 3486 QualType Type; 3487 switch (size) { 3488 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3489 case size: Type = Context.Id##Ty; break; 3490 #include "clang/Basic/PPCTypes.def" 3491 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3492 } 3493 bool CheckVectorArgs = false; 3494 while (!CheckVectorArgs) { 3495 switch (*Str++) { 3496 case '*': 3497 Type = Context.getPointerType(Type); 3498 break; 3499 case 'C': 3500 Type = Type.withConst(); 3501 break; 3502 default: 3503 CheckVectorArgs = true; 3504 --Str; 3505 break; 3506 } 3507 } 3508 return Type; 3509 } 3510 default: 3511 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3512 } 3513 } 3514 3515 static bool isPPC_64Builtin(unsigned BuiltinID) { 3516 // These builtins only work on PPC 64bit targets. 3517 switch (BuiltinID) { 3518 case PPC::BI__builtin_divde: 3519 case PPC::BI__builtin_divdeu: 3520 case PPC::BI__builtin_bpermd: 3521 case PPC::BI__builtin_ppc_ldarx: 3522 case PPC::BI__builtin_ppc_stdcx: 3523 case PPC::BI__builtin_ppc_tdw: 3524 case PPC::BI__builtin_ppc_trapd: 3525 case PPC::BI__builtin_ppc_cmpeqb: 3526 case PPC::BI__builtin_ppc_setb: 3527 case PPC::BI__builtin_ppc_mulhd: 3528 case PPC::BI__builtin_ppc_mulhdu: 3529 case PPC::BI__builtin_ppc_maddhd: 3530 case PPC::BI__builtin_ppc_maddhdu: 3531 case PPC::BI__builtin_ppc_maddld: 3532 case PPC::BI__builtin_ppc_load8r: 3533 case PPC::BI__builtin_ppc_store8r: 3534 case PPC::BI__builtin_ppc_insert_exp: 3535 case PPC::BI__builtin_ppc_extract_sig: 3536 case PPC::BI__builtin_ppc_addex: 3537 case PPC::BI__builtin_darn: 3538 case PPC::BI__builtin_darn_raw: 3539 case PPC::BI__builtin_ppc_compare_and_swaplp: 3540 case PPC::BI__builtin_ppc_fetch_and_addlp: 3541 case PPC::BI__builtin_ppc_fetch_and_andlp: 3542 case PPC::BI__builtin_ppc_fetch_and_orlp: 3543 case PPC::BI__builtin_ppc_fetch_and_swaplp: 3544 return true; 3545 } 3546 return false; 3547 } 3548 3549 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3550 StringRef FeatureToCheck, unsigned DiagID, 3551 StringRef DiagArg = "") { 3552 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3553 return false; 3554 3555 if (DiagArg.empty()) 3556 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3557 else 3558 S.Diag(TheCall->getBeginLoc(), DiagID) 3559 << DiagArg << TheCall->getSourceRange(); 3560 3561 return true; 3562 } 3563 3564 /// Returns true if the argument consists of one contiguous run of 1s with any 3565 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3566 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3567 /// since all 1s are not contiguous. 3568 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3569 llvm::APSInt Result; 3570 // We can't check the value of a dependent argument. 3571 Expr *Arg = TheCall->getArg(ArgNum); 3572 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3573 return false; 3574 3575 // Check constant-ness first. 3576 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3577 return true; 3578 3579 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3580 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3581 return false; 3582 3583 return Diag(TheCall->getBeginLoc(), 3584 diag::err_argument_not_contiguous_bit_field) 3585 << ArgNum << Arg->getSourceRange(); 3586 } 3587 3588 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3589 CallExpr *TheCall) { 3590 unsigned i = 0, l = 0, u = 0; 3591 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3592 llvm::APSInt Result; 3593 3594 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3595 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3596 << TheCall->getSourceRange(); 3597 3598 switch (BuiltinID) { 3599 default: return false; 3600 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3601 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3602 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3603 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3604 case PPC::BI__builtin_altivec_dss: 3605 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3606 case PPC::BI__builtin_tbegin: 3607 case PPC::BI__builtin_tend: 3608 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) || 3609 SemaFeatureCheck(*this, TheCall, "htm", 3610 diag::err_ppc_builtin_requires_htm); 3611 case PPC::BI__builtin_tsr: 3612 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3613 SemaFeatureCheck(*this, TheCall, "htm", 3614 diag::err_ppc_builtin_requires_htm); 3615 case PPC::BI__builtin_tabortwc: 3616 case PPC::BI__builtin_tabortdc: 3617 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3618 SemaFeatureCheck(*this, TheCall, "htm", 3619 diag::err_ppc_builtin_requires_htm); 3620 case PPC::BI__builtin_tabortwci: 3621 case PPC::BI__builtin_tabortdci: 3622 return SemaFeatureCheck(*this, TheCall, "htm", 3623 diag::err_ppc_builtin_requires_htm) || 3624 (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3625 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31)); 3626 case PPC::BI__builtin_tabort: 3627 case PPC::BI__builtin_tcheck: 3628 case PPC::BI__builtin_treclaim: 3629 case PPC::BI__builtin_trechkpt: 3630 case PPC::BI__builtin_tendall: 3631 case PPC::BI__builtin_tresume: 3632 case PPC::BI__builtin_tsuspend: 3633 case PPC::BI__builtin_get_texasr: 3634 case PPC::BI__builtin_get_texasru: 3635 case PPC::BI__builtin_get_tfhar: 3636 case PPC::BI__builtin_get_tfiar: 3637 case PPC::BI__builtin_set_texasr: 3638 case PPC::BI__builtin_set_texasru: 3639 case PPC::BI__builtin_set_tfhar: 3640 case PPC::BI__builtin_set_tfiar: 3641 case PPC::BI__builtin_ttest: 3642 return SemaFeatureCheck(*this, TheCall, "htm", 3643 diag::err_ppc_builtin_requires_htm); 3644 // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05', 3645 // __builtin_(un)pack_longdouble are available only if long double uses IBM 3646 // extended double representation. 3647 case PPC::BI__builtin_unpack_longdouble: 3648 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1)) 3649 return true; 3650 LLVM_FALLTHROUGH; 3651 case PPC::BI__builtin_pack_longdouble: 3652 if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble()) 3653 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi) 3654 << "ibmlongdouble"; 3655 return false; 3656 case PPC::BI__builtin_altivec_dst: 3657 case PPC::BI__builtin_altivec_dstt: 3658 case PPC::BI__builtin_altivec_dstst: 3659 case PPC::BI__builtin_altivec_dststt: 3660 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3661 case PPC::BI__builtin_vsx_xxpermdi: 3662 case PPC::BI__builtin_vsx_xxsldwi: 3663 return SemaBuiltinVSX(TheCall); 3664 case PPC::BI__builtin_divwe: 3665 case PPC::BI__builtin_divweu: 3666 case PPC::BI__builtin_divde: 3667 case PPC::BI__builtin_divdeu: 3668 return SemaFeatureCheck(*this, TheCall, "extdiv", 3669 diag::err_ppc_builtin_only_on_arch, "7"); 3670 case PPC::BI__builtin_bpermd: 3671 return SemaFeatureCheck(*this, TheCall, "bpermd", 3672 diag::err_ppc_builtin_only_on_arch, "7"); 3673 case PPC::BI__builtin_unpack_vector_int128: 3674 return SemaFeatureCheck(*this, TheCall, "vsx", 3675 diag::err_ppc_builtin_only_on_arch, "7") || 3676 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3677 case PPC::BI__builtin_pack_vector_int128: 3678 return SemaFeatureCheck(*this, TheCall, "vsx", 3679 diag::err_ppc_builtin_only_on_arch, "7"); 3680 case PPC::BI__builtin_altivec_vgnb: 3681 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3682 case PPC::BI__builtin_altivec_vec_replace_elt: 3683 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3684 QualType VecTy = TheCall->getArg(0)->getType(); 3685 QualType EltTy = TheCall->getArg(1)->getType(); 3686 unsigned Width = Context.getIntWidth(EltTy); 3687 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3688 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3689 } 3690 case PPC::BI__builtin_vsx_xxeval: 3691 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3692 case PPC::BI__builtin_altivec_vsldbi: 3693 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3694 case PPC::BI__builtin_altivec_vsrdbi: 3695 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3696 case PPC::BI__builtin_vsx_xxpermx: 3697 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3698 case PPC::BI__builtin_ppc_tw: 3699 case PPC::BI__builtin_ppc_tdw: 3700 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); 3701 case PPC::BI__builtin_ppc_cmpeqb: 3702 case PPC::BI__builtin_ppc_setb: 3703 case PPC::BI__builtin_ppc_maddhd: 3704 case PPC::BI__builtin_ppc_maddhdu: 3705 case PPC::BI__builtin_ppc_maddld: 3706 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3707 diag::err_ppc_builtin_only_on_arch, "9"); 3708 case PPC::BI__builtin_ppc_cmprb: 3709 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3710 diag::err_ppc_builtin_only_on_arch, "9") || 3711 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3712 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3713 // be a constant that represents a contiguous bit field. 3714 case PPC::BI__builtin_ppc_rlwnm: 3715 return SemaValueIsRunOfOnes(TheCall, 2); 3716 case PPC::BI__builtin_ppc_rlwimi: 3717 case PPC::BI__builtin_ppc_rldimi: 3718 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3719 SemaValueIsRunOfOnes(TheCall, 3); 3720 case PPC::BI__builtin_ppc_extract_exp: 3721 case PPC::BI__builtin_ppc_extract_sig: 3722 case PPC::BI__builtin_ppc_insert_exp: 3723 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3724 diag::err_ppc_builtin_only_on_arch, "9"); 3725 case PPC::BI__builtin_ppc_addex: { 3726 if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3727 diag::err_ppc_builtin_only_on_arch, "9") || 3728 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3)) 3729 return true; 3730 // Output warning for reserved values 1 to 3. 3731 int ArgValue = 3732 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue(); 3733 if (ArgValue != 0) 3734 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour) 3735 << ArgValue; 3736 return false; 3737 } 3738 case PPC::BI__builtin_ppc_mtfsb0: 3739 case PPC::BI__builtin_ppc_mtfsb1: 3740 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3741 case PPC::BI__builtin_ppc_mtfsf: 3742 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3743 case PPC::BI__builtin_ppc_mtfsfi: 3744 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3745 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3746 case PPC::BI__builtin_ppc_alignx: 3747 return SemaBuiltinConstantArgPower2(TheCall, 0); 3748 case PPC::BI__builtin_ppc_rdlam: 3749 return SemaValueIsRunOfOnes(TheCall, 2); 3750 case PPC::BI__builtin_ppc_icbt: 3751 case PPC::BI__builtin_ppc_sthcx: 3752 case PPC::BI__builtin_ppc_stbcx: 3753 case PPC::BI__builtin_ppc_lharx: 3754 case PPC::BI__builtin_ppc_lbarx: 3755 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3756 diag::err_ppc_builtin_only_on_arch, "8"); 3757 case PPC::BI__builtin_vsx_ldrmb: 3758 case PPC::BI__builtin_vsx_strmb: 3759 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3760 diag::err_ppc_builtin_only_on_arch, "8") || 3761 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 3762 case PPC::BI__builtin_altivec_vcntmbb: 3763 case PPC::BI__builtin_altivec_vcntmbh: 3764 case PPC::BI__builtin_altivec_vcntmbw: 3765 case PPC::BI__builtin_altivec_vcntmbd: 3766 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3767 case PPC::BI__builtin_darn: 3768 case PPC::BI__builtin_darn_raw: 3769 case PPC::BI__builtin_darn_32: 3770 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3771 diag::err_ppc_builtin_only_on_arch, "9"); 3772 case PPC::BI__builtin_vsx_xxgenpcvbm: 3773 case PPC::BI__builtin_vsx_xxgenpcvhm: 3774 case PPC::BI__builtin_vsx_xxgenpcvwm: 3775 case PPC::BI__builtin_vsx_xxgenpcvdm: 3776 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3777 case PPC::BI__builtin_ppc_compare_exp_uo: 3778 case PPC::BI__builtin_ppc_compare_exp_lt: 3779 case PPC::BI__builtin_ppc_compare_exp_gt: 3780 case PPC::BI__builtin_ppc_compare_exp_eq: 3781 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3782 diag::err_ppc_builtin_only_on_arch, "9") || 3783 SemaFeatureCheck(*this, TheCall, "vsx", 3784 diag::err_ppc_builtin_requires_vsx); 3785 case PPC::BI__builtin_ppc_test_data_class: { 3786 // Check if the first argument of the __builtin_ppc_test_data_class call is 3787 // valid. The argument must be either a 'float' or a 'double'. 3788 QualType ArgType = TheCall->getArg(0)->getType(); 3789 if (ArgType != QualType(Context.FloatTy) && 3790 ArgType != QualType(Context.DoubleTy)) 3791 return Diag(TheCall->getBeginLoc(), 3792 diag::err_ppc_invalid_test_data_class_type); 3793 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3794 diag::err_ppc_builtin_only_on_arch, "9") || 3795 SemaFeatureCheck(*this, TheCall, "vsx", 3796 diag::err_ppc_builtin_requires_vsx) || 3797 SemaBuiltinConstantArgRange(TheCall, 1, 0, 127); 3798 } 3799 case PPC::BI__builtin_ppc_load8r: 3800 case PPC::BI__builtin_ppc_store8r: 3801 return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions", 3802 diag::err_ppc_builtin_only_on_arch, "7"); 3803 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3804 case PPC::BI__builtin_##Name: \ 3805 return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types); 3806 #include "clang/Basic/BuiltinsPPC.def" 3807 } 3808 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3809 } 3810 3811 // Check if the given type is a non-pointer PPC MMA type. This function is used 3812 // in Sema to prevent invalid uses of restricted PPC MMA types. 3813 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3814 if (Type->isPointerType() || Type->isArrayType()) 3815 return false; 3816 3817 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3818 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3819 if (false 3820 #include "clang/Basic/PPCTypes.def" 3821 ) { 3822 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3823 return true; 3824 } 3825 return false; 3826 } 3827 3828 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3829 CallExpr *TheCall) { 3830 // position of memory order and scope arguments in the builtin 3831 unsigned OrderIndex, ScopeIndex; 3832 switch (BuiltinID) { 3833 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3834 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3835 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3836 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3837 OrderIndex = 2; 3838 ScopeIndex = 3; 3839 break; 3840 case AMDGPU::BI__builtin_amdgcn_fence: 3841 OrderIndex = 0; 3842 ScopeIndex = 1; 3843 break; 3844 default: 3845 return false; 3846 } 3847 3848 ExprResult Arg = TheCall->getArg(OrderIndex); 3849 auto ArgExpr = Arg.get(); 3850 Expr::EvalResult ArgResult; 3851 3852 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3853 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3854 << ArgExpr->getType(); 3855 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3856 3857 // Check validity of memory ordering as per C11 / C++11's memody model. 3858 // Only fence needs check. Atomic dec/inc allow all memory orders. 3859 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3860 return Diag(ArgExpr->getBeginLoc(), 3861 diag::warn_atomic_op_has_invalid_memory_order) 3862 << ArgExpr->getSourceRange(); 3863 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3864 case llvm::AtomicOrderingCABI::relaxed: 3865 case llvm::AtomicOrderingCABI::consume: 3866 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3867 return Diag(ArgExpr->getBeginLoc(), 3868 diag::warn_atomic_op_has_invalid_memory_order) 3869 << ArgExpr->getSourceRange(); 3870 break; 3871 case llvm::AtomicOrderingCABI::acquire: 3872 case llvm::AtomicOrderingCABI::release: 3873 case llvm::AtomicOrderingCABI::acq_rel: 3874 case llvm::AtomicOrderingCABI::seq_cst: 3875 break; 3876 } 3877 3878 Arg = TheCall->getArg(ScopeIndex); 3879 ArgExpr = Arg.get(); 3880 Expr::EvalResult ArgResult1; 3881 // Check that sync scope is a constant literal 3882 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3883 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3884 << ArgExpr->getType(); 3885 3886 return false; 3887 } 3888 3889 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3890 llvm::APSInt Result; 3891 3892 // We can't check the value of a dependent argument. 3893 Expr *Arg = TheCall->getArg(ArgNum); 3894 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3895 return false; 3896 3897 // Check constant-ness first. 3898 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3899 return true; 3900 3901 int64_t Val = Result.getSExtValue(); 3902 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3903 return false; 3904 3905 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3906 << Arg->getSourceRange(); 3907 } 3908 3909 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3910 unsigned BuiltinID, 3911 CallExpr *TheCall) { 3912 // CodeGenFunction can also detect this, but this gives a better error 3913 // message. 3914 bool FeatureMissing = false; 3915 SmallVector<StringRef> ReqFeatures; 3916 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3917 Features.split(ReqFeatures, ','); 3918 3919 // Check if each required feature is included 3920 for (StringRef F : ReqFeatures) { 3921 if (TI.hasFeature(F)) 3922 continue; 3923 3924 // If the feature is 64bit, alter the string so it will print better in 3925 // the diagnostic. 3926 if (F == "64bit") 3927 F = "RV64"; 3928 3929 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3930 F.consume_front("experimental-"); 3931 std::string FeatureStr = F.str(); 3932 FeatureStr[0] = std::toupper(FeatureStr[0]); 3933 3934 // Error message 3935 FeatureMissing = true; 3936 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3937 << TheCall->getSourceRange() << StringRef(FeatureStr); 3938 } 3939 3940 if (FeatureMissing) 3941 return true; 3942 3943 switch (BuiltinID) { 3944 case RISCVVector::BI__builtin_rvv_vsetvli: 3945 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3946 CheckRISCVLMUL(TheCall, 2); 3947 case RISCVVector::BI__builtin_rvv_vsetvlimax: 3948 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3949 CheckRISCVLMUL(TheCall, 1); 3950 } 3951 3952 return false; 3953 } 3954 3955 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3956 CallExpr *TheCall) { 3957 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3958 Expr *Arg = TheCall->getArg(0); 3959 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3960 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3961 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3962 << Arg->getSourceRange(); 3963 } 3964 3965 // For intrinsics which take an immediate value as part of the instruction, 3966 // range check them here. 3967 unsigned i = 0, l = 0, u = 0; 3968 switch (BuiltinID) { 3969 default: return false; 3970 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3971 case SystemZ::BI__builtin_s390_verimb: 3972 case SystemZ::BI__builtin_s390_verimh: 3973 case SystemZ::BI__builtin_s390_verimf: 3974 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3975 case SystemZ::BI__builtin_s390_vfaeb: 3976 case SystemZ::BI__builtin_s390_vfaeh: 3977 case SystemZ::BI__builtin_s390_vfaef: 3978 case SystemZ::BI__builtin_s390_vfaebs: 3979 case SystemZ::BI__builtin_s390_vfaehs: 3980 case SystemZ::BI__builtin_s390_vfaefs: 3981 case SystemZ::BI__builtin_s390_vfaezb: 3982 case SystemZ::BI__builtin_s390_vfaezh: 3983 case SystemZ::BI__builtin_s390_vfaezf: 3984 case SystemZ::BI__builtin_s390_vfaezbs: 3985 case SystemZ::BI__builtin_s390_vfaezhs: 3986 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3987 case SystemZ::BI__builtin_s390_vfisb: 3988 case SystemZ::BI__builtin_s390_vfidb: 3989 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3990 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3991 case SystemZ::BI__builtin_s390_vftcisb: 3992 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3993 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3994 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3995 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3996 case SystemZ::BI__builtin_s390_vstrcb: 3997 case SystemZ::BI__builtin_s390_vstrch: 3998 case SystemZ::BI__builtin_s390_vstrcf: 3999 case SystemZ::BI__builtin_s390_vstrczb: 4000 case SystemZ::BI__builtin_s390_vstrczh: 4001 case SystemZ::BI__builtin_s390_vstrczf: 4002 case SystemZ::BI__builtin_s390_vstrcbs: 4003 case SystemZ::BI__builtin_s390_vstrchs: 4004 case SystemZ::BI__builtin_s390_vstrcfs: 4005 case SystemZ::BI__builtin_s390_vstrczbs: 4006 case SystemZ::BI__builtin_s390_vstrczhs: 4007 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 4008 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 4009 case SystemZ::BI__builtin_s390_vfminsb: 4010 case SystemZ::BI__builtin_s390_vfmaxsb: 4011 case SystemZ::BI__builtin_s390_vfmindb: 4012 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 4013 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 4014 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 4015 case SystemZ::BI__builtin_s390_vclfnhs: 4016 case SystemZ::BI__builtin_s390_vclfnls: 4017 case SystemZ::BI__builtin_s390_vcfn: 4018 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 4019 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 4020 } 4021 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 4022 } 4023 4024 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 4025 /// This checks that the target supports __builtin_cpu_supports and 4026 /// that the string argument is constant and valid. 4027 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 4028 CallExpr *TheCall) { 4029 Expr *Arg = TheCall->getArg(0); 4030 4031 // Check if the argument is a string literal. 4032 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4033 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 4034 << Arg->getSourceRange(); 4035 4036 // Check the contents of the string. 4037 StringRef Feature = 4038 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4039 if (!TI.validateCpuSupports(Feature)) 4040 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 4041 << Arg->getSourceRange(); 4042 return false; 4043 } 4044 4045 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 4046 /// This checks that the target supports __builtin_cpu_is and 4047 /// that the string argument is constant and valid. 4048 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 4049 Expr *Arg = TheCall->getArg(0); 4050 4051 // Check if the argument is a string literal. 4052 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4053 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 4054 << Arg->getSourceRange(); 4055 4056 // Check the contents of the string. 4057 StringRef Feature = 4058 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4059 if (!TI.validateCpuIs(Feature)) 4060 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 4061 << Arg->getSourceRange(); 4062 return false; 4063 } 4064 4065 // Check if the rounding mode is legal. 4066 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 4067 // Indicates if this instruction has rounding control or just SAE. 4068 bool HasRC = false; 4069 4070 unsigned ArgNum = 0; 4071 switch (BuiltinID) { 4072 default: 4073 return false; 4074 case X86::BI__builtin_ia32_vcvttsd2si32: 4075 case X86::BI__builtin_ia32_vcvttsd2si64: 4076 case X86::BI__builtin_ia32_vcvttsd2usi32: 4077 case X86::BI__builtin_ia32_vcvttsd2usi64: 4078 case X86::BI__builtin_ia32_vcvttss2si32: 4079 case X86::BI__builtin_ia32_vcvttss2si64: 4080 case X86::BI__builtin_ia32_vcvttss2usi32: 4081 case X86::BI__builtin_ia32_vcvttss2usi64: 4082 case X86::BI__builtin_ia32_vcvttsh2si32: 4083 case X86::BI__builtin_ia32_vcvttsh2si64: 4084 case X86::BI__builtin_ia32_vcvttsh2usi32: 4085 case X86::BI__builtin_ia32_vcvttsh2usi64: 4086 ArgNum = 1; 4087 break; 4088 case X86::BI__builtin_ia32_maxpd512: 4089 case X86::BI__builtin_ia32_maxps512: 4090 case X86::BI__builtin_ia32_minpd512: 4091 case X86::BI__builtin_ia32_minps512: 4092 case X86::BI__builtin_ia32_maxph512: 4093 case X86::BI__builtin_ia32_minph512: 4094 ArgNum = 2; 4095 break; 4096 case X86::BI__builtin_ia32_vcvtph2pd512_mask: 4097 case X86::BI__builtin_ia32_vcvtph2psx512_mask: 4098 case X86::BI__builtin_ia32_cvtps2pd512_mask: 4099 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 4100 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 4101 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 4102 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 4103 case X86::BI__builtin_ia32_cvttps2dq512_mask: 4104 case X86::BI__builtin_ia32_cvttps2qq512_mask: 4105 case X86::BI__builtin_ia32_cvttps2udq512_mask: 4106 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 4107 case X86::BI__builtin_ia32_vcvttph2w512_mask: 4108 case X86::BI__builtin_ia32_vcvttph2uw512_mask: 4109 case X86::BI__builtin_ia32_vcvttph2dq512_mask: 4110 case X86::BI__builtin_ia32_vcvttph2udq512_mask: 4111 case X86::BI__builtin_ia32_vcvttph2qq512_mask: 4112 case X86::BI__builtin_ia32_vcvttph2uqq512_mask: 4113 case X86::BI__builtin_ia32_exp2pd_mask: 4114 case X86::BI__builtin_ia32_exp2ps_mask: 4115 case X86::BI__builtin_ia32_getexppd512_mask: 4116 case X86::BI__builtin_ia32_getexpps512_mask: 4117 case X86::BI__builtin_ia32_getexpph512_mask: 4118 case X86::BI__builtin_ia32_rcp28pd_mask: 4119 case X86::BI__builtin_ia32_rcp28ps_mask: 4120 case X86::BI__builtin_ia32_rsqrt28pd_mask: 4121 case X86::BI__builtin_ia32_rsqrt28ps_mask: 4122 case X86::BI__builtin_ia32_vcomisd: 4123 case X86::BI__builtin_ia32_vcomiss: 4124 case X86::BI__builtin_ia32_vcomish: 4125 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 4126 ArgNum = 3; 4127 break; 4128 case X86::BI__builtin_ia32_cmppd512_mask: 4129 case X86::BI__builtin_ia32_cmpps512_mask: 4130 case X86::BI__builtin_ia32_cmpsd_mask: 4131 case X86::BI__builtin_ia32_cmpss_mask: 4132 case X86::BI__builtin_ia32_cmpsh_mask: 4133 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: 4134 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: 4135 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 4136 case X86::BI__builtin_ia32_getexpsd128_round_mask: 4137 case X86::BI__builtin_ia32_getexpss128_round_mask: 4138 case X86::BI__builtin_ia32_getexpsh128_round_mask: 4139 case X86::BI__builtin_ia32_getmantpd512_mask: 4140 case X86::BI__builtin_ia32_getmantps512_mask: 4141 case X86::BI__builtin_ia32_getmantph512_mask: 4142 case X86::BI__builtin_ia32_maxsd_round_mask: 4143 case X86::BI__builtin_ia32_maxss_round_mask: 4144 case X86::BI__builtin_ia32_maxsh_round_mask: 4145 case X86::BI__builtin_ia32_minsd_round_mask: 4146 case X86::BI__builtin_ia32_minss_round_mask: 4147 case X86::BI__builtin_ia32_minsh_round_mask: 4148 case X86::BI__builtin_ia32_rcp28sd_round_mask: 4149 case X86::BI__builtin_ia32_rcp28ss_round_mask: 4150 case X86::BI__builtin_ia32_reducepd512_mask: 4151 case X86::BI__builtin_ia32_reduceps512_mask: 4152 case X86::BI__builtin_ia32_reduceph512_mask: 4153 case X86::BI__builtin_ia32_rndscalepd_mask: 4154 case X86::BI__builtin_ia32_rndscaleps_mask: 4155 case X86::BI__builtin_ia32_rndscaleph_mask: 4156 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 4157 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 4158 ArgNum = 4; 4159 break; 4160 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4161 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4162 case X86::BI__builtin_ia32_fixupimmps512_mask: 4163 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4164 case X86::BI__builtin_ia32_fixupimmsd_mask: 4165 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4166 case X86::BI__builtin_ia32_fixupimmss_mask: 4167 case X86::BI__builtin_ia32_fixupimmss_maskz: 4168 case X86::BI__builtin_ia32_getmantsd_round_mask: 4169 case X86::BI__builtin_ia32_getmantss_round_mask: 4170 case X86::BI__builtin_ia32_getmantsh_round_mask: 4171 case X86::BI__builtin_ia32_rangepd512_mask: 4172 case X86::BI__builtin_ia32_rangeps512_mask: 4173 case X86::BI__builtin_ia32_rangesd128_round_mask: 4174 case X86::BI__builtin_ia32_rangess128_round_mask: 4175 case X86::BI__builtin_ia32_reducesd_mask: 4176 case X86::BI__builtin_ia32_reducess_mask: 4177 case X86::BI__builtin_ia32_reducesh_mask: 4178 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4179 case X86::BI__builtin_ia32_rndscaless_round_mask: 4180 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4181 ArgNum = 5; 4182 break; 4183 case X86::BI__builtin_ia32_vcvtsd2si64: 4184 case X86::BI__builtin_ia32_vcvtsd2si32: 4185 case X86::BI__builtin_ia32_vcvtsd2usi32: 4186 case X86::BI__builtin_ia32_vcvtsd2usi64: 4187 case X86::BI__builtin_ia32_vcvtss2si32: 4188 case X86::BI__builtin_ia32_vcvtss2si64: 4189 case X86::BI__builtin_ia32_vcvtss2usi32: 4190 case X86::BI__builtin_ia32_vcvtss2usi64: 4191 case X86::BI__builtin_ia32_vcvtsh2si32: 4192 case X86::BI__builtin_ia32_vcvtsh2si64: 4193 case X86::BI__builtin_ia32_vcvtsh2usi32: 4194 case X86::BI__builtin_ia32_vcvtsh2usi64: 4195 case X86::BI__builtin_ia32_sqrtpd512: 4196 case X86::BI__builtin_ia32_sqrtps512: 4197 case X86::BI__builtin_ia32_sqrtph512: 4198 ArgNum = 1; 4199 HasRC = true; 4200 break; 4201 case X86::BI__builtin_ia32_addph512: 4202 case X86::BI__builtin_ia32_divph512: 4203 case X86::BI__builtin_ia32_mulph512: 4204 case X86::BI__builtin_ia32_subph512: 4205 case X86::BI__builtin_ia32_addpd512: 4206 case X86::BI__builtin_ia32_addps512: 4207 case X86::BI__builtin_ia32_divpd512: 4208 case X86::BI__builtin_ia32_divps512: 4209 case X86::BI__builtin_ia32_mulpd512: 4210 case X86::BI__builtin_ia32_mulps512: 4211 case X86::BI__builtin_ia32_subpd512: 4212 case X86::BI__builtin_ia32_subps512: 4213 case X86::BI__builtin_ia32_cvtsi2sd64: 4214 case X86::BI__builtin_ia32_cvtsi2ss32: 4215 case X86::BI__builtin_ia32_cvtsi2ss64: 4216 case X86::BI__builtin_ia32_cvtusi2sd64: 4217 case X86::BI__builtin_ia32_cvtusi2ss32: 4218 case X86::BI__builtin_ia32_cvtusi2ss64: 4219 case X86::BI__builtin_ia32_vcvtusi2sh: 4220 case X86::BI__builtin_ia32_vcvtusi642sh: 4221 case X86::BI__builtin_ia32_vcvtsi2sh: 4222 case X86::BI__builtin_ia32_vcvtsi642sh: 4223 ArgNum = 2; 4224 HasRC = true; 4225 break; 4226 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 4227 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 4228 case X86::BI__builtin_ia32_vcvtpd2ph512_mask: 4229 case X86::BI__builtin_ia32_vcvtps2phx512_mask: 4230 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 4231 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 4232 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 4233 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 4234 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 4235 case X86::BI__builtin_ia32_cvtps2dq512_mask: 4236 case X86::BI__builtin_ia32_cvtps2qq512_mask: 4237 case X86::BI__builtin_ia32_cvtps2udq512_mask: 4238 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 4239 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 4240 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 4241 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 4242 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 4243 case X86::BI__builtin_ia32_vcvtdq2ph512_mask: 4244 case X86::BI__builtin_ia32_vcvtudq2ph512_mask: 4245 case X86::BI__builtin_ia32_vcvtw2ph512_mask: 4246 case X86::BI__builtin_ia32_vcvtuw2ph512_mask: 4247 case X86::BI__builtin_ia32_vcvtph2w512_mask: 4248 case X86::BI__builtin_ia32_vcvtph2uw512_mask: 4249 case X86::BI__builtin_ia32_vcvtph2dq512_mask: 4250 case X86::BI__builtin_ia32_vcvtph2udq512_mask: 4251 case X86::BI__builtin_ia32_vcvtph2qq512_mask: 4252 case X86::BI__builtin_ia32_vcvtph2uqq512_mask: 4253 case X86::BI__builtin_ia32_vcvtqq2ph512_mask: 4254 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: 4255 ArgNum = 3; 4256 HasRC = true; 4257 break; 4258 case X86::BI__builtin_ia32_addsh_round_mask: 4259 case X86::BI__builtin_ia32_addss_round_mask: 4260 case X86::BI__builtin_ia32_addsd_round_mask: 4261 case X86::BI__builtin_ia32_divsh_round_mask: 4262 case X86::BI__builtin_ia32_divss_round_mask: 4263 case X86::BI__builtin_ia32_divsd_round_mask: 4264 case X86::BI__builtin_ia32_mulsh_round_mask: 4265 case X86::BI__builtin_ia32_mulss_round_mask: 4266 case X86::BI__builtin_ia32_mulsd_round_mask: 4267 case X86::BI__builtin_ia32_subsh_round_mask: 4268 case X86::BI__builtin_ia32_subss_round_mask: 4269 case X86::BI__builtin_ia32_subsd_round_mask: 4270 case X86::BI__builtin_ia32_scalefph512_mask: 4271 case X86::BI__builtin_ia32_scalefpd512_mask: 4272 case X86::BI__builtin_ia32_scalefps512_mask: 4273 case X86::BI__builtin_ia32_scalefsd_round_mask: 4274 case X86::BI__builtin_ia32_scalefss_round_mask: 4275 case X86::BI__builtin_ia32_scalefsh_round_mask: 4276 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4277 case X86::BI__builtin_ia32_vcvtss2sh_round_mask: 4278 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: 4279 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4280 case X86::BI__builtin_ia32_sqrtss_round_mask: 4281 case X86::BI__builtin_ia32_sqrtsh_round_mask: 4282 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4283 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4284 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4285 case X86::BI__builtin_ia32_vfmaddss3_mask: 4286 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4287 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4288 case X86::BI__builtin_ia32_vfmaddsh3_mask: 4289 case X86::BI__builtin_ia32_vfmaddsh3_maskz: 4290 case X86::BI__builtin_ia32_vfmaddsh3_mask3: 4291 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4292 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4293 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4294 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4295 case X86::BI__builtin_ia32_vfmaddps512_mask: 4296 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4297 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4298 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4299 case X86::BI__builtin_ia32_vfmaddph512_mask: 4300 case X86::BI__builtin_ia32_vfmaddph512_maskz: 4301 case X86::BI__builtin_ia32_vfmaddph512_mask3: 4302 case X86::BI__builtin_ia32_vfmsubph512_mask3: 4303 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4304 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4305 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4306 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4307 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4308 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4309 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4310 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4311 case X86::BI__builtin_ia32_vfmaddsubph512_mask: 4312 case X86::BI__builtin_ia32_vfmaddsubph512_maskz: 4313 case X86::BI__builtin_ia32_vfmaddsubph512_mask3: 4314 case X86::BI__builtin_ia32_vfmsubaddph512_mask3: 4315 case X86::BI__builtin_ia32_vfmaddcsh_mask: 4316 case X86::BI__builtin_ia32_vfmaddcsh_round_mask: 4317 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3: 4318 case X86::BI__builtin_ia32_vfmaddcph512_mask: 4319 case X86::BI__builtin_ia32_vfmaddcph512_maskz: 4320 case X86::BI__builtin_ia32_vfmaddcph512_mask3: 4321 case X86::BI__builtin_ia32_vfcmaddcsh_mask: 4322 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask: 4323 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3: 4324 case X86::BI__builtin_ia32_vfcmaddcph512_mask: 4325 case X86::BI__builtin_ia32_vfcmaddcph512_maskz: 4326 case X86::BI__builtin_ia32_vfcmaddcph512_mask3: 4327 case X86::BI__builtin_ia32_vfmulcsh_mask: 4328 case X86::BI__builtin_ia32_vfmulcph512_mask: 4329 case X86::BI__builtin_ia32_vfcmulcsh_mask: 4330 case X86::BI__builtin_ia32_vfcmulcph512_mask: 4331 ArgNum = 4; 4332 HasRC = true; 4333 break; 4334 } 4335 4336 llvm::APSInt Result; 4337 4338 // We can't check the value of a dependent argument. 4339 Expr *Arg = TheCall->getArg(ArgNum); 4340 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4341 return false; 4342 4343 // Check constant-ness first. 4344 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4345 return true; 4346 4347 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4348 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4349 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4350 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4351 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4352 Result == 8/*ROUND_NO_EXC*/ || 4353 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4354 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4355 return false; 4356 4357 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4358 << Arg->getSourceRange(); 4359 } 4360 4361 // Check if the gather/scatter scale is legal. 4362 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4363 CallExpr *TheCall) { 4364 unsigned ArgNum = 0; 4365 switch (BuiltinID) { 4366 default: 4367 return false; 4368 case X86::BI__builtin_ia32_gatherpfdpd: 4369 case X86::BI__builtin_ia32_gatherpfdps: 4370 case X86::BI__builtin_ia32_gatherpfqpd: 4371 case X86::BI__builtin_ia32_gatherpfqps: 4372 case X86::BI__builtin_ia32_scatterpfdpd: 4373 case X86::BI__builtin_ia32_scatterpfdps: 4374 case X86::BI__builtin_ia32_scatterpfqpd: 4375 case X86::BI__builtin_ia32_scatterpfqps: 4376 ArgNum = 3; 4377 break; 4378 case X86::BI__builtin_ia32_gatherd_pd: 4379 case X86::BI__builtin_ia32_gatherd_pd256: 4380 case X86::BI__builtin_ia32_gatherq_pd: 4381 case X86::BI__builtin_ia32_gatherq_pd256: 4382 case X86::BI__builtin_ia32_gatherd_ps: 4383 case X86::BI__builtin_ia32_gatherd_ps256: 4384 case X86::BI__builtin_ia32_gatherq_ps: 4385 case X86::BI__builtin_ia32_gatherq_ps256: 4386 case X86::BI__builtin_ia32_gatherd_q: 4387 case X86::BI__builtin_ia32_gatherd_q256: 4388 case X86::BI__builtin_ia32_gatherq_q: 4389 case X86::BI__builtin_ia32_gatherq_q256: 4390 case X86::BI__builtin_ia32_gatherd_d: 4391 case X86::BI__builtin_ia32_gatherd_d256: 4392 case X86::BI__builtin_ia32_gatherq_d: 4393 case X86::BI__builtin_ia32_gatherq_d256: 4394 case X86::BI__builtin_ia32_gather3div2df: 4395 case X86::BI__builtin_ia32_gather3div2di: 4396 case X86::BI__builtin_ia32_gather3div4df: 4397 case X86::BI__builtin_ia32_gather3div4di: 4398 case X86::BI__builtin_ia32_gather3div4sf: 4399 case X86::BI__builtin_ia32_gather3div4si: 4400 case X86::BI__builtin_ia32_gather3div8sf: 4401 case X86::BI__builtin_ia32_gather3div8si: 4402 case X86::BI__builtin_ia32_gather3siv2df: 4403 case X86::BI__builtin_ia32_gather3siv2di: 4404 case X86::BI__builtin_ia32_gather3siv4df: 4405 case X86::BI__builtin_ia32_gather3siv4di: 4406 case X86::BI__builtin_ia32_gather3siv4sf: 4407 case X86::BI__builtin_ia32_gather3siv4si: 4408 case X86::BI__builtin_ia32_gather3siv8sf: 4409 case X86::BI__builtin_ia32_gather3siv8si: 4410 case X86::BI__builtin_ia32_gathersiv8df: 4411 case X86::BI__builtin_ia32_gathersiv16sf: 4412 case X86::BI__builtin_ia32_gatherdiv8df: 4413 case X86::BI__builtin_ia32_gatherdiv16sf: 4414 case X86::BI__builtin_ia32_gathersiv8di: 4415 case X86::BI__builtin_ia32_gathersiv16si: 4416 case X86::BI__builtin_ia32_gatherdiv8di: 4417 case X86::BI__builtin_ia32_gatherdiv16si: 4418 case X86::BI__builtin_ia32_scatterdiv2df: 4419 case X86::BI__builtin_ia32_scatterdiv2di: 4420 case X86::BI__builtin_ia32_scatterdiv4df: 4421 case X86::BI__builtin_ia32_scatterdiv4di: 4422 case X86::BI__builtin_ia32_scatterdiv4sf: 4423 case X86::BI__builtin_ia32_scatterdiv4si: 4424 case X86::BI__builtin_ia32_scatterdiv8sf: 4425 case X86::BI__builtin_ia32_scatterdiv8si: 4426 case X86::BI__builtin_ia32_scattersiv2df: 4427 case X86::BI__builtin_ia32_scattersiv2di: 4428 case X86::BI__builtin_ia32_scattersiv4df: 4429 case X86::BI__builtin_ia32_scattersiv4di: 4430 case X86::BI__builtin_ia32_scattersiv4sf: 4431 case X86::BI__builtin_ia32_scattersiv4si: 4432 case X86::BI__builtin_ia32_scattersiv8sf: 4433 case X86::BI__builtin_ia32_scattersiv8si: 4434 case X86::BI__builtin_ia32_scattersiv8df: 4435 case X86::BI__builtin_ia32_scattersiv16sf: 4436 case X86::BI__builtin_ia32_scatterdiv8df: 4437 case X86::BI__builtin_ia32_scatterdiv16sf: 4438 case X86::BI__builtin_ia32_scattersiv8di: 4439 case X86::BI__builtin_ia32_scattersiv16si: 4440 case X86::BI__builtin_ia32_scatterdiv8di: 4441 case X86::BI__builtin_ia32_scatterdiv16si: 4442 ArgNum = 4; 4443 break; 4444 } 4445 4446 llvm::APSInt Result; 4447 4448 // We can't check the value of a dependent argument. 4449 Expr *Arg = TheCall->getArg(ArgNum); 4450 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4451 return false; 4452 4453 // Check constant-ness first. 4454 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4455 return true; 4456 4457 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4458 return false; 4459 4460 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4461 << Arg->getSourceRange(); 4462 } 4463 4464 enum { TileRegLow = 0, TileRegHigh = 7 }; 4465 4466 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4467 ArrayRef<int> ArgNums) { 4468 for (int ArgNum : ArgNums) { 4469 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4470 return true; 4471 } 4472 return false; 4473 } 4474 4475 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4476 ArrayRef<int> ArgNums) { 4477 // Because the max number of tile register is TileRegHigh + 1, so here we use 4478 // each bit to represent the usage of them in bitset. 4479 std::bitset<TileRegHigh + 1> ArgValues; 4480 for (int ArgNum : ArgNums) { 4481 Expr *Arg = TheCall->getArg(ArgNum); 4482 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4483 continue; 4484 4485 llvm::APSInt Result; 4486 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4487 return true; 4488 int ArgExtValue = Result.getExtValue(); 4489 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4490 "Incorrect tile register num."); 4491 if (ArgValues.test(ArgExtValue)) 4492 return Diag(TheCall->getBeginLoc(), 4493 diag::err_x86_builtin_tile_arg_duplicate) 4494 << TheCall->getArg(ArgNum)->getSourceRange(); 4495 ArgValues.set(ArgExtValue); 4496 } 4497 return false; 4498 } 4499 4500 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4501 ArrayRef<int> ArgNums) { 4502 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4503 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4504 } 4505 4506 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4507 switch (BuiltinID) { 4508 default: 4509 return false; 4510 case X86::BI__builtin_ia32_tileloadd64: 4511 case X86::BI__builtin_ia32_tileloaddt164: 4512 case X86::BI__builtin_ia32_tilestored64: 4513 case X86::BI__builtin_ia32_tilezero: 4514 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4515 case X86::BI__builtin_ia32_tdpbssd: 4516 case X86::BI__builtin_ia32_tdpbsud: 4517 case X86::BI__builtin_ia32_tdpbusd: 4518 case X86::BI__builtin_ia32_tdpbuud: 4519 case X86::BI__builtin_ia32_tdpbf16ps: 4520 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4521 } 4522 } 4523 static bool isX86_32Builtin(unsigned BuiltinID) { 4524 // These builtins only work on x86-32 targets. 4525 switch (BuiltinID) { 4526 case X86::BI__builtin_ia32_readeflags_u32: 4527 case X86::BI__builtin_ia32_writeeflags_u32: 4528 return true; 4529 } 4530 4531 return false; 4532 } 4533 4534 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4535 CallExpr *TheCall) { 4536 if (BuiltinID == X86::BI__builtin_cpu_supports) 4537 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4538 4539 if (BuiltinID == X86::BI__builtin_cpu_is) 4540 return SemaBuiltinCpuIs(*this, TI, TheCall); 4541 4542 // Check for 32-bit only builtins on a 64-bit target. 4543 const llvm::Triple &TT = TI.getTriple(); 4544 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4545 return Diag(TheCall->getCallee()->getBeginLoc(), 4546 diag::err_32_bit_builtin_64_bit_tgt); 4547 4548 // If the intrinsic has rounding or SAE make sure its valid. 4549 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4550 return true; 4551 4552 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4553 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4554 return true; 4555 4556 // If the intrinsic has a tile arguments, make sure they are valid. 4557 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4558 return true; 4559 4560 // For intrinsics which take an immediate value as part of the instruction, 4561 // range check them here. 4562 int i = 0, l = 0, u = 0; 4563 switch (BuiltinID) { 4564 default: 4565 return false; 4566 case X86::BI__builtin_ia32_vec_ext_v2si: 4567 case X86::BI__builtin_ia32_vec_ext_v2di: 4568 case X86::BI__builtin_ia32_vextractf128_pd256: 4569 case X86::BI__builtin_ia32_vextractf128_ps256: 4570 case X86::BI__builtin_ia32_vextractf128_si256: 4571 case X86::BI__builtin_ia32_extract128i256: 4572 case X86::BI__builtin_ia32_extractf64x4_mask: 4573 case X86::BI__builtin_ia32_extracti64x4_mask: 4574 case X86::BI__builtin_ia32_extractf32x8_mask: 4575 case X86::BI__builtin_ia32_extracti32x8_mask: 4576 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4577 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4578 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4579 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4580 i = 1; l = 0; u = 1; 4581 break; 4582 case X86::BI__builtin_ia32_vec_set_v2di: 4583 case X86::BI__builtin_ia32_vinsertf128_pd256: 4584 case X86::BI__builtin_ia32_vinsertf128_ps256: 4585 case X86::BI__builtin_ia32_vinsertf128_si256: 4586 case X86::BI__builtin_ia32_insert128i256: 4587 case X86::BI__builtin_ia32_insertf32x8: 4588 case X86::BI__builtin_ia32_inserti32x8: 4589 case X86::BI__builtin_ia32_insertf64x4: 4590 case X86::BI__builtin_ia32_inserti64x4: 4591 case X86::BI__builtin_ia32_insertf64x2_256: 4592 case X86::BI__builtin_ia32_inserti64x2_256: 4593 case X86::BI__builtin_ia32_insertf32x4_256: 4594 case X86::BI__builtin_ia32_inserti32x4_256: 4595 i = 2; l = 0; u = 1; 4596 break; 4597 case X86::BI__builtin_ia32_vpermilpd: 4598 case X86::BI__builtin_ia32_vec_ext_v4hi: 4599 case X86::BI__builtin_ia32_vec_ext_v4si: 4600 case X86::BI__builtin_ia32_vec_ext_v4sf: 4601 case X86::BI__builtin_ia32_vec_ext_v4di: 4602 case X86::BI__builtin_ia32_extractf32x4_mask: 4603 case X86::BI__builtin_ia32_extracti32x4_mask: 4604 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4605 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4606 i = 1; l = 0; u = 3; 4607 break; 4608 case X86::BI_mm_prefetch: 4609 case X86::BI__builtin_ia32_vec_ext_v8hi: 4610 case X86::BI__builtin_ia32_vec_ext_v8si: 4611 i = 1; l = 0; u = 7; 4612 break; 4613 case X86::BI__builtin_ia32_sha1rnds4: 4614 case X86::BI__builtin_ia32_blendpd: 4615 case X86::BI__builtin_ia32_shufpd: 4616 case X86::BI__builtin_ia32_vec_set_v4hi: 4617 case X86::BI__builtin_ia32_vec_set_v4si: 4618 case X86::BI__builtin_ia32_vec_set_v4di: 4619 case X86::BI__builtin_ia32_shuf_f32x4_256: 4620 case X86::BI__builtin_ia32_shuf_f64x2_256: 4621 case X86::BI__builtin_ia32_shuf_i32x4_256: 4622 case X86::BI__builtin_ia32_shuf_i64x2_256: 4623 case X86::BI__builtin_ia32_insertf64x2_512: 4624 case X86::BI__builtin_ia32_inserti64x2_512: 4625 case X86::BI__builtin_ia32_insertf32x4: 4626 case X86::BI__builtin_ia32_inserti32x4: 4627 i = 2; l = 0; u = 3; 4628 break; 4629 case X86::BI__builtin_ia32_vpermil2pd: 4630 case X86::BI__builtin_ia32_vpermil2pd256: 4631 case X86::BI__builtin_ia32_vpermil2ps: 4632 case X86::BI__builtin_ia32_vpermil2ps256: 4633 i = 3; l = 0; u = 3; 4634 break; 4635 case X86::BI__builtin_ia32_cmpb128_mask: 4636 case X86::BI__builtin_ia32_cmpw128_mask: 4637 case X86::BI__builtin_ia32_cmpd128_mask: 4638 case X86::BI__builtin_ia32_cmpq128_mask: 4639 case X86::BI__builtin_ia32_cmpb256_mask: 4640 case X86::BI__builtin_ia32_cmpw256_mask: 4641 case X86::BI__builtin_ia32_cmpd256_mask: 4642 case X86::BI__builtin_ia32_cmpq256_mask: 4643 case X86::BI__builtin_ia32_cmpb512_mask: 4644 case X86::BI__builtin_ia32_cmpw512_mask: 4645 case X86::BI__builtin_ia32_cmpd512_mask: 4646 case X86::BI__builtin_ia32_cmpq512_mask: 4647 case X86::BI__builtin_ia32_ucmpb128_mask: 4648 case X86::BI__builtin_ia32_ucmpw128_mask: 4649 case X86::BI__builtin_ia32_ucmpd128_mask: 4650 case X86::BI__builtin_ia32_ucmpq128_mask: 4651 case X86::BI__builtin_ia32_ucmpb256_mask: 4652 case X86::BI__builtin_ia32_ucmpw256_mask: 4653 case X86::BI__builtin_ia32_ucmpd256_mask: 4654 case X86::BI__builtin_ia32_ucmpq256_mask: 4655 case X86::BI__builtin_ia32_ucmpb512_mask: 4656 case X86::BI__builtin_ia32_ucmpw512_mask: 4657 case X86::BI__builtin_ia32_ucmpd512_mask: 4658 case X86::BI__builtin_ia32_ucmpq512_mask: 4659 case X86::BI__builtin_ia32_vpcomub: 4660 case X86::BI__builtin_ia32_vpcomuw: 4661 case X86::BI__builtin_ia32_vpcomud: 4662 case X86::BI__builtin_ia32_vpcomuq: 4663 case X86::BI__builtin_ia32_vpcomb: 4664 case X86::BI__builtin_ia32_vpcomw: 4665 case X86::BI__builtin_ia32_vpcomd: 4666 case X86::BI__builtin_ia32_vpcomq: 4667 case X86::BI__builtin_ia32_vec_set_v8hi: 4668 case X86::BI__builtin_ia32_vec_set_v8si: 4669 i = 2; l = 0; u = 7; 4670 break; 4671 case X86::BI__builtin_ia32_vpermilpd256: 4672 case X86::BI__builtin_ia32_roundps: 4673 case X86::BI__builtin_ia32_roundpd: 4674 case X86::BI__builtin_ia32_roundps256: 4675 case X86::BI__builtin_ia32_roundpd256: 4676 case X86::BI__builtin_ia32_getmantpd128_mask: 4677 case X86::BI__builtin_ia32_getmantpd256_mask: 4678 case X86::BI__builtin_ia32_getmantps128_mask: 4679 case X86::BI__builtin_ia32_getmantps256_mask: 4680 case X86::BI__builtin_ia32_getmantpd512_mask: 4681 case X86::BI__builtin_ia32_getmantps512_mask: 4682 case X86::BI__builtin_ia32_getmantph128_mask: 4683 case X86::BI__builtin_ia32_getmantph256_mask: 4684 case X86::BI__builtin_ia32_getmantph512_mask: 4685 case X86::BI__builtin_ia32_vec_ext_v16qi: 4686 case X86::BI__builtin_ia32_vec_ext_v16hi: 4687 i = 1; l = 0; u = 15; 4688 break; 4689 case X86::BI__builtin_ia32_pblendd128: 4690 case X86::BI__builtin_ia32_blendps: 4691 case X86::BI__builtin_ia32_blendpd256: 4692 case X86::BI__builtin_ia32_shufpd256: 4693 case X86::BI__builtin_ia32_roundss: 4694 case X86::BI__builtin_ia32_roundsd: 4695 case X86::BI__builtin_ia32_rangepd128_mask: 4696 case X86::BI__builtin_ia32_rangepd256_mask: 4697 case X86::BI__builtin_ia32_rangepd512_mask: 4698 case X86::BI__builtin_ia32_rangeps128_mask: 4699 case X86::BI__builtin_ia32_rangeps256_mask: 4700 case X86::BI__builtin_ia32_rangeps512_mask: 4701 case X86::BI__builtin_ia32_getmantsd_round_mask: 4702 case X86::BI__builtin_ia32_getmantss_round_mask: 4703 case X86::BI__builtin_ia32_getmantsh_round_mask: 4704 case X86::BI__builtin_ia32_vec_set_v16qi: 4705 case X86::BI__builtin_ia32_vec_set_v16hi: 4706 i = 2; l = 0; u = 15; 4707 break; 4708 case X86::BI__builtin_ia32_vec_ext_v32qi: 4709 i = 1; l = 0; u = 31; 4710 break; 4711 case X86::BI__builtin_ia32_cmpps: 4712 case X86::BI__builtin_ia32_cmpss: 4713 case X86::BI__builtin_ia32_cmppd: 4714 case X86::BI__builtin_ia32_cmpsd: 4715 case X86::BI__builtin_ia32_cmpps256: 4716 case X86::BI__builtin_ia32_cmppd256: 4717 case X86::BI__builtin_ia32_cmpps128_mask: 4718 case X86::BI__builtin_ia32_cmppd128_mask: 4719 case X86::BI__builtin_ia32_cmpps256_mask: 4720 case X86::BI__builtin_ia32_cmppd256_mask: 4721 case X86::BI__builtin_ia32_cmpps512_mask: 4722 case X86::BI__builtin_ia32_cmppd512_mask: 4723 case X86::BI__builtin_ia32_cmpsd_mask: 4724 case X86::BI__builtin_ia32_cmpss_mask: 4725 case X86::BI__builtin_ia32_vec_set_v32qi: 4726 i = 2; l = 0; u = 31; 4727 break; 4728 case X86::BI__builtin_ia32_permdf256: 4729 case X86::BI__builtin_ia32_permdi256: 4730 case X86::BI__builtin_ia32_permdf512: 4731 case X86::BI__builtin_ia32_permdi512: 4732 case X86::BI__builtin_ia32_vpermilps: 4733 case X86::BI__builtin_ia32_vpermilps256: 4734 case X86::BI__builtin_ia32_vpermilpd512: 4735 case X86::BI__builtin_ia32_vpermilps512: 4736 case X86::BI__builtin_ia32_pshufd: 4737 case X86::BI__builtin_ia32_pshufd256: 4738 case X86::BI__builtin_ia32_pshufd512: 4739 case X86::BI__builtin_ia32_pshufhw: 4740 case X86::BI__builtin_ia32_pshufhw256: 4741 case X86::BI__builtin_ia32_pshufhw512: 4742 case X86::BI__builtin_ia32_pshuflw: 4743 case X86::BI__builtin_ia32_pshuflw256: 4744 case X86::BI__builtin_ia32_pshuflw512: 4745 case X86::BI__builtin_ia32_vcvtps2ph: 4746 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4747 case X86::BI__builtin_ia32_vcvtps2ph256: 4748 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4749 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4750 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4751 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4752 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4753 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4754 case X86::BI__builtin_ia32_rndscaleps_mask: 4755 case X86::BI__builtin_ia32_rndscalepd_mask: 4756 case X86::BI__builtin_ia32_rndscaleph_mask: 4757 case X86::BI__builtin_ia32_reducepd128_mask: 4758 case X86::BI__builtin_ia32_reducepd256_mask: 4759 case X86::BI__builtin_ia32_reducepd512_mask: 4760 case X86::BI__builtin_ia32_reduceps128_mask: 4761 case X86::BI__builtin_ia32_reduceps256_mask: 4762 case X86::BI__builtin_ia32_reduceps512_mask: 4763 case X86::BI__builtin_ia32_reduceph128_mask: 4764 case X86::BI__builtin_ia32_reduceph256_mask: 4765 case X86::BI__builtin_ia32_reduceph512_mask: 4766 case X86::BI__builtin_ia32_prold512: 4767 case X86::BI__builtin_ia32_prolq512: 4768 case X86::BI__builtin_ia32_prold128: 4769 case X86::BI__builtin_ia32_prold256: 4770 case X86::BI__builtin_ia32_prolq128: 4771 case X86::BI__builtin_ia32_prolq256: 4772 case X86::BI__builtin_ia32_prord512: 4773 case X86::BI__builtin_ia32_prorq512: 4774 case X86::BI__builtin_ia32_prord128: 4775 case X86::BI__builtin_ia32_prord256: 4776 case X86::BI__builtin_ia32_prorq128: 4777 case X86::BI__builtin_ia32_prorq256: 4778 case X86::BI__builtin_ia32_fpclasspd128_mask: 4779 case X86::BI__builtin_ia32_fpclasspd256_mask: 4780 case X86::BI__builtin_ia32_fpclassps128_mask: 4781 case X86::BI__builtin_ia32_fpclassps256_mask: 4782 case X86::BI__builtin_ia32_fpclassps512_mask: 4783 case X86::BI__builtin_ia32_fpclasspd512_mask: 4784 case X86::BI__builtin_ia32_fpclassph128_mask: 4785 case X86::BI__builtin_ia32_fpclassph256_mask: 4786 case X86::BI__builtin_ia32_fpclassph512_mask: 4787 case X86::BI__builtin_ia32_fpclasssd_mask: 4788 case X86::BI__builtin_ia32_fpclassss_mask: 4789 case X86::BI__builtin_ia32_fpclasssh_mask: 4790 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4791 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4792 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4793 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4794 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4795 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4796 case X86::BI__builtin_ia32_kshiftliqi: 4797 case X86::BI__builtin_ia32_kshiftlihi: 4798 case X86::BI__builtin_ia32_kshiftlisi: 4799 case X86::BI__builtin_ia32_kshiftlidi: 4800 case X86::BI__builtin_ia32_kshiftriqi: 4801 case X86::BI__builtin_ia32_kshiftrihi: 4802 case X86::BI__builtin_ia32_kshiftrisi: 4803 case X86::BI__builtin_ia32_kshiftridi: 4804 i = 1; l = 0; u = 255; 4805 break; 4806 case X86::BI__builtin_ia32_vperm2f128_pd256: 4807 case X86::BI__builtin_ia32_vperm2f128_ps256: 4808 case X86::BI__builtin_ia32_vperm2f128_si256: 4809 case X86::BI__builtin_ia32_permti256: 4810 case X86::BI__builtin_ia32_pblendw128: 4811 case X86::BI__builtin_ia32_pblendw256: 4812 case X86::BI__builtin_ia32_blendps256: 4813 case X86::BI__builtin_ia32_pblendd256: 4814 case X86::BI__builtin_ia32_palignr128: 4815 case X86::BI__builtin_ia32_palignr256: 4816 case X86::BI__builtin_ia32_palignr512: 4817 case X86::BI__builtin_ia32_alignq512: 4818 case X86::BI__builtin_ia32_alignd512: 4819 case X86::BI__builtin_ia32_alignd128: 4820 case X86::BI__builtin_ia32_alignd256: 4821 case X86::BI__builtin_ia32_alignq128: 4822 case X86::BI__builtin_ia32_alignq256: 4823 case X86::BI__builtin_ia32_vcomisd: 4824 case X86::BI__builtin_ia32_vcomiss: 4825 case X86::BI__builtin_ia32_shuf_f32x4: 4826 case X86::BI__builtin_ia32_shuf_f64x2: 4827 case X86::BI__builtin_ia32_shuf_i32x4: 4828 case X86::BI__builtin_ia32_shuf_i64x2: 4829 case X86::BI__builtin_ia32_shufpd512: 4830 case X86::BI__builtin_ia32_shufps: 4831 case X86::BI__builtin_ia32_shufps256: 4832 case X86::BI__builtin_ia32_shufps512: 4833 case X86::BI__builtin_ia32_dbpsadbw128: 4834 case X86::BI__builtin_ia32_dbpsadbw256: 4835 case X86::BI__builtin_ia32_dbpsadbw512: 4836 case X86::BI__builtin_ia32_vpshldd128: 4837 case X86::BI__builtin_ia32_vpshldd256: 4838 case X86::BI__builtin_ia32_vpshldd512: 4839 case X86::BI__builtin_ia32_vpshldq128: 4840 case X86::BI__builtin_ia32_vpshldq256: 4841 case X86::BI__builtin_ia32_vpshldq512: 4842 case X86::BI__builtin_ia32_vpshldw128: 4843 case X86::BI__builtin_ia32_vpshldw256: 4844 case X86::BI__builtin_ia32_vpshldw512: 4845 case X86::BI__builtin_ia32_vpshrdd128: 4846 case X86::BI__builtin_ia32_vpshrdd256: 4847 case X86::BI__builtin_ia32_vpshrdd512: 4848 case X86::BI__builtin_ia32_vpshrdq128: 4849 case X86::BI__builtin_ia32_vpshrdq256: 4850 case X86::BI__builtin_ia32_vpshrdq512: 4851 case X86::BI__builtin_ia32_vpshrdw128: 4852 case X86::BI__builtin_ia32_vpshrdw256: 4853 case X86::BI__builtin_ia32_vpshrdw512: 4854 i = 2; l = 0; u = 255; 4855 break; 4856 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4857 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4858 case X86::BI__builtin_ia32_fixupimmps512_mask: 4859 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4860 case X86::BI__builtin_ia32_fixupimmsd_mask: 4861 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4862 case X86::BI__builtin_ia32_fixupimmss_mask: 4863 case X86::BI__builtin_ia32_fixupimmss_maskz: 4864 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4865 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4866 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4867 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4868 case X86::BI__builtin_ia32_fixupimmps128_mask: 4869 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4870 case X86::BI__builtin_ia32_fixupimmps256_mask: 4871 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4872 case X86::BI__builtin_ia32_pternlogd512_mask: 4873 case X86::BI__builtin_ia32_pternlogd512_maskz: 4874 case X86::BI__builtin_ia32_pternlogq512_mask: 4875 case X86::BI__builtin_ia32_pternlogq512_maskz: 4876 case X86::BI__builtin_ia32_pternlogd128_mask: 4877 case X86::BI__builtin_ia32_pternlogd128_maskz: 4878 case X86::BI__builtin_ia32_pternlogd256_mask: 4879 case X86::BI__builtin_ia32_pternlogd256_maskz: 4880 case X86::BI__builtin_ia32_pternlogq128_mask: 4881 case X86::BI__builtin_ia32_pternlogq128_maskz: 4882 case X86::BI__builtin_ia32_pternlogq256_mask: 4883 case X86::BI__builtin_ia32_pternlogq256_maskz: 4884 i = 3; l = 0; u = 255; 4885 break; 4886 case X86::BI__builtin_ia32_gatherpfdpd: 4887 case X86::BI__builtin_ia32_gatherpfdps: 4888 case X86::BI__builtin_ia32_gatherpfqpd: 4889 case X86::BI__builtin_ia32_gatherpfqps: 4890 case X86::BI__builtin_ia32_scatterpfdpd: 4891 case X86::BI__builtin_ia32_scatterpfdps: 4892 case X86::BI__builtin_ia32_scatterpfqpd: 4893 case X86::BI__builtin_ia32_scatterpfqps: 4894 i = 4; l = 2; u = 3; 4895 break; 4896 case X86::BI__builtin_ia32_reducesd_mask: 4897 case X86::BI__builtin_ia32_reducess_mask: 4898 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4899 case X86::BI__builtin_ia32_rndscaless_round_mask: 4900 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4901 case X86::BI__builtin_ia32_reducesh_mask: 4902 i = 4; l = 0; u = 255; 4903 break; 4904 } 4905 4906 // Note that we don't force a hard error on the range check here, allowing 4907 // template-generated or macro-generated dead code to potentially have out-of- 4908 // range values. These need to code generate, but don't need to necessarily 4909 // make any sense. We use a warning that defaults to an error. 4910 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4911 } 4912 4913 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4914 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4915 /// Returns true when the format fits the function and the FormatStringInfo has 4916 /// been populated. 4917 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4918 FormatStringInfo *FSI) { 4919 FSI->HasVAListArg = Format->getFirstArg() == 0; 4920 FSI->FormatIdx = Format->getFormatIdx() - 1; 4921 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4922 4923 // The way the format attribute works in GCC, the implicit this argument 4924 // of member functions is counted. However, it doesn't appear in our own 4925 // lists, so decrement format_idx in that case. 4926 if (IsCXXMember) { 4927 if(FSI->FormatIdx == 0) 4928 return false; 4929 --FSI->FormatIdx; 4930 if (FSI->FirstDataArg != 0) 4931 --FSI->FirstDataArg; 4932 } 4933 return true; 4934 } 4935 4936 /// Checks if a the given expression evaluates to null. 4937 /// 4938 /// Returns true if the value evaluates to null. 4939 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4940 // If the expression has non-null type, it doesn't evaluate to null. 4941 if (auto nullability 4942 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4943 if (*nullability == NullabilityKind::NonNull) 4944 return false; 4945 } 4946 4947 // As a special case, transparent unions initialized with zero are 4948 // considered null for the purposes of the nonnull attribute. 4949 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4950 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4951 if (const CompoundLiteralExpr *CLE = 4952 dyn_cast<CompoundLiteralExpr>(Expr)) 4953 if (const InitListExpr *ILE = 4954 dyn_cast<InitListExpr>(CLE->getInitializer())) 4955 Expr = ILE->getInit(0); 4956 } 4957 4958 bool Result; 4959 return (!Expr->isValueDependent() && 4960 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4961 !Result); 4962 } 4963 4964 static void CheckNonNullArgument(Sema &S, 4965 const Expr *ArgExpr, 4966 SourceLocation CallSiteLoc) { 4967 if (CheckNonNullExpr(S, ArgExpr)) 4968 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4969 S.PDiag(diag::warn_null_arg) 4970 << ArgExpr->getSourceRange()); 4971 } 4972 4973 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4974 FormatStringInfo FSI; 4975 if ((GetFormatStringType(Format) == FST_NSString) && 4976 getFormatStringInfo(Format, false, &FSI)) { 4977 Idx = FSI.FormatIdx; 4978 return true; 4979 } 4980 return false; 4981 } 4982 4983 /// Diagnose use of %s directive in an NSString which is being passed 4984 /// as formatting string to formatting method. 4985 static void 4986 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4987 const NamedDecl *FDecl, 4988 Expr **Args, 4989 unsigned NumArgs) { 4990 unsigned Idx = 0; 4991 bool Format = false; 4992 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4993 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4994 Idx = 2; 4995 Format = true; 4996 } 4997 else 4998 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4999 if (S.GetFormatNSStringIdx(I, Idx)) { 5000 Format = true; 5001 break; 5002 } 5003 } 5004 if (!Format || NumArgs <= Idx) 5005 return; 5006 const Expr *FormatExpr = Args[Idx]; 5007 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 5008 FormatExpr = CSCE->getSubExpr(); 5009 const StringLiteral *FormatString; 5010 if (const ObjCStringLiteral *OSL = 5011 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 5012 FormatString = OSL->getString(); 5013 else 5014 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 5015 if (!FormatString) 5016 return; 5017 if (S.FormatStringHasSArg(FormatString)) { 5018 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 5019 << "%s" << 1 << 1; 5020 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 5021 << FDecl->getDeclName(); 5022 } 5023 } 5024 5025 /// Determine whether the given type has a non-null nullability annotation. 5026 static bool isNonNullType(ASTContext &ctx, QualType type) { 5027 if (auto nullability = type->getNullability(ctx)) 5028 return *nullability == NullabilityKind::NonNull; 5029 5030 return false; 5031 } 5032 5033 static void CheckNonNullArguments(Sema &S, 5034 const NamedDecl *FDecl, 5035 const FunctionProtoType *Proto, 5036 ArrayRef<const Expr *> Args, 5037 SourceLocation CallSiteLoc) { 5038 assert((FDecl || Proto) && "Need a function declaration or prototype"); 5039 5040 // Already checked by by constant evaluator. 5041 if (S.isConstantEvaluated()) 5042 return; 5043 // Check the attributes attached to the method/function itself. 5044 llvm::SmallBitVector NonNullArgs; 5045 if (FDecl) { 5046 // Handle the nonnull attribute on the function/method declaration itself. 5047 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 5048 if (!NonNull->args_size()) { 5049 // Easy case: all pointer arguments are nonnull. 5050 for (const auto *Arg : Args) 5051 if (S.isValidPointerAttrType(Arg->getType())) 5052 CheckNonNullArgument(S, Arg, CallSiteLoc); 5053 return; 5054 } 5055 5056 for (const ParamIdx &Idx : NonNull->args()) { 5057 unsigned IdxAST = Idx.getASTIndex(); 5058 if (IdxAST >= Args.size()) 5059 continue; 5060 if (NonNullArgs.empty()) 5061 NonNullArgs.resize(Args.size()); 5062 NonNullArgs.set(IdxAST); 5063 } 5064 } 5065 } 5066 5067 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 5068 // Handle the nonnull attribute on the parameters of the 5069 // function/method. 5070 ArrayRef<ParmVarDecl*> parms; 5071 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 5072 parms = FD->parameters(); 5073 else 5074 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 5075 5076 unsigned ParamIndex = 0; 5077 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 5078 I != E; ++I, ++ParamIndex) { 5079 const ParmVarDecl *PVD = *I; 5080 if (PVD->hasAttr<NonNullAttr>() || 5081 isNonNullType(S.Context, PVD->getType())) { 5082 if (NonNullArgs.empty()) 5083 NonNullArgs.resize(Args.size()); 5084 5085 NonNullArgs.set(ParamIndex); 5086 } 5087 } 5088 } else { 5089 // If we have a non-function, non-method declaration but no 5090 // function prototype, try to dig out the function prototype. 5091 if (!Proto) { 5092 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 5093 QualType type = VD->getType().getNonReferenceType(); 5094 if (auto pointerType = type->getAs<PointerType>()) 5095 type = pointerType->getPointeeType(); 5096 else if (auto blockType = type->getAs<BlockPointerType>()) 5097 type = blockType->getPointeeType(); 5098 // FIXME: data member pointers? 5099 5100 // Dig out the function prototype, if there is one. 5101 Proto = type->getAs<FunctionProtoType>(); 5102 } 5103 } 5104 5105 // Fill in non-null argument information from the nullability 5106 // information on the parameter types (if we have them). 5107 if (Proto) { 5108 unsigned Index = 0; 5109 for (auto paramType : Proto->getParamTypes()) { 5110 if (isNonNullType(S.Context, paramType)) { 5111 if (NonNullArgs.empty()) 5112 NonNullArgs.resize(Args.size()); 5113 5114 NonNullArgs.set(Index); 5115 } 5116 5117 ++Index; 5118 } 5119 } 5120 } 5121 5122 // Check for non-null arguments. 5123 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 5124 ArgIndex != ArgIndexEnd; ++ArgIndex) { 5125 if (NonNullArgs[ArgIndex]) 5126 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 5127 } 5128 } 5129 5130 /// Warn if a pointer or reference argument passed to a function points to an 5131 /// object that is less aligned than the parameter. This can happen when 5132 /// creating a typedef with a lower alignment than the original type and then 5133 /// calling functions defined in terms of the original type. 5134 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 5135 StringRef ParamName, QualType ArgTy, 5136 QualType ParamTy) { 5137 5138 // If a function accepts a pointer or reference type 5139 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 5140 return; 5141 5142 // If the parameter is a pointer type, get the pointee type for the 5143 // argument too. If the parameter is a reference type, don't try to get 5144 // the pointee type for the argument. 5145 if (ParamTy->isPointerType()) 5146 ArgTy = ArgTy->getPointeeType(); 5147 5148 // Remove reference or pointer 5149 ParamTy = ParamTy->getPointeeType(); 5150 5151 // Find expected alignment, and the actual alignment of the passed object. 5152 // getTypeAlignInChars requires complete types 5153 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 5154 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 5155 ArgTy->isUndeducedType()) 5156 return; 5157 5158 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 5159 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 5160 5161 // If the argument is less aligned than the parameter, there is a 5162 // potential alignment issue. 5163 if (ArgAlign < ParamAlign) 5164 Diag(Loc, diag::warn_param_mismatched_alignment) 5165 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 5166 << ParamName << (FDecl != nullptr) << FDecl; 5167 } 5168 5169 /// Handles the checks for format strings, non-POD arguments to vararg 5170 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 5171 /// attributes. 5172 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 5173 const Expr *ThisArg, ArrayRef<const Expr *> Args, 5174 bool IsMemberFunction, SourceLocation Loc, 5175 SourceRange Range, VariadicCallType CallType) { 5176 // FIXME: We should check as much as we can in the template definition. 5177 if (CurContext->isDependentContext()) 5178 return; 5179 5180 // Printf and scanf checking. 5181 llvm::SmallBitVector CheckedVarArgs; 5182 if (FDecl) { 5183 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5184 // Only create vector if there are format attributes. 5185 CheckedVarArgs.resize(Args.size()); 5186 5187 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 5188 CheckedVarArgs); 5189 } 5190 } 5191 5192 // Refuse POD arguments that weren't caught by the format string 5193 // checks above. 5194 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 5195 if (CallType != VariadicDoesNotApply && 5196 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 5197 unsigned NumParams = Proto ? Proto->getNumParams() 5198 : FDecl && isa<FunctionDecl>(FDecl) 5199 ? cast<FunctionDecl>(FDecl)->getNumParams() 5200 : FDecl && isa<ObjCMethodDecl>(FDecl) 5201 ? cast<ObjCMethodDecl>(FDecl)->param_size() 5202 : 0; 5203 5204 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 5205 // Args[ArgIdx] can be null in malformed code. 5206 if (const Expr *Arg = Args[ArgIdx]) { 5207 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 5208 checkVariadicArgument(Arg, CallType); 5209 } 5210 } 5211 } 5212 5213 if (FDecl || Proto) { 5214 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 5215 5216 // Type safety checking. 5217 if (FDecl) { 5218 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 5219 CheckArgumentWithTypeTag(I, Args, Loc); 5220 } 5221 } 5222 5223 // Check that passed arguments match the alignment of original arguments. 5224 // Try to get the missing prototype from the declaration. 5225 if (!Proto && FDecl) { 5226 const auto *FT = FDecl->getFunctionType(); 5227 if (isa_and_nonnull<FunctionProtoType>(FT)) 5228 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 5229 } 5230 if (Proto) { 5231 // For variadic functions, we may have more args than parameters. 5232 // For some K&R functions, we may have less args than parameters. 5233 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 5234 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 5235 // Args[ArgIdx] can be null in malformed code. 5236 if (const Expr *Arg = Args[ArgIdx]) { 5237 if (Arg->containsErrors()) 5238 continue; 5239 5240 QualType ParamTy = Proto->getParamType(ArgIdx); 5241 QualType ArgTy = Arg->getType(); 5242 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 5243 ArgTy, ParamTy); 5244 } 5245 } 5246 } 5247 5248 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 5249 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 5250 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 5251 if (!Arg->isValueDependent()) { 5252 Expr::EvalResult Align; 5253 if (Arg->EvaluateAsInt(Align, Context)) { 5254 const llvm::APSInt &I = Align.Val.getInt(); 5255 if (!I.isPowerOf2()) 5256 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 5257 << Arg->getSourceRange(); 5258 5259 if (I > Sema::MaximumAlignment) 5260 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 5261 << Arg->getSourceRange() << Sema::MaximumAlignment; 5262 } 5263 } 5264 } 5265 5266 if (FD) 5267 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 5268 } 5269 5270 /// CheckConstructorCall - Check a constructor call for correctness and safety 5271 /// properties not enforced by the C type system. 5272 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 5273 ArrayRef<const Expr *> Args, 5274 const FunctionProtoType *Proto, 5275 SourceLocation Loc) { 5276 VariadicCallType CallType = 5277 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5278 5279 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 5280 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 5281 Context.getPointerType(Ctor->getThisObjectType())); 5282 5283 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 5284 Loc, SourceRange(), CallType); 5285 } 5286 5287 /// CheckFunctionCall - Check a direct function call for various correctness 5288 /// and safety properties not strictly enforced by the C type system. 5289 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 5290 const FunctionProtoType *Proto) { 5291 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 5292 isa<CXXMethodDecl>(FDecl); 5293 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 5294 IsMemberOperatorCall; 5295 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 5296 TheCall->getCallee()); 5297 Expr** Args = TheCall->getArgs(); 5298 unsigned NumArgs = TheCall->getNumArgs(); 5299 5300 Expr *ImplicitThis = nullptr; 5301 if (IsMemberOperatorCall) { 5302 // If this is a call to a member operator, hide the first argument 5303 // from checkCall. 5304 // FIXME: Our choice of AST representation here is less than ideal. 5305 ImplicitThis = Args[0]; 5306 ++Args; 5307 --NumArgs; 5308 } else if (IsMemberFunction) 5309 ImplicitThis = 5310 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 5311 5312 if (ImplicitThis) { 5313 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 5314 // used. 5315 QualType ThisType = ImplicitThis->getType(); 5316 if (!ThisType->isPointerType()) { 5317 assert(!ThisType->isReferenceType()); 5318 ThisType = Context.getPointerType(ThisType); 5319 } 5320 5321 QualType ThisTypeFromDecl = 5322 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5323 5324 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5325 ThisTypeFromDecl); 5326 } 5327 5328 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5329 IsMemberFunction, TheCall->getRParenLoc(), 5330 TheCall->getCallee()->getSourceRange(), CallType); 5331 5332 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5333 // None of the checks below are needed for functions that don't have 5334 // simple names (e.g., C++ conversion functions). 5335 if (!FnInfo) 5336 return false; 5337 5338 CheckTCBEnforcement(TheCall, FDecl); 5339 5340 CheckAbsoluteValueFunction(TheCall, FDecl); 5341 CheckMaxUnsignedZero(TheCall, FDecl); 5342 5343 if (getLangOpts().ObjC) 5344 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5345 5346 unsigned CMId = FDecl->getMemoryFunctionKind(); 5347 5348 // Handle memory setting and copying functions. 5349 switch (CMId) { 5350 case 0: 5351 return false; 5352 case Builtin::BIstrlcpy: // fallthrough 5353 case Builtin::BIstrlcat: 5354 CheckStrlcpycatArguments(TheCall, FnInfo); 5355 break; 5356 case Builtin::BIstrncat: 5357 CheckStrncatArguments(TheCall, FnInfo); 5358 break; 5359 case Builtin::BIfree: 5360 CheckFreeArguments(TheCall); 5361 break; 5362 default: 5363 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5364 } 5365 5366 return false; 5367 } 5368 5369 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5370 ArrayRef<const Expr *> Args) { 5371 VariadicCallType CallType = 5372 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5373 5374 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5375 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5376 CallType); 5377 5378 return false; 5379 } 5380 5381 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5382 const FunctionProtoType *Proto) { 5383 QualType Ty; 5384 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5385 Ty = V->getType().getNonReferenceType(); 5386 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5387 Ty = F->getType().getNonReferenceType(); 5388 else 5389 return false; 5390 5391 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5392 !Ty->isFunctionProtoType()) 5393 return false; 5394 5395 VariadicCallType CallType; 5396 if (!Proto || !Proto->isVariadic()) { 5397 CallType = VariadicDoesNotApply; 5398 } else if (Ty->isBlockPointerType()) { 5399 CallType = VariadicBlock; 5400 } else { // Ty->isFunctionPointerType() 5401 CallType = VariadicFunction; 5402 } 5403 5404 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5405 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5406 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5407 TheCall->getCallee()->getSourceRange(), CallType); 5408 5409 return false; 5410 } 5411 5412 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5413 /// such as function pointers returned from functions. 5414 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5415 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5416 TheCall->getCallee()); 5417 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5418 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5419 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5420 TheCall->getCallee()->getSourceRange(), CallType); 5421 5422 return false; 5423 } 5424 5425 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5426 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5427 return false; 5428 5429 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5430 switch (Op) { 5431 case AtomicExpr::AO__c11_atomic_init: 5432 case AtomicExpr::AO__opencl_atomic_init: 5433 llvm_unreachable("There is no ordering argument for an init"); 5434 5435 case AtomicExpr::AO__c11_atomic_load: 5436 case AtomicExpr::AO__opencl_atomic_load: 5437 case AtomicExpr::AO__hip_atomic_load: 5438 case AtomicExpr::AO__atomic_load_n: 5439 case AtomicExpr::AO__atomic_load: 5440 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5441 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5442 5443 case AtomicExpr::AO__c11_atomic_store: 5444 case AtomicExpr::AO__opencl_atomic_store: 5445 case AtomicExpr::AO__hip_atomic_store: 5446 case AtomicExpr::AO__atomic_store: 5447 case AtomicExpr::AO__atomic_store_n: 5448 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5449 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5450 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5451 5452 default: 5453 return true; 5454 } 5455 } 5456 5457 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5458 AtomicExpr::AtomicOp Op) { 5459 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5460 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5461 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5462 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5463 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5464 Op); 5465 } 5466 5467 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5468 SourceLocation RParenLoc, MultiExprArg Args, 5469 AtomicExpr::AtomicOp Op, 5470 AtomicArgumentOrder ArgOrder) { 5471 // All the non-OpenCL operations take one of the following forms. 5472 // The OpenCL operations take the __c11 forms with one extra argument for 5473 // synchronization scope. 5474 enum { 5475 // C __c11_atomic_init(A *, C) 5476 Init, 5477 5478 // C __c11_atomic_load(A *, int) 5479 Load, 5480 5481 // void __atomic_load(A *, CP, int) 5482 LoadCopy, 5483 5484 // void __atomic_store(A *, CP, int) 5485 Copy, 5486 5487 // C __c11_atomic_add(A *, M, int) 5488 Arithmetic, 5489 5490 // C __atomic_exchange_n(A *, CP, int) 5491 Xchg, 5492 5493 // void __atomic_exchange(A *, C *, CP, int) 5494 GNUXchg, 5495 5496 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5497 C11CmpXchg, 5498 5499 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5500 GNUCmpXchg 5501 } Form = Init; 5502 5503 const unsigned NumForm = GNUCmpXchg + 1; 5504 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5505 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5506 // where: 5507 // C is an appropriate type, 5508 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5509 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5510 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5511 // the int parameters are for orderings. 5512 5513 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5514 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5515 "need to update code for modified forms"); 5516 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5517 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5518 AtomicExpr::AO__atomic_load, 5519 "need to update code for modified C11 atomics"); 5520 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5521 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5522 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load && 5523 Op <= AtomicExpr::AO__hip_atomic_fetch_max; 5524 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5525 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5526 IsOpenCL; 5527 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5528 Op == AtomicExpr::AO__atomic_store_n || 5529 Op == AtomicExpr::AO__atomic_exchange_n || 5530 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5531 bool IsAddSub = false; 5532 5533 switch (Op) { 5534 case AtomicExpr::AO__c11_atomic_init: 5535 case AtomicExpr::AO__opencl_atomic_init: 5536 Form = Init; 5537 break; 5538 5539 case AtomicExpr::AO__c11_atomic_load: 5540 case AtomicExpr::AO__opencl_atomic_load: 5541 case AtomicExpr::AO__hip_atomic_load: 5542 case AtomicExpr::AO__atomic_load_n: 5543 Form = Load; 5544 break; 5545 5546 case AtomicExpr::AO__atomic_load: 5547 Form = LoadCopy; 5548 break; 5549 5550 case AtomicExpr::AO__c11_atomic_store: 5551 case AtomicExpr::AO__opencl_atomic_store: 5552 case AtomicExpr::AO__hip_atomic_store: 5553 case AtomicExpr::AO__atomic_store: 5554 case AtomicExpr::AO__atomic_store_n: 5555 Form = Copy; 5556 break; 5557 case AtomicExpr::AO__hip_atomic_fetch_add: 5558 case AtomicExpr::AO__hip_atomic_fetch_min: 5559 case AtomicExpr::AO__hip_atomic_fetch_max: 5560 case AtomicExpr::AO__c11_atomic_fetch_add: 5561 case AtomicExpr::AO__c11_atomic_fetch_sub: 5562 case AtomicExpr::AO__opencl_atomic_fetch_add: 5563 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5564 case AtomicExpr::AO__atomic_fetch_add: 5565 case AtomicExpr::AO__atomic_fetch_sub: 5566 case AtomicExpr::AO__atomic_add_fetch: 5567 case AtomicExpr::AO__atomic_sub_fetch: 5568 IsAddSub = true; 5569 Form = Arithmetic; 5570 break; 5571 case AtomicExpr::AO__c11_atomic_fetch_and: 5572 case AtomicExpr::AO__c11_atomic_fetch_or: 5573 case AtomicExpr::AO__c11_atomic_fetch_xor: 5574 case AtomicExpr::AO__hip_atomic_fetch_and: 5575 case AtomicExpr::AO__hip_atomic_fetch_or: 5576 case AtomicExpr::AO__hip_atomic_fetch_xor: 5577 case AtomicExpr::AO__c11_atomic_fetch_nand: 5578 case AtomicExpr::AO__opencl_atomic_fetch_and: 5579 case AtomicExpr::AO__opencl_atomic_fetch_or: 5580 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5581 case AtomicExpr::AO__atomic_fetch_and: 5582 case AtomicExpr::AO__atomic_fetch_or: 5583 case AtomicExpr::AO__atomic_fetch_xor: 5584 case AtomicExpr::AO__atomic_fetch_nand: 5585 case AtomicExpr::AO__atomic_and_fetch: 5586 case AtomicExpr::AO__atomic_or_fetch: 5587 case AtomicExpr::AO__atomic_xor_fetch: 5588 case AtomicExpr::AO__atomic_nand_fetch: 5589 Form = Arithmetic; 5590 break; 5591 case AtomicExpr::AO__c11_atomic_fetch_min: 5592 case AtomicExpr::AO__c11_atomic_fetch_max: 5593 case AtomicExpr::AO__opencl_atomic_fetch_min: 5594 case AtomicExpr::AO__opencl_atomic_fetch_max: 5595 case AtomicExpr::AO__atomic_min_fetch: 5596 case AtomicExpr::AO__atomic_max_fetch: 5597 case AtomicExpr::AO__atomic_fetch_min: 5598 case AtomicExpr::AO__atomic_fetch_max: 5599 Form = Arithmetic; 5600 break; 5601 5602 case AtomicExpr::AO__c11_atomic_exchange: 5603 case AtomicExpr::AO__hip_atomic_exchange: 5604 case AtomicExpr::AO__opencl_atomic_exchange: 5605 case AtomicExpr::AO__atomic_exchange_n: 5606 Form = Xchg; 5607 break; 5608 5609 case AtomicExpr::AO__atomic_exchange: 5610 Form = GNUXchg; 5611 break; 5612 5613 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5614 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5615 case AtomicExpr::AO__hip_atomic_compare_exchange_strong: 5616 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5617 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5618 case AtomicExpr::AO__hip_atomic_compare_exchange_weak: 5619 Form = C11CmpXchg; 5620 break; 5621 5622 case AtomicExpr::AO__atomic_compare_exchange: 5623 case AtomicExpr::AO__atomic_compare_exchange_n: 5624 Form = GNUCmpXchg; 5625 break; 5626 } 5627 5628 unsigned AdjustedNumArgs = NumArgs[Form]; 5629 if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init) 5630 ++AdjustedNumArgs; 5631 // Check we have the right number of arguments. 5632 if (Args.size() < AdjustedNumArgs) { 5633 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5634 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5635 << ExprRange; 5636 return ExprError(); 5637 } else if (Args.size() > AdjustedNumArgs) { 5638 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5639 diag::err_typecheck_call_too_many_args) 5640 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5641 << ExprRange; 5642 return ExprError(); 5643 } 5644 5645 // Inspect the first argument of the atomic operation. 5646 Expr *Ptr = Args[0]; 5647 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5648 if (ConvertedPtr.isInvalid()) 5649 return ExprError(); 5650 5651 Ptr = ConvertedPtr.get(); 5652 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5653 if (!pointerType) { 5654 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5655 << Ptr->getType() << Ptr->getSourceRange(); 5656 return ExprError(); 5657 } 5658 5659 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5660 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5661 QualType ValType = AtomTy; // 'C' 5662 if (IsC11) { 5663 if (!AtomTy->isAtomicType()) { 5664 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5665 << Ptr->getType() << Ptr->getSourceRange(); 5666 return ExprError(); 5667 } 5668 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5669 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5670 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5671 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5672 << Ptr->getSourceRange(); 5673 return ExprError(); 5674 } 5675 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5676 } else if (Form != Load && Form != LoadCopy) { 5677 if (ValType.isConstQualified()) { 5678 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5679 << Ptr->getType() << Ptr->getSourceRange(); 5680 return ExprError(); 5681 } 5682 } 5683 5684 // For an arithmetic operation, the implied arithmetic must be well-formed. 5685 if (Form == Arithmetic) { 5686 // GCC does not enforce these rules for GNU atomics, but we do to help catch 5687 // trivial type errors. 5688 auto IsAllowedValueType = [&](QualType ValType) { 5689 if (ValType->isIntegerType()) 5690 return true; 5691 if (ValType->isPointerType()) 5692 return true; 5693 if (!ValType->isFloatingType()) 5694 return false; 5695 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5696 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5697 &Context.getTargetInfo().getLongDoubleFormat() == 5698 &llvm::APFloat::x87DoubleExtended()) 5699 return false; 5700 return true; 5701 }; 5702 if (IsAddSub && !IsAllowedValueType(ValType)) { 5703 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5704 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5705 return ExprError(); 5706 } 5707 if (!IsAddSub && !ValType->isIntegerType()) { 5708 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5709 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5710 return ExprError(); 5711 } 5712 if (IsC11 && ValType->isPointerType() && 5713 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5714 diag::err_incomplete_type)) { 5715 return ExprError(); 5716 } 5717 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5718 // For __atomic_*_n operations, the value type must be a scalar integral or 5719 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5720 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5721 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5722 return ExprError(); 5723 } 5724 5725 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5726 !AtomTy->isScalarType()) { 5727 // For GNU atomics, require a trivially-copyable type. This is not part of 5728 // the GNU atomics specification but we enforce it for consistency with 5729 // other atomics which generally all require a trivially-copyable type. This 5730 // is because atomics just copy bits. 5731 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5732 << Ptr->getType() << Ptr->getSourceRange(); 5733 return ExprError(); 5734 } 5735 5736 switch (ValType.getObjCLifetime()) { 5737 case Qualifiers::OCL_None: 5738 case Qualifiers::OCL_ExplicitNone: 5739 // okay 5740 break; 5741 5742 case Qualifiers::OCL_Weak: 5743 case Qualifiers::OCL_Strong: 5744 case Qualifiers::OCL_Autoreleasing: 5745 // FIXME: Can this happen? By this point, ValType should be known 5746 // to be trivially copyable. 5747 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5748 << ValType << Ptr->getSourceRange(); 5749 return ExprError(); 5750 } 5751 5752 // All atomic operations have an overload which takes a pointer to a volatile 5753 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5754 // into the result or the other operands. Similarly atomic_load takes a 5755 // pointer to a const 'A'. 5756 ValType.removeLocalVolatile(); 5757 ValType.removeLocalConst(); 5758 QualType ResultType = ValType; 5759 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5760 Form == Init) 5761 ResultType = Context.VoidTy; 5762 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5763 ResultType = Context.BoolTy; 5764 5765 // The type of a parameter passed 'by value'. In the GNU atomics, such 5766 // arguments are actually passed as pointers. 5767 QualType ByValType = ValType; // 'CP' 5768 bool IsPassedByAddress = false; 5769 if (!IsC11 && !IsHIP && !IsN) { 5770 ByValType = Ptr->getType(); 5771 IsPassedByAddress = true; 5772 } 5773 5774 SmallVector<Expr *, 5> APIOrderedArgs; 5775 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5776 APIOrderedArgs.push_back(Args[0]); 5777 switch (Form) { 5778 case Init: 5779 case Load: 5780 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5781 break; 5782 case LoadCopy: 5783 case Copy: 5784 case Arithmetic: 5785 case Xchg: 5786 APIOrderedArgs.push_back(Args[2]); // Val1 5787 APIOrderedArgs.push_back(Args[1]); // Order 5788 break; 5789 case GNUXchg: 5790 APIOrderedArgs.push_back(Args[2]); // Val1 5791 APIOrderedArgs.push_back(Args[3]); // Val2 5792 APIOrderedArgs.push_back(Args[1]); // Order 5793 break; 5794 case C11CmpXchg: 5795 APIOrderedArgs.push_back(Args[2]); // Val1 5796 APIOrderedArgs.push_back(Args[4]); // Val2 5797 APIOrderedArgs.push_back(Args[1]); // Order 5798 APIOrderedArgs.push_back(Args[3]); // OrderFail 5799 break; 5800 case GNUCmpXchg: 5801 APIOrderedArgs.push_back(Args[2]); // Val1 5802 APIOrderedArgs.push_back(Args[4]); // Val2 5803 APIOrderedArgs.push_back(Args[5]); // Weak 5804 APIOrderedArgs.push_back(Args[1]); // Order 5805 APIOrderedArgs.push_back(Args[3]); // OrderFail 5806 break; 5807 } 5808 } else 5809 APIOrderedArgs.append(Args.begin(), Args.end()); 5810 5811 // The first argument's non-CV pointer type is used to deduce the type of 5812 // subsequent arguments, except for: 5813 // - weak flag (always converted to bool) 5814 // - memory order (always converted to int) 5815 // - scope (always converted to int) 5816 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5817 QualType Ty; 5818 if (i < NumVals[Form] + 1) { 5819 switch (i) { 5820 case 0: 5821 // The first argument is always a pointer. It has a fixed type. 5822 // It is always dereferenced, a nullptr is undefined. 5823 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5824 // Nothing else to do: we already know all we want about this pointer. 5825 continue; 5826 case 1: 5827 // The second argument is the non-atomic operand. For arithmetic, this 5828 // is always passed by value, and for a compare_exchange it is always 5829 // passed by address. For the rest, GNU uses by-address and C11 uses 5830 // by-value. 5831 assert(Form != Load); 5832 if (Form == Arithmetic && ValType->isPointerType()) 5833 Ty = Context.getPointerDiffType(); 5834 else if (Form == Init || Form == Arithmetic) 5835 Ty = ValType; 5836 else if (Form == Copy || Form == Xchg) { 5837 if (IsPassedByAddress) { 5838 // The value pointer is always dereferenced, a nullptr is undefined. 5839 CheckNonNullArgument(*this, APIOrderedArgs[i], 5840 ExprRange.getBegin()); 5841 } 5842 Ty = ByValType; 5843 } else { 5844 Expr *ValArg = APIOrderedArgs[i]; 5845 // The value pointer is always dereferenced, a nullptr is undefined. 5846 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5847 LangAS AS = LangAS::Default; 5848 // Keep address space of non-atomic pointer type. 5849 if (const PointerType *PtrTy = 5850 ValArg->getType()->getAs<PointerType>()) { 5851 AS = PtrTy->getPointeeType().getAddressSpace(); 5852 } 5853 Ty = Context.getPointerType( 5854 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5855 } 5856 break; 5857 case 2: 5858 // The third argument to compare_exchange / GNU exchange is the desired 5859 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5860 if (IsPassedByAddress) 5861 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5862 Ty = ByValType; 5863 break; 5864 case 3: 5865 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5866 Ty = Context.BoolTy; 5867 break; 5868 } 5869 } else { 5870 // The order(s) and scope are always converted to int. 5871 Ty = Context.IntTy; 5872 } 5873 5874 InitializedEntity Entity = 5875 InitializedEntity::InitializeParameter(Context, Ty, false); 5876 ExprResult Arg = APIOrderedArgs[i]; 5877 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5878 if (Arg.isInvalid()) 5879 return true; 5880 APIOrderedArgs[i] = Arg.get(); 5881 } 5882 5883 // Permute the arguments into a 'consistent' order. 5884 SmallVector<Expr*, 5> SubExprs; 5885 SubExprs.push_back(Ptr); 5886 switch (Form) { 5887 case Init: 5888 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5889 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5890 break; 5891 case Load: 5892 SubExprs.push_back(APIOrderedArgs[1]); // Order 5893 break; 5894 case LoadCopy: 5895 case Copy: 5896 case Arithmetic: 5897 case Xchg: 5898 SubExprs.push_back(APIOrderedArgs[2]); // Order 5899 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5900 break; 5901 case GNUXchg: 5902 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5903 SubExprs.push_back(APIOrderedArgs[3]); // Order 5904 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5905 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5906 break; 5907 case C11CmpXchg: 5908 SubExprs.push_back(APIOrderedArgs[3]); // Order 5909 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5910 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5911 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5912 break; 5913 case GNUCmpXchg: 5914 SubExprs.push_back(APIOrderedArgs[4]); // Order 5915 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5916 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5917 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5918 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5919 break; 5920 } 5921 5922 if (SubExprs.size() >= 2 && Form != Init) { 5923 if (Optional<llvm::APSInt> Result = 5924 SubExprs[1]->getIntegerConstantExpr(Context)) 5925 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5926 Diag(SubExprs[1]->getBeginLoc(), 5927 diag::warn_atomic_op_has_invalid_memory_order) 5928 << SubExprs[1]->getSourceRange(); 5929 } 5930 5931 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5932 auto *Scope = Args[Args.size() - 1]; 5933 if (Optional<llvm::APSInt> Result = 5934 Scope->getIntegerConstantExpr(Context)) { 5935 if (!ScopeModel->isValid(Result->getZExtValue())) 5936 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5937 << Scope->getSourceRange(); 5938 } 5939 SubExprs.push_back(Scope); 5940 } 5941 5942 AtomicExpr *AE = new (Context) 5943 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5944 5945 if ((Op == AtomicExpr::AO__c11_atomic_load || 5946 Op == AtomicExpr::AO__c11_atomic_store || 5947 Op == AtomicExpr::AO__opencl_atomic_load || 5948 Op == AtomicExpr::AO__hip_atomic_load || 5949 Op == AtomicExpr::AO__opencl_atomic_store || 5950 Op == AtomicExpr::AO__hip_atomic_store) && 5951 Context.AtomicUsesUnsupportedLibcall(AE)) 5952 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5953 << ((Op == AtomicExpr::AO__c11_atomic_load || 5954 Op == AtomicExpr::AO__opencl_atomic_load || 5955 Op == AtomicExpr::AO__hip_atomic_load) 5956 ? 0 5957 : 1); 5958 5959 if (ValType->isBitIntType()) { 5960 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit); 5961 return ExprError(); 5962 } 5963 5964 return AE; 5965 } 5966 5967 /// checkBuiltinArgument - Given a call to a builtin function, perform 5968 /// normal type-checking on the given argument, updating the call in 5969 /// place. This is useful when a builtin function requires custom 5970 /// type-checking for some of its arguments but not necessarily all of 5971 /// them. 5972 /// 5973 /// Returns true on error. 5974 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5975 FunctionDecl *Fn = E->getDirectCallee(); 5976 assert(Fn && "builtin call without direct callee!"); 5977 5978 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5979 InitializedEntity Entity = 5980 InitializedEntity::InitializeParameter(S.Context, Param); 5981 5982 ExprResult Arg = E->getArg(0); 5983 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5984 if (Arg.isInvalid()) 5985 return true; 5986 5987 E->setArg(ArgIndex, Arg.get()); 5988 return false; 5989 } 5990 5991 /// We have a call to a function like __sync_fetch_and_add, which is an 5992 /// overloaded function based on the pointer type of its first argument. 5993 /// The main BuildCallExpr routines have already promoted the types of 5994 /// arguments because all of these calls are prototyped as void(...). 5995 /// 5996 /// This function goes through and does final semantic checking for these 5997 /// builtins, as well as generating any warnings. 5998 ExprResult 5999 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 6000 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 6001 Expr *Callee = TheCall->getCallee(); 6002 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 6003 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6004 6005 // Ensure that we have at least one argument to do type inference from. 6006 if (TheCall->getNumArgs() < 1) { 6007 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6008 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 6009 return ExprError(); 6010 } 6011 6012 // Inspect the first argument of the atomic builtin. This should always be 6013 // a pointer type, whose element is an integral scalar or pointer type. 6014 // Because it is a pointer type, we don't have to worry about any implicit 6015 // casts here. 6016 // FIXME: We don't allow floating point scalars as input. 6017 Expr *FirstArg = TheCall->getArg(0); 6018 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 6019 if (FirstArgResult.isInvalid()) 6020 return ExprError(); 6021 FirstArg = FirstArgResult.get(); 6022 TheCall->setArg(0, FirstArg); 6023 6024 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 6025 if (!pointerType) { 6026 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 6027 << FirstArg->getType() << FirstArg->getSourceRange(); 6028 return ExprError(); 6029 } 6030 6031 QualType ValType = pointerType->getPointeeType(); 6032 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6033 !ValType->isBlockPointerType()) { 6034 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 6035 << FirstArg->getType() << FirstArg->getSourceRange(); 6036 return ExprError(); 6037 } 6038 6039 if (ValType.isConstQualified()) { 6040 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 6041 << FirstArg->getType() << FirstArg->getSourceRange(); 6042 return ExprError(); 6043 } 6044 6045 switch (ValType.getObjCLifetime()) { 6046 case Qualifiers::OCL_None: 6047 case Qualifiers::OCL_ExplicitNone: 6048 // okay 6049 break; 6050 6051 case Qualifiers::OCL_Weak: 6052 case Qualifiers::OCL_Strong: 6053 case Qualifiers::OCL_Autoreleasing: 6054 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 6055 << ValType << FirstArg->getSourceRange(); 6056 return ExprError(); 6057 } 6058 6059 // Strip any qualifiers off ValType. 6060 ValType = ValType.getUnqualifiedType(); 6061 6062 // The majority of builtins return a value, but a few have special return 6063 // types, so allow them to override appropriately below. 6064 QualType ResultType = ValType; 6065 6066 // We need to figure out which concrete builtin this maps onto. For example, 6067 // __sync_fetch_and_add with a 2 byte object turns into 6068 // __sync_fetch_and_add_2. 6069 #define BUILTIN_ROW(x) \ 6070 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 6071 Builtin::BI##x##_8, Builtin::BI##x##_16 } 6072 6073 static const unsigned BuiltinIndices[][5] = { 6074 BUILTIN_ROW(__sync_fetch_and_add), 6075 BUILTIN_ROW(__sync_fetch_and_sub), 6076 BUILTIN_ROW(__sync_fetch_and_or), 6077 BUILTIN_ROW(__sync_fetch_and_and), 6078 BUILTIN_ROW(__sync_fetch_and_xor), 6079 BUILTIN_ROW(__sync_fetch_and_nand), 6080 6081 BUILTIN_ROW(__sync_add_and_fetch), 6082 BUILTIN_ROW(__sync_sub_and_fetch), 6083 BUILTIN_ROW(__sync_and_and_fetch), 6084 BUILTIN_ROW(__sync_or_and_fetch), 6085 BUILTIN_ROW(__sync_xor_and_fetch), 6086 BUILTIN_ROW(__sync_nand_and_fetch), 6087 6088 BUILTIN_ROW(__sync_val_compare_and_swap), 6089 BUILTIN_ROW(__sync_bool_compare_and_swap), 6090 BUILTIN_ROW(__sync_lock_test_and_set), 6091 BUILTIN_ROW(__sync_lock_release), 6092 BUILTIN_ROW(__sync_swap) 6093 }; 6094 #undef BUILTIN_ROW 6095 6096 // Determine the index of the size. 6097 unsigned SizeIndex; 6098 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 6099 case 1: SizeIndex = 0; break; 6100 case 2: SizeIndex = 1; break; 6101 case 4: SizeIndex = 2; break; 6102 case 8: SizeIndex = 3; break; 6103 case 16: SizeIndex = 4; break; 6104 default: 6105 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 6106 << FirstArg->getType() << FirstArg->getSourceRange(); 6107 return ExprError(); 6108 } 6109 6110 // Each of these builtins has one pointer argument, followed by some number of 6111 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 6112 // that we ignore. Find out which row of BuiltinIndices to read from as well 6113 // as the number of fixed args. 6114 unsigned BuiltinID = FDecl->getBuiltinID(); 6115 unsigned BuiltinIndex, NumFixed = 1; 6116 bool WarnAboutSemanticsChange = false; 6117 switch (BuiltinID) { 6118 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 6119 case Builtin::BI__sync_fetch_and_add: 6120 case Builtin::BI__sync_fetch_and_add_1: 6121 case Builtin::BI__sync_fetch_and_add_2: 6122 case Builtin::BI__sync_fetch_and_add_4: 6123 case Builtin::BI__sync_fetch_and_add_8: 6124 case Builtin::BI__sync_fetch_and_add_16: 6125 BuiltinIndex = 0; 6126 break; 6127 6128 case Builtin::BI__sync_fetch_and_sub: 6129 case Builtin::BI__sync_fetch_and_sub_1: 6130 case Builtin::BI__sync_fetch_and_sub_2: 6131 case Builtin::BI__sync_fetch_and_sub_4: 6132 case Builtin::BI__sync_fetch_and_sub_8: 6133 case Builtin::BI__sync_fetch_and_sub_16: 6134 BuiltinIndex = 1; 6135 break; 6136 6137 case Builtin::BI__sync_fetch_and_or: 6138 case Builtin::BI__sync_fetch_and_or_1: 6139 case Builtin::BI__sync_fetch_and_or_2: 6140 case Builtin::BI__sync_fetch_and_or_4: 6141 case Builtin::BI__sync_fetch_and_or_8: 6142 case Builtin::BI__sync_fetch_and_or_16: 6143 BuiltinIndex = 2; 6144 break; 6145 6146 case Builtin::BI__sync_fetch_and_and: 6147 case Builtin::BI__sync_fetch_and_and_1: 6148 case Builtin::BI__sync_fetch_and_and_2: 6149 case Builtin::BI__sync_fetch_and_and_4: 6150 case Builtin::BI__sync_fetch_and_and_8: 6151 case Builtin::BI__sync_fetch_and_and_16: 6152 BuiltinIndex = 3; 6153 break; 6154 6155 case Builtin::BI__sync_fetch_and_xor: 6156 case Builtin::BI__sync_fetch_and_xor_1: 6157 case Builtin::BI__sync_fetch_and_xor_2: 6158 case Builtin::BI__sync_fetch_and_xor_4: 6159 case Builtin::BI__sync_fetch_and_xor_8: 6160 case Builtin::BI__sync_fetch_and_xor_16: 6161 BuiltinIndex = 4; 6162 break; 6163 6164 case Builtin::BI__sync_fetch_and_nand: 6165 case Builtin::BI__sync_fetch_and_nand_1: 6166 case Builtin::BI__sync_fetch_and_nand_2: 6167 case Builtin::BI__sync_fetch_and_nand_4: 6168 case Builtin::BI__sync_fetch_and_nand_8: 6169 case Builtin::BI__sync_fetch_and_nand_16: 6170 BuiltinIndex = 5; 6171 WarnAboutSemanticsChange = true; 6172 break; 6173 6174 case Builtin::BI__sync_add_and_fetch: 6175 case Builtin::BI__sync_add_and_fetch_1: 6176 case Builtin::BI__sync_add_and_fetch_2: 6177 case Builtin::BI__sync_add_and_fetch_4: 6178 case Builtin::BI__sync_add_and_fetch_8: 6179 case Builtin::BI__sync_add_and_fetch_16: 6180 BuiltinIndex = 6; 6181 break; 6182 6183 case Builtin::BI__sync_sub_and_fetch: 6184 case Builtin::BI__sync_sub_and_fetch_1: 6185 case Builtin::BI__sync_sub_and_fetch_2: 6186 case Builtin::BI__sync_sub_and_fetch_4: 6187 case Builtin::BI__sync_sub_and_fetch_8: 6188 case Builtin::BI__sync_sub_and_fetch_16: 6189 BuiltinIndex = 7; 6190 break; 6191 6192 case Builtin::BI__sync_and_and_fetch: 6193 case Builtin::BI__sync_and_and_fetch_1: 6194 case Builtin::BI__sync_and_and_fetch_2: 6195 case Builtin::BI__sync_and_and_fetch_4: 6196 case Builtin::BI__sync_and_and_fetch_8: 6197 case Builtin::BI__sync_and_and_fetch_16: 6198 BuiltinIndex = 8; 6199 break; 6200 6201 case Builtin::BI__sync_or_and_fetch: 6202 case Builtin::BI__sync_or_and_fetch_1: 6203 case Builtin::BI__sync_or_and_fetch_2: 6204 case Builtin::BI__sync_or_and_fetch_4: 6205 case Builtin::BI__sync_or_and_fetch_8: 6206 case Builtin::BI__sync_or_and_fetch_16: 6207 BuiltinIndex = 9; 6208 break; 6209 6210 case Builtin::BI__sync_xor_and_fetch: 6211 case Builtin::BI__sync_xor_and_fetch_1: 6212 case Builtin::BI__sync_xor_and_fetch_2: 6213 case Builtin::BI__sync_xor_and_fetch_4: 6214 case Builtin::BI__sync_xor_and_fetch_8: 6215 case Builtin::BI__sync_xor_and_fetch_16: 6216 BuiltinIndex = 10; 6217 break; 6218 6219 case Builtin::BI__sync_nand_and_fetch: 6220 case Builtin::BI__sync_nand_and_fetch_1: 6221 case Builtin::BI__sync_nand_and_fetch_2: 6222 case Builtin::BI__sync_nand_and_fetch_4: 6223 case Builtin::BI__sync_nand_and_fetch_8: 6224 case Builtin::BI__sync_nand_and_fetch_16: 6225 BuiltinIndex = 11; 6226 WarnAboutSemanticsChange = true; 6227 break; 6228 6229 case Builtin::BI__sync_val_compare_and_swap: 6230 case Builtin::BI__sync_val_compare_and_swap_1: 6231 case Builtin::BI__sync_val_compare_and_swap_2: 6232 case Builtin::BI__sync_val_compare_and_swap_4: 6233 case Builtin::BI__sync_val_compare_and_swap_8: 6234 case Builtin::BI__sync_val_compare_and_swap_16: 6235 BuiltinIndex = 12; 6236 NumFixed = 2; 6237 break; 6238 6239 case Builtin::BI__sync_bool_compare_and_swap: 6240 case Builtin::BI__sync_bool_compare_and_swap_1: 6241 case Builtin::BI__sync_bool_compare_and_swap_2: 6242 case Builtin::BI__sync_bool_compare_and_swap_4: 6243 case Builtin::BI__sync_bool_compare_and_swap_8: 6244 case Builtin::BI__sync_bool_compare_and_swap_16: 6245 BuiltinIndex = 13; 6246 NumFixed = 2; 6247 ResultType = Context.BoolTy; 6248 break; 6249 6250 case Builtin::BI__sync_lock_test_and_set: 6251 case Builtin::BI__sync_lock_test_and_set_1: 6252 case Builtin::BI__sync_lock_test_and_set_2: 6253 case Builtin::BI__sync_lock_test_and_set_4: 6254 case Builtin::BI__sync_lock_test_and_set_8: 6255 case Builtin::BI__sync_lock_test_and_set_16: 6256 BuiltinIndex = 14; 6257 break; 6258 6259 case Builtin::BI__sync_lock_release: 6260 case Builtin::BI__sync_lock_release_1: 6261 case Builtin::BI__sync_lock_release_2: 6262 case Builtin::BI__sync_lock_release_4: 6263 case Builtin::BI__sync_lock_release_8: 6264 case Builtin::BI__sync_lock_release_16: 6265 BuiltinIndex = 15; 6266 NumFixed = 0; 6267 ResultType = Context.VoidTy; 6268 break; 6269 6270 case Builtin::BI__sync_swap: 6271 case Builtin::BI__sync_swap_1: 6272 case Builtin::BI__sync_swap_2: 6273 case Builtin::BI__sync_swap_4: 6274 case Builtin::BI__sync_swap_8: 6275 case Builtin::BI__sync_swap_16: 6276 BuiltinIndex = 16; 6277 break; 6278 } 6279 6280 // Now that we know how many fixed arguments we expect, first check that we 6281 // have at least that many. 6282 if (TheCall->getNumArgs() < 1+NumFixed) { 6283 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6284 << 0 << 1 + NumFixed << TheCall->getNumArgs() 6285 << Callee->getSourceRange(); 6286 return ExprError(); 6287 } 6288 6289 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 6290 << Callee->getSourceRange(); 6291 6292 if (WarnAboutSemanticsChange) { 6293 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 6294 << Callee->getSourceRange(); 6295 } 6296 6297 // Get the decl for the concrete builtin from this, we can tell what the 6298 // concrete integer type we should convert to is. 6299 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 6300 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 6301 FunctionDecl *NewBuiltinDecl; 6302 if (NewBuiltinID == BuiltinID) 6303 NewBuiltinDecl = FDecl; 6304 else { 6305 // Perform builtin lookup to avoid redeclaring it. 6306 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 6307 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 6308 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 6309 assert(Res.getFoundDecl()); 6310 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 6311 if (!NewBuiltinDecl) 6312 return ExprError(); 6313 } 6314 6315 // The first argument --- the pointer --- has a fixed type; we 6316 // deduce the types of the rest of the arguments accordingly. Walk 6317 // the remaining arguments, converting them to the deduced value type. 6318 for (unsigned i = 0; i != NumFixed; ++i) { 6319 ExprResult Arg = TheCall->getArg(i+1); 6320 6321 // GCC does an implicit conversion to the pointer or integer ValType. This 6322 // can fail in some cases (1i -> int**), check for this error case now. 6323 // Initialize the argument. 6324 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6325 ValType, /*consume*/ false); 6326 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6327 if (Arg.isInvalid()) 6328 return ExprError(); 6329 6330 // Okay, we have something that *can* be converted to the right type. Check 6331 // to see if there is a potentially weird extension going on here. This can 6332 // happen when you do an atomic operation on something like an char* and 6333 // pass in 42. The 42 gets converted to char. This is even more strange 6334 // for things like 45.123 -> char, etc. 6335 // FIXME: Do this check. 6336 TheCall->setArg(i+1, Arg.get()); 6337 } 6338 6339 // Create a new DeclRefExpr to refer to the new decl. 6340 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6341 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6342 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6343 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6344 6345 // Set the callee in the CallExpr. 6346 // FIXME: This loses syntactic information. 6347 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6348 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6349 CK_BuiltinFnToFnPtr); 6350 TheCall->setCallee(PromotedCall.get()); 6351 6352 // Change the result type of the call to match the original value type. This 6353 // is arbitrary, but the codegen for these builtins ins design to handle it 6354 // gracefully. 6355 TheCall->setType(ResultType); 6356 6357 // Prohibit problematic uses of bit-precise integer types with atomic 6358 // builtins. The arguments would have already been converted to the first 6359 // argument's type, so only need to check the first argument. 6360 const auto *BitIntValType = ValType->getAs<BitIntType>(); 6361 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) { 6362 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6363 return ExprError(); 6364 } 6365 6366 return TheCallResult; 6367 } 6368 6369 /// SemaBuiltinNontemporalOverloaded - We have a call to 6370 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6371 /// overloaded function based on the pointer type of its last argument. 6372 /// 6373 /// This function goes through and does final semantic checking for these 6374 /// builtins. 6375 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6376 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6377 DeclRefExpr *DRE = 6378 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6379 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6380 unsigned BuiltinID = FDecl->getBuiltinID(); 6381 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6382 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6383 "Unexpected nontemporal load/store builtin!"); 6384 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6385 unsigned numArgs = isStore ? 2 : 1; 6386 6387 // Ensure that we have the proper number of arguments. 6388 if (checkArgCount(*this, TheCall, numArgs)) 6389 return ExprError(); 6390 6391 // Inspect the last argument of the nontemporal builtin. This should always 6392 // be a pointer type, from which we imply the type of the memory access. 6393 // Because it is a pointer type, we don't have to worry about any implicit 6394 // casts here. 6395 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6396 ExprResult PointerArgResult = 6397 DefaultFunctionArrayLvalueConversion(PointerArg); 6398 6399 if (PointerArgResult.isInvalid()) 6400 return ExprError(); 6401 PointerArg = PointerArgResult.get(); 6402 TheCall->setArg(numArgs - 1, PointerArg); 6403 6404 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6405 if (!pointerType) { 6406 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6407 << PointerArg->getType() << PointerArg->getSourceRange(); 6408 return ExprError(); 6409 } 6410 6411 QualType ValType = pointerType->getPointeeType(); 6412 6413 // Strip any qualifiers off ValType. 6414 ValType = ValType.getUnqualifiedType(); 6415 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6416 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6417 !ValType->isVectorType()) { 6418 Diag(DRE->getBeginLoc(), 6419 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6420 << PointerArg->getType() << PointerArg->getSourceRange(); 6421 return ExprError(); 6422 } 6423 6424 if (!isStore) { 6425 TheCall->setType(ValType); 6426 return TheCallResult; 6427 } 6428 6429 ExprResult ValArg = TheCall->getArg(0); 6430 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6431 Context, ValType, /*consume*/ false); 6432 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6433 if (ValArg.isInvalid()) 6434 return ExprError(); 6435 6436 TheCall->setArg(0, ValArg.get()); 6437 TheCall->setType(Context.VoidTy); 6438 return TheCallResult; 6439 } 6440 6441 /// CheckObjCString - Checks that the argument to the builtin 6442 /// CFString constructor is correct 6443 /// Note: It might also make sense to do the UTF-16 conversion here (would 6444 /// simplify the backend). 6445 bool Sema::CheckObjCString(Expr *Arg) { 6446 Arg = Arg->IgnoreParenCasts(); 6447 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6448 6449 if (!Literal || !Literal->isAscii()) { 6450 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6451 << Arg->getSourceRange(); 6452 return true; 6453 } 6454 6455 if (Literal->containsNonAsciiOrNull()) { 6456 StringRef String = Literal->getString(); 6457 unsigned NumBytes = String.size(); 6458 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6459 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6460 llvm::UTF16 *ToPtr = &ToBuf[0]; 6461 6462 llvm::ConversionResult Result = 6463 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6464 ToPtr + NumBytes, llvm::strictConversion); 6465 // Check for conversion failure. 6466 if (Result != llvm::conversionOK) 6467 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6468 << Arg->getSourceRange(); 6469 } 6470 return false; 6471 } 6472 6473 /// CheckObjCString - Checks that the format string argument to the os_log() 6474 /// and os_trace() functions is correct, and converts it to const char *. 6475 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6476 Arg = Arg->IgnoreParenCasts(); 6477 auto *Literal = dyn_cast<StringLiteral>(Arg); 6478 if (!Literal) { 6479 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6480 Literal = ObjcLiteral->getString(); 6481 } 6482 } 6483 6484 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6485 return ExprError( 6486 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6487 << Arg->getSourceRange()); 6488 } 6489 6490 ExprResult Result(Literal); 6491 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6492 InitializedEntity Entity = 6493 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6494 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6495 return Result; 6496 } 6497 6498 /// Check that the user is calling the appropriate va_start builtin for the 6499 /// target and calling convention. 6500 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6501 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6502 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6503 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6504 TT.getArch() == llvm::Triple::aarch64_32); 6505 bool IsWindows = TT.isOSWindows(); 6506 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6507 if (IsX64 || IsAArch64) { 6508 CallingConv CC = CC_C; 6509 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6510 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6511 if (IsMSVAStart) { 6512 // Don't allow this in System V ABI functions. 6513 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6514 return S.Diag(Fn->getBeginLoc(), 6515 diag::err_ms_va_start_used_in_sysv_function); 6516 } else { 6517 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6518 // On x64 Windows, don't allow this in System V ABI functions. 6519 // (Yes, that means there's no corresponding way to support variadic 6520 // System V ABI functions on Windows.) 6521 if ((IsWindows && CC == CC_X86_64SysV) || 6522 (!IsWindows && CC == CC_Win64)) 6523 return S.Diag(Fn->getBeginLoc(), 6524 diag::err_va_start_used_in_wrong_abi_function) 6525 << !IsWindows; 6526 } 6527 return false; 6528 } 6529 6530 if (IsMSVAStart) 6531 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6532 return false; 6533 } 6534 6535 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6536 ParmVarDecl **LastParam = nullptr) { 6537 // Determine whether the current function, block, or obj-c method is variadic 6538 // and get its parameter list. 6539 bool IsVariadic = false; 6540 ArrayRef<ParmVarDecl *> Params; 6541 DeclContext *Caller = S.CurContext; 6542 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6543 IsVariadic = Block->isVariadic(); 6544 Params = Block->parameters(); 6545 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6546 IsVariadic = FD->isVariadic(); 6547 Params = FD->parameters(); 6548 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6549 IsVariadic = MD->isVariadic(); 6550 // FIXME: This isn't correct for methods (results in bogus warning). 6551 Params = MD->parameters(); 6552 } else if (isa<CapturedDecl>(Caller)) { 6553 // We don't support va_start in a CapturedDecl. 6554 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6555 return true; 6556 } else { 6557 // This must be some other declcontext that parses exprs. 6558 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6559 return true; 6560 } 6561 6562 if (!IsVariadic) { 6563 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6564 return true; 6565 } 6566 6567 if (LastParam) 6568 *LastParam = Params.empty() ? nullptr : Params.back(); 6569 6570 return false; 6571 } 6572 6573 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6574 /// for validity. Emit an error and return true on failure; return false 6575 /// on success. 6576 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6577 Expr *Fn = TheCall->getCallee(); 6578 6579 if (checkVAStartABI(*this, BuiltinID, Fn)) 6580 return true; 6581 6582 if (checkArgCount(*this, TheCall, 2)) 6583 return true; 6584 6585 // Type-check the first argument normally. 6586 if (checkBuiltinArgument(*this, TheCall, 0)) 6587 return true; 6588 6589 // Check that the current function is variadic, and get its last parameter. 6590 ParmVarDecl *LastParam; 6591 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6592 return true; 6593 6594 // Verify that the second argument to the builtin is the last argument of the 6595 // current function or method. 6596 bool SecondArgIsLastNamedArgument = false; 6597 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6598 6599 // These are valid if SecondArgIsLastNamedArgument is false after the next 6600 // block. 6601 QualType Type; 6602 SourceLocation ParamLoc; 6603 bool IsCRegister = false; 6604 6605 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6606 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6607 SecondArgIsLastNamedArgument = PV == LastParam; 6608 6609 Type = PV->getType(); 6610 ParamLoc = PV->getLocation(); 6611 IsCRegister = 6612 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6613 } 6614 } 6615 6616 if (!SecondArgIsLastNamedArgument) 6617 Diag(TheCall->getArg(1)->getBeginLoc(), 6618 diag::warn_second_arg_of_va_start_not_last_named_param); 6619 else if (IsCRegister || Type->isReferenceType() || 6620 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6621 // Promotable integers are UB, but enumerations need a bit of 6622 // extra checking to see what their promotable type actually is. 6623 if (!Type->isPromotableIntegerType()) 6624 return false; 6625 if (!Type->isEnumeralType()) 6626 return true; 6627 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6628 return !(ED && 6629 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6630 }()) { 6631 unsigned Reason = 0; 6632 if (Type->isReferenceType()) Reason = 1; 6633 else if (IsCRegister) Reason = 2; 6634 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6635 Diag(ParamLoc, diag::note_parameter_type) << Type; 6636 } 6637 6638 TheCall->setType(Context.VoidTy); 6639 return false; 6640 } 6641 6642 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6643 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { 6644 const LangOptions &LO = getLangOpts(); 6645 6646 if (LO.CPlusPlus) 6647 return Arg->getType() 6648 .getCanonicalType() 6649 .getTypePtr() 6650 ->getPointeeType() 6651 .withoutLocalFastQualifiers() == Context.CharTy; 6652 6653 // In C, allow aliasing through `char *`, this is required for AArch64 at 6654 // least. 6655 return true; 6656 }; 6657 6658 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6659 // const char *named_addr); 6660 6661 Expr *Func = Call->getCallee(); 6662 6663 if (Call->getNumArgs() < 3) 6664 return Diag(Call->getEndLoc(), 6665 diag::err_typecheck_call_too_few_args_at_least) 6666 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6667 6668 // Type-check the first argument normally. 6669 if (checkBuiltinArgument(*this, Call, 0)) 6670 return true; 6671 6672 // Check that the current function is variadic. 6673 if (checkVAStartIsInVariadicFunction(*this, Func)) 6674 return true; 6675 6676 // __va_start on Windows does not validate the parameter qualifiers 6677 6678 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6679 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6680 6681 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6682 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6683 6684 const QualType &ConstCharPtrTy = 6685 Context.getPointerType(Context.CharTy.withConst()); 6686 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) 6687 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6688 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6689 << 0 /* qualifier difference */ 6690 << 3 /* parameter mismatch */ 6691 << 2 << Arg1->getType() << ConstCharPtrTy; 6692 6693 const QualType SizeTy = Context.getSizeType(); 6694 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6695 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6696 << Arg2->getType() << SizeTy << 1 /* different class */ 6697 << 0 /* qualifier difference */ 6698 << 3 /* parameter mismatch */ 6699 << 3 << Arg2->getType() << SizeTy; 6700 6701 return false; 6702 } 6703 6704 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6705 /// friends. This is declared to take (...), so we have to check everything. 6706 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6707 if (checkArgCount(*this, TheCall, 2)) 6708 return true; 6709 6710 ExprResult OrigArg0 = TheCall->getArg(0); 6711 ExprResult OrigArg1 = TheCall->getArg(1); 6712 6713 // Do standard promotions between the two arguments, returning their common 6714 // type. 6715 QualType Res = UsualArithmeticConversions( 6716 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6717 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6718 return true; 6719 6720 // Make sure any conversions are pushed back into the call; this is 6721 // type safe since unordered compare builtins are declared as "_Bool 6722 // foo(...)". 6723 TheCall->setArg(0, OrigArg0.get()); 6724 TheCall->setArg(1, OrigArg1.get()); 6725 6726 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6727 return false; 6728 6729 // If the common type isn't a real floating type, then the arguments were 6730 // invalid for this operation. 6731 if (Res.isNull() || !Res->isRealFloatingType()) 6732 return Diag(OrigArg0.get()->getBeginLoc(), 6733 diag::err_typecheck_call_invalid_ordered_compare) 6734 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6735 << SourceRange(OrigArg0.get()->getBeginLoc(), 6736 OrigArg1.get()->getEndLoc()); 6737 6738 return false; 6739 } 6740 6741 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6742 /// __builtin_isnan and friends. This is declared to take (...), so we have 6743 /// to check everything. We expect the last argument to be a floating point 6744 /// value. 6745 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6746 if (checkArgCount(*this, TheCall, NumArgs)) 6747 return true; 6748 6749 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6750 // on all preceding parameters just being int. Try all of those. 6751 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6752 Expr *Arg = TheCall->getArg(i); 6753 6754 if (Arg->isTypeDependent()) 6755 return false; 6756 6757 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6758 6759 if (Res.isInvalid()) 6760 return true; 6761 TheCall->setArg(i, Res.get()); 6762 } 6763 6764 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6765 6766 if (OrigArg->isTypeDependent()) 6767 return false; 6768 6769 // Usual Unary Conversions will convert half to float, which we want for 6770 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6771 // type how it is, but do normal L->Rvalue conversions. 6772 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6773 OrigArg = UsualUnaryConversions(OrigArg).get(); 6774 else 6775 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6776 TheCall->setArg(NumArgs - 1, OrigArg); 6777 6778 // This operation requires a non-_Complex floating-point number. 6779 if (!OrigArg->getType()->isRealFloatingType()) 6780 return Diag(OrigArg->getBeginLoc(), 6781 diag::err_typecheck_call_invalid_unary_fp) 6782 << OrigArg->getType() << OrigArg->getSourceRange(); 6783 6784 return false; 6785 } 6786 6787 /// Perform semantic analysis for a call to __builtin_complex. 6788 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6789 if (checkArgCount(*this, TheCall, 2)) 6790 return true; 6791 6792 bool Dependent = false; 6793 for (unsigned I = 0; I != 2; ++I) { 6794 Expr *Arg = TheCall->getArg(I); 6795 QualType T = Arg->getType(); 6796 if (T->isDependentType()) { 6797 Dependent = true; 6798 continue; 6799 } 6800 6801 // Despite supporting _Complex int, GCC requires a real floating point type 6802 // for the operands of __builtin_complex. 6803 if (!T->isRealFloatingType()) { 6804 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6805 << Arg->getType() << Arg->getSourceRange(); 6806 } 6807 6808 ExprResult Converted = DefaultLvalueConversion(Arg); 6809 if (Converted.isInvalid()) 6810 return true; 6811 TheCall->setArg(I, Converted.get()); 6812 } 6813 6814 if (Dependent) { 6815 TheCall->setType(Context.DependentTy); 6816 return false; 6817 } 6818 6819 Expr *Real = TheCall->getArg(0); 6820 Expr *Imag = TheCall->getArg(1); 6821 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6822 return Diag(Real->getBeginLoc(), 6823 diag::err_typecheck_call_different_arg_types) 6824 << Real->getType() << Imag->getType() 6825 << Real->getSourceRange() << Imag->getSourceRange(); 6826 } 6827 6828 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6829 // don't allow this builtin to form those types either. 6830 // FIXME: Should we allow these types? 6831 if (Real->getType()->isFloat16Type()) 6832 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6833 << "_Float16"; 6834 if (Real->getType()->isHalfType()) 6835 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6836 << "half"; 6837 6838 TheCall->setType(Context.getComplexType(Real->getType())); 6839 return false; 6840 } 6841 6842 // Customized Sema Checking for VSX builtins that have the following signature: 6843 // vector [...] builtinName(vector [...], vector [...], const int); 6844 // Which takes the same type of vectors (any legal vector type) for the first 6845 // two arguments and takes compile time constant for the third argument. 6846 // Example builtins are : 6847 // vector double vec_xxpermdi(vector double, vector double, int); 6848 // vector short vec_xxsldwi(vector short, vector short, int); 6849 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6850 unsigned ExpectedNumArgs = 3; 6851 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6852 return true; 6853 6854 // Check the third argument is a compile time constant 6855 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6856 return Diag(TheCall->getBeginLoc(), 6857 diag::err_vsx_builtin_nonconstant_argument) 6858 << 3 /* argument index */ << TheCall->getDirectCallee() 6859 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6860 TheCall->getArg(2)->getEndLoc()); 6861 6862 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6863 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6864 6865 // Check the type of argument 1 and argument 2 are vectors. 6866 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6867 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6868 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6869 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6870 << TheCall->getDirectCallee() 6871 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6872 TheCall->getArg(1)->getEndLoc()); 6873 } 6874 6875 // Check the first two arguments are the same type. 6876 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6877 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6878 << TheCall->getDirectCallee() 6879 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6880 TheCall->getArg(1)->getEndLoc()); 6881 } 6882 6883 // When default clang type checking is turned off and the customized type 6884 // checking is used, the returning type of the function must be explicitly 6885 // set. Otherwise it is _Bool by default. 6886 TheCall->setType(Arg1Ty); 6887 6888 return false; 6889 } 6890 6891 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6892 // This is declared to take (...), so we have to check everything. 6893 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6894 if (TheCall->getNumArgs() < 2) 6895 return ExprError(Diag(TheCall->getEndLoc(), 6896 diag::err_typecheck_call_too_few_args_at_least) 6897 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6898 << TheCall->getSourceRange()); 6899 6900 // Determine which of the following types of shufflevector we're checking: 6901 // 1) unary, vector mask: (lhs, mask) 6902 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6903 QualType resType = TheCall->getArg(0)->getType(); 6904 unsigned numElements = 0; 6905 6906 if (!TheCall->getArg(0)->isTypeDependent() && 6907 !TheCall->getArg(1)->isTypeDependent()) { 6908 QualType LHSType = TheCall->getArg(0)->getType(); 6909 QualType RHSType = TheCall->getArg(1)->getType(); 6910 6911 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6912 return ExprError( 6913 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6914 << TheCall->getDirectCallee() 6915 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6916 TheCall->getArg(1)->getEndLoc())); 6917 6918 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6919 unsigned numResElements = TheCall->getNumArgs() - 2; 6920 6921 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6922 // with mask. If so, verify that RHS is an integer vector type with the 6923 // same number of elts as lhs. 6924 if (TheCall->getNumArgs() == 2) { 6925 if (!RHSType->hasIntegerRepresentation() || 6926 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6927 return ExprError(Diag(TheCall->getBeginLoc(), 6928 diag::err_vec_builtin_incompatible_vector) 6929 << TheCall->getDirectCallee() 6930 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6931 TheCall->getArg(1)->getEndLoc())); 6932 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6933 return ExprError(Diag(TheCall->getBeginLoc(), 6934 diag::err_vec_builtin_incompatible_vector) 6935 << TheCall->getDirectCallee() 6936 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6937 TheCall->getArg(1)->getEndLoc())); 6938 } else if (numElements != numResElements) { 6939 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6940 resType = Context.getVectorType(eltType, numResElements, 6941 VectorType::GenericVector); 6942 } 6943 } 6944 6945 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6946 if (TheCall->getArg(i)->isTypeDependent() || 6947 TheCall->getArg(i)->isValueDependent()) 6948 continue; 6949 6950 Optional<llvm::APSInt> Result; 6951 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6952 return ExprError(Diag(TheCall->getBeginLoc(), 6953 diag::err_shufflevector_nonconstant_argument) 6954 << TheCall->getArg(i)->getSourceRange()); 6955 6956 // Allow -1 which will be translated to undef in the IR. 6957 if (Result->isSigned() && Result->isAllOnes()) 6958 continue; 6959 6960 if (Result->getActiveBits() > 64 || 6961 Result->getZExtValue() >= numElements * 2) 6962 return ExprError(Diag(TheCall->getBeginLoc(), 6963 diag::err_shufflevector_argument_too_large) 6964 << TheCall->getArg(i)->getSourceRange()); 6965 } 6966 6967 SmallVector<Expr*, 32> exprs; 6968 6969 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6970 exprs.push_back(TheCall->getArg(i)); 6971 TheCall->setArg(i, nullptr); 6972 } 6973 6974 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6975 TheCall->getCallee()->getBeginLoc(), 6976 TheCall->getRParenLoc()); 6977 } 6978 6979 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6980 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6981 SourceLocation BuiltinLoc, 6982 SourceLocation RParenLoc) { 6983 ExprValueKind VK = VK_PRValue; 6984 ExprObjectKind OK = OK_Ordinary; 6985 QualType DstTy = TInfo->getType(); 6986 QualType SrcTy = E->getType(); 6987 6988 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6989 return ExprError(Diag(BuiltinLoc, 6990 diag::err_convertvector_non_vector) 6991 << E->getSourceRange()); 6992 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6993 return ExprError(Diag(BuiltinLoc, 6994 diag::err_convertvector_non_vector_type)); 6995 6996 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6997 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6998 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6999 if (SrcElts != DstElts) 7000 return ExprError(Diag(BuiltinLoc, 7001 diag::err_convertvector_incompatible_vector) 7002 << E->getSourceRange()); 7003 } 7004 7005 return new (Context) 7006 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 7007 } 7008 7009 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 7010 // This is declared to take (const void*, ...) and can take two 7011 // optional constant int args. 7012 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 7013 unsigned NumArgs = TheCall->getNumArgs(); 7014 7015 if (NumArgs > 3) 7016 return Diag(TheCall->getEndLoc(), 7017 diag::err_typecheck_call_too_many_args_at_most) 7018 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 7019 7020 // Argument 0 is checked for us and the remaining arguments must be 7021 // constant integers. 7022 for (unsigned i = 1; i != NumArgs; ++i) 7023 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 7024 return true; 7025 7026 return false; 7027 } 7028 7029 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 7030 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 7031 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 7032 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 7033 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7034 if (checkArgCount(*this, TheCall, 1)) 7035 return true; 7036 Expr *Arg = TheCall->getArg(0); 7037 if (Arg->isInstantiationDependent()) 7038 return false; 7039 7040 QualType ArgTy = Arg->getType(); 7041 if (!ArgTy->hasFloatingRepresentation()) 7042 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 7043 << ArgTy; 7044 if (Arg->isLValue()) { 7045 ExprResult FirstArg = DefaultLvalueConversion(Arg); 7046 TheCall->setArg(0, FirstArg.get()); 7047 } 7048 TheCall->setType(TheCall->getArg(0)->getType()); 7049 return false; 7050 } 7051 7052 /// SemaBuiltinAssume - Handle __assume (MS Extension). 7053 // __assume does not evaluate its arguments, and should warn if its argument 7054 // has side effects. 7055 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 7056 Expr *Arg = TheCall->getArg(0); 7057 if (Arg->isInstantiationDependent()) return false; 7058 7059 if (Arg->HasSideEffects(Context)) 7060 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 7061 << Arg->getSourceRange() 7062 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 7063 7064 return false; 7065 } 7066 7067 /// Handle __builtin_alloca_with_align. This is declared 7068 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 7069 /// than 8. 7070 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 7071 // The alignment must be a constant integer. 7072 Expr *Arg = TheCall->getArg(1); 7073 7074 // We can't check the value of a dependent argument. 7075 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 7076 if (const auto *UE = 7077 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 7078 if (UE->getKind() == UETT_AlignOf || 7079 UE->getKind() == UETT_PreferredAlignOf) 7080 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 7081 << Arg->getSourceRange(); 7082 7083 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 7084 7085 if (!Result.isPowerOf2()) 7086 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 7087 << Arg->getSourceRange(); 7088 7089 if (Result < Context.getCharWidth()) 7090 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 7091 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 7092 7093 if (Result > std::numeric_limits<int32_t>::max()) 7094 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 7095 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 7096 } 7097 7098 return false; 7099 } 7100 7101 /// Handle __builtin_assume_aligned. This is declared 7102 /// as (const void*, size_t, ...) and can take one optional constant int arg. 7103 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 7104 unsigned NumArgs = TheCall->getNumArgs(); 7105 7106 if (NumArgs > 3) 7107 return Diag(TheCall->getEndLoc(), 7108 diag::err_typecheck_call_too_many_args_at_most) 7109 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 7110 7111 // The alignment must be a constant integer. 7112 Expr *Arg = TheCall->getArg(1); 7113 7114 // We can't check the value of a dependent argument. 7115 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 7116 llvm::APSInt Result; 7117 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7118 return true; 7119 7120 if (!Result.isPowerOf2()) 7121 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 7122 << Arg->getSourceRange(); 7123 7124 if (Result > Sema::MaximumAlignment) 7125 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 7126 << Arg->getSourceRange() << Sema::MaximumAlignment; 7127 } 7128 7129 if (NumArgs > 2) { 7130 ExprResult Arg(TheCall->getArg(2)); 7131 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 7132 Context.getSizeType(), false); 7133 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7134 if (Arg.isInvalid()) return true; 7135 TheCall->setArg(2, Arg.get()); 7136 } 7137 7138 return false; 7139 } 7140 7141 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 7142 unsigned BuiltinID = 7143 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 7144 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 7145 7146 unsigned NumArgs = TheCall->getNumArgs(); 7147 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 7148 if (NumArgs < NumRequiredArgs) { 7149 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 7150 << 0 /* function call */ << NumRequiredArgs << NumArgs 7151 << TheCall->getSourceRange(); 7152 } 7153 if (NumArgs >= NumRequiredArgs + 0x100) { 7154 return Diag(TheCall->getEndLoc(), 7155 diag::err_typecheck_call_too_many_args_at_most) 7156 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 7157 << TheCall->getSourceRange(); 7158 } 7159 unsigned i = 0; 7160 7161 // For formatting call, check buffer arg. 7162 if (!IsSizeCall) { 7163 ExprResult Arg(TheCall->getArg(i)); 7164 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7165 Context, Context.VoidPtrTy, false); 7166 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7167 if (Arg.isInvalid()) 7168 return true; 7169 TheCall->setArg(i, Arg.get()); 7170 i++; 7171 } 7172 7173 // Check string literal arg. 7174 unsigned FormatIdx = i; 7175 { 7176 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 7177 if (Arg.isInvalid()) 7178 return true; 7179 TheCall->setArg(i, Arg.get()); 7180 i++; 7181 } 7182 7183 // Make sure variadic args are scalar. 7184 unsigned FirstDataArg = i; 7185 while (i < NumArgs) { 7186 ExprResult Arg = DefaultVariadicArgumentPromotion( 7187 TheCall->getArg(i), VariadicFunction, nullptr); 7188 if (Arg.isInvalid()) 7189 return true; 7190 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 7191 if (ArgSize.getQuantity() >= 0x100) { 7192 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 7193 << i << (int)ArgSize.getQuantity() << 0xff 7194 << TheCall->getSourceRange(); 7195 } 7196 TheCall->setArg(i, Arg.get()); 7197 i++; 7198 } 7199 7200 // Check formatting specifiers. NOTE: We're only doing this for the non-size 7201 // call to avoid duplicate diagnostics. 7202 if (!IsSizeCall) { 7203 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 7204 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 7205 bool Success = CheckFormatArguments( 7206 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 7207 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 7208 CheckedVarArgs); 7209 if (!Success) 7210 return true; 7211 } 7212 7213 if (IsSizeCall) { 7214 TheCall->setType(Context.getSizeType()); 7215 } else { 7216 TheCall->setType(Context.VoidPtrTy); 7217 } 7218 return false; 7219 } 7220 7221 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 7222 /// TheCall is a constant expression. 7223 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7224 llvm::APSInt &Result) { 7225 Expr *Arg = TheCall->getArg(ArgNum); 7226 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 7227 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 7228 7229 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 7230 7231 Optional<llvm::APSInt> R; 7232 if (!(R = Arg->getIntegerConstantExpr(Context))) 7233 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 7234 << FDecl->getDeclName() << Arg->getSourceRange(); 7235 Result = *R; 7236 return false; 7237 } 7238 7239 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 7240 /// TheCall is a constant expression in the range [Low, High]. 7241 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 7242 int Low, int High, bool RangeIsError) { 7243 if (isConstantEvaluated()) 7244 return false; 7245 llvm::APSInt Result; 7246 7247 // We can't check the value of a dependent argument. 7248 Expr *Arg = TheCall->getArg(ArgNum); 7249 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7250 return false; 7251 7252 // Check constant-ness first. 7253 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7254 return true; 7255 7256 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 7257 if (RangeIsError) 7258 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 7259 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 7260 else 7261 // Defer the warning until we know if the code will be emitted so that 7262 // dead code can ignore this. 7263 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 7264 PDiag(diag::warn_argument_invalid_range) 7265 << toString(Result, 10) << Low << High 7266 << Arg->getSourceRange()); 7267 } 7268 7269 return false; 7270 } 7271 7272 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 7273 /// TheCall is a constant expression is a multiple of Num.. 7274 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 7275 unsigned Num) { 7276 llvm::APSInt Result; 7277 7278 // We can't check the value of a dependent argument. 7279 Expr *Arg = TheCall->getArg(ArgNum); 7280 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7281 return false; 7282 7283 // Check constant-ness first. 7284 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7285 return true; 7286 7287 if (Result.getSExtValue() % Num != 0) 7288 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 7289 << Num << Arg->getSourceRange(); 7290 7291 return false; 7292 } 7293 7294 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 7295 /// constant expression representing a power of 2. 7296 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 7297 llvm::APSInt Result; 7298 7299 // We can't check the value of a dependent argument. 7300 Expr *Arg = TheCall->getArg(ArgNum); 7301 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7302 return false; 7303 7304 // Check constant-ness first. 7305 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7306 return true; 7307 7308 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 7309 // and only if x is a power of 2. 7310 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 7311 return false; 7312 7313 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 7314 << Arg->getSourceRange(); 7315 } 7316 7317 static bool IsShiftedByte(llvm::APSInt Value) { 7318 if (Value.isNegative()) 7319 return false; 7320 7321 // Check if it's a shifted byte, by shifting it down 7322 while (true) { 7323 // If the value fits in the bottom byte, the check passes. 7324 if (Value < 0x100) 7325 return true; 7326 7327 // Otherwise, if the value has _any_ bits in the bottom byte, the check 7328 // fails. 7329 if ((Value & 0xFF) != 0) 7330 return false; 7331 7332 // If the bottom 8 bits are all 0, but something above that is nonzero, 7333 // then shifting the value right by 8 bits won't affect whether it's a 7334 // shifted byte or not. So do that, and go round again. 7335 Value >>= 8; 7336 } 7337 } 7338 7339 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 7340 /// a constant expression representing an arbitrary byte value shifted left by 7341 /// a multiple of 8 bits. 7342 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 7343 unsigned ArgBits) { 7344 llvm::APSInt Result; 7345 7346 // We can't check the value of a dependent argument. 7347 Expr *Arg = TheCall->getArg(ArgNum); 7348 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7349 return false; 7350 7351 // Check constant-ness first. 7352 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7353 return true; 7354 7355 // Truncate to the given size. 7356 Result = Result.getLoBits(ArgBits); 7357 Result.setIsUnsigned(true); 7358 7359 if (IsShiftedByte(Result)) 7360 return false; 7361 7362 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7363 << Arg->getSourceRange(); 7364 } 7365 7366 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7367 /// TheCall is a constant expression representing either a shifted byte value, 7368 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7369 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7370 /// Arm MVE intrinsics. 7371 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7372 int ArgNum, 7373 unsigned ArgBits) { 7374 llvm::APSInt Result; 7375 7376 // We can't check the value of a dependent argument. 7377 Expr *Arg = TheCall->getArg(ArgNum); 7378 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7379 return false; 7380 7381 // Check constant-ness first. 7382 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7383 return true; 7384 7385 // Truncate to the given size. 7386 Result = Result.getLoBits(ArgBits); 7387 Result.setIsUnsigned(true); 7388 7389 // Check to see if it's in either of the required forms. 7390 if (IsShiftedByte(Result) || 7391 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7392 return false; 7393 7394 return Diag(TheCall->getBeginLoc(), 7395 diag::err_argument_not_shifted_byte_or_xxff) 7396 << Arg->getSourceRange(); 7397 } 7398 7399 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7400 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7401 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7402 if (checkArgCount(*this, TheCall, 2)) 7403 return true; 7404 Expr *Arg0 = TheCall->getArg(0); 7405 Expr *Arg1 = TheCall->getArg(1); 7406 7407 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7408 if (FirstArg.isInvalid()) 7409 return true; 7410 QualType FirstArgType = FirstArg.get()->getType(); 7411 if (!FirstArgType->isAnyPointerType()) 7412 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7413 << "first" << FirstArgType << Arg0->getSourceRange(); 7414 TheCall->setArg(0, FirstArg.get()); 7415 7416 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7417 if (SecArg.isInvalid()) 7418 return true; 7419 QualType SecArgType = SecArg.get()->getType(); 7420 if (!SecArgType->isIntegerType()) 7421 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7422 << "second" << SecArgType << Arg1->getSourceRange(); 7423 7424 // Derive the return type from the pointer argument. 7425 TheCall->setType(FirstArgType); 7426 return false; 7427 } 7428 7429 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7430 if (checkArgCount(*this, TheCall, 2)) 7431 return true; 7432 7433 Expr *Arg0 = TheCall->getArg(0); 7434 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7435 if (FirstArg.isInvalid()) 7436 return true; 7437 QualType FirstArgType = FirstArg.get()->getType(); 7438 if (!FirstArgType->isAnyPointerType()) 7439 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7440 << "first" << FirstArgType << Arg0->getSourceRange(); 7441 TheCall->setArg(0, FirstArg.get()); 7442 7443 // Derive the return type from the pointer argument. 7444 TheCall->setType(FirstArgType); 7445 7446 // Second arg must be an constant in range [0,15] 7447 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7448 } 7449 7450 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7451 if (checkArgCount(*this, TheCall, 2)) 7452 return true; 7453 Expr *Arg0 = TheCall->getArg(0); 7454 Expr *Arg1 = TheCall->getArg(1); 7455 7456 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7457 if (FirstArg.isInvalid()) 7458 return true; 7459 QualType FirstArgType = FirstArg.get()->getType(); 7460 if (!FirstArgType->isAnyPointerType()) 7461 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7462 << "first" << FirstArgType << Arg0->getSourceRange(); 7463 7464 QualType SecArgType = Arg1->getType(); 7465 if (!SecArgType->isIntegerType()) 7466 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7467 << "second" << SecArgType << Arg1->getSourceRange(); 7468 TheCall->setType(Context.IntTy); 7469 return false; 7470 } 7471 7472 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7473 BuiltinID == AArch64::BI__builtin_arm_stg) { 7474 if (checkArgCount(*this, TheCall, 1)) 7475 return true; 7476 Expr *Arg0 = TheCall->getArg(0); 7477 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7478 if (FirstArg.isInvalid()) 7479 return true; 7480 7481 QualType FirstArgType = FirstArg.get()->getType(); 7482 if (!FirstArgType->isAnyPointerType()) 7483 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7484 << "first" << FirstArgType << Arg0->getSourceRange(); 7485 TheCall->setArg(0, FirstArg.get()); 7486 7487 // Derive the return type from the pointer argument. 7488 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7489 TheCall->setType(FirstArgType); 7490 return false; 7491 } 7492 7493 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7494 Expr *ArgA = TheCall->getArg(0); 7495 Expr *ArgB = TheCall->getArg(1); 7496 7497 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7498 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7499 7500 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7501 return true; 7502 7503 QualType ArgTypeA = ArgExprA.get()->getType(); 7504 QualType ArgTypeB = ArgExprB.get()->getType(); 7505 7506 auto isNull = [&] (Expr *E) -> bool { 7507 return E->isNullPointerConstant( 7508 Context, Expr::NPC_ValueDependentIsNotNull); }; 7509 7510 // argument should be either a pointer or null 7511 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7512 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7513 << "first" << ArgTypeA << ArgA->getSourceRange(); 7514 7515 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7516 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7517 << "second" << ArgTypeB << ArgB->getSourceRange(); 7518 7519 // Ensure Pointee types are compatible 7520 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7521 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7522 QualType pointeeA = ArgTypeA->getPointeeType(); 7523 QualType pointeeB = ArgTypeB->getPointeeType(); 7524 if (!Context.typesAreCompatible( 7525 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7526 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7527 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7528 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7529 << ArgB->getSourceRange(); 7530 } 7531 } 7532 7533 // at least one argument should be pointer type 7534 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7535 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7536 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7537 7538 if (isNull(ArgA)) // adopt type of the other pointer 7539 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7540 7541 if (isNull(ArgB)) 7542 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7543 7544 TheCall->setArg(0, ArgExprA.get()); 7545 TheCall->setArg(1, ArgExprB.get()); 7546 TheCall->setType(Context.LongLongTy); 7547 return false; 7548 } 7549 assert(false && "Unhandled ARM MTE intrinsic"); 7550 return true; 7551 } 7552 7553 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7554 /// TheCall is an ARM/AArch64 special register string literal. 7555 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7556 int ArgNum, unsigned ExpectedFieldNum, 7557 bool AllowName) { 7558 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7559 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7560 BuiltinID == ARM::BI__builtin_arm_rsr || 7561 BuiltinID == ARM::BI__builtin_arm_rsrp || 7562 BuiltinID == ARM::BI__builtin_arm_wsr || 7563 BuiltinID == ARM::BI__builtin_arm_wsrp; 7564 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7565 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7566 BuiltinID == AArch64::BI__builtin_arm_rsr || 7567 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7568 BuiltinID == AArch64::BI__builtin_arm_wsr || 7569 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7570 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7571 7572 // We can't check the value of a dependent argument. 7573 Expr *Arg = TheCall->getArg(ArgNum); 7574 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7575 return false; 7576 7577 // Check if the argument is a string literal. 7578 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7579 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7580 << Arg->getSourceRange(); 7581 7582 // Check the type of special register given. 7583 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7584 SmallVector<StringRef, 6> Fields; 7585 Reg.split(Fields, ":"); 7586 7587 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7588 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7589 << Arg->getSourceRange(); 7590 7591 // If the string is the name of a register then we cannot check that it is 7592 // valid here but if the string is of one the forms described in ACLE then we 7593 // can check that the supplied fields are integers and within the valid 7594 // ranges. 7595 if (Fields.size() > 1) { 7596 bool FiveFields = Fields.size() == 5; 7597 7598 bool ValidString = true; 7599 if (IsARMBuiltin) { 7600 ValidString &= Fields[0].startswith_insensitive("cp") || 7601 Fields[0].startswith_insensitive("p"); 7602 if (ValidString) 7603 Fields[0] = Fields[0].drop_front( 7604 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7605 7606 ValidString &= Fields[2].startswith_insensitive("c"); 7607 if (ValidString) 7608 Fields[2] = Fields[2].drop_front(1); 7609 7610 if (FiveFields) { 7611 ValidString &= Fields[3].startswith_insensitive("c"); 7612 if (ValidString) 7613 Fields[3] = Fields[3].drop_front(1); 7614 } 7615 } 7616 7617 SmallVector<int, 5> Ranges; 7618 if (FiveFields) 7619 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7620 else 7621 Ranges.append({15, 7, 15}); 7622 7623 for (unsigned i=0; i<Fields.size(); ++i) { 7624 int IntField; 7625 ValidString &= !Fields[i].getAsInteger(10, IntField); 7626 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7627 } 7628 7629 if (!ValidString) 7630 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7631 << Arg->getSourceRange(); 7632 } else if (IsAArch64Builtin && Fields.size() == 1) { 7633 // If the register name is one of those that appear in the condition below 7634 // and the special register builtin being used is one of the write builtins, 7635 // then we require that the argument provided for writing to the register 7636 // is an integer constant expression. This is because it will be lowered to 7637 // an MSR (immediate) instruction, so we need to know the immediate at 7638 // compile time. 7639 if (TheCall->getNumArgs() != 2) 7640 return false; 7641 7642 std::string RegLower = Reg.lower(); 7643 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7644 RegLower != "pan" && RegLower != "uao") 7645 return false; 7646 7647 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7648 } 7649 7650 return false; 7651 } 7652 7653 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7654 /// Emit an error and return true on failure; return false on success. 7655 /// TypeStr is a string containing the type descriptor of the value returned by 7656 /// the builtin and the descriptors of the expected type of the arguments. 7657 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, 7658 const char *TypeStr) { 7659 7660 assert((TypeStr[0] != '\0') && 7661 "Invalid types in PPC MMA builtin declaration"); 7662 7663 switch (BuiltinID) { 7664 default: 7665 // This function is called in CheckPPCBuiltinFunctionCall where the 7666 // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here 7667 // we are isolating the pair vector memop builtins that can be used with mma 7668 // off so the default case is every builtin that requires mma and paired 7669 // vector memops. 7670 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7671 diag::err_ppc_builtin_only_on_arch, "10") || 7672 SemaFeatureCheck(*this, TheCall, "mma", 7673 diag::err_ppc_builtin_only_on_arch, "10")) 7674 return true; 7675 break; 7676 case PPC::BI__builtin_vsx_lxvp: 7677 case PPC::BI__builtin_vsx_stxvp: 7678 case PPC::BI__builtin_vsx_assemble_pair: 7679 case PPC::BI__builtin_vsx_disassemble_pair: 7680 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7681 diag::err_ppc_builtin_only_on_arch, "10")) 7682 return true; 7683 break; 7684 } 7685 7686 unsigned Mask = 0; 7687 unsigned ArgNum = 0; 7688 7689 // The first type in TypeStr is the type of the value returned by the 7690 // builtin. So we first read that type and change the type of TheCall. 7691 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7692 TheCall->setType(type); 7693 7694 while (*TypeStr != '\0') { 7695 Mask = 0; 7696 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7697 if (ArgNum >= TheCall->getNumArgs()) { 7698 ArgNum++; 7699 break; 7700 } 7701 7702 Expr *Arg = TheCall->getArg(ArgNum); 7703 QualType PassedType = Arg->getType(); 7704 QualType StrippedRVType = PassedType.getCanonicalType(); 7705 7706 // Strip Restrict/Volatile qualifiers. 7707 if (StrippedRVType.isRestrictQualified() || 7708 StrippedRVType.isVolatileQualified()) 7709 StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType(); 7710 7711 // The only case where the argument type and expected type are allowed to 7712 // mismatch is if the argument type is a non-void pointer (or array) and 7713 // expected type is a void pointer. 7714 if (StrippedRVType != ExpectedType) 7715 if (!(ExpectedType->isVoidPointerType() && 7716 (StrippedRVType->isPointerType() || StrippedRVType->isArrayType()))) 7717 return Diag(Arg->getBeginLoc(), 7718 diag::err_typecheck_convert_incompatible) 7719 << PassedType << ExpectedType << 1 << 0 << 0; 7720 7721 // If the value of the Mask is not 0, we have a constraint in the size of 7722 // the integer argument so here we ensure the argument is a constant that 7723 // is in the valid range. 7724 if (Mask != 0 && 7725 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7726 return true; 7727 7728 ArgNum++; 7729 } 7730 7731 // In case we exited early from the previous loop, there are other types to 7732 // read from TypeStr. So we need to read them all to ensure we have the right 7733 // number of arguments in TheCall and if it is not the case, to display a 7734 // better error message. 7735 while (*TypeStr != '\0') { 7736 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7737 ArgNum++; 7738 } 7739 if (checkArgCount(*this, TheCall, ArgNum)) 7740 return true; 7741 7742 return false; 7743 } 7744 7745 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7746 /// This checks that the target supports __builtin_longjmp and 7747 /// that val is a constant 1. 7748 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7749 if (!Context.getTargetInfo().hasSjLjLowering()) 7750 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7751 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7752 7753 Expr *Arg = TheCall->getArg(1); 7754 llvm::APSInt Result; 7755 7756 // TODO: This is less than ideal. Overload this to take a value. 7757 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7758 return true; 7759 7760 if (Result != 1) 7761 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7762 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7763 7764 return false; 7765 } 7766 7767 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7768 /// This checks that the target supports __builtin_setjmp. 7769 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7770 if (!Context.getTargetInfo().hasSjLjLowering()) 7771 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7772 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7773 return false; 7774 } 7775 7776 namespace { 7777 7778 class UncoveredArgHandler { 7779 enum { Unknown = -1, AllCovered = -2 }; 7780 7781 signed FirstUncoveredArg = Unknown; 7782 SmallVector<const Expr *, 4> DiagnosticExprs; 7783 7784 public: 7785 UncoveredArgHandler() = default; 7786 7787 bool hasUncoveredArg() const { 7788 return (FirstUncoveredArg >= 0); 7789 } 7790 7791 unsigned getUncoveredArg() const { 7792 assert(hasUncoveredArg() && "no uncovered argument"); 7793 return FirstUncoveredArg; 7794 } 7795 7796 void setAllCovered() { 7797 // A string has been found with all arguments covered, so clear out 7798 // the diagnostics. 7799 DiagnosticExprs.clear(); 7800 FirstUncoveredArg = AllCovered; 7801 } 7802 7803 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7804 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7805 7806 // Don't update if a previous string covers all arguments. 7807 if (FirstUncoveredArg == AllCovered) 7808 return; 7809 7810 // UncoveredArgHandler tracks the highest uncovered argument index 7811 // and with it all the strings that match this index. 7812 if (NewFirstUncoveredArg == FirstUncoveredArg) 7813 DiagnosticExprs.push_back(StrExpr); 7814 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7815 DiagnosticExprs.clear(); 7816 DiagnosticExprs.push_back(StrExpr); 7817 FirstUncoveredArg = NewFirstUncoveredArg; 7818 } 7819 } 7820 7821 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7822 }; 7823 7824 enum StringLiteralCheckType { 7825 SLCT_NotALiteral, 7826 SLCT_UncheckedLiteral, 7827 SLCT_CheckedLiteral 7828 }; 7829 7830 } // namespace 7831 7832 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7833 BinaryOperatorKind BinOpKind, 7834 bool AddendIsRight) { 7835 unsigned BitWidth = Offset.getBitWidth(); 7836 unsigned AddendBitWidth = Addend.getBitWidth(); 7837 // There might be negative interim results. 7838 if (Addend.isUnsigned()) { 7839 Addend = Addend.zext(++AddendBitWidth); 7840 Addend.setIsSigned(true); 7841 } 7842 // Adjust the bit width of the APSInts. 7843 if (AddendBitWidth > BitWidth) { 7844 Offset = Offset.sext(AddendBitWidth); 7845 BitWidth = AddendBitWidth; 7846 } else if (BitWidth > AddendBitWidth) { 7847 Addend = Addend.sext(BitWidth); 7848 } 7849 7850 bool Ov = false; 7851 llvm::APSInt ResOffset = Offset; 7852 if (BinOpKind == BO_Add) 7853 ResOffset = Offset.sadd_ov(Addend, Ov); 7854 else { 7855 assert(AddendIsRight && BinOpKind == BO_Sub && 7856 "operator must be add or sub with addend on the right"); 7857 ResOffset = Offset.ssub_ov(Addend, Ov); 7858 } 7859 7860 // We add an offset to a pointer here so we should support an offset as big as 7861 // possible. 7862 if (Ov) { 7863 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7864 "index (intermediate) result too big"); 7865 Offset = Offset.sext(2 * BitWidth); 7866 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7867 return; 7868 } 7869 7870 Offset = ResOffset; 7871 } 7872 7873 namespace { 7874 7875 // This is a wrapper class around StringLiteral to support offsetted string 7876 // literals as format strings. It takes the offset into account when returning 7877 // the string and its length or the source locations to display notes correctly. 7878 class FormatStringLiteral { 7879 const StringLiteral *FExpr; 7880 int64_t Offset; 7881 7882 public: 7883 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7884 : FExpr(fexpr), Offset(Offset) {} 7885 7886 StringRef getString() const { 7887 return FExpr->getString().drop_front(Offset); 7888 } 7889 7890 unsigned getByteLength() const { 7891 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7892 } 7893 7894 unsigned getLength() const { return FExpr->getLength() - Offset; } 7895 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7896 7897 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7898 7899 QualType getType() const { return FExpr->getType(); } 7900 7901 bool isAscii() const { return FExpr->isAscii(); } 7902 bool isWide() const { return FExpr->isWide(); } 7903 bool isUTF8() const { return FExpr->isUTF8(); } 7904 bool isUTF16() const { return FExpr->isUTF16(); } 7905 bool isUTF32() const { return FExpr->isUTF32(); } 7906 bool isPascal() const { return FExpr->isPascal(); } 7907 7908 SourceLocation getLocationOfByte( 7909 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7910 const TargetInfo &Target, unsigned *StartToken = nullptr, 7911 unsigned *StartTokenByteOffset = nullptr) const { 7912 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7913 StartToken, StartTokenByteOffset); 7914 } 7915 7916 SourceLocation getBeginLoc() const LLVM_READONLY { 7917 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7918 } 7919 7920 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7921 }; 7922 7923 } // namespace 7924 7925 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7926 const Expr *OrigFormatExpr, 7927 ArrayRef<const Expr *> Args, 7928 bool HasVAListArg, unsigned format_idx, 7929 unsigned firstDataArg, 7930 Sema::FormatStringType Type, 7931 bool inFunctionCall, 7932 Sema::VariadicCallType CallType, 7933 llvm::SmallBitVector &CheckedVarArgs, 7934 UncoveredArgHandler &UncoveredArg, 7935 bool IgnoreStringsWithoutSpecifiers); 7936 7937 // Determine if an expression is a string literal or constant string. 7938 // If this function returns false on the arguments to a function expecting a 7939 // format string, we will usually need to emit a warning. 7940 // True string literals are then checked by CheckFormatString. 7941 static StringLiteralCheckType 7942 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7943 bool HasVAListArg, unsigned format_idx, 7944 unsigned firstDataArg, Sema::FormatStringType Type, 7945 Sema::VariadicCallType CallType, bool InFunctionCall, 7946 llvm::SmallBitVector &CheckedVarArgs, 7947 UncoveredArgHandler &UncoveredArg, 7948 llvm::APSInt Offset, 7949 bool IgnoreStringsWithoutSpecifiers = false) { 7950 if (S.isConstantEvaluated()) 7951 return SLCT_NotALiteral; 7952 tryAgain: 7953 assert(Offset.isSigned() && "invalid offset"); 7954 7955 if (E->isTypeDependent() || E->isValueDependent()) 7956 return SLCT_NotALiteral; 7957 7958 E = E->IgnoreParenCasts(); 7959 7960 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7961 // Technically -Wformat-nonliteral does not warn about this case. 7962 // The behavior of printf and friends in this case is implementation 7963 // dependent. Ideally if the format string cannot be null then 7964 // it should have a 'nonnull' attribute in the function prototype. 7965 return SLCT_UncheckedLiteral; 7966 7967 switch (E->getStmtClass()) { 7968 case Stmt::BinaryConditionalOperatorClass: 7969 case Stmt::ConditionalOperatorClass: { 7970 // The expression is a literal if both sub-expressions were, and it was 7971 // completely checked only if both sub-expressions were checked. 7972 const AbstractConditionalOperator *C = 7973 cast<AbstractConditionalOperator>(E); 7974 7975 // Determine whether it is necessary to check both sub-expressions, for 7976 // example, because the condition expression is a constant that can be 7977 // evaluated at compile time. 7978 bool CheckLeft = true, CheckRight = true; 7979 7980 bool Cond; 7981 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7982 S.isConstantEvaluated())) { 7983 if (Cond) 7984 CheckRight = false; 7985 else 7986 CheckLeft = false; 7987 } 7988 7989 // We need to maintain the offsets for the right and the left hand side 7990 // separately to check if every possible indexed expression is a valid 7991 // string literal. They might have different offsets for different string 7992 // literals in the end. 7993 StringLiteralCheckType Left; 7994 if (!CheckLeft) 7995 Left = SLCT_UncheckedLiteral; 7996 else { 7997 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7998 HasVAListArg, format_idx, firstDataArg, 7999 Type, CallType, InFunctionCall, 8000 CheckedVarArgs, UncoveredArg, Offset, 8001 IgnoreStringsWithoutSpecifiers); 8002 if (Left == SLCT_NotALiteral || !CheckRight) { 8003 return Left; 8004 } 8005 } 8006 8007 StringLiteralCheckType Right = checkFormatStringExpr( 8008 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 8009 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8010 IgnoreStringsWithoutSpecifiers); 8011 8012 return (CheckLeft && Left < Right) ? Left : Right; 8013 } 8014 8015 case Stmt::ImplicitCastExprClass: 8016 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 8017 goto tryAgain; 8018 8019 case Stmt::OpaqueValueExprClass: 8020 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 8021 E = src; 8022 goto tryAgain; 8023 } 8024 return SLCT_NotALiteral; 8025 8026 case Stmt::PredefinedExprClass: 8027 // While __func__, etc., are technically not string literals, they 8028 // cannot contain format specifiers and thus are not a security 8029 // liability. 8030 return SLCT_UncheckedLiteral; 8031 8032 case Stmt::DeclRefExprClass: { 8033 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8034 8035 // As an exception, do not flag errors for variables binding to 8036 // const string literals. 8037 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 8038 bool isConstant = false; 8039 QualType T = DR->getType(); 8040 8041 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 8042 isConstant = AT->getElementType().isConstant(S.Context); 8043 } else if (const PointerType *PT = T->getAs<PointerType>()) { 8044 isConstant = T.isConstant(S.Context) && 8045 PT->getPointeeType().isConstant(S.Context); 8046 } else if (T->isObjCObjectPointerType()) { 8047 // In ObjC, there is usually no "const ObjectPointer" type, 8048 // so don't check if the pointee type is constant. 8049 isConstant = T.isConstant(S.Context); 8050 } 8051 8052 if (isConstant) { 8053 if (const Expr *Init = VD->getAnyInitializer()) { 8054 // Look through initializers like const char c[] = { "foo" } 8055 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 8056 if (InitList->isStringLiteralInit()) 8057 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 8058 } 8059 return checkFormatStringExpr(S, Init, Args, 8060 HasVAListArg, format_idx, 8061 firstDataArg, Type, CallType, 8062 /*InFunctionCall*/ false, CheckedVarArgs, 8063 UncoveredArg, Offset); 8064 } 8065 } 8066 8067 // For vprintf* functions (i.e., HasVAListArg==true), we add a 8068 // special check to see if the format string is a function parameter 8069 // of the function calling the printf function. If the function 8070 // has an attribute indicating it is a printf-like function, then we 8071 // should suppress warnings concerning non-literals being used in a call 8072 // to a vprintf function. For example: 8073 // 8074 // void 8075 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 8076 // va_list ap; 8077 // va_start(ap, fmt); 8078 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 8079 // ... 8080 // } 8081 if (HasVAListArg) { 8082 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 8083 if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) { 8084 int PVIndex = PV->getFunctionScopeIndex() + 1; 8085 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) { 8086 // adjust for implicit parameter 8087 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) 8088 if (MD->isInstance()) 8089 ++PVIndex; 8090 // We also check if the formats are compatible. 8091 // We can't pass a 'scanf' string to a 'printf' function. 8092 if (PVIndex == PVFormat->getFormatIdx() && 8093 Type == S.GetFormatStringType(PVFormat)) 8094 return SLCT_UncheckedLiteral; 8095 } 8096 } 8097 } 8098 } 8099 } 8100 8101 return SLCT_NotALiteral; 8102 } 8103 8104 case Stmt::CallExprClass: 8105 case Stmt::CXXMemberCallExprClass: { 8106 const CallExpr *CE = cast<CallExpr>(E); 8107 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 8108 bool IsFirst = true; 8109 StringLiteralCheckType CommonResult; 8110 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 8111 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 8112 StringLiteralCheckType Result = checkFormatStringExpr( 8113 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 8114 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8115 IgnoreStringsWithoutSpecifiers); 8116 if (IsFirst) { 8117 CommonResult = Result; 8118 IsFirst = false; 8119 } 8120 } 8121 if (!IsFirst) 8122 return CommonResult; 8123 8124 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 8125 unsigned BuiltinID = FD->getBuiltinID(); 8126 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 8127 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 8128 const Expr *Arg = CE->getArg(0); 8129 return checkFormatStringExpr(S, Arg, Args, 8130 HasVAListArg, format_idx, 8131 firstDataArg, Type, CallType, 8132 InFunctionCall, CheckedVarArgs, 8133 UncoveredArg, Offset, 8134 IgnoreStringsWithoutSpecifiers); 8135 } 8136 } 8137 } 8138 8139 return SLCT_NotALiteral; 8140 } 8141 case Stmt::ObjCMessageExprClass: { 8142 const auto *ME = cast<ObjCMessageExpr>(E); 8143 if (const auto *MD = ME->getMethodDecl()) { 8144 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 8145 // As a special case heuristic, if we're using the method -[NSBundle 8146 // localizedStringForKey:value:table:], ignore any key strings that lack 8147 // format specifiers. The idea is that if the key doesn't have any 8148 // format specifiers then its probably just a key to map to the 8149 // localized strings. If it does have format specifiers though, then its 8150 // likely that the text of the key is the format string in the 8151 // programmer's language, and should be checked. 8152 const ObjCInterfaceDecl *IFace; 8153 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 8154 IFace->getIdentifier()->isStr("NSBundle") && 8155 MD->getSelector().isKeywordSelector( 8156 {"localizedStringForKey", "value", "table"})) { 8157 IgnoreStringsWithoutSpecifiers = true; 8158 } 8159 8160 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 8161 return checkFormatStringExpr( 8162 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 8163 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8164 IgnoreStringsWithoutSpecifiers); 8165 } 8166 } 8167 8168 return SLCT_NotALiteral; 8169 } 8170 case Stmt::ObjCStringLiteralClass: 8171 case Stmt::StringLiteralClass: { 8172 const StringLiteral *StrE = nullptr; 8173 8174 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 8175 StrE = ObjCFExpr->getString(); 8176 else 8177 StrE = cast<StringLiteral>(E); 8178 8179 if (StrE) { 8180 if (Offset.isNegative() || Offset > StrE->getLength()) { 8181 // TODO: It would be better to have an explicit warning for out of 8182 // bounds literals. 8183 return SLCT_NotALiteral; 8184 } 8185 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 8186 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 8187 firstDataArg, Type, InFunctionCall, CallType, 8188 CheckedVarArgs, UncoveredArg, 8189 IgnoreStringsWithoutSpecifiers); 8190 return SLCT_CheckedLiteral; 8191 } 8192 8193 return SLCT_NotALiteral; 8194 } 8195 case Stmt::BinaryOperatorClass: { 8196 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 8197 8198 // A string literal + an int offset is still a string literal. 8199 if (BinOp->isAdditiveOp()) { 8200 Expr::EvalResult LResult, RResult; 8201 8202 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 8203 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8204 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 8205 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8206 8207 if (LIsInt != RIsInt) { 8208 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 8209 8210 if (LIsInt) { 8211 if (BinOpKind == BO_Add) { 8212 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 8213 E = BinOp->getRHS(); 8214 goto tryAgain; 8215 } 8216 } else { 8217 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 8218 E = BinOp->getLHS(); 8219 goto tryAgain; 8220 } 8221 } 8222 } 8223 8224 return SLCT_NotALiteral; 8225 } 8226 case Stmt::UnaryOperatorClass: { 8227 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 8228 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 8229 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 8230 Expr::EvalResult IndexResult; 8231 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 8232 Expr::SE_NoSideEffects, 8233 S.isConstantEvaluated())) { 8234 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 8235 /*RHS is int*/ true); 8236 E = ASE->getBase(); 8237 goto tryAgain; 8238 } 8239 } 8240 8241 return SLCT_NotALiteral; 8242 } 8243 8244 default: 8245 return SLCT_NotALiteral; 8246 } 8247 } 8248 8249 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 8250 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 8251 .Case("scanf", FST_Scanf) 8252 .Cases("printf", "printf0", FST_Printf) 8253 .Cases("NSString", "CFString", FST_NSString) 8254 .Case("strftime", FST_Strftime) 8255 .Case("strfmon", FST_Strfmon) 8256 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 8257 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 8258 .Case("os_trace", FST_OSLog) 8259 .Case("os_log", FST_OSLog) 8260 .Default(FST_Unknown); 8261 } 8262 8263 /// CheckFormatArguments - Check calls to printf and scanf (and similar 8264 /// functions) for correct use of format strings. 8265 /// Returns true if a format string has been fully checked. 8266 bool Sema::CheckFormatArguments(const FormatAttr *Format, 8267 ArrayRef<const Expr *> Args, 8268 bool IsCXXMember, 8269 VariadicCallType CallType, 8270 SourceLocation Loc, SourceRange Range, 8271 llvm::SmallBitVector &CheckedVarArgs) { 8272 FormatStringInfo FSI; 8273 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 8274 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 8275 FSI.FirstDataArg, GetFormatStringType(Format), 8276 CallType, Loc, Range, CheckedVarArgs); 8277 return false; 8278 } 8279 8280 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 8281 bool HasVAListArg, unsigned format_idx, 8282 unsigned firstDataArg, FormatStringType Type, 8283 VariadicCallType CallType, 8284 SourceLocation Loc, SourceRange Range, 8285 llvm::SmallBitVector &CheckedVarArgs) { 8286 // CHECK: printf/scanf-like function is called with no format string. 8287 if (format_idx >= Args.size()) { 8288 Diag(Loc, diag::warn_missing_format_string) << Range; 8289 return false; 8290 } 8291 8292 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 8293 8294 // CHECK: format string is not a string literal. 8295 // 8296 // Dynamically generated format strings are difficult to 8297 // automatically vet at compile time. Requiring that format strings 8298 // are string literals: (1) permits the checking of format strings by 8299 // the compiler and thereby (2) can practically remove the source of 8300 // many format string exploits. 8301 8302 // Format string can be either ObjC string (e.g. @"%d") or 8303 // C string (e.g. "%d") 8304 // ObjC string uses the same format specifiers as C string, so we can use 8305 // the same format string checking logic for both ObjC and C strings. 8306 UncoveredArgHandler UncoveredArg; 8307 StringLiteralCheckType CT = 8308 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 8309 format_idx, firstDataArg, Type, CallType, 8310 /*IsFunctionCall*/ true, CheckedVarArgs, 8311 UncoveredArg, 8312 /*no string offset*/ llvm::APSInt(64, false) = 0); 8313 8314 // Generate a diagnostic where an uncovered argument is detected. 8315 if (UncoveredArg.hasUncoveredArg()) { 8316 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 8317 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 8318 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 8319 } 8320 8321 if (CT != SLCT_NotALiteral) 8322 // Literal format string found, check done! 8323 return CT == SLCT_CheckedLiteral; 8324 8325 // Strftime is particular as it always uses a single 'time' argument, 8326 // so it is safe to pass a non-literal string. 8327 if (Type == FST_Strftime) 8328 return false; 8329 8330 // Do not emit diag when the string param is a macro expansion and the 8331 // format is either NSString or CFString. This is a hack to prevent 8332 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 8333 // which are usually used in place of NS and CF string literals. 8334 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 8335 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 8336 return false; 8337 8338 // If there are no arguments specified, warn with -Wformat-security, otherwise 8339 // warn only with -Wformat-nonliteral. 8340 if (Args.size() == firstDataArg) { 8341 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 8342 << OrigFormatExpr->getSourceRange(); 8343 switch (Type) { 8344 default: 8345 break; 8346 case FST_Kprintf: 8347 case FST_FreeBSDKPrintf: 8348 case FST_Printf: 8349 Diag(FormatLoc, diag::note_format_security_fixit) 8350 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 8351 break; 8352 case FST_NSString: 8353 Diag(FormatLoc, diag::note_format_security_fixit) 8354 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 8355 break; 8356 } 8357 } else { 8358 Diag(FormatLoc, diag::warn_format_nonliteral) 8359 << OrigFormatExpr->getSourceRange(); 8360 } 8361 return false; 8362 } 8363 8364 namespace { 8365 8366 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 8367 protected: 8368 Sema &S; 8369 const FormatStringLiteral *FExpr; 8370 const Expr *OrigFormatExpr; 8371 const Sema::FormatStringType FSType; 8372 const unsigned FirstDataArg; 8373 const unsigned NumDataArgs; 8374 const char *Beg; // Start of format string. 8375 const bool HasVAListArg; 8376 ArrayRef<const Expr *> Args; 8377 unsigned FormatIdx; 8378 llvm::SmallBitVector CoveredArgs; 8379 bool usesPositionalArgs = false; 8380 bool atFirstArg = true; 8381 bool inFunctionCall; 8382 Sema::VariadicCallType CallType; 8383 llvm::SmallBitVector &CheckedVarArgs; 8384 UncoveredArgHandler &UncoveredArg; 8385 8386 public: 8387 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8388 const Expr *origFormatExpr, 8389 const Sema::FormatStringType type, unsigned firstDataArg, 8390 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8391 ArrayRef<const Expr *> Args, unsigned formatIdx, 8392 bool inFunctionCall, Sema::VariadicCallType callType, 8393 llvm::SmallBitVector &CheckedVarArgs, 8394 UncoveredArgHandler &UncoveredArg) 8395 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8396 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8397 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8398 inFunctionCall(inFunctionCall), CallType(callType), 8399 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8400 CoveredArgs.resize(numDataArgs); 8401 CoveredArgs.reset(); 8402 } 8403 8404 void DoneProcessing(); 8405 8406 void HandleIncompleteSpecifier(const char *startSpecifier, 8407 unsigned specifierLen) override; 8408 8409 void HandleInvalidLengthModifier( 8410 const analyze_format_string::FormatSpecifier &FS, 8411 const analyze_format_string::ConversionSpecifier &CS, 8412 const char *startSpecifier, unsigned specifierLen, 8413 unsigned DiagID); 8414 8415 void HandleNonStandardLengthModifier( 8416 const analyze_format_string::FormatSpecifier &FS, 8417 const char *startSpecifier, unsigned specifierLen); 8418 8419 void HandleNonStandardConversionSpecifier( 8420 const analyze_format_string::ConversionSpecifier &CS, 8421 const char *startSpecifier, unsigned specifierLen); 8422 8423 void HandlePosition(const char *startPos, unsigned posLen) override; 8424 8425 void HandleInvalidPosition(const char *startSpecifier, 8426 unsigned specifierLen, 8427 analyze_format_string::PositionContext p) override; 8428 8429 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8430 8431 void HandleNullChar(const char *nullCharacter) override; 8432 8433 template <typename Range> 8434 static void 8435 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8436 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8437 bool IsStringLocation, Range StringRange, 8438 ArrayRef<FixItHint> Fixit = None); 8439 8440 protected: 8441 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8442 const char *startSpec, 8443 unsigned specifierLen, 8444 const char *csStart, unsigned csLen); 8445 8446 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8447 const char *startSpec, 8448 unsigned specifierLen); 8449 8450 SourceRange getFormatStringRange(); 8451 CharSourceRange getSpecifierRange(const char *startSpecifier, 8452 unsigned specifierLen); 8453 SourceLocation getLocationOfByte(const char *x); 8454 8455 const Expr *getDataArg(unsigned i) const; 8456 8457 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8458 const analyze_format_string::ConversionSpecifier &CS, 8459 const char *startSpecifier, unsigned specifierLen, 8460 unsigned argIndex); 8461 8462 template <typename Range> 8463 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8464 bool IsStringLocation, Range StringRange, 8465 ArrayRef<FixItHint> Fixit = None); 8466 }; 8467 8468 } // namespace 8469 8470 SourceRange CheckFormatHandler::getFormatStringRange() { 8471 return OrigFormatExpr->getSourceRange(); 8472 } 8473 8474 CharSourceRange CheckFormatHandler:: 8475 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8476 SourceLocation Start = getLocationOfByte(startSpecifier); 8477 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8478 8479 // Advance the end SourceLocation by one due to half-open ranges. 8480 End = End.getLocWithOffset(1); 8481 8482 return CharSourceRange::getCharRange(Start, End); 8483 } 8484 8485 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8486 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8487 S.getLangOpts(), S.Context.getTargetInfo()); 8488 } 8489 8490 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8491 unsigned specifierLen){ 8492 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8493 getLocationOfByte(startSpecifier), 8494 /*IsStringLocation*/true, 8495 getSpecifierRange(startSpecifier, specifierLen)); 8496 } 8497 8498 void CheckFormatHandler::HandleInvalidLengthModifier( 8499 const analyze_format_string::FormatSpecifier &FS, 8500 const analyze_format_string::ConversionSpecifier &CS, 8501 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8502 using namespace analyze_format_string; 8503 8504 const LengthModifier &LM = FS.getLengthModifier(); 8505 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8506 8507 // See if we know how to fix this length modifier. 8508 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8509 if (FixedLM) { 8510 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8511 getLocationOfByte(LM.getStart()), 8512 /*IsStringLocation*/true, 8513 getSpecifierRange(startSpecifier, specifierLen)); 8514 8515 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8516 << FixedLM->toString() 8517 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8518 8519 } else { 8520 FixItHint Hint; 8521 if (DiagID == diag::warn_format_nonsensical_length) 8522 Hint = FixItHint::CreateRemoval(LMRange); 8523 8524 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8525 getLocationOfByte(LM.getStart()), 8526 /*IsStringLocation*/true, 8527 getSpecifierRange(startSpecifier, specifierLen), 8528 Hint); 8529 } 8530 } 8531 8532 void CheckFormatHandler::HandleNonStandardLengthModifier( 8533 const analyze_format_string::FormatSpecifier &FS, 8534 const char *startSpecifier, unsigned specifierLen) { 8535 using namespace analyze_format_string; 8536 8537 const LengthModifier &LM = FS.getLengthModifier(); 8538 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8539 8540 // See if we know how to fix this length modifier. 8541 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8542 if (FixedLM) { 8543 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8544 << LM.toString() << 0, 8545 getLocationOfByte(LM.getStart()), 8546 /*IsStringLocation*/true, 8547 getSpecifierRange(startSpecifier, specifierLen)); 8548 8549 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8550 << FixedLM->toString() 8551 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8552 8553 } else { 8554 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8555 << LM.toString() << 0, 8556 getLocationOfByte(LM.getStart()), 8557 /*IsStringLocation*/true, 8558 getSpecifierRange(startSpecifier, specifierLen)); 8559 } 8560 } 8561 8562 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8563 const analyze_format_string::ConversionSpecifier &CS, 8564 const char *startSpecifier, unsigned specifierLen) { 8565 using namespace analyze_format_string; 8566 8567 // See if we know how to fix this conversion specifier. 8568 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8569 if (FixedCS) { 8570 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8571 << CS.toString() << /*conversion specifier*/1, 8572 getLocationOfByte(CS.getStart()), 8573 /*IsStringLocation*/true, 8574 getSpecifierRange(startSpecifier, specifierLen)); 8575 8576 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8577 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8578 << FixedCS->toString() 8579 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8580 } else { 8581 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8582 << CS.toString() << /*conversion specifier*/1, 8583 getLocationOfByte(CS.getStart()), 8584 /*IsStringLocation*/true, 8585 getSpecifierRange(startSpecifier, specifierLen)); 8586 } 8587 } 8588 8589 void CheckFormatHandler::HandlePosition(const char *startPos, 8590 unsigned posLen) { 8591 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8592 getLocationOfByte(startPos), 8593 /*IsStringLocation*/true, 8594 getSpecifierRange(startPos, posLen)); 8595 } 8596 8597 void 8598 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8599 analyze_format_string::PositionContext p) { 8600 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8601 << (unsigned) p, 8602 getLocationOfByte(startPos), /*IsStringLocation*/true, 8603 getSpecifierRange(startPos, posLen)); 8604 } 8605 8606 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8607 unsigned posLen) { 8608 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8609 getLocationOfByte(startPos), 8610 /*IsStringLocation*/true, 8611 getSpecifierRange(startPos, posLen)); 8612 } 8613 8614 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8615 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8616 // The presence of a null character is likely an error. 8617 EmitFormatDiagnostic( 8618 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8619 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8620 getFormatStringRange()); 8621 } 8622 } 8623 8624 // Note that this may return NULL if there was an error parsing or building 8625 // one of the argument expressions. 8626 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8627 return Args[FirstDataArg + i]; 8628 } 8629 8630 void CheckFormatHandler::DoneProcessing() { 8631 // Does the number of data arguments exceed the number of 8632 // format conversions in the format string? 8633 if (!HasVAListArg) { 8634 // Find any arguments that weren't covered. 8635 CoveredArgs.flip(); 8636 signed notCoveredArg = CoveredArgs.find_first(); 8637 if (notCoveredArg >= 0) { 8638 assert((unsigned)notCoveredArg < NumDataArgs); 8639 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8640 } else { 8641 UncoveredArg.setAllCovered(); 8642 } 8643 } 8644 } 8645 8646 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8647 const Expr *ArgExpr) { 8648 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8649 "Invalid state"); 8650 8651 if (!ArgExpr) 8652 return; 8653 8654 SourceLocation Loc = ArgExpr->getBeginLoc(); 8655 8656 if (S.getSourceManager().isInSystemMacro(Loc)) 8657 return; 8658 8659 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8660 for (auto E : DiagnosticExprs) 8661 PDiag << E->getSourceRange(); 8662 8663 CheckFormatHandler::EmitFormatDiagnostic( 8664 S, IsFunctionCall, DiagnosticExprs[0], 8665 PDiag, Loc, /*IsStringLocation*/false, 8666 DiagnosticExprs[0]->getSourceRange()); 8667 } 8668 8669 bool 8670 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8671 SourceLocation Loc, 8672 const char *startSpec, 8673 unsigned specifierLen, 8674 const char *csStart, 8675 unsigned csLen) { 8676 bool keepGoing = true; 8677 if (argIndex < NumDataArgs) { 8678 // Consider the argument coverered, even though the specifier doesn't 8679 // make sense. 8680 CoveredArgs.set(argIndex); 8681 } 8682 else { 8683 // If argIndex exceeds the number of data arguments we 8684 // don't issue a warning because that is just a cascade of warnings (and 8685 // they may have intended '%%' anyway). We don't want to continue processing 8686 // the format string after this point, however, as we will like just get 8687 // gibberish when trying to match arguments. 8688 keepGoing = false; 8689 } 8690 8691 StringRef Specifier(csStart, csLen); 8692 8693 // If the specifier in non-printable, it could be the first byte of a UTF-8 8694 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8695 // hex value. 8696 std::string CodePointStr; 8697 if (!llvm::sys::locale::isPrint(*csStart)) { 8698 llvm::UTF32 CodePoint; 8699 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8700 const llvm::UTF8 *E = 8701 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8702 llvm::ConversionResult Result = 8703 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8704 8705 if (Result != llvm::conversionOK) { 8706 unsigned char FirstChar = *csStart; 8707 CodePoint = (llvm::UTF32)FirstChar; 8708 } 8709 8710 llvm::raw_string_ostream OS(CodePointStr); 8711 if (CodePoint < 256) 8712 OS << "\\x" << llvm::format("%02x", CodePoint); 8713 else if (CodePoint <= 0xFFFF) 8714 OS << "\\u" << llvm::format("%04x", CodePoint); 8715 else 8716 OS << "\\U" << llvm::format("%08x", CodePoint); 8717 OS.flush(); 8718 Specifier = CodePointStr; 8719 } 8720 8721 EmitFormatDiagnostic( 8722 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8723 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8724 8725 return keepGoing; 8726 } 8727 8728 void 8729 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8730 const char *startSpec, 8731 unsigned specifierLen) { 8732 EmitFormatDiagnostic( 8733 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8734 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8735 } 8736 8737 bool 8738 CheckFormatHandler::CheckNumArgs( 8739 const analyze_format_string::FormatSpecifier &FS, 8740 const analyze_format_string::ConversionSpecifier &CS, 8741 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8742 8743 if (argIndex >= NumDataArgs) { 8744 PartialDiagnostic PDiag = FS.usesPositionalArg() 8745 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8746 << (argIndex+1) << NumDataArgs) 8747 : S.PDiag(diag::warn_printf_insufficient_data_args); 8748 EmitFormatDiagnostic( 8749 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8750 getSpecifierRange(startSpecifier, specifierLen)); 8751 8752 // Since more arguments than conversion tokens are given, by extension 8753 // all arguments are covered, so mark this as so. 8754 UncoveredArg.setAllCovered(); 8755 return false; 8756 } 8757 return true; 8758 } 8759 8760 template<typename Range> 8761 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8762 SourceLocation Loc, 8763 bool IsStringLocation, 8764 Range StringRange, 8765 ArrayRef<FixItHint> FixIt) { 8766 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8767 Loc, IsStringLocation, StringRange, FixIt); 8768 } 8769 8770 /// If the format string is not within the function call, emit a note 8771 /// so that the function call and string are in diagnostic messages. 8772 /// 8773 /// \param InFunctionCall if true, the format string is within the function 8774 /// call and only one diagnostic message will be produced. Otherwise, an 8775 /// extra note will be emitted pointing to location of the format string. 8776 /// 8777 /// \param ArgumentExpr the expression that is passed as the format string 8778 /// argument in the function call. Used for getting locations when two 8779 /// diagnostics are emitted. 8780 /// 8781 /// \param PDiag the callee should already have provided any strings for the 8782 /// diagnostic message. This function only adds locations and fixits 8783 /// to diagnostics. 8784 /// 8785 /// \param Loc primary location for diagnostic. If two diagnostics are 8786 /// required, one will be at Loc and a new SourceLocation will be created for 8787 /// the other one. 8788 /// 8789 /// \param IsStringLocation if true, Loc points to the format string should be 8790 /// used for the note. Otherwise, Loc points to the argument list and will 8791 /// be used with PDiag. 8792 /// 8793 /// \param StringRange some or all of the string to highlight. This is 8794 /// templated so it can accept either a CharSourceRange or a SourceRange. 8795 /// 8796 /// \param FixIt optional fix it hint for the format string. 8797 template <typename Range> 8798 void CheckFormatHandler::EmitFormatDiagnostic( 8799 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8800 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8801 Range StringRange, ArrayRef<FixItHint> FixIt) { 8802 if (InFunctionCall) { 8803 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8804 D << StringRange; 8805 D << FixIt; 8806 } else { 8807 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8808 << ArgumentExpr->getSourceRange(); 8809 8810 const Sema::SemaDiagnosticBuilder &Note = 8811 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8812 diag::note_format_string_defined); 8813 8814 Note << StringRange; 8815 Note << FixIt; 8816 } 8817 } 8818 8819 //===--- CHECK: Printf format string checking ------------------------------===// 8820 8821 namespace { 8822 8823 class CheckPrintfHandler : public CheckFormatHandler { 8824 public: 8825 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8826 const Expr *origFormatExpr, 8827 const Sema::FormatStringType type, unsigned firstDataArg, 8828 unsigned numDataArgs, bool isObjC, const char *beg, 8829 bool hasVAListArg, ArrayRef<const Expr *> Args, 8830 unsigned formatIdx, bool inFunctionCall, 8831 Sema::VariadicCallType CallType, 8832 llvm::SmallBitVector &CheckedVarArgs, 8833 UncoveredArgHandler &UncoveredArg) 8834 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8835 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8836 inFunctionCall, CallType, CheckedVarArgs, 8837 UncoveredArg) {} 8838 8839 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8840 8841 /// Returns true if '%@' specifiers are allowed in the format string. 8842 bool allowsObjCArg() const { 8843 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8844 FSType == Sema::FST_OSTrace; 8845 } 8846 8847 bool HandleInvalidPrintfConversionSpecifier( 8848 const analyze_printf::PrintfSpecifier &FS, 8849 const char *startSpecifier, 8850 unsigned specifierLen) override; 8851 8852 void handleInvalidMaskType(StringRef MaskType) override; 8853 8854 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8855 const char *startSpecifier, 8856 unsigned specifierLen) override; 8857 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8858 const char *StartSpecifier, 8859 unsigned SpecifierLen, 8860 const Expr *E); 8861 8862 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8863 const char *startSpecifier, unsigned specifierLen); 8864 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8865 const analyze_printf::OptionalAmount &Amt, 8866 unsigned type, 8867 const char *startSpecifier, unsigned specifierLen); 8868 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8869 const analyze_printf::OptionalFlag &flag, 8870 const char *startSpecifier, unsigned specifierLen); 8871 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8872 const analyze_printf::OptionalFlag &ignoredFlag, 8873 const analyze_printf::OptionalFlag &flag, 8874 const char *startSpecifier, unsigned specifierLen); 8875 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8876 const Expr *E); 8877 8878 void HandleEmptyObjCModifierFlag(const char *startFlag, 8879 unsigned flagLen) override; 8880 8881 void HandleInvalidObjCModifierFlag(const char *startFlag, 8882 unsigned flagLen) override; 8883 8884 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8885 const char *flagsEnd, 8886 const char *conversionPosition) 8887 override; 8888 }; 8889 8890 } // namespace 8891 8892 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8893 const analyze_printf::PrintfSpecifier &FS, 8894 const char *startSpecifier, 8895 unsigned specifierLen) { 8896 const analyze_printf::PrintfConversionSpecifier &CS = 8897 FS.getConversionSpecifier(); 8898 8899 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8900 getLocationOfByte(CS.getStart()), 8901 startSpecifier, specifierLen, 8902 CS.getStart(), CS.getLength()); 8903 } 8904 8905 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8906 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8907 } 8908 8909 bool CheckPrintfHandler::HandleAmount( 8910 const analyze_format_string::OptionalAmount &Amt, 8911 unsigned k, const char *startSpecifier, 8912 unsigned specifierLen) { 8913 if (Amt.hasDataArgument()) { 8914 if (!HasVAListArg) { 8915 unsigned argIndex = Amt.getArgIndex(); 8916 if (argIndex >= NumDataArgs) { 8917 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8918 << k, 8919 getLocationOfByte(Amt.getStart()), 8920 /*IsStringLocation*/true, 8921 getSpecifierRange(startSpecifier, specifierLen)); 8922 // Don't do any more checking. We will just emit 8923 // spurious errors. 8924 return false; 8925 } 8926 8927 // Type check the data argument. It should be an 'int'. 8928 // Although not in conformance with C99, we also allow the argument to be 8929 // an 'unsigned int' as that is a reasonably safe case. GCC also 8930 // doesn't emit a warning for that case. 8931 CoveredArgs.set(argIndex); 8932 const Expr *Arg = getDataArg(argIndex); 8933 if (!Arg) 8934 return false; 8935 8936 QualType T = Arg->getType(); 8937 8938 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8939 assert(AT.isValid()); 8940 8941 if (!AT.matchesType(S.Context, T)) { 8942 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8943 << k << AT.getRepresentativeTypeName(S.Context) 8944 << T << Arg->getSourceRange(), 8945 getLocationOfByte(Amt.getStart()), 8946 /*IsStringLocation*/true, 8947 getSpecifierRange(startSpecifier, specifierLen)); 8948 // Don't do any more checking. We will just emit 8949 // spurious errors. 8950 return false; 8951 } 8952 } 8953 } 8954 return true; 8955 } 8956 8957 void CheckPrintfHandler::HandleInvalidAmount( 8958 const analyze_printf::PrintfSpecifier &FS, 8959 const analyze_printf::OptionalAmount &Amt, 8960 unsigned type, 8961 const char *startSpecifier, 8962 unsigned specifierLen) { 8963 const analyze_printf::PrintfConversionSpecifier &CS = 8964 FS.getConversionSpecifier(); 8965 8966 FixItHint fixit = 8967 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8968 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8969 Amt.getConstantLength())) 8970 : FixItHint(); 8971 8972 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8973 << type << CS.toString(), 8974 getLocationOfByte(Amt.getStart()), 8975 /*IsStringLocation*/true, 8976 getSpecifierRange(startSpecifier, specifierLen), 8977 fixit); 8978 } 8979 8980 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8981 const analyze_printf::OptionalFlag &flag, 8982 const char *startSpecifier, 8983 unsigned specifierLen) { 8984 // Warn about pointless flag with a fixit removal. 8985 const analyze_printf::PrintfConversionSpecifier &CS = 8986 FS.getConversionSpecifier(); 8987 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8988 << flag.toString() << CS.toString(), 8989 getLocationOfByte(flag.getPosition()), 8990 /*IsStringLocation*/true, 8991 getSpecifierRange(startSpecifier, specifierLen), 8992 FixItHint::CreateRemoval( 8993 getSpecifierRange(flag.getPosition(), 1))); 8994 } 8995 8996 void CheckPrintfHandler::HandleIgnoredFlag( 8997 const analyze_printf::PrintfSpecifier &FS, 8998 const analyze_printf::OptionalFlag &ignoredFlag, 8999 const analyze_printf::OptionalFlag &flag, 9000 const char *startSpecifier, 9001 unsigned specifierLen) { 9002 // Warn about ignored flag with a fixit removal. 9003 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 9004 << ignoredFlag.toString() << flag.toString(), 9005 getLocationOfByte(ignoredFlag.getPosition()), 9006 /*IsStringLocation*/true, 9007 getSpecifierRange(startSpecifier, specifierLen), 9008 FixItHint::CreateRemoval( 9009 getSpecifierRange(ignoredFlag.getPosition(), 1))); 9010 } 9011 9012 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 9013 unsigned flagLen) { 9014 // Warn about an empty flag. 9015 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 9016 getLocationOfByte(startFlag), 9017 /*IsStringLocation*/true, 9018 getSpecifierRange(startFlag, flagLen)); 9019 } 9020 9021 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 9022 unsigned flagLen) { 9023 // Warn about an invalid flag. 9024 auto Range = getSpecifierRange(startFlag, flagLen); 9025 StringRef flag(startFlag, flagLen); 9026 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 9027 getLocationOfByte(startFlag), 9028 /*IsStringLocation*/true, 9029 Range, FixItHint::CreateRemoval(Range)); 9030 } 9031 9032 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 9033 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 9034 // Warn about using '[...]' without a '@' conversion. 9035 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 9036 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 9037 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 9038 getLocationOfByte(conversionPosition), 9039 /*IsStringLocation*/true, 9040 Range, FixItHint::CreateRemoval(Range)); 9041 } 9042 9043 // Determines if the specified is a C++ class or struct containing 9044 // a member with the specified name and kind (e.g. a CXXMethodDecl named 9045 // "c_str()"). 9046 template<typename MemberKind> 9047 static llvm::SmallPtrSet<MemberKind*, 1> 9048 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 9049 const RecordType *RT = Ty->getAs<RecordType>(); 9050 llvm::SmallPtrSet<MemberKind*, 1> Results; 9051 9052 if (!RT) 9053 return Results; 9054 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 9055 if (!RD || !RD->getDefinition()) 9056 return Results; 9057 9058 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 9059 Sema::LookupMemberName); 9060 R.suppressDiagnostics(); 9061 9062 // We just need to include all members of the right kind turned up by the 9063 // filter, at this point. 9064 if (S.LookupQualifiedName(R, RT->getDecl())) 9065 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9066 NamedDecl *decl = (*I)->getUnderlyingDecl(); 9067 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 9068 Results.insert(FK); 9069 } 9070 return Results; 9071 } 9072 9073 /// Check if we could call '.c_str()' on an object. 9074 /// 9075 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 9076 /// allow the call, or if it would be ambiguous). 9077 bool Sema::hasCStrMethod(const Expr *E) { 9078 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 9079 9080 MethodSet Results = 9081 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 9082 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 9083 MI != ME; ++MI) 9084 if ((*MI)->getMinRequiredArguments() == 0) 9085 return true; 9086 return false; 9087 } 9088 9089 // Check if a (w)string was passed when a (w)char* was needed, and offer a 9090 // better diagnostic if so. AT is assumed to be valid. 9091 // Returns true when a c_str() conversion method is found. 9092 bool CheckPrintfHandler::checkForCStrMembers( 9093 const analyze_printf::ArgType &AT, const Expr *E) { 9094 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 9095 9096 MethodSet Results = 9097 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 9098 9099 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 9100 MI != ME; ++MI) { 9101 const CXXMethodDecl *Method = *MI; 9102 if (Method->getMinRequiredArguments() == 0 && 9103 AT.matchesType(S.Context, Method->getReturnType())) { 9104 // FIXME: Suggest parens if the expression needs them. 9105 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 9106 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 9107 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 9108 return true; 9109 } 9110 } 9111 9112 return false; 9113 } 9114 9115 bool 9116 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 9117 &FS, 9118 const char *startSpecifier, 9119 unsigned specifierLen) { 9120 using namespace analyze_format_string; 9121 using namespace analyze_printf; 9122 9123 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 9124 9125 if (FS.consumesDataArgument()) { 9126 if (atFirstArg) { 9127 atFirstArg = false; 9128 usesPositionalArgs = FS.usesPositionalArg(); 9129 } 9130 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9131 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9132 startSpecifier, specifierLen); 9133 return false; 9134 } 9135 } 9136 9137 // First check if the field width, precision, and conversion specifier 9138 // have matching data arguments. 9139 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 9140 startSpecifier, specifierLen)) { 9141 return false; 9142 } 9143 9144 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 9145 startSpecifier, specifierLen)) { 9146 return false; 9147 } 9148 9149 if (!CS.consumesDataArgument()) { 9150 // FIXME: Technically specifying a precision or field width here 9151 // makes no sense. Worth issuing a warning at some point. 9152 return true; 9153 } 9154 9155 // Consume the argument. 9156 unsigned argIndex = FS.getArgIndex(); 9157 if (argIndex < NumDataArgs) { 9158 // The check to see if the argIndex is valid will come later. 9159 // We set the bit here because we may exit early from this 9160 // function if we encounter some other error. 9161 CoveredArgs.set(argIndex); 9162 } 9163 9164 // FreeBSD kernel extensions. 9165 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 9166 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 9167 // We need at least two arguments. 9168 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 9169 return false; 9170 9171 // Claim the second argument. 9172 CoveredArgs.set(argIndex + 1); 9173 9174 // Type check the first argument (int for %b, pointer for %D) 9175 const Expr *Ex = getDataArg(argIndex); 9176 const analyze_printf::ArgType &AT = 9177 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 9178 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 9179 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 9180 EmitFormatDiagnostic( 9181 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9182 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 9183 << false << Ex->getSourceRange(), 9184 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9185 getSpecifierRange(startSpecifier, specifierLen)); 9186 9187 // Type check the second argument (char * for both %b and %D) 9188 Ex = getDataArg(argIndex + 1); 9189 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 9190 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 9191 EmitFormatDiagnostic( 9192 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9193 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 9194 << false << Ex->getSourceRange(), 9195 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9196 getSpecifierRange(startSpecifier, specifierLen)); 9197 9198 return true; 9199 } 9200 9201 // Check for using an Objective-C specific conversion specifier 9202 // in a non-ObjC literal. 9203 if (!allowsObjCArg() && CS.isObjCArg()) { 9204 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9205 specifierLen); 9206 } 9207 9208 // %P can only be used with os_log. 9209 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 9210 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9211 specifierLen); 9212 } 9213 9214 // %n is not allowed with os_log. 9215 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 9216 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 9217 getLocationOfByte(CS.getStart()), 9218 /*IsStringLocation*/ false, 9219 getSpecifierRange(startSpecifier, specifierLen)); 9220 9221 return true; 9222 } 9223 9224 // Only scalars are allowed for os_trace. 9225 if (FSType == Sema::FST_OSTrace && 9226 (CS.getKind() == ConversionSpecifier::PArg || 9227 CS.getKind() == ConversionSpecifier::sArg || 9228 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 9229 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9230 specifierLen); 9231 } 9232 9233 // Check for use of public/private annotation outside of os_log(). 9234 if (FSType != Sema::FST_OSLog) { 9235 if (FS.isPublic().isSet()) { 9236 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9237 << "public", 9238 getLocationOfByte(FS.isPublic().getPosition()), 9239 /*IsStringLocation*/ false, 9240 getSpecifierRange(startSpecifier, specifierLen)); 9241 } 9242 if (FS.isPrivate().isSet()) { 9243 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9244 << "private", 9245 getLocationOfByte(FS.isPrivate().getPosition()), 9246 /*IsStringLocation*/ false, 9247 getSpecifierRange(startSpecifier, specifierLen)); 9248 } 9249 } 9250 9251 // Check for invalid use of field width 9252 if (!FS.hasValidFieldWidth()) { 9253 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 9254 startSpecifier, specifierLen); 9255 } 9256 9257 // Check for invalid use of precision 9258 if (!FS.hasValidPrecision()) { 9259 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 9260 startSpecifier, specifierLen); 9261 } 9262 9263 // Precision is mandatory for %P specifier. 9264 if (CS.getKind() == ConversionSpecifier::PArg && 9265 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 9266 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 9267 getLocationOfByte(startSpecifier), 9268 /*IsStringLocation*/ false, 9269 getSpecifierRange(startSpecifier, specifierLen)); 9270 } 9271 9272 // Check each flag does not conflict with any other component. 9273 if (!FS.hasValidThousandsGroupingPrefix()) 9274 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 9275 if (!FS.hasValidLeadingZeros()) 9276 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 9277 if (!FS.hasValidPlusPrefix()) 9278 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 9279 if (!FS.hasValidSpacePrefix()) 9280 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 9281 if (!FS.hasValidAlternativeForm()) 9282 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 9283 if (!FS.hasValidLeftJustified()) 9284 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 9285 9286 // Check that flags are not ignored by another flag 9287 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 9288 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 9289 startSpecifier, specifierLen); 9290 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 9291 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 9292 startSpecifier, specifierLen); 9293 9294 // Check the length modifier is valid with the given conversion specifier. 9295 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9296 S.getLangOpts())) 9297 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9298 diag::warn_format_nonsensical_length); 9299 else if (!FS.hasStandardLengthModifier()) 9300 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9301 else if (!FS.hasStandardLengthConversionCombination()) 9302 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9303 diag::warn_format_non_standard_conversion_spec); 9304 9305 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9306 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9307 9308 // The remaining checks depend on the data arguments. 9309 if (HasVAListArg) 9310 return true; 9311 9312 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9313 return false; 9314 9315 const Expr *Arg = getDataArg(argIndex); 9316 if (!Arg) 9317 return true; 9318 9319 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 9320 } 9321 9322 static bool requiresParensToAddCast(const Expr *E) { 9323 // FIXME: We should have a general way to reason about operator 9324 // precedence and whether parens are actually needed here. 9325 // Take care of a few common cases where they aren't. 9326 const Expr *Inside = E->IgnoreImpCasts(); 9327 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 9328 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 9329 9330 switch (Inside->getStmtClass()) { 9331 case Stmt::ArraySubscriptExprClass: 9332 case Stmt::CallExprClass: 9333 case Stmt::CharacterLiteralClass: 9334 case Stmt::CXXBoolLiteralExprClass: 9335 case Stmt::DeclRefExprClass: 9336 case Stmt::FloatingLiteralClass: 9337 case Stmt::IntegerLiteralClass: 9338 case Stmt::MemberExprClass: 9339 case Stmt::ObjCArrayLiteralClass: 9340 case Stmt::ObjCBoolLiteralExprClass: 9341 case Stmt::ObjCBoxedExprClass: 9342 case Stmt::ObjCDictionaryLiteralClass: 9343 case Stmt::ObjCEncodeExprClass: 9344 case Stmt::ObjCIvarRefExprClass: 9345 case Stmt::ObjCMessageExprClass: 9346 case Stmt::ObjCPropertyRefExprClass: 9347 case Stmt::ObjCStringLiteralClass: 9348 case Stmt::ObjCSubscriptRefExprClass: 9349 case Stmt::ParenExprClass: 9350 case Stmt::StringLiteralClass: 9351 case Stmt::UnaryOperatorClass: 9352 return false; 9353 default: 9354 return true; 9355 } 9356 } 9357 9358 static std::pair<QualType, StringRef> 9359 shouldNotPrintDirectly(const ASTContext &Context, 9360 QualType IntendedTy, 9361 const Expr *E) { 9362 // Use a 'while' to peel off layers of typedefs. 9363 QualType TyTy = IntendedTy; 9364 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 9365 StringRef Name = UserTy->getDecl()->getName(); 9366 QualType CastTy = llvm::StringSwitch<QualType>(Name) 9367 .Case("CFIndex", Context.getNSIntegerType()) 9368 .Case("NSInteger", Context.getNSIntegerType()) 9369 .Case("NSUInteger", Context.getNSUIntegerType()) 9370 .Case("SInt32", Context.IntTy) 9371 .Case("UInt32", Context.UnsignedIntTy) 9372 .Default(QualType()); 9373 9374 if (!CastTy.isNull()) 9375 return std::make_pair(CastTy, Name); 9376 9377 TyTy = UserTy->desugar(); 9378 } 9379 9380 // Strip parens if necessary. 9381 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 9382 return shouldNotPrintDirectly(Context, 9383 PE->getSubExpr()->getType(), 9384 PE->getSubExpr()); 9385 9386 // If this is a conditional expression, then its result type is constructed 9387 // via usual arithmetic conversions and thus there might be no necessary 9388 // typedef sugar there. Recurse to operands to check for NSInteger & 9389 // Co. usage condition. 9390 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9391 QualType TrueTy, FalseTy; 9392 StringRef TrueName, FalseName; 9393 9394 std::tie(TrueTy, TrueName) = 9395 shouldNotPrintDirectly(Context, 9396 CO->getTrueExpr()->getType(), 9397 CO->getTrueExpr()); 9398 std::tie(FalseTy, FalseName) = 9399 shouldNotPrintDirectly(Context, 9400 CO->getFalseExpr()->getType(), 9401 CO->getFalseExpr()); 9402 9403 if (TrueTy == FalseTy) 9404 return std::make_pair(TrueTy, TrueName); 9405 else if (TrueTy.isNull()) 9406 return std::make_pair(FalseTy, FalseName); 9407 else if (FalseTy.isNull()) 9408 return std::make_pair(TrueTy, TrueName); 9409 } 9410 9411 return std::make_pair(QualType(), StringRef()); 9412 } 9413 9414 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9415 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9416 /// type do not count. 9417 static bool 9418 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9419 QualType From = ICE->getSubExpr()->getType(); 9420 QualType To = ICE->getType(); 9421 // It's an integer promotion if the destination type is the promoted 9422 // source type. 9423 if (ICE->getCastKind() == CK_IntegralCast && 9424 From->isPromotableIntegerType() && 9425 S.Context.getPromotedIntegerType(From) == To) 9426 return true; 9427 // Look through vector types, since we do default argument promotion for 9428 // those in OpenCL. 9429 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9430 From = VecTy->getElementType(); 9431 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9432 To = VecTy->getElementType(); 9433 // It's a floating promotion if the source type is a lower rank. 9434 return ICE->getCastKind() == CK_FloatingCast && 9435 S.Context.getFloatingTypeOrder(From, To) < 0; 9436 } 9437 9438 bool 9439 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9440 const char *StartSpecifier, 9441 unsigned SpecifierLen, 9442 const Expr *E) { 9443 using namespace analyze_format_string; 9444 using namespace analyze_printf; 9445 9446 // Now type check the data expression that matches the 9447 // format specifier. 9448 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9449 if (!AT.isValid()) 9450 return true; 9451 9452 QualType ExprTy = E->getType(); 9453 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9454 ExprTy = TET->getUnderlyingExpr()->getType(); 9455 } 9456 9457 // Diagnose attempts to print a boolean value as a character. Unlike other 9458 // -Wformat diagnostics, this is fine from a type perspective, but it still 9459 // doesn't make sense. 9460 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9461 E->isKnownToHaveBooleanValue()) { 9462 const CharSourceRange &CSR = 9463 getSpecifierRange(StartSpecifier, SpecifierLen); 9464 SmallString<4> FSString; 9465 llvm::raw_svector_ostream os(FSString); 9466 FS.toString(os); 9467 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9468 << FSString, 9469 E->getExprLoc(), false, CSR); 9470 return true; 9471 } 9472 9473 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9474 if (Match == analyze_printf::ArgType::Match) 9475 return true; 9476 9477 // Look through argument promotions for our error message's reported type. 9478 // This includes the integral and floating promotions, but excludes array 9479 // and function pointer decay (seeing that an argument intended to be a 9480 // string has type 'char [6]' is probably more confusing than 'char *') and 9481 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9482 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9483 if (isArithmeticArgumentPromotion(S, ICE)) { 9484 E = ICE->getSubExpr(); 9485 ExprTy = E->getType(); 9486 9487 // Check if we didn't match because of an implicit cast from a 'char' 9488 // or 'short' to an 'int'. This is done because printf is a varargs 9489 // function. 9490 if (ICE->getType() == S.Context.IntTy || 9491 ICE->getType() == S.Context.UnsignedIntTy) { 9492 // All further checking is done on the subexpression 9493 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9494 AT.matchesType(S.Context, ExprTy); 9495 if (ImplicitMatch == analyze_printf::ArgType::Match) 9496 return true; 9497 if (ImplicitMatch == ArgType::NoMatchPedantic || 9498 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9499 Match = ImplicitMatch; 9500 } 9501 } 9502 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9503 // Special case for 'a', which has type 'int' in C. 9504 // Note, however, that we do /not/ want to treat multibyte constants like 9505 // 'MooV' as characters! This form is deprecated but still exists. In 9506 // addition, don't treat expressions as of type 'char' if one byte length 9507 // modifier is provided. 9508 if (ExprTy == S.Context.IntTy && 9509 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9510 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9511 ExprTy = S.Context.CharTy; 9512 } 9513 9514 // Look through enums to their underlying type. 9515 bool IsEnum = false; 9516 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9517 ExprTy = EnumTy->getDecl()->getIntegerType(); 9518 IsEnum = true; 9519 } 9520 9521 // %C in an Objective-C context prints a unichar, not a wchar_t. 9522 // If the argument is an integer of some kind, believe the %C and suggest 9523 // a cast instead of changing the conversion specifier. 9524 QualType IntendedTy = ExprTy; 9525 if (isObjCContext() && 9526 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9527 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9528 !ExprTy->isCharType()) { 9529 // 'unichar' is defined as a typedef of unsigned short, but we should 9530 // prefer using the typedef if it is visible. 9531 IntendedTy = S.Context.UnsignedShortTy; 9532 9533 // While we are here, check if the value is an IntegerLiteral that happens 9534 // to be within the valid range. 9535 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9536 const llvm::APInt &V = IL->getValue(); 9537 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9538 return true; 9539 } 9540 9541 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9542 Sema::LookupOrdinaryName); 9543 if (S.LookupName(Result, S.getCurScope())) { 9544 NamedDecl *ND = Result.getFoundDecl(); 9545 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9546 if (TD->getUnderlyingType() == IntendedTy) 9547 IntendedTy = S.Context.getTypedefType(TD); 9548 } 9549 } 9550 } 9551 9552 // Special-case some of Darwin's platform-independence types by suggesting 9553 // casts to primitive types that are known to be large enough. 9554 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9555 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9556 QualType CastTy; 9557 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9558 if (!CastTy.isNull()) { 9559 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9560 // (long in ASTContext). Only complain to pedants. 9561 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9562 (AT.isSizeT() || AT.isPtrdiffT()) && 9563 AT.matchesType(S.Context, CastTy)) 9564 Match = ArgType::NoMatchPedantic; 9565 IntendedTy = CastTy; 9566 ShouldNotPrintDirectly = true; 9567 } 9568 } 9569 9570 // We may be able to offer a FixItHint if it is a supported type. 9571 PrintfSpecifier fixedFS = FS; 9572 bool Success = 9573 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9574 9575 if (Success) { 9576 // Get the fix string from the fixed format specifier 9577 SmallString<16> buf; 9578 llvm::raw_svector_ostream os(buf); 9579 fixedFS.toString(os); 9580 9581 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9582 9583 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9584 unsigned Diag; 9585 switch (Match) { 9586 case ArgType::Match: llvm_unreachable("expected non-matching"); 9587 case ArgType::NoMatchPedantic: 9588 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9589 break; 9590 case ArgType::NoMatchTypeConfusion: 9591 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9592 break; 9593 case ArgType::NoMatch: 9594 Diag = diag::warn_format_conversion_argument_type_mismatch; 9595 break; 9596 } 9597 9598 // In this case, the specifier is wrong and should be changed to match 9599 // the argument. 9600 EmitFormatDiagnostic(S.PDiag(Diag) 9601 << AT.getRepresentativeTypeName(S.Context) 9602 << IntendedTy << IsEnum << E->getSourceRange(), 9603 E->getBeginLoc(), 9604 /*IsStringLocation*/ false, SpecRange, 9605 FixItHint::CreateReplacement(SpecRange, os.str())); 9606 } else { 9607 // The canonical type for formatting this value is different from the 9608 // actual type of the expression. (This occurs, for example, with Darwin's 9609 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9610 // should be printed as 'long' for 64-bit compatibility.) 9611 // Rather than emitting a normal format/argument mismatch, we want to 9612 // add a cast to the recommended type (and correct the format string 9613 // if necessary). 9614 SmallString<16> CastBuf; 9615 llvm::raw_svector_ostream CastFix(CastBuf); 9616 CastFix << "("; 9617 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9618 CastFix << ")"; 9619 9620 SmallVector<FixItHint,4> Hints; 9621 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9622 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9623 9624 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9625 // If there's already a cast present, just replace it. 9626 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9627 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9628 9629 } else if (!requiresParensToAddCast(E)) { 9630 // If the expression has high enough precedence, 9631 // just write the C-style cast. 9632 Hints.push_back( 9633 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9634 } else { 9635 // Otherwise, add parens around the expression as well as the cast. 9636 CastFix << "("; 9637 Hints.push_back( 9638 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9639 9640 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9641 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9642 } 9643 9644 if (ShouldNotPrintDirectly) { 9645 // The expression has a type that should not be printed directly. 9646 // We extract the name from the typedef because we don't want to show 9647 // the underlying type in the diagnostic. 9648 StringRef Name; 9649 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9650 Name = TypedefTy->getDecl()->getName(); 9651 else 9652 Name = CastTyName; 9653 unsigned Diag = Match == ArgType::NoMatchPedantic 9654 ? diag::warn_format_argument_needs_cast_pedantic 9655 : diag::warn_format_argument_needs_cast; 9656 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9657 << E->getSourceRange(), 9658 E->getBeginLoc(), /*IsStringLocation=*/false, 9659 SpecRange, Hints); 9660 } else { 9661 // In this case, the expression could be printed using a different 9662 // specifier, but we've decided that the specifier is probably correct 9663 // and we should cast instead. Just use the normal warning message. 9664 EmitFormatDiagnostic( 9665 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9666 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9667 << E->getSourceRange(), 9668 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9669 } 9670 } 9671 } else { 9672 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9673 SpecifierLen); 9674 // Since the warning for passing non-POD types to variadic functions 9675 // was deferred until now, we emit a warning for non-POD 9676 // arguments here. 9677 switch (S.isValidVarArgType(ExprTy)) { 9678 case Sema::VAK_Valid: 9679 case Sema::VAK_ValidInCXX11: { 9680 unsigned Diag; 9681 switch (Match) { 9682 case ArgType::Match: llvm_unreachable("expected non-matching"); 9683 case ArgType::NoMatchPedantic: 9684 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9685 break; 9686 case ArgType::NoMatchTypeConfusion: 9687 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9688 break; 9689 case ArgType::NoMatch: 9690 Diag = diag::warn_format_conversion_argument_type_mismatch; 9691 break; 9692 } 9693 9694 EmitFormatDiagnostic( 9695 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9696 << IsEnum << CSR << E->getSourceRange(), 9697 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9698 break; 9699 } 9700 case Sema::VAK_Undefined: 9701 case Sema::VAK_MSVCUndefined: 9702 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9703 << S.getLangOpts().CPlusPlus11 << ExprTy 9704 << CallType 9705 << AT.getRepresentativeTypeName(S.Context) << CSR 9706 << E->getSourceRange(), 9707 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9708 checkForCStrMembers(AT, E); 9709 break; 9710 9711 case Sema::VAK_Invalid: 9712 if (ExprTy->isObjCObjectType()) 9713 EmitFormatDiagnostic( 9714 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9715 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9716 << AT.getRepresentativeTypeName(S.Context) << CSR 9717 << E->getSourceRange(), 9718 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9719 else 9720 // FIXME: If this is an initializer list, suggest removing the braces 9721 // or inserting a cast to the target type. 9722 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9723 << isa<InitListExpr>(E) << ExprTy << CallType 9724 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9725 break; 9726 } 9727 9728 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9729 "format string specifier index out of range"); 9730 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9731 } 9732 9733 return true; 9734 } 9735 9736 //===--- CHECK: Scanf format string checking ------------------------------===// 9737 9738 namespace { 9739 9740 class CheckScanfHandler : public CheckFormatHandler { 9741 public: 9742 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9743 const Expr *origFormatExpr, Sema::FormatStringType type, 9744 unsigned firstDataArg, unsigned numDataArgs, 9745 const char *beg, bool hasVAListArg, 9746 ArrayRef<const Expr *> Args, unsigned formatIdx, 9747 bool inFunctionCall, Sema::VariadicCallType CallType, 9748 llvm::SmallBitVector &CheckedVarArgs, 9749 UncoveredArgHandler &UncoveredArg) 9750 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9751 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9752 inFunctionCall, CallType, CheckedVarArgs, 9753 UncoveredArg) {} 9754 9755 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9756 const char *startSpecifier, 9757 unsigned specifierLen) override; 9758 9759 bool HandleInvalidScanfConversionSpecifier( 9760 const analyze_scanf::ScanfSpecifier &FS, 9761 const char *startSpecifier, 9762 unsigned specifierLen) override; 9763 9764 void HandleIncompleteScanList(const char *start, const char *end) override; 9765 }; 9766 9767 } // namespace 9768 9769 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9770 const char *end) { 9771 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9772 getLocationOfByte(end), /*IsStringLocation*/true, 9773 getSpecifierRange(start, end - start)); 9774 } 9775 9776 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9777 const analyze_scanf::ScanfSpecifier &FS, 9778 const char *startSpecifier, 9779 unsigned specifierLen) { 9780 const analyze_scanf::ScanfConversionSpecifier &CS = 9781 FS.getConversionSpecifier(); 9782 9783 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9784 getLocationOfByte(CS.getStart()), 9785 startSpecifier, specifierLen, 9786 CS.getStart(), CS.getLength()); 9787 } 9788 9789 bool CheckScanfHandler::HandleScanfSpecifier( 9790 const analyze_scanf::ScanfSpecifier &FS, 9791 const char *startSpecifier, 9792 unsigned specifierLen) { 9793 using namespace analyze_scanf; 9794 using namespace analyze_format_string; 9795 9796 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9797 9798 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9799 // be used to decide if we are using positional arguments consistently. 9800 if (FS.consumesDataArgument()) { 9801 if (atFirstArg) { 9802 atFirstArg = false; 9803 usesPositionalArgs = FS.usesPositionalArg(); 9804 } 9805 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9806 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9807 startSpecifier, specifierLen); 9808 return false; 9809 } 9810 } 9811 9812 // Check if the field with is non-zero. 9813 const OptionalAmount &Amt = FS.getFieldWidth(); 9814 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9815 if (Amt.getConstantAmount() == 0) { 9816 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9817 Amt.getConstantLength()); 9818 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9819 getLocationOfByte(Amt.getStart()), 9820 /*IsStringLocation*/true, R, 9821 FixItHint::CreateRemoval(R)); 9822 } 9823 } 9824 9825 if (!FS.consumesDataArgument()) { 9826 // FIXME: Technically specifying a precision or field width here 9827 // makes no sense. Worth issuing a warning at some point. 9828 return true; 9829 } 9830 9831 // Consume the argument. 9832 unsigned argIndex = FS.getArgIndex(); 9833 if (argIndex < NumDataArgs) { 9834 // The check to see if the argIndex is valid will come later. 9835 // We set the bit here because we may exit early from this 9836 // function if we encounter some other error. 9837 CoveredArgs.set(argIndex); 9838 } 9839 9840 // Check the length modifier is valid with the given conversion specifier. 9841 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9842 S.getLangOpts())) 9843 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9844 diag::warn_format_nonsensical_length); 9845 else if (!FS.hasStandardLengthModifier()) 9846 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9847 else if (!FS.hasStandardLengthConversionCombination()) 9848 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9849 diag::warn_format_non_standard_conversion_spec); 9850 9851 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9852 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9853 9854 // The remaining checks depend on the data arguments. 9855 if (HasVAListArg) 9856 return true; 9857 9858 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9859 return false; 9860 9861 // Check that the argument type matches the format specifier. 9862 const Expr *Ex = getDataArg(argIndex); 9863 if (!Ex) 9864 return true; 9865 9866 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9867 9868 if (!AT.isValid()) { 9869 return true; 9870 } 9871 9872 analyze_format_string::ArgType::MatchKind Match = 9873 AT.matchesType(S.Context, Ex->getType()); 9874 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9875 if (Match == analyze_format_string::ArgType::Match) 9876 return true; 9877 9878 ScanfSpecifier fixedFS = FS; 9879 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9880 S.getLangOpts(), S.Context); 9881 9882 unsigned Diag = 9883 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9884 : diag::warn_format_conversion_argument_type_mismatch; 9885 9886 if (Success) { 9887 // Get the fix string from the fixed format specifier. 9888 SmallString<128> buf; 9889 llvm::raw_svector_ostream os(buf); 9890 fixedFS.toString(os); 9891 9892 EmitFormatDiagnostic( 9893 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9894 << Ex->getType() << false << Ex->getSourceRange(), 9895 Ex->getBeginLoc(), 9896 /*IsStringLocation*/ false, 9897 getSpecifierRange(startSpecifier, specifierLen), 9898 FixItHint::CreateReplacement( 9899 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9900 } else { 9901 EmitFormatDiagnostic(S.PDiag(Diag) 9902 << AT.getRepresentativeTypeName(S.Context) 9903 << Ex->getType() << false << Ex->getSourceRange(), 9904 Ex->getBeginLoc(), 9905 /*IsStringLocation*/ false, 9906 getSpecifierRange(startSpecifier, specifierLen)); 9907 } 9908 9909 return true; 9910 } 9911 9912 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9913 const Expr *OrigFormatExpr, 9914 ArrayRef<const Expr *> Args, 9915 bool HasVAListArg, unsigned format_idx, 9916 unsigned firstDataArg, 9917 Sema::FormatStringType Type, 9918 bool inFunctionCall, 9919 Sema::VariadicCallType CallType, 9920 llvm::SmallBitVector &CheckedVarArgs, 9921 UncoveredArgHandler &UncoveredArg, 9922 bool IgnoreStringsWithoutSpecifiers) { 9923 // CHECK: is the format string a wide literal? 9924 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9925 CheckFormatHandler::EmitFormatDiagnostic( 9926 S, inFunctionCall, Args[format_idx], 9927 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9928 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9929 return; 9930 } 9931 9932 // Str - The format string. NOTE: this is NOT null-terminated! 9933 StringRef StrRef = FExpr->getString(); 9934 const char *Str = StrRef.data(); 9935 // Account for cases where the string literal is truncated in a declaration. 9936 const ConstantArrayType *T = 9937 S.Context.getAsConstantArrayType(FExpr->getType()); 9938 assert(T && "String literal not of constant array type!"); 9939 size_t TypeSize = T->getSize().getZExtValue(); 9940 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9941 const unsigned numDataArgs = Args.size() - firstDataArg; 9942 9943 if (IgnoreStringsWithoutSpecifiers && 9944 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9945 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9946 return; 9947 9948 // Emit a warning if the string literal is truncated and does not contain an 9949 // embedded null character. 9950 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) { 9951 CheckFormatHandler::EmitFormatDiagnostic( 9952 S, inFunctionCall, Args[format_idx], 9953 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9954 FExpr->getBeginLoc(), 9955 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9956 return; 9957 } 9958 9959 // CHECK: empty format string? 9960 if (StrLen == 0 && numDataArgs > 0) { 9961 CheckFormatHandler::EmitFormatDiagnostic( 9962 S, inFunctionCall, Args[format_idx], 9963 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9964 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9965 return; 9966 } 9967 9968 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9969 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9970 Type == Sema::FST_OSTrace) { 9971 CheckPrintfHandler H( 9972 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9973 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9974 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9975 CheckedVarArgs, UncoveredArg); 9976 9977 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9978 S.getLangOpts(), 9979 S.Context.getTargetInfo(), 9980 Type == Sema::FST_FreeBSDKPrintf)) 9981 H.DoneProcessing(); 9982 } else if (Type == Sema::FST_Scanf) { 9983 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9984 numDataArgs, Str, HasVAListArg, Args, format_idx, 9985 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9986 9987 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9988 S.getLangOpts(), 9989 S.Context.getTargetInfo())) 9990 H.DoneProcessing(); 9991 } // TODO: handle other formats 9992 } 9993 9994 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9995 // Str - The format string. NOTE: this is NOT null-terminated! 9996 StringRef StrRef = FExpr->getString(); 9997 const char *Str = StrRef.data(); 9998 // Account for cases where the string literal is truncated in a declaration. 9999 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 10000 assert(T && "String literal not of constant array type!"); 10001 size_t TypeSize = T->getSize().getZExtValue(); 10002 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 10003 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 10004 getLangOpts(), 10005 Context.getTargetInfo()); 10006 } 10007 10008 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 10009 10010 // Returns the related absolute value function that is larger, of 0 if one 10011 // does not exist. 10012 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 10013 switch (AbsFunction) { 10014 default: 10015 return 0; 10016 10017 case Builtin::BI__builtin_abs: 10018 return Builtin::BI__builtin_labs; 10019 case Builtin::BI__builtin_labs: 10020 return Builtin::BI__builtin_llabs; 10021 case Builtin::BI__builtin_llabs: 10022 return 0; 10023 10024 case Builtin::BI__builtin_fabsf: 10025 return Builtin::BI__builtin_fabs; 10026 case Builtin::BI__builtin_fabs: 10027 return Builtin::BI__builtin_fabsl; 10028 case Builtin::BI__builtin_fabsl: 10029 return 0; 10030 10031 case Builtin::BI__builtin_cabsf: 10032 return Builtin::BI__builtin_cabs; 10033 case Builtin::BI__builtin_cabs: 10034 return Builtin::BI__builtin_cabsl; 10035 case Builtin::BI__builtin_cabsl: 10036 return 0; 10037 10038 case Builtin::BIabs: 10039 return Builtin::BIlabs; 10040 case Builtin::BIlabs: 10041 return Builtin::BIllabs; 10042 case Builtin::BIllabs: 10043 return 0; 10044 10045 case Builtin::BIfabsf: 10046 return Builtin::BIfabs; 10047 case Builtin::BIfabs: 10048 return Builtin::BIfabsl; 10049 case Builtin::BIfabsl: 10050 return 0; 10051 10052 case Builtin::BIcabsf: 10053 return Builtin::BIcabs; 10054 case Builtin::BIcabs: 10055 return Builtin::BIcabsl; 10056 case Builtin::BIcabsl: 10057 return 0; 10058 } 10059 } 10060 10061 // Returns the argument type of the absolute value function. 10062 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 10063 unsigned AbsType) { 10064 if (AbsType == 0) 10065 return QualType(); 10066 10067 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 10068 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 10069 if (Error != ASTContext::GE_None) 10070 return QualType(); 10071 10072 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 10073 if (!FT) 10074 return QualType(); 10075 10076 if (FT->getNumParams() != 1) 10077 return QualType(); 10078 10079 return FT->getParamType(0); 10080 } 10081 10082 // Returns the best absolute value function, or zero, based on type and 10083 // current absolute value function. 10084 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 10085 unsigned AbsFunctionKind) { 10086 unsigned BestKind = 0; 10087 uint64_t ArgSize = Context.getTypeSize(ArgType); 10088 for (unsigned Kind = AbsFunctionKind; Kind != 0; 10089 Kind = getLargerAbsoluteValueFunction(Kind)) { 10090 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 10091 if (Context.getTypeSize(ParamType) >= ArgSize) { 10092 if (BestKind == 0) 10093 BestKind = Kind; 10094 else if (Context.hasSameType(ParamType, ArgType)) { 10095 BestKind = Kind; 10096 break; 10097 } 10098 } 10099 } 10100 return BestKind; 10101 } 10102 10103 enum AbsoluteValueKind { 10104 AVK_Integer, 10105 AVK_Floating, 10106 AVK_Complex 10107 }; 10108 10109 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 10110 if (T->isIntegralOrEnumerationType()) 10111 return AVK_Integer; 10112 if (T->isRealFloatingType()) 10113 return AVK_Floating; 10114 if (T->isAnyComplexType()) 10115 return AVK_Complex; 10116 10117 llvm_unreachable("Type not integer, floating, or complex"); 10118 } 10119 10120 // Changes the absolute value function to a different type. Preserves whether 10121 // the function is a builtin. 10122 static unsigned changeAbsFunction(unsigned AbsKind, 10123 AbsoluteValueKind ValueKind) { 10124 switch (ValueKind) { 10125 case AVK_Integer: 10126 switch (AbsKind) { 10127 default: 10128 return 0; 10129 case Builtin::BI__builtin_fabsf: 10130 case Builtin::BI__builtin_fabs: 10131 case Builtin::BI__builtin_fabsl: 10132 case Builtin::BI__builtin_cabsf: 10133 case Builtin::BI__builtin_cabs: 10134 case Builtin::BI__builtin_cabsl: 10135 return Builtin::BI__builtin_abs; 10136 case Builtin::BIfabsf: 10137 case Builtin::BIfabs: 10138 case Builtin::BIfabsl: 10139 case Builtin::BIcabsf: 10140 case Builtin::BIcabs: 10141 case Builtin::BIcabsl: 10142 return Builtin::BIabs; 10143 } 10144 case AVK_Floating: 10145 switch (AbsKind) { 10146 default: 10147 return 0; 10148 case Builtin::BI__builtin_abs: 10149 case Builtin::BI__builtin_labs: 10150 case Builtin::BI__builtin_llabs: 10151 case Builtin::BI__builtin_cabsf: 10152 case Builtin::BI__builtin_cabs: 10153 case Builtin::BI__builtin_cabsl: 10154 return Builtin::BI__builtin_fabsf; 10155 case Builtin::BIabs: 10156 case Builtin::BIlabs: 10157 case Builtin::BIllabs: 10158 case Builtin::BIcabsf: 10159 case Builtin::BIcabs: 10160 case Builtin::BIcabsl: 10161 return Builtin::BIfabsf; 10162 } 10163 case AVK_Complex: 10164 switch (AbsKind) { 10165 default: 10166 return 0; 10167 case Builtin::BI__builtin_abs: 10168 case Builtin::BI__builtin_labs: 10169 case Builtin::BI__builtin_llabs: 10170 case Builtin::BI__builtin_fabsf: 10171 case Builtin::BI__builtin_fabs: 10172 case Builtin::BI__builtin_fabsl: 10173 return Builtin::BI__builtin_cabsf; 10174 case Builtin::BIabs: 10175 case Builtin::BIlabs: 10176 case Builtin::BIllabs: 10177 case Builtin::BIfabsf: 10178 case Builtin::BIfabs: 10179 case Builtin::BIfabsl: 10180 return Builtin::BIcabsf; 10181 } 10182 } 10183 llvm_unreachable("Unable to convert function"); 10184 } 10185 10186 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 10187 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 10188 if (!FnInfo) 10189 return 0; 10190 10191 switch (FDecl->getBuiltinID()) { 10192 default: 10193 return 0; 10194 case Builtin::BI__builtin_abs: 10195 case Builtin::BI__builtin_fabs: 10196 case Builtin::BI__builtin_fabsf: 10197 case Builtin::BI__builtin_fabsl: 10198 case Builtin::BI__builtin_labs: 10199 case Builtin::BI__builtin_llabs: 10200 case Builtin::BI__builtin_cabs: 10201 case Builtin::BI__builtin_cabsf: 10202 case Builtin::BI__builtin_cabsl: 10203 case Builtin::BIabs: 10204 case Builtin::BIlabs: 10205 case Builtin::BIllabs: 10206 case Builtin::BIfabs: 10207 case Builtin::BIfabsf: 10208 case Builtin::BIfabsl: 10209 case Builtin::BIcabs: 10210 case Builtin::BIcabsf: 10211 case Builtin::BIcabsl: 10212 return FDecl->getBuiltinID(); 10213 } 10214 llvm_unreachable("Unknown Builtin type"); 10215 } 10216 10217 // If the replacement is valid, emit a note with replacement function. 10218 // Additionally, suggest including the proper header if not already included. 10219 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 10220 unsigned AbsKind, QualType ArgType) { 10221 bool EmitHeaderHint = true; 10222 const char *HeaderName = nullptr; 10223 const char *FunctionName = nullptr; 10224 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 10225 FunctionName = "std::abs"; 10226 if (ArgType->isIntegralOrEnumerationType()) { 10227 HeaderName = "cstdlib"; 10228 } else if (ArgType->isRealFloatingType()) { 10229 HeaderName = "cmath"; 10230 } else { 10231 llvm_unreachable("Invalid Type"); 10232 } 10233 10234 // Lookup all std::abs 10235 if (NamespaceDecl *Std = S.getStdNamespace()) { 10236 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 10237 R.suppressDiagnostics(); 10238 S.LookupQualifiedName(R, Std); 10239 10240 for (const auto *I : R) { 10241 const FunctionDecl *FDecl = nullptr; 10242 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 10243 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 10244 } else { 10245 FDecl = dyn_cast<FunctionDecl>(I); 10246 } 10247 if (!FDecl) 10248 continue; 10249 10250 // Found std::abs(), check that they are the right ones. 10251 if (FDecl->getNumParams() != 1) 10252 continue; 10253 10254 // Check that the parameter type can handle the argument. 10255 QualType ParamType = FDecl->getParamDecl(0)->getType(); 10256 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 10257 S.Context.getTypeSize(ArgType) <= 10258 S.Context.getTypeSize(ParamType)) { 10259 // Found a function, don't need the header hint. 10260 EmitHeaderHint = false; 10261 break; 10262 } 10263 } 10264 } 10265 } else { 10266 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 10267 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 10268 10269 if (HeaderName) { 10270 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 10271 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 10272 R.suppressDiagnostics(); 10273 S.LookupName(R, S.getCurScope()); 10274 10275 if (R.isSingleResult()) { 10276 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 10277 if (FD && FD->getBuiltinID() == AbsKind) { 10278 EmitHeaderHint = false; 10279 } else { 10280 return; 10281 } 10282 } else if (!R.empty()) { 10283 return; 10284 } 10285 } 10286 } 10287 10288 S.Diag(Loc, diag::note_replace_abs_function) 10289 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 10290 10291 if (!HeaderName) 10292 return; 10293 10294 if (!EmitHeaderHint) 10295 return; 10296 10297 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 10298 << FunctionName; 10299 } 10300 10301 template <std::size_t StrLen> 10302 static bool IsStdFunction(const FunctionDecl *FDecl, 10303 const char (&Str)[StrLen]) { 10304 if (!FDecl) 10305 return false; 10306 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 10307 return false; 10308 if (!FDecl->isInStdNamespace()) 10309 return false; 10310 10311 return true; 10312 } 10313 10314 // Warn when using the wrong abs() function. 10315 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 10316 const FunctionDecl *FDecl) { 10317 if (Call->getNumArgs() != 1) 10318 return; 10319 10320 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 10321 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 10322 if (AbsKind == 0 && !IsStdAbs) 10323 return; 10324 10325 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10326 QualType ParamType = Call->getArg(0)->getType(); 10327 10328 // Unsigned types cannot be negative. Suggest removing the absolute value 10329 // function call. 10330 if (ArgType->isUnsignedIntegerType()) { 10331 const char *FunctionName = 10332 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 10333 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 10334 Diag(Call->getExprLoc(), diag::note_remove_abs) 10335 << FunctionName 10336 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 10337 return; 10338 } 10339 10340 // Taking the absolute value of a pointer is very suspicious, they probably 10341 // wanted to index into an array, dereference a pointer, call a function, etc. 10342 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 10343 unsigned DiagType = 0; 10344 if (ArgType->isFunctionType()) 10345 DiagType = 1; 10346 else if (ArgType->isArrayType()) 10347 DiagType = 2; 10348 10349 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 10350 return; 10351 } 10352 10353 // std::abs has overloads which prevent most of the absolute value problems 10354 // from occurring. 10355 if (IsStdAbs) 10356 return; 10357 10358 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 10359 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 10360 10361 // The argument and parameter are the same kind. Check if they are the right 10362 // size. 10363 if (ArgValueKind == ParamValueKind) { 10364 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 10365 return; 10366 10367 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 10368 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 10369 << FDecl << ArgType << ParamType; 10370 10371 if (NewAbsKind == 0) 10372 return; 10373 10374 emitReplacement(*this, Call->getExprLoc(), 10375 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10376 return; 10377 } 10378 10379 // ArgValueKind != ParamValueKind 10380 // The wrong type of absolute value function was used. Attempt to find the 10381 // proper one. 10382 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 10383 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 10384 if (NewAbsKind == 0) 10385 return; 10386 10387 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10388 << FDecl << ParamValueKind << ArgValueKind; 10389 10390 emitReplacement(*this, Call->getExprLoc(), 10391 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10392 } 10393 10394 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10395 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10396 const FunctionDecl *FDecl) { 10397 if (!Call || !FDecl) return; 10398 10399 // Ignore template specializations and macros. 10400 if (inTemplateInstantiation()) return; 10401 if (Call->getExprLoc().isMacroID()) return; 10402 10403 // Only care about the one template argument, two function parameter std::max 10404 if (Call->getNumArgs() != 2) return; 10405 if (!IsStdFunction(FDecl, "max")) return; 10406 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10407 if (!ArgList) return; 10408 if (ArgList->size() != 1) return; 10409 10410 // Check that template type argument is unsigned integer. 10411 const auto& TA = ArgList->get(0); 10412 if (TA.getKind() != TemplateArgument::Type) return; 10413 QualType ArgType = TA.getAsType(); 10414 if (!ArgType->isUnsignedIntegerType()) return; 10415 10416 // See if either argument is a literal zero. 10417 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10418 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10419 if (!MTE) return false; 10420 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10421 if (!Num) return false; 10422 if (Num->getValue() != 0) return false; 10423 return true; 10424 }; 10425 10426 const Expr *FirstArg = Call->getArg(0); 10427 const Expr *SecondArg = Call->getArg(1); 10428 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10429 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10430 10431 // Only warn when exactly one argument is zero. 10432 if (IsFirstArgZero == IsSecondArgZero) return; 10433 10434 SourceRange FirstRange = FirstArg->getSourceRange(); 10435 SourceRange SecondRange = SecondArg->getSourceRange(); 10436 10437 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10438 10439 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10440 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10441 10442 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10443 SourceRange RemovalRange; 10444 if (IsFirstArgZero) { 10445 RemovalRange = SourceRange(FirstRange.getBegin(), 10446 SecondRange.getBegin().getLocWithOffset(-1)); 10447 } else { 10448 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10449 SecondRange.getEnd()); 10450 } 10451 10452 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10453 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10454 << FixItHint::CreateRemoval(RemovalRange); 10455 } 10456 10457 //===--- CHECK: Standard memory functions ---------------------------------===// 10458 10459 /// Takes the expression passed to the size_t parameter of functions 10460 /// such as memcmp, strncat, etc and warns if it's a comparison. 10461 /// 10462 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10463 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10464 IdentifierInfo *FnName, 10465 SourceLocation FnLoc, 10466 SourceLocation RParenLoc) { 10467 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10468 if (!Size) 10469 return false; 10470 10471 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10472 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10473 return false; 10474 10475 SourceRange SizeRange = Size->getSourceRange(); 10476 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10477 << SizeRange << FnName; 10478 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10479 << FnName 10480 << FixItHint::CreateInsertion( 10481 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10482 << FixItHint::CreateRemoval(RParenLoc); 10483 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10484 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10485 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10486 ")"); 10487 10488 return true; 10489 } 10490 10491 /// Determine whether the given type is or contains a dynamic class type 10492 /// (e.g., whether it has a vtable). 10493 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10494 bool &IsContained) { 10495 // Look through array types while ignoring qualifiers. 10496 const Type *Ty = T->getBaseElementTypeUnsafe(); 10497 IsContained = false; 10498 10499 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10500 RD = RD ? RD->getDefinition() : nullptr; 10501 if (!RD || RD->isInvalidDecl()) 10502 return nullptr; 10503 10504 if (RD->isDynamicClass()) 10505 return RD; 10506 10507 // Check all the fields. If any bases were dynamic, the class is dynamic. 10508 // It's impossible for a class to transitively contain itself by value, so 10509 // infinite recursion is impossible. 10510 for (auto *FD : RD->fields()) { 10511 bool SubContained; 10512 if (const CXXRecordDecl *ContainedRD = 10513 getContainedDynamicClass(FD->getType(), SubContained)) { 10514 IsContained = true; 10515 return ContainedRD; 10516 } 10517 } 10518 10519 return nullptr; 10520 } 10521 10522 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10523 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10524 if (Unary->getKind() == UETT_SizeOf) 10525 return Unary; 10526 return nullptr; 10527 } 10528 10529 /// If E is a sizeof expression, returns its argument expression, 10530 /// otherwise returns NULL. 10531 static const Expr *getSizeOfExprArg(const Expr *E) { 10532 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10533 if (!SizeOf->isArgumentType()) 10534 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10535 return nullptr; 10536 } 10537 10538 /// If E is a sizeof expression, returns its argument type. 10539 static QualType getSizeOfArgType(const Expr *E) { 10540 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10541 return SizeOf->getTypeOfArgument(); 10542 return QualType(); 10543 } 10544 10545 namespace { 10546 10547 struct SearchNonTrivialToInitializeField 10548 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10549 using Super = 10550 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10551 10552 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10553 10554 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10555 SourceLocation SL) { 10556 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10557 asDerived().visitArray(PDIK, AT, SL); 10558 return; 10559 } 10560 10561 Super::visitWithKind(PDIK, FT, SL); 10562 } 10563 10564 void visitARCStrong(QualType FT, SourceLocation SL) { 10565 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10566 } 10567 void visitARCWeak(QualType FT, SourceLocation SL) { 10568 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10569 } 10570 void visitStruct(QualType FT, SourceLocation SL) { 10571 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10572 visit(FD->getType(), FD->getLocation()); 10573 } 10574 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10575 const ArrayType *AT, SourceLocation SL) { 10576 visit(getContext().getBaseElementType(AT), SL); 10577 } 10578 void visitTrivial(QualType FT, SourceLocation SL) {} 10579 10580 static void diag(QualType RT, const Expr *E, Sema &S) { 10581 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10582 } 10583 10584 ASTContext &getContext() { return S.getASTContext(); } 10585 10586 const Expr *E; 10587 Sema &S; 10588 }; 10589 10590 struct SearchNonTrivialToCopyField 10591 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10592 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10593 10594 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10595 10596 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10597 SourceLocation SL) { 10598 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10599 asDerived().visitArray(PCK, AT, SL); 10600 return; 10601 } 10602 10603 Super::visitWithKind(PCK, FT, SL); 10604 } 10605 10606 void visitARCStrong(QualType FT, SourceLocation SL) { 10607 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10608 } 10609 void visitARCWeak(QualType FT, SourceLocation SL) { 10610 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10611 } 10612 void visitStruct(QualType FT, SourceLocation SL) { 10613 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10614 visit(FD->getType(), FD->getLocation()); 10615 } 10616 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10617 SourceLocation SL) { 10618 visit(getContext().getBaseElementType(AT), SL); 10619 } 10620 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10621 SourceLocation SL) {} 10622 void visitTrivial(QualType FT, SourceLocation SL) {} 10623 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10624 10625 static void diag(QualType RT, const Expr *E, Sema &S) { 10626 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10627 } 10628 10629 ASTContext &getContext() { return S.getASTContext(); } 10630 10631 const Expr *E; 10632 Sema &S; 10633 }; 10634 10635 } 10636 10637 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10638 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10639 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10640 10641 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10642 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10643 return false; 10644 10645 return doesExprLikelyComputeSize(BO->getLHS()) || 10646 doesExprLikelyComputeSize(BO->getRHS()); 10647 } 10648 10649 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10650 } 10651 10652 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10653 /// 10654 /// \code 10655 /// #define MACRO 0 10656 /// foo(MACRO); 10657 /// foo(0); 10658 /// \endcode 10659 /// 10660 /// This should return true for the first call to foo, but not for the second 10661 /// (regardless of whether foo is a macro or function). 10662 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10663 SourceLocation CallLoc, 10664 SourceLocation ArgLoc) { 10665 if (!CallLoc.isMacroID()) 10666 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10667 10668 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10669 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10670 } 10671 10672 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10673 /// last two arguments transposed. 10674 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10675 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10676 return; 10677 10678 const Expr *SizeArg = 10679 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10680 10681 auto isLiteralZero = [](const Expr *E) { 10682 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10683 }; 10684 10685 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10686 SourceLocation CallLoc = Call->getRParenLoc(); 10687 SourceManager &SM = S.getSourceManager(); 10688 if (isLiteralZero(SizeArg) && 10689 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10690 10691 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10692 10693 // Some platforms #define bzero to __builtin_memset. See if this is the 10694 // case, and if so, emit a better diagnostic. 10695 if (BId == Builtin::BIbzero || 10696 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10697 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10698 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10699 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10700 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10701 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10702 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10703 } 10704 return; 10705 } 10706 10707 // If the second argument to a memset is a sizeof expression and the third 10708 // isn't, this is also likely an error. This should catch 10709 // 'memset(buf, sizeof(buf), 0xff)'. 10710 if (BId == Builtin::BImemset && 10711 doesExprLikelyComputeSize(Call->getArg(1)) && 10712 !doesExprLikelyComputeSize(Call->getArg(2))) { 10713 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10714 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10715 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10716 return; 10717 } 10718 } 10719 10720 /// Check for dangerous or invalid arguments to memset(). 10721 /// 10722 /// This issues warnings on known problematic, dangerous or unspecified 10723 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10724 /// function calls. 10725 /// 10726 /// \param Call The call expression to diagnose. 10727 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10728 unsigned BId, 10729 IdentifierInfo *FnName) { 10730 assert(BId != 0); 10731 10732 // It is possible to have a non-standard definition of memset. Validate 10733 // we have enough arguments, and if not, abort further checking. 10734 unsigned ExpectedNumArgs = 10735 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10736 if (Call->getNumArgs() < ExpectedNumArgs) 10737 return; 10738 10739 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10740 BId == Builtin::BIstrndup ? 1 : 2); 10741 unsigned LenArg = 10742 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10743 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10744 10745 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10746 Call->getBeginLoc(), Call->getRParenLoc())) 10747 return; 10748 10749 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10750 CheckMemaccessSize(*this, BId, Call); 10751 10752 // We have special checking when the length is a sizeof expression. 10753 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10754 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10755 llvm::FoldingSetNodeID SizeOfArgID; 10756 10757 // Although widely used, 'bzero' is not a standard function. Be more strict 10758 // with the argument types before allowing diagnostics and only allow the 10759 // form bzero(ptr, sizeof(...)). 10760 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10761 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10762 return; 10763 10764 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10765 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10766 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10767 10768 QualType DestTy = Dest->getType(); 10769 QualType PointeeTy; 10770 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10771 PointeeTy = DestPtrTy->getPointeeType(); 10772 10773 // Never warn about void type pointers. This can be used to suppress 10774 // false positives. 10775 if (PointeeTy->isVoidType()) 10776 continue; 10777 10778 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10779 // actually comparing the expressions for equality. Because computing the 10780 // expression IDs can be expensive, we only do this if the diagnostic is 10781 // enabled. 10782 if (SizeOfArg && 10783 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10784 SizeOfArg->getExprLoc())) { 10785 // We only compute IDs for expressions if the warning is enabled, and 10786 // cache the sizeof arg's ID. 10787 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10788 SizeOfArg->Profile(SizeOfArgID, Context, true); 10789 llvm::FoldingSetNodeID DestID; 10790 Dest->Profile(DestID, Context, true); 10791 if (DestID == SizeOfArgID) { 10792 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10793 // over sizeof(src) as well. 10794 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10795 StringRef ReadableName = FnName->getName(); 10796 10797 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10798 if (UnaryOp->getOpcode() == UO_AddrOf) 10799 ActionIdx = 1; // If its an address-of operator, just remove it. 10800 if (!PointeeTy->isIncompleteType() && 10801 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10802 ActionIdx = 2; // If the pointee's size is sizeof(char), 10803 // suggest an explicit length. 10804 10805 // If the function is defined as a builtin macro, do not show macro 10806 // expansion. 10807 SourceLocation SL = SizeOfArg->getExprLoc(); 10808 SourceRange DSR = Dest->getSourceRange(); 10809 SourceRange SSR = SizeOfArg->getSourceRange(); 10810 SourceManager &SM = getSourceManager(); 10811 10812 if (SM.isMacroArgExpansion(SL)) { 10813 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10814 SL = SM.getSpellingLoc(SL); 10815 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10816 SM.getSpellingLoc(DSR.getEnd())); 10817 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10818 SM.getSpellingLoc(SSR.getEnd())); 10819 } 10820 10821 DiagRuntimeBehavior(SL, SizeOfArg, 10822 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10823 << ReadableName 10824 << PointeeTy 10825 << DestTy 10826 << DSR 10827 << SSR); 10828 DiagRuntimeBehavior(SL, SizeOfArg, 10829 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10830 << ActionIdx 10831 << SSR); 10832 10833 break; 10834 } 10835 } 10836 10837 // Also check for cases where the sizeof argument is the exact same 10838 // type as the memory argument, and where it points to a user-defined 10839 // record type. 10840 if (SizeOfArgTy != QualType()) { 10841 if (PointeeTy->isRecordType() && 10842 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10843 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10844 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10845 << FnName << SizeOfArgTy << ArgIdx 10846 << PointeeTy << Dest->getSourceRange() 10847 << LenExpr->getSourceRange()); 10848 break; 10849 } 10850 } 10851 } else if (DestTy->isArrayType()) { 10852 PointeeTy = DestTy; 10853 } 10854 10855 if (PointeeTy == QualType()) 10856 continue; 10857 10858 // Always complain about dynamic classes. 10859 bool IsContained; 10860 if (const CXXRecordDecl *ContainedRD = 10861 getContainedDynamicClass(PointeeTy, IsContained)) { 10862 10863 unsigned OperationType = 0; 10864 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10865 // "overwritten" if we're warning about the destination for any call 10866 // but memcmp; otherwise a verb appropriate to the call. 10867 if (ArgIdx != 0 || IsCmp) { 10868 if (BId == Builtin::BImemcpy) 10869 OperationType = 1; 10870 else if(BId == Builtin::BImemmove) 10871 OperationType = 2; 10872 else if (IsCmp) 10873 OperationType = 3; 10874 } 10875 10876 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10877 PDiag(diag::warn_dyn_class_memaccess) 10878 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10879 << IsContained << ContainedRD << OperationType 10880 << Call->getCallee()->getSourceRange()); 10881 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10882 BId != Builtin::BImemset) 10883 DiagRuntimeBehavior( 10884 Dest->getExprLoc(), Dest, 10885 PDiag(diag::warn_arc_object_memaccess) 10886 << ArgIdx << FnName << PointeeTy 10887 << Call->getCallee()->getSourceRange()); 10888 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10889 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10890 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10891 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10892 PDiag(diag::warn_cstruct_memaccess) 10893 << ArgIdx << FnName << PointeeTy << 0); 10894 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10895 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10896 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10897 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10898 PDiag(diag::warn_cstruct_memaccess) 10899 << ArgIdx << FnName << PointeeTy << 1); 10900 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10901 } else { 10902 continue; 10903 } 10904 } else 10905 continue; 10906 10907 DiagRuntimeBehavior( 10908 Dest->getExprLoc(), Dest, 10909 PDiag(diag::note_bad_memaccess_silence) 10910 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10911 break; 10912 } 10913 } 10914 10915 // A little helper routine: ignore addition and subtraction of integer literals. 10916 // This intentionally does not ignore all integer constant expressions because 10917 // we don't want to remove sizeof(). 10918 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10919 Ex = Ex->IgnoreParenCasts(); 10920 10921 while (true) { 10922 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10923 if (!BO || !BO->isAdditiveOp()) 10924 break; 10925 10926 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10927 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10928 10929 if (isa<IntegerLiteral>(RHS)) 10930 Ex = LHS; 10931 else if (isa<IntegerLiteral>(LHS)) 10932 Ex = RHS; 10933 else 10934 break; 10935 } 10936 10937 return Ex; 10938 } 10939 10940 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10941 ASTContext &Context) { 10942 // Only handle constant-sized or VLAs, but not flexible members. 10943 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10944 // Only issue the FIXIT for arrays of size > 1. 10945 if (CAT->getSize().getSExtValue() <= 1) 10946 return false; 10947 } else if (!Ty->isVariableArrayType()) { 10948 return false; 10949 } 10950 return true; 10951 } 10952 10953 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10954 // be the size of the source, instead of the destination. 10955 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10956 IdentifierInfo *FnName) { 10957 10958 // Don't crash if the user has the wrong number of arguments 10959 unsigned NumArgs = Call->getNumArgs(); 10960 if ((NumArgs != 3) && (NumArgs != 4)) 10961 return; 10962 10963 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10964 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10965 const Expr *CompareWithSrc = nullptr; 10966 10967 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10968 Call->getBeginLoc(), Call->getRParenLoc())) 10969 return; 10970 10971 // Look for 'strlcpy(dst, x, sizeof(x))' 10972 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10973 CompareWithSrc = Ex; 10974 else { 10975 // Look for 'strlcpy(dst, x, strlen(x))' 10976 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10977 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10978 SizeCall->getNumArgs() == 1) 10979 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10980 } 10981 } 10982 10983 if (!CompareWithSrc) 10984 return; 10985 10986 // Determine if the argument to sizeof/strlen is equal to the source 10987 // argument. In principle there's all kinds of things you could do 10988 // here, for instance creating an == expression and evaluating it with 10989 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10990 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10991 if (!SrcArgDRE) 10992 return; 10993 10994 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10995 if (!CompareWithSrcDRE || 10996 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10997 return; 10998 10999 const Expr *OriginalSizeArg = Call->getArg(2); 11000 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 11001 << OriginalSizeArg->getSourceRange() << FnName; 11002 11003 // Output a FIXIT hint if the destination is an array (rather than a 11004 // pointer to an array). This could be enhanced to handle some 11005 // pointers if we know the actual size, like if DstArg is 'array+2' 11006 // we could say 'sizeof(array)-2'. 11007 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 11008 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 11009 return; 11010 11011 SmallString<128> sizeString; 11012 llvm::raw_svector_ostream OS(sizeString); 11013 OS << "sizeof("; 11014 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11015 OS << ")"; 11016 11017 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 11018 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 11019 OS.str()); 11020 } 11021 11022 /// Check if two expressions refer to the same declaration. 11023 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 11024 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 11025 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 11026 return D1->getDecl() == D2->getDecl(); 11027 return false; 11028 } 11029 11030 static const Expr *getStrlenExprArg(const Expr *E) { 11031 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11032 const FunctionDecl *FD = CE->getDirectCallee(); 11033 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 11034 return nullptr; 11035 return CE->getArg(0)->IgnoreParenCasts(); 11036 } 11037 return nullptr; 11038 } 11039 11040 // Warn on anti-patterns as the 'size' argument to strncat. 11041 // The correct size argument should look like following: 11042 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 11043 void Sema::CheckStrncatArguments(const CallExpr *CE, 11044 IdentifierInfo *FnName) { 11045 // Don't crash if the user has the wrong number of arguments. 11046 if (CE->getNumArgs() < 3) 11047 return; 11048 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 11049 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 11050 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 11051 11052 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 11053 CE->getRParenLoc())) 11054 return; 11055 11056 // Identify common expressions, which are wrongly used as the size argument 11057 // to strncat and may lead to buffer overflows. 11058 unsigned PatternType = 0; 11059 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 11060 // - sizeof(dst) 11061 if (referToTheSameDecl(SizeOfArg, DstArg)) 11062 PatternType = 1; 11063 // - sizeof(src) 11064 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 11065 PatternType = 2; 11066 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 11067 if (BE->getOpcode() == BO_Sub) { 11068 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 11069 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 11070 // - sizeof(dst) - strlen(dst) 11071 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 11072 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 11073 PatternType = 1; 11074 // - sizeof(src) - (anything) 11075 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 11076 PatternType = 2; 11077 } 11078 } 11079 11080 if (PatternType == 0) 11081 return; 11082 11083 // Generate the diagnostic. 11084 SourceLocation SL = LenArg->getBeginLoc(); 11085 SourceRange SR = LenArg->getSourceRange(); 11086 SourceManager &SM = getSourceManager(); 11087 11088 // If the function is defined as a builtin macro, do not show macro expansion. 11089 if (SM.isMacroArgExpansion(SL)) { 11090 SL = SM.getSpellingLoc(SL); 11091 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 11092 SM.getSpellingLoc(SR.getEnd())); 11093 } 11094 11095 // Check if the destination is an array (rather than a pointer to an array). 11096 QualType DstTy = DstArg->getType(); 11097 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 11098 Context); 11099 if (!isKnownSizeArray) { 11100 if (PatternType == 1) 11101 Diag(SL, diag::warn_strncat_wrong_size) << SR; 11102 else 11103 Diag(SL, diag::warn_strncat_src_size) << SR; 11104 return; 11105 } 11106 11107 if (PatternType == 1) 11108 Diag(SL, diag::warn_strncat_large_size) << SR; 11109 else 11110 Diag(SL, diag::warn_strncat_src_size) << SR; 11111 11112 SmallString<128> sizeString; 11113 llvm::raw_svector_ostream OS(sizeString); 11114 OS << "sizeof("; 11115 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11116 OS << ") - "; 11117 OS << "strlen("; 11118 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11119 OS << ") - 1"; 11120 11121 Diag(SL, diag::note_strncat_wrong_size) 11122 << FixItHint::CreateReplacement(SR, OS.str()); 11123 } 11124 11125 namespace { 11126 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 11127 const UnaryOperator *UnaryExpr, const Decl *D) { 11128 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 11129 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 11130 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 11131 return; 11132 } 11133 } 11134 11135 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 11136 const UnaryOperator *UnaryExpr) { 11137 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 11138 const Decl *D = Lvalue->getDecl(); 11139 if (isa<DeclaratorDecl>(D)) 11140 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 11141 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 11142 } 11143 11144 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 11145 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 11146 Lvalue->getMemberDecl()); 11147 } 11148 11149 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 11150 const UnaryOperator *UnaryExpr) { 11151 const auto *Lambda = dyn_cast<LambdaExpr>( 11152 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 11153 if (!Lambda) 11154 return; 11155 11156 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 11157 << CalleeName << 2 /*object: lambda expression*/; 11158 } 11159 11160 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 11161 const DeclRefExpr *Lvalue) { 11162 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 11163 if (Var == nullptr) 11164 return; 11165 11166 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 11167 << CalleeName << 0 /*object: */ << Var; 11168 } 11169 11170 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 11171 const CastExpr *Cast) { 11172 SmallString<128> SizeString; 11173 llvm::raw_svector_ostream OS(SizeString); 11174 11175 clang::CastKind Kind = Cast->getCastKind(); 11176 if (Kind == clang::CK_BitCast && 11177 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 11178 return; 11179 if (Kind == clang::CK_IntegralToPointer && 11180 !isa<IntegerLiteral>( 11181 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 11182 return; 11183 11184 switch (Cast->getCastKind()) { 11185 case clang::CK_BitCast: 11186 case clang::CK_IntegralToPointer: 11187 case clang::CK_FunctionToPointerDecay: 11188 OS << '\''; 11189 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 11190 OS << '\''; 11191 break; 11192 default: 11193 return; 11194 } 11195 11196 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 11197 << CalleeName << 0 /*object: */ << OS.str(); 11198 } 11199 } // namespace 11200 11201 /// Alerts the user that they are attempting to free a non-malloc'd object. 11202 void Sema::CheckFreeArguments(const CallExpr *E) { 11203 const std::string CalleeName = 11204 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 11205 11206 { // Prefer something that doesn't involve a cast to make things simpler. 11207 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 11208 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 11209 switch (UnaryExpr->getOpcode()) { 11210 case UnaryOperator::Opcode::UO_AddrOf: 11211 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 11212 case UnaryOperator::Opcode::UO_Plus: 11213 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 11214 default: 11215 break; 11216 } 11217 11218 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 11219 if (Lvalue->getType()->isArrayType()) 11220 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 11221 11222 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 11223 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 11224 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 11225 return; 11226 } 11227 11228 if (isa<BlockExpr>(Arg)) { 11229 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 11230 << CalleeName << 1 /*object: block*/; 11231 return; 11232 } 11233 } 11234 // Maybe the cast was important, check after the other cases. 11235 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 11236 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 11237 } 11238 11239 void 11240 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 11241 SourceLocation ReturnLoc, 11242 bool isObjCMethod, 11243 const AttrVec *Attrs, 11244 const FunctionDecl *FD) { 11245 // Check if the return value is null but should not be. 11246 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 11247 (!isObjCMethod && isNonNullType(Context, lhsType))) && 11248 CheckNonNullExpr(*this, RetValExp)) 11249 Diag(ReturnLoc, diag::warn_null_ret) 11250 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 11251 11252 // C++11 [basic.stc.dynamic.allocation]p4: 11253 // If an allocation function declared with a non-throwing 11254 // exception-specification fails to allocate storage, it shall return 11255 // a null pointer. Any other allocation function that fails to allocate 11256 // storage shall indicate failure only by throwing an exception [...] 11257 if (FD) { 11258 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 11259 if (Op == OO_New || Op == OO_Array_New) { 11260 const FunctionProtoType *Proto 11261 = FD->getType()->castAs<FunctionProtoType>(); 11262 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 11263 CheckNonNullExpr(*this, RetValExp)) 11264 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 11265 << FD << getLangOpts().CPlusPlus11; 11266 } 11267 } 11268 11269 // PPC MMA non-pointer types are not allowed as return type. Checking the type 11270 // here prevent the user from using a PPC MMA type as trailing return type. 11271 if (Context.getTargetInfo().getTriple().isPPC64()) 11272 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 11273 } 11274 11275 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 11276 11277 /// Check for comparisons of floating point operands using != and ==. 11278 /// Issue a warning if these are no self-comparisons, as they are not likely 11279 /// to do what the programmer intended. 11280 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 11281 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 11282 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 11283 11284 // Special case: check for x == x (which is OK). 11285 // Do not emit warnings for such cases. 11286 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 11287 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 11288 if (DRL->getDecl() == DRR->getDecl()) 11289 return; 11290 11291 // Special case: check for comparisons against literals that can be exactly 11292 // represented by APFloat. In such cases, do not emit a warning. This 11293 // is a heuristic: often comparison against such literals are used to 11294 // detect if a value in a variable has not changed. This clearly can 11295 // lead to false negatives. 11296 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 11297 if (FLL->isExact()) 11298 return; 11299 } else 11300 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 11301 if (FLR->isExact()) 11302 return; 11303 11304 // Check for comparisons with builtin types. 11305 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 11306 if (CL->getBuiltinCallee()) 11307 return; 11308 11309 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 11310 if (CR->getBuiltinCallee()) 11311 return; 11312 11313 // Emit the diagnostic. 11314 Diag(Loc, diag::warn_floatingpoint_eq) 11315 << LHS->getSourceRange() << RHS->getSourceRange(); 11316 } 11317 11318 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 11319 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 11320 11321 namespace { 11322 11323 /// Structure recording the 'active' range of an integer-valued 11324 /// expression. 11325 struct IntRange { 11326 /// The number of bits active in the int. Note that this includes exactly one 11327 /// sign bit if !NonNegative. 11328 unsigned Width; 11329 11330 /// True if the int is known not to have negative values. If so, all leading 11331 /// bits before Width are known zero, otherwise they are known to be the 11332 /// same as the MSB within Width. 11333 bool NonNegative; 11334 11335 IntRange(unsigned Width, bool NonNegative) 11336 : Width(Width), NonNegative(NonNegative) {} 11337 11338 /// Number of bits excluding the sign bit. 11339 unsigned valueBits() const { 11340 return NonNegative ? Width : Width - 1; 11341 } 11342 11343 /// Returns the range of the bool type. 11344 static IntRange forBoolType() { 11345 return IntRange(1, true); 11346 } 11347 11348 /// Returns the range of an opaque value of the given integral type. 11349 static IntRange forValueOfType(ASTContext &C, QualType T) { 11350 return forValueOfCanonicalType(C, 11351 T->getCanonicalTypeInternal().getTypePtr()); 11352 } 11353 11354 /// Returns the range of an opaque value of a canonical integral type. 11355 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 11356 assert(T->isCanonicalUnqualified()); 11357 11358 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11359 T = VT->getElementType().getTypePtr(); 11360 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11361 T = CT->getElementType().getTypePtr(); 11362 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11363 T = AT->getValueType().getTypePtr(); 11364 11365 if (!C.getLangOpts().CPlusPlus) { 11366 // For enum types in C code, use the underlying datatype. 11367 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11368 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 11369 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 11370 // For enum types in C++, use the known bit width of the enumerators. 11371 EnumDecl *Enum = ET->getDecl(); 11372 // In C++11, enums can have a fixed underlying type. Use this type to 11373 // compute the range. 11374 if (Enum->isFixed()) { 11375 return IntRange(C.getIntWidth(QualType(T, 0)), 11376 !ET->isSignedIntegerOrEnumerationType()); 11377 } 11378 11379 unsigned NumPositive = Enum->getNumPositiveBits(); 11380 unsigned NumNegative = Enum->getNumNegativeBits(); 11381 11382 if (NumNegative == 0) 11383 return IntRange(NumPositive, true/*NonNegative*/); 11384 else 11385 return IntRange(std::max(NumPositive + 1, NumNegative), 11386 false/*NonNegative*/); 11387 } 11388 11389 if (const auto *EIT = dyn_cast<BitIntType>(T)) 11390 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11391 11392 const BuiltinType *BT = cast<BuiltinType>(T); 11393 assert(BT->isInteger()); 11394 11395 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11396 } 11397 11398 /// Returns the "target" range of a canonical integral type, i.e. 11399 /// the range of values expressible in the type. 11400 /// 11401 /// This matches forValueOfCanonicalType except that enums have the 11402 /// full range of their type, not the range of their enumerators. 11403 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11404 assert(T->isCanonicalUnqualified()); 11405 11406 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11407 T = VT->getElementType().getTypePtr(); 11408 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11409 T = CT->getElementType().getTypePtr(); 11410 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11411 T = AT->getValueType().getTypePtr(); 11412 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11413 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11414 11415 if (const auto *EIT = dyn_cast<BitIntType>(T)) 11416 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11417 11418 const BuiltinType *BT = cast<BuiltinType>(T); 11419 assert(BT->isInteger()); 11420 11421 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11422 } 11423 11424 /// Returns the supremum of two ranges: i.e. their conservative merge. 11425 static IntRange join(IntRange L, IntRange R) { 11426 bool Unsigned = L.NonNegative && R.NonNegative; 11427 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11428 L.NonNegative && R.NonNegative); 11429 } 11430 11431 /// Return the range of a bitwise-AND of the two ranges. 11432 static IntRange bit_and(IntRange L, IntRange R) { 11433 unsigned Bits = std::max(L.Width, R.Width); 11434 bool NonNegative = false; 11435 if (L.NonNegative) { 11436 Bits = std::min(Bits, L.Width); 11437 NonNegative = true; 11438 } 11439 if (R.NonNegative) { 11440 Bits = std::min(Bits, R.Width); 11441 NonNegative = true; 11442 } 11443 return IntRange(Bits, NonNegative); 11444 } 11445 11446 /// Return the range of a sum of the two ranges. 11447 static IntRange sum(IntRange L, IntRange R) { 11448 bool Unsigned = L.NonNegative && R.NonNegative; 11449 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11450 Unsigned); 11451 } 11452 11453 /// Return the range of a difference of the two ranges. 11454 static IntRange difference(IntRange L, IntRange R) { 11455 // We need a 1-bit-wider range if: 11456 // 1) LHS can be negative: least value can be reduced. 11457 // 2) RHS can be negative: greatest value can be increased. 11458 bool CanWiden = !L.NonNegative || !R.NonNegative; 11459 bool Unsigned = L.NonNegative && R.Width == 0; 11460 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11461 !Unsigned, 11462 Unsigned); 11463 } 11464 11465 /// Return the range of a product of the two ranges. 11466 static IntRange product(IntRange L, IntRange R) { 11467 // If both LHS and RHS can be negative, we can form 11468 // -2^L * -2^R = 2^(L + R) 11469 // which requires L + R + 1 value bits to represent. 11470 bool CanWiden = !L.NonNegative && !R.NonNegative; 11471 bool Unsigned = L.NonNegative && R.NonNegative; 11472 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11473 Unsigned); 11474 } 11475 11476 /// Return the range of a remainder operation between the two ranges. 11477 static IntRange rem(IntRange L, IntRange R) { 11478 // The result of a remainder can't be larger than the result of 11479 // either side. The sign of the result is the sign of the LHS. 11480 bool Unsigned = L.NonNegative; 11481 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11482 Unsigned); 11483 } 11484 }; 11485 11486 } // namespace 11487 11488 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11489 unsigned MaxWidth) { 11490 if (value.isSigned() && value.isNegative()) 11491 return IntRange(value.getMinSignedBits(), false); 11492 11493 if (value.getBitWidth() > MaxWidth) 11494 value = value.trunc(MaxWidth); 11495 11496 // isNonNegative() just checks the sign bit without considering 11497 // signedness. 11498 return IntRange(value.getActiveBits(), true); 11499 } 11500 11501 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11502 unsigned MaxWidth) { 11503 if (result.isInt()) 11504 return GetValueRange(C, result.getInt(), MaxWidth); 11505 11506 if (result.isVector()) { 11507 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11508 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11509 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11510 R = IntRange::join(R, El); 11511 } 11512 return R; 11513 } 11514 11515 if (result.isComplexInt()) { 11516 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11517 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11518 return IntRange::join(R, I); 11519 } 11520 11521 // This can happen with lossless casts to intptr_t of "based" lvalues. 11522 // Assume it might use arbitrary bits. 11523 // FIXME: The only reason we need to pass the type in here is to get 11524 // the sign right on this one case. It would be nice if APValue 11525 // preserved this. 11526 assert(result.isLValue() || result.isAddrLabelDiff()); 11527 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11528 } 11529 11530 static QualType GetExprType(const Expr *E) { 11531 QualType Ty = E->getType(); 11532 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11533 Ty = AtomicRHS->getValueType(); 11534 return Ty; 11535 } 11536 11537 /// Pseudo-evaluate the given integer expression, estimating the 11538 /// range of values it might take. 11539 /// 11540 /// \param MaxWidth The width to which the value will be truncated. 11541 /// \param Approximate If \c true, return a likely range for the result: in 11542 /// particular, assume that arithmetic on narrower types doesn't leave 11543 /// those types. If \c false, return a range including all possible 11544 /// result values. 11545 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11546 bool InConstantContext, bool Approximate) { 11547 E = E->IgnoreParens(); 11548 11549 // Try a full evaluation first. 11550 Expr::EvalResult result; 11551 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11552 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11553 11554 // I think we only want to look through implicit casts here; if the 11555 // user has an explicit widening cast, we should treat the value as 11556 // being of the new, wider type. 11557 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11558 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11559 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11560 Approximate); 11561 11562 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11563 11564 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11565 CE->getCastKind() == CK_BooleanToSignedIntegral; 11566 11567 // Assume that non-integer casts can span the full range of the type. 11568 if (!isIntegerCast) 11569 return OutputTypeRange; 11570 11571 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11572 std::min(MaxWidth, OutputTypeRange.Width), 11573 InConstantContext, Approximate); 11574 11575 // Bail out if the subexpr's range is as wide as the cast type. 11576 if (SubRange.Width >= OutputTypeRange.Width) 11577 return OutputTypeRange; 11578 11579 // Otherwise, we take the smaller width, and we're non-negative if 11580 // either the output type or the subexpr is. 11581 return IntRange(SubRange.Width, 11582 SubRange.NonNegative || OutputTypeRange.NonNegative); 11583 } 11584 11585 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11586 // If we can fold the condition, just take that operand. 11587 bool CondResult; 11588 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11589 return GetExprRange(C, 11590 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11591 MaxWidth, InConstantContext, Approximate); 11592 11593 // Otherwise, conservatively merge. 11594 // GetExprRange requires an integer expression, but a throw expression 11595 // results in a void type. 11596 Expr *E = CO->getTrueExpr(); 11597 IntRange L = E->getType()->isVoidType() 11598 ? IntRange{0, true} 11599 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11600 E = CO->getFalseExpr(); 11601 IntRange R = E->getType()->isVoidType() 11602 ? IntRange{0, true} 11603 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11604 return IntRange::join(L, R); 11605 } 11606 11607 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11608 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11609 11610 switch (BO->getOpcode()) { 11611 case BO_Cmp: 11612 llvm_unreachable("builtin <=> should have class type"); 11613 11614 // Boolean-valued operations are single-bit and positive. 11615 case BO_LAnd: 11616 case BO_LOr: 11617 case BO_LT: 11618 case BO_GT: 11619 case BO_LE: 11620 case BO_GE: 11621 case BO_EQ: 11622 case BO_NE: 11623 return IntRange::forBoolType(); 11624 11625 // The type of the assignments is the type of the LHS, so the RHS 11626 // is not necessarily the same type. 11627 case BO_MulAssign: 11628 case BO_DivAssign: 11629 case BO_RemAssign: 11630 case BO_AddAssign: 11631 case BO_SubAssign: 11632 case BO_XorAssign: 11633 case BO_OrAssign: 11634 // TODO: bitfields? 11635 return IntRange::forValueOfType(C, GetExprType(E)); 11636 11637 // Simple assignments just pass through the RHS, which will have 11638 // been coerced to the LHS type. 11639 case BO_Assign: 11640 // TODO: bitfields? 11641 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11642 Approximate); 11643 11644 // Operations with opaque sources are black-listed. 11645 case BO_PtrMemD: 11646 case BO_PtrMemI: 11647 return IntRange::forValueOfType(C, GetExprType(E)); 11648 11649 // Bitwise-and uses the *infinum* of the two source ranges. 11650 case BO_And: 11651 case BO_AndAssign: 11652 Combine = IntRange::bit_and; 11653 break; 11654 11655 // Left shift gets black-listed based on a judgement call. 11656 case BO_Shl: 11657 // ...except that we want to treat '1 << (blah)' as logically 11658 // positive. It's an important idiom. 11659 if (IntegerLiteral *I 11660 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11661 if (I->getValue() == 1) { 11662 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11663 return IntRange(R.Width, /*NonNegative*/ true); 11664 } 11665 } 11666 LLVM_FALLTHROUGH; 11667 11668 case BO_ShlAssign: 11669 return IntRange::forValueOfType(C, GetExprType(E)); 11670 11671 // Right shift by a constant can narrow its left argument. 11672 case BO_Shr: 11673 case BO_ShrAssign: { 11674 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11675 Approximate); 11676 11677 // If the shift amount is a positive constant, drop the width by 11678 // that much. 11679 if (Optional<llvm::APSInt> shift = 11680 BO->getRHS()->getIntegerConstantExpr(C)) { 11681 if (shift->isNonNegative()) { 11682 unsigned zext = shift->getZExtValue(); 11683 if (zext >= L.Width) 11684 L.Width = (L.NonNegative ? 0 : 1); 11685 else 11686 L.Width -= zext; 11687 } 11688 } 11689 11690 return L; 11691 } 11692 11693 // Comma acts as its right operand. 11694 case BO_Comma: 11695 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11696 Approximate); 11697 11698 case BO_Add: 11699 if (!Approximate) 11700 Combine = IntRange::sum; 11701 break; 11702 11703 case BO_Sub: 11704 if (BO->getLHS()->getType()->isPointerType()) 11705 return IntRange::forValueOfType(C, GetExprType(E)); 11706 if (!Approximate) 11707 Combine = IntRange::difference; 11708 break; 11709 11710 case BO_Mul: 11711 if (!Approximate) 11712 Combine = IntRange::product; 11713 break; 11714 11715 // The width of a division result is mostly determined by the size 11716 // of the LHS. 11717 case BO_Div: { 11718 // Don't 'pre-truncate' the operands. 11719 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11720 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11721 Approximate); 11722 11723 // If the divisor is constant, use that. 11724 if (Optional<llvm::APSInt> divisor = 11725 BO->getRHS()->getIntegerConstantExpr(C)) { 11726 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11727 if (log2 >= L.Width) 11728 L.Width = (L.NonNegative ? 0 : 1); 11729 else 11730 L.Width = std::min(L.Width - log2, MaxWidth); 11731 return L; 11732 } 11733 11734 // Otherwise, just use the LHS's width. 11735 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11736 // could be -1. 11737 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11738 Approximate); 11739 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11740 } 11741 11742 case BO_Rem: 11743 Combine = IntRange::rem; 11744 break; 11745 11746 // The default behavior is okay for these. 11747 case BO_Xor: 11748 case BO_Or: 11749 break; 11750 } 11751 11752 // Combine the two ranges, but limit the result to the type in which we 11753 // performed the computation. 11754 QualType T = GetExprType(E); 11755 unsigned opWidth = C.getIntWidth(T); 11756 IntRange L = 11757 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11758 IntRange R = 11759 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11760 IntRange C = Combine(L, R); 11761 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11762 C.Width = std::min(C.Width, MaxWidth); 11763 return C; 11764 } 11765 11766 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11767 switch (UO->getOpcode()) { 11768 // Boolean-valued operations are white-listed. 11769 case UO_LNot: 11770 return IntRange::forBoolType(); 11771 11772 // Operations with opaque sources are black-listed. 11773 case UO_Deref: 11774 case UO_AddrOf: // should be impossible 11775 return IntRange::forValueOfType(C, GetExprType(E)); 11776 11777 default: 11778 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11779 Approximate); 11780 } 11781 } 11782 11783 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11784 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11785 Approximate); 11786 11787 if (const auto *BitField = E->getSourceBitField()) 11788 return IntRange(BitField->getBitWidthValue(C), 11789 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11790 11791 return IntRange::forValueOfType(C, GetExprType(E)); 11792 } 11793 11794 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11795 bool InConstantContext, bool Approximate) { 11796 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11797 Approximate); 11798 } 11799 11800 /// Checks whether the given value, which currently has the given 11801 /// source semantics, has the same value when coerced through the 11802 /// target semantics. 11803 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11804 const llvm::fltSemantics &Src, 11805 const llvm::fltSemantics &Tgt) { 11806 llvm::APFloat truncated = value; 11807 11808 bool ignored; 11809 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11810 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11811 11812 return truncated.bitwiseIsEqual(value); 11813 } 11814 11815 /// Checks whether the given value, which currently has the given 11816 /// source semantics, has the same value when coerced through the 11817 /// target semantics. 11818 /// 11819 /// The value might be a vector of floats (or a complex number). 11820 static bool IsSameFloatAfterCast(const APValue &value, 11821 const llvm::fltSemantics &Src, 11822 const llvm::fltSemantics &Tgt) { 11823 if (value.isFloat()) 11824 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11825 11826 if (value.isVector()) { 11827 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11828 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11829 return false; 11830 return true; 11831 } 11832 11833 assert(value.isComplexFloat()); 11834 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11835 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11836 } 11837 11838 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11839 bool IsListInit = false); 11840 11841 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11842 // Suppress cases where we are comparing against an enum constant. 11843 if (const DeclRefExpr *DR = 11844 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11845 if (isa<EnumConstantDecl>(DR->getDecl())) 11846 return true; 11847 11848 // Suppress cases where the value is expanded from a macro, unless that macro 11849 // is how a language represents a boolean literal. This is the case in both C 11850 // and Objective-C. 11851 SourceLocation BeginLoc = E->getBeginLoc(); 11852 if (BeginLoc.isMacroID()) { 11853 StringRef MacroName = Lexer::getImmediateMacroName( 11854 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11855 return MacroName != "YES" && MacroName != "NO" && 11856 MacroName != "true" && MacroName != "false"; 11857 } 11858 11859 return false; 11860 } 11861 11862 static bool isKnownToHaveUnsignedValue(Expr *E) { 11863 return E->getType()->isIntegerType() && 11864 (!E->getType()->isSignedIntegerType() || 11865 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11866 } 11867 11868 namespace { 11869 /// The promoted range of values of a type. In general this has the 11870 /// following structure: 11871 /// 11872 /// |-----------| . . . |-----------| 11873 /// ^ ^ ^ ^ 11874 /// Min HoleMin HoleMax Max 11875 /// 11876 /// ... where there is only a hole if a signed type is promoted to unsigned 11877 /// (in which case Min and Max are the smallest and largest representable 11878 /// values). 11879 struct PromotedRange { 11880 // Min, or HoleMax if there is a hole. 11881 llvm::APSInt PromotedMin; 11882 // Max, or HoleMin if there is a hole. 11883 llvm::APSInt PromotedMax; 11884 11885 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11886 if (R.Width == 0) 11887 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11888 else if (R.Width >= BitWidth && !Unsigned) { 11889 // Promotion made the type *narrower*. This happens when promoting 11890 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11891 // Treat all values of 'signed int' as being in range for now. 11892 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11893 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11894 } else { 11895 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11896 .extOrTrunc(BitWidth); 11897 PromotedMin.setIsUnsigned(Unsigned); 11898 11899 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11900 .extOrTrunc(BitWidth); 11901 PromotedMax.setIsUnsigned(Unsigned); 11902 } 11903 } 11904 11905 // Determine whether this range is contiguous (has no hole). 11906 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11907 11908 // Where a constant value is within the range. 11909 enum ComparisonResult { 11910 LT = 0x1, 11911 LE = 0x2, 11912 GT = 0x4, 11913 GE = 0x8, 11914 EQ = 0x10, 11915 NE = 0x20, 11916 InRangeFlag = 0x40, 11917 11918 Less = LE | LT | NE, 11919 Min = LE | InRangeFlag, 11920 InRange = InRangeFlag, 11921 Max = GE | InRangeFlag, 11922 Greater = GE | GT | NE, 11923 11924 OnlyValue = LE | GE | EQ | InRangeFlag, 11925 InHole = NE 11926 }; 11927 11928 ComparisonResult compare(const llvm::APSInt &Value) const { 11929 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11930 Value.isUnsigned() == PromotedMin.isUnsigned()); 11931 if (!isContiguous()) { 11932 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11933 if (Value.isMinValue()) return Min; 11934 if (Value.isMaxValue()) return Max; 11935 if (Value >= PromotedMin) return InRange; 11936 if (Value <= PromotedMax) return InRange; 11937 return InHole; 11938 } 11939 11940 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11941 case -1: return Less; 11942 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11943 case 1: 11944 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11945 case -1: return InRange; 11946 case 0: return Max; 11947 case 1: return Greater; 11948 } 11949 } 11950 11951 llvm_unreachable("impossible compare result"); 11952 } 11953 11954 static llvm::Optional<StringRef> 11955 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11956 if (Op == BO_Cmp) { 11957 ComparisonResult LTFlag = LT, GTFlag = GT; 11958 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11959 11960 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11961 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11962 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11963 return llvm::None; 11964 } 11965 11966 ComparisonResult TrueFlag, FalseFlag; 11967 if (Op == BO_EQ) { 11968 TrueFlag = EQ; 11969 FalseFlag = NE; 11970 } else if (Op == BO_NE) { 11971 TrueFlag = NE; 11972 FalseFlag = EQ; 11973 } else { 11974 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11975 TrueFlag = LT; 11976 FalseFlag = GE; 11977 } else { 11978 TrueFlag = GT; 11979 FalseFlag = LE; 11980 } 11981 if (Op == BO_GE || Op == BO_LE) 11982 std::swap(TrueFlag, FalseFlag); 11983 } 11984 if (R & TrueFlag) 11985 return StringRef("true"); 11986 if (R & FalseFlag) 11987 return StringRef("false"); 11988 return llvm::None; 11989 } 11990 }; 11991 } 11992 11993 static bool HasEnumType(Expr *E) { 11994 // Strip off implicit integral promotions. 11995 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11996 if (ICE->getCastKind() != CK_IntegralCast && 11997 ICE->getCastKind() != CK_NoOp) 11998 break; 11999 E = ICE->getSubExpr(); 12000 } 12001 12002 return E->getType()->isEnumeralType(); 12003 } 12004 12005 static int classifyConstantValue(Expr *Constant) { 12006 // The values of this enumeration are used in the diagnostics 12007 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 12008 enum ConstantValueKind { 12009 Miscellaneous = 0, 12010 LiteralTrue, 12011 LiteralFalse 12012 }; 12013 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 12014 return BL->getValue() ? ConstantValueKind::LiteralTrue 12015 : ConstantValueKind::LiteralFalse; 12016 return ConstantValueKind::Miscellaneous; 12017 } 12018 12019 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 12020 Expr *Constant, Expr *Other, 12021 const llvm::APSInt &Value, 12022 bool RhsConstant) { 12023 if (S.inTemplateInstantiation()) 12024 return false; 12025 12026 Expr *OriginalOther = Other; 12027 12028 Constant = Constant->IgnoreParenImpCasts(); 12029 Other = Other->IgnoreParenImpCasts(); 12030 12031 // Suppress warnings on tautological comparisons between values of the same 12032 // enumeration type. There are only two ways we could warn on this: 12033 // - If the constant is outside the range of representable values of 12034 // the enumeration. In such a case, we should warn about the cast 12035 // to enumeration type, not about the comparison. 12036 // - If the constant is the maximum / minimum in-range value. For an 12037 // enumeratin type, such comparisons can be meaningful and useful. 12038 if (Constant->getType()->isEnumeralType() && 12039 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 12040 return false; 12041 12042 IntRange OtherValueRange = GetExprRange( 12043 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 12044 12045 QualType OtherT = Other->getType(); 12046 if (const auto *AT = OtherT->getAs<AtomicType>()) 12047 OtherT = AT->getValueType(); 12048 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 12049 12050 // Special case for ObjC BOOL on targets where its a typedef for a signed char 12051 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 12052 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 12053 S.NSAPIObj->isObjCBOOLType(OtherT) && 12054 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 12055 12056 // Whether we're treating Other as being a bool because of the form of 12057 // expression despite it having another type (typically 'int' in C). 12058 bool OtherIsBooleanDespiteType = 12059 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 12060 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 12061 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 12062 12063 // Check if all values in the range of possible values of this expression 12064 // lead to the same comparison outcome. 12065 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 12066 Value.isUnsigned()); 12067 auto Cmp = OtherPromotedValueRange.compare(Value); 12068 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 12069 if (!Result) 12070 return false; 12071 12072 // Also consider the range determined by the type alone. This allows us to 12073 // classify the warning under the proper diagnostic group. 12074 bool TautologicalTypeCompare = false; 12075 { 12076 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 12077 Value.isUnsigned()); 12078 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 12079 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 12080 RhsConstant)) { 12081 TautologicalTypeCompare = true; 12082 Cmp = TypeCmp; 12083 Result = TypeResult; 12084 } 12085 } 12086 12087 // Don't warn if the non-constant operand actually always evaluates to the 12088 // same value. 12089 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 12090 return false; 12091 12092 // Suppress the diagnostic for an in-range comparison if the constant comes 12093 // from a macro or enumerator. We don't want to diagnose 12094 // 12095 // some_long_value <= INT_MAX 12096 // 12097 // when sizeof(int) == sizeof(long). 12098 bool InRange = Cmp & PromotedRange::InRangeFlag; 12099 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 12100 return false; 12101 12102 // A comparison of an unsigned bit-field against 0 is really a type problem, 12103 // even though at the type level the bit-field might promote to 'signed int'. 12104 if (Other->refersToBitField() && InRange && Value == 0 && 12105 Other->getType()->isUnsignedIntegerOrEnumerationType()) 12106 TautologicalTypeCompare = true; 12107 12108 // If this is a comparison to an enum constant, include that 12109 // constant in the diagnostic. 12110 const EnumConstantDecl *ED = nullptr; 12111 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 12112 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 12113 12114 // Should be enough for uint128 (39 decimal digits) 12115 SmallString<64> PrettySourceValue; 12116 llvm::raw_svector_ostream OS(PrettySourceValue); 12117 if (ED) { 12118 OS << '\'' << *ED << "' (" << Value << ")"; 12119 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 12120 Constant->IgnoreParenImpCasts())) { 12121 OS << (BL->getValue() ? "YES" : "NO"); 12122 } else { 12123 OS << Value; 12124 } 12125 12126 if (!TautologicalTypeCompare) { 12127 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 12128 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 12129 << E->getOpcodeStr() << OS.str() << *Result 12130 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 12131 return true; 12132 } 12133 12134 if (IsObjCSignedCharBool) { 12135 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12136 S.PDiag(diag::warn_tautological_compare_objc_bool) 12137 << OS.str() << *Result); 12138 return true; 12139 } 12140 12141 // FIXME: We use a somewhat different formatting for the in-range cases and 12142 // cases involving boolean values for historical reasons. We should pick a 12143 // consistent way of presenting these diagnostics. 12144 if (!InRange || Other->isKnownToHaveBooleanValue()) { 12145 12146 S.DiagRuntimeBehavior( 12147 E->getOperatorLoc(), E, 12148 S.PDiag(!InRange ? diag::warn_out_of_range_compare 12149 : diag::warn_tautological_bool_compare) 12150 << OS.str() << classifyConstantValue(Constant) << OtherT 12151 << OtherIsBooleanDespiteType << *Result 12152 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 12153 } else { 12154 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 12155 unsigned Diag = 12156 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 12157 ? (HasEnumType(OriginalOther) 12158 ? diag::warn_unsigned_enum_always_true_comparison 12159 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 12160 : diag::warn_unsigned_always_true_comparison) 12161 : diag::warn_tautological_constant_compare; 12162 12163 S.Diag(E->getOperatorLoc(), Diag) 12164 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 12165 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 12166 } 12167 12168 return true; 12169 } 12170 12171 /// Analyze the operands of the given comparison. Implements the 12172 /// fallback case from AnalyzeComparison. 12173 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 12174 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12175 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12176 } 12177 12178 /// Implements -Wsign-compare. 12179 /// 12180 /// \param E the binary operator to check for warnings 12181 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 12182 // The type the comparison is being performed in. 12183 QualType T = E->getLHS()->getType(); 12184 12185 // Only analyze comparison operators where both sides have been converted to 12186 // the same type. 12187 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 12188 return AnalyzeImpConvsInComparison(S, E); 12189 12190 // Don't analyze value-dependent comparisons directly. 12191 if (E->isValueDependent()) 12192 return AnalyzeImpConvsInComparison(S, E); 12193 12194 Expr *LHS = E->getLHS(); 12195 Expr *RHS = E->getRHS(); 12196 12197 if (T->isIntegralType(S.Context)) { 12198 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 12199 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 12200 12201 // We don't care about expressions whose result is a constant. 12202 if (RHSValue && LHSValue) 12203 return AnalyzeImpConvsInComparison(S, E); 12204 12205 // We only care about expressions where just one side is literal 12206 if ((bool)RHSValue ^ (bool)LHSValue) { 12207 // Is the constant on the RHS or LHS? 12208 const bool RhsConstant = (bool)RHSValue; 12209 Expr *Const = RhsConstant ? RHS : LHS; 12210 Expr *Other = RhsConstant ? LHS : RHS; 12211 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 12212 12213 // Check whether an integer constant comparison results in a value 12214 // of 'true' or 'false'. 12215 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 12216 return AnalyzeImpConvsInComparison(S, E); 12217 } 12218 } 12219 12220 if (!T->hasUnsignedIntegerRepresentation()) { 12221 // We don't do anything special if this isn't an unsigned integral 12222 // comparison: we're only interested in integral comparisons, and 12223 // signed comparisons only happen in cases we don't care to warn about. 12224 return AnalyzeImpConvsInComparison(S, E); 12225 } 12226 12227 LHS = LHS->IgnoreParenImpCasts(); 12228 RHS = RHS->IgnoreParenImpCasts(); 12229 12230 if (!S.getLangOpts().CPlusPlus) { 12231 // Avoid warning about comparison of integers with different signs when 12232 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 12233 // the type of `E`. 12234 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 12235 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12236 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 12237 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12238 } 12239 12240 // Check to see if one of the (unmodified) operands is of different 12241 // signedness. 12242 Expr *signedOperand, *unsignedOperand; 12243 if (LHS->getType()->hasSignedIntegerRepresentation()) { 12244 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 12245 "unsigned comparison between two signed integer expressions?"); 12246 signedOperand = LHS; 12247 unsignedOperand = RHS; 12248 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 12249 signedOperand = RHS; 12250 unsignedOperand = LHS; 12251 } else { 12252 return AnalyzeImpConvsInComparison(S, E); 12253 } 12254 12255 // Otherwise, calculate the effective range of the signed operand. 12256 IntRange signedRange = GetExprRange( 12257 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 12258 12259 // Go ahead and analyze implicit conversions in the operands. Note 12260 // that we skip the implicit conversions on both sides. 12261 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 12262 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 12263 12264 // If the signed range is non-negative, -Wsign-compare won't fire. 12265 if (signedRange.NonNegative) 12266 return; 12267 12268 // For (in)equality comparisons, if the unsigned operand is a 12269 // constant which cannot collide with a overflowed signed operand, 12270 // then reinterpreting the signed operand as unsigned will not 12271 // change the result of the comparison. 12272 if (E->isEqualityOp()) { 12273 unsigned comparisonWidth = S.Context.getIntWidth(T); 12274 IntRange unsignedRange = 12275 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 12276 /*Approximate*/ true); 12277 12278 // We should never be unable to prove that the unsigned operand is 12279 // non-negative. 12280 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 12281 12282 if (unsignedRange.Width < comparisonWidth) 12283 return; 12284 } 12285 12286 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12287 S.PDiag(diag::warn_mixed_sign_comparison) 12288 << LHS->getType() << RHS->getType() 12289 << LHS->getSourceRange() << RHS->getSourceRange()); 12290 } 12291 12292 /// Analyzes an attempt to assign the given value to a bitfield. 12293 /// 12294 /// Returns true if there was something fishy about the attempt. 12295 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 12296 SourceLocation InitLoc) { 12297 assert(Bitfield->isBitField()); 12298 if (Bitfield->isInvalidDecl()) 12299 return false; 12300 12301 // White-list bool bitfields. 12302 QualType BitfieldType = Bitfield->getType(); 12303 if (BitfieldType->isBooleanType()) 12304 return false; 12305 12306 if (BitfieldType->isEnumeralType()) { 12307 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 12308 // If the underlying enum type was not explicitly specified as an unsigned 12309 // type and the enum contain only positive values, MSVC++ will cause an 12310 // inconsistency by storing this as a signed type. 12311 if (S.getLangOpts().CPlusPlus11 && 12312 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 12313 BitfieldEnumDecl->getNumPositiveBits() > 0 && 12314 BitfieldEnumDecl->getNumNegativeBits() == 0) { 12315 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 12316 << BitfieldEnumDecl; 12317 } 12318 } 12319 12320 if (Bitfield->getType()->isBooleanType()) 12321 return false; 12322 12323 // Ignore value- or type-dependent expressions. 12324 if (Bitfield->getBitWidth()->isValueDependent() || 12325 Bitfield->getBitWidth()->isTypeDependent() || 12326 Init->isValueDependent() || 12327 Init->isTypeDependent()) 12328 return false; 12329 12330 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 12331 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 12332 12333 Expr::EvalResult Result; 12334 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 12335 Expr::SE_AllowSideEffects)) { 12336 // The RHS is not constant. If the RHS has an enum type, make sure the 12337 // bitfield is wide enough to hold all the values of the enum without 12338 // truncation. 12339 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 12340 EnumDecl *ED = EnumTy->getDecl(); 12341 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 12342 12343 // Enum types are implicitly signed on Windows, so check if there are any 12344 // negative enumerators to see if the enum was intended to be signed or 12345 // not. 12346 bool SignedEnum = ED->getNumNegativeBits() > 0; 12347 12348 // Check for surprising sign changes when assigning enum values to a 12349 // bitfield of different signedness. If the bitfield is signed and we 12350 // have exactly the right number of bits to store this unsigned enum, 12351 // suggest changing the enum to an unsigned type. This typically happens 12352 // on Windows where unfixed enums always use an underlying type of 'int'. 12353 unsigned DiagID = 0; 12354 if (SignedEnum && !SignedBitfield) { 12355 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 12356 } else if (SignedBitfield && !SignedEnum && 12357 ED->getNumPositiveBits() == FieldWidth) { 12358 DiagID = diag::warn_signed_bitfield_enum_conversion; 12359 } 12360 12361 if (DiagID) { 12362 S.Diag(InitLoc, DiagID) << Bitfield << ED; 12363 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 12364 SourceRange TypeRange = 12365 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 12366 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 12367 << SignedEnum << TypeRange; 12368 } 12369 12370 // Compute the required bitwidth. If the enum has negative values, we need 12371 // one more bit than the normal number of positive bits to represent the 12372 // sign bit. 12373 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 12374 ED->getNumNegativeBits()) 12375 : ED->getNumPositiveBits(); 12376 12377 // Check the bitwidth. 12378 if (BitsNeeded > FieldWidth) { 12379 Expr *WidthExpr = Bitfield->getBitWidth(); 12380 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 12381 << Bitfield << ED; 12382 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 12383 << BitsNeeded << ED << WidthExpr->getSourceRange(); 12384 } 12385 } 12386 12387 return false; 12388 } 12389 12390 llvm::APSInt Value = Result.Val.getInt(); 12391 12392 unsigned OriginalWidth = Value.getBitWidth(); 12393 12394 if (!Value.isSigned() || Value.isNegative()) 12395 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12396 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12397 OriginalWidth = Value.getMinSignedBits(); 12398 12399 if (OriginalWidth <= FieldWidth) 12400 return false; 12401 12402 // Compute the value which the bitfield will contain. 12403 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12404 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12405 12406 // Check whether the stored value is equal to the original value. 12407 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12408 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12409 return false; 12410 12411 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12412 // therefore don't strictly fit into a signed bitfield of width 1. 12413 if (FieldWidth == 1 && Value == 1) 12414 return false; 12415 12416 std::string PrettyValue = toString(Value, 10); 12417 std::string PrettyTrunc = toString(TruncatedValue, 10); 12418 12419 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12420 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12421 << Init->getSourceRange(); 12422 12423 return true; 12424 } 12425 12426 /// Analyze the given simple or compound assignment for warning-worthy 12427 /// operations. 12428 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12429 // Just recurse on the LHS. 12430 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12431 12432 // We want to recurse on the RHS as normal unless we're assigning to 12433 // a bitfield. 12434 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12435 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12436 E->getOperatorLoc())) { 12437 // Recurse, ignoring any implicit conversions on the RHS. 12438 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12439 E->getOperatorLoc()); 12440 } 12441 } 12442 12443 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12444 12445 // Diagnose implicitly sequentially-consistent atomic assignment. 12446 if (E->getLHS()->getType()->isAtomicType()) 12447 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12448 } 12449 12450 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12451 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12452 SourceLocation CContext, unsigned diag, 12453 bool pruneControlFlow = false) { 12454 if (pruneControlFlow) { 12455 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12456 S.PDiag(diag) 12457 << SourceType << T << E->getSourceRange() 12458 << SourceRange(CContext)); 12459 return; 12460 } 12461 S.Diag(E->getExprLoc(), diag) 12462 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12463 } 12464 12465 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12466 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12467 SourceLocation CContext, 12468 unsigned diag, bool pruneControlFlow = false) { 12469 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12470 } 12471 12472 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12473 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12474 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12475 } 12476 12477 static void adornObjCBoolConversionDiagWithTernaryFixit( 12478 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12479 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12480 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12481 Ignored = OVE->getSourceExpr(); 12482 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12483 isa<BinaryOperator>(Ignored) || 12484 isa<CXXOperatorCallExpr>(Ignored); 12485 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12486 if (NeedsParens) 12487 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12488 << FixItHint::CreateInsertion(EndLoc, ")"); 12489 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12490 } 12491 12492 /// Diagnose an implicit cast from a floating point value to an integer value. 12493 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12494 SourceLocation CContext) { 12495 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12496 const bool PruneWarnings = S.inTemplateInstantiation(); 12497 12498 Expr *InnerE = E->IgnoreParenImpCasts(); 12499 // We also want to warn on, e.g., "int i = -1.234" 12500 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12501 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12502 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12503 12504 const bool IsLiteral = 12505 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12506 12507 llvm::APFloat Value(0.0); 12508 bool IsConstant = 12509 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12510 if (!IsConstant) { 12511 if (isObjCSignedCharBool(S, T)) { 12512 return adornObjCBoolConversionDiagWithTernaryFixit( 12513 S, E, 12514 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12515 << E->getType()); 12516 } 12517 12518 return DiagnoseImpCast(S, E, T, CContext, 12519 diag::warn_impcast_float_integer, PruneWarnings); 12520 } 12521 12522 bool isExact = false; 12523 12524 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12525 T->hasUnsignedIntegerRepresentation()); 12526 llvm::APFloat::opStatus Result = Value.convertToInteger( 12527 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12528 12529 // FIXME: Force the precision of the source value down so we don't print 12530 // digits which are usually useless (we don't really care here if we 12531 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12532 // would automatically print the shortest representation, but it's a bit 12533 // tricky to implement. 12534 SmallString<16> PrettySourceValue; 12535 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12536 precision = (precision * 59 + 195) / 196; 12537 Value.toString(PrettySourceValue, precision); 12538 12539 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12540 return adornObjCBoolConversionDiagWithTernaryFixit( 12541 S, E, 12542 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12543 << PrettySourceValue); 12544 } 12545 12546 if (Result == llvm::APFloat::opOK && isExact) { 12547 if (IsLiteral) return; 12548 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12549 PruneWarnings); 12550 } 12551 12552 // Conversion of a floating-point value to a non-bool integer where the 12553 // integral part cannot be represented by the integer type is undefined. 12554 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12555 return DiagnoseImpCast( 12556 S, E, T, CContext, 12557 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12558 : diag::warn_impcast_float_to_integer_out_of_range, 12559 PruneWarnings); 12560 12561 unsigned DiagID = 0; 12562 if (IsLiteral) { 12563 // Warn on floating point literal to integer. 12564 DiagID = diag::warn_impcast_literal_float_to_integer; 12565 } else if (IntegerValue == 0) { 12566 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12567 return DiagnoseImpCast(S, E, T, CContext, 12568 diag::warn_impcast_float_integer, PruneWarnings); 12569 } 12570 // Warn on non-zero to zero conversion. 12571 DiagID = diag::warn_impcast_float_to_integer_zero; 12572 } else { 12573 if (IntegerValue.isUnsigned()) { 12574 if (!IntegerValue.isMaxValue()) { 12575 return DiagnoseImpCast(S, E, T, CContext, 12576 diag::warn_impcast_float_integer, PruneWarnings); 12577 } 12578 } else { // IntegerValue.isSigned() 12579 if (!IntegerValue.isMaxSignedValue() && 12580 !IntegerValue.isMinSignedValue()) { 12581 return DiagnoseImpCast(S, E, T, CContext, 12582 diag::warn_impcast_float_integer, PruneWarnings); 12583 } 12584 } 12585 // Warn on evaluatable floating point expression to integer conversion. 12586 DiagID = diag::warn_impcast_float_to_integer; 12587 } 12588 12589 SmallString<16> PrettyTargetValue; 12590 if (IsBool) 12591 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12592 else 12593 IntegerValue.toString(PrettyTargetValue); 12594 12595 if (PruneWarnings) { 12596 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12597 S.PDiag(DiagID) 12598 << E->getType() << T.getUnqualifiedType() 12599 << PrettySourceValue << PrettyTargetValue 12600 << E->getSourceRange() << SourceRange(CContext)); 12601 } else { 12602 S.Diag(E->getExprLoc(), DiagID) 12603 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12604 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12605 } 12606 } 12607 12608 /// Analyze the given compound assignment for the possible losing of 12609 /// floating-point precision. 12610 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12611 assert(isa<CompoundAssignOperator>(E) && 12612 "Must be compound assignment operation"); 12613 // Recurse on the LHS and RHS in here 12614 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12615 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12616 12617 if (E->getLHS()->getType()->isAtomicType()) 12618 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12619 12620 // Now check the outermost expression 12621 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12622 const auto *RBT = cast<CompoundAssignOperator>(E) 12623 ->getComputationResultType() 12624 ->getAs<BuiltinType>(); 12625 12626 // The below checks assume source is floating point. 12627 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12628 12629 // If source is floating point but target is an integer. 12630 if (ResultBT->isInteger()) 12631 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12632 E->getExprLoc(), diag::warn_impcast_float_integer); 12633 12634 if (!ResultBT->isFloatingPoint()) 12635 return; 12636 12637 // If both source and target are floating points, warn about losing precision. 12638 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12639 QualType(ResultBT, 0), QualType(RBT, 0)); 12640 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12641 // warn about dropping FP rank. 12642 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12643 diag::warn_impcast_float_result_precision); 12644 } 12645 12646 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12647 IntRange Range) { 12648 if (!Range.Width) return "0"; 12649 12650 llvm::APSInt ValueInRange = Value; 12651 ValueInRange.setIsSigned(!Range.NonNegative); 12652 ValueInRange = ValueInRange.trunc(Range.Width); 12653 return toString(ValueInRange, 10); 12654 } 12655 12656 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12657 if (!isa<ImplicitCastExpr>(Ex)) 12658 return false; 12659 12660 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12661 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12662 const Type *Source = 12663 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12664 if (Target->isDependentType()) 12665 return false; 12666 12667 const BuiltinType *FloatCandidateBT = 12668 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12669 const Type *BoolCandidateType = ToBool ? Target : Source; 12670 12671 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12672 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12673 } 12674 12675 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12676 SourceLocation CC) { 12677 unsigned NumArgs = TheCall->getNumArgs(); 12678 for (unsigned i = 0; i < NumArgs; ++i) { 12679 Expr *CurrA = TheCall->getArg(i); 12680 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12681 continue; 12682 12683 bool IsSwapped = ((i > 0) && 12684 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12685 IsSwapped |= ((i < (NumArgs - 1)) && 12686 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12687 if (IsSwapped) { 12688 // Warn on this floating-point to bool conversion. 12689 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12690 CurrA->getType(), CC, 12691 diag::warn_impcast_floating_point_to_bool); 12692 } 12693 } 12694 } 12695 12696 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12697 SourceLocation CC) { 12698 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12699 E->getExprLoc())) 12700 return; 12701 12702 // Don't warn on functions which have return type nullptr_t. 12703 if (isa<CallExpr>(E)) 12704 return; 12705 12706 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12707 const Expr::NullPointerConstantKind NullKind = 12708 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12709 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12710 return; 12711 12712 // Return if target type is a safe conversion. 12713 if (T->isAnyPointerType() || T->isBlockPointerType() || 12714 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12715 return; 12716 12717 SourceLocation Loc = E->getSourceRange().getBegin(); 12718 12719 // Venture through the macro stacks to get to the source of macro arguments. 12720 // The new location is a better location than the complete location that was 12721 // passed in. 12722 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12723 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12724 12725 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12726 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12727 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12728 Loc, S.SourceMgr, S.getLangOpts()); 12729 if (MacroName == "NULL") 12730 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12731 } 12732 12733 // Only warn if the null and context location are in the same macro expansion. 12734 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12735 return; 12736 12737 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12738 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12739 << FixItHint::CreateReplacement(Loc, 12740 S.getFixItZeroLiteralForType(T, Loc)); 12741 } 12742 12743 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12744 ObjCArrayLiteral *ArrayLiteral); 12745 12746 static void 12747 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12748 ObjCDictionaryLiteral *DictionaryLiteral); 12749 12750 /// Check a single element within a collection literal against the 12751 /// target element type. 12752 static void checkObjCCollectionLiteralElement(Sema &S, 12753 QualType TargetElementType, 12754 Expr *Element, 12755 unsigned ElementKind) { 12756 // Skip a bitcast to 'id' or qualified 'id'. 12757 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12758 if (ICE->getCastKind() == CK_BitCast && 12759 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12760 Element = ICE->getSubExpr(); 12761 } 12762 12763 QualType ElementType = Element->getType(); 12764 ExprResult ElementResult(Element); 12765 if (ElementType->getAs<ObjCObjectPointerType>() && 12766 S.CheckSingleAssignmentConstraints(TargetElementType, 12767 ElementResult, 12768 false, false) 12769 != Sema::Compatible) { 12770 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12771 << ElementType << ElementKind << TargetElementType 12772 << Element->getSourceRange(); 12773 } 12774 12775 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12776 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12777 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12778 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12779 } 12780 12781 /// Check an Objective-C array literal being converted to the given 12782 /// target type. 12783 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12784 ObjCArrayLiteral *ArrayLiteral) { 12785 if (!S.NSArrayDecl) 12786 return; 12787 12788 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12789 if (!TargetObjCPtr) 12790 return; 12791 12792 if (TargetObjCPtr->isUnspecialized() || 12793 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12794 != S.NSArrayDecl->getCanonicalDecl()) 12795 return; 12796 12797 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12798 if (TypeArgs.size() != 1) 12799 return; 12800 12801 QualType TargetElementType = TypeArgs[0]; 12802 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12803 checkObjCCollectionLiteralElement(S, TargetElementType, 12804 ArrayLiteral->getElement(I), 12805 0); 12806 } 12807 } 12808 12809 /// Check an Objective-C dictionary literal being converted to the given 12810 /// target type. 12811 static void 12812 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12813 ObjCDictionaryLiteral *DictionaryLiteral) { 12814 if (!S.NSDictionaryDecl) 12815 return; 12816 12817 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12818 if (!TargetObjCPtr) 12819 return; 12820 12821 if (TargetObjCPtr->isUnspecialized() || 12822 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12823 != S.NSDictionaryDecl->getCanonicalDecl()) 12824 return; 12825 12826 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12827 if (TypeArgs.size() != 2) 12828 return; 12829 12830 QualType TargetKeyType = TypeArgs[0]; 12831 QualType TargetObjectType = TypeArgs[1]; 12832 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12833 auto Element = DictionaryLiteral->getKeyValueElement(I); 12834 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12835 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12836 } 12837 } 12838 12839 // Helper function to filter out cases for constant width constant conversion. 12840 // Don't warn on char array initialization or for non-decimal values. 12841 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12842 SourceLocation CC) { 12843 // If initializing from a constant, and the constant starts with '0', 12844 // then it is a binary, octal, or hexadecimal. Allow these constants 12845 // to fill all the bits, even if there is a sign change. 12846 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12847 const char FirstLiteralCharacter = 12848 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12849 if (FirstLiteralCharacter == '0') 12850 return false; 12851 } 12852 12853 // If the CC location points to a '{', and the type is char, then assume 12854 // assume it is an array initialization. 12855 if (CC.isValid() && T->isCharType()) { 12856 const char FirstContextCharacter = 12857 S.getSourceManager().getCharacterData(CC)[0]; 12858 if (FirstContextCharacter == '{') 12859 return false; 12860 } 12861 12862 return true; 12863 } 12864 12865 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12866 const auto *IL = dyn_cast<IntegerLiteral>(E); 12867 if (!IL) { 12868 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12869 if (UO->getOpcode() == UO_Minus) 12870 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12871 } 12872 } 12873 12874 return IL; 12875 } 12876 12877 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12878 E = E->IgnoreParenImpCasts(); 12879 SourceLocation ExprLoc = E->getExprLoc(); 12880 12881 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12882 BinaryOperator::Opcode Opc = BO->getOpcode(); 12883 Expr::EvalResult Result; 12884 // Do not diagnose unsigned shifts. 12885 if (Opc == BO_Shl) { 12886 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12887 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12888 if (LHS && LHS->getValue() == 0) 12889 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12890 else if (!E->isValueDependent() && LHS && RHS && 12891 RHS->getValue().isNonNegative() && 12892 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12893 S.Diag(ExprLoc, diag::warn_left_shift_always) 12894 << (Result.Val.getInt() != 0); 12895 else if (E->getType()->isSignedIntegerType()) 12896 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12897 } 12898 } 12899 12900 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12901 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12902 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12903 if (!LHS || !RHS) 12904 return; 12905 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12906 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12907 // Do not diagnose common idioms. 12908 return; 12909 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12910 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12911 } 12912 } 12913 12914 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12915 SourceLocation CC, 12916 bool *ICContext = nullptr, 12917 bool IsListInit = false) { 12918 if (E->isTypeDependent() || E->isValueDependent()) return; 12919 12920 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12921 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12922 if (Source == Target) return; 12923 if (Target->isDependentType()) return; 12924 12925 // If the conversion context location is invalid don't complain. We also 12926 // don't want to emit a warning if the issue occurs from the expansion of 12927 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12928 // delay this check as long as possible. Once we detect we are in that 12929 // scenario, we just return. 12930 if (CC.isInvalid()) 12931 return; 12932 12933 if (Source->isAtomicType()) 12934 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12935 12936 // Diagnose implicit casts to bool. 12937 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12938 if (isa<StringLiteral>(E)) 12939 // Warn on string literal to bool. Checks for string literals in logical 12940 // and expressions, for instance, assert(0 && "error here"), are 12941 // prevented by a check in AnalyzeImplicitConversions(). 12942 return DiagnoseImpCast(S, E, T, CC, 12943 diag::warn_impcast_string_literal_to_bool); 12944 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12945 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12946 // This covers the literal expressions that evaluate to Objective-C 12947 // objects. 12948 return DiagnoseImpCast(S, E, T, CC, 12949 diag::warn_impcast_objective_c_literal_to_bool); 12950 } 12951 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12952 // Warn on pointer to bool conversion that is always true. 12953 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12954 SourceRange(CC)); 12955 } 12956 } 12957 12958 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12959 // is a typedef for signed char (macOS), then that constant value has to be 1 12960 // or 0. 12961 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12962 Expr::EvalResult Result; 12963 if (E->EvaluateAsInt(Result, S.getASTContext(), 12964 Expr::SE_AllowSideEffects)) { 12965 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12966 adornObjCBoolConversionDiagWithTernaryFixit( 12967 S, E, 12968 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12969 << toString(Result.Val.getInt(), 10)); 12970 } 12971 return; 12972 } 12973 } 12974 12975 // Check implicit casts from Objective-C collection literals to specialized 12976 // collection types, e.g., NSArray<NSString *> *. 12977 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12978 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12979 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12980 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12981 12982 // Strip vector types. 12983 if (isa<VectorType>(Source)) { 12984 if (Target->isVLSTBuiltinType() && 12985 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 12986 QualType(Source, 0)) || 12987 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 12988 QualType(Source, 0)))) 12989 return; 12990 12991 if (!isa<VectorType>(Target)) { 12992 if (S.SourceMgr.isInSystemMacro(CC)) 12993 return; 12994 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12995 } 12996 12997 // If the vector cast is cast between two vectors of the same size, it is 12998 // a bitcast, not a conversion. 12999 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 13000 return; 13001 13002 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 13003 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 13004 } 13005 if (auto VecTy = dyn_cast<VectorType>(Target)) 13006 Target = VecTy->getElementType().getTypePtr(); 13007 13008 // Strip complex types. 13009 if (isa<ComplexType>(Source)) { 13010 if (!isa<ComplexType>(Target)) { 13011 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 13012 return; 13013 13014 return DiagnoseImpCast(S, E, T, CC, 13015 S.getLangOpts().CPlusPlus 13016 ? diag::err_impcast_complex_scalar 13017 : diag::warn_impcast_complex_scalar); 13018 } 13019 13020 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 13021 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 13022 } 13023 13024 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 13025 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 13026 13027 // If the source is floating point... 13028 if (SourceBT && SourceBT->isFloatingPoint()) { 13029 // ...and the target is floating point... 13030 if (TargetBT && TargetBT->isFloatingPoint()) { 13031 // ...then warn if we're dropping FP rank. 13032 13033 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 13034 QualType(SourceBT, 0), QualType(TargetBT, 0)); 13035 if (Order > 0) { 13036 // Don't warn about float constants that are precisely 13037 // representable in the target type. 13038 Expr::EvalResult result; 13039 if (E->EvaluateAsRValue(result, S.Context)) { 13040 // Value might be a float, a float vector, or a float complex. 13041 if (IsSameFloatAfterCast(result.Val, 13042 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 13043 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 13044 return; 13045 } 13046 13047 if (S.SourceMgr.isInSystemMacro(CC)) 13048 return; 13049 13050 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 13051 } 13052 // ... or possibly if we're increasing rank, too 13053 else if (Order < 0) { 13054 if (S.SourceMgr.isInSystemMacro(CC)) 13055 return; 13056 13057 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 13058 } 13059 return; 13060 } 13061 13062 // If the target is integral, always warn. 13063 if (TargetBT && TargetBT->isInteger()) { 13064 if (S.SourceMgr.isInSystemMacro(CC)) 13065 return; 13066 13067 DiagnoseFloatingImpCast(S, E, T, CC); 13068 } 13069 13070 // Detect the case where a call result is converted from floating-point to 13071 // to bool, and the final argument to the call is converted from bool, to 13072 // discover this typo: 13073 // 13074 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 13075 // 13076 // FIXME: This is an incredibly special case; is there some more general 13077 // way to detect this class of misplaced-parentheses bug? 13078 if (Target->isBooleanType() && isa<CallExpr>(E)) { 13079 // Check last argument of function call to see if it is an 13080 // implicit cast from a type matching the type the result 13081 // is being cast to. 13082 CallExpr *CEx = cast<CallExpr>(E); 13083 if (unsigned NumArgs = CEx->getNumArgs()) { 13084 Expr *LastA = CEx->getArg(NumArgs - 1); 13085 Expr *InnerE = LastA->IgnoreParenImpCasts(); 13086 if (isa<ImplicitCastExpr>(LastA) && 13087 InnerE->getType()->isBooleanType()) { 13088 // Warn on this floating-point to bool conversion 13089 DiagnoseImpCast(S, E, T, CC, 13090 diag::warn_impcast_floating_point_to_bool); 13091 } 13092 } 13093 } 13094 return; 13095 } 13096 13097 // Valid casts involving fixed point types should be accounted for here. 13098 if (Source->isFixedPointType()) { 13099 if (Target->isUnsaturatedFixedPointType()) { 13100 Expr::EvalResult Result; 13101 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 13102 S.isConstantEvaluated())) { 13103 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 13104 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 13105 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 13106 if (Value > MaxVal || Value < MinVal) { 13107 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13108 S.PDiag(diag::warn_impcast_fixed_point_range) 13109 << Value.toString() << T 13110 << E->getSourceRange() 13111 << clang::SourceRange(CC)); 13112 return; 13113 } 13114 } 13115 } else if (Target->isIntegerType()) { 13116 Expr::EvalResult Result; 13117 if (!S.isConstantEvaluated() && 13118 E->EvaluateAsFixedPoint(Result, S.Context, 13119 Expr::SE_AllowSideEffects)) { 13120 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 13121 13122 bool Overflowed; 13123 llvm::APSInt IntResult = FXResult.convertToInt( 13124 S.Context.getIntWidth(T), 13125 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 13126 13127 if (Overflowed) { 13128 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13129 S.PDiag(diag::warn_impcast_fixed_point_range) 13130 << FXResult.toString() << T 13131 << E->getSourceRange() 13132 << clang::SourceRange(CC)); 13133 return; 13134 } 13135 } 13136 } 13137 } else if (Target->isUnsaturatedFixedPointType()) { 13138 if (Source->isIntegerType()) { 13139 Expr::EvalResult Result; 13140 if (!S.isConstantEvaluated() && 13141 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 13142 llvm::APSInt Value = Result.Val.getInt(); 13143 13144 bool Overflowed; 13145 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 13146 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 13147 13148 if (Overflowed) { 13149 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13150 S.PDiag(diag::warn_impcast_fixed_point_range) 13151 << toString(Value, /*Radix=*/10) << T 13152 << E->getSourceRange() 13153 << clang::SourceRange(CC)); 13154 return; 13155 } 13156 } 13157 } 13158 } 13159 13160 // If we are casting an integer type to a floating point type without 13161 // initialization-list syntax, we might lose accuracy if the floating 13162 // point type has a narrower significand than the integer type. 13163 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 13164 TargetBT->isFloatingType() && !IsListInit) { 13165 // Determine the number of precision bits in the source integer type. 13166 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 13167 /*Approximate*/ true); 13168 unsigned int SourcePrecision = SourceRange.Width; 13169 13170 // Determine the number of precision bits in the 13171 // target floating point type. 13172 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 13173 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13174 13175 if (SourcePrecision > 0 && TargetPrecision > 0 && 13176 SourcePrecision > TargetPrecision) { 13177 13178 if (Optional<llvm::APSInt> SourceInt = 13179 E->getIntegerConstantExpr(S.Context)) { 13180 // If the source integer is a constant, convert it to the target 13181 // floating point type. Issue a warning if the value changes 13182 // during the whole conversion. 13183 llvm::APFloat TargetFloatValue( 13184 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13185 llvm::APFloat::opStatus ConversionStatus = 13186 TargetFloatValue.convertFromAPInt( 13187 *SourceInt, SourceBT->isSignedInteger(), 13188 llvm::APFloat::rmNearestTiesToEven); 13189 13190 if (ConversionStatus != llvm::APFloat::opOK) { 13191 SmallString<32> PrettySourceValue; 13192 SourceInt->toString(PrettySourceValue, 10); 13193 SmallString<32> PrettyTargetValue; 13194 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 13195 13196 S.DiagRuntimeBehavior( 13197 E->getExprLoc(), E, 13198 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 13199 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13200 << E->getSourceRange() << clang::SourceRange(CC)); 13201 } 13202 } else { 13203 // Otherwise, the implicit conversion may lose precision. 13204 DiagnoseImpCast(S, E, T, CC, 13205 diag::warn_impcast_integer_float_precision); 13206 } 13207 } 13208 } 13209 13210 DiagnoseNullConversion(S, E, T, CC); 13211 13212 S.DiscardMisalignedMemberAddress(Target, E); 13213 13214 if (Target->isBooleanType()) 13215 DiagnoseIntInBoolContext(S, E); 13216 13217 if (!Source->isIntegerType() || !Target->isIntegerType()) 13218 return; 13219 13220 // TODO: remove this early return once the false positives for constant->bool 13221 // in templates, macros, etc, are reduced or removed. 13222 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 13223 return; 13224 13225 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 13226 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 13227 return adornObjCBoolConversionDiagWithTernaryFixit( 13228 S, E, 13229 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 13230 << E->getType()); 13231 } 13232 13233 IntRange SourceTypeRange = 13234 IntRange::forTargetOfCanonicalType(S.Context, Source); 13235 IntRange LikelySourceRange = 13236 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 13237 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 13238 13239 if (LikelySourceRange.Width > TargetRange.Width) { 13240 // If the source is a constant, use a default-on diagnostic. 13241 // TODO: this should happen for bitfield stores, too. 13242 Expr::EvalResult Result; 13243 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 13244 S.isConstantEvaluated())) { 13245 llvm::APSInt Value(32); 13246 Value = Result.Val.getInt(); 13247 13248 if (S.SourceMgr.isInSystemMacro(CC)) 13249 return; 13250 13251 std::string PrettySourceValue = toString(Value, 10); 13252 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13253 13254 S.DiagRuntimeBehavior( 13255 E->getExprLoc(), E, 13256 S.PDiag(diag::warn_impcast_integer_precision_constant) 13257 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13258 << E->getSourceRange() << SourceRange(CC)); 13259 return; 13260 } 13261 13262 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 13263 if (S.SourceMgr.isInSystemMacro(CC)) 13264 return; 13265 13266 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 13267 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 13268 /* pruneControlFlow */ true); 13269 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 13270 } 13271 13272 if (TargetRange.Width > SourceTypeRange.Width) { 13273 if (auto *UO = dyn_cast<UnaryOperator>(E)) 13274 if (UO->getOpcode() == UO_Minus) 13275 if (Source->isUnsignedIntegerType()) { 13276 if (Target->isUnsignedIntegerType()) 13277 return DiagnoseImpCast(S, E, T, CC, 13278 diag::warn_impcast_high_order_zero_bits); 13279 if (Target->isSignedIntegerType()) 13280 return DiagnoseImpCast(S, E, T, CC, 13281 diag::warn_impcast_nonnegative_result); 13282 } 13283 } 13284 13285 if (TargetRange.Width == LikelySourceRange.Width && 13286 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 13287 Source->isSignedIntegerType()) { 13288 // Warn when doing a signed to signed conversion, warn if the positive 13289 // source value is exactly the width of the target type, which will 13290 // cause a negative value to be stored. 13291 13292 Expr::EvalResult Result; 13293 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 13294 !S.SourceMgr.isInSystemMacro(CC)) { 13295 llvm::APSInt Value = Result.Val.getInt(); 13296 if (isSameWidthConstantConversion(S, E, T, CC)) { 13297 std::string PrettySourceValue = toString(Value, 10); 13298 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13299 13300 S.DiagRuntimeBehavior( 13301 E->getExprLoc(), E, 13302 S.PDiag(diag::warn_impcast_integer_precision_constant) 13303 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13304 << E->getSourceRange() << SourceRange(CC)); 13305 return; 13306 } 13307 } 13308 13309 // Fall through for non-constants to give a sign conversion warning. 13310 } 13311 13312 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 13313 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 13314 LikelySourceRange.Width == TargetRange.Width)) { 13315 if (S.SourceMgr.isInSystemMacro(CC)) 13316 return; 13317 13318 unsigned DiagID = diag::warn_impcast_integer_sign; 13319 13320 // Traditionally, gcc has warned about this under -Wsign-compare. 13321 // We also want to warn about it in -Wconversion. 13322 // So if -Wconversion is off, use a completely identical diagnostic 13323 // in the sign-compare group. 13324 // The conditional-checking code will 13325 if (ICContext) { 13326 DiagID = diag::warn_impcast_integer_sign_conditional; 13327 *ICContext = true; 13328 } 13329 13330 return DiagnoseImpCast(S, E, T, CC, DiagID); 13331 } 13332 13333 // Diagnose conversions between different enumeration types. 13334 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 13335 // type, to give us better diagnostics. 13336 QualType SourceType = E->getType(); 13337 if (!S.getLangOpts().CPlusPlus) { 13338 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13339 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 13340 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 13341 SourceType = S.Context.getTypeDeclType(Enum); 13342 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 13343 } 13344 } 13345 13346 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 13347 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 13348 if (SourceEnum->getDecl()->hasNameForLinkage() && 13349 TargetEnum->getDecl()->hasNameForLinkage() && 13350 SourceEnum != TargetEnum) { 13351 if (S.SourceMgr.isInSystemMacro(CC)) 13352 return; 13353 13354 return DiagnoseImpCast(S, E, SourceType, T, CC, 13355 diag::warn_impcast_different_enum_types); 13356 } 13357 } 13358 13359 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13360 SourceLocation CC, QualType T); 13361 13362 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 13363 SourceLocation CC, bool &ICContext) { 13364 E = E->IgnoreParenImpCasts(); 13365 13366 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 13367 return CheckConditionalOperator(S, CO, CC, T); 13368 13369 AnalyzeImplicitConversions(S, E, CC); 13370 if (E->getType() != T) 13371 return CheckImplicitConversion(S, E, T, CC, &ICContext); 13372 } 13373 13374 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13375 SourceLocation CC, QualType T) { 13376 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 13377 13378 Expr *TrueExpr = E->getTrueExpr(); 13379 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 13380 TrueExpr = BCO->getCommon(); 13381 13382 bool Suspicious = false; 13383 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 13384 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 13385 13386 if (T->isBooleanType()) 13387 DiagnoseIntInBoolContext(S, E); 13388 13389 // If -Wconversion would have warned about either of the candidates 13390 // for a signedness conversion to the context type... 13391 if (!Suspicious) return; 13392 13393 // ...but it's currently ignored... 13394 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13395 return; 13396 13397 // ...then check whether it would have warned about either of the 13398 // candidates for a signedness conversion to the condition type. 13399 if (E->getType() == T) return; 13400 13401 Suspicious = false; 13402 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13403 E->getType(), CC, &Suspicious); 13404 if (!Suspicious) 13405 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13406 E->getType(), CC, &Suspicious); 13407 } 13408 13409 /// Check conversion of given expression to boolean. 13410 /// Input argument E is a logical expression. 13411 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13412 if (S.getLangOpts().Bool) 13413 return; 13414 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13415 return; 13416 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13417 } 13418 13419 namespace { 13420 struct AnalyzeImplicitConversionsWorkItem { 13421 Expr *E; 13422 SourceLocation CC; 13423 bool IsListInit; 13424 }; 13425 } 13426 13427 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13428 /// that should be visited are added to WorkList. 13429 static void AnalyzeImplicitConversions( 13430 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13431 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13432 Expr *OrigE = Item.E; 13433 SourceLocation CC = Item.CC; 13434 13435 QualType T = OrigE->getType(); 13436 Expr *E = OrigE->IgnoreParenImpCasts(); 13437 13438 // Propagate whether we are in a C++ list initialization expression. 13439 // If so, we do not issue warnings for implicit int-float conversion 13440 // precision loss, because C++11 narrowing already handles it. 13441 bool IsListInit = Item.IsListInit || 13442 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13443 13444 if (E->isTypeDependent() || E->isValueDependent()) 13445 return; 13446 13447 Expr *SourceExpr = E; 13448 // Examine, but don't traverse into the source expression of an 13449 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13450 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13451 // evaluate it in the context of checking the specific conversion to T though. 13452 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13453 if (auto *Src = OVE->getSourceExpr()) 13454 SourceExpr = Src; 13455 13456 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13457 if (UO->getOpcode() == UO_Not && 13458 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13459 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13460 << OrigE->getSourceRange() << T->isBooleanType() 13461 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13462 13463 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) 13464 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && 13465 BO->getLHS()->isKnownToHaveBooleanValue() && 13466 BO->getRHS()->isKnownToHaveBooleanValue() && 13467 BO->getLHS()->HasSideEffects(S.Context) && 13468 BO->getRHS()->HasSideEffects(S.Context)) { 13469 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) 13470 << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange() 13471 << FixItHint::CreateReplacement( 13472 BO->getOperatorLoc(), 13473 (BO->getOpcode() == BO_And ? "&&" : "||")); 13474 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int); 13475 } 13476 13477 // For conditional operators, we analyze the arguments as if they 13478 // were being fed directly into the output. 13479 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13480 CheckConditionalOperator(S, CO, CC, T); 13481 return; 13482 } 13483 13484 // Check implicit argument conversions for function calls. 13485 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13486 CheckImplicitArgumentConversions(S, Call, CC); 13487 13488 // Go ahead and check any implicit conversions we might have skipped. 13489 // The non-canonical typecheck is just an optimization; 13490 // CheckImplicitConversion will filter out dead implicit conversions. 13491 if (SourceExpr->getType() != T) 13492 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13493 13494 // Now continue drilling into this expression. 13495 13496 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13497 // The bound subexpressions in a PseudoObjectExpr are not reachable 13498 // as transitive children. 13499 // FIXME: Use a more uniform representation for this. 13500 for (auto *SE : POE->semantics()) 13501 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13502 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13503 } 13504 13505 // Skip past explicit casts. 13506 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13507 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13508 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13509 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13510 WorkList.push_back({E, CC, IsListInit}); 13511 return; 13512 } 13513 13514 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13515 // Do a somewhat different check with comparison operators. 13516 if (BO->isComparisonOp()) 13517 return AnalyzeComparison(S, BO); 13518 13519 // And with simple assignments. 13520 if (BO->getOpcode() == BO_Assign) 13521 return AnalyzeAssignment(S, BO); 13522 // And with compound assignments. 13523 if (BO->isAssignmentOp()) 13524 return AnalyzeCompoundAssignment(S, BO); 13525 } 13526 13527 // These break the otherwise-useful invariant below. Fortunately, 13528 // we don't really need to recurse into them, because any internal 13529 // expressions should have been analyzed already when they were 13530 // built into statements. 13531 if (isa<StmtExpr>(E)) return; 13532 13533 // Don't descend into unevaluated contexts. 13534 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13535 13536 // Now just recurse over the expression's children. 13537 CC = E->getExprLoc(); 13538 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13539 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13540 for (Stmt *SubStmt : E->children()) { 13541 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13542 if (!ChildExpr) 13543 continue; 13544 13545 if (IsLogicalAndOperator && 13546 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13547 // Ignore checking string literals that are in logical and operators. 13548 // This is a common pattern for asserts. 13549 continue; 13550 WorkList.push_back({ChildExpr, CC, IsListInit}); 13551 } 13552 13553 if (BO && BO->isLogicalOp()) { 13554 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13555 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13556 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13557 13558 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13559 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13560 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13561 } 13562 13563 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13564 if (U->getOpcode() == UO_LNot) { 13565 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13566 } else if (U->getOpcode() != UO_AddrOf) { 13567 if (U->getSubExpr()->getType()->isAtomicType()) 13568 S.Diag(U->getSubExpr()->getBeginLoc(), 13569 diag::warn_atomic_implicit_seq_cst); 13570 } 13571 } 13572 } 13573 13574 /// AnalyzeImplicitConversions - Find and report any interesting 13575 /// implicit conversions in the given expression. There are a couple 13576 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13577 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13578 bool IsListInit/*= false*/) { 13579 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13580 WorkList.push_back({OrigE, CC, IsListInit}); 13581 while (!WorkList.empty()) 13582 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13583 } 13584 13585 /// Diagnose integer type and any valid implicit conversion to it. 13586 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13587 // Taking into account implicit conversions, 13588 // allow any integer. 13589 if (!E->getType()->isIntegerType()) { 13590 S.Diag(E->getBeginLoc(), 13591 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13592 return true; 13593 } 13594 // Potentially emit standard warnings for implicit conversions if enabled 13595 // using -Wconversion. 13596 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13597 return false; 13598 } 13599 13600 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13601 // Returns true when emitting a warning about taking the address of a reference. 13602 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13603 const PartialDiagnostic &PD) { 13604 E = E->IgnoreParenImpCasts(); 13605 13606 const FunctionDecl *FD = nullptr; 13607 13608 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13609 if (!DRE->getDecl()->getType()->isReferenceType()) 13610 return false; 13611 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13612 if (!M->getMemberDecl()->getType()->isReferenceType()) 13613 return false; 13614 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13615 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13616 return false; 13617 FD = Call->getDirectCallee(); 13618 } else { 13619 return false; 13620 } 13621 13622 SemaRef.Diag(E->getExprLoc(), PD); 13623 13624 // If possible, point to location of function. 13625 if (FD) { 13626 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13627 } 13628 13629 return true; 13630 } 13631 13632 // Returns true if the SourceLocation is expanded from any macro body. 13633 // Returns false if the SourceLocation is invalid, is from not in a macro 13634 // expansion, or is from expanded from a top-level macro argument. 13635 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13636 if (Loc.isInvalid()) 13637 return false; 13638 13639 while (Loc.isMacroID()) { 13640 if (SM.isMacroBodyExpansion(Loc)) 13641 return true; 13642 Loc = SM.getImmediateMacroCallerLoc(Loc); 13643 } 13644 13645 return false; 13646 } 13647 13648 /// Diagnose pointers that are always non-null. 13649 /// \param E the expression containing the pointer 13650 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13651 /// compared to a null pointer 13652 /// \param IsEqual True when the comparison is equal to a null pointer 13653 /// \param Range Extra SourceRange to highlight in the diagnostic 13654 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13655 Expr::NullPointerConstantKind NullKind, 13656 bool IsEqual, SourceRange Range) { 13657 if (!E) 13658 return; 13659 13660 // Don't warn inside macros. 13661 if (E->getExprLoc().isMacroID()) { 13662 const SourceManager &SM = getSourceManager(); 13663 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13664 IsInAnyMacroBody(SM, Range.getBegin())) 13665 return; 13666 } 13667 E = E->IgnoreImpCasts(); 13668 13669 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13670 13671 if (isa<CXXThisExpr>(E)) { 13672 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13673 : diag::warn_this_bool_conversion; 13674 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13675 return; 13676 } 13677 13678 bool IsAddressOf = false; 13679 13680 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13681 if (UO->getOpcode() != UO_AddrOf) 13682 return; 13683 IsAddressOf = true; 13684 E = UO->getSubExpr(); 13685 } 13686 13687 if (IsAddressOf) { 13688 unsigned DiagID = IsCompare 13689 ? diag::warn_address_of_reference_null_compare 13690 : diag::warn_address_of_reference_bool_conversion; 13691 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13692 << IsEqual; 13693 if (CheckForReference(*this, E, PD)) { 13694 return; 13695 } 13696 } 13697 13698 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13699 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13700 std::string Str; 13701 llvm::raw_string_ostream S(Str); 13702 E->printPretty(S, nullptr, getPrintingPolicy()); 13703 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13704 : diag::warn_cast_nonnull_to_bool; 13705 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13706 << E->getSourceRange() << Range << IsEqual; 13707 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13708 }; 13709 13710 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13711 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13712 if (auto *Callee = Call->getDirectCallee()) { 13713 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13714 ComplainAboutNonnullParamOrCall(A); 13715 return; 13716 } 13717 } 13718 } 13719 13720 // Expect to find a single Decl. Skip anything more complicated. 13721 ValueDecl *D = nullptr; 13722 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13723 D = R->getDecl(); 13724 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13725 D = M->getMemberDecl(); 13726 } 13727 13728 // Weak Decls can be null. 13729 if (!D || D->isWeak()) 13730 return; 13731 13732 // Check for parameter decl with nonnull attribute 13733 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13734 if (getCurFunction() && 13735 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13736 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13737 ComplainAboutNonnullParamOrCall(A); 13738 return; 13739 } 13740 13741 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13742 // Skip function template not specialized yet. 13743 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13744 return; 13745 auto ParamIter = llvm::find(FD->parameters(), PV); 13746 assert(ParamIter != FD->param_end()); 13747 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13748 13749 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13750 if (!NonNull->args_size()) { 13751 ComplainAboutNonnullParamOrCall(NonNull); 13752 return; 13753 } 13754 13755 for (const ParamIdx &ArgNo : NonNull->args()) { 13756 if (ArgNo.getASTIndex() == ParamNo) { 13757 ComplainAboutNonnullParamOrCall(NonNull); 13758 return; 13759 } 13760 } 13761 } 13762 } 13763 } 13764 } 13765 13766 QualType T = D->getType(); 13767 const bool IsArray = T->isArrayType(); 13768 const bool IsFunction = T->isFunctionType(); 13769 13770 // Address of function is used to silence the function warning. 13771 if (IsAddressOf && IsFunction) { 13772 return; 13773 } 13774 13775 // Found nothing. 13776 if (!IsAddressOf && !IsFunction && !IsArray) 13777 return; 13778 13779 // Pretty print the expression for the diagnostic. 13780 std::string Str; 13781 llvm::raw_string_ostream S(Str); 13782 E->printPretty(S, nullptr, getPrintingPolicy()); 13783 13784 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13785 : diag::warn_impcast_pointer_to_bool; 13786 enum { 13787 AddressOf, 13788 FunctionPointer, 13789 ArrayPointer 13790 } DiagType; 13791 if (IsAddressOf) 13792 DiagType = AddressOf; 13793 else if (IsFunction) 13794 DiagType = FunctionPointer; 13795 else if (IsArray) 13796 DiagType = ArrayPointer; 13797 else 13798 llvm_unreachable("Could not determine diagnostic."); 13799 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13800 << Range << IsEqual; 13801 13802 if (!IsFunction) 13803 return; 13804 13805 // Suggest '&' to silence the function warning. 13806 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13807 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13808 13809 // Check to see if '()' fixit should be emitted. 13810 QualType ReturnType; 13811 UnresolvedSet<4> NonTemplateOverloads; 13812 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13813 if (ReturnType.isNull()) 13814 return; 13815 13816 if (IsCompare) { 13817 // There are two cases here. If there is null constant, the only suggest 13818 // for a pointer return type. If the null is 0, then suggest if the return 13819 // type is a pointer or an integer type. 13820 if (!ReturnType->isPointerType()) { 13821 if (NullKind == Expr::NPCK_ZeroExpression || 13822 NullKind == Expr::NPCK_ZeroLiteral) { 13823 if (!ReturnType->isIntegerType()) 13824 return; 13825 } else { 13826 return; 13827 } 13828 } 13829 } else { // !IsCompare 13830 // For function to bool, only suggest if the function pointer has bool 13831 // return type. 13832 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13833 return; 13834 } 13835 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13836 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13837 } 13838 13839 /// Diagnoses "dangerous" implicit conversions within the given 13840 /// expression (which is a full expression). Implements -Wconversion 13841 /// and -Wsign-compare. 13842 /// 13843 /// \param CC the "context" location of the implicit conversion, i.e. 13844 /// the most location of the syntactic entity requiring the implicit 13845 /// conversion 13846 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13847 // Don't diagnose in unevaluated contexts. 13848 if (isUnevaluatedContext()) 13849 return; 13850 13851 // Don't diagnose for value- or type-dependent expressions. 13852 if (E->isTypeDependent() || E->isValueDependent()) 13853 return; 13854 13855 // Check for array bounds violations in cases where the check isn't triggered 13856 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13857 // ArraySubscriptExpr is on the RHS of a variable initialization. 13858 CheckArrayAccess(E); 13859 13860 // This is not the right CC for (e.g.) a variable initialization. 13861 AnalyzeImplicitConversions(*this, E, CC); 13862 } 13863 13864 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13865 /// Input argument E is a logical expression. 13866 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13867 ::CheckBoolLikeConversion(*this, E, CC); 13868 } 13869 13870 /// Diagnose when expression is an integer constant expression and its evaluation 13871 /// results in integer overflow 13872 void Sema::CheckForIntOverflow (Expr *E) { 13873 // Use a work list to deal with nested struct initializers. 13874 SmallVector<Expr *, 2> Exprs(1, E); 13875 13876 do { 13877 Expr *OriginalE = Exprs.pop_back_val(); 13878 Expr *E = OriginalE->IgnoreParenCasts(); 13879 13880 if (isa<BinaryOperator>(E)) { 13881 E->EvaluateForOverflow(Context); 13882 continue; 13883 } 13884 13885 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13886 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13887 else if (isa<ObjCBoxedExpr>(OriginalE)) 13888 E->EvaluateForOverflow(Context); 13889 else if (auto Call = dyn_cast<CallExpr>(E)) 13890 Exprs.append(Call->arg_begin(), Call->arg_end()); 13891 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13892 Exprs.append(Message->arg_begin(), Message->arg_end()); 13893 } while (!Exprs.empty()); 13894 } 13895 13896 namespace { 13897 13898 /// Visitor for expressions which looks for unsequenced operations on the 13899 /// same object. 13900 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13901 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13902 13903 /// A tree of sequenced regions within an expression. Two regions are 13904 /// unsequenced if one is an ancestor or a descendent of the other. When we 13905 /// finish processing an expression with sequencing, such as a comma 13906 /// expression, we fold its tree nodes into its parent, since they are 13907 /// unsequenced with respect to nodes we will visit later. 13908 class SequenceTree { 13909 struct Value { 13910 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13911 unsigned Parent : 31; 13912 unsigned Merged : 1; 13913 }; 13914 SmallVector<Value, 8> Values; 13915 13916 public: 13917 /// A region within an expression which may be sequenced with respect 13918 /// to some other region. 13919 class Seq { 13920 friend class SequenceTree; 13921 13922 unsigned Index; 13923 13924 explicit Seq(unsigned N) : Index(N) {} 13925 13926 public: 13927 Seq() : Index(0) {} 13928 }; 13929 13930 SequenceTree() { Values.push_back(Value(0)); } 13931 Seq root() const { return Seq(0); } 13932 13933 /// Create a new sequence of operations, which is an unsequenced 13934 /// subset of \p Parent. This sequence of operations is sequenced with 13935 /// respect to other children of \p Parent. 13936 Seq allocate(Seq Parent) { 13937 Values.push_back(Value(Parent.Index)); 13938 return Seq(Values.size() - 1); 13939 } 13940 13941 /// Merge a sequence of operations into its parent. 13942 void merge(Seq S) { 13943 Values[S.Index].Merged = true; 13944 } 13945 13946 /// Determine whether two operations are unsequenced. This operation 13947 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13948 /// should have been merged into its parent as appropriate. 13949 bool isUnsequenced(Seq Cur, Seq Old) { 13950 unsigned C = representative(Cur.Index); 13951 unsigned Target = representative(Old.Index); 13952 while (C >= Target) { 13953 if (C == Target) 13954 return true; 13955 C = Values[C].Parent; 13956 } 13957 return false; 13958 } 13959 13960 private: 13961 /// Pick a representative for a sequence. 13962 unsigned representative(unsigned K) { 13963 if (Values[K].Merged) 13964 // Perform path compression as we go. 13965 return Values[K].Parent = representative(Values[K].Parent); 13966 return K; 13967 } 13968 }; 13969 13970 /// An object for which we can track unsequenced uses. 13971 using Object = const NamedDecl *; 13972 13973 /// Different flavors of object usage which we track. We only track the 13974 /// least-sequenced usage of each kind. 13975 enum UsageKind { 13976 /// A read of an object. Multiple unsequenced reads are OK. 13977 UK_Use, 13978 13979 /// A modification of an object which is sequenced before the value 13980 /// computation of the expression, such as ++n in C++. 13981 UK_ModAsValue, 13982 13983 /// A modification of an object which is not sequenced before the value 13984 /// computation of the expression, such as n++. 13985 UK_ModAsSideEffect, 13986 13987 UK_Count = UK_ModAsSideEffect + 1 13988 }; 13989 13990 /// Bundle together a sequencing region and the expression corresponding 13991 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13992 struct Usage { 13993 const Expr *UsageExpr; 13994 SequenceTree::Seq Seq; 13995 13996 Usage() : UsageExpr(nullptr), Seq() {} 13997 }; 13998 13999 struct UsageInfo { 14000 Usage Uses[UK_Count]; 14001 14002 /// Have we issued a diagnostic for this object already? 14003 bool Diagnosed; 14004 14005 UsageInfo() : Uses(), Diagnosed(false) {} 14006 }; 14007 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 14008 14009 Sema &SemaRef; 14010 14011 /// Sequenced regions within the expression. 14012 SequenceTree Tree; 14013 14014 /// Declaration modifications and references which we have seen. 14015 UsageInfoMap UsageMap; 14016 14017 /// The region we are currently within. 14018 SequenceTree::Seq Region; 14019 14020 /// Filled in with declarations which were modified as a side-effect 14021 /// (that is, post-increment operations). 14022 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 14023 14024 /// Expressions to check later. We defer checking these to reduce 14025 /// stack usage. 14026 SmallVectorImpl<const Expr *> &WorkList; 14027 14028 /// RAII object wrapping the visitation of a sequenced subexpression of an 14029 /// expression. At the end of this process, the side-effects of the evaluation 14030 /// become sequenced with respect to the value computation of the result, so 14031 /// we downgrade any UK_ModAsSideEffect within the evaluation to 14032 /// UK_ModAsValue. 14033 struct SequencedSubexpression { 14034 SequencedSubexpression(SequenceChecker &Self) 14035 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 14036 Self.ModAsSideEffect = &ModAsSideEffect; 14037 } 14038 14039 ~SequencedSubexpression() { 14040 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 14041 // Add a new usage with usage kind UK_ModAsValue, and then restore 14042 // the previous usage with UK_ModAsSideEffect (thus clearing it if 14043 // the previous one was empty). 14044 UsageInfo &UI = Self.UsageMap[M.first]; 14045 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 14046 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 14047 SideEffectUsage = M.second; 14048 } 14049 Self.ModAsSideEffect = OldModAsSideEffect; 14050 } 14051 14052 SequenceChecker &Self; 14053 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 14054 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 14055 }; 14056 14057 /// RAII object wrapping the visitation of a subexpression which we might 14058 /// choose to evaluate as a constant. If any subexpression is evaluated and 14059 /// found to be non-constant, this allows us to suppress the evaluation of 14060 /// the outer expression. 14061 class EvaluationTracker { 14062 public: 14063 EvaluationTracker(SequenceChecker &Self) 14064 : Self(Self), Prev(Self.EvalTracker) { 14065 Self.EvalTracker = this; 14066 } 14067 14068 ~EvaluationTracker() { 14069 Self.EvalTracker = Prev; 14070 if (Prev) 14071 Prev->EvalOK &= EvalOK; 14072 } 14073 14074 bool evaluate(const Expr *E, bool &Result) { 14075 if (!EvalOK || E->isValueDependent()) 14076 return false; 14077 EvalOK = E->EvaluateAsBooleanCondition( 14078 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 14079 return EvalOK; 14080 } 14081 14082 private: 14083 SequenceChecker &Self; 14084 EvaluationTracker *Prev; 14085 bool EvalOK = true; 14086 } *EvalTracker = nullptr; 14087 14088 /// Find the object which is produced by the specified expression, 14089 /// if any. 14090 Object getObject(const Expr *E, bool Mod) const { 14091 E = E->IgnoreParenCasts(); 14092 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 14093 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 14094 return getObject(UO->getSubExpr(), Mod); 14095 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 14096 if (BO->getOpcode() == BO_Comma) 14097 return getObject(BO->getRHS(), Mod); 14098 if (Mod && BO->isAssignmentOp()) 14099 return getObject(BO->getLHS(), Mod); 14100 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14101 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 14102 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 14103 return ME->getMemberDecl(); 14104 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 14105 // FIXME: If this is a reference, map through to its value. 14106 return DRE->getDecl(); 14107 return nullptr; 14108 } 14109 14110 /// Note that an object \p O was modified or used by an expression 14111 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 14112 /// the object \p O as obtained via the \p UsageMap. 14113 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 14114 // Get the old usage for the given object and usage kind. 14115 Usage &U = UI.Uses[UK]; 14116 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 14117 // If we have a modification as side effect and are in a sequenced 14118 // subexpression, save the old Usage so that we can restore it later 14119 // in SequencedSubexpression::~SequencedSubexpression. 14120 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 14121 ModAsSideEffect->push_back(std::make_pair(O, U)); 14122 // Then record the new usage with the current sequencing region. 14123 U.UsageExpr = UsageExpr; 14124 U.Seq = Region; 14125 } 14126 } 14127 14128 /// Check whether a modification or use of an object \p O in an expression 14129 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 14130 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 14131 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 14132 /// usage and false we are checking for a mod-use unsequenced usage. 14133 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 14134 UsageKind OtherKind, bool IsModMod) { 14135 if (UI.Diagnosed) 14136 return; 14137 14138 const Usage &U = UI.Uses[OtherKind]; 14139 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 14140 return; 14141 14142 const Expr *Mod = U.UsageExpr; 14143 const Expr *ModOrUse = UsageExpr; 14144 if (OtherKind == UK_Use) 14145 std::swap(Mod, ModOrUse); 14146 14147 SemaRef.DiagRuntimeBehavior( 14148 Mod->getExprLoc(), {Mod, ModOrUse}, 14149 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 14150 : diag::warn_unsequenced_mod_use) 14151 << O << SourceRange(ModOrUse->getExprLoc())); 14152 UI.Diagnosed = true; 14153 } 14154 14155 // A note on note{Pre, Post}{Use, Mod}: 14156 // 14157 // (It helps to follow the algorithm with an expression such as 14158 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 14159 // operations before C++17 and both are well-defined in C++17). 14160 // 14161 // When visiting a node which uses/modify an object we first call notePreUse 14162 // or notePreMod before visiting its sub-expression(s). At this point the 14163 // children of the current node have not yet been visited and so the eventual 14164 // uses/modifications resulting from the children of the current node have not 14165 // been recorded yet. 14166 // 14167 // We then visit the children of the current node. After that notePostUse or 14168 // notePostMod is called. These will 1) detect an unsequenced modification 14169 // as side effect (as in "k++ + k") and 2) add a new usage with the 14170 // appropriate usage kind. 14171 // 14172 // We also have to be careful that some operation sequences modification as 14173 // side effect as well (for example: || or ,). To account for this we wrap 14174 // the visitation of such a sub-expression (for example: the LHS of || or ,) 14175 // with SequencedSubexpression. SequencedSubexpression is an RAII object 14176 // which record usages which are modifications as side effect, and then 14177 // downgrade them (or more accurately restore the previous usage which was a 14178 // modification as side effect) when exiting the scope of the sequenced 14179 // subexpression. 14180 14181 void notePreUse(Object O, const Expr *UseExpr) { 14182 UsageInfo &UI = UsageMap[O]; 14183 // Uses conflict with other modifications. 14184 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 14185 } 14186 14187 void notePostUse(Object O, const Expr *UseExpr) { 14188 UsageInfo &UI = UsageMap[O]; 14189 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 14190 /*IsModMod=*/false); 14191 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 14192 } 14193 14194 void notePreMod(Object O, const Expr *ModExpr) { 14195 UsageInfo &UI = UsageMap[O]; 14196 // Modifications conflict with other modifications and with uses. 14197 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 14198 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 14199 } 14200 14201 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 14202 UsageInfo &UI = UsageMap[O]; 14203 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 14204 /*IsModMod=*/true); 14205 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 14206 } 14207 14208 public: 14209 SequenceChecker(Sema &S, const Expr *E, 14210 SmallVectorImpl<const Expr *> &WorkList) 14211 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 14212 Visit(E); 14213 // Silence a -Wunused-private-field since WorkList is now unused. 14214 // TODO: Evaluate if it can be used, and if not remove it. 14215 (void)this->WorkList; 14216 } 14217 14218 void VisitStmt(const Stmt *S) { 14219 // Skip all statements which aren't expressions for now. 14220 } 14221 14222 void VisitExpr(const Expr *E) { 14223 // By default, just recurse to evaluated subexpressions. 14224 Base::VisitStmt(E); 14225 } 14226 14227 void VisitCastExpr(const CastExpr *E) { 14228 Object O = Object(); 14229 if (E->getCastKind() == CK_LValueToRValue) 14230 O = getObject(E->getSubExpr(), false); 14231 14232 if (O) 14233 notePreUse(O, E); 14234 VisitExpr(E); 14235 if (O) 14236 notePostUse(O, E); 14237 } 14238 14239 void VisitSequencedExpressions(const Expr *SequencedBefore, 14240 const Expr *SequencedAfter) { 14241 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 14242 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 14243 SequenceTree::Seq OldRegion = Region; 14244 14245 { 14246 SequencedSubexpression SeqBefore(*this); 14247 Region = BeforeRegion; 14248 Visit(SequencedBefore); 14249 } 14250 14251 Region = AfterRegion; 14252 Visit(SequencedAfter); 14253 14254 Region = OldRegion; 14255 14256 Tree.merge(BeforeRegion); 14257 Tree.merge(AfterRegion); 14258 } 14259 14260 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 14261 // C++17 [expr.sub]p1: 14262 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 14263 // expression E1 is sequenced before the expression E2. 14264 if (SemaRef.getLangOpts().CPlusPlus17) 14265 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 14266 else { 14267 Visit(ASE->getLHS()); 14268 Visit(ASE->getRHS()); 14269 } 14270 } 14271 14272 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14273 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14274 void VisitBinPtrMem(const BinaryOperator *BO) { 14275 // C++17 [expr.mptr.oper]p4: 14276 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 14277 // the expression E1 is sequenced before the expression E2. 14278 if (SemaRef.getLangOpts().CPlusPlus17) 14279 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14280 else { 14281 Visit(BO->getLHS()); 14282 Visit(BO->getRHS()); 14283 } 14284 } 14285 14286 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14287 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14288 void VisitBinShlShr(const BinaryOperator *BO) { 14289 // C++17 [expr.shift]p4: 14290 // The expression E1 is sequenced before the expression E2. 14291 if (SemaRef.getLangOpts().CPlusPlus17) 14292 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14293 else { 14294 Visit(BO->getLHS()); 14295 Visit(BO->getRHS()); 14296 } 14297 } 14298 14299 void VisitBinComma(const BinaryOperator *BO) { 14300 // C++11 [expr.comma]p1: 14301 // Every value computation and side effect associated with the left 14302 // expression is sequenced before every value computation and side 14303 // effect associated with the right expression. 14304 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14305 } 14306 14307 void VisitBinAssign(const BinaryOperator *BO) { 14308 SequenceTree::Seq RHSRegion; 14309 SequenceTree::Seq LHSRegion; 14310 if (SemaRef.getLangOpts().CPlusPlus17) { 14311 RHSRegion = Tree.allocate(Region); 14312 LHSRegion = Tree.allocate(Region); 14313 } else { 14314 RHSRegion = Region; 14315 LHSRegion = Region; 14316 } 14317 SequenceTree::Seq OldRegion = Region; 14318 14319 // C++11 [expr.ass]p1: 14320 // [...] the assignment is sequenced after the value computation 14321 // of the right and left operands, [...] 14322 // 14323 // so check it before inspecting the operands and update the 14324 // map afterwards. 14325 Object O = getObject(BO->getLHS(), /*Mod=*/true); 14326 if (O) 14327 notePreMod(O, BO); 14328 14329 if (SemaRef.getLangOpts().CPlusPlus17) { 14330 // C++17 [expr.ass]p1: 14331 // [...] The right operand is sequenced before the left operand. [...] 14332 { 14333 SequencedSubexpression SeqBefore(*this); 14334 Region = RHSRegion; 14335 Visit(BO->getRHS()); 14336 } 14337 14338 Region = LHSRegion; 14339 Visit(BO->getLHS()); 14340 14341 if (O && isa<CompoundAssignOperator>(BO)) 14342 notePostUse(O, BO); 14343 14344 } else { 14345 // C++11 does not specify any sequencing between the LHS and RHS. 14346 Region = LHSRegion; 14347 Visit(BO->getLHS()); 14348 14349 if (O && isa<CompoundAssignOperator>(BO)) 14350 notePostUse(O, BO); 14351 14352 Region = RHSRegion; 14353 Visit(BO->getRHS()); 14354 } 14355 14356 // C++11 [expr.ass]p1: 14357 // the assignment is sequenced [...] before the value computation of the 14358 // assignment expression. 14359 // C11 6.5.16/3 has no such rule. 14360 Region = OldRegion; 14361 if (O) 14362 notePostMod(O, BO, 14363 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14364 : UK_ModAsSideEffect); 14365 if (SemaRef.getLangOpts().CPlusPlus17) { 14366 Tree.merge(RHSRegion); 14367 Tree.merge(LHSRegion); 14368 } 14369 } 14370 14371 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 14372 VisitBinAssign(CAO); 14373 } 14374 14375 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14376 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14377 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 14378 Object O = getObject(UO->getSubExpr(), true); 14379 if (!O) 14380 return VisitExpr(UO); 14381 14382 notePreMod(O, UO); 14383 Visit(UO->getSubExpr()); 14384 // C++11 [expr.pre.incr]p1: 14385 // the expression ++x is equivalent to x+=1 14386 notePostMod(O, UO, 14387 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14388 : UK_ModAsSideEffect); 14389 } 14390 14391 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14392 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14393 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 14394 Object O = getObject(UO->getSubExpr(), true); 14395 if (!O) 14396 return VisitExpr(UO); 14397 14398 notePreMod(O, UO); 14399 Visit(UO->getSubExpr()); 14400 notePostMod(O, UO, UK_ModAsSideEffect); 14401 } 14402 14403 void VisitBinLOr(const BinaryOperator *BO) { 14404 // C++11 [expr.log.or]p2: 14405 // If the second expression is evaluated, every value computation and 14406 // side effect associated with the first expression is sequenced before 14407 // every value computation and side effect associated with the 14408 // second expression. 14409 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14410 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14411 SequenceTree::Seq OldRegion = Region; 14412 14413 EvaluationTracker Eval(*this); 14414 { 14415 SequencedSubexpression Sequenced(*this); 14416 Region = LHSRegion; 14417 Visit(BO->getLHS()); 14418 } 14419 14420 // C++11 [expr.log.or]p1: 14421 // [...] the second operand is not evaluated if the first operand 14422 // evaluates to true. 14423 bool EvalResult = false; 14424 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14425 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14426 if (ShouldVisitRHS) { 14427 Region = RHSRegion; 14428 Visit(BO->getRHS()); 14429 } 14430 14431 Region = OldRegion; 14432 Tree.merge(LHSRegion); 14433 Tree.merge(RHSRegion); 14434 } 14435 14436 void VisitBinLAnd(const BinaryOperator *BO) { 14437 // C++11 [expr.log.and]p2: 14438 // If the second expression is evaluated, every value computation and 14439 // side effect associated with the first expression is sequenced before 14440 // every value computation and side effect associated with the 14441 // second expression. 14442 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14443 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14444 SequenceTree::Seq OldRegion = Region; 14445 14446 EvaluationTracker Eval(*this); 14447 { 14448 SequencedSubexpression Sequenced(*this); 14449 Region = LHSRegion; 14450 Visit(BO->getLHS()); 14451 } 14452 14453 // C++11 [expr.log.and]p1: 14454 // [...] the second operand is not evaluated if the first operand is false. 14455 bool EvalResult = false; 14456 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14457 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14458 if (ShouldVisitRHS) { 14459 Region = RHSRegion; 14460 Visit(BO->getRHS()); 14461 } 14462 14463 Region = OldRegion; 14464 Tree.merge(LHSRegion); 14465 Tree.merge(RHSRegion); 14466 } 14467 14468 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14469 // C++11 [expr.cond]p1: 14470 // [...] Every value computation and side effect associated with the first 14471 // expression is sequenced before every value computation and side effect 14472 // associated with the second or third expression. 14473 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14474 14475 // No sequencing is specified between the true and false expression. 14476 // However since exactly one of both is going to be evaluated we can 14477 // consider them to be sequenced. This is needed to avoid warning on 14478 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14479 // both the true and false expressions because we can't evaluate x. 14480 // This will still allow us to detect an expression like (pre C++17) 14481 // "(x ? y += 1 : y += 2) = y". 14482 // 14483 // We don't wrap the visitation of the true and false expression with 14484 // SequencedSubexpression because we don't want to downgrade modifications 14485 // as side effect in the true and false expressions after the visition 14486 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14487 // not warn between the two "y++", but we should warn between the "y++" 14488 // and the "y". 14489 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14490 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14491 SequenceTree::Seq OldRegion = Region; 14492 14493 EvaluationTracker Eval(*this); 14494 { 14495 SequencedSubexpression Sequenced(*this); 14496 Region = ConditionRegion; 14497 Visit(CO->getCond()); 14498 } 14499 14500 // C++11 [expr.cond]p1: 14501 // [...] The first expression is contextually converted to bool (Clause 4). 14502 // It is evaluated and if it is true, the result of the conditional 14503 // expression is the value of the second expression, otherwise that of the 14504 // third expression. Only one of the second and third expressions is 14505 // evaluated. [...] 14506 bool EvalResult = false; 14507 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14508 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14509 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14510 if (ShouldVisitTrueExpr) { 14511 Region = TrueRegion; 14512 Visit(CO->getTrueExpr()); 14513 } 14514 if (ShouldVisitFalseExpr) { 14515 Region = FalseRegion; 14516 Visit(CO->getFalseExpr()); 14517 } 14518 14519 Region = OldRegion; 14520 Tree.merge(ConditionRegion); 14521 Tree.merge(TrueRegion); 14522 Tree.merge(FalseRegion); 14523 } 14524 14525 void VisitCallExpr(const CallExpr *CE) { 14526 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14527 14528 if (CE->isUnevaluatedBuiltinCall(Context)) 14529 return; 14530 14531 // C++11 [intro.execution]p15: 14532 // When calling a function [...], every value computation and side effect 14533 // associated with any argument expression, or with the postfix expression 14534 // designating the called function, is sequenced before execution of every 14535 // expression or statement in the body of the function [and thus before 14536 // the value computation of its result]. 14537 SequencedSubexpression Sequenced(*this); 14538 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14539 // C++17 [expr.call]p5 14540 // The postfix-expression is sequenced before each expression in the 14541 // expression-list and any default argument. [...] 14542 SequenceTree::Seq CalleeRegion; 14543 SequenceTree::Seq OtherRegion; 14544 if (SemaRef.getLangOpts().CPlusPlus17) { 14545 CalleeRegion = Tree.allocate(Region); 14546 OtherRegion = Tree.allocate(Region); 14547 } else { 14548 CalleeRegion = Region; 14549 OtherRegion = Region; 14550 } 14551 SequenceTree::Seq OldRegion = Region; 14552 14553 // Visit the callee expression first. 14554 Region = CalleeRegion; 14555 if (SemaRef.getLangOpts().CPlusPlus17) { 14556 SequencedSubexpression Sequenced(*this); 14557 Visit(CE->getCallee()); 14558 } else { 14559 Visit(CE->getCallee()); 14560 } 14561 14562 // Then visit the argument expressions. 14563 Region = OtherRegion; 14564 for (const Expr *Argument : CE->arguments()) 14565 Visit(Argument); 14566 14567 Region = OldRegion; 14568 if (SemaRef.getLangOpts().CPlusPlus17) { 14569 Tree.merge(CalleeRegion); 14570 Tree.merge(OtherRegion); 14571 } 14572 }); 14573 } 14574 14575 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14576 // C++17 [over.match.oper]p2: 14577 // [...] the operator notation is first transformed to the equivalent 14578 // function-call notation as summarized in Table 12 (where @ denotes one 14579 // of the operators covered in the specified subclause). However, the 14580 // operands are sequenced in the order prescribed for the built-in 14581 // operator (Clause 8). 14582 // 14583 // From the above only overloaded binary operators and overloaded call 14584 // operators have sequencing rules in C++17 that we need to handle 14585 // separately. 14586 if (!SemaRef.getLangOpts().CPlusPlus17 || 14587 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14588 return VisitCallExpr(CXXOCE); 14589 14590 enum { 14591 NoSequencing, 14592 LHSBeforeRHS, 14593 RHSBeforeLHS, 14594 LHSBeforeRest 14595 } SequencingKind; 14596 switch (CXXOCE->getOperator()) { 14597 case OO_Equal: 14598 case OO_PlusEqual: 14599 case OO_MinusEqual: 14600 case OO_StarEqual: 14601 case OO_SlashEqual: 14602 case OO_PercentEqual: 14603 case OO_CaretEqual: 14604 case OO_AmpEqual: 14605 case OO_PipeEqual: 14606 case OO_LessLessEqual: 14607 case OO_GreaterGreaterEqual: 14608 SequencingKind = RHSBeforeLHS; 14609 break; 14610 14611 case OO_LessLess: 14612 case OO_GreaterGreater: 14613 case OO_AmpAmp: 14614 case OO_PipePipe: 14615 case OO_Comma: 14616 case OO_ArrowStar: 14617 case OO_Subscript: 14618 SequencingKind = LHSBeforeRHS; 14619 break; 14620 14621 case OO_Call: 14622 SequencingKind = LHSBeforeRest; 14623 break; 14624 14625 default: 14626 SequencingKind = NoSequencing; 14627 break; 14628 } 14629 14630 if (SequencingKind == NoSequencing) 14631 return VisitCallExpr(CXXOCE); 14632 14633 // This is a call, so all subexpressions are sequenced before the result. 14634 SequencedSubexpression Sequenced(*this); 14635 14636 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14637 assert(SemaRef.getLangOpts().CPlusPlus17 && 14638 "Should only get there with C++17 and above!"); 14639 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14640 "Should only get there with an overloaded binary operator" 14641 " or an overloaded call operator!"); 14642 14643 if (SequencingKind == LHSBeforeRest) { 14644 assert(CXXOCE->getOperator() == OO_Call && 14645 "We should only have an overloaded call operator here!"); 14646 14647 // This is very similar to VisitCallExpr, except that we only have the 14648 // C++17 case. The postfix-expression is the first argument of the 14649 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14650 // are in the following arguments. 14651 // 14652 // Note that we intentionally do not visit the callee expression since 14653 // it is just a decayed reference to a function. 14654 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14655 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14656 SequenceTree::Seq OldRegion = Region; 14657 14658 assert(CXXOCE->getNumArgs() >= 1 && 14659 "An overloaded call operator must have at least one argument" 14660 " for the postfix-expression!"); 14661 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14662 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14663 CXXOCE->getNumArgs() - 1); 14664 14665 // Visit the postfix-expression first. 14666 { 14667 Region = PostfixExprRegion; 14668 SequencedSubexpression Sequenced(*this); 14669 Visit(PostfixExpr); 14670 } 14671 14672 // Then visit the argument expressions. 14673 Region = ArgsRegion; 14674 for (const Expr *Arg : Args) 14675 Visit(Arg); 14676 14677 Region = OldRegion; 14678 Tree.merge(PostfixExprRegion); 14679 Tree.merge(ArgsRegion); 14680 } else { 14681 assert(CXXOCE->getNumArgs() == 2 && 14682 "Should only have two arguments here!"); 14683 assert((SequencingKind == LHSBeforeRHS || 14684 SequencingKind == RHSBeforeLHS) && 14685 "Unexpected sequencing kind!"); 14686 14687 // We do not visit the callee expression since it is just a decayed 14688 // reference to a function. 14689 const Expr *E1 = CXXOCE->getArg(0); 14690 const Expr *E2 = CXXOCE->getArg(1); 14691 if (SequencingKind == RHSBeforeLHS) 14692 std::swap(E1, E2); 14693 14694 return VisitSequencedExpressions(E1, E2); 14695 } 14696 }); 14697 } 14698 14699 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14700 // This is a call, so all subexpressions are sequenced before the result. 14701 SequencedSubexpression Sequenced(*this); 14702 14703 if (!CCE->isListInitialization()) 14704 return VisitExpr(CCE); 14705 14706 // In C++11, list initializations are sequenced. 14707 SmallVector<SequenceTree::Seq, 32> Elts; 14708 SequenceTree::Seq Parent = Region; 14709 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14710 E = CCE->arg_end(); 14711 I != E; ++I) { 14712 Region = Tree.allocate(Parent); 14713 Elts.push_back(Region); 14714 Visit(*I); 14715 } 14716 14717 // Forget that the initializers are sequenced. 14718 Region = Parent; 14719 for (unsigned I = 0; I < Elts.size(); ++I) 14720 Tree.merge(Elts[I]); 14721 } 14722 14723 void VisitInitListExpr(const InitListExpr *ILE) { 14724 if (!SemaRef.getLangOpts().CPlusPlus11) 14725 return VisitExpr(ILE); 14726 14727 // In C++11, list initializations are sequenced. 14728 SmallVector<SequenceTree::Seq, 32> Elts; 14729 SequenceTree::Seq Parent = Region; 14730 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14731 const Expr *E = ILE->getInit(I); 14732 if (!E) 14733 continue; 14734 Region = Tree.allocate(Parent); 14735 Elts.push_back(Region); 14736 Visit(E); 14737 } 14738 14739 // Forget that the initializers are sequenced. 14740 Region = Parent; 14741 for (unsigned I = 0; I < Elts.size(); ++I) 14742 Tree.merge(Elts[I]); 14743 } 14744 }; 14745 14746 } // namespace 14747 14748 void Sema::CheckUnsequencedOperations(const Expr *E) { 14749 SmallVector<const Expr *, 8> WorkList; 14750 WorkList.push_back(E); 14751 while (!WorkList.empty()) { 14752 const Expr *Item = WorkList.pop_back_val(); 14753 SequenceChecker(*this, Item, WorkList); 14754 } 14755 } 14756 14757 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14758 bool IsConstexpr) { 14759 llvm::SaveAndRestore<bool> ConstantContext( 14760 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14761 CheckImplicitConversions(E, CheckLoc); 14762 if (!E->isInstantiationDependent()) 14763 CheckUnsequencedOperations(E); 14764 if (!IsConstexpr && !E->isValueDependent()) 14765 CheckForIntOverflow(E); 14766 DiagnoseMisalignedMembers(); 14767 } 14768 14769 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14770 FieldDecl *BitField, 14771 Expr *Init) { 14772 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14773 } 14774 14775 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14776 SourceLocation Loc) { 14777 if (!PType->isVariablyModifiedType()) 14778 return; 14779 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14780 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14781 return; 14782 } 14783 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14784 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14785 return; 14786 } 14787 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14788 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14789 return; 14790 } 14791 14792 const ArrayType *AT = S.Context.getAsArrayType(PType); 14793 if (!AT) 14794 return; 14795 14796 if (AT->getSizeModifier() != ArrayType::Star) { 14797 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14798 return; 14799 } 14800 14801 S.Diag(Loc, diag::err_array_star_in_function_definition); 14802 } 14803 14804 /// CheckParmsForFunctionDef - Check that the parameters of the given 14805 /// function are appropriate for the definition of a function. This 14806 /// takes care of any checks that cannot be performed on the 14807 /// declaration itself, e.g., that the types of each of the function 14808 /// parameters are complete. 14809 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14810 bool CheckParameterNames) { 14811 bool HasInvalidParm = false; 14812 for (ParmVarDecl *Param : Parameters) { 14813 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14814 // function declarator that is part of a function definition of 14815 // that function shall not have incomplete type. 14816 // 14817 // This is also C++ [dcl.fct]p6. 14818 if (!Param->isInvalidDecl() && 14819 RequireCompleteType(Param->getLocation(), Param->getType(), 14820 diag::err_typecheck_decl_incomplete_type)) { 14821 Param->setInvalidDecl(); 14822 HasInvalidParm = true; 14823 } 14824 14825 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14826 // declaration of each parameter shall include an identifier. 14827 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14828 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14829 // Diagnose this as an extension in C17 and earlier. 14830 if (!getLangOpts().C2x) 14831 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14832 } 14833 14834 // C99 6.7.5.3p12: 14835 // If the function declarator is not part of a definition of that 14836 // function, parameters may have incomplete type and may use the [*] 14837 // notation in their sequences of declarator specifiers to specify 14838 // variable length array types. 14839 QualType PType = Param->getOriginalType(); 14840 // FIXME: This diagnostic should point the '[*]' if source-location 14841 // information is added for it. 14842 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14843 14844 // If the parameter is a c++ class type and it has to be destructed in the 14845 // callee function, declare the destructor so that it can be called by the 14846 // callee function. Do not perform any direct access check on the dtor here. 14847 if (!Param->isInvalidDecl()) { 14848 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14849 if (!ClassDecl->isInvalidDecl() && 14850 !ClassDecl->hasIrrelevantDestructor() && 14851 !ClassDecl->isDependentContext() && 14852 ClassDecl->isParamDestroyedInCallee()) { 14853 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14854 MarkFunctionReferenced(Param->getLocation(), Destructor); 14855 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14856 } 14857 } 14858 } 14859 14860 // Parameters with the pass_object_size attribute only need to be marked 14861 // constant at function definitions. Because we lack information about 14862 // whether we're on a declaration or definition when we're instantiating the 14863 // attribute, we need to check for constness here. 14864 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14865 if (!Param->getType().isConstQualified()) 14866 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14867 << Attr->getSpelling() << 1; 14868 14869 // Check for parameter names shadowing fields from the class. 14870 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14871 // The owning context for the parameter should be the function, but we 14872 // want to see if this function's declaration context is a record. 14873 DeclContext *DC = Param->getDeclContext(); 14874 if (DC && DC->isFunctionOrMethod()) { 14875 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14876 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14877 RD, /*DeclIsField*/ false); 14878 } 14879 } 14880 } 14881 14882 return HasInvalidParm; 14883 } 14884 14885 Optional<std::pair<CharUnits, CharUnits>> 14886 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14887 14888 /// Compute the alignment and offset of the base class object given the 14889 /// derived-to-base cast expression and the alignment and offset of the derived 14890 /// class object. 14891 static std::pair<CharUnits, CharUnits> 14892 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14893 CharUnits BaseAlignment, CharUnits Offset, 14894 ASTContext &Ctx) { 14895 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14896 ++PathI) { 14897 const CXXBaseSpecifier *Base = *PathI; 14898 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14899 if (Base->isVirtual()) { 14900 // The complete object may have a lower alignment than the non-virtual 14901 // alignment of the base, in which case the base may be misaligned. Choose 14902 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14903 // conservative lower bound of the complete object alignment. 14904 CharUnits NonVirtualAlignment = 14905 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14906 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14907 Offset = CharUnits::Zero(); 14908 } else { 14909 const ASTRecordLayout &RL = 14910 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14911 Offset += RL.getBaseClassOffset(BaseDecl); 14912 } 14913 DerivedType = Base->getType(); 14914 } 14915 14916 return std::make_pair(BaseAlignment, Offset); 14917 } 14918 14919 /// Compute the alignment and offset of a binary additive operator. 14920 static Optional<std::pair<CharUnits, CharUnits>> 14921 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14922 bool IsSub, ASTContext &Ctx) { 14923 QualType PointeeType = PtrE->getType()->getPointeeType(); 14924 14925 if (!PointeeType->isConstantSizeType()) 14926 return llvm::None; 14927 14928 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14929 14930 if (!P) 14931 return llvm::None; 14932 14933 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14934 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14935 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14936 if (IsSub) 14937 Offset = -Offset; 14938 return std::make_pair(P->first, P->second + Offset); 14939 } 14940 14941 // If the integer expression isn't a constant expression, compute the lower 14942 // bound of the alignment using the alignment and offset of the pointer 14943 // expression and the element size. 14944 return std::make_pair( 14945 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14946 CharUnits::Zero()); 14947 } 14948 14949 /// This helper function takes an lvalue expression and returns the alignment of 14950 /// a VarDecl and a constant offset from the VarDecl. 14951 Optional<std::pair<CharUnits, CharUnits>> 14952 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14953 E = E->IgnoreParens(); 14954 switch (E->getStmtClass()) { 14955 default: 14956 break; 14957 case Stmt::CStyleCastExprClass: 14958 case Stmt::CXXStaticCastExprClass: 14959 case Stmt::ImplicitCastExprClass: { 14960 auto *CE = cast<CastExpr>(E); 14961 const Expr *From = CE->getSubExpr(); 14962 switch (CE->getCastKind()) { 14963 default: 14964 break; 14965 case CK_NoOp: 14966 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14967 case CK_UncheckedDerivedToBase: 14968 case CK_DerivedToBase: { 14969 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14970 if (!P) 14971 break; 14972 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14973 P->second, Ctx); 14974 } 14975 } 14976 break; 14977 } 14978 case Stmt::ArraySubscriptExprClass: { 14979 auto *ASE = cast<ArraySubscriptExpr>(E); 14980 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14981 false, Ctx); 14982 } 14983 case Stmt::DeclRefExprClass: { 14984 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14985 // FIXME: If VD is captured by copy or is an escaping __block variable, 14986 // use the alignment of VD's type. 14987 if (!VD->getType()->isReferenceType()) 14988 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14989 if (VD->hasInit()) 14990 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14991 } 14992 break; 14993 } 14994 case Stmt::MemberExprClass: { 14995 auto *ME = cast<MemberExpr>(E); 14996 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14997 if (!FD || FD->getType()->isReferenceType() || 14998 FD->getParent()->isInvalidDecl()) 14999 break; 15000 Optional<std::pair<CharUnits, CharUnits>> P; 15001 if (ME->isArrow()) 15002 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 15003 else 15004 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 15005 if (!P) 15006 break; 15007 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 15008 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 15009 return std::make_pair(P->first, 15010 P->second + CharUnits::fromQuantity(Offset)); 15011 } 15012 case Stmt::UnaryOperatorClass: { 15013 auto *UO = cast<UnaryOperator>(E); 15014 switch (UO->getOpcode()) { 15015 default: 15016 break; 15017 case UO_Deref: 15018 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 15019 } 15020 break; 15021 } 15022 case Stmt::BinaryOperatorClass: { 15023 auto *BO = cast<BinaryOperator>(E); 15024 auto Opcode = BO->getOpcode(); 15025 switch (Opcode) { 15026 default: 15027 break; 15028 case BO_Comma: 15029 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 15030 } 15031 break; 15032 } 15033 } 15034 return llvm::None; 15035 } 15036 15037 /// This helper function takes a pointer expression and returns the alignment of 15038 /// a VarDecl and a constant offset from the VarDecl. 15039 Optional<std::pair<CharUnits, CharUnits>> 15040 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 15041 E = E->IgnoreParens(); 15042 switch (E->getStmtClass()) { 15043 default: 15044 break; 15045 case Stmt::CStyleCastExprClass: 15046 case Stmt::CXXStaticCastExprClass: 15047 case Stmt::ImplicitCastExprClass: { 15048 auto *CE = cast<CastExpr>(E); 15049 const Expr *From = CE->getSubExpr(); 15050 switch (CE->getCastKind()) { 15051 default: 15052 break; 15053 case CK_NoOp: 15054 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 15055 case CK_ArrayToPointerDecay: 15056 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15057 case CK_UncheckedDerivedToBase: 15058 case CK_DerivedToBase: { 15059 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 15060 if (!P) 15061 break; 15062 return getDerivedToBaseAlignmentAndOffset( 15063 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 15064 } 15065 } 15066 break; 15067 } 15068 case Stmt::CXXThisExprClass: { 15069 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 15070 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 15071 return std::make_pair(Alignment, CharUnits::Zero()); 15072 } 15073 case Stmt::UnaryOperatorClass: { 15074 auto *UO = cast<UnaryOperator>(E); 15075 if (UO->getOpcode() == UO_AddrOf) 15076 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 15077 break; 15078 } 15079 case Stmt::BinaryOperatorClass: { 15080 auto *BO = cast<BinaryOperator>(E); 15081 auto Opcode = BO->getOpcode(); 15082 switch (Opcode) { 15083 default: 15084 break; 15085 case BO_Add: 15086 case BO_Sub: { 15087 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 15088 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 15089 std::swap(LHS, RHS); 15090 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 15091 Ctx); 15092 } 15093 case BO_Comma: 15094 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 15095 } 15096 break; 15097 } 15098 } 15099 return llvm::None; 15100 } 15101 15102 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 15103 // See if we can compute the alignment of a VarDecl and an offset from it. 15104 Optional<std::pair<CharUnits, CharUnits>> P = 15105 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 15106 15107 if (P) 15108 return P->first.alignmentAtOffset(P->second); 15109 15110 // If that failed, return the type's alignment. 15111 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 15112 } 15113 15114 /// CheckCastAlign - Implements -Wcast-align, which warns when a 15115 /// pointer cast increases the alignment requirements. 15116 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 15117 // This is actually a lot of work to potentially be doing on every 15118 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 15119 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 15120 return; 15121 15122 // Ignore dependent types. 15123 if (T->isDependentType() || Op->getType()->isDependentType()) 15124 return; 15125 15126 // Require that the destination be a pointer type. 15127 const PointerType *DestPtr = T->getAs<PointerType>(); 15128 if (!DestPtr) return; 15129 15130 // If the destination has alignment 1, we're done. 15131 QualType DestPointee = DestPtr->getPointeeType(); 15132 if (DestPointee->isIncompleteType()) return; 15133 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 15134 if (DestAlign.isOne()) return; 15135 15136 // Require that the source be a pointer type. 15137 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 15138 if (!SrcPtr) return; 15139 QualType SrcPointee = SrcPtr->getPointeeType(); 15140 15141 // Explicitly allow casts from cv void*. We already implicitly 15142 // allowed casts to cv void*, since they have alignment 1. 15143 // Also allow casts involving incomplete types, which implicitly 15144 // includes 'void'. 15145 if (SrcPointee->isIncompleteType()) return; 15146 15147 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 15148 15149 if (SrcAlign >= DestAlign) return; 15150 15151 Diag(TRange.getBegin(), diag::warn_cast_align) 15152 << Op->getType() << T 15153 << static_cast<unsigned>(SrcAlign.getQuantity()) 15154 << static_cast<unsigned>(DestAlign.getQuantity()) 15155 << TRange << Op->getSourceRange(); 15156 } 15157 15158 /// Check whether this array fits the idiom of a size-one tail padded 15159 /// array member of a struct. 15160 /// 15161 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 15162 /// commonly used to emulate flexible arrays in C89 code. 15163 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 15164 const NamedDecl *ND) { 15165 if (Size != 1 || !ND) return false; 15166 15167 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 15168 if (!FD) return false; 15169 15170 // Don't consider sizes resulting from macro expansions or template argument 15171 // substitution to form C89 tail-padded arrays. 15172 15173 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 15174 while (TInfo) { 15175 TypeLoc TL = TInfo->getTypeLoc(); 15176 // Look through typedefs. 15177 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 15178 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 15179 TInfo = TDL->getTypeSourceInfo(); 15180 continue; 15181 } 15182 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 15183 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 15184 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 15185 return false; 15186 } 15187 break; 15188 } 15189 15190 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 15191 if (!RD) return false; 15192 if (RD->isUnion()) return false; 15193 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15194 if (!CRD->isStandardLayout()) return false; 15195 } 15196 15197 // See if this is the last field decl in the record. 15198 const Decl *D = FD; 15199 while ((D = D->getNextDeclInContext())) 15200 if (isa<FieldDecl>(D)) 15201 return false; 15202 return true; 15203 } 15204 15205 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 15206 const ArraySubscriptExpr *ASE, 15207 bool AllowOnePastEnd, bool IndexNegated) { 15208 // Already diagnosed by the constant evaluator. 15209 if (isConstantEvaluated()) 15210 return; 15211 15212 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 15213 if (IndexExpr->isValueDependent()) 15214 return; 15215 15216 const Type *EffectiveType = 15217 BaseExpr->getType()->getPointeeOrArrayElementType(); 15218 BaseExpr = BaseExpr->IgnoreParenCasts(); 15219 const ConstantArrayType *ArrayTy = 15220 Context.getAsConstantArrayType(BaseExpr->getType()); 15221 15222 const Type *BaseType = 15223 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 15224 bool IsUnboundedArray = (BaseType == nullptr); 15225 if (EffectiveType->isDependentType() || 15226 (!IsUnboundedArray && BaseType->isDependentType())) 15227 return; 15228 15229 Expr::EvalResult Result; 15230 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 15231 return; 15232 15233 llvm::APSInt index = Result.Val.getInt(); 15234 if (IndexNegated) { 15235 index.setIsUnsigned(false); 15236 index = -index; 15237 } 15238 15239 const NamedDecl *ND = nullptr; 15240 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15241 ND = DRE->getDecl(); 15242 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 15243 ND = ME->getMemberDecl(); 15244 15245 if (IsUnboundedArray) { 15246 if (index.isUnsigned() || !index.isNegative()) { 15247 const auto &ASTC = getASTContext(); 15248 unsigned AddrBits = 15249 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 15250 EffectiveType->getCanonicalTypeInternal())); 15251 if (index.getBitWidth() < AddrBits) 15252 index = index.zext(AddrBits); 15253 Optional<CharUnits> ElemCharUnits = 15254 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 15255 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 15256 // pointer) bounds-checking isn't meaningful. 15257 if (!ElemCharUnits) 15258 return; 15259 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 15260 // If index has more active bits than address space, we already know 15261 // we have a bounds violation to warn about. Otherwise, compute 15262 // address of (index + 1)th element, and warn about bounds violation 15263 // only if that address exceeds address space. 15264 if (index.getActiveBits() <= AddrBits) { 15265 bool Overflow; 15266 llvm::APInt Product(index); 15267 Product += 1; 15268 Product = Product.umul_ov(ElemBytes, Overflow); 15269 if (!Overflow && Product.getActiveBits() <= AddrBits) 15270 return; 15271 } 15272 15273 // Need to compute max possible elements in address space, since that 15274 // is included in diag message. 15275 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 15276 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 15277 MaxElems += 1; 15278 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 15279 MaxElems = MaxElems.udiv(ElemBytes); 15280 15281 unsigned DiagID = 15282 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 15283 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 15284 15285 // Diag message shows element size in bits and in "bytes" (platform- 15286 // dependent CharUnits) 15287 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15288 PDiag(DiagID) 15289 << toString(index, 10, true) << AddrBits 15290 << (unsigned)ASTC.toBits(*ElemCharUnits) 15291 << toString(ElemBytes, 10, false) 15292 << toString(MaxElems, 10, false) 15293 << (unsigned)MaxElems.getLimitedValue(~0U) 15294 << IndexExpr->getSourceRange()); 15295 15296 if (!ND) { 15297 // Try harder to find a NamedDecl to point at in the note. 15298 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15299 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15300 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15301 ND = DRE->getDecl(); 15302 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15303 ND = ME->getMemberDecl(); 15304 } 15305 15306 if (ND) 15307 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15308 PDiag(diag::note_array_declared_here) << ND); 15309 } 15310 return; 15311 } 15312 15313 if (index.isUnsigned() || !index.isNegative()) { 15314 // It is possible that the type of the base expression after 15315 // IgnoreParenCasts is incomplete, even though the type of the base 15316 // expression before IgnoreParenCasts is complete (see PR39746 for an 15317 // example). In this case we have no information about whether the array 15318 // access exceeds the array bounds. However we can still diagnose an array 15319 // access which precedes the array bounds. 15320 if (BaseType->isIncompleteType()) 15321 return; 15322 15323 llvm::APInt size = ArrayTy->getSize(); 15324 if (!size.isStrictlyPositive()) 15325 return; 15326 15327 if (BaseType != EffectiveType) { 15328 // Make sure we're comparing apples to apples when comparing index to size 15329 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 15330 uint64_t array_typesize = Context.getTypeSize(BaseType); 15331 // Handle ptrarith_typesize being zero, such as when casting to void* 15332 if (!ptrarith_typesize) ptrarith_typesize = 1; 15333 if (ptrarith_typesize != array_typesize) { 15334 // There's a cast to a different size type involved 15335 uint64_t ratio = array_typesize / ptrarith_typesize; 15336 // TODO: Be smarter about handling cases where array_typesize is not a 15337 // multiple of ptrarith_typesize 15338 if (ptrarith_typesize * ratio == array_typesize) 15339 size *= llvm::APInt(size.getBitWidth(), ratio); 15340 } 15341 } 15342 15343 if (size.getBitWidth() > index.getBitWidth()) 15344 index = index.zext(size.getBitWidth()); 15345 else if (size.getBitWidth() < index.getBitWidth()) 15346 size = size.zext(index.getBitWidth()); 15347 15348 // For array subscripting the index must be less than size, but for pointer 15349 // arithmetic also allow the index (offset) to be equal to size since 15350 // computing the next address after the end of the array is legal and 15351 // commonly done e.g. in C++ iterators and range-based for loops. 15352 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 15353 return; 15354 15355 // Also don't warn for arrays of size 1 which are members of some 15356 // structure. These are often used to approximate flexible arrays in C89 15357 // code. 15358 if (IsTailPaddedMemberArray(*this, size, ND)) 15359 return; 15360 15361 // Suppress the warning if the subscript expression (as identified by the 15362 // ']' location) and the index expression are both from macro expansions 15363 // within a system header. 15364 if (ASE) { 15365 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 15366 ASE->getRBracketLoc()); 15367 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 15368 SourceLocation IndexLoc = 15369 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 15370 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 15371 return; 15372 } 15373 } 15374 15375 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 15376 : diag::warn_ptr_arith_exceeds_bounds; 15377 15378 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15379 PDiag(DiagID) << toString(index, 10, true) 15380 << toString(size, 10, true) 15381 << (unsigned)size.getLimitedValue(~0U) 15382 << IndexExpr->getSourceRange()); 15383 } else { 15384 unsigned DiagID = diag::warn_array_index_precedes_bounds; 15385 if (!ASE) { 15386 DiagID = diag::warn_ptr_arith_precedes_bounds; 15387 if (index.isNegative()) index = -index; 15388 } 15389 15390 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15391 PDiag(DiagID) << toString(index, 10, true) 15392 << IndexExpr->getSourceRange()); 15393 } 15394 15395 if (!ND) { 15396 // Try harder to find a NamedDecl to point at in the note. 15397 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15398 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15399 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15400 ND = DRE->getDecl(); 15401 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15402 ND = ME->getMemberDecl(); 15403 } 15404 15405 if (ND) 15406 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15407 PDiag(diag::note_array_declared_here) << ND); 15408 } 15409 15410 void Sema::CheckArrayAccess(const Expr *expr) { 15411 int AllowOnePastEnd = 0; 15412 while (expr) { 15413 expr = expr->IgnoreParenImpCasts(); 15414 switch (expr->getStmtClass()) { 15415 case Stmt::ArraySubscriptExprClass: { 15416 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15417 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15418 AllowOnePastEnd > 0); 15419 expr = ASE->getBase(); 15420 break; 15421 } 15422 case Stmt::MemberExprClass: { 15423 expr = cast<MemberExpr>(expr)->getBase(); 15424 break; 15425 } 15426 case Stmt::OMPArraySectionExprClass: { 15427 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15428 if (ASE->getLowerBound()) 15429 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15430 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15431 return; 15432 } 15433 case Stmt::UnaryOperatorClass: { 15434 // Only unwrap the * and & unary operators 15435 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15436 expr = UO->getSubExpr(); 15437 switch (UO->getOpcode()) { 15438 case UO_AddrOf: 15439 AllowOnePastEnd++; 15440 break; 15441 case UO_Deref: 15442 AllowOnePastEnd--; 15443 break; 15444 default: 15445 return; 15446 } 15447 break; 15448 } 15449 case Stmt::ConditionalOperatorClass: { 15450 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15451 if (const Expr *lhs = cond->getLHS()) 15452 CheckArrayAccess(lhs); 15453 if (const Expr *rhs = cond->getRHS()) 15454 CheckArrayAccess(rhs); 15455 return; 15456 } 15457 case Stmt::CXXOperatorCallExprClass: { 15458 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15459 for (const auto *Arg : OCE->arguments()) 15460 CheckArrayAccess(Arg); 15461 return; 15462 } 15463 default: 15464 return; 15465 } 15466 } 15467 } 15468 15469 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15470 15471 namespace { 15472 15473 struct RetainCycleOwner { 15474 VarDecl *Variable = nullptr; 15475 SourceRange Range; 15476 SourceLocation Loc; 15477 bool Indirect = false; 15478 15479 RetainCycleOwner() = default; 15480 15481 void setLocsFrom(Expr *e) { 15482 Loc = e->getExprLoc(); 15483 Range = e->getSourceRange(); 15484 } 15485 }; 15486 15487 } // namespace 15488 15489 /// Consider whether capturing the given variable can possibly lead to 15490 /// a retain cycle. 15491 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15492 // In ARC, it's captured strongly iff the variable has __strong 15493 // lifetime. In MRR, it's captured strongly if the variable is 15494 // __block and has an appropriate type. 15495 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15496 return false; 15497 15498 owner.Variable = var; 15499 if (ref) 15500 owner.setLocsFrom(ref); 15501 return true; 15502 } 15503 15504 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15505 while (true) { 15506 e = e->IgnoreParens(); 15507 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15508 switch (cast->getCastKind()) { 15509 case CK_BitCast: 15510 case CK_LValueBitCast: 15511 case CK_LValueToRValue: 15512 case CK_ARCReclaimReturnedObject: 15513 e = cast->getSubExpr(); 15514 continue; 15515 15516 default: 15517 return false; 15518 } 15519 } 15520 15521 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15522 ObjCIvarDecl *ivar = ref->getDecl(); 15523 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15524 return false; 15525 15526 // Try to find a retain cycle in the base. 15527 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15528 return false; 15529 15530 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15531 owner.Indirect = true; 15532 return true; 15533 } 15534 15535 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15536 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15537 if (!var) return false; 15538 return considerVariable(var, ref, owner); 15539 } 15540 15541 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15542 if (member->isArrow()) return false; 15543 15544 // Don't count this as an indirect ownership. 15545 e = member->getBase(); 15546 continue; 15547 } 15548 15549 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15550 // Only pay attention to pseudo-objects on property references. 15551 ObjCPropertyRefExpr *pre 15552 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15553 ->IgnoreParens()); 15554 if (!pre) return false; 15555 if (pre->isImplicitProperty()) return false; 15556 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15557 if (!property->isRetaining() && 15558 !(property->getPropertyIvarDecl() && 15559 property->getPropertyIvarDecl()->getType() 15560 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15561 return false; 15562 15563 owner.Indirect = true; 15564 if (pre->isSuperReceiver()) { 15565 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15566 if (!owner.Variable) 15567 return false; 15568 owner.Loc = pre->getLocation(); 15569 owner.Range = pre->getSourceRange(); 15570 return true; 15571 } 15572 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15573 ->getSourceExpr()); 15574 continue; 15575 } 15576 15577 // Array ivars? 15578 15579 return false; 15580 } 15581 } 15582 15583 namespace { 15584 15585 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15586 ASTContext &Context; 15587 VarDecl *Variable; 15588 Expr *Capturer = nullptr; 15589 bool VarWillBeReased = false; 15590 15591 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15592 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15593 Context(Context), Variable(variable) {} 15594 15595 void VisitDeclRefExpr(DeclRefExpr *ref) { 15596 if (ref->getDecl() == Variable && !Capturer) 15597 Capturer = ref; 15598 } 15599 15600 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15601 if (Capturer) return; 15602 Visit(ref->getBase()); 15603 if (Capturer && ref->isFreeIvar()) 15604 Capturer = ref; 15605 } 15606 15607 void VisitBlockExpr(BlockExpr *block) { 15608 // Look inside nested blocks 15609 if (block->getBlockDecl()->capturesVariable(Variable)) 15610 Visit(block->getBlockDecl()->getBody()); 15611 } 15612 15613 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15614 if (Capturer) return; 15615 if (OVE->getSourceExpr()) 15616 Visit(OVE->getSourceExpr()); 15617 } 15618 15619 void VisitBinaryOperator(BinaryOperator *BinOp) { 15620 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15621 return; 15622 Expr *LHS = BinOp->getLHS(); 15623 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15624 if (DRE->getDecl() != Variable) 15625 return; 15626 if (Expr *RHS = BinOp->getRHS()) { 15627 RHS = RHS->IgnoreParenCasts(); 15628 Optional<llvm::APSInt> Value; 15629 VarWillBeReased = 15630 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15631 *Value == 0); 15632 } 15633 } 15634 } 15635 }; 15636 15637 } // namespace 15638 15639 /// Check whether the given argument is a block which captures a 15640 /// variable. 15641 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15642 assert(owner.Variable && owner.Loc.isValid()); 15643 15644 e = e->IgnoreParenCasts(); 15645 15646 // Look through [^{...} copy] and Block_copy(^{...}). 15647 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15648 Selector Cmd = ME->getSelector(); 15649 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15650 e = ME->getInstanceReceiver(); 15651 if (!e) 15652 return nullptr; 15653 e = e->IgnoreParenCasts(); 15654 } 15655 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15656 if (CE->getNumArgs() == 1) { 15657 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15658 if (Fn) { 15659 const IdentifierInfo *FnI = Fn->getIdentifier(); 15660 if (FnI && FnI->isStr("_Block_copy")) { 15661 e = CE->getArg(0)->IgnoreParenCasts(); 15662 } 15663 } 15664 } 15665 } 15666 15667 BlockExpr *block = dyn_cast<BlockExpr>(e); 15668 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15669 return nullptr; 15670 15671 FindCaptureVisitor visitor(S.Context, owner.Variable); 15672 visitor.Visit(block->getBlockDecl()->getBody()); 15673 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15674 } 15675 15676 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15677 RetainCycleOwner &owner) { 15678 assert(capturer); 15679 assert(owner.Variable && owner.Loc.isValid()); 15680 15681 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15682 << owner.Variable << capturer->getSourceRange(); 15683 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15684 << owner.Indirect << owner.Range; 15685 } 15686 15687 /// Check for a keyword selector that starts with the word 'add' or 15688 /// 'set'. 15689 static bool isSetterLikeSelector(Selector sel) { 15690 if (sel.isUnarySelector()) return false; 15691 15692 StringRef str = sel.getNameForSlot(0); 15693 while (!str.empty() && str.front() == '_') str = str.substr(1); 15694 if (str.startswith("set")) 15695 str = str.substr(3); 15696 else if (str.startswith("add")) { 15697 // Specially allow 'addOperationWithBlock:'. 15698 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15699 return false; 15700 str = str.substr(3); 15701 } 15702 else 15703 return false; 15704 15705 if (str.empty()) return true; 15706 return !isLowercase(str.front()); 15707 } 15708 15709 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15710 ObjCMessageExpr *Message) { 15711 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15712 Message->getReceiverInterface(), 15713 NSAPI::ClassId_NSMutableArray); 15714 if (!IsMutableArray) { 15715 return None; 15716 } 15717 15718 Selector Sel = Message->getSelector(); 15719 15720 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15721 S.NSAPIObj->getNSArrayMethodKind(Sel); 15722 if (!MKOpt) { 15723 return None; 15724 } 15725 15726 NSAPI::NSArrayMethodKind MK = *MKOpt; 15727 15728 switch (MK) { 15729 case NSAPI::NSMutableArr_addObject: 15730 case NSAPI::NSMutableArr_insertObjectAtIndex: 15731 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15732 return 0; 15733 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15734 return 1; 15735 15736 default: 15737 return None; 15738 } 15739 15740 return None; 15741 } 15742 15743 static 15744 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15745 ObjCMessageExpr *Message) { 15746 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15747 Message->getReceiverInterface(), 15748 NSAPI::ClassId_NSMutableDictionary); 15749 if (!IsMutableDictionary) { 15750 return None; 15751 } 15752 15753 Selector Sel = Message->getSelector(); 15754 15755 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15756 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15757 if (!MKOpt) { 15758 return None; 15759 } 15760 15761 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15762 15763 switch (MK) { 15764 case NSAPI::NSMutableDict_setObjectForKey: 15765 case NSAPI::NSMutableDict_setValueForKey: 15766 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15767 return 0; 15768 15769 default: 15770 return None; 15771 } 15772 15773 return None; 15774 } 15775 15776 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15777 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15778 Message->getReceiverInterface(), 15779 NSAPI::ClassId_NSMutableSet); 15780 15781 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15782 Message->getReceiverInterface(), 15783 NSAPI::ClassId_NSMutableOrderedSet); 15784 if (!IsMutableSet && !IsMutableOrderedSet) { 15785 return None; 15786 } 15787 15788 Selector Sel = Message->getSelector(); 15789 15790 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15791 if (!MKOpt) { 15792 return None; 15793 } 15794 15795 NSAPI::NSSetMethodKind MK = *MKOpt; 15796 15797 switch (MK) { 15798 case NSAPI::NSMutableSet_addObject: 15799 case NSAPI::NSOrderedSet_setObjectAtIndex: 15800 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15801 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15802 return 0; 15803 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15804 return 1; 15805 } 15806 15807 return None; 15808 } 15809 15810 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15811 if (!Message->isInstanceMessage()) { 15812 return; 15813 } 15814 15815 Optional<int> ArgOpt; 15816 15817 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15818 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15819 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15820 return; 15821 } 15822 15823 int ArgIndex = *ArgOpt; 15824 15825 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15826 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15827 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15828 } 15829 15830 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15831 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15832 if (ArgRE->isObjCSelfExpr()) { 15833 Diag(Message->getSourceRange().getBegin(), 15834 diag::warn_objc_circular_container) 15835 << ArgRE->getDecl() << StringRef("'super'"); 15836 } 15837 } 15838 } else { 15839 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15840 15841 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15842 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15843 } 15844 15845 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15846 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15847 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15848 ValueDecl *Decl = ReceiverRE->getDecl(); 15849 Diag(Message->getSourceRange().getBegin(), 15850 diag::warn_objc_circular_container) 15851 << Decl << Decl; 15852 if (!ArgRE->isObjCSelfExpr()) { 15853 Diag(Decl->getLocation(), 15854 diag::note_objc_circular_container_declared_here) 15855 << Decl; 15856 } 15857 } 15858 } 15859 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15860 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15861 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15862 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15863 Diag(Message->getSourceRange().getBegin(), 15864 diag::warn_objc_circular_container) 15865 << Decl << Decl; 15866 Diag(Decl->getLocation(), 15867 diag::note_objc_circular_container_declared_here) 15868 << Decl; 15869 } 15870 } 15871 } 15872 } 15873 } 15874 15875 /// Check a message send to see if it's likely to cause a retain cycle. 15876 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15877 // Only check instance methods whose selector looks like a setter. 15878 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15879 return; 15880 15881 // Try to find a variable that the receiver is strongly owned by. 15882 RetainCycleOwner owner; 15883 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15884 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15885 return; 15886 } else { 15887 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15888 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15889 owner.Loc = msg->getSuperLoc(); 15890 owner.Range = msg->getSuperLoc(); 15891 } 15892 15893 // Check whether the receiver is captured by any of the arguments. 15894 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15895 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15896 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15897 // noescape blocks should not be retained by the method. 15898 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15899 continue; 15900 return diagnoseRetainCycle(*this, capturer, owner); 15901 } 15902 } 15903 } 15904 15905 /// Check a property assign to see if it's likely to cause a retain cycle. 15906 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15907 RetainCycleOwner owner; 15908 if (!findRetainCycleOwner(*this, receiver, owner)) 15909 return; 15910 15911 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15912 diagnoseRetainCycle(*this, capturer, owner); 15913 } 15914 15915 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15916 RetainCycleOwner Owner; 15917 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15918 return; 15919 15920 // Because we don't have an expression for the variable, we have to set the 15921 // location explicitly here. 15922 Owner.Loc = Var->getLocation(); 15923 Owner.Range = Var->getSourceRange(); 15924 15925 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15926 diagnoseRetainCycle(*this, Capturer, Owner); 15927 } 15928 15929 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15930 Expr *RHS, bool isProperty) { 15931 // Check if RHS is an Objective-C object literal, which also can get 15932 // immediately zapped in a weak reference. Note that we explicitly 15933 // allow ObjCStringLiterals, since those are designed to never really die. 15934 RHS = RHS->IgnoreParenImpCasts(); 15935 15936 // This enum needs to match with the 'select' in 15937 // warn_objc_arc_literal_assign (off-by-1). 15938 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15939 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15940 return false; 15941 15942 S.Diag(Loc, diag::warn_arc_literal_assign) 15943 << (unsigned) Kind 15944 << (isProperty ? 0 : 1) 15945 << RHS->getSourceRange(); 15946 15947 return true; 15948 } 15949 15950 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15951 Qualifiers::ObjCLifetime LT, 15952 Expr *RHS, bool isProperty) { 15953 // Strip off any implicit cast added to get to the one ARC-specific. 15954 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15955 if (cast->getCastKind() == CK_ARCConsumeObject) { 15956 S.Diag(Loc, diag::warn_arc_retained_assign) 15957 << (LT == Qualifiers::OCL_ExplicitNone) 15958 << (isProperty ? 0 : 1) 15959 << RHS->getSourceRange(); 15960 return true; 15961 } 15962 RHS = cast->getSubExpr(); 15963 } 15964 15965 if (LT == Qualifiers::OCL_Weak && 15966 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15967 return true; 15968 15969 return false; 15970 } 15971 15972 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15973 QualType LHS, Expr *RHS) { 15974 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15975 15976 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15977 return false; 15978 15979 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15980 return true; 15981 15982 return false; 15983 } 15984 15985 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15986 Expr *LHS, Expr *RHS) { 15987 QualType LHSType; 15988 // PropertyRef on LHS type need be directly obtained from 15989 // its declaration as it has a PseudoType. 15990 ObjCPropertyRefExpr *PRE 15991 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15992 if (PRE && !PRE->isImplicitProperty()) { 15993 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15994 if (PD) 15995 LHSType = PD->getType(); 15996 } 15997 15998 if (LHSType.isNull()) 15999 LHSType = LHS->getType(); 16000 16001 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 16002 16003 if (LT == Qualifiers::OCL_Weak) { 16004 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 16005 getCurFunction()->markSafeWeakUse(LHS); 16006 } 16007 16008 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 16009 return; 16010 16011 // FIXME. Check for other life times. 16012 if (LT != Qualifiers::OCL_None) 16013 return; 16014 16015 if (PRE) { 16016 if (PRE->isImplicitProperty()) 16017 return; 16018 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 16019 if (!PD) 16020 return; 16021 16022 unsigned Attributes = PD->getPropertyAttributes(); 16023 if (Attributes & ObjCPropertyAttribute::kind_assign) { 16024 // when 'assign' attribute was not explicitly specified 16025 // by user, ignore it and rely on property type itself 16026 // for lifetime info. 16027 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 16028 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 16029 LHSType->isObjCRetainableType()) 16030 return; 16031 16032 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 16033 if (cast->getCastKind() == CK_ARCConsumeObject) { 16034 Diag(Loc, diag::warn_arc_retained_property_assign) 16035 << RHS->getSourceRange(); 16036 return; 16037 } 16038 RHS = cast->getSubExpr(); 16039 } 16040 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 16041 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 16042 return; 16043 } 16044 } 16045 } 16046 16047 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 16048 16049 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 16050 SourceLocation StmtLoc, 16051 const NullStmt *Body) { 16052 // Do not warn if the body is a macro that expands to nothing, e.g: 16053 // 16054 // #define CALL(x) 16055 // if (condition) 16056 // CALL(0); 16057 if (Body->hasLeadingEmptyMacro()) 16058 return false; 16059 16060 // Get line numbers of statement and body. 16061 bool StmtLineInvalid; 16062 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 16063 &StmtLineInvalid); 16064 if (StmtLineInvalid) 16065 return false; 16066 16067 bool BodyLineInvalid; 16068 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 16069 &BodyLineInvalid); 16070 if (BodyLineInvalid) 16071 return false; 16072 16073 // Warn if null statement and body are on the same line. 16074 if (StmtLine != BodyLine) 16075 return false; 16076 16077 return true; 16078 } 16079 16080 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 16081 const Stmt *Body, 16082 unsigned DiagID) { 16083 // Since this is a syntactic check, don't emit diagnostic for template 16084 // instantiations, this just adds noise. 16085 if (CurrentInstantiationScope) 16086 return; 16087 16088 // The body should be a null statement. 16089 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 16090 if (!NBody) 16091 return; 16092 16093 // Do the usual checks. 16094 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 16095 return; 16096 16097 Diag(NBody->getSemiLoc(), DiagID); 16098 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 16099 } 16100 16101 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 16102 const Stmt *PossibleBody) { 16103 assert(!CurrentInstantiationScope); // Ensured by caller 16104 16105 SourceLocation StmtLoc; 16106 const Stmt *Body; 16107 unsigned DiagID; 16108 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 16109 StmtLoc = FS->getRParenLoc(); 16110 Body = FS->getBody(); 16111 DiagID = diag::warn_empty_for_body; 16112 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 16113 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 16114 Body = WS->getBody(); 16115 DiagID = diag::warn_empty_while_body; 16116 } else 16117 return; // Neither `for' nor `while'. 16118 16119 // The body should be a null statement. 16120 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 16121 if (!NBody) 16122 return; 16123 16124 // Skip expensive checks if diagnostic is disabled. 16125 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 16126 return; 16127 16128 // Do the usual checks. 16129 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 16130 return; 16131 16132 // `for(...);' and `while(...);' are popular idioms, so in order to keep 16133 // noise level low, emit diagnostics only if for/while is followed by a 16134 // CompoundStmt, e.g.: 16135 // for (int i = 0; i < n; i++); 16136 // { 16137 // a(i); 16138 // } 16139 // or if for/while is followed by a statement with more indentation 16140 // than for/while itself: 16141 // for (int i = 0; i < n; i++); 16142 // a(i); 16143 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 16144 if (!ProbableTypo) { 16145 bool BodyColInvalid; 16146 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 16147 PossibleBody->getBeginLoc(), &BodyColInvalid); 16148 if (BodyColInvalid) 16149 return; 16150 16151 bool StmtColInvalid; 16152 unsigned StmtCol = 16153 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 16154 if (StmtColInvalid) 16155 return; 16156 16157 if (BodyCol > StmtCol) 16158 ProbableTypo = true; 16159 } 16160 16161 if (ProbableTypo) { 16162 Diag(NBody->getSemiLoc(), DiagID); 16163 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 16164 } 16165 } 16166 16167 //===--- CHECK: Warn on self move with std::move. -------------------------===// 16168 16169 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 16170 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 16171 SourceLocation OpLoc) { 16172 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 16173 return; 16174 16175 if (inTemplateInstantiation()) 16176 return; 16177 16178 // Strip parens and casts away. 16179 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 16180 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 16181 16182 // Check for a call expression 16183 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 16184 if (!CE || CE->getNumArgs() != 1) 16185 return; 16186 16187 // Check for a call to std::move 16188 if (!CE->isCallToStdMove()) 16189 return; 16190 16191 // Get argument from std::move 16192 RHSExpr = CE->getArg(0); 16193 16194 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 16195 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 16196 16197 // Two DeclRefExpr's, check that the decls are the same. 16198 if (LHSDeclRef && RHSDeclRef) { 16199 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16200 return; 16201 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16202 RHSDeclRef->getDecl()->getCanonicalDecl()) 16203 return; 16204 16205 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16206 << LHSExpr->getSourceRange() 16207 << RHSExpr->getSourceRange(); 16208 return; 16209 } 16210 16211 // Member variables require a different approach to check for self moves. 16212 // MemberExpr's are the same if every nested MemberExpr refers to the same 16213 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 16214 // the base Expr's are CXXThisExpr's. 16215 const Expr *LHSBase = LHSExpr; 16216 const Expr *RHSBase = RHSExpr; 16217 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 16218 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 16219 if (!LHSME || !RHSME) 16220 return; 16221 16222 while (LHSME && RHSME) { 16223 if (LHSME->getMemberDecl()->getCanonicalDecl() != 16224 RHSME->getMemberDecl()->getCanonicalDecl()) 16225 return; 16226 16227 LHSBase = LHSME->getBase(); 16228 RHSBase = RHSME->getBase(); 16229 LHSME = dyn_cast<MemberExpr>(LHSBase); 16230 RHSME = dyn_cast<MemberExpr>(RHSBase); 16231 } 16232 16233 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 16234 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 16235 if (LHSDeclRef && RHSDeclRef) { 16236 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16237 return; 16238 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16239 RHSDeclRef->getDecl()->getCanonicalDecl()) 16240 return; 16241 16242 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16243 << LHSExpr->getSourceRange() 16244 << RHSExpr->getSourceRange(); 16245 return; 16246 } 16247 16248 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 16249 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16250 << LHSExpr->getSourceRange() 16251 << RHSExpr->getSourceRange(); 16252 } 16253 16254 //===--- Layout compatibility ----------------------------------------------// 16255 16256 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 16257 16258 /// Check if two enumeration types are layout-compatible. 16259 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 16260 // C++11 [dcl.enum] p8: 16261 // Two enumeration types are layout-compatible if they have the same 16262 // underlying type. 16263 return ED1->isComplete() && ED2->isComplete() && 16264 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 16265 } 16266 16267 /// Check if two fields are layout-compatible. 16268 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 16269 FieldDecl *Field2) { 16270 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 16271 return false; 16272 16273 if (Field1->isBitField() != Field2->isBitField()) 16274 return false; 16275 16276 if (Field1->isBitField()) { 16277 // Make sure that the bit-fields are the same length. 16278 unsigned Bits1 = Field1->getBitWidthValue(C); 16279 unsigned Bits2 = Field2->getBitWidthValue(C); 16280 16281 if (Bits1 != Bits2) 16282 return false; 16283 } 16284 16285 return true; 16286 } 16287 16288 /// Check if two standard-layout structs are layout-compatible. 16289 /// (C++11 [class.mem] p17) 16290 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 16291 RecordDecl *RD2) { 16292 // If both records are C++ classes, check that base classes match. 16293 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 16294 // If one of records is a CXXRecordDecl we are in C++ mode, 16295 // thus the other one is a CXXRecordDecl, too. 16296 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 16297 // Check number of base classes. 16298 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 16299 return false; 16300 16301 // Check the base classes. 16302 for (CXXRecordDecl::base_class_const_iterator 16303 Base1 = D1CXX->bases_begin(), 16304 BaseEnd1 = D1CXX->bases_end(), 16305 Base2 = D2CXX->bases_begin(); 16306 Base1 != BaseEnd1; 16307 ++Base1, ++Base2) { 16308 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 16309 return false; 16310 } 16311 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 16312 // If only RD2 is a C++ class, it should have zero base classes. 16313 if (D2CXX->getNumBases() > 0) 16314 return false; 16315 } 16316 16317 // Check the fields. 16318 RecordDecl::field_iterator Field2 = RD2->field_begin(), 16319 Field2End = RD2->field_end(), 16320 Field1 = RD1->field_begin(), 16321 Field1End = RD1->field_end(); 16322 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 16323 if (!isLayoutCompatible(C, *Field1, *Field2)) 16324 return false; 16325 } 16326 if (Field1 != Field1End || Field2 != Field2End) 16327 return false; 16328 16329 return true; 16330 } 16331 16332 /// Check if two standard-layout unions are layout-compatible. 16333 /// (C++11 [class.mem] p18) 16334 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 16335 RecordDecl *RD2) { 16336 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 16337 for (auto *Field2 : RD2->fields()) 16338 UnmatchedFields.insert(Field2); 16339 16340 for (auto *Field1 : RD1->fields()) { 16341 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 16342 I = UnmatchedFields.begin(), 16343 E = UnmatchedFields.end(); 16344 16345 for ( ; I != E; ++I) { 16346 if (isLayoutCompatible(C, Field1, *I)) { 16347 bool Result = UnmatchedFields.erase(*I); 16348 (void) Result; 16349 assert(Result); 16350 break; 16351 } 16352 } 16353 if (I == E) 16354 return false; 16355 } 16356 16357 return UnmatchedFields.empty(); 16358 } 16359 16360 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 16361 RecordDecl *RD2) { 16362 if (RD1->isUnion() != RD2->isUnion()) 16363 return false; 16364 16365 if (RD1->isUnion()) 16366 return isLayoutCompatibleUnion(C, RD1, RD2); 16367 else 16368 return isLayoutCompatibleStruct(C, RD1, RD2); 16369 } 16370 16371 /// Check if two types are layout-compatible in C++11 sense. 16372 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 16373 if (T1.isNull() || T2.isNull()) 16374 return false; 16375 16376 // C++11 [basic.types] p11: 16377 // If two types T1 and T2 are the same type, then T1 and T2 are 16378 // layout-compatible types. 16379 if (C.hasSameType(T1, T2)) 16380 return true; 16381 16382 T1 = T1.getCanonicalType().getUnqualifiedType(); 16383 T2 = T2.getCanonicalType().getUnqualifiedType(); 16384 16385 const Type::TypeClass TC1 = T1->getTypeClass(); 16386 const Type::TypeClass TC2 = T2->getTypeClass(); 16387 16388 if (TC1 != TC2) 16389 return false; 16390 16391 if (TC1 == Type::Enum) { 16392 return isLayoutCompatible(C, 16393 cast<EnumType>(T1)->getDecl(), 16394 cast<EnumType>(T2)->getDecl()); 16395 } else if (TC1 == Type::Record) { 16396 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 16397 return false; 16398 16399 return isLayoutCompatible(C, 16400 cast<RecordType>(T1)->getDecl(), 16401 cast<RecordType>(T2)->getDecl()); 16402 } 16403 16404 return false; 16405 } 16406 16407 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16408 16409 /// Given a type tag expression find the type tag itself. 16410 /// 16411 /// \param TypeExpr Type tag expression, as it appears in user's code. 16412 /// 16413 /// \param VD Declaration of an identifier that appears in a type tag. 16414 /// 16415 /// \param MagicValue Type tag magic value. 16416 /// 16417 /// \param isConstantEvaluated whether the evalaution should be performed in 16418 16419 /// constant context. 16420 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16421 const ValueDecl **VD, uint64_t *MagicValue, 16422 bool isConstantEvaluated) { 16423 while(true) { 16424 if (!TypeExpr) 16425 return false; 16426 16427 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16428 16429 switch (TypeExpr->getStmtClass()) { 16430 case Stmt::UnaryOperatorClass: { 16431 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16432 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16433 TypeExpr = UO->getSubExpr(); 16434 continue; 16435 } 16436 return false; 16437 } 16438 16439 case Stmt::DeclRefExprClass: { 16440 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16441 *VD = DRE->getDecl(); 16442 return true; 16443 } 16444 16445 case Stmt::IntegerLiteralClass: { 16446 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16447 llvm::APInt MagicValueAPInt = IL->getValue(); 16448 if (MagicValueAPInt.getActiveBits() <= 64) { 16449 *MagicValue = MagicValueAPInt.getZExtValue(); 16450 return true; 16451 } else 16452 return false; 16453 } 16454 16455 case Stmt::BinaryConditionalOperatorClass: 16456 case Stmt::ConditionalOperatorClass: { 16457 const AbstractConditionalOperator *ACO = 16458 cast<AbstractConditionalOperator>(TypeExpr); 16459 bool Result; 16460 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16461 isConstantEvaluated)) { 16462 if (Result) 16463 TypeExpr = ACO->getTrueExpr(); 16464 else 16465 TypeExpr = ACO->getFalseExpr(); 16466 continue; 16467 } 16468 return false; 16469 } 16470 16471 case Stmt::BinaryOperatorClass: { 16472 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16473 if (BO->getOpcode() == BO_Comma) { 16474 TypeExpr = BO->getRHS(); 16475 continue; 16476 } 16477 return false; 16478 } 16479 16480 default: 16481 return false; 16482 } 16483 } 16484 } 16485 16486 /// Retrieve the C type corresponding to type tag TypeExpr. 16487 /// 16488 /// \param TypeExpr Expression that specifies a type tag. 16489 /// 16490 /// \param MagicValues Registered magic values. 16491 /// 16492 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16493 /// kind. 16494 /// 16495 /// \param TypeInfo Information about the corresponding C type. 16496 /// 16497 /// \param isConstantEvaluated whether the evalaution should be performed in 16498 /// constant context. 16499 /// 16500 /// \returns true if the corresponding C type was found. 16501 static bool GetMatchingCType( 16502 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16503 const ASTContext &Ctx, 16504 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16505 *MagicValues, 16506 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16507 bool isConstantEvaluated) { 16508 FoundWrongKind = false; 16509 16510 // Variable declaration that has type_tag_for_datatype attribute. 16511 const ValueDecl *VD = nullptr; 16512 16513 uint64_t MagicValue; 16514 16515 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16516 return false; 16517 16518 if (VD) { 16519 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16520 if (I->getArgumentKind() != ArgumentKind) { 16521 FoundWrongKind = true; 16522 return false; 16523 } 16524 TypeInfo.Type = I->getMatchingCType(); 16525 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16526 TypeInfo.MustBeNull = I->getMustBeNull(); 16527 return true; 16528 } 16529 return false; 16530 } 16531 16532 if (!MagicValues) 16533 return false; 16534 16535 llvm::DenseMap<Sema::TypeTagMagicValue, 16536 Sema::TypeTagData>::const_iterator I = 16537 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16538 if (I == MagicValues->end()) 16539 return false; 16540 16541 TypeInfo = I->second; 16542 return true; 16543 } 16544 16545 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16546 uint64_t MagicValue, QualType Type, 16547 bool LayoutCompatible, 16548 bool MustBeNull) { 16549 if (!TypeTagForDatatypeMagicValues) 16550 TypeTagForDatatypeMagicValues.reset( 16551 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16552 16553 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16554 (*TypeTagForDatatypeMagicValues)[Magic] = 16555 TypeTagData(Type, LayoutCompatible, MustBeNull); 16556 } 16557 16558 static bool IsSameCharType(QualType T1, QualType T2) { 16559 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16560 if (!BT1) 16561 return false; 16562 16563 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16564 if (!BT2) 16565 return false; 16566 16567 BuiltinType::Kind T1Kind = BT1->getKind(); 16568 BuiltinType::Kind T2Kind = BT2->getKind(); 16569 16570 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16571 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16572 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16573 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16574 } 16575 16576 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16577 const ArrayRef<const Expr *> ExprArgs, 16578 SourceLocation CallSiteLoc) { 16579 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16580 bool IsPointerAttr = Attr->getIsPointer(); 16581 16582 // Retrieve the argument representing the 'type_tag'. 16583 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16584 if (TypeTagIdxAST >= ExprArgs.size()) { 16585 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16586 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16587 return; 16588 } 16589 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16590 bool FoundWrongKind; 16591 TypeTagData TypeInfo; 16592 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16593 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16594 TypeInfo, isConstantEvaluated())) { 16595 if (FoundWrongKind) 16596 Diag(TypeTagExpr->getExprLoc(), 16597 diag::warn_type_tag_for_datatype_wrong_kind) 16598 << TypeTagExpr->getSourceRange(); 16599 return; 16600 } 16601 16602 // Retrieve the argument representing the 'arg_idx'. 16603 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16604 if (ArgumentIdxAST >= ExprArgs.size()) { 16605 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16606 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16607 return; 16608 } 16609 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16610 if (IsPointerAttr) { 16611 // Skip implicit cast of pointer to `void *' (as a function argument). 16612 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16613 if (ICE->getType()->isVoidPointerType() && 16614 ICE->getCastKind() == CK_BitCast) 16615 ArgumentExpr = ICE->getSubExpr(); 16616 } 16617 QualType ArgumentType = ArgumentExpr->getType(); 16618 16619 // Passing a `void*' pointer shouldn't trigger a warning. 16620 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16621 return; 16622 16623 if (TypeInfo.MustBeNull) { 16624 // Type tag with matching void type requires a null pointer. 16625 if (!ArgumentExpr->isNullPointerConstant(Context, 16626 Expr::NPC_ValueDependentIsNotNull)) { 16627 Diag(ArgumentExpr->getExprLoc(), 16628 diag::warn_type_safety_null_pointer_required) 16629 << ArgumentKind->getName() 16630 << ArgumentExpr->getSourceRange() 16631 << TypeTagExpr->getSourceRange(); 16632 } 16633 return; 16634 } 16635 16636 QualType RequiredType = TypeInfo.Type; 16637 if (IsPointerAttr) 16638 RequiredType = Context.getPointerType(RequiredType); 16639 16640 bool mismatch = false; 16641 if (!TypeInfo.LayoutCompatible) { 16642 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16643 16644 // C++11 [basic.fundamental] p1: 16645 // Plain char, signed char, and unsigned char are three distinct types. 16646 // 16647 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16648 // char' depending on the current char signedness mode. 16649 if (mismatch) 16650 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16651 RequiredType->getPointeeType())) || 16652 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16653 mismatch = false; 16654 } else 16655 if (IsPointerAttr) 16656 mismatch = !isLayoutCompatible(Context, 16657 ArgumentType->getPointeeType(), 16658 RequiredType->getPointeeType()); 16659 else 16660 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16661 16662 if (mismatch) 16663 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16664 << ArgumentType << ArgumentKind 16665 << TypeInfo.LayoutCompatible << RequiredType 16666 << ArgumentExpr->getSourceRange() 16667 << TypeTagExpr->getSourceRange(); 16668 } 16669 16670 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16671 CharUnits Alignment) { 16672 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16673 } 16674 16675 void Sema::DiagnoseMisalignedMembers() { 16676 for (MisalignedMember &m : MisalignedMembers) { 16677 const NamedDecl *ND = m.RD; 16678 if (ND->getName().empty()) { 16679 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16680 ND = TD; 16681 } 16682 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16683 << m.MD << ND << m.E->getSourceRange(); 16684 } 16685 MisalignedMembers.clear(); 16686 } 16687 16688 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16689 E = E->IgnoreParens(); 16690 if (!T->isPointerType() && !T->isIntegerType()) 16691 return; 16692 if (isa<UnaryOperator>(E) && 16693 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16694 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16695 if (isa<MemberExpr>(Op)) { 16696 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16697 if (MA != MisalignedMembers.end() && 16698 (T->isIntegerType() || 16699 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16700 Context.getTypeAlignInChars( 16701 T->getPointeeType()) <= MA->Alignment)))) 16702 MisalignedMembers.erase(MA); 16703 } 16704 } 16705 } 16706 16707 void Sema::RefersToMemberWithReducedAlignment( 16708 Expr *E, 16709 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16710 Action) { 16711 const auto *ME = dyn_cast<MemberExpr>(E); 16712 if (!ME) 16713 return; 16714 16715 // No need to check expressions with an __unaligned-qualified type. 16716 if (E->getType().getQualifiers().hasUnaligned()) 16717 return; 16718 16719 // For a chain of MemberExpr like "a.b.c.d" this list 16720 // will keep FieldDecl's like [d, c, b]. 16721 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16722 const MemberExpr *TopME = nullptr; 16723 bool AnyIsPacked = false; 16724 do { 16725 QualType BaseType = ME->getBase()->getType(); 16726 if (BaseType->isDependentType()) 16727 return; 16728 if (ME->isArrow()) 16729 BaseType = BaseType->getPointeeType(); 16730 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16731 if (RD->isInvalidDecl()) 16732 return; 16733 16734 ValueDecl *MD = ME->getMemberDecl(); 16735 auto *FD = dyn_cast<FieldDecl>(MD); 16736 // We do not care about non-data members. 16737 if (!FD || FD->isInvalidDecl()) 16738 return; 16739 16740 AnyIsPacked = 16741 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16742 ReverseMemberChain.push_back(FD); 16743 16744 TopME = ME; 16745 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16746 } while (ME); 16747 assert(TopME && "We did not compute a topmost MemberExpr!"); 16748 16749 // Not the scope of this diagnostic. 16750 if (!AnyIsPacked) 16751 return; 16752 16753 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16754 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16755 // TODO: The innermost base of the member expression may be too complicated. 16756 // For now, just disregard these cases. This is left for future 16757 // improvement. 16758 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16759 return; 16760 16761 // Alignment expected by the whole expression. 16762 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16763 16764 // No need to do anything else with this case. 16765 if (ExpectedAlignment.isOne()) 16766 return; 16767 16768 // Synthesize offset of the whole access. 16769 CharUnits Offset; 16770 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain)) 16771 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD)); 16772 16773 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16774 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16775 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16776 16777 // The base expression of the innermost MemberExpr may give 16778 // stronger guarantees than the class containing the member. 16779 if (DRE && !TopME->isArrow()) { 16780 const ValueDecl *VD = DRE->getDecl(); 16781 if (!VD->getType()->isReferenceType()) 16782 CompleteObjectAlignment = 16783 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16784 } 16785 16786 // Check if the synthesized offset fulfills the alignment. 16787 if (Offset % ExpectedAlignment != 0 || 16788 // It may fulfill the offset it but the effective alignment may still be 16789 // lower than the expected expression alignment. 16790 CompleteObjectAlignment < ExpectedAlignment) { 16791 // If this happens, we want to determine a sensible culprit of this. 16792 // Intuitively, watching the chain of member expressions from right to 16793 // left, we start with the required alignment (as required by the field 16794 // type) but some packed attribute in that chain has reduced the alignment. 16795 // It may happen that another packed structure increases it again. But if 16796 // we are here such increase has not been enough. So pointing the first 16797 // FieldDecl that either is packed or else its RecordDecl is, 16798 // seems reasonable. 16799 FieldDecl *FD = nullptr; 16800 CharUnits Alignment; 16801 for (FieldDecl *FDI : ReverseMemberChain) { 16802 if (FDI->hasAttr<PackedAttr>() || 16803 FDI->getParent()->hasAttr<PackedAttr>()) { 16804 FD = FDI; 16805 Alignment = std::min( 16806 Context.getTypeAlignInChars(FD->getType()), 16807 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16808 break; 16809 } 16810 } 16811 assert(FD && "We did not find a packed FieldDecl!"); 16812 Action(E, FD->getParent(), FD, Alignment); 16813 } 16814 } 16815 16816 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16817 using namespace std::placeholders; 16818 16819 RefersToMemberWithReducedAlignment( 16820 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16821 _2, _3, _4)); 16822 } 16823 16824 // Check if \p Ty is a valid type for the elementwise math builtins. If it is 16825 // not a valid type, emit an error message and return true. Otherwise return 16826 // false. 16827 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, 16828 QualType Ty) { 16829 if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) { 16830 S.Diag(Loc, diag::err_builtin_invalid_arg_type) 16831 << 1 << /* vector, integer or float ty*/ 0 << Ty; 16832 return true; 16833 } 16834 return false; 16835 } 16836 16837 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) { 16838 if (checkArgCount(*this, TheCall, 1)) 16839 return true; 16840 16841 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 16842 if (A.isInvalid()) 16843 return true; 16844 16845 TheCall->setArg(0, A.get()); 16846 QualType TyA = A.get()->getType(); 16847 16848 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 16849 return true; 16850 16851 TheCall->setType(TyA); 16852 return false; 16853 } 16854 16855 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) { 16856 if (checkArgCount(*this, TheCall, 2)) 16857 return true; 16858 16859 ExprResult A = TheCall->getArg(0); 16860 ExprResult B = TheCall->getArg(1); 16861 // Do standard promotions between the two arguments, returning their common 16862 // type. 16863 QualType Res = 16864 UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison); 16865 if (A.isInvalid() || B.isInvalid()) 16866 return true; 16867 16868 QualType TyA = A.get()->getType(); 16869 QualType TyB = B.get()->getType(); 16870 16871 if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType()) 16872 return Diag(A.get()->getBeginLoc(), 16873 diag::err_typecheck_call_different_arg_types) 16874 << TyA << TyB; 16875 16876 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 16877 return true; 16878 16879 TheCall->setArg(0, A.get()); 16880 TheCall->setArg(1, B.get()); 16881 TheCall->setType(Res); 16882 return false; 16883 } 16884 16885 bool Sema::SemaBuiltinReduceMath(CallExpr *TheCall) { 16886 if (checkArgCount(*this, TheCall, 1)) 16887 return true; 16888 16889 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 16890 if (A.isInvalid()) 16891 return true; 16892 16893 TheCall->setArg(0, A.get()); 16894 const VectorType *TyA = A.get()->getType()->getAs<VectorType>(); 16895 if (!TyA) { 16896 SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc(); 16897 return Diag(ArgLoc, diag::err_builtin_invalid_arg_type) 16898 << 1 << /* vector ty*/ 4 << A.get()->getType(); 16899 } 16900 16901 TheCall->setType(TyA->getElementType()); 16902 return false; 16903 } 16904 16905 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16906 ExprResult CallResult) { 16907 if (checkArgCount(*this, TheCall, 1)) 16908 return ExprError(); 16909 16910 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16911 if (MatrixArg.isInvalid()) 16912 return MatrixArg; 16913 Expr *Matrix = MatrixArg.get(); 16914 16915 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16916 if (!MType) { 16917 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16918 << 1 << /* matrix ty*/ 1 << Matrix->getType(); 16919 return ExprError(); 16920 } 16921 16922 // Create returned matrix type by swapping rows and columns of the argument 16923 // matrix type. 16924 QualType ResultType = Context.getConstantMatrixType( 16925 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16926 16927 // Change the return type to the type of the returned matrix. 16928 TheCall->setType(ResultType); 16929 16930 // Update call argument to use the possibly converted matrix argument. 16931 TheCall->setArg(0, Matrix); 16932 return CallResult; 16933 } 16934 16935 // Get and verify the matrix dimensions. 16936 static llvm::Optional<unsigned> 16937 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16938 SourceLocation ErrorPos; 16939 Optional<llvm::APSInt> Value = 16940 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16941 if (!Value) { 16942 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16943 << Name; 16944 return {}; 16945 } 16946 uint64_t Dim = Value->getZExtValue(); 16947 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16948 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16949 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16950 return {}; 16951 } 16952 return Dim; 16953 } 16954 16955 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16956 ExprResult CallResult) { 16957 if (!getLangOpts().MatrixTypes) { 16958 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16959 return ExprError(); 16960 } 16961 16962 if (checkArgCount(*this, TheCall, 4)) 16963 return ExprError(); 16964 16965 unsigned PtrArgIdx = 0; 16966 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16967 Expr *RowsExpr = TheCall->getArg(1); 16968 Expr *ColumnsExpr = TheCall->getArg(2); 16969 Expr *StrideExpr = TheCall->getArg(3); 16970 16971 bool ArgError = false; 16972 16973 // Check pointer argument. 16974 { 16975 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16976 if (PtrConv.isInvalid()) 16977 return PtrConv; 16978 PtrExpr = PtrConv.get(); 16979 TheCall->setArg(0, PtrExpr); 16980 if (PtrExpr->isTypeDependent()) { 16981 TheCall->setType(Context.DependentTy); 16982 return TheCall; 16983 } 16984 } 16985 16986 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16987 QualType ElementTy; 16988 if (!PtrTy) { 16989 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16990 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 16991 ArgError = true; 16992 } else { 16993 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16994 16995 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16996 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16997 << PtrArgIdx + 1 << /* pointer to element ty*/ 2 16998 << PtrExpr->getType(); 16999 ArgError = true; 17000 } 17001 } 17002 17003 // Apply default Lvalue conversions and convert the expression to size_t. 17004 auto ApplyArgumentConversions = [this](Expr *E) { 17005 ExprResult Conv = DefaultLvalueConversion(E); 17006 if (Conv.isInvalid()) 17007 return Conv; 17008 17009 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 17010 }; 17011 17012 // Apply conversion to row and column expressions. 17013 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 17014 if (!RowsConv.isInvalid()) { 17015 RowsExpr = RowsConv.get(); 17016 TheCall->setArg(1, RowsExpr); 17017 } else 17018 RowsExpr = nullptr; 17019 17020 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 17021 if (!ColumnsConv.isInvalid()) { 17022 ColumnsExpr = ColumnsConv.get(); 17023 TheCall->setArg(2, ColumnsExpr); 17024 } else 17025 ColumnsExpr = nullptr; 17026 17027 // If any any part of the result matrix type is still pending, just use 17028 // Context.DependentTy, until all parts are resolved. 17029 if ((RowsExpr && RowsExpr->isTypeDependent()) || 17030 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 17031 TheCall->setType(Context.DependentTy); 17032 return CallResult; 17033 } 17034 17035 // Check row and column dimensions. 17036 llvm::Optional<unsigned> MaybeRows; 17037 if (RowsExpr) 17038 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 17039 17040 llvm::Optional<unsigned> MaybeColumns; 17041 if (ColumnsExpr) 17042 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 17043 17044 // Check stride argument. 17045 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 17046 if (StrideConv.isInvalid()) 17047 return ExprError(); 17048 StrideExpr = StrideConv.get(); 17049 TheCall->setArg(3, StrideExpr); 17050 17051 if (MaybeRows) { 17052 if (Optional<llvm::APSInt> Value = 17053 StrideExpr->getIntegerConstantExpr(Context)) { 17054 uint64_t Stride = Value->getZExtValue(); 17055 if (Stride < *MaybeRows) { 17056 Diag(StrideExpr->getBeginLoc(), 17057 diag::err_builtin_matrix_stride_too_small); 17058 ArgError = true; 17059 } 17060 } 17061 } 17062 17063 if (ArgError || !MaybeRows || !MaybeColumns) 17064 return ExprError(); 17065 17066 TheCall->setType( 17067 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 17068 return CallResult; 17069 } 17070 17071 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 17072 ExprResult CallResult) { 17073 if (checkArgCount(*this, TheCall, 3)) 17074 return ExprError(); 17075 17076 unsigned PtrArgIdx = 1; 17077 Expr *MatrixExpr = TheCall->getArg(0); 17078 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 17079 Expr *StrideExpr = TheCall->getArg(2); 17080 17081 bool ArgError = false; 17082 17083 { 17084 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 17085 if (MatrixConv.isInvalid()) 17086 return MatrixConv; 17087 MatrixExpr = MatrixConv.get(); 17088 TheCall->setArg(0, MatrixExpr); 17089 } 17090 if (MatrixExpr->isTypeDependent()) { 17091 TheCall->setType(Context.DependentTy); 17092 return TheCall; 17093 } 17094 17095 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 17096 if (!MatrixTy) { 17097 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17098 << 1 << /*matrix ty */ 1 << MatrixExpr->getType(); 17099 ArgError = true; 17100 } 17101 17102 { 17103 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 17104 if (PtrConv.isInvalid()) 17105 return PtrConv; 17106 PtrExpr = PtrConv.get(); 17107 TheCall->setArg(1, PtrExpr); 17108 if (PtrExpr->isTypeDependent()) { 17109 TheCall->setType(Context.DependentTy); 17110 return TheCall; 17111 } 17112 } 17113 17114 // Check pointer argument. 17115 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 17116 if (!PtrTy) { 17117 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17118 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 17119 ArgError = true; 17120 } else { 17121 QualType ElementTy = PtrTy->getPointeeType(); 17122 if (ElementTy.isConstQualified()) { 17123 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 17124 ArgError = true; 17125 } 17126 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 17127 if (MatrixTy && 17128 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 17129 Diag(PtrExpr->getBeginLoc(), 17130 diag::err_builtin_matrix_pointer_arg_mismatch) 17131 << ElementTy << MatrixTy->getElementType(); 17132 ArgError = true; 17133 } 17134 } 17135 17136 // Apply default Lvalue conversions and convert the stride expression to 17137 // size_t. 17138 { 17139 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 17140 if (StrideConv.isInvalid()) 17141 return StrideConv; 17142 17143 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 17144 if (StrideConv.isInvalid()) 17145 return StrideConv; 17146 StrideExpr = StrideConv.get(); 17147 TheCall->setArg(2, StrideExpr); 17148 } 17149 17150 // Check stride argument. 17151 if (MatrixTy) { 17152 if (Optional<llvm::APSInt> Value = 17153 StrideExpr->getIntegerConstantExpr(Context)) { 17154 uint64_t Stride = Value->getZExtValue(); 17155 if (Stride < MatrixTy->getNumRows()) { 17156 Diag(StrideExpr->getBeginLoc(), 17157 diag::err_builtin_matrix_stride_too_small); 17158 ArgError = true; 17159 } 17160 } 17161 } 17162 17163 if (ArgError) 17164 return ExprError(); 17165 17166 return CallResult; 17167 } 17168 17169 /// \brief Enforce the bounds of a TCB 17170 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 17171 /// directly calls other functions in the same TCB as marked by the enforce_tcb 17172 /// and enforce_tcb_leaf attributes. 17173 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 17174 const FunctionDecl *Callee) { 17175 const FunctionDecl *Caller = getCurFunctionDecl(); 17176 17177 // Calls to builtins are not enforced. 17178 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 17179 Callee->getBuiltinID() != 0) 17180 return; 17181 17182 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 17183 // all TCBs the callee is a part of. 17184 llvm::StringSet<> CalleeTCBs; 17185 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 17186 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17187 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 17188 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17189 17190 // Go through the TCBs the caller is a part of and emit warnings if Caller 17191 // is in a TCB that the Callee is not. 17192 for_each( 17193 Caller->specific_attrs<EnforceTCBAttr>(), 17194 [&](const auto *A) { 17195 StringRef CallerTCB = A->getTCBName(); 17196 if (CalleeTCBs.count(CallerTCB) == 0) { 17197 this->Diag(TheCall->getExprLoc(), 17198 diag::warn_tcb_enforcement_violation) << Callee 17199 << CallerTCB; 17200 } 17201 }); 17202 } 17203